From 7e8d219d73a074b86704807bcf1b9dd59e1e22af Mon Sep 17 00:00:00 2001 From: Matt Edmonston Date: Sat, 28 Nov 2026 07:04:46 +0000 Subject: [PATCH] Fix TUI sizing: borders, input width, wrapping, wide runes - Style Width and Height include the border, as in the browser: a bordered Width 20 Box or Text is 20 cells, and a bordered Fill box no longer overflows the terminal. Box inner sizes subtract the border. - An Input with Style.Width scrolls its value within the width instead of wrapping onto extra rows. - TextArea wraps long lines before clipping to Rows, so it keeps its height. - A Card title longer than Style.Width is truncated instead of widening the card. - An unsized Divider spans its pane, not the terminal, so it no longer breaks Split and Sidebar rows. - A wrapping Row that collapses re-renders its children at the column width, so Responsive content picks the variant for the space it has. - The status bar and divider labels measure and truncate by display cells, so wide glyphs no longer push the frame past the terminal. Closes #27 --- go.mod | 2 +- render_tui.go | 65 ++++++++++++++++++++++++++++++++--------- sizing_test.go | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++ status.go | 26 ++++++++++------- 4 files changed, 147 insertions(+), 25 deletions(-) create mode 100644 sizing_test.go diff --git a/go.mod b/go.mod index 1a75ddd..7cc716a 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/charmbracelet/bubbles v1.0.0 github.com/charmbracelet/bubbletea v1.3.10 github.com/charmbracelet/lipgloss v1.1.0 + github.com/charmbracelet/x/ansi v0.11.6 github.com/lrstanley/bubblezone v1.0.0 ) @@ -13,7 +14,6 @@ require ( github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/charmbracelet/colorprofile v0.4.1 // indirect - github.com/charmbracelet/x/ansi v0.11.6 // indirect github.com/charmbracelet/x/cellbuf v0.0.15 // indirect github.com/charmbracelet/x/term v0.2.2 // indirect github.com/clipperhouse/displaywidth v0.9.0 // indirect diff --git a/render_tui.go b/render_tui.go index 354bc8e..1c09b39 100644 --- a/render_tui.go +++ b/render_tui.go @@ -10,6 +10,7 @@ import ( "github.com/charmbracelet/bubbles/textinput" "github.com/charmbracelet/lipgloss" ltable "github.com/charmbracelet/lipgloss/table" + "github.com/charmbracelet/x/ansi" zone "github.com/lrstanley/bubblezone" ) @@ -131,6 +132,16 @@ func (r *tuiRenderer) Render(el Element) string { // tree order, so they agree on every key. type focusKeys map[string]int +// clone copies k, so a subtree rendered twice can number its buttons +// from the same starting point both times. +func (k focusKeys) clone() focusKeys { + c := make(focusKeys, len(k)) + for key, n := range k { + c[key] = n + } + return c +} + // next returns the unique key for the next button whose derived key is // base. func (k focusKeys) next(base string) string { @@ -401,7 +412,7 @@ func (r *tuiRenderer) renderSpacer(e SpacerEl) string { func (r *tuiRenderer) renderDivider(e DividerEl) string { width := e.Style.Width if width <= 0 { - width = r.Width + width = r.availWidth() } if width < 2 { width = 2 @@ -500,7 +511,12 @@ func (r *tuiRenderer) renderTextArea(e TextAreaEl) string { body += "▏" } - lines := strings.Split(body, "\n") + width := e.Style.Width + if width <= 0 { + width = 40 + } + contentW := max(width-e.Style.Padding[1]-e.Style.Padding[3]-borderCells(e.Style), 1) + lines := strings.Split(ansi.Wrap(body, contentW, ""), "\n") for len(lines) < rows { lines = append(lines, "") } @@ -514,15 +530,11 @@ func (r *tuiRenderer) renderTextArea(e TextAreaEl) string { inner = lipgloss.NewStyle().Faint(true).Render(inner) } - width := e.Style.Width - if width <= 0 { - width = 40 - } // Border is opt-in via Style, like every other element — a // TextArea inside a Card must not draw a second frame inside the // card's. Focus is shown by tinting whichever frame exists, or by // the cursor alone when there is none. - box := styleToLipgloss(e.Style).Width(width).Height(rows) + box := styleToLipgloss(e.Style).Width(width - borderCells(e.Style)).Height(rows) if e.Disabled { box = box.Faint(true) } else if focused && e.Style.Border { @@ -618,7 +630,7 @@ func (r *tuiRenderer) renderBox(e BoxEl) string { innerW := width if innerW > 0 { - innerW -= e.Style.Padding[1] + e.Style.Padding[3] + innerW -= e.Style.Padding[1] + e.Style.Padding[3] + borderCells(e.Style) } // Children see the width this Box makes available to them: the @@ -628,12 +640,13 @@ func (r *tuiRenderer) renderBox(e BoxEl) string { // the row, not a share of it. childAvail := innerW if childAvail <= 0 { - childAvail = r.availWidth() - e.Style.Padding[1] - e.Style.Padding[3] + childAvail = r.availWidth() - e.Style.Padding[1] - e.Style.Padding[3] - borderCells(e.Style) } shareAvail := childAvail if shareAvail > 0 && e.Direction == Row && len(e.Children) > 1 { shareAvail = (shareAvail - e.Gap*(len(e.Children)-1)) / len(e.Children) } + keysBefore := r.buttonKeys.clone() parts := make([]string, 0, len(e.Children)) for _, c := range e.Children { w := shareAvail @@ -644,7 +657,7 @@ func (r *tuiRenderer) renderBox(e BoxEl) string { } innerH := height if innerH > 0 { - innerH -= e.Style.Padding[0] + e.Style.Padding[2] + innerH -= e.Style.Padding[0] + e.Style.Padding[2] + borderCells(e.Style) } dir := e.Direction @@ -653,7 +666,9 @@ func (r *tuiRenderer) renderBox(e BoxEl) string { // vertical stack, the TUI's flex-wrap. Growing children take // the full width so the collapsed panes stay aligned. dir = Column + r.buttonKeys = keysBefore for i, c := range e.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]) } @@ -667,7 +682,7 @@ func (r *tuiRenderer) renderBox(e BoxEl) string { // terminal. distW := innerW if distW <= 0 { - distW = r.availWidth() - e.Style.Padding[1] - e.Style.Padding[3] + distW = r.availWidth() - e.Style.Padding[1] - e.Style.Padding[3] - borderCells(e.Style) } distributeRow(e.Children, parts, e.Gap, distW) if e.Align == AlignStretch && innerH > 0 { @@ -969,6 +984,14 @@ func (r *tuiRenderer) renderTextInput(e TextInputEl) string { } else if !focused && in.Focused() { in.Blur() } + if e.Style.Width > 0 { + if w := max(e.Style.Width-e.Style.Padding[1]-e.Style.Padding[3]-borderCells(e.Style)-1, 1); in.Width != w { + in.Width = w + // The visible window is recomputed only when the cursor + // moves, so a new width needs a cursor update to apply. + in.SetCursor(in.Position()) + } + } style := styleToLipgloss(e.Style) out := style.Render(in.View()) if e.ID != "" { @@ -1023,7 +1046,11 @@ func (r *tuiRenderer) renderCard(e CardEl) string { title := "" if e.Title != "" { - title = lipgloss.NewStyle().Bold(true).Render(" " + e.Title + " ") + text := " " + e.Title + " " + if e.Style.Width > 5 { + text = truncate(text, e.Style.Width-4) + } + title = lipgloss.NewStyle().Bold(true).Render(text) } tw := lipgloss.Width(title) w := lipgloss.Width(inner) @@ -1125,11 +1152,11 @@ func styleToLipgloss(s Style) lipgloss.Style { ls = ls.Strikethrough(true) } if s.Width > 0 { - ls = ls.Width(s.Width) + ls = ls.Width(max(s.Width-borderCells(s), 0)) ls = ls.Align(alignToPosition(s.Align)) } if s.Height > 0 { - ls = ls.Height(s.Height) + ls = ls.Height(max(s.Height-borderCells(s), 0)) } ls = ls.Padding(s.Padding[0], s.Padding[1], s.Padding[2], s.Padding[3]) ls = ls.Margin(s.Margin[0], s.Margin[1], s.Margin[2], s.Margin[3]) @@ -1142,6 +1169,16 @@ func styleToLipgloss(s Style) lipgloss.Style { return ls } +// borderCells is how many cells a style's border adds across each +// axis. Width and Height include the border, as in the browser, while +// lipgloss draws it outside the size it is given. +func borderCells(s Style) int { + if s.Border { + return 2 + } + return 0 +} + func resolveColor(c Color) string { if idx, err := strconv.Atoi(string(c)); err == nil && idx >= 0 && idx < 16 { return ansiPalette[idx] diff --git a/sizing_test.go b/sizing_test.go new file mode 100644 index 0000000..6d3c538 --- /dev/null +++ b/sizing_test.go @@ -0,0 +1,79 @@ +//go:build !js + +package wui + +import ( + "strings" + "testing" + + "github.com/charmbracelet/lipgloss" +) + +func dims(s string) (w, h int) { + return lipgloss.Width(s), lipgloss.Height(s) +} + +func TestBorderedSizesIncludeTheBorder(t *testing.T) { + box := BoxStyled(Column, 0, Style{Width: 20, Height: 5, Border: true}, Text("hi")) + if w, h := dims(RenderTUISized(box, 80, 24)); w != 20 || h != 5 { + t.Errorf("bordered 20x5 box rendered %dx%d", w, h) + } + text := Text("hi", WithTextStyle(NewStyle().W(10).Bordered(""))) + if w, _ := dims(RenderTUISized(text, 80, 24)); w != 10 { + t.Errorf("bordered Width:10 text rendered %d wide", w) + } + fill := BoxStyled(Column, 0, Style{Width: Fill, Border: true}, Text("hi")) + if w, _ := dims(RenderTUISized(fill, 40, 10)); w != 40 { + t.Errorf("bordered Fill box rendered %d wide in a 40-cell terminal", w) + } + area := TextArea("a", WithAreaRows(2), WithAreaStyle(NewStyle().W(30).Bordered(""))) + if w, h := dims(RenderTUISized(area, 80, 24)); w != 30 || h != 4 { + t.Errorf("bordered 30-wide 2-row TextArea rendered %dx%d, want 30x4", w, h) + } +} + +func TestInputWithWidthScrollsInsteadOfWrapping(t *testing.T) { + in := Input("i", WithValue("abcdefghijklmnopqrstuvwxyz"), func(e *TextInputEl) { e.Style = NewStyle().W(10) }) + if w, h := dims(RenderTUISized(in, 80, 24)); h != 1 || w != 10 { + t.Errorf("Width:10 input rendered %dx%d, want 10x1", w, h) + } +} + +func TestTextAreaRowsCountWrappedLines(t *testing.T) { + area := TextArea("a", WithAreaRows(2), WithAreaValue(strings.Repeat("x", 26)), WithAreaStyle(NewStyle().W(10))) + if _, h := dims(RenderTUISized(area, 80, 24)); h != 2 { + t.Errorf("2-row TextArea with a long line rendered %d rows", h) + } +} + +func TestLongCardTitleKeepsCardWidth(t *testing.T) { + card := Card("A very long card title here", Text("x"), WithCardStyle(NewStyle().W(16))) + if w, _ := dims(RenderTUISized(card, 80, 24)); w != 16 { + t.Errorf("Width:16 card with a long title rendered %d wide", w) + } +} + +func TestDividerFitsItsPane(t *testing.T) { + out := RenderTUISized(Split(Divider("x"), Text("y")), 60, 3) + if _, h := dims(out); h != 1 { + t.Errorf("Split of a divider and text took %d rows, want 1:\n%s", h, out) + } +} + +func TestCollapsedRowRendersChildrenAtFullWidth(t *testing.T) { + el := Sidebar(Text("side"), Responsive(At(0, Text("NARROW")), At(50, Text("WIDE")))) + out := RenderTUISized(el, 60, 10) + if !strings.Contains(out, "WIDE") || strings.Contains(out, "NARROW") { + t.Errorf("collapsed sidebar at 60 cols should give the main pane the full width:\n%s", out) + } +} + +func TestStatusLineMeasuresCells(t *testing.T) { + line := plainStatusLine(NewStatus().Left("界界界界界界界界界界").Right("help"), 20) + if w := lipgloss.Width(line); w > 20 { + t.Errorf("status line is %d cells for width 20: %q", w, line) + } + if got := truncate("界界界", 5); lipgloss.Width(got) > 5 { + t.Errorf("truncate to 5 cells gave %q (%d cells)", got, lipgloss.Width(got)) + } +} diff --git a/status.go b/status.go index a448811..ab63b33 100644 --- a/status.go +++ b/status.go @@ -1,6 +1,10 @@ package wui -import "strings" +import ( + "strings" + + "github.com/charmbracelet/x/ansi" +) // StatusItem is one segment of the status line. type StatusItem struct { @@ -193,7 +197,7 @@ func plainStatusLine(s Status, width int) string { if inner < 1 { inner = 1 } - lw, rw := runeLen(l), runeLen(r) + lw, rw := ansi.StringWidth(l), ansi.StringWidth(r) if lw+rw+1 > inner { // Not enough room for both: the right side is supplementary // (help text), so drop it before truncating the left. @@ -206,16 +210,18 @@ func plainStatusLine(s Status, width int) string { return " " + l + strings.Repeat(" ", pad) + r + " " } -func runeLen(s string) int { return len([]rune(s)) } - -// truncate shortens s to n runes, marking the cut with an ellipsis. +// truncate shortens s to at most n terminal cells, marking the cut +// with an ellipsis. It measures display width, so wide glyphs (CJK, +// emoji) count as the two cells they occupy. func truncate(s string, n int) string { - r := []rune(s) - if len(r) <= n { + if n <= 0 { + return "" + } + if ansi.StringWidth(s) <= n { return s } - if n <= 1 { - return string(r[:n]) + if n == 1 { + return ansi.Truncate(s, 1, "") } - return string(r[:n-1]) + "…" + return ansi.Truncate(s, n, "…") }