62159
Sy
symb / files
13.6 KB
1# TUI Expert Knowledge 2 3Best practices for building polished Bubbletea TUIs, distilled from studying 4Charm's production codebase (github.com/charmbracelet/crush). All patterns use 5bubbletea, bubbles, lipgloss, and related Charm libraries. 6 7References: `crush:<path>:<line>` pointing to the crush source at `/tmp/crush`. 8 9--- 10 11## 1. Architecture 12 13### ELM Pattern with Composed Sub-Models 14 15Top-level `Model` owns all sub-models as struct fields. Each sub-model 16exposes methods the parent calls -- the parent does all message routing. 17 18```go 19type UI struct { 20 chat *Chat // message list 21 textarea textarea.Model // input editor 22 dialog *Overlay // modal stack 23 completions *Completions // popup 24 status *Status // status bar 25 layout uiLayout // computed rectangles 26 state uiState // state machine (onboarding/landing/chat) 27 focus uiFocus // which pane has focus (none/editor/main) 28} 29``` 30 31> crush:internal/ui/model/ui.go:42-59, 130 32 33### Service Events via Channel Bridge 34 35Backend services publish events through a channel. A goroutine bridges them 36into bubbletea via `program.Send()`: 37 38```go 39func (a *App) Subscribe(p *tea.Program) { 40 for msg := range a.events { p.Send(msg) } 41} 42``` 43 44> crush:internal/app/app.go:508 45 46--- 47 48## 2. Layout 49 50### Rectangle-Based Layout 51 52Store layout as `image.Rectangle` fields. Compute in a pure function from 53terminal dimensions. Re-compute on `WindowSizeMsg` and on every `Draw()`. 54 55```go 56type uiLayout struct { 57 area, header, main, editor, sidebar, status image.Rectangle 58} 59``` 60 61Use `layout.SplitVertical`/`SplitHorizontal` with `layout.Fixed` constraints: 62 63```go 64mainRect, sideRect := layout.SplitHorizontal(appRect, 65 layout.Fixed(appRect.Dx()-sidebarWidth)) 66chatRect, editorRect := layout.SplitVertical(mainRect, 67 layout.Fixed(mainRect.Dy()-editorHeight)) 68``` 69 70After computing layout, push dimensions to every sub-model: 71 72```go 73m.chat.SetSize(m.layout.main.Dx(), m.layout.main.Dy()) 74m.textarea.SetWidth(m.layout.editor.Dx()) 75``` 76 77> crush:internal/ui/model/ui.go:2220-2240, 2244-2413 78 79### Responsive Breakpoints 80 81Toggle compact/full mode at breakpoints. In compact mode: sidebar disappears, 82header shrinks, session details become a toggleable overlay. 83 84```go 85const ( 86 compactWidthBreakpoint = 120 87 compactHeightBreakpoint = 30 88) 89m.isCompact = m.width < compactWidthBreakpoint || m.height < compactHeightBreakpoint 90``` 91 92> crush:internal/ui/model/ui.go:57-59, 2202-2218 93 94--- 95 96## 3. Screen Buffer Rendering 97 98Draw components into rectangular regions on a shared screen buffer instead 99of concatenating strings. This enables overlapping content (dialogs, popups). 100 101```go 102func (m *UI) View() tea.View { 103 canvas := uv.NewScreenBuffer(m.width, m.height) 104 m.Draw(canvas, canvas.Bounds()) 105 return tea.View{Content: canvas.Render(), AltScreen: true} 106} 107 108func (m *UI) Draw(scr uv.Screen, area uv.Rectangle) { 109 screen.Clear(scr) 110 uv.NewStyledString(headerView).Draw(scr, m.layout.header) 111 m.chat.Draw(scr, m.layout.main) 112 // Dialogs LAST -- they paint over everything 113 if m.dialog.HasDialogs() { m.dialog.Draw(scr, scr.Bounds()) } 114} 115``` 116 117> crush:internal/ui/model/ui.go:1823-1974 118 119--- 120 121## 4. Mouse Support 122 123### Mode and Throttling 124 125Use `MouseModeCellMotion` -- motion events only fire during drag, not on 126every cursor move. Rate-limit wheel/motion at the program level via 127`tea.WithFilter`. Never filter clicks: 128 129```go 130v.MouseMode = tea.MouseModeCellMotion 131 132func MouseEventFilter(m tea.Model, msg tea.Msg) tea.Msg { 133 switch msg.(type) { 134 case tea.MouseWheelMsg, tea.MouseMotionMsg: 135 if time.Since(lastMouseEvent) < 15*time.Millisecond { 136 return nil // drop 137 } 138 lastMouseEvent = time.Now() 139 } 140 return msg 141} 142``` 143 144> crush:internal/ui/model/filter.go:9-22, ui.go:1951 145 146### Coordinate Translation and Hit-Testing 147 148Mouse events arrive in screen-absolute coordinates. Translate to component- 149local by subtracting layout region origin. Hit-test with `image.Point.In`: 150 151```go 152x, y := msg.X-m.layout.main.Min.X, msg.Y-m.layout.main.Min.Y 153 154if image.Pt(msg.X, msg.Y).In(m.layout.editor) { 155 m.focus = uiFocusEditor 156} else if image.Pt(msg.X, msg.Y).In(m.layout.main) { 157 m.focus = uiFocusMain 158} 159``` 160 161> crush:internal/ui/model/ui.go:580, 952-968 162 163### Routing Priority 164 165Every mouse event type checks dialogs first. If a dialog is open, route 166exclusively to it and return early (no click-through): 167 168```go 169case tea.MouseClickMsg: 170 if m.dialog.HasDialogs() { 171 m.dialog.Update(msg) 172 return m, tea.Batch(cmds...) 173 } 174 // ...normal handling with coordinate translation 175``` 176 177> crush:internal/ui/model/ui.go:565-684 178 179### Multi-Click Detection 180 181Use a pending-click-ID pattern to distinguish single/double/triple clicks. 182Single-click actions are delayed by `doubleClickThreshold` (400ms); 183subsequent clicks invalidate the pending ID: 184 185```go 186m.pendingClickID++ 187id := m.pendingClickID 188cmds = append(cmds, tea.Tick(doubleClickThreshold, func(t time.Time) tea.Msg { 189 return DelayedClickMsg{ID: id} 190})) 191// On delayed msg: only act if ID still matches (no newer click) 192``` 193 194Double-click selects a word (UAX#29 word segmentation). Triple-click selects 195a line. Selection state tracked as `mouseDownItem/X/Y`, `mouseDragItem/X/Y`. 196 197> crush:internal/ui/model/chat.go:463-562 198 199### Mouse Text Selection 200 201Apply highlight during render via a registered callback, not during Update. 202The callback sets `item.(Highlightable).SetHighlight(...)` on each item. 203Highlight uses `AttrReverse` on individual cells in the screen buffer: 204 205```go 206var DefaultHighlighter = func(x, y int, c *uv.Cell) *uv.Cell { 207 c.Style.Attrs |= uv.AttrReverse 208 return c 209} 210l.RegisterRenderCallback(c.applyHighlightRange) 211``` 212 213> crush:internal/ui/list/highlight.go:13-135 214 215--- 216 217## 5. Modal Dialogs 218 219### Stack-Based Overlay 220 221Dialogs managed in a slice-as-stack. Only the front dialog receives messages. 222All dialogs render back-to-front (z-order painting): 223 224```go 225type Overlay struct { dialogs []Dialog } 226 227type Dialog interface { 228 ID() string 229 HandleMsg(msg tea.Msg) Action // returns typed Action, NOT tea.Cmd 230 Draw(scr uv.Screen, area uv.Rectangle) *tea.Cursor 231} 232 233func (d *Overlay) Update(msg tea.Msg) tea.Msg { 234 return d.dialogs[len(d.dialogs)-1].HandleMsg(msg) 235} 236func (d *Overlay) Draw(scr uv.Screen, area uv.Rectangle) *tea.Cursor { 237 for _, dialog := range d.dialogs { dialog.Draw(scr, area) } 238} 239``` 240 241> crush:internal/ui/dialog/dialog.go:30-205 242 243### Action-Based Communication 244 245Dialogs return typed action structs. The parent type-switches to handle them. 246This is cleaner than `tea.Cmd` for dialog results: 247 248```go 249type Action any 250// ActionClose, ActionSelectModel{Provider,Model}, ActionPermissionResponse{...} 251 252action := m.dialog.Update(msg) 253switch a := action.(type) { 254case dialog.ActionClose: m.dialog.CloseFrontDialog() 255case dialog.ActionSelectModel: m.switchModel(a.Provider, a.Model) 256case dialog.ActionPermissionResponse: m.handlePermission(a.Permission, a.Action) 257} 258``` 259 260> crush:internal/ui/model/ui.go:1127-1200 261 262### Centering and Sizing 263 264Center dialogs with pure geometry. Scale dimensions relative to terminal 265with caps. Force fullscreen when terminal is too small: 266 267```go 268func CenterRect(area image.Rectangle, w, h int) image.Rectangle { 269 cx, cy := area.Min.X+area.Dx()/2, area.Min.Y+area.Dy()/2 270 return image.Rect(cx-w/2, cy-h/2, cx-w/2+w, cy-h/2+h) 271} 272// Adaptive sizing: 273width = min(int(float64(area.Dx())*0.8), 180) // with diff 274width = min(int(float64(area.Dx())*0.6), 100) // without diff 275if area.Dx() < 77 || area.Dy() < 20 { forceFullscreen = true } 276``` 277 278> crush:internal/ui/common/common.go:45-56 279> crush:internal/ui/dialog/permissions.go:345-401 280 281### Standardized Dialog Layout 282 283Use a `RenderContext` builder for consistent dialog structure: gradient title 284bar, content parts with optional gaps, help bar, wrapped in rounded border: 285 286```go 287rc := NewRenderContext(styles, width) 288rc.Title = "Commands" 289rc.TitleInfo = radioButtons // inline tab selector 290rc.AddPart(inputView) // text filter 291rc.AddPart(listView) // filtered list 292rc.Help = helpView 293view := rc.Render() // bordered dialog with gradient title 294DrawCenterCursor(scr, area, view, cursor) 295``` 296 297> crush:internal/ui/dialog/common.go:42-151 298 299--- 300 301## 6. Scrolling 302 303### Line-Granularity Scroll Model 304 305Track two values: index of first visible item and lines of that item above 306viewport. This allows partial item visibility at the top: 307 308```go 309type List struct { 310 items []Item 311 offsetIdx int // first visible item index 312 offsetLine int // lines of that item above viewport 313 height int // viewport height in lines 314} 315``` 316 317> crush:internal/ui/list/list.go:10-36 318 319### Sticky-Bottom Auto-Scroll 320 321Check `AtBottom()` before appending content. Only auto-scroll if user was 322already at bottom. Scroll 5 lines per wheel tick: 323 324```go 325atBottom := m.chat.list.AtBottom() 326// ...append new items... 327if atBottom { m.chat.ScrollToBottom() } 328 329case tea.MouseWheelUp: m.chat.ScrollBy(-5) 330case tea.MouseWheelDown: m.chat.ScrollBy(5) 331``` 332 333> crush:internal/ui/model/ui.go:652-684, 883-949 334 335### Scrollbar 336 337Pure function. Proportional thumb size and position: 338 339```go 340func Scrollbar(height, contentSize, viewportSize, offset int) string { 341 thumbSize := max(1, height*viewportSize/contentSize) 342 trackSpace := height - thumbSize 343 thumbPos := min(trackSpace, offset*trackSpace/(contentSize-viewportSize)) 344} 345``` 346 347> crush:internal/ui/common/scrollbar.go:11-46 348 349### Pause Off-Screen Animations 350 351Track visible animations. Pause off-screen ones. Restart after scroll: 352 353```go 354func (m *Chat) ScrollByAndAnimate(lines int) tea.Cmd { 355 m.list.ScrollBy(lines) 356 return m.RestartPausedVisibleAnimations() 357} 358``` 359 360> crush:internal/ui/model/chat.go:170-258 361 362--- 363 364## 7. Syntax Highlighting 365 366### Chroma with True-Color 367 368Use `terminal16m` formatter. Three-tier lexer fallback: filename match -> 369content analysis -> fallback. Override background per-context: 370 371```go 372l := lexers.Match(fileName) 373if l == nil { l = lexers.Analyse(source) } 374if l == nil { l = lexers.Fallback } 375l = chroma.Coalesce(l) 376f := formatters.Get("terminal16m") 377 378// Override background for different contexts (diffs, panels): 379s, _ = s.Builder().Transform(func(se chroma.StyleEntry) chroma.StyleEntry { 380 se.Background = chroma.Colour(bgHex) 381 return se 382}).Build() 383``` 384 385> crush:internal/ui/common/highlight.go:10-56 386 387### Glamour Markdown 388 389Configure via `ansi.StyleConfig` structs, not built-in themes. Keep two 390configs -- full-color for content, muted for thinking/secondary: 391 392```go 393glamour.NewTermRenderer(glamour.WithStyles(styles.Markdown), glamour.WithWordWrap(w)) 394glamour.NewTermRenderer(glamour.WithStyles(styles.PlainMarkdown), glamour.WithWordWrap(w)) 395``` 396 397> crush:internal/ui/common/markdown.go:10-26 398 399--- 400 401## 8. Styling 402 403### Centralized Styles Struct 404 405One struct with nested groups for every component. Construct once, share 406via a `Common` pointer. Use semantic color names, not raw hex: 407 408```go 409type Styles struct { 410 Base, Muted, Subtle lipgloss.Style 411 Primary, Secondary color.Color 412 BgBase, BgSubtle color.Color 413 FgBase, FgMuted color.Color 414 Header struct { ... } 415 Chat struct { Message struct { ... } } 416 Dialog struct { View lipgloss.Style; ... } 417 Markdown, PlainMarkdown ansi.StyleConfig 418 Diff diffview.Style 419} 420``` 421 422> crush:internal/ui/styles/styles.go:60-538 423 424### Gradients 425 426Split into grapheme clusters, blend in HCL space, style individually. Use 427sparingly for decorative elements like dialog title lines: 428 429```go 430graphemes := splitGraphemes(input) 431ramp := blendHCL(c1, c2, len(graphemes)) 432for i, g := range graphemes { result += style.Foreground(ramp[i]).Render(g) } 433``` 434 435> crush:internal/ui/styles/grad.go:16-117 436 437### Reusable Elements 438 439Build a library of composable elements: `Section(title, width)` with `─` 440fill, `DialogTitle(title, width, c1, c2)` with gradient `╱` fill, 441`Status(icon, title, desc, width)` with truncation, `ButtonGroup(buttons)`. 442 443> crush:internal/ui/common/elements.go:17-190 444 445--- 446 447## 9. Render Caching 448 449Cache rendered output keyed by width. Invalidate on content change: 450 451```go 452func (item *Item) RawRender(width int) string { 453 if cached, ok := item.getCached(width); ok { return cached } 454 result := item.renderContent(width) 455 item.setCache(result, width) 456 return result 457} 458func (item *Item) SetMessage(msg *Message) { 459 item.Message = msg 460 item.clearCache() 461} 462``` 463 464> crush:internal/ui/chat/assistant.go:81-238 465 466--- 467 468## 10. Quick Reference 469 470| Pattern | Rule | 471|---------|------| 472| Mouse mode | `CellMotion` (drag only), not `AllMotion` | 473| Mouse filter | Throttle wheel/motion at 15ms; never filter clicks | 474| Mouse routing | Dialog-first, then focus-based, coordinate translation | 475| Multi-click | Pending-ID pattern with 400ms threshold | 476| Selection | Render callback with `AttrReverse`; UAX#29 for word bounds | 477| Dialog stack | Slice-as-stack; front gets messages; all render back-to-front | 478| Dialog results | Typed Action structs, not `tea.Cmd`; parent type-switches | 479| Dialog render | No backdrop; direct cell overwrite; `CenterRect` geometry | 480| Layout | `image.Rectangle` fields; pure layout function; split helpers | 481| Responsive | Breakpoint toggle compact/full; adaptive dialog sizing | 482| Scrolling | Index + line offset; sticky-bottom; 5 lines/wheel tick | 483| Highlighting | Chroma `terminal16m`; 3-tier lexer; bg override per context | 484| Markdown | Glamour with custom `ansi.StyleConfig`; two themes | 485| Styles | One centralized struct; semantic colors; shared via pointer | 486| Caching | Width-keyed render cache; invalidate on mutation | 487| Animations | Pre-computed frames; pause off-screen; ID-based tick routing | 488| Screen buffer | Draw into rects on shared buffer; dialogs paint last |