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
177 changes: 177 additions & 0 deletions focus_ring_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
66 changes: 42 additions & 24 deletions focus_tui.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand All @@ -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
}
14 changes: 9 additions & 5 deletions program_tui.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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.
Expand All @@ -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)
}
Expand Down
Loading
Loading