diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 9a4c67b..adef17f 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -269,3 +269,13 @@ the same exception the root AGENTS.md makes for `paths/knownfolders_windows.go`. Everything above the window (`assets`, `document`, `bridge`) is platform-free and unit-tested on any host; browser behavior is verified by the prototype's in-window selftest. + +## core/tui: only what is already identical + +`tui/` is a nested module for the same reason as `gui/` (Charm stays out +of the main module's graph). It holds only code that at least two +programs carried byte-identically (themes, styles, paint/outer, list +state, text helpers), not a framework: the app frame, menus and screens +differ per program and move here only once two programs share them. The +long-term `core/ui` (UI-neutral model) / `core/tui` / `core/gui` split of +`docs/yetano-ui/` can grow from this without breaking it. diff --git a/README.md b/README.md index f041845..8a9c904 100644 --- a/README.md +++ b/README.md @@ -13,10 +13,11 @@ every Yetano program offers (`core/manual`, `core/completion`, docs/program-conventions.md in the meta-repository), and secret references in configuration (`core/secretref`). -The native WebView GUI host is a **separate, nested module**, -`yetano.dev/yetano/core/gui` (tags `gui/vX.Y.Z`), so this module keeps -its single dependency and stays free of cgo -- see -[gui/README.md](gui/README.md). +Two **separate, nested modules** keep this module at its single +dependency: the native WebView GUI host `yetano.dev/yetano/core/gui` +(tags `gui/vX.Y.Z`, cgo, see [gui/README.md](gui/README.md)) and the +shared terminal-UI kernel `yetano.dev/yetano/core/tui` (tags +`tui/vX.Y.Z`, Charm lipgloss v2, see [tui/README.md](tui/README.md)). ```text yetano.dev/yetano/core @@ -34,6 +35,7 @@ yetano.dev/yetano/core/gui/assets yetano.dev/yetano/core/gui/document yetano.dev/yetano/core/gui/bridge yetano.dev/yetano/core/gui/window +yetano.dev/yetano/core/tui (own module, tags tui/vX.Y.Z) ``` Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions @@ -360,9 +362,9 @@ one-line form for log lines and web UI footers. Tagged as plain semver on this repository (`v0.1.0`, ...), per the meta-repo `AGENTS.md`'s versioning rules: an existing tag is never -force-moved to a different commit. The nested `gui` module has its own -prefixed tags (`gui/v0.1.0`, ...); a change there needs no main-module -tag and vice versa. +force-moved to a different commit. The nested `gui` and `tui` modules +have their own prefixed tags (`gui/v0.1.0`, `tui/v0.1.0`, ...); a change +there needs no main-module tag and vice versa. ## core/secretref @@ -397,3 +399,11 @@ streaming, abort and reload handling -- never a local HTTP listener or port. Packages `assets`, `document`, `bridge`, `window`; extracted from `prototypes/yetano-webview` (AP1). Details, invariants, measured platform pitfalls and the yet-gui migration: [gui/README.md](gui/README.md). + +## core/tui (separate module) + +`yetano.dev/yetano/core/tui` is the kernel the Charm-v2 terminal UIs +(yet, yavebu, yalsh menuconfig) had as hand-kept copies: the themes +`slate`/`dialog`/`midnight` and their lipgloss styles, `Paint`/`Outer`, +`ListState` and text helpers. No app shell or screens yet -- see +[tui/README.md](tui/README.md), which also has the migration steps. diff --git a/TODO.md b/TODO.md index d9332ac..5948349 100644 --- a/TODO.md +++ b/TODO.md @@ -39,6 +39,12 @@ speculatively. - [ ] Move yet-gui off its copy in `yet/gui/internal` onto `core/gui` (steps in [gui/README.md](gui/README.md)). - [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md. +- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer, + ListState, text helpers) as the nested module + `yetano.dev/yetano/core/tui` (`tui/v0.1.0`). +- [ ] Move yet's and yavebu's `internal/tui` onto `core/tui` (steps in + [tui/README.md](tui/README.md)); yalsh menuconfig after an owner + decision on `yalsh.dev` -> `yetano.dev` imports. ## Platform tuning diff --git a/tui/README.md b/tui/README.md new file mode 100644 index 0000000..6d96636 --- /dev/null +++ b/tui/README.md @@ -0,0 +1,79 @@ +# yetano.dev/yetano/core/tui + +The shared kernel of the Yetano terminal UIs, on Charm v2 +(`charm.land/lipgloss/v2`). It is the code that yet's TUI +(`yet/internal/tui`), yavebu's TUI (`yavebu/internal/tui`) and yalsh's +menuconfig (`yalsh/cli/internal/menuconfig`) each carried as a hand-kept +copy -- and that had already started to drift (yavebu's slate theme kept +two blue-tinted greys that render dark blue without truecolor; yet and +yavebu kept an older, truecolor-only `paint`). + +```text +module yetano.dev/yetano/core/tui tags: tui/v0.1.0, ... go 1.25 +``` + +A nested module of the core repository, like `core/gui`, so the main core +module stays free of Charm. Depends only on lipgloss v2 (and +`colorprofile` in tests); no bubbletea, no bubbles. + +```sh +GOPRIVATE=teruna.dev,yetano.dev,yalsh.dev go get yetano.dev/yetano/core/tui@tui/v0.1.0 +``` + +## API + +| | | +|---|---| +| `Theme`, `ThemeByName(name)`, `ThemeNames`, `ValidTheme`, `NormalizeThemeName`, `NextThemeName` | the three themes `slate` (default), `dialog`, `midnight`; F2 cycles them | +| `Theme.Styles() Styles` | the 21 lipgloss styles (Root, Header, Info, Panel, PanelAlt, ListItem, ListSelected, Search, Footer, Key, Value, ...) | +| `Paint(block, fg, bg, width)` | re-grounds a pre-styled block on its area's colors after every SGR reset and pads each line (menuconfig's profile-aware version) | +| `Outer(style, w, h)` | sizes a style so the rendered block, border and padding included, is exactly w x h | +| `ListState{Filtered, Cursor, Scroll}` with `Rebuild`, `Move`, `ClampScroll`, `Index` | filtered list with cursor and scroll window | +| `Truncate`, `TruncateBlock`, `WrapStyled`, `KeyValue`, `FirstNonEmpty` | text helpers; `Truncate` counts runes, not cells (unchanged behavior) | + +The values are byte-identical to yet's `theme.go` (= menuconfig's). The +exported names are the former unexported ones capitalized; `listState` +fields are exported (`filtered` -> `Filtered`, ...). + +## Not in the kernel (yet) + +- The app frame (`render()`: header, info bar, list + detail, search, + footer): yet, yavebu and menuconfig share the structure, not the code + (minimum sizes, width ratios, stacking differ). A `Frame` helper is the + natural next step once a third v2 program needs it. +- Menus/dialogs, task logs, terminal hand-over (`tea.Exec`), yet's + Markdown renderer and manual view: each exists in one program only. +- Standard screens for `manual`/`doctor`/`version`: only yet has a manual + view; it belongs here once a second program wants it (it would build on + the JSON form of `core/manual`). +- yamc (Charm v1, its own Midnight-Commander palette and layout) and yaki + (no TUI yet) are not consumers. + +## Migration (per program, when it is next touched) + +**yet** (`internal/tui`): + +1. `go get yetano.dev/yetano/core/tui@tui/v0.1.0`. +2. Delete `theme.go` (keep the package comment elsewhere), `list.go`, + `paint`/`outer`/`truncate`/`truncateBlock`/`wrapStyled`/`keyValue`/ + `firstNonEmpty` in `view.go`, `ThemeNames`/`ValidTheme` in `app.go` + (re-export `ThemeNames = coretui.ThemeNames` if the CLI uses it). +3. Rename call sites: `themeByName` -> `coretui.ThemeByName`, + `theme.styles()` -> `theme.Styles()`, `paint` -> `coretui.Paint`, + `listState` -> `coretui.ListState` (`.filtered/.cursor/.scroll` -> + `.Filtered/.Cursor/.Scroll`, methods capitalized), and so on. +4. Move `theme_test.go` away (it lives here now). `go test ./...`, then + look at `yet tui` in Apple Terminal (no truecolor) and a truecolor + terminal. `Paint` now emits lipgloss's own sequence, which Bubble Tea + downsamples -- the visible change is that slate stays grey on + 256-color terminals. + +**yavebu** (`internal/tui`): same steps for `theme.go`, `util.go` +(`listState`, `paint`, `outer`, `truncate*`, `wrapStyled`, `keyValue`, +`firstNonEmpty`) and `ThemeNames`/`ValidTheme` in `tui.go`. Intended +visible change: slate `Panel` `#2A2D33` -> `#2A2A2E` and `SelectedText` +`#202734` -> `#20242B` (the grey fix yet already has). + +**yalsh menuconfig**: identical code; whether a `yalsh.dev` program +imports a `yetano.dev` module is an owner decision -- until then it stays +a copy. diff --git a/tui/go.mod b/tui/go.mod new file mode 100644 index 0000000..060c899 --- /dev/null +++ b/tui/go.mod @@ -0,0 +1,25 @@ +module yetano.dev/yetano/core/tui + +go 1.25.0 + +require ( + charm.land/lipgloss/v2 v2.0.6 + github.com/charmbracelet/colorprofile v0.4.3 +) + +require ( + github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect + github.com/charmbracelet/x/ansi v0.11.8 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/charmbracelet/x/termios v0.1.1 // indirect + github.com/charmbracelet/x/windows v0.2.2 // indirect + github.com/clipperhouse/displaywidth v0.11.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/lucasb-eyer/go-colorful v1.4.1 // indirect + github.com/mattn/go-runewidth v0.0.24 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/sys v0.47.0 // indirect +) diff --git a/tui/go.sum b/tui/go.sum new file mode 100644 index 0000000..fca9edd --- /dev/null +++ b/tui/go.sum @@ -0,0 +1,34 @@ +charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ= +charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q= +github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= +github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 h1:rdnVWKgJpTVXKuKuJyxDJ+NFJdUaUqGvyGy61OcvlbA= +github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886/go.mod h1:nAw0d9PhFp1qdzi2xhQU5YOu5sVpDIHWlaW2Uz/bCro= +github.com/charmbracelet/x/ansi v0.11.8 h1:JMFwp0CgDC2+jcOB162HH5k7I3FVbgFSMMYg7dSPBQQ= +github.com/charmbracelet/x/ansi v0.11.8/go.mod h1:ZNN+3mXny/516oTQPLMPIBeSINvNJJQ8uQXDgbeJxY0= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= +github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= +github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM= +github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k= +github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= +github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= +github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU= +github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= diff --git a/tui/list.go b/tui/list.go new file mode 100644 index 0000000..8e276af --- /dev/null +++ b/tui/list.go @@ -0,0 +1,54 @@ +package tui + +// ListState is the filtered/cursor/scroll state of a list view: Filtered +// holds indexes into the view's own item slice. +type ListState struct { + Filtered []int + Cursor int + Scroll int +} + +// Rebuild filters the n items with match and keeps the cursor in range. +func (l *ListState) Rebuild(n int, match func(i int) bool) { + l.Filtered = l.Filtered[:0] + for i := 0; i < n; i++ { + if match(i) { + l.Filtered = append(l.Filtered, i) + } + } + if l.Cursor >= len(l.Filtered) { + l.Cursor = max(0, len(l.Filtered)-1) + } +} + +// Move moves the cursor by delta, clamped to the filtered items. +func (l *ListState) Move(delta int) { + l.Cursor += delta + if l.Cursor >= len(l.Filtered) { + l.Cursor = len(l.Filtered) - 1 + } + if l.Cursor < 0 { + l.Cursor = 0 + } +} + +// ClampScroll scrolls so the cursor is visible in a window of rows lines. +func (l *ListState) ClampScroll(rows int) { + if l.Cursor < l.Scroll { + l.Scroll = l.Cursor + } + if l.Cursor >= l.Scroll+rows { + l.Scroll = l.Cursor - rows + 1 + } + if l.Scroll < 0 { + l.Scroll = 0 + } +} + +// Index is the item index under the cursor, or -1. +func (l ListState) Index() int { + if l.Cursor < 0 || l.Cursor >= len(l.Filtered) { + return -1 + } + return l.Filtered[l.Cursor] +} diff --git a/tui/paint.go b/tui/paint.go new file mode 100644 index 0000000..d416620 --- /dev/null +++ b/tui/paint.go @@ -0,0 +1,49 @@ +package tui + +import ( + "image/color" + "strings" + + "charm.land/lipgloss/v2" +) + +// Paint grounds a pre-styled block on its area's colors: lipgloss ends +// every styled segment with a full SGR reset, which also drops the +// enclosing area's background and foreground, so the rest of that line +// (JoinVertical/Width padding, the gap between panels, unstyled borders, +// plain text after a styled label) would fall back to the terminal's own +// colors -- black background, and white or bold-yellow text that is +// unreadable on a light header. Paint re-applies fg/bg after every reset +// and pads each line to width with them. The sequence comes from lipgloss +// itself; Bubble Tea downsamples it to the terminal's color profile. +// +// This is menuconfig's version; yet's and yavebu's copies hard-coded a +// truecolor sequence instead. +func Paint(block string, fg, bg color.Color, width int) string { + set, _, _ := strings.Cut(lipgloss.NewStyle().Foreground(fg).Background(bg).Render("x"), "x") + lines := strings.Split(block, "\n") + for i, line := range lines { + if set != "" { + line = strings.ReplaceAll(line, "\x1b[0m", "\x1b[m") + line = strings.ReplaceAll(line, "\x1b[m", "\x1b[m"+set) + } + if pad := width - lipgloss.Width(line); pad > 0 { + line += strings.Repeat(" ", pad) + } + if set != "" { + line = set + line + "\x1b[m" + } + lines[i] = line + } + return strings.Join(lines, "\n") +} + +// Outer sizes style so its rendered block, border and padding included, +// is exactly width x height cells (height 0: natural height). +func Outer(style lipgloss.Style, width, height int) lipgloss.Style { + style = style.Width(width).MaxWidth(width) + if height > 0 { + style = style.Height(height).MaxHeight(height) + } + return style +} diff --git a/tui/text.go b/tui/text.go new file mode 100644 index 0000000..5470d54 --- /dev/null +++ b/tui/text.go @@ -0,0 +1,66 @@ +package tui + +import ( + "strings" + + "charm.land/lipgloss/v2" +) + +// Truncate cuts text to width with a trailing "..." (width > 3). +// It counts runes, not terminal cells: wide (CJK, emoji) characters can +// still overflow -- the behavior the programs had; a cell-aware version +// would be a deliberate, tested change. +func Truncate(text string, width int) string { + if width <= 0 { + return "" + } + runes := []rune(text) + if len(runes) <= width { + return text + } + if width <= 3 { + return string(runes[:width]) + } + return string(runes[:width-3]) + "..." +} + +// TruncateBlock truncates every line of text to width. +func TruncateBlock(text string, width int) string { + lines := strings.Split(text, "\n") + for i, line := range lines { + lines[i] = Truncate(line, width) + } + return strings.Join(lines, "\n") +} + +// WrapStyled wraps text to width and renders each line with style. +func WrapStyled(text string, width int, style lipgloss.Style) []string { + if strings.TrimSpace(text) == "" { + return []string{style.Render("")} + } + wrapped := lipgloss.NewStyle().Width(width).Render(text) + lines := strings.Split(wrapped, "\n") + for i, line := range lines { + lines[i] = style.Render(line) + } + return lines +} + +// KeyValue returns a renderer for "key: value" lines of at most width +// cells, the value truncated. +func KeyValue(width int, styles Styles) func(k, v string) string { + return func(k, v string) string { + label := k + ": " + return styles.Key.Render(label) + styles.Value.Render(Truncate(v, width-lipgloss.Width(label))) + } +} + +// FirstNonEmpty returns the first non-empty value, or "". +func FirstNonEmpty(values ...string) string { + for _, v := range values { + if v != "" { + return v + } + } + return "" +} diff --git a/tui/theme.go b/tui/theme.go new file mode 100644 index 0000000..ed038bb --- /dev/null +++ b/tui/theme.go @@ -0,0 +1,237 @@ +// Package tui is the shared kernel of the Yetano terminal UIs (Charm v2): +// the three color themes and their lipgloss styles, the paint/outer layout +// helpers, the filtered list state and the text helpers that yet's TUI, +// yavebu's TUI and yalsh's menuconfig each carried as a hand-kept copy. +// It deliberately holds no app shell, menus or screens -- those still +// differ per program (see README.md). +package tui + +import ( + "image/color" + + "charm.land/lipgloss/v2" +) + +// Theme is one color scheme; every surface of a Yetano TUI takes its colors +// from these roles. +type Theme struct { + Name string + Background color.Color + Panel color.Color + PanelAlt color.Color + PanelBorder color.Color + Text color.Color + Muted color.Color + Accent color.Color + AccentText color.Color + Selected color.Color + SelectedText color.Color + Success color.Color + Warning color.Color +} + +// Styles are the lipgloss styles derived from a Theme. +type Styles struct { + Root lipgloss.Style + Header lipgloss.Style + HeaderTitle lipgloss.Style + HeaderMeta lipgloss.Style + Info lipgloss.Style + Panel lipgloss.Style + PanelAlt lipgloss.Style + PanelTitle lipgloss.Style + ListItem lipgloss.Style + ListEnabled lipgloss.Style + ListSelected lipgloss.Style + Search lipgloss.Style + SearchLabel lipgloss.Style + SearchInput lipgloss.Style + Footer lipgloss.Style + Key lipgloss.Style + Value lipgloss.Style + Text lipgloss.Style + Subtle lipgloss.Style + Warning lipgloss.Style + Empty lipgloss.Style +} + +// NormalizeThemeName maps "" and "default" (and anything unknown) to +// "slate"; known names stay. +func NormalizeThemeName(name string) string { + switch name { + case "", "default": + return "slate" + case "slate", "dialog", "midnight": + return name + default: + return "slate" + } +} + +// NextThemeName is the theme after current in the cycle slate -> dialog -> +// midnight -> slate (the F2 key). +func NextThemeName(current string) string { + switch NormalizeThemeName(current) { + case "slate": + return "dialog" + case "dialog": + return "midnight" + default: + return "slate" + } +} + +// ThemeByName returns the named theme (see NormalizeThemeName). +func ThemeByName(name string) Theme { + switch NormalizeThemeName(name) { + case "dialog": + return Theme{ + Name: "dialog", + Background: lipgloss.Color("#1B2D70"), + Panel: lipgloss.Color("#3552A5"), + PanelAlt: lipgloss.Color("#2E4A95"), + PanelBorder: lipgloss.Color("#AFC6FF"), + Text: lipgloss.Color("#F6F8FF"), + Muted: lipgloss.Color("#D9E2FF"), + Accent: lipgloss.Color("#EDF3FF"), + AccentText: lipgloss.Color("#12307A"), + Selected: lipgloss.Color("#FFF2A8"), + SelectedText: lipgloss.Color("#1B2450"), + Success: lipgloss.Color("#C2FFD1"), + Warning: lipgloss.Color("#FFE08A"), + } + case "midnight": + return Theme{ + Name: "midnight", + Background: lipgloss.Color("#0B1020"), + Panel: lipgloss.Color("#102341"), + PanelAlt: lipgloss.Color("#17315A"), + PanelBorder: lipgloss.Color("#4C89C8"), + Text: lipgloss.Color("#EAF6FF"), + Muted: lipgloss.Color("#B6CEE4"), + Accent: lipgloss.Color("#FFD166"), + AccentText: lipgloss.Color("#12233C"), + Selected: lipgloss.Color("#64C7FF"), + SelectedText: lipgloss.Color("#0C1D33"), + Success: lipgloss.Color("#95E6B0"), + Warning: lipgloss.Color("#FFC857"), + } + default: + return Theme{ + Name: "slate", + Background: lipgloss.Color("#1D1F24"), + Panel: lipgloss.Color("#2A2A2E"), + PanelAlt: lipgloss.Color("#343840"), + PanelBorder: lipgloss.Color("#6F7683"), + Text: lipgloss.Color("#F2F3F5"), + Muted: lipgloss.Color("#C5CAD3"), + Accent: lipgloss.Color("#BDC7D8"), + AccentText: lipgloss.Color("#1D232F"), + Selected: lipgloss.Color("#E7EDF7"), + SelectedText: lipgloss.Color("#20242B"), + Success: lipgloss.Color("#B5E48C"), + Warning: lipgloss.Color("#FFD27D"), + } + } +} + +// Styles derives the lipgloss styles of t. +func (t Theme) Styles() Styles { + return Styles{ + Root: lipgloss.NewStyle(). + Background(t.Background). + Foreground(t.Text). + Padding(1, 2), + Header: lipgloss.NewStyle(). + Background(t.Accent). + Foreground(t.AccentText). + Bold(true). + Padding(0, 1), + HeaderTitle: lipgloss.NewStyle(). + Background(t.Accent). + Foreground(t.AccentText). + Bold(true). + MarginRight(2), + HeaderMeta: lipgloss.NewStyle(). + Background(t.Accent). + Foreground(t.AccentText), + Info: lipgloss.NewStyle(). + Background(t.PanelAlt). + Foreground(t.Muted). + Padding(0, 1), + Panel: lipgloss.NewStyle(). + Background(t.Panel). + Foreground(t.Text). + Border(lipgloss.RoundedBorder()). + BorderForeground(t.PanelBorder). + Padding(1, 1), + PanelAlt: lipgloss.NewStyle(). + Background(t.PanelAlt). + Foreground(t.Text). + Border(lipgloss.RoundedBorder()). + BorderForeground(t.PanelBorder). + Padding(1, 1), + PanelTitle: lipgloss.NewStyle(). + Foreground(t.Accent). + Bold(true). + MarginBottom(1), + ListItem: lipgloss.NewStyle(). + Foreground(t.Text). + Padding(0, 1), + ListEnabled: lipgloss.NewStyle(). + Foreground(t.Success). + Padding(0, 1), + ListSelected: lipgloss.NewStyle(). + Background(t.Selected). + Foreground(t.SelectedText). + Bold(true). + Padding(0, 1), + Search: lipgloss.NewStyle(). + Background(t.Panel). + Foreground(t.Text). + Border(lipgloss.NormalBorder()). + BorderForeground(t.PanelBorder). + Padding(0, 1), + SearchLabel: lipgloss.NewStyle(). + Foreground(t.Accent). + Bold(true), + SearchInput: lipgloss.NewStyle(). + Foreground(t.Text), + Footer: lipgloss.NewStyle(). + Background(t.PanelAlt). + Foreground(t.Muted). + Padding(0, 1), + Key: lipgloss.NewStyle(). + Foreground(t.Accent). + Bold(true), + Value: lipgloss.NewStyle(). + Foreground(t.Text), + Text: lipgloss.NewStyle(). + Foreground(t.Text), + Subtle: lipgloss.NewStyle(). + Foreground(t.Muted). + Bold(true), + Warning: lipgloss.NewStyle(). + Foreground(t.Warning). + Bold(true), + Empty: lipgloss.NewStyle(). + Foreground(t.Muted). + Italic(true), + } +} + +// ThemeNames lists the accepted --theme values. +var ThemeNames = []string{"slate", "dialog", "midnight"} + +// ValidTheme reports whether name is one of ThemeNames (or empty). +func ValidTheme(name string) bool { + if name == "" { + return true + } + for _, n := range ThemeNames { + if n == name { + return true + } + } + return false +} diff --git a/tui/tui_test.go b/tui/tui_test.go new file mode 100644 index 0000000..bda1172 --- /dev/null +++ b/tui/tui_test.go @@ -0,0 +1,152 @@ +package tui + +import ( + "image/color" + "strings" + "testing" + + "charm.land/lipgloss/v2" + "github.com/charmbracelet/colorprofile" +) + +// TestSlateDarkColorsStayGreyWithoutTruecolor guards the slate theme's +// dark surfaces against a terminal without truecolor (no COLORTERM, e.g. +// Apple Terminal, ssh, tmux without Tc): bubbletea then downsamples every +// color to the 256-color palette, and a dark grey with a slight blue tint +// (#2A2D33 for Panel did) lands on index 17, #00005F -- painting the list +// panel and search bar dark blue. Each of these must map to a grey. +func TestSlateDarkColorsStayGreyWithoutTruecolor(t *testing.T) { + th := ThemeByName("slate") + for name, c := range map[string]color.Color{ + "Background": th.Background, + "Panel": th.Panel, + "PanelAlt": th.PanelAlt, + "AccentText": th.AccentText, + "SelectedText": th.SelectedText, + } { + got := colorprofile.ANSI256.Convert(c) + r, g, b, _ := got.RGBA() + if r != g || g != b { + t.Errorf("slate %s converts to non-grey 256-color %v (#%02x%02x%02x)", name, got, r>>8, g>>8, b>>8) + } + } +} + +func TestThemeNames(t *testing.T) { + for in, want := range map[string]string{"": "slate", "default": "slate", "bogus": "slate", "dialog": "dialog", "midnight": "midnight"} { + if got := NormalizeThemeName(in); got != want { + t.Errorf("NormalizeThemeName(%q) = %q, want %q", in, got, want) + } + if got := ThemeByName(in).Name; got != want { + t.Errorf("ThemeByName(%q).Name = %q, want %q", in, got, want) + } + } + name := "slate" + for i, want := range []string{"dialog", "midnight", "slate"} { + name = NextThemeName(name) + if name != want { + t.Fatalf("cycle step %d = %q, want %q", i, name, want) + } + } + for _, n := range append([]string{""}, ThemeNames...) { + if !ValidTheme(n) { + t.Errorf("ValidTheme(%q) = false", n) + } + } + if ValidTheme("default") || ValidTheme("x") { + t.Error("ValidTheme accepts a name outside ThemeNames") + } + _ = ThemeByName("dialog").Styles() // must not panic +} + +func TestListState(t *testing.T) { + var l ListState + if l.Index() != -1 { + t.Fatal("empty list must have Index -1") + } + l.Rebuild(10, func(i int) bool { return i%2 == 0 }) // 0 2 4 6 8 + l.Move(3) + if l.Index() != 6 { + t.Fatalf("Index = %d, want 6", l.Index()) + } + l.Move(100) + if l.Cursor != 4 || l.Index() != 8 { + t.Fatalf("Move past end: cursor %d index %d", l.Cursor, l.Index()) + } + l.ClampScroll(2) + if l.Scroll != 3 { + t.Fatalf("Scroll = %d, want 3", l.Scroll) + } + l.Rebuild(10, func(i int) bool { return i < 4 }) // 0 1 2 3: cursor clamps + if l.Cursor != 3 { + t.Fatalf("Rebuild must clamp cursor, got %d", l.Cursor) + } + l.Move(-100) + l.ClampScroll(2) + if l.Cursor != 0 || l.Scroll != 0 { + t.Fatalf("cursor %d scroll %d", l.Cursor, l.Scroll) + } + l.Rebuild(3, func(int) bool { return false }) + if l.Cursor != 0 || l.Index() != -1 { + t.Fatal("empty filter") + } +} + +func TestTextHelpers(t *testing.T) { + cases := []struct { + in string + w int + want string + }{{"hello", 10, "hello"}, {"hello world", 8, "hello..."}, {"hello", 2, "he"}, {"hello", 0, ""}, {"äöüäöü", 5, "äö..."}} + for _, c := range cases { + if got := Truncate(c.in, c.w); got != c.want { + t.Errorf("Truncate(%q,%d) = %q, want %q", c.in, c.w, got, c.want) + } + } + if got := TruncateBlock("abcdef\nxy", 5); got != "ab...\nxy" { + t.Errorf("TruncateBlock = %q", got) + } + if got := FirstNonEmpty("", "", "b", "c"); got != "b" { + t.Errorf("FirstNonEmpty = %q", got) + } + if got := WrapStyled("one two three", 7, lipgloss.NewStyle()); len(got) != 2 { + t.Errorf("WrapStyled = %q", got) + } + if got := WrapStyled(" ", 7, lipgloss.NewStyle()); len(got) != 1 { + t.Errorf("WrapStyled blank = %q", got) + } + kv := KeyValue(12, ThemeByName("slate").Styles())("name", "a-very-long-value") + if w := lipgloss.Width(kv); w > 12 { + t.Errorf("KeyValue width %d > 12: %q", w, kv) + } +} + +func TestPaintReappliesColorsAndPads(t *testing.T) { + th := ThemeByName("slate") + set, _, _ := strings.Cut(lipgloss.NewStyle().Foreground(th.Text).Background(th.Background).Render("x"), "x") + if set == "" { + t.Skip("lipgloss rendered no color sequence") + } + got := Paint("a\x1b[0mb\nc", th.Text, th.Background, 4) + lines := strings.Split(got, "\n") + if len(lines) != 2 { + t.Fatalf("lines = %q", lines) + } + if want := set + "a\x1b[m" + set + "b \x1b[m"; lines[0] != want { + t.Errorf("line 0 = %q, want %q", lines[0], want) + } + if lipgloss.Width(lines[1]) != 4 { + t.Errorf("line 1 not padded to 4: %q", lines[1]) + } +} + +func TestOuter(t *testing.T) { + s := Outer(lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).Padding(0, 1), 20, 5) + out := s.Render("x") + if w, h := lipgloss.Width(out), lipgloss.Height(out); w != 20 || h != 5 { + t.Errorf("Outer block %dx%d, want 20x5", w, h) + } + if h := lipgloss.Height(Outer(lipgloss.NewStyle(), 10, 0).Render("a\nb\nc")); h != 3 { + t.Errorf("height 0 must keep natural height, got %d", h) + } +}