diff --git a/focus_ring_test.go b/focus_ring_test.go new file mode 100644 index 0000000..cf33cf9 --- /dev/null +++ b/focus_ring_test.go @@ -0,0 +1,177 @@ +//go:build !js + +package wui + +import ( + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + zone "github.com/lrstanley/bubblezone" +) + +// ringModel renders whatever view func returns and records every Msg +// its Update receives, so tests can drive focus and routing. +type ringModel struct { + view func(m ringModel) Element + msgs *[]Msg + views *int + state map[string]bool +} + +func newRingModel(view func(m ringModel) Element) ringModel { + return ringModel{view: view, msgs: new([]Msg), views: new(int), state: map[string]bool{}} +} + +func (m ringModel) Init() Cmd { return nil } + +func (m ringModel) Update(msg Msg) (Model, Cmd) { + *m.msgs = append(*m.msgs, msg) + return m, nil +} + +func (m ringModel) View() Element { + *m.views++ + return m.view(m) +} + +func key(a *teaAdapter, k string) { + var m tea.KeyMsg + switch k { + case "tab": + m = tea.KeyMsg{Type: tea.KeyTab} + case "enter": + m = tea.KeyMsg{Type: tea.KeyEnter} + default: + m = tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(k)} + } + a.handleKey(m) + a.View() +} + +func lastMsg(m ringModel) Msg { + if len(*m.msgs) == 0 { + return nil + } + return (*m.msgs)[len(*m.msgs)-1] +} + +func TestDisabledInputsAreNotFocusable(t *testing.T) { + fs := collectFocusables(Box(Column, + Input("off", WithValue("keep"), func(e *TextInputEl) { e.Disabled = true }), + TextArea("area-off", AreaDisabled()), + Input("on"), + ), 80) + if len(fs) != 1 || fs[0].ID != "on" { + t.Fatalf("focus ring = %+v, want only the enabled input", fs) + } +} + +func TestFocusFollowsIDNotPosition(t *testing.T) { + m := newRingModel(func(m ringModel) Element { + btn := func(name string) Element { + return Button(name, func() Msg { return testMsg(name) }) + } + if m.state["hideB"] { + return Box(Column, btn("a"), btn("c")) + } + return Box(Column, btn("a"), btn("b"), btn("c")) + }) + a := newTrapAdapter(m) + a.View() + key(a, "tab") + key(a, "tab") + if got := a.focus.FocusedID(); got != "btn:b" { + t.Fatalf("focused %q, want btn:b", got) + } + m.state["hideB"] = true + a.View() + if got := a.focus.FocusedID(); got != "" { + t.Fatalf("focus slid onto %q after its control left the view, want none", got) + } + key(a, "enter") + if got := lastMsg(m); got == testMsg("c") { + t.Fatal("Enter activated the control that took the removed button's place") + } +} + +func TestIDlessControlsNeverLookFocused(t *testing.T) { + r := newTUIRenderer(40, 5, zone.New()) + r.Render(Box(Column, Input(""), Checkbox("", "box", false, nil))) + if st, ok := r.inputs[""]; ok && st.model.Focused() { + t.Error("an input without an ID is focused while nothing has focus") + } + if fs := collectFocusables(Checkbox("", "box", false, nil), 80); len(fs) != 0 { + t.Errorf("checkbox without an ID joined the ring: %+v", fs) + } +} + +func TestEnterUsesTheVisibleResponsiveVariant(t *testing.T) { + m := newRingModel(func(ringModel) Element { + return Responsive( + At(0, Input("q", WithOnSubmit(func(string) Msg { return testMsg("narrow") }))), + At(60, Input("q", WithOnSubmit(func(string) Msg { return testMsg("wide") }))), + ) + }) + a := newTrapAdapter(m) + a.View() + key(a, "tab") + key(a, "enter") + if got := lastMsg(m); got != testMsg("wide") { + t.Fatalf("Enter dispatched %v at width 80, want the visible (wide) variant's OnSubmit", got) + } +} + +func TestButtonsSharingALabelActivateThemselves(t *testing.T) { + m := newRingModel(func(ringModel) Element { + return Box(Column, + Button("Delete", func() Msg { return testMsg("first") }), + Button("Delete", func() Msg { return testMsg("second") }), + ) + }) + a := newTrapAdapter(m) + a.View() + key(a, "tab") + key(a, "tab") + if got := a.focus.FocusedID(); got != "btn:Delete#2" { + t.Fatalf("focused %q, want the second button's own key", got) + } + key(a, "enter") + if got := lastMsg(m); got != testMsg("second") { + t.Fatalf("Enter on the second Delete dispatched %v", got) + } +} + +func TestKeystrokeBuildsTheViewTwiceAtMost(t *testing.T) { + m := newRingModel(func(ringModel) Element { return Input("q") }) + a := newTrapAdapter(m) + a.View() + key(a, "tab") + *m.views = 0 + key(a, "x") + if *m.views > 2 { + t.Errorf("one keystroke built the view %d times, want at most 2 (route + render)", *m.views) + } +} + +func TestClickingSelectInFormCyclesWithoutSubmitting(t *testing.T) { + m := newRingModel(func(ringModel) Element { + return Form(func(map[string]string) Msg { return testMsg("submitted") }, + Select("sel", Options("a", "b"), "a", func(v string) Msg { return testMsg("sel=" + v) }), + ) + }) + a := newTrapAdapter(m) + a.View() + var z *zone.ZoneInfo + for i := 0; i < 100 && (z == nil || z.IsZero()); i++ { + time.Sleep(5 * time.Millisecond) + z = a.zones.Get("sel") + } + if z == nil || z.IsZero() { + t.Fatal("select zone never registered") + } + a.handleMouse(tea.MouseMsg{X: z.StartX, Y: z.StartY, Action: tea.MouseActionRelease, Button: tea.MouseButtonLeft}) + if got := lastMsg(m); got != testMsg("sel=b") { + t.Fatalf("click on a Select dispatched %v, want it to cycle to b", got) + } +} diff --git a/focus_tui.go b/focus_tui.go index b234caa..1caa851 100644 --- a/focus_tui.go +++ b/focus_tui.go @@ -2,52 +2,71 @@ package wui -// tuiFocusManager is an index-based focus ring over a list of -// focusable element IDs, used because the terminal has no native tab -// order. -// tuiFocusManager is an index-based focus ring over a list of -// focusable element IDs. cursor=-1 means nothing is focused yet; -// first Next() advances to 0. +// tuiFocusManager is the terminal's focus ring over the focusable +// element IDs of the current view, used because the terminal has no +// native tab order. Focus is held by ID, not position: when the view +// changes, focus stays on the same control wherever it moved, and is +// cleared when that control leaves the view rather than sliding onto +// whatever took its place. type tuiFocusManager struct { - ids []string - cursor int + ids []string + focused string } func newTUIFocusManager() *tuiFocusManager { - return &tuiFocusManager{cursor: -1} + return &tuiFocusManager{} } +// SetIDs replaces the ring with the current view's focusable IDs, +// clearing focus if the focused control is no longer among them. func (m *tuiFocusManager) SetIDs(ids []string) { m.ids = ids - if m.cursor >= len(ids) { - m.cursor = -1 + if m.focused != "" && m.index() < 0 { + m.focused = "" } } +// index returns the position of the focused ID in the ring, or -1. +func (m *tuiFocusManager) index() int { + if m.focused == "" { + return -1 + } + for i, id := range m.ids { + if id == m.focused { + return i + } + } + return -1 +} + +// Next moves focus to the following control, wrapping around; with +// nothing focused it moves to the first. func (m *tuiFocusManager) Next() { if len(m.ids) == 0 { return } - m.cursor = (m.cursor + 1) % len(m.ids) + m.focused = m.ids[(m.index()+1)%len(m.ids)] } +// Prev moves focus to the preceding control, wrapping around; with +// nothing focused it moves to the last. func (m *tuiFocusManager) Prev() { if len(m.ids) == 0 { return } - if m.cursor <= 0 { - m.cursor = len(m.ids) - 1 - } else { - m.cursor-- + i := m.index() + if i <= 0 { + i = len(m.ids) } + m.focused = m.ids[i-1] } -// Focus moves the cursor to the given ID, if present in the ring. +// Focus moves focus to the given ID, if present in the ring. // Unknown IDs leave focus unchanged. func (m *tuiFocusManager) Focus(id string) { - for i, v := range m.ids { + for _, v := range m.ids { if v == id { - m.cursor = i + m.focused = id return } } @@ -56,12 +75,11 @@ func (m *tuiFocusManager) Focus(id string) { // Blur clears focus entirely; the next Next() starts from the first // element again. func (m *tuiFocusManager) Blur() { - m.cursor = -1 + m.focused = "" } +// FocusedID returns the focused control's ID, or "" when nothing is +// focused. func (m *tuiFocusManager) FocusedID() string { - if len(m.ids) == 0 || m.cursor < 0 { - return "" - } - return m.ids[m.cursor] + return m.focused } diff --git a/program_tui.go b/program_tui.go index 9671e70..32776d4 100644 --- a/program_tui.go +++ b/program_tui.go @@ -217,6 +217,9 @@ func (a *teaAdapter) handleMouse(m tea.MouseMsg) (tea.Model, tea.Cmd) { if f.IsInput { return a, nil } + if f.Cycle != nil { + return a, a.apply(f.Cycle(1)) + } if f.Activate != nil { return a, a.apply(f.Activate()) } @@ -282,11 +285,11 @@ func (a *teaAdapter) routeKeyToFocused(focusedID string, focusables []focusable, return a.model, nil, false } - if area := findAreaByID(a.model.View(), focusedID); area != nil { - return a.routeKeyToArea(*area, m) + if target.Area != nil { + return a.routeKeyToArea(*target.Area, m) } - el := findInputByID(a.model.View(), focusedID) + el := target.Input if el == nil { return a.model, nil, false } @@ -376,7 +379,8 @@ func (a *teaAdapter) submitForm(form *FormEl) Msg { } func (a *teaAdapter) View() string { - a.focus.SetIDs(focusableIDs(collectFocusables(a.model.View(), a.renderer.Width))) + el := a.model.View() + a.focus.SetIDs(focusableIDs(collectFocusables(el, a.renderer.Width))) a.renderer.FocusedID = a.focus.FocusedID() // The bar is built before the body so Fill-height layouts know how // many rows remain for them. @@ -385,7 +389,7 @@ func (a *teaAdapter) View() string { if bar != "" { a.renderer.Reserved = 1 } - view := a.renderer.Render(a.model.View()) + view := a.renderer.Render(el) if bar != "" { view = a.withStatusBar(view, bar) } diff --git a/render_tui.go b/render_tui.go index 8fbf5f7..587e58f 100644 --- a/render_tui.go +++ b/render_tui.go @@ -3,6 +3,7 @@ package wui import ( + "fmt" "strconv" "strings" @@ -37,6 +38,10 @@ type tuiRenderer struct { // which case the terminal width applies. avail int + // buttonKeys numbers duplicate button focus keys during a render; + // see focusKeys. + buttonKeys focusKeys + inputs map[string]*tuiInputState areas map[string]*tuiAreaState zones *zone.Manager @@ -93,9 +98,33 @@ func newTUIRenderer(width, height int, zones *zone.Manager) *tuiRenderer { } func (r *tuiRenderer) Render(el Element) string { + r.buttonKeys = focusKeys{} return r.renderEl(el) } +// focusKeys makes button focus keys unique within one view. Buttons +// without an ID derive their key from the label, so two "Delete" +// buttons would share one; the second and later get "#2", "#3" +// suffixes. collectFocusables and the renderer both number buttons in +// tree order, so they agree on every key. +type focusKeys map[string]int + +// next returns the unique key for the next button whose derived key is +// base. +func (k focusKeys) next(base string) string { + k[base]++ + if n := k[base]; n > 1 { + return fmt.Sprintf("%s#%d", base, n) + } + return base +} + +// focusedOn reports whether the control with the given ID has focus. +// An empty ID never does: controls without IDs cannot join the ring. +func (r *tuiRenderer) focusedOn(id string) bool { + return id != "" && r.FocusedID == id +} + // focusable describes one element the Tab ring can land on. Inputs // are edited in place by routeKeyToFocused; buttons and links activate // via their Activate closure when Enter is pressed. Form points at the @@ -112,6 +141,11 @@ type focusable struct { // moving the selection by delta options, so arrow keys can step // through the list the way a browser dropdown does. Cycle func(delta int) Msg + + // Input and Area hold the element for text inputs and text areas, + // so key routing edits the control that is actually on screen. + Input *TextInputEl + Area *TextAreaEl } // collectFocusables walks the tree and returns focus-ring entries in @@ -120,25 +154,29 @@ type focusable struct { // visible controls join the ring. func collectFocusables(el Element, width int) []focusable { var out []focusable + keys := focusKeys{} var walk func(Element, *FormEl) walk = func(e Element, form *FormEl) { switch v := e.(type) { case TextInputEl: - if v.ID != "" { - out = append(out, focusable{ID: v.ID, IsInput: true, Form: form}) + if v.ID != "" && !v.Disabled { + in := v + out = append(out, focusable{ID: v.ID, IsInput: true, Form: form, Input: &in}) } case ButtonEl: + key := keys.next(buttonFocusKey(v)) if v.Disabled { return } if v.OnClick != nil { - out = append(out, focusable{ID: buttonFocusKey(v), Activate: v.OnClick, Form: form}) + out = append(out, focusable{ID: key, Activate: v.OnClick, Form: form}) } else if form != nil && form.OnSubmit != nil { - out = append(out, focusable{ID: buttonFocusKey(v), Form: form}) + out = append(out, focusable{ID: key, Form: form}) } case TextAreaEl: - if v.ID != "" { - out = append(out, focusable{ID: v.ID, IsInput: true, Form: form}) + if v.ID != "" && !v.Disabled { + area := v + out = append(out, focusable{ID: v.ID, IsInput: true, Form: form, Area: &area}) } case SelectEl: if v.Disabled || v.ID == "" { @@ -151,7 +189,7 @@ func collectFocusables(el Element, width int) []focusable { Cycle: func(delta int) Msg { return selectChangeMsg(sel, selectCycle(sel, delta)) }, }) case CheckboxEl: - if v.Disabled { + if v.Disabled || v.ID == "" { return } cb := v @@ -209,6 +247,8 @@ func (r *tuiRenderer) formValues(form FormEl) map[string]string { if v.ID != "" { values[v.ID] = v.Value } + case ResponsiveEl: + walk(v.pick(r.Width)) default: for _, c := range Children(e) { walk(c) @@ -229,30 +269,6 @@ func focusableIDs(items []focusable) []string { return ids } -func findInputByID(el Element, id string) *TextInputEl { - found, ok := Find(el, func(e Element) bool { - v, isInput := e.(TextInputEl) - return isInput && v.ID == id - }) - if !ok { - return nil - } - v := found.(TextInputEl) - return &v -} - -func findAreaByID(el Element, id string) *TextAreaEl { - found, ok := Find(el, func(e Element) bool { - v, isArea := e.(TextAreaEl) - return isArea && v.ID == id - }) - if !ok { - return nil - } - v := found.(TextAreaEl) - return &v -} - // ensureInput creates (if absent) and syncs placeholder/value for the // input with the given spec, returning the live bubbles model. The // value is re-synced only when the spec value differs from the spec @@ -428,7 +444,7 @@ func (r *tuiRenderer) renderSelect(e SelectEl) string { if e.Disabled { return style.Faint(true).Render(label) } - if r.FocusedID == e.ID { + if r.focusedOn(e.ID) { style = style.Reverse(true) } out := style.Render(label) @@ -447,7 +463,7 @@ func (r *tuiRenderer) renderTextArea(e TextAreaEl) string { rows = 4 } value := r.ensureArea(e) - focused := r.FocusedID == e.ID + focused := r.focusedOn(e.ID) body := value faint := false @@ -901,21 +917,25 @@ func alignToPosition(a Align) lipgloss.Position { } func (r *tuiRenderer) renderButton(e ButtonEl) string { + if r.buttonKeys == nil { + r.buttonKeys = focusKeys{} + } + key := r.buttonKeys.next(buttonFocusKey(e)) label := "[ " + e.Label + " ]" style := styleToLipgloss(e.Style) if e.Disabled { style = style.Faint(true) return style.Render(label) } - if r.FocusedID == buttonFocusKey(e) { + if r.focusedOn(key) { style = style.Reverse(true) } - return r.zones.Mark(buttonFocusKey(e), style.Render(label)) + return r.zones.Mark(key, style.Render(label)) } func (r *tuiRenderer) renderTextInput(e TextInputEl) string { in := r.ensureInput(e) - focused := r.FocusedID == e.ID + focused := r.focusedOn(e.ID) if focused && !in.Focused() { in.Focus() } else if !focused && in.Focused() { @@ -942,7 +962,7 @@ func (r *tuiRenderer) renderCheckbox(e CheckboxEl) string { if e.Disabled { return style.Faint(true).Render(label) } - if r.FocusedID == e.ID { + if r.focusedOn(e.ID) { style = style.Reverse(true) } return r.zones.Mark(e.ID, style.Render(label)) diff --git a/render_tui_new_test.go b/render_tui_new_test.go index d6da0d5..3d89252 100644 --- a/render_tui_new_test.go +++ b/render_tui_new_test.go @@ -214,30 +214,3 @@ func TestBuildStatusKeepsWebLinkAlongsideCustomSegments(t *testing.T) { t.Errorf("hidden status = %+v, want no items", hidden) } } - -func TestFindInputAndAreaByID(t *testing.T) { - tree := Box(Column, - Card("c", Input("name", WithValue("v"))), - Scroll(TextArea("bio", WithAreaValue("hello")), 5), - ) - - in := findInputByID(tree, "name") - if in == nil || in.Value != "v" { - t.Errorf("findInputByID = %+v, want the nested input", in) - } - if findInputByID(tree, "missing") != nil { - t.Error("findInputByID found a nonexistent input") - } - - area := findAreaByID(tree, "bio") - if area == nil || area.Value != "hello" { - t.Errorf("findAreaByID = %+v, want the nested textarea", area) - } - // A TextArea must not be mistaken for a TextInput and vice versa. - if findInputByID(tree, "bio") != nil { - t.Error("findInputByID matched a TextAreaEl") - } - if findAreaByID(tree, "name") != nil { - t.Error("findAreaByID matched a TextInputEl") - } -} diff --git a/render_tui_test.go b/render_tui_test.go index cd07056..02563f8 100644 --- a/render_tui_test.go +++ b/render_tui_test.go @@ -122,7 +122,7 @@ func TestCardChildrenReachableByWalkers(t *testing.T) { if len(fs) != 2 { t.Fatalf("focusables inside Card not collected: got %d, want 2", len(fs)) } - if findInputByID(tree, "name") == nil { - t.Error("findInputByID does not descend into Card") + if fs[0].Input == nil || fs[0].Input.ID != "name" { + t.Errorf("focusable for the input does not carry the element: %+v", fs[0]) } }