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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1023,6 +1023,7 @@ The WASM binary includes none of the charmbracelet packages. The TUI binary incl

## Limitations (v1)

- **Responsive in a browser Row reserves its widest breakpoint** — the browser picks a variant with container queries, which need a box whose width does not depend on the variant shown, so inside a Row the wrapper takes up to its largest `MinWidth` (shrinking when the row is tight) whatever variant is visible, including an `Empty()` one. The TUI sizes it to the variant drawn. In a Column the two match, and an `Empty()` variant takes no space in either.
- **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
28 changes: 28 additions & 0 deletions e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,3 +429,31 @@ func TestColumnGapIsOneLineAndSkipsEmpty(t *testing.T) {
t.Errorf("a hidden When adds space: %.1fpx with it, %.1fpx without", withEmpty, plain)
}
}

func TestResponsiveEmptyPickTakesNoSlot(t *testing.T) {
ctx := page(t, 1000)
vgap := func(a, b string) float64 {
return eval[float64](t, ctx, fmt.Sprintf(
`byText(%q).getBoundingClientRect().top - byText(%q).getBoundingClientRect().bottom`, b, a))
}
near := func(got, want float64) bool { return got-want > -1 && got-want < 1 }
line := vgap("gap-a", "gap-b")

if !eval[bool](t, ctx, `visible("rg-wide")`) {
t.Fatal("wide variant not shown at 1000px")
}
wideTop := eval[float64](t, ctx, `byText("rg-wide").parentElement.getBoundingClientRect().top`)
aBottom := eval[float64](t, ctx, `byText("rg-a").getBoundingClientRect().bottom`)
if got := wideTop - aBottom; !near(got, line) {
t.Errorf("gap before the visible wide variant = %.1fpx, want one gap (%.1fpx)", got, line)
}

if err := chromedp.Do(ctx, chromedp.EmulateViewport(300, 900)); err != nil {
t.Fatal(err)
}
waitJS(t, ctx, `!visible("rg-wide")`)
time.Sleep(50 * time.Millisecond)
if got := vgap("rg-a", "rg-b"); !near(got, line) {
t.Errorf("Column: an empty Responsive pick leaves %.1fpx between its siblings, want one gap (%.1fpx)", got, line)
}
}
2 changes: 2 additions & 0 deletions e2e/probe/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ func (m model) View() wui.Element {
return wui.Box(wui.Column,
shifting,
wui.BoxStyled(wui.Column, 1, wui.Style{}, wui.Text("gap-a"), wui.Text("gap-b")),
wui.BoxStyled(wui.Column, 1, wui.Style{},
wui.Text("rg-a"), wui.Responsive(wui.At(0, wui.Empty()), wui.At(60, wui.Text("rg-wide"))), wui.Text("rg-b")),
wui.BoxStyled(wui.Column, 1, wui.Style{},
wui.Text("gap-c"), wui.When(false, func() wui.Element { return wui.Text("hidden") }), wui.Text("gap-d")),
wui.Button("Prepend", func() wui.Msg { return prependMsg{} }, wui.WithID("prepend")),
Expand Down
59 changes: 59 additions & 0 deletions rempty_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//go:build !js

package wui

import (
"strings"
"testing"
)

// trimLines drops trailing spaces from every line, so expectations do
// not depend on how far lipgloss pads each line.
func trimLines(s string) string {
lines := strings.Split(s, "\n")
for i, l := range lines {
lines[i] = strings.TrimRight(l, " ")
}
return strings.Join(lines, "\n")
}

func TestResponsiveEmptyVariantTakesNoSlot(t *testing.T) {
r := func() Element { return Responsive(At(0, Empty()), At(30, Text("wide"))) }
tests := []struct {
name string
el Element
width int
want string
}{
{"column gap, empty picked", BoxStyled(Column, 1, Style{}, Text("a"), r(), Text("b")), 20, "a\n\nb"},
{"column gap, content picked", BoxStyled(Column, 1, Style{}, Text("a"), r(), Text("b")), 40, "a\n\nwide\n\nb"},
{"column no gap, empty picked", BoxStyled(Column, 0, Style{}, Text("a"), r(), Text("b")), 20, "a\nb"},
{"row gap, empty picked", BoxStyled(Row, 1, Style{}, Text("a"), r(), Text("b")), 20, "a b"},
{"keyed, empty picked", BoxStyled(Column, 1, Style{}, Text("a"), Keyed("k", r()), Text("b")), 20, "a\n\nb"},
{"nested responsive", BoxStyled(Column, 1, Style{}, Text("a"),
Responsive(At(0, r()), At(100, Text("huge"))), Text("b")), 20, "a\n\nb"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := trimLines(RenderTUISized(tt.el, tt.width, 10)); got != tt.want {
t.Errorf("got %q, want %q", got, tt.want)
}
})
}
}

func TestDroppedResponsiveKeepsFocusPicksAligned(t *testing.T) {
m := newRingModel(func(ringModel) Element {
return BoxStyled(Column, 1, Style{},
Responsive(At(0, Empty()), At(30, Button("Hidden", func() Msg { return testMsg("hidden") }))),
Responsive(At(0, Button("Small", func() Msg { return testMsg("small") })), At(30, Button("Big", func() Msg { return testMsg("big") }))),
)
})
a := newTrapAdapter(m)
a.renderer.Width = 20
a.View()
key(a, "tab")
if got := a.focus.FocusedID(); got != "btn:Small" {
t.Fatalf("Tab focused %q, want btn:Small after an empty-picking Responsive", got)
}
}
47 changes: 45 additions & 2 deletions render_tui.go
Original file line number Diff line number Diff line change
Expand Up @@ -665,14 +665,20 @@ func (r *tuiRenderer) renderBox(e BoxEl) string {
shareAvail = (shareAvail - e.Gap*(len(children)-1)) / len(children)
}
keysBefore, picksBefore := r.buttonKeys.clone(), len(r.picks)
rendered := children
parts := make([]string, 0, len(children))
avails := make([]int, 0, len(children))
for _, c := range children {
w := shareAvail
if s, ok := styleOf(c); ok && s.Width == Fill {
w = childAvail
}
parts = append(parts, r.withAvail(w, func() string { return r.renderEl(c) }))
parts = append(parts, r.withAvail(w, func() string {
avails = append(avails, r.availWidth())
return r.renderEl(c)
}))
}
children, parts = dropEmptyPicks(rendered, parts, avails)
innerH := height
if innerH > 0 {
innerH -= e.Style.Padding[0] + e.Style.Padding[2] + borderCells(e.Style)
Expand All @@ -685,8 +691,15 @@ func (r *tuiRenderer) renderBox(e BoxEl) string {
// the full width so the collapsed panes stay aligned.
dir = Column
r.buttonKeys, r.picks = keysBefore, r.picks[:picksBefore]
parts, avails = parts[:0], avails[:0]
for _, c := range rendered {
parts = append(parts, r.withAvail(childAvail, func() string {
avails = append(avails, r.availWidth())
return r.renderEl(c)
}))
}
children, parts = dropEmptyPicks(rendered, parts, avails)
for i, c := range children {
parts[i] = r.withAvail(childAvail, func() string { return r.renderEl(c) })
if s, ok := styleOf(c); ok && s.Grow > 0 {
parts[i] = lipgloss.NewStyle().Width(innerW).Render(parts[i])
}
Expand Down Expand Up @@ -812,6 +825,36 @@ func laidOutChildren(children []Element) []Element {
return out
}

// dropEmptyPicks removes the children that drew nothing because a
// Responsive picked an empty variant at the width it was given (avails,
// parallel to children and parts), so they take no slot and no gap,
// like a static Empty. They are rendered first, so their picks are
// still recorded for the focus ring.
func dropEmptyPicks(children []Element, parts []string, avails []int) ([]Element, []string) {
keptC, keptP := children[:0:0], parts[:0:0]
for i, c := range children {
if pickedEmpty(c, avails[i]) {
continue
}
keptC = append(keptC, c)
keptP = append(keptP, parts[i])
}
return keptC, keptP
}

// pickedEmpty reports whether el renders as Empty at the given
// available width, looking through Keyed and the variant a Responsive
// picks.
func pickedEmpty(el Element, avail int) bool {
switch v := unkeyed(el).(type) {
case nil, EmptyEl:
return true
case ResponsiveEl:
return pickedEmpty(v.variant(v.pickIndex(avail)), avail)
}
return false
}

// 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 {
Expand Down
67 changes: 67 additions & 0 deletions render_wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ type wasmRenderer struct {
dispatch func(Msg)
doc js.Value
tree *mounted

// emptyWatch observes Responsive wrappers that have an Empty
// variant, re-checking which variant shows whenever their size
// changes; see watchEmptyAttr. Created on first use.
emptyWatch js.Value
emptyWatchFn js.Func
}

// mounted is a vnode together with the DOM node created for it.
Expand Down Expand Up @@ -99,6 +105,9 @@ func (r *wasmRenderer) create(v *vnode) *mounted {
m.dom.Set(p.name, p.value)
}
r.listen(m, v.on)
if _, ok := v.attrs[watchEmptyAttr]; ok {
r.watchEmpty(m.dom)
}
return m
}

Expand Down Expand Up @@ -156,6 +165,16 @@ func (r *wasmRenderer) patch(m *mounted, v *vnode) *mounted {
}

r.listen(m, v.on)
_, was := old.attrs[watchEmptyAttr]
_, is := v.attrs[watchEmptyAttr]
switch {
case is && !was:
r.watchEmpty(m.dom)
case was && !is:
r.unwatchEmpty(m.dom)
case is:
markEmptyPick(m.dom)
}
m.v = v
return m
}
Expand Down Expand Up @@ -293,6 +312,9 @@ func (r *wasmRenderer) listen(m *mounted, on map[string]vhandler) {
// removed its own form) then skips them instead of calling a released
// function.
func (r *wasmRenderer) release(m *mounted) {
if _, ok := m.v.attrs[watchEmptyAttr]; ok {
r.unwatchEmpty(m.dom)
}
for typ, l := range m.listeners {
l.fn = nil
m.dom.Call("removeEventListener", typ, l.js)
Expand All @@ -304,6 +326,51 @@ func (r *wasmRenderer) release(m *mounted) {
}
}

// watchEmpty starts observing a Responsive wrapper so markEmptyPick
// runs whenever its size changes. ResizeObserver delivers the first
// observation, and every later one, after layout and before paint, so
// the gap is corrected without a visible flicker.
func (r *wasmRenderer) watchEmpty(outer js.Value) {
if r.emptyWatch.IsUndefined() {
r.emptyWatchFn = js.FuncOf(func(this js.Value, args []js.Value) any {
entries := args[0]
for i, n := 0, entries.Length(); i < n; i++ {
markEmptyPick(entries.Index(i).Get("target"))
}
return nil
})
r.emptyWatch = js.Global().Get("ResizeObserver").New(r.emptyWatchFn)
}
r.emptyWatch.Call("observe", outer)
}

// unwatchEmpty stops observing a wrapper and clears its flag.
func (r *wasmRenderer) unwatchEmpty(outer js.Value) {
if !r.emptyWatch.IsUndefined() {
r.emptyWatch.Call("unobserve", outer)
}
outer.Call("removeAttribute", emptyFlagAttr)
}

// markEmptyPick sets emptyFlagAttr on a Responsive wrapper while one of
// its Empty variants is the variant on display, and clears it
// otherwise.
func markEmptyPick(outer js.Value) {
variants := outer.Call("querySelectorAll", ":scope > div > ["+emptyVariantAttr+"]")
empty := false
for i, n := 0, variants.Length(); i < n; i++ {
if js.Global().Call("getComputedStyle", variants.Index(i)).Get("display").String() != "none" {
empty = true
break
}
}
if empty {
outer.Call("setAttribute", emptyFlagAttr, "")
} else {
outer.Call("removeAttribute", emptyFlagAttr)
}
}

// propEquals compares a live DOM property with a described value.
func propEquals(cur js.Value, want any) bool {
switch w := want.(type) {
Expand Down
Loading
Loading