Skip to content
7 changes: 6 additions & 1 deletion base/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
18 changes: 18 additions & 0 deletions base/field_wipe.go
Original file line number Diff line number Diff line change
@@ -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{}
}
24 changes: 23 additions & 1 deletion base/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}
Expand All @@ -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)
Expand All @@ -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}
}
Expand Down
69 changes: 69 additions & 0 deletions base/state_within.go
Original file line number Diff line number Diff line change
@@ -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
}
15 changes: 13 additions & 2 deletions base/style.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
46 changes: 46 additions & 0 deletions base/style_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
28 changes: 26 additions & 2 deletions base/text_value.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}
Expand All @@ -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 {
Expand All @@ -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
}
6 changes: 4 additions & 2 deletions cmd/viva/initfiles/AGENTS.md.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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): <https://github.com/vivaui/viva/tree/main/examples/recipes>, with guidance in <https://github.com/vivaui/viva/blob/main/docs/skills/building-with-viva/recipes.md>.
- 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
Expand Down
37 changes: 37 additions & 0 deletions cmd/viva/vet.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion cmd/viva/vet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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)
}
Expand Down
Loading
Loading