xonecas.io
62159
Sy

symb / commit 9a96378

fix: proper TUI structure and usage of libraries

xonecas2026-02-12 9a9637818f3285803195ebafceb473f07c0341b4 parent 5231fb6

10 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

cmd/symb/main.go+1−0
@@ -111,6 +111,7 @@ func main() {
111111 tui.New(prov, proxy, tools, providerCfg.Model),
112112 tea.WithAltScreen(),
113113 tea.WithMouseCellMotion(),
114+ tea.WithFilter(tui.MouseEventFilter),
114115 )
115116
116117 // Set program reference for tools that need it
docs/TUI_EXPERT.md+488−0
@@ -0,0 +1,488 @@
1+# TUI Expert Knowledge
2+
3+Best practices for building polished Bubbletea TUIs, distilled from studying
4+Charm's production codebase (github.com/charmbracelet/crush). All patterns use
5+bubbletea, bubbles, lipgloss, and related Charm libraries.
6+
7+References: `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+
15+Top-level `Model` owns all sub-models as struct fields. Each sub-model
16+exposes methods the parent calls -- the parent does all message routing.
17+
18+```go
19+type 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+
35+Backend services publish events through a channel. A goroutine bridges them
36+into bubbletea via `program.Send()`:
37+
38+```go
39+func (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+
52+Store layout as `image.Rectangle` fields. Compute in a pure function from
53+terminal dimensions. Re-compute on `WindowSizeMsg` and on every `Draw()`.
54+
55+```go
56+type uiLayout struct {
57+ area, header, main, editor, sidebar, status image.Rectangle
58+}
59+```
60+
61+Use `layout.SplitVertical`/`SplitHorizontal` with `layout.Fixed` constraints:
62+
63+```go
64+mainRect, sideRect := layout.SplitHorizontal(appRect,
65+ layout.Fixed(appRect.Dx()-sidebarWidth))
66+chatRect, editorRect := layout.SplitVertical(mainRect,
67+ layout.Fixed(mainRect.Dy()-editorHeight))
68+```
69+
70+After computing layout, push dimensions to every sub-model:
71+
72+```go
73+m.chat.SetSize(m.layout.main.Dx(), m.layout.main.Dy())
74+m.textarea.SetWidth(m.layout.editor.Dx())
75+```
76+
77+> crush:internal/ui/model/ui.go:2220-2240, 2244-2413
78+
79+### Responsive Breakpoints
80+
81+Toggle compact/full mode at breakpoints. In compact mode: sidebar disappears,
82+header shrinks, session details become a toggleable overlay.
83+
84+```go
85+const (
86+ compactWidthBreakpoint = 120
87+ compactHeightBreakpoint = 30
88+)
89+m.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+
98+Draw components into rectangular regions on a shared screen buffer instead
99+of concatenating strings. This enables overlapping content (dialogs, popups).
100+
101+```go
102+func (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+
108+func (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+
125+Use `MouseModeCellMotion` -- motion events only fire during drag, not on
126+every cursor move. Rate-limit wheel/motion at the program level via
127+`tea.WithFilter`. Never filter clicks:
128+
129+```go
130+v.MouseMode = tea.MouseModeCellMotion
131+
132+func 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+
148+Mouse events arrive in screen-absolute coordinates. Translate to component-
149+local by subtracting layout region origin. Hit-test with `image.Point.In`:
150+
151+```go
152+x, y := msg.X-m.layout.main.Min.X, msg.Y-m.layout.main.Min.Y
153+
154+if 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+
165+Every mouse event type checks dialogs first. If a dialog is open, route
166+exclusively to it and return early (no click-through):
167+
168+```go
169+case 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+
181+Use a pending-click-ID pattern to distinguish single/double/triple clicks.
182+Single-click actions are delayed by `doubleClickThreshold` (400ms);
183+subsequent clicks invalidate the pending ID:
184+
185+```go
186+m.pendingClickID++
187+id := m.pendingClickID
188+cmds = 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+
194+Double-click selects a word (UAX#29 word segmentation). Triple-click selects
195+a 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+
201+Apply highlight during render via a registered callback, not during Update.
202+The callback sets `item.(Highlightable).SetHighlight(...)` on each item.
203+Highlight uses `AttrReverse` on individual cells in the screen buffer:
204+
205+```go
206+var DefaultHighlighter = func(x, y int, c *uv.Cell) *uv.Cell {
207+ c.Style.Attrs |= uv.AttrReverse
208+ return c
209+}
210+l.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+
221+Dialogs managed in a slice-as-stack. Only the front dialog receives messages.
222+All dialogs render back-to-front (z-order painting):
223+
224+```go
225+type Overlay struct { dialogs []Dialog }
226+
227+type 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+
233+func (d *Overlay) Update(msg tea.Msg) tea.Msg {
234+ return d.dialogs[len(d.dialogs)-1].HandleMsg(msg)
235+}
236+func (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+
245+Dialogs return typed action structs. The parent type-switches to handle them.
246+This is cleaner than `tea.Cmd` for dialog results:
247+
248+```go
249+type Action any
250+// ActionClose, ActionSelectModel{Provider,Model}, ActionPermissionResponse{...}
251+
252+action := m.dialog.Update(msg)
253+switch a := action.(type) {
254+case dialog.ActionClose: m.dialog.CloseFrontDialog()
255+case dialog.ActionSelectModel: m.switchModel(a.Provider, a.Model)
256+case 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+
264+Center dialogs with pure geometry. Scale dimensions relative to terminal
265+with caps. Force fullscreen when terminal is too small:
266+
267+```go
268+func 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:
273+width = min(int(float64(area.Dx())*0.8), 180) // with diff
274+width = min(int(float64(area.Dx())*0.6), 100) // without diff
275+if 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+
283+Use a `RenderContext` builder for consistent dialog structure: gradient title
284+bar, content parts with optional gaps, help bar, wrapped in rounded border:
285+
286+```go
287+rc := NewRenderContext(styles, width)
288+rc.Title = "Commands"
289+rc.TitleInfo = radioButtons // inline tab selector
290+rc.AddPart(inputView) // text filter
291+rc.AddPart(listView) // filtered list
292+rc.Help = helpView
293+view := rc.Render() // bordered dialog with gradient title
294+DrawCenterCursor(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+
305+Track two values: index of first visible item and lines of that item above
306+viewport. This allows partial item visibility at the top:
307+
308+```go
309+type 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+
321+Check `AtBottom()` before appending content. Only auto-scroll if user was
322+already at bottom. Scroll 5 lines per wheel tick:
323+
324+```go
325+atBottom := m.chat.list.AtBottom()
326+// ...append new items...
327+if atBottom { m.chat.ScrollToBottom() }
328+
329+case tea.MouseWheelUp: m.chat.ScrollBy(-5)
330+case tea.MouseWheelDown: m.chat.ScrollBy(5)
331+```
332+
333+> crush:internal/ui/model/ui.go:652-684, 883-949
334+
335+### Scrollbar
336+
337+Pure function. Proportional thumb size and position:
338+
339+```go
340+func 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+
351+Track visible animations. Pause off-screen ones. Restart after scroll:
352+
353+```go
354+func (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+
368+Use `terminal16m` formatter. Three-tier lexer fallback: filename match ->
369+content analysis -> fallback. Override background per-context:
370+
371+```go
372+l := lexers.Match(fileName)
373+if l == nil { l = lexers.Analyse(source) }
374+if l == nil { l = lexers.Fallback }
375+l = chroma.Coalesce(l)
376+f := formatters.Get("terminal16m")
377+
378+// Override background for different contexts (diffs, panels):
379+s, _ = 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+
389+Configure via `ansi.StyleConfig` structs, not built-in themes. Keep two
390+configs -- full-color for content, muted for thinking/secondary:
391+
392+```go
393+glamour.NewTermRenderer(glamour.WithStyles(styles.Markdown), glamour.WithWordWrap(w))
394+glamour.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+
405+One struct with nested groups for every component. Construct once, share
406+via a `Common` pointer. Use semantic color names, not raw hex:
407+
408+```go
409+type 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+
426+Split into grapheme clusters, blend in HCL space, style individually. Use
427+sparingly for decorative elements like dialog title lines:
428+
429+```go
430+graphemes := splitGraphemes(input)
431+ramp := blendHCL(c1, c2, len(graphemes))
432+for 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+
439+Build a library of composable elements: `Section(title, width)` with `─`
440+fill, `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+
449+Cache rendered output keyed by width. Invalidate on content change:
450+
451+```go
452+func (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+}
458+func (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 |
internal/tui/editor/editor.go+750−0
@@ -0,0 +1,750 @@
1+// Package editor provides a minimal text editor component for bubbletea.
2+// Supports optional line numbers, Chroma syntax highlighting, mouse cursor
3+// placement, drag-to-select, and consistent background colors.
4+package editor
5+
6+import (
7+ "fmt"
8+ "strings"
9+ "sync"
10+
11+ "github.com/alecthomas/chroma/v2"
12+ "github.com/alecthomas/chroma/v2/formatters"
13+ "github.com/alecthomas/chroma/v2/lexers"
14+ "github.com/alecthomas/chroma/v2/styles"
15+ "github.com/atotto/clipboard"
16+ "github.com/charmbracelet/bubbles/cursor"
17+ tea "github.com/charmbracelet/bubbletea"
18+ "github.com/charmbracelet/lipgloss"
19+ "github.com/charmbracelet/x/ansi"
20+)
21+
22+// ---------------------------------------------------------------------------
23+// Highlight cache (global, shared across instances)
24+// ---------------------------------------------------------------------------
25+
26+var (
27+ hlCache = make(map[string]string)
28+ hlCacheMu sync.RWMutex
29+)
30+
31+func cachedHighlight(text, language, theme string) string {
32+ cacheKey := language + ":" + theme + ":" + text
33+ hlCacheMu.RLock()
34+ if v, ok := hlCache[cacheKey]; ok {
35+ hlCacheMu.RUnlock()
36+ return v
37+ }
38+ hlCacheMu.RUnlock()
39+
40+ lex := lexers.Get(language)
41+ if lex == nil {
42+ return text
43+ }
44+ lex = chroma.Coalesce(lex)
45+ sty := styles.Get(theme)
46+ fmtr := formatters.Get("terminal16m")
47+ if fmtr == nil {
48+ fmtr = formatters.Fallback
49+ }
50+ it, err := lex.Tokenise(nil, text)
51+ if err != nil {
52+ return text
53+ }
54+ var buf strings.Builder
55+ if err := fmtr.Format(&buf, sty, it); err != nil {
56+ return text
57+ }
58+ result := strings.TrimRight(buf.String(), "\n")
59+
60+ hlCacheMu.Lock()
61+ if len(hlCache) > 2000 {
62+ hlCache = make(map[string]string)
63+ }
64+ hlCache[cacheKey] = result
65+ hlCacheMu.Unlock()
66+ return result
67+}
68+
69+// themeBg extracts the background hex color from a Chroma style.
70+// Returns "" if no background is set.
71+func themeBg(theme string) string {
72+ sty := styles.Get(theme)
73+ if sty == nil {
74+ return ""
75+ }
76+ bg := sty.Get(chroma.Background).Background
77+ if !bg.IsSet() {
78+ return ""
79+ }
80+ return bg.String() // "#rrggbb"
81+}
82+
83+// ---------------------------------------------------------------------------
84+// Model
85+// ---------------------------------------------------------------------------
86+
87+// Model is a minimal text editor / viewer component.
88+type Model struct {
89+ // Public configuration — set before first Update/View.
90+ ReadOnly bool
91+ ShowLineNumbers bool
92+ Language string // Chroma lexer name (empty = no highlighting)
93+ SyntaxTheme string // Chroma style name (empty = no highlighting)
94+ Placeholder string // Shown when empty and blurred
95+
96+ // Styles — set by parent.
97+ CursorStyle lipgloss.Style // Foreground for the cursor character
98+ LineNumStyle lipgloss.Style // Line number gutter
99+ PlaceholderSty lipgloss.Style // Placeholder text
100+ BgColor lipgloss.Color // Fallback bg when no syntax theme
101+
102+ // Internal state
103+ lines [][]rune // Backing store, one entry per line
104+ row int // Cursor row (0-indexed into lines)
105+ col int // Cursor column (0-indexed into line runes)
106+ scroll int // First visible row
107+
108+ width int // Viewport width (cells)
109+ height int // Viewport height (rows)
110+
111+ focus bool
112+ cursor cursor.Model
113+
114+ // Mouse selection
115+ selecting bool
116+ selectStart pos
117+ selectEnd pos
118+
119+ // Cached computed values
120+ gutterWidth int // Width of line number gutter (0 if disabled)
121+}
122+
123+type pos struct{ row, col int }
124+
125+// New creates a new editor with sensible defaults.
126+func New() Model {
127+ c := cursor.New()
128+ c.SetMode(cursor.CursorBlink)
129+ return Model{
130+ lines: [][]rune{{}},
131+ cursor: c,
132+ }
133+}
134+
135+// ---------------------------------------------------------------------------
136+// Public methods called by parent
137+// ---------------------------------------------------------------------------
138+
139+func (m *Model) SetWidth(w int) { m.width = w; m.clampScroll() }
140+func (m *Model) SetHeight(h int) { m.height = h; m.clampScroll() }
141+
142+func (m *Model) Focus() {
143+ m.focus = true
144+ m.cursor.Focus()
145+}
146+
147+func (m *Model) Blur() {
148+ m.focus = false
149+ m.cursor.Blur()
150+}
151+
152+func (m Model) Focused() bool { return m.focus }
153+
154+func (m *Model) SetValue(s string) {
155+ raw := strings.Split(s, "\n")
156+ m.lines = make([][]rune, len(raw))
157+ for i, l := range raw {
158+ m.lines[i] = []rune(l)
159+ }
160+ if len(m.lines) == 0 {
161+ m.lines = [][]rune{{}}
162+ }
163+ m.row = 0
164+ m.col = 0
165+ m.scroll = 0
166+}
167+
168+func (m Model) Value() string {
169+ var sb strings.Builder
170+ for i, line := range m.lines {
171+ sb.WriteString(string(line))
172+ if i < len(m.lines)-1 {
173+ sb.WriteByte('\n')
174+ }
175+ }
176+ return sb.String()
177+}
178+
179+func (m *Model) Reset() {
180+ m.lines = [][]rune{{}}
181+ m.row = 0
182+ m.col = 0
183+ m.scroll = 0
184+}
185+
186+// Blink returns the initial cursor blink message. Call from Init().
187+func Blink() tea.Msg { return cursor.Blink() }
188+
189+// ---------------------------------------------------------------------------
190+// Internal helpers
191+// ---------------------------------------------------------------------------
192+
193+func (m *Model) currentLine() []rune { return m.lines[m.row] }
194+
195+func (m *Model) clampCursor() {
196+ if m.row < 0 {
197+ m.row = 0
198+ }
199+ if m.row >= len(m.lines) {
200+ m.row = len(m.lines) - 1
201+ }
202+ if m.col < 0 {
203+ m.col = 0
204+ }
205+ if m.col > len(m.currentLine()) {
206+ m.col = len(m.currentLine())
207+ }
208+}
209+
210+func (m *Model) clampScroll() {
211+ if m.height <= 0 {
212+ return
213+ }
214+ // Ensure cursor is visible
215+ if m.row < m.scroll {
216+ m.scroll = m.row
217+ }
218+ if m.row >= m.scroll+m.height {
219+ m.scroll = m.row - m.height + 1
220+ }
221+ // Don't scroll past content
222+ maxScroll := len(m.lines) - m.height
223+ if maxScroll < 0 {
224+ maxScroll = 0
225+ }
226+ if m.scroll > maxScroll {
227+ m.scroll = maxScroll
228+ }
229+ if m.scroll < 0 {
230+ m.scroll = 0
231+ }
232+}
233+
234+const tabWidth = 4
235+
236+// expandTabs replaces tabs with spaces (tabWidth-aligned).
237+func expandTabs(s string) string {
238+ var b strings.Builder
239+ col := 0
240+ for _, r := range s {
241+ if r == '\t' {
242+ spaces := tabWidth - (col % tabWidth)
243+ b.WriteString(strings.Repeat(" ", spaces))
244+ col += spaces
245+ } else {
246+ b.WriteRune(r)
247+ col++
248+ }
249+ }
250+ return b.String()
251+}
252+
253+// textWidth returns the width available for text content.
254+func (m *Model) textWidth() int {
255+ m.gutterWidth = 0
256+ if m.ShowLineNumbers {
257+ digits := len(fmt.Sprintf("%d", len(m.lines)))
258+ if digits < 2 {
259+ digits = 2
260+ }
261+ m.gutterWidth = digits + 1 // digits + 1 space
262+ }
263+ w := m.width - m.gutterWidth
264+ if w < 1 {
265+ w = 1
266+ }
267+ return w
268+}
269+
270+// bgForRender returns the background style. Extracts from syntax theme if
271+// available, falls back to BgColor.
272+func (m *Model) bgForRender() lipgloss.Style {
273+ if m.Language != "" && m.SyntaxTheme != "" {
274+ if hex := themeBg(m.SyntaxTheme); hex != "" {
275+ return lipgloss.NewStyle().Background(lipgloss.Color(hex))
276+ }
277+ }
278+ return lipgloss.NewStyle().Background(m.BgColor)
279+}
280+
281+// ---------------------------------------------------------------------------
282+// Editing operations
283+// ---------------------------------------------------------------------------
284+
285+func (m *Model) insertRune(r rune) {
286+ if m.ReadOnly {
287+ return
288+ }
289+ line := m.currentLine()
290+ newLine := make([]rune, 0, len(line)+1)
291+ newLine = append(newLine, line[:m.col]...)
292+ newLine = append(newLine, r)
293+ newLine = append(newLine, line[m.col:]...)
294+ m.lines[m.row] = newLine
295+ m.col++
296+}
297+
298+func (m *Model) insertNewline() {
299+ if m.ReadOnly {
300+ return
301+ }
302+ line := m.currentLine()
303+ after := make([]rune, len(line[m.col:]))
304+ copy(after, line[m.col:])
305+ m.lines[m.row] = line[:m.col]
306+ // Insert new line after current
307+ newLines := make([][]rune, 0, len(m.lines)+1)
308+ newLines = append(newLines, m.lines[:m.row+1]...)
309+ newLines = append(newLines, after)
310+ newLines = append(newLines, m.lines[m.row+1:]...)
311+ m.lines = newLines
312+ m.row++
313+ m.col = 0
314+}
315+
316+func (m *Model) deleteBack() {
317+ if m.ReadOnly {
318+ return
319+ }
320+ if m.col > 0 {
321+ line := m.currentLine()
322+ m.lines[m.row] = append(line[:m.col-1], line[m.col:]...)
323+ m.col--
324+ } else if m.row > 0 {
325+ // Merge with previous line
326+ prev := m.lines[m.row-1]
327+ m.col = len(prev)
328+ m.lines[m.row-1] = append(prev, m.currentLine()...)
329+ m.lines = append(m.lines[:m.row], m.lines[m.row+1:]...)
330+ m.row--
331+ }
332+}
333+
334+func (m *Model) deleteForward() {
335+ if m.ReadOnly {
336+ return
337+ }
338+ line := m.currentLine()
339+ if m.col < len(line) {
340+ m.lines[m.row] = append(line[:m.col], line[m.col+1:]...)
341+ } else if m.row < len(m.lines)-1 {
342+ // Merge with next line
343+ m.lines[m.row] = append(line, m.lines[m.row+1]...)
344+ m.lines = append(m.lines[:m.row+1], m.lines[m.row+2:]...)
345+ }
346+}
347+
348+func (m *Model) tabIndent() {
349+ if m.ReadOnly {
350+ return
351+ }
352+ // Indent to match the leading whitespace of the line above.
353+ indent := "\t"
354+ if m.row > 0 {
355+ above := m.lines[m.row-1]
356+ indent = ""
357+ for _, r := range above {
358+ if r == ' ' || r == '\t' {
359+ indent += string(r)
360+ } else {
361+ break
362+ }
363+ }
364+ if indent == "" {
365+ indent = "\t"
366+ }
367+ }
368+ for _, r := range indent {
369+ m.insertRune(r)
370+ }
371+}
372+
373+// ---------------------------------------------------------------------------
374+// Selection helpers
375+// ---------------------------------------------------------------------------
376+
377+func (m *Model) selectionOrdered() (start, end pos) {
378+ s, e := m.selectStart, m.selectEnd
379+ if s.row > e.row || (s.row == e.row && s.col > e.col) {
380+ s, e = e, s
381+ }
382+ return s, e
383+}
384+
385+func (m *Model) hasSelection() bool {
386+ return m.selectStart != m.selectEnd
387+}
388+
389+func (m *Model) clearSelection() {
390+ m.selecting = false
391+ m.selectStart = pos{}
392+ m.selectEnd = pos{}
393+}
394+
395+func (m *Model) selectedText() string {
396+ if !m.hasSelection() {
397+ return ""
398+ }
399+ s, e := m.selectionOrdered()
400+ if s.row == e.row {
401+ line := m.lines[s.row]
402+ sc := clampMax(s.col, len(line))
403+ ec := clampMax(e.col, len(line))
404+ return string(line[sc:ec])
405+ }
406+ var sb strings.Builder
407+ // First line from s.col to end
408+ first := m.lines[s.row]
409+ sb.WriteString(string(first[clampMax(s.col, len(first)):]))
410+ // Middle lines in full
411+ for r := s.row + 1; r < e.row; r++ {
412+ sb.WriteByte('\n')
413+ sb.WriteString(string(m.lines[r]))
414+ }
415+ // Last line from start to e.col
416+ sb.WriteByte('\n')
417+ last := m.lines[e.row]
418+ sb.WriteString(string(last[:clampMax(e.col, len(last))]))
419+ return sb.String()
420+}
421+
422+// screenToPos converts screen-relative x,y to a buffer row,col.
423+func (m *Model) screenToPos(x, y int) pos {
424+ row := m.scroll + y
425+ if row < 0 {
426+ row = 0
427+ }
428+ if row >= len(m.lines) {
429+ row = len(m.lines) - 1
430+ }
431+ col := x - m.gutterWidth
432+ if col < 0 {
433+ col = 0
434+ }
435+ lineLen := len(m.lines[row])
436+ if col > lineLen {
437+ col = lineLen
438+ }
439+ return pos{row: row, col: col}
440+}
441+
442+func clampMax(v, hi int) int {
443+ if v < 0 {
444+ return 0
445+ }
446+ if v > hi {
447+ return hi
448+ }
449+ return v
450+}
451+
452+// ---------------------------------------------------------------------------
453+// Update
454+// ---------------------------------------------------------------------------
455+
456+func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
457+ var cmds []tea.Cmd
458+
459+ switch msg := msg.(type) {
460+ case tea.KeyMsg:
461+ if !m.focus {
462+ break
463+ }
464+ moved := true
465+ switch msg.String() {
466+ // Navigation
467+ case "up":
468+ m.row--
469+ m.clampCursor()
470+ case "down":
471+ m.row++
472+ m.clampCursor()
473+ case "left":
474+ if m.col > 0 {
475+ m.col--
476+ } else if m.row > 0 {
477+ m.row--
478+ m.col = len(m.currentLine())
479+ }
480+ case "right":
481+ if m.col < len(m.currentLine()) {
482+ m.col++
483+ } else if m.row < len(m.lines)-1 {
484+ m.row++
485+ m.col = 0
486+ }
487+ case "home", "ctrl+a":
488+ m.col = 0
489+ case "end", "ctrl+e":
490+ m.col = len(m.currentLine())
491+ case "pgup":
492+ m.row -= m.height
493+ m.clampCursor()
494+ case "pgdown":
495+ m.row += m.height
496+ m.clampCursor()
497+ case "ctrl+home":
498+ m.row = 0
499+ m.col = 0
500+ case "ctrl+end":
501+ m.row = len(m.lines) - 1
502+ m.col = len(m.currentLine())
Cut short: this commit's diff is over 1000 lines.
internal/tui/editor/editor_test.go+57−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/styles.go+55−6
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLayout/120x40/ANSI.golden+2−2
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLayout/120x40/Stripped.golden+2−2
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLayout/80x24/ANSI.golden+2−2
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLayout/80x24/Stripped.golden+2−2
Cut short: this commit's diff is over 1000 lines.
internal/tui/tui.go+568−543
Cut short: this commit's diff is over 1000 lines.