Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,16 @@ The `element.go`, `style.go`, `msg.go`, `program.go`, `key.go`, `cmd.go`, `statu

**HTML**: every state change describes the new tree as lightweight virtual nodes and **patches** `#wui-root` in place. Children are matched by identity: controls with an ID (inputs, buttons, selects, checkboxes, text areas, links) find their old node wherever it moved, and other nodes reuse the next old sibling with the same tag. A node is replaced only when nothing matches, so a banner inserted above a form does not rebuild the inputs below it. Because the DOM nodes persist, browser-owned state survives updates without any bookkeeping: keyboard focus, caret and selection, scroll offsets, in-progress typing, and an open native dropdown. `Empty()` and false `If`/`When` branches render as invisible placeholders, so toggling one never shifts its siblings onto each other's nodes.

For lists whose rows have no ID'd controls, give each row a key with `wui.Keyed`. The renderer then moves existing rows and inserts only the new one, instead of re-patching every row from the insertion point down, and per-row browser state stays with its row:

```go
wui.List(false, wui.Map(m.todos, func(_ int, t Todo) wui.Element {
return wui.Keyed(t.ID, row(t))
})...)
```

`Keyed` adds no markup or layout, and the TUI renders the child unchanged.

Event listeners are attached once per node and swap their handler on each patch, so a re-render allocates no new `js.Func`s for unchanged elements.

---
Expand Down Expand Up @@ -983,7 +993,6 @@ The WASM binary includes none of the charmbracelet packages. The TUI binary incl

## Limitations (v1)

- **No explicit keys** — the HTML renderer matches controls by their IDs and everything else by tag order. Rows without ID'd controls are matched in order, so inserting at the front of a long list patches every row rather than moving them.
- **Button focus keys derive from labels by default** — two buttons with the same label and no `WithID` in one view share TUI focus; give repeated buttons IDs.
- **No theme system** — style is applied per-element inline (`Style.Merge` helps compose variants); in the browser the base stylesheet's `--wui-*` custom properties, `WithStylesheet` and `Style.Class` are the global styling hooks.
- **TextArea editing is basic in the TUI** — typing, Enter, and Backspace append and delete at the end of the buffer; there is no cursor movement within the text. The browser build uses a native `<textarea>` with full editing.
Expand Down
16 changes: 16 additions & 0 deletions e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -397,3 +397,19 @@ func TestInsertedSiblingsKeepStatefulNodes(t *testing.T) {
}
}
}

func TestKeyedRowsMoveInsteadOfRepatching(t *testing.T) {
ctx := page(t, 1000)
do(t, ctx, `byText("row-r1").wuiMark = "r1"; byText("row-r2").wuiMark = "r2"`)
do(t, ctx, `document.getElementById("btn:prepend").click()`)
waitText(t, ctx, "row-r3")
for _, r := range []string{"r1", "r2"} {
if got := eval[string](t, ctx, fmt.Sprintf(`String(byText("row-%s").wuiMark)`, r)); got != r {
t.Errorf("row %s was re-patched from another row's node (mark %q)", r, got)
}
}
order := eval[string](t, ctx, `[...byText("row-r3").closest("ul").children].map(li => li.textContent).join(",")`)
if order != "row-r3,row-r2,row-r1" {
t.Errorf("row order = %q", order)
}
}
10 changes: 9 additions & 1 deletion e2e/probe/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type model struct {
checked bool
cancels int
submits int
rows []string
}

type clickMsg struct{}
Expand All @@ -29,6 +30,7 @@ type submitMsg map[string]string
type envMsg string
type checkMsg bool
type cancelMsg struct{}
type prependMsg struct{}

func (m model) Init() wui.Cmd { return nil }

Expand All @@ -46,6 +48,8 @@ func (m model) Update(msg wui.Msg) (wui.Model, wui.Cmd) {
m.checked = bool(v)
case cancelMsg:
m.cancels++
case prependMsg:
m.rows = append([]string{fmt.Sprintf("r%d", len(m.rows)+1)}, m.rows...)
case submitMsg:
m.submits++
keys := make([]string, 0, len(v))
Expand Down Expand Up @@ -90,6 +94,10 @@ func (m model) View() wui.Element {

return wui.Box(wui.Column,
shifting,
wui.Button("Prepend", func() wui.Msg { return prependMsg{} }, wui.WithID("prepend")),
wui.List(false, wui.Map(m.rows, func(_ int, r string) wui.Element {
return wui.Keyed(r, wui.Text("row-"+r))
})...),
wui.Responsive(wui.At(0, wui.Text("resp-narrow")), wui.At(60, wui.Text("resp-wide"))),
wui.Box(wui.Row,
wui.Text("[row]"),
Expand Down Expand Up @@ -132,7 +140,7 @@ func (m model) View() wui.Element {

func main() {
sheet := wui.WithStylesheet(`.probe-class { color: rgb(1, 2, 3); } :root { --wui-accent: rgb(4, 5, 6); }`)
if err := wui.NewProgram(model{env: "dev"}, sheet).Run(); err != nil {
if err := wui.NewProgram(model{env: "dev", rows: []string{"r2", "r1"}}, sheet).Run(); err != nil {
panic(err)
}
}
46 changes: 46 additions & 0 deletions element.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,33 @@ func (ProgressEl) isElement() {}
func (SpinnerEl) isElement() {}
func (SelectEl) isElement() {}
func (TextAreaEl) isElement() {}
func (KeyedEl) isElement() {}

// KeyedEl gives its child a stable identity for the browser renderer;
// see Keyed.
type KeyedEl struct {
Key string
Child Element
}

// Keyed tags el with an identity the browser renderer matches on when
// patching, like keys in React or Elm. Without keys, children are
// matched by their controls' IDs and then in order, so inserting at the
// front of a long list patches every row; with a key per row the
// renderer moves the existing rows and inserts one, and per-row browser
// state (text selection, an open details element, a CSS transition)
// stays with its row. Keys must be unique among siblings.
//
// Keyed adds no layout or markup of its own: the child renders exactly
// as it would unwrapped, and a Box reads Grow and MinWidth through it.
// The TUI renders the child unchanged.
//
// wui.List(false, wui.Map(m.todos, func(_ int, t Todo) wui.Element {
// return wui.Keyed(t.ID, row(t))
// })...)
func Keyed(key string, el Element) Element {
return KeyedEl{Key: key, Child: orEmpty(el)}
}

// spinnerFrames is the glyph cycle used by SpinnerEl in both renderers,
// so an app's frame counter animates identically on either platform.
Expand Down Expand Up @@ -301,6 +328,11 @@ func Children(el Element) []Element {
return nil
}
return []Element{v.Child}
case KeyedEl:
if v.Child == nil {
return nil
}
return []Element{v.Child}
case ResponsiveEl:
// Every variant counts as a child. Which one draws depends on
// the width available at render time, which Children cannot
Expand Down Expand Up @@ -356,10 +388,24 @@ func styleOf(el Element) (Style, bool) {
return v.Style, true
case TextAreaEl:
return v.Style, true
case KeyedEl:
return styleOf(v.Child)
}
return Style{}, false
}

// unkeyed strips Keyed wrappers, for layout code that checks a child's
// concrete type.
func unkeyed(el Element) Element {
for {
k, ok := el.(KeyedEl)
if !ok {
return el
}
el = k.Child
}
}

// Walk calls fn for el and every descendant, depth-first in tree order.
// Returning false from fn skips that element's children.
func Walk(el Element, fn func(Element) bool) {
Expand Down
40 changes: 11 additions & 29 deletions render_tui.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,27 +159,19 @@ func collectFocusables(el Element, width int) []focusable {
case LinkEl:
id := "link:" + v.Href
out = append(out, focusable{ID: id, Activate: func() Msg { return ClickMsg{TargetID: v.Href} }})
case CardEl:
walk(v.Child, form)
case BoxEl:
for _, c := range v.Children {
walk(c, form)
}
case FormEl:
f := v
for _, c := range v.Children {
walk(c, &f)
}
case ListEl:
for _, c := range v.Items {
walk(c, form)
}
case ScrollAreaEl:
walk(v.Child, form)
case ResponsiveEl:
// Only the variant that actually draws is focusable, so
// Tab never lands on a control hidden at this width.
walk(v.pick(width), form)
default:
for _, c := range Children(e) {
walk(c, form)
}
}
}
walk(el, nil)
Expand Down Expand Up @@ -217,22 +209,10 @@ func (r *tuiRenderer) formValues(form FormEl) map[string]string {
if v.ID != "" {
values[v.ID] = v.Value
}
case BoxEl:
for _, c := range v.Children {
walk(c)
}
case FormEl:
for _, c := range v.Children {
walk(c)
}
case ListEl:
for _, c := range v.Items {
default:
for _, c := range Children(e) {
walk(c)
}
case ScrollAreaEl:
walk(v.Child)
case CardEl:
walk(v.Child)
}
}
for _, c := range form.Children {
Expand Down Expand Up @@ -358,6 +338,8 @@ func (r *tuiRenderer) renderEl(el Element) string {
return r.renderTextArea(e)
case ResponsiveEl:
return r.renderEl(e.pick(r.availWidth()))
case KeyedEl:
return r.renderEl(e.Child)
default:
return ""
}
Expand Down Expand Up @@ -740,7 +722,7 @@ func orElse(v, fallback int) int {
// flexWeight returns the flex-grow share of a Box child: its style's
// Grow, with a zero-size (Flex) spacer defaulting to one share.
func flexWeight(c Element) int {
if sp, ok := c.(SpacerEl); ok && sp.Size <= 0 {
if sp, ok := unkeyed(c).(SpacerEl); ok && sp.Size <= 0 {
return 1
}
if s, ok := styleOf(c); ok && s.Grow > 0 {
Expand Down Expand Up @@ -809,7 +791,7 @@ func distributeRow(children []Element, parts []string, gap, width int) {
if share <= 0 {
continue
}
if _, isSpacer := c.(SpacerEl); isSpacer {
if _, isSpacer := unkeyed(c).(SpacerEl); isSpacer {
parts[i] = strings.Repeat(" ", share)
continue
}
Expand Down Expand Up @@ -863,7 +845,7 @@ func distributeColumn(children []Element, parts []string, gap, height int) {
if share <= 0 {
continue
}
if _, isSpacer := c.(SpacerEl); isSpacer {
if _, isSpacer := unkeyed(c).(SpacerEl); isSpacer {
// A part occupies lipgloss.Height lines once joined; an
// n-line spacer is n-1 newlines.
parts[i] = strings.Repeat("\n", lipgloss.Height(parts[i])+share-1)
Expand Down
13 changes: 13 additions & 0 deletions responsive_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,3 +366,16 @@ func TestMaxHeightCaps(t *testing.T) {
t.Fatalf("MaxHeight 10 rendered %d rows", got)
}
}

func TestKeyedRendersChildUnchangedInTUI(t *testing.T) {
plain := Box(Row, Text("left"), Flex(), Text("right"))
keyed := Box(Row, Keyed("a", Text("left")), Keyed("f", Flex()), Keyed("b", Text("right")))
if got, want := renderAt(keyed, 30, 3), renderAt(plain, 30, 3); got != want {
t.Errorf("Keyed changed TUI output:\n%q\nwant\n%q", got, want)
}
nop := func() Msg { return nil }
fs := collectFocusables(Box(Column, Keyed("x", Button("Go", nop))), 80)
if len(fs) != 1 || fs[0].ID != "btn:Go" {
t.Errorf("button inside Keyed not focusable: %+v", fs)
}
}
11 changes: 10 additions & 1 deletion vdom.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,11 @@ func (d *describer) describe(el Element) *vnode {
return describeSelect(e)
case TextAreaEl:
return describeTextArea(e)
case KeyedEl:
d.inRow = inRow
n := d.describe(e.Child)
n.key = "keyed:" + e.Key
return n
case nil, EmptyEl:
return &vnode{tag: commentTag}
}
Expand Down Expand Up @@ -380,7 +385,11 @@ func (d *describer) describeList(e ListEl) *vnode {
}
n := styled(&vnode{tag: tag}, "", e.Style)
for _, item := range e.Items {
n.kids = append(n.kids, &vnode{tag: "li", kids: []*vnode{d.describe(orEmpty(item))}})
li := &vnode{tag: "li", kids: []*vnode{d.describe(orEmpty(item))}}
if k, ok := item.(KeyedEl); ok {
li.key = "keyed:" + k.Key
}
n.kids = append(n.kids, li)
}
return n
}
Expand Down
16 changes: 16 additions & 0 deletions vdom_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,19 @@ func TestDescribeStyleClassAndDividerClass(t *testing.T) {
t.Errorf("unstyled text has attrs %v", v.attrs)
}
}

func TestDescribeKeyedIsTransparent(t *testing.T) {
plain := describeTree(Box(Row, Text("a", WithTextStyle(NewStyle().Grown(2)))))
keyed := describeTree(Box(Row, Keyed("k1", Text("a", WithTextStyle(NewStyle().Grown(2))))))
p, k := plain.kids[0], keyed.kids[0]
if k.key != "keyed:k1" {
t.Errorf("keyed child key = %q", k.key)
}
if p.tag != k.tag || !reflect.DeepEqual(p.attrs, k.attrs) || p.text != k.text {
t.Errorf("Keyed changed the markup: %+v vs %+v", p, k)
}
spacer := describeTree(Box(Row, Keyed("s", Spacer(2))))
if got := spacer.kids[0].attrs["style"]; got != spacerCSS(2, true) {
t.Errorf("Keyed must pass the Row context through: spacer style %q", got)
}
}
Loading