diff --git a/base/field.go b/base/field.go index b78e3c00a..36af06729 100644 --- a/base/field.go +++ b/base/field.go @@ -92,6 +92,10 @@ type Field struct { // FieldArea once and as a Field since keeps its layout but moves by its line. area *TextareaLayout rows bool + // secret is whether the last declaration made the field Secure (Box.Secure): + // such a field bound to a string is wiped when the page forgets it and when + // the program replaces its text, so neither the editor nor its undo keeps it. + secret bool } // Restrict limits what edits may put into the field: accept reports whether a rune @@ -395,7 +399,8 @@ func Fields(fields ...*Field) func(window.TextInputContext) *window.TextInput { // snapshot is what the field is painted from: focus, platform editing and the caret are // filled in for the frame being declared. func (field *Field) Snapshot(f *Frame, ID gfx.ID, Label, placeholder string) InputSnapshot { - field.rows = false // FieldArea sets it again after + field.rows = false // FieldArea sets it again after + field.secret = false // Box.Secure sets it again after editor := field.ensure() field.ID = ID value := editor.String() diff --git a/base/field_wipe.go b/base/field_wipe.go new file mode 100644 index 000000000..bf5a6e7ae --- /dev/null +++ b/base/field_wipe.go @@ -0,0 +1,18 @@ +package base + +// Wipe overwrites with zeros what the field holds of its text, as +// text.Editor.Wipe does for its editor (the text, its undo and redo, an input +// method's composition), and leaves the field empty. The change is the +// program's, not an edit: Changed does not report it. +// +// A Secure field bound to a string is wiped by the page; a Field the +// application keeps is the application's to wipe, once the secret is done with. +// +// m.password.Wipe() +func (field *Field) Wipe() { + if field.editor != nil { + field.editor.Wipe() + } + field.seen = "" + field.scroll = InputScroll{} +} diff --git a/base/page.go b/base/page.go index e752e7635..5b5b85ba5 100644 --- a/base/page.go +++ b/base/page.go @@ -89,6 +89,11 @@ func (c *Ctx) KeyInt(key int) C { // Part names the next element by a word of the program: the parts of a component // (its trigger, its list), which a test can address by that word. +// +// Key, KeyInt and Part name a container or a control. Text, Textf, Paragraph, +// Wrap, Icon, Image, Spacer, Divider and Spinner have no identity and take no +// name: a dev build stops on one given a name, a release build drops it, and +// viva vet reports it (named-leaf). Name the row around them instead. func (c *Ctx) Part(Name string) C { checkName("Part", Name) c.Next, c.nextSet = protoName{part: Name, kindOf: 2}, true @@ -1064,6 +1069,10 @@ func (p *Page) BoundScope(Kind uint8, Value unsafe.Pointer) gfx.Scope { // its name. A new value takes its place's name, unless a value declared in an // earlier paint than the last still holds it; a value that is new in every paint (a // copy) is given the name the last paint's copy had, so a copy works as its place. +// A control named with a Key or a Part keeps that name whatever value it is bound +// to: the value the last paint bound to another control does not take that +// control's name along. A named control that moved to a place no control held in +// the last paint keeps the name its value had, and its focus with it. func (p *Page) boundID(Kind uint8, Value unsafe.Pointer) gfx.ID { at, named := p.Name(Kind) key := boundKey{Value: Value, Kind: Kind} @@ -1073,7 +1082,7 @@ func (p *Page) boundID(Kind uint8, Value unsafe.Pointer) gfx.ID { key.n++ continue } - if ok && p.names[entry.ID].seen != p.epoch { + if ok && p.names[entry.ID].seen != p.epoch && (!named || !p.keepsPlace(entry.ID, at)) { entry.epoch = p.epoch p.Bound[key] = entry p.claim(entry.ID, entry.born) @@ -1099,6 +1108,19 @@ func (p *Page) boundID(Kind uint8, Value unsafe.Pointer) gfx.ID { } } +// keepsPlace reports whether a control named at, whose value last held the name +// id, takes at's name instead: at was held in the last paint, by another control +// whose value has since moved. A control named at a place that is new follows its +// value, as one that moved keeps its focus. +func (p *Page) keepsPlace(id gfx.ID, at Place) bool { + place := p.ID(at) + if id == place { + return false + } + owner, held := p.names[place] + return held && owner.seen+1 == p.epoch +} + func (p *Page) claim(ID gfx.ID, born uint32) { p.names[ID] = nameUse{seen: p.epoch, born: born} } diff --git a/base/state_within.go b/base/state_within.go new file mode 100644 index 000000000..cc866f135 --- /dev/null +++ b/base/state_within.go @@ -0,0 +1,69 @@ +package base + +import "github.com/vivaui/viva/gfx" + +// StateWithin is State together with what the element holds: Hovered, Pressed, +// Focused and FocusVisible are true while the element has them or any element +// declared inside it does, as CSS's :hover takes in an element's descendants +// and :focus-within its focus. It is how a declaration decides to show more of +// a row while the pointer or the keyboard is anywhere on it, its buttons +// included. Ask it after declaring the element's children, which it looks +// through. StateFrom follows a container the same way. +// +// A container's own blank area takes the pointer only with an identity of its +// own: HitWith and gfx.HitOptions.Presentational give it one that only takes the +// pointer, with no accessibility node and no tab stop. +// +// row := ui.Row(c).HitWith(ui.ID(c), "", gfx.HitOptions{Presentational: true}) +// row.Children(func() { ... }) +// if row.StateWithin().Interacting() { ... } +func (b Box) StateWithin() gfx.State { + state := b.State() + within := b.f.stateWithin(b.i) + state.Hovered = state.Hovered || within.Hovered + state.Pressed = state.Pressed || within.Pressed + state.Focused = state.Focused || within.Focused + state.FocusVisible = state.FocusVisible || within.FocusVisible + return state +} + +// stateWithin is the pointer and keyboard state of element i and what was declared +// inside it: which of the hovered, pressed and focused controls is one of them. +func (f *Frame) stateWithin(i int32) gfx.State { + canvas := f.Surface + if canvas == nil { + return gfx.State{} + } + hovered, pressed, focused, visible := canvas.Hovered(), canvas.Pressed(), canvas.Focused(), canvas.FocusVisible() + var state gfx.State + // The elements declared inside follow the element without a gap: those after + // it whose parents lead back to it. A popup declared inside has no parent in + // the flow and is passed over. + for at := i; at < int32(len(f.Nodes)); at++ { + n := &f.Nodes[at] + if at != i && n.Parent == -1 { + continue + } + if at != i && !f.holds(i, at) { + break + } + if n.ID.IsZero() { + continue + } + state.Hovered = state.Hovered || n.ID == hovered + state.Pressed = state.Pressed || n.ID == pressed + state.Focused = state.Focused || n.ID == focused + state.FocusVisible = state.FocusVisible || n.ID == visible + } + return state +} + +// holds reports whether element inner was declared inside element outer. +func (f *Frame) holds(outer, inner int32) bool { + for at := f.Nodes[inner].Parent; at >= outer; at = f.Nodes[at].Parent { + if at == outer { + return true + } + } + return false +} diff --git a/base/style.go b/base/style.go index 444d1b903..2da3aec08 100644 --- a/base/style.go +++ b/base/style.go @@ -23,7 +23,8 @@ import "github.com/vivaui/viva/gfx" // // StateFrom makes an element follow the state of another instead of its own, so // a pencil that appears when its row is hovered, or an icon that takes the row's -// color, is declared on the pencil and the icon: +// color, is declared on the pencil and the icon. The row's state takes in what it +// holds, so the pencil stays while the pointer is on it: // // row := f.Row().Hit(id, "Host") // row.Children(func() { @@ -205,7 +206,11 @@ func (b Box) Focused(look Look) Box { b.States().Focused = look; return b } // StateFrom makes the element take its Hover, Pressed and Focus looks, and the // timeline of its Transition, from the state of container instead of its own, so -// that what is inside a row changes with the row. +// that what is inside a row changes with the row. The container's state takes in +// what it holds, as StateWithin says: a row stays hovered while the pointer is on +// a button in it, and focused while the keyboard is. The container needs an +// identity to be followed; HitWith with gfx.HitOptions.Presentational gives a row +// one that only takes the pointer. func (b Box) StateFrom(container Box) Box { b.States().follow = container.i + 1; return b } // Transition fades the element between its looks over the theme's Transition @@ -390,6 +395,12 @@ func (f *Frame) resolve(n *Node, Extra *Extra) resolved { canvas := f.Surface focus, hover, pressed := target(canvas.FocusVisible() == source), target(canvas.Hovered() == source), target(canvas.Pressed() == source) focused := target(canvas.Focused() == source) + if looks.follow != 0 { + // A followed container is hovered, pressed or focused while anything in it is. + within := f.stateWithin(looks.follow - 1) + focus, hover, pressed = target(within.FocusVisible), target(within.Hovered), target(within.Pressed) + focused = target(within.Focused) + } if f.Disabled(n) { hover, pressed = 0, 0 if !Extra.hit.FocusableWhenDisabled { diff --git a/base/style_test.go b/base/style_test.go index cdc8cb121..5e2814276 100644 --- a/base/style_test.go +++ b/base/style_test.go @@ -130,6 +130,52 @@ func TestStateFromMakesWhatIsInsideFollowTheContainer(t *testing.T) { } } +// An element that follows a row keeps the row's looks while the pointer or the +// keyboard is on something the row holds, as a pencil revealed on hover stays +// while the pointer moves onto it; what is outside the row does not count. +func TestStateFromTakesInWhatTheContainerHolds(t *testing.T) { + outside := tree.ID(page, "style-outside") + for _, test := range []struct { + name string + hovered, focused gfx.ID + visible bool + want gfx.Color + }{ + {"pointer on the button in the row", styleChild, gfx.ID{}, false, colorHover}, + {"keyboard on the button in the row", gfx.ID{}, styleChild, true, colorPressed}, + {"pointer outside the row", outside, gfx.ID{}, false, gfx.Color{}}, + {"keyboard outside the row", gfx.ID{}, outside, true, gfx.Color{}}, + } { + t.Run(test.name, func(t *testing.T) { + canvas := styleCanvas(test.hovered, gfx.ID{}, test.focused, test.visible) + var view View + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 300, Height: 100}, func(f *Frame) { + f.Column().Children(func() { + row := f.Row().Size(200, 40).HitWith(styleRow, "", gfx.HitOptions{Presentational: true}) + row.Children(func() { + f.Text("edit").Color(colorRest).FontSize(10).Opacity(0).StateFrom(row). + Hover(Look{}.Opacity(1).Color(colorHover)).Focus(Look{}.Opacity(1).Color(colorPressed)) + f.Row().Size(20, 20).Hit(styleChild, "button") + }) + f.Row().Size(20, 20).Hit(outside, "outside") + }) + }) + var edit *gfx.Text + for index, shown := range canvas.Texts() { + if shown.Value == "edit" { + edit = &canvas.Texts()[index] + } + } + switch { + case test.want != (gfx.Color{}) && (edit == nil || edit.Style.Color != test.want): + t.Fatalf("the text that follows the row is %+v, want %+v", edit, test.want) + case test.want == (gfx.Color{}) && edit != nil && edit.Style.Color.Alpha != 0: + t.Fatalf("the text that follows the row is %+v, want it invisible", edit) + } + }) + } +} + // drawFrames paints the row once per entry of times, with the hover as given, and // returns the fill after each. func TestTransitionFadesBetweenLooksAndSettles(t *testing.T) { diff --git a/base/text_value.go b/base/text_value.go index b28b0af86..63b25a95c 100644 --- a/base/text_value.go +++ b/base/text_value.go @@ -47,6 +47,12 @@ func fieldOf[T TextValue](p *Page, Kind uint8, Value T) (*Field, gfx.ID) { switch typed := bound.field.Text(); { case typed != bound.synced: *v, bound.synced = typed, typed + case *v != bound.synced && bound.field.secret: + // A secret the program replaced, or cleared, is not an edit to undo back. + bound.field.Wipe() + bound.field.SetText(*v) + bound.field.ensure().ClearHistory() + bound.synced = *v case *v != bound.synced: bound.field.follow(*v) bound.synced = *v @@ -111,10 +117,16 @@ func (field *Field) follow(value string) { } // sweepTexts forgets the fields of strings whose names the page no longer keeps: -// a field a Memo copies keeps its name, and so its editor. +// a field a Memo copies keeps its name, and so its editor. A Secure field is +// wiped as it is forgotten, so its editor does not wait for the garbage +// collector with the secret in it. func (p *Page) sweepTexts() { - for id := range p.texts { + for id, bound := range p.texts { if _, ok := p.names[id]; !ok { + if bound.field.secret { + bound.field.Wipe() + bound.synced = "" + } delete(p.texts, id) } } @@ -139,6 +151,10 @@ func (b Box) NavigationKeys() Box { // clipboard and the platform's suggestions: a password. It is Field.Secure for a // field bound to a string, for a TextField as for the rows of a TextArea. // +// A Secure field bound to a string is wiped (Field.Wipe) when it is no longer +// declared and when the program changes the string: setting it to "" as a +// dialog closes leaves neither the text nor an undo that brings it back. +// // ui.TextField(c, &m.password, "Password", "").Secure() // ui.TextArea(c, &m.privateKey, "Private key", "").Secure() func (b Box) Secure() Box { @@ -151,5 +167,13 @@ func (b Box) Secure() Box { default: panic("ui: Secure is for a TextField or TextArea") } + if p := b.f.page; p != nil { + for i := len(p.fields) - 1; i >= 0; i-- { + if p.fields[i].ID == n.ID { + p.fields[i].field.secret = true + break + } + } + } return b } diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 049529b4e..461570438 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -101,7 +101,8 @@ func (m *model) page(c ui.C) { - `c.Key("text")` / `c.KeyInt(id)` name the next element (a row); `c.Part("word")` names a part of a component. Everything else is named by its place in its parent: no names to declare. - Bind fields of the model (`&h.Done`). A copy (`v := m.viewed[id]; ui.Checkbox(c, &v, ...)`) works too: - write it back on `.Changed()`. + write it back on `.Changed()`. A control inside `c.Key` or named with `c.Part` keeps that name whatever it + is bound to. - `Changed()` reports the paint in which a bound control changed its value; `Clicked()` on a `Button`. `Popover` and `Modal` set their `*bool` to false when dismissed (Escape, a press outside, the close button) and give the focus back. @@ -433,7 +434,8 @@ func (m *model) page(c ui.C) { `Color`, `Ring`, `Shadow` and `Opacity`; looks combine field by field (Focus, then Hover, then Pressed win). `Transition()` fades between them over the theme's motion and schedules nothing while at rest. `StateFrom(row)` makes a child follow its row's state: a pencil that shows on hover is - `ui.Icon(c, edit).Opacity(0).StateFrom(row).Hover(ui.Look{}.Opacity(1))`. + `ui.Icon(c, edit).Opacity(0).StateFrom(row).Hover(ui.Look{}.Opacity(1))`. The row's state takes in what it holds (the + pencil stays while the pointer is on it); `row.StateWithin()` gives that state to a declaration. - Finished, themed examples to copy (settings row, list row with a hover action, avatar, badge, stat card, gradient hero, icon button, empty state): , with guidance in . - Icons move inside their box, not the box: `ui.Icon(c, glyph).IconTransform(gfx.IconTransform{Rotate: radians, Scale: 0.9, Offset: gfx.Point{X: 2, Y: 0}})` turns and scales the glyph about the center of its box and moves it after that, while the row keeps its place, its diff --git a/cmd/viva/vet.go b/cmd/viva/vet.go index e60f06531..371f75a9a 100644 --- a/cmd/viva/vet.go +++ b/cmd/viva/vet.go @@ -331,6 +331,43 @@ func (checker *vetChecker) call(call *ast.CallExpr, stack []ast.Node) { case "Memo": checker.memo(call) } + if namelessLeaves[selector.Sel.Name] { + checker.namedLeaf(call, selector.Sel.Name) + } +} + +// namelessLeaves are the elements of package ui that take no name: they have no +// identity, state or focus, so a Key or a Part names nothing on them. +var namelessLeaves = map[string]bool{ + "Text": true, "Textf": true, "Paragraph": true, "Wrap": true, + "Icon": true, "Image": true, "Spacer": true, "Divider": true, "Spinner": true, +} + +// namedLeaf reports a Key or a Part given straight to an element that takes no +// name: the dev build stops on it, and a release build drops the name. +func (checker *vetChecker) namedLeaf(call *ast.CallExpr, element string) { + if len(call.Args) == 0 { + return + } + naming, ok := call.Args[0].(*ast.CallExpr) + if !ok { + return + } + selector, ok := naming.Fun.(*ast.SelectorExpr) + if !ok { + return + } + switch selector.Sel.Name { + case "Key", "KeyInt", "Part": + default: + return + } + if t := checker.info.Types[selector.X].Type; t == nil || !isContext(t) { + return + } + checker.report(call, "named-leaf", fmt.Sprintf( + "ui.%s takes no name, so this %s names nothing (a dev build stops here): give the %s to the row or control around it, or pass c", + element, selector.Sel.Name, selector.Sel.Name)) } // unkeyedButton reports a Button with the same label in every row of a loop diff --git a/cmd/viva/vet_test.go b/cmd/viva/vet_test.go index 24d31248d..038adffda 100644 --- a/cmd/viva/vet_test.go +++ b/cmd/viva/vet_test.go @@ -43,6 +43,10 @@ func (m *model) page(c ui.C) { ui.Button(c, "Same") } ui.Modal(c, &m.open, "Title", ui.ModalSpec{}, nil, nil) + ui.Text(c.Part("note"), "Note") // a Text takes no name + ui.Row(c.Part("aside")).Children(func() { + ui.Text(c, "Aside") // the Row is named + }) } func main() { _ = (&model{}).page } @@ -80,7 +84,7 @@ func TestVetFindsPageMistakes(t *testing.T) { for _, finding := range findings { got = append(got, finding.check+"@"+strconv.Itoa(finding.pos.Line)) } - want := []string{"kept-context@14", "unkeyed-button@20"} + want := []string{"kept-context@14", "unkeyed-button@20", "named-leaf@36"} if strings.Join(got, " ") != strings.Join(want, " ") { t.Fatalf("findings = %v, want %v", got, want) } diff --git a/docs/skills/building-with-viva/recipes.md b/docs/skills/building-with-viva/recipes.md index 743347342..5ba444ac2 100644 --- a/docs/skills/building-with-viva/recipes.md +++ b/docs/skills/building-with-viva/recipes.md @@ -25,7 +25,7 @@ The recipes take a `ui.C` and the theme — `func SettingsRow(c ui.C, theme gfx. - **Two radii.** Controls and rows take `theme.Metrics.RadiusControl`, cards and panels `RadiusSurface`, a circle is half its size or `gfx.RadiusFull`. Do not invent a third. - **Hierarchy by weight and color, not size.** A title is `Weight(gfx.WeightMedium)`, its explanation is `.Muted()` at `FontSizeS`. Reserve a large `FontSize` for one figure or heading per screen. - **Every reactive thing has all three looks.** Hover to show it is live, Pressed to show it took the press, Focus with `Ring(3, theme.Ring)` so the keyboard user can see where they are. `Interactive` gives the standard set; `Transition()` makes them fade instead of snap. -- **Reveal with `StateFrom`.** Secondary actions that appear on hover (`Opacity(0)` at rest, `Hover(Look{}.Opacity(1))`, and `Focus` too so a keyboard user can find them) keep a list calm. Do not read `canvas.Hovered()` by hand. +- **Reveal with `StateFrom`.** Secondary actions that appear on hover (`Opacity(0)` at rest, `Hover(Look{}.Opacity(1))`, and `Focus` too so a keyboard user can find them) keep a list calm. The row's state takes in what it holds, so they stay while the pointer is on them; `row.StateWithin()` gives the same state to a declaration. Do not read `canvas.Hovered()` by hand. - **Shadow sparingly.** `ShadowXS` for a card on the page, `ShadowMD` for something lifted (a hero, a popover). Never on every row. - **Gradients are an accent.** A thin bar (`StatCard`), a hero, an avatar background. Two or three stops, hues close together; a large gradient behind body text needs white text and a contrast check. - **Fade with `Opacity`**, not by hand-mixing colors, to show something is off: `Section(..., enabled=false)` dims the group including its controls. diff --git a/text/wipe.go b/text/wipe.go new file mode 100644 index 000000000..f65d7f3f8 --- /dev/null +++ b/text/wipe.go @@ -0,0 +1,43 @@ +package text + +// Wipe overwrites with zeros what the editor holds of its text and leaves it +// empty: the text itself, every undo and redo unit, the history an input +// method's cancel would restore, and the composition's original runes. It is +// for a secret, a password or a key, once it is done with: dropping the editor +// would leave those buffers to the garbage collector with the secret in them. +// +// What Restrict, SetCode, the overwrite mode and OnDeleteAtEdge set stays. The +// journals TrackEdits and TrackLineEdits keep are dropped, so a cursor taken +// before Wipe reads as expired. Strings the editor handed out (String, +// CommittedString) are immutable and the caller's: Wipe drops the editor's own +// references to them and cannot clear them. Memory an earlier edit already +// gave back to the garbage collector is not the editor's to reach either. +func (editor *Editor) Wipe() { + for _, history := range [2][]historyEdit{editor.history, editor.compositionHistory} { + history = history[:cap(history)] + for index := range history { + clear(history[index].removed) + clear(history[index].inserted) + } + } + clear(editor.compositionOriginal) + pieces := editor.rollback.pieces[:cap(editor.rollback.pieces)] + for index := range pieces { + clear(pieces[index].removed) + } + for index := range editor.runes.leaves { + leaf := editor.runes.leaves[index].text + clear(leaf[:cap(leaf)]) + } + clear(editor.runes.scratch[:cap(editor.runes.scratch)]) + + *editor = Editor{ + OnDeleteAtEdge: editor.OnDeleteAtEdge, + accept: editor.accept, + maxRunes: editor.maxRunes, + overwrite: editor.overwrite, + code: editor.code, + codeSet: editor.codeSet, + } + editor.start("") +} diff --git a/text/wipe_test.go b/text/wipe_test.go new file mode 100644 index 000000000..bca799f56 --- /dev/null +++ b/text/wipe_test.go @@ -0,0 +1,70 @@ +package text + +import ( + "bytes" + "testing" + "unicode/utf8" +) + +// The buffers an editor kept a secret in hold zeros once it is wiped: its +// text, the runes of its undo and redo units, and an input method's original +// runes, read through the slices the editor itself held. The editor is left +// empty, with nothing to undo or redo, and keeps its restrictions. +func TestWipeZeroesTheTextAndItsHistory(t *testing.T) { + const secret = "test-key-not-real" + editor := NewEditor("") + digitsOnly := func(r rune) bool { return r >= '0' && r <= '9' } + for _, r := range secret { + editor.Insert(string(r)) + editor.BreakUndoGroup() + } + editor.DeleteBackward() + editor.Undo() // a redo unit holds the deleted rune + editor.SetSelection(Range{Start: 0, End: 4}) + editor.SetMarkedText("composed", Range{Start: 8, End: 8}) + if editor.String() == secret || !editor.CanUndo() { + t.Fatalf("setup: text %q, can undo %v", editor.String(), editor.CanUndo()) + } + + var held [][]byte + for _, leaf := range editor.runes.leaves { + held = append(held, leaf.text[:cap(leaf.text)]) + } + var heldRunes [][]rune + for _, history := range [][]historyEdit{editor.history, editor.compositionHistory} { + for _, edit := range history { + heldRunes = append(heldRunes, edit.removed, edit.inserted) + } + } + heldRunes = append(heldRunes, editor.compositionOriginal) + if len(heldRunes) < 3 { + t.Fatalf("setup: only %d rune buffers in history", len(heldRunes)) + } + + editor.Restrict(digitsOnly, 6) + editor.Wipe() + + for index, buffer := range held { + if !bytes.Equal(buffer, make([]byte, len(buffer))) { + t.Errorf("text leaf %d still holds %q after Wipe", index, buffer) + } + } + for index, buffer := range heldRunes { + for _, r := range buffer { + if r != 0 { + t.Errorf("history buffer %d still holds %q after Wipe", index, string(buffer)) + break + } + } + } + if editor.String() != "" || editor.CanUndo() || editor.CanRedo() { + t.Errorf("after Wipe: text %q, can undo %v, can redo %v", editor.String(), editor.CanUndo(), editor.CanRedo()) + } + if _, composing := editor.Composition(); composing { + t.Error("after Wipe the editor is still composing") + } + editor.Insert("a1b2345678") + if got := editor.String(); got != "123456" || !utf8.ValidString(got) { + t.Errorf("after Wipe the restriction no longer holds: %q", got) + } +} diff --git a/ui/secure_wipe_test.go b/ui/secure_wipe_test.go new file mode 100644 index 000000000..b7bc2f21b --- /dev/null +++ b/ui/secure_wipe_test.go @@ -0,0 +1,83 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// editorOf is the editor the page gives the platform for the field labeled label. +func (d *pageDriver) editorOf(label string) *text.Editor { + d.t.Helper() + input := d.page.TextInput(window.TextInputContext{ID: d.hit(label).ID}) + if input == nil || input.Editor == nil { + d.t.Fatalf("the page gives %q no editor", label) + } + return input.Editor +} + +// A Secure field bound to a string leaves nothing of what was typed in its editor +// once it is gone: closing the dialog it is in wipes the editor, text and undo +// alike. A field that is not Secure keeps its editor's text as before. +func TestSecureFieldIsWipedWhenItGoes(t *testing.T) { + const secret = "test-key-not-real" + for _, secure := range []bool{true, false} { + var m struct { + open bool + key string + } + m.open = true + d := openPage(t, func(c ui.C) { + if !m.open { + return + } + field := ui.TextField(c, &m.key, "Key", "") + if secure { + field.Secure() + } + }) + d.click("Key") + d.typeText(secret) + editor := d.editorOf("Key") + if editor.String() != secret || m.key != secret { + t.Fatalf("secure=%v: typed %q, the model holds %q", secure, editor.String(), m.key) + } + m.open = false + d.repaint() + d.repaint() + left := editor.String() + switch { + case secure && (left != "" || editor.CanUndo() || editor.CanRedo()): + t.Errorf("the closed secure field's editor holds %q, can undo %v, can redo %v", left, editor.CanUndo(), editor.CanRedo()) + case !secure && left != secret: + t.Errorf("the closed plain field's editor holds %q, want its text kept", left) + } + } +} + +// The program clearing the string of a Secure field, as a dialog that forgets the +// key does, clears the field too: no undo brings the secret back. +func TestSecureFieldClearedByTheProgramHasNoUndo(t *testing.T) { + const secret = "test-key-not-real" + var key string + d := openPage(t, func(c ui.C) { + ui.TextField(c, &key, "Key", "").Secure() + }) + d.click("Key") + d.typeText(secret) + key = "" + d.repaint() + editor := d.editorOf("Key") + if editor.String() != "" { + t.Fatalf("the field holds %q after the program cleared it", editor.String()) + } + if editor.Undo(); editor.String() != "" { + t.Errorf("undo brought back %q", editor.String()) + } + d.repaint() + if key != "" { + t.Errorf("the model holds %q after an undo of the cleared field", key) + } +} diff --git a/ui/state_within_test.go b/ui/state_within_test.go new file mode 100644 index 000000000..ffd204451 --- /dev/null +++ b/ui/state_within_test.go @@ -0,0 +1,55 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A row's StateWithin takes in what the row holds: the pointer on a button in it, +// or on the row's own blank area, is on the row, and so is the keyboard on the +// button, where the row's State has only its own hover. A row beside it is not +// on. +func TestStateWithinTakesInWhatTheElementHolds(t *testing.T) { + var own, within [2]gfx.State + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Gap(8).Children(func() { + for i := range 2 { + row := ui.Row(c.KeyInt(i)).Width(300).Height(40).PadX(8).Items(ui.Center). + HitWith(ui.ID(c), "", gfx.HitOptions{Presentational: true}) + row.Children(func() { + ui.Spacer(c) + ui.Button(c.KeyInt(i), []string{"Edit first", "Edit second"}[i]) + }) + own[i], within[i] = row.State(), row.StateWithin() + } + }) + }) + button := d.hit("Edit first").Bounds + if err := d.driver.Move(center(button)); err != nil { + t.Fatal(err) + } + d.repaint() + if own[0].Hovered || !within[0].Hovered || within[1].Hovered { + t.Errorf("pointer on the first row's button: own %+v, within %+v, second row within %+v", own[0], within[0], within[1]) + } + if err := d.driver.Move(button.X-100, button.Y+button.Height/2); err != nil { + t.Fatal(err) + } + d.repaint() + if !own[0].Hovered || !within[0].Hovered || within[1].Hovered { + t.Errorf("pointer on the first row's blank area: own %+v, within %+v, second row within %+v", own[0], within[0], within[1]) + } + if err := d.driver.Move(400, 400); err != nil { + t.Fatal(err) + } + d.key(gfx.KeyTab) + d.repaint() + if d.Focused() != "Edit first" { + t.Fatalf("Tab focused %q", d.Focused()) + } + if own[0].Focused || within[0].Hovered || !within[0].Focused || within[1].Focused { + t.Errorf("keyboard on the first row's button: own %+v, within %+v, second row within %+v", own[0], within[0], within[1]) + } +} diff --git a/ui/switch_key_test.go b/ui/switch_key_test.go new file mode 100644 index 000000000..fcb851c2c --- /dev/null +++ b/ui/switch_key_test.go @@ -0,0 +1,89 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A switch named with a Key keeps its name when the value it is bound to moves to +// another address: rows that copy their state into the same scratch storage in a +// new order keep the keyboard on the switch it was on, and Space flips that one. +// Unnamed, a switch follows its value's address, as before. +func TestKeyedSwitchKeepsItsNameWhenItsValueMoves(t *testing.T) { + for _, named := range []bool{true, false} { + enabled := map[string]bool{"Alpha": false, "Beta": false} + var scratch [2]bool + swapped := false + d := openPage(t, func(c ui.C) { + ui.Column(c).Children(func() { + for i, name := range []string{"Alpha", "Beta"} { + slot := i + if swapped { + slot = 1 - i + } + scratch[slot] = enabled[name] + in := c + if named { + in = c.Key(name) + } + if ui.SwitchBase(in, &scratch[slot], name).Size(32, 19).Changed() { + enabled[name] = scratch[slot] + } + } + }) + }) + d.click("Alpha") + if !enabled["Alpha"] || d.Focused() != "Alpha" { + t.Fatalf("named=%v: a click on Alpha left %v with %q focused", named, enabled, d.Focused()) + } + before := d.hit("Alpha").ID + swapped = true + d.repaint() + if !named { + if d.Focused() != "Beta" { + t.Errorf("unnamed: the focus is on %q, want it to follow the value to Beta", d.Focused()) + } + continue + } + if after := d.hit("Alpha").ID; after != before || d.Focused() != "Alpha" { + t.Fatalf("keyed: Alpha went from %v to %v and %q has the focus", before, after, d.Focused()) + } + d.key(gfx.KeySpace) + if enabled["Alpha"] || enabled["Beta"] { + t.Errorf("keyed: Space on Alpha left %v", enabled) + } + } +} + +// A keyed control that moves to a place no control held in the last paint, as a +// prompt that moves from one layout to another, keeps the name its value had and +// the keyboard with it. +func TestKeyedSwitchThatMovesToANewPlaceKeepsItsFocus(t *testing.T) { + on := false + wide := false + d := openPage(t, func(c ui.C) { + layout := "narrow" + if wide { + layout = "wide" + } + ui.Column(c.Key(layout)).Children(func() { + ui.SwitchBase(c.Key("prompt"), &on, "Prompt").Size(32, 19) + }) + }) + d.click("Prompt") + if !on || d.Focused() != "Prompt" { + t.Fatalf("a click on Prompt left on=%v with %q focused", on, d.Focused()) + } + before := d.hit("Prompt").ID + wide = true + d.repaint() + if after := d.hit("Prompt").ID; after != before || d.Focused() != "Prompt" { + t.Fatalf("Prompt went from %v to %v and %q has the focus", before, after, d.Focused()) + } + d.key(gfx.KeySpace) + if on { + t.Error("Space after the move did not reach Prompt") + } +} diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md index 464989988..265aece41 100644 --- a/website/content/guides/en/declarative-layout.md +++ b/website/content/guides/en/declarative-layout.md @@ -63,8 +63,8 @@ A click flips `m.sync` in the paint that delivers it, the first time the control An element is named by where it is: its kind and its number among the elements of that kind in its container. Three things refine that: -- A control bound to a value is named by that value's address, and the name follows the value when it moves: a field shown above a password field does not take the password's focus, and filtering a list keeps each checkbox's focus on its row. A copy (`v := m.items[k]; ui.Checkbox(c, &v, ...)`) works too: it keeps the name of its place, so write the copy back after the call. -- Inside `c.Key(item.ID)` or `c.KeyInt(id)`, elements are numbered within that row, so a row's buttons follow it when rows come, go or move. Keys are reused two paints after their row is gone. A loop whose rows hold a `Button` keys its rows; `viva vet` reports one that does not. +- A control bound to a value is named by that value's address, and the name follows the value when it moves: a field shown above a password field does not take the password's focus, and filtering a list keeps each checkbox's focus on its row. A copy (`v := m.items[k]; ui.Checkbox(c, &v, ...)`) works too: it keeps the name of its place, so write the copy back after the call. A control inside `c.Key` or named with `c.Part` keeps that name whatever it is bound to, so copies that trade addresses between paints, as copies into one scratch slice do when rows move, do not trade the controls' focus. +- Inside `c.Key(item.ID)` or `c.KeyInt(id)`, elements are numbered within that row, so a row's buttons follow it when rows come, go or move. Keys are reused two paints after their row is gone. A loop whose rows hold a `Button` keys its rows; `viva vet` reports one that does not. `Text`, `Icon`, `Spacer` and the other leaves have no identity and take no name: give the Key or Part to the row around them (a dev build stops on a leaf given one, and `viva vet` reports it). - While the user holds a button (presses it, or it has the focus), a paint in which another button took its place does not deliver the press, and the focus is given up. @@ -282,7 +282,7 @@ ui.Row(c).Pad(8).Radius(8).Hit(ui.ID(c), "Open").Transition(). Focus(ui.Look{}.Ring(3, theme.Ring)) ``` -`Focus` applies when the focus is meant to be seen (after a key, not after a click); a `Hit` is focusable unless `HitWith` says `SkipFocus`. The looks combine field by field in the order Focus, Hover, Pressed, so a focused row that is hovered shows the ring of one and the fill of the other. `Transition()` fades between them over the theme's motion (`TransitionWith` takes another); while nothing changes it schedules no frames. `StateFrom(row)` makes an element follow the state of another, so what is inside a row can change with the row: `ui.Icon(c, edit).Opacity(0).StateFrom(row).Hover(ui.Look{}.Opacity(1))` is an icon that appears when its row is hovered. +`Focus` applies when the focus is meant to be seen (after a key, not after a click); a `Hit` is focusable unless `HitWith` says `SkipFocus`. The looks combine field by field in the order Focus, Hover, Pressed, so a focused row that is hovered shows the ring of one and the fill of the other. `Transition()` fades between them over the theme's motion (`TransitionWith` takes another); while nothing changes it schedules no frames. `StateFrom(row)` makes an element follow the state of another, so what is inside a row can change with the row: `ui.Icon(c, edit).Opacity(0).StateFrom(row).Hover(ui.Look{}.Opacity(1))` is an icon that appears when its row is hovered. The row's state takes in what the row holds, as CSS's `:hover` and `:focus-within` do, so the icon stays while the pointer is on a button in the row or the keyboard is on it; `row.StateWithin()` gives the same state to code that declares more or less. A row with no action of its own takes the pointer with `HitWith(ui.ID(c), "", gfx.HitOptions{Presentational: true})`, which adds no tab stop. Four effects have no state of their own. `Ring(width, color)` draws a line around the outside of the element without taking room, as a focus ring does. `Opacity(v)` fades the element and everything in it, controls included; it stays laid out and clickable at 0, and an `Image` is not faded. `Gradient(angle, from, to)` and `GradientStops(angle, stops...)` fill the element, corners included, with a linear gradient, over its `Background` and under its `Border`; the angle is in degrees clockwise from up, as in CSS, and `ui.ToRight`, `ui.ToBottomRight` and the others name the common ones. diff --git a/website/content/guides/en/testing.md b/website/content/guides/en/testing.md index 53783a3ef..9f66e7ff4 100644 --- a/website/content/guides/en/testing.md +++ b/website/content/guides/en/testing.md @@ -116,7 +116,7 @@ A page can compile and still do the wrong thing: a `Button` with the same label viva vet # or go tool viva vet; packages default to ./... ``` -It reports each one as `file:line:col: what is wrong and what to write (check)`, exits non-zero when it finds something, and runs with the project's own Go. A line, or the line above it, with `// viva:ignore ` silences one finding. It also reports a `ui.C` or `ui.Box` kept past its paint (in a struct, a package variable or a goroutine), and a `ui.Memo` whose value misses a field its function reads. A `ui.Memo` whose value misses something its function reads shows stale content: `ui.MemoCheck(true)` (or `PageConfig.MemoCheck`) in a test declares every part and panics where a copy would have differed. +It reports each one as `file:line:col: what is wrong and what to write (check)`, exits non-zero when it finds something, and runs with the project's own Go. A line, or the line above it, with `// viva:ignore ` silences one finding. It also reports a `ui.C` or `ui.Box` kept past its paint (in a struct, a package variable or a goroutine), a `ui.Memo` whose value misses a field its function reads, and a Key or Part given straight to an element that takes no name (`ui.Text(c.Part("note"), ...)`, an `Icon`, a `Spacer`), which the dev build stops on (named-leaf). A `ui.Memo` whose value misses something its function reads shows stale content: `ui.MemoCheck(true)` (or `PageConfig.MemoCheck`) in a test declares every part and panics where a copy would have differed. ## The line protocol diff --git a/website/content/guides/en/text-input.md b/website/content/guides/en/text-input.md index 51c3bd7f6..2cfd9e413 100644 --- a/website/content/guides/en/text-input.md +++ b/website/content/guides/en/text-input.md @@ -115,6 +115,8 @@ Call `.Secure()` on the `ui.TextField` (or set `Secure` on a `ui.Field`, or `Inp A `ui.TextArea` is a password field the same way: `.Secure()` on it, or `Secure` on its `ui.Field` (or `TextareaSnapshot.Secure`). It keeps its line breaks between the bullets, so its rows, its caret, a selection and a press land where they do for the text, and the offsets its `TextareaLayout` reports stay offsets into the value. A secret the size of a key costs one build of its bullets per edit, and a steady paint allocates nothing. Without a `Layout` such a box paints a run of bullets for each of its rows from the first, and no caret or selection. +A secret should not outlive its use in the field either. A `.Secure()` field bound to a string is wiped when the page no longer declares it, and when the program changes the string (setting it to `""` as a dialog closes): `Field.Wipe` overwrites with zeros what its editor held, the text, its undo and redo and an input method's composition, and leaves it empty, so neither memory nor an undo brings the secret back. A `ui.Field` the application keeps is its own to wipe with `Wipe` once the secret is done with; `text.Editor.Wipe` does the same for an editor of yours. The string the field wrote into your model is yours: Go strings cannot be overwritten, so keep the secret there only as long as you need it. + ## Several lines and addons `components.PaintInputGroup` takes the same kind of snapshot with `Multiline`, and four addon slots, `InlineStart`, `InlineEnd`, `BlockStart` and `BlockEnd`, for icons, text prefixes and buttons. `components.PaintTextarea` and the other fields build on the same pieces; each has a page in the [component catalog](/en/ui/input/) with runnable examples. diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md index ea5bc332d..84f2a99f2 100644 --- a/website/content/guides/zh/declarative-layout.md +++ b/website/content/guides/zh/declarative-layout.md @@ -63,8 +63,8 @@ ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, ui.PageConfig{Vie 元素按位置命名:它的种类,以及它在所在容器里同类元素中的序号。另有三条细化: -- 绑定了值的控件以该值的地址命名,值移动时名字跟着走:在密码框上方出现的输入框不会拿走密码框的焦点;过滤列表时,每个复选框的焦点留在它那一行。绑定副本(`v := m.items[k]; ui.Checkbox(c, &v, ...)`)同样可用:它沿用所在位置的名字,调用之后把副本写回即可。 -- 在 `c.Key(item.ID)` 或 `c.KeyInt(id)` 里,元素只在这一行内部编号,所以行出现、消失或移动时,行里的按钮跟着这一行走。行消失两遍绘制之后,它的 Key 才会被复用。行里有 `Button` 的循环要给行加 Key;没加时 `viva vet` 会报告。 +- 绑定了值的控件以该值的地址命名,值移动时名字跟着走:在密码框上方出现的输入框不会拿走密码框的焦点;过滤列表时,每个复选框的焦点留在它那一行。绑定副本(`v := m.items[k]; ui.Checkbox(c, &v, ...)`)同样可用:它沿用所在位置的名字,调用之后把副本写回即可。在 `c.Key` 里或用 `c.Part` 命名的控件,无论绑定到哪个值都保留这个名字;所以副本在两次绘制之间互换地址时(比如行移动后复制进同一个暂存切片),控件的焦点不会跟着互换。 +- 在 `c.Key(item.ID)` 或 `c.KeyInt(id)` 里,元素只在这一行内部编号,所以行出现、消失或移动时,行里的按钮跟着这一行走。行消失两遍绘制之后,它的 Key 才会被复用。行里有 `Button` 的循环要给行加 Key;没加时 `viva vet` 会报告。`Text`、`Icon`、`Spacer` 等叶子元素没有标识,不接受名字:把 Key 或 Part 给它们外面的行(给叶子元素名字时开发构建会停下,`viva vet` 也会报告)。 - 用户按住一个按钮(按下它,或它有焦点)时,如果某一遍绘制里另一个按钮占了它的位置,这次按下不会递送,焦点也会被放弃。 `ui.TextArea(c, &m.notes, label, placeholder)` 是多行输入框。 @@ -283,7 +283,7 @@ ui.Row(c).Pad(8).Radius(8).Hit(ui.ID(c), "Open").Transition(). Focus(ui.Look{}.Ring(3, theme.Ring)) ``` -`Focus` 在焦点应当可见时生效(由按键移动而来,点击不算);`Hit` 默认可获得焦点,除非用 `HitWith` 指定 `SkipFocus`。几个 Look 按 Focus、Hover、Pressed 的顺序逐字段合并,所以既聚焦又悬停的行会同时显示前者的光环和后者的底色。`Transition()` 按主题的动效在它们之间渐变(`TransitionWith` 可指定其他动效);没有变化时不会安排任何帧。`StateFrom(row)` 让一个元素跟随另一个元素的状态,行内的内容就能随行变化:`ui.Icon(c, edit).Opacity(0).StateFrom(row).Hover(ui.Look{}.Opacity(1))` 是一个在所在行悬停时才出现的图标。 +`Focus` 在焦点应当可见时生效(由按键移动而来,点击不算);`Hit` 默认可获得焦点,除非用 `HitWith` 指定 `SkipFocus`。几个 Look 按 Focus、Hover、Pressed 的顺序逐字段合并,所以既聚焦又悬停的行会同时显示前者的光环和后者的底色。`Transition()` 按主题的动效在它们之间渐变(`TransitionWith` 可指定其他动效);没有变化时不会安排任何帧。`StateFrom(row)` 让一个元素跟随另一个元素的状态,行内的内容就能随行变化:`ui.Icon(c, edit).Opacity(0).StateFrom(row).Hover(ui.Look{}.Opacity(1))` 是一个在所在行悬停时才出现的图标。行的状态包含行内的元素,和 CSS 的 `:hover`、`:focus-within` 一样:指针停在行内按钮上、或键盘焦点在行内时,图标仍然显示;需要据此多声明或少声明内容时,用 `row.StateWithin()` 取同样的状态。自身没有动作的行用 `HitWith(ui.ID(c), "", gfx.HitOptions{Presentational: true})` 接收指针,不会多出 Tab 停靠点。 另有四种不依赖状态的效果。`Ring(width, color)` 在元素外侧画一圈线且不占空间,焦点环就是这样画的。`Opacity(v)` 让元素及其内部的一切(包括控件)淡化;取 0 时仍参与布局、仍可点击;`Image` 不会被淡化。`Gradient(angle, from, to)` 和 `GradientStops(angle, stops...)` 沿圆角用线性渐变填充元素,画在 `Background` 之上、`Border` 之下;角度与 CSS 相同,以向上为 0 顺时针计,`ui.ToRight`、`ui.ToBottomRight` 等给常用方向命名。 diff --git a/website/content/guides/zh/testing.md b/website/content/guides/zh/testing.md index 4eabbb194..54965b3d7 100644 --- a/website/content/guides/zh/testing.md +++ b/website/content/guides/zh/testing.md @@ -109,7 +109,7 @@ if got := session.Notifications(); len(got) != 1 || got[0].Title != "Installed" viva vet # 或 go tool viva vet;包默认为 ./... ``` -每个问题报告为 `文件:行:列: 哪里错了以及应该怎么写 (检查名)`,发现问题时以非零状态退出,并使用项目自己的 Go 运行。在该行或上一行写 `// viva:ignore <检查名>` 可以忽略一条。它还会报告跨帧保留的 `ui.C` 或 `ui.Box`(在结构体、包变量或 goroutine 里),以及 value 漏掉函数读取字段的 `ui.Memo`。`ui.Memo` 的值漏掉了函数读取的某个状态时会显示旧内容:在测试里打开 `ui.MemoCheck(true)`(或 `PageConfig.MemoCheck`),它会声明每个部件,并在复制结果与声明结果不同时 panic。 +每个问题报告为 `文件:行:列: 哪里错了以及应该怎么写 (检查名)`,发现问题时以非零状态退出,并使用项目自己的 Go 运行。在该行或上一行写 `// viva:ignore <检查名>` 可以忽略一条。它还会报告跨帧保留的 `ui.C` 或 `ui.Box`(在结构体、包变量或 goroutine 里),value 漏掉函数读取字段的 `ui.Memo`,以及直接交给不接受名字的元素的 Key 或 Part(`ui.Text(c.Part("note"), ...)`、`Icon`、`Spacer`),开发构建会在这里停下(named-leaf)。`ui.Memo` 的值漏掉了函数读取的某个状态时会显示旧内容:在测试里打开 `ui.MemoCheck(true)`(或 `PageConfig.MemoCheck`),它会声明每个部件,并在复制结果与声明结果不同时 panic。 ## 行协议 diff --git a/website/content/guides/zh/text-input.md b/website/content/guides/zh/text-input.md index 41bb8d962..f4b8833d5 100644 --- a/website/content/guides/zh/text-input.md +++ b/website/content/guides/zh/text-input.md @@ -115,6 +115,8 @@ func (m *model) page(c ui.C) { `ui.TextArea` 同样可以成为密码字段:在它上面调用 `.Secure()`,或在其 `ui.Field` 上设置 `Secure`(或设置 `TextareaSnapshot.Secure`)。多行文本区域在圆点之间保留换行,所以它的行、光标、选区和点击定位都与显示文本时一致,`TextareaLayout` 报告的偏移量仍是值里的偏移量。一份密钥大小的机密只在文本变化时重建一次圆点,稳定状态下绘制零分配。没有 `Layout` 时,这样的框从第一行起为每行画一段圆点,不画光标和选区。 +机密用完后也不应留在字段里。绑定到字符串的 `.Secure()` 字段在页面不再声明它时,以及程序修改这个字符串时(比如关闭对话框时把它设为 `""`),会被擦除:`Field.Wipe` 用零覆盖编辑器持有的内容,包括文本、撤销与重做记录和输入法的组字,并把字段清空,内存和撤销都找不回机密。应用自己持有的 `ui.Field` 在机密用完后由应用调用 `Wipe`;你自己的编辑器用 `text.Editor.Wipe`。字段写回模型的字符串归你所有:Go 字符串无法被覆盖,所以只在需要的时候把机密留在那里。 + ## 多行与附加元素 `components.PaintInputGroup` 接受同类型的快照,支持 `Multiline`,并提供四个附加槽位 `InlineStart`、`InlineEnd`、`BlockStart` 和 `BlockEnd`,用于图标、文字前缀和按钮。`components.PaintTextarea` 和其他字段建立在同样的部件之上;[组件目录](/zh/ui/input/)里每个都有一页,带可运行的示例。