@@ -1,363 +0,0 @@
1-# Mouse & Selection in Bubbletea TUIs
2-
3-Reference document based on patterns from Charm's Crush (production TUI using
4-Bubbletea v2 + Lipgloss v2). Applies directly to our stack.
5-
6----
7-
8-## 1. Mouse Modes
9-
10-Bubbletea supports two mouse tracking modes:
11-
12-- **CellMotion** (`tea.WithMouseCellMotion()` / `MouseModeCellMotion`): reports
13- presses, releases, and motion *while a button is held* (i.e. drags). This is
14- what you want for selection. Does NOT report hover.
15-- **AllMotion** (`tea.WithMouseAllMotion()` / `MouseModeAllMotion`): also
16- reports motion with no button held. Expensive — avoid unless hover is needed.
17-
18-Crush uses CellMotion. So do we.
19-
20-## 2. Mouse Message Types (Bubbletea v2)
21-
22-Bubbletea v2 splits the old `tea.MouseMsg` into distinct types:
23-
24-| Type | When fired |
25-|---------------------|----------------------------------|
26-| `tea.MouseClickMsg` | Button pressed |
27-| `tea.MouseMotionMsg`| Motion while button held (drag) |
28-| `tea.MouseReleaseMsg`| Button released |
29-| `tea.MouseWheelMsg` | Scroll wheel |
30-
31-Bubbletea v1 (what we use) has a single `tea.MouseMsg` with `.Action` field:
32-
33-| `msg.Action` | Equivalent v2 type |
34-|---------------------------|-----------------------|
35-| `tea.MouseActionPress` | `tea.MouseClickMsg` |
36-| `tea.MouseActionMotion` | `tea.MouseMotionMsg` |
37-| `tea.MouseActionRelease` | `tea.MouseReleaseMsg` |
38-
39-And `msg.Button` for wheel: `tea.MouseButtonWheelUp`, `tea.MouseButtonWheelDown`.
40-
41-## 3. Event Throttling
42-
43-Trackpads and high-refresh mice flood the event queue. Use `tea.WithFilter` to
44-throttle motion and wheel events at the program level:
45-
46-```go
47-var lastMouseEvent time.Time
48-
49-func MouseEventFilter(_ tea.Model, msg tea.Msg) tea.Msg {
50- switch msg.(type) {
51- case tea.MouseWheelMsg, tea.MouseMotionMsg:
52- now := time.Now()
53- if now.Sub(lastMouseEvent) < 15*time.Millisecond {
54- return nil // drop event
55- }
56- lastMouseEvent = now
57- }
58- return msg
59-}
60-```
61-
62-For v1 (our code), switch on `tea.MouseMsg` and check `msg.Action`/`msg.Button`
63-instead. **Never drop click or release events** — only motion and wheel.
64-
65-Register at program creation:
66-
67-```go
68-p := tea.NewProgram(model, tea.WithMouseCellMotion(), tea.WithFilter(filter))
69-```
70-
71-## 4. Mouse Event Routing
72-
73-### 4.1 Layout Rects (Not Zones)
74-
75-Both Crush and our codebase use `image.Rectangle` structs for layout regions.
76-Hit testing is `image.Pt(msg.X, msg.Y).In(rect)`. This is simpler and more
77-predictable than lipgloss zone-based routing.
78-
79-### 4.2 Coordinate Translation
80-
81-Mouse coordinates are screen-absolute. Child components expect local
82-coordinates. Subtract the layout rect origin before forwarding:
83-
84-```go
85-localX := msg.X - layout.pane.Min.X
86-localY := msg.Y - layout.pane.Min.Y
87-```
88-
89-### 4.3 Routing Priority
90-
91-Process mouse events in this order:
92-
93-1. **Dialogs/overlays** — if open, they consume all mouse events
94-2. **Divider drag** — if resizing, motion goes to resize logic
95-3. **Focus switching** — click sets focus to the clicked region
96-4. **Component dispatch** — forward (with coord translation) to the hit region
97-
98-This matches both Crush and our current approach.
99-
100-## 5. Selection Data Model
101-
102-### 5.1 Anchor + Active Pattern
103-
104-Selection is defined by two points:
105-
106-- **Anchor**: where the selection started (mouse down, or cursor position when
107- shift was first held)
108-- **Active**: where the selection currently extends to (mouse drag position, or
109- current cursor position while shift is held)
110-
111-The anchor is fixed; the active point moves. This lets backward selection
112-(dragging up/left) work naturally.
113-
114-```go
115-type selPos struct{ row, col int }
116-
117-type selection struct {
118- anchor selPos
119- active selPos
120-}
121-```
122-
123-To get the ordered range:
124-
125-```go
126-func (s selection) ordered() (start, end selPos) {
127- if s.anchor.row > s.active.row ||
128- (s.anchor.row == s.active.row && s.anchor.col > s.active.col) {
129- return s.active, s.anchor
130- }
131- return s.anchor, s.active
132-}
133-```
134-
135-### 5.2 Valid Selection Check
136-
137-A selection is "empty" when anchor == active. Only render highlight and allow
138-copy when they differ.
139-
140-### 5.3 Clearing Selection
141-
142-Clear on:
143-- Any non-shift cursor movement (arrows, home, end, pgup, pgdown)
144-- Click (press) without drag
145-- Edit operations (typing, backspace, delete, paste)
146-- Explicit copy (Ctrl+Shift+C) — optional, some editors keep it
147-
148-Do NOT clear on:
149-- Mouse motion during drag
150-- Shift+movement keys
151-- Scroll (wheel)
152-
153-## 6. Mouse Selection Flow
154-
155-### 6.1 Press → Drag → Release
156-
157-```
158-Press: Set anchor = active = screenToPos(x, y). Set mouseDown = true.
159-Motion: If mouseDown, update active = screenToPos(x, y).
160-Release: Set mouseDown = false. Keep selection visible.
161-```
162-
163-Crush does NOT auto-copy on release. It waits for an explicit copy action
164-(keyboard shortcut or delayed auto-copy after double-click timeout). This
165-prevents accidental clipboard overwrites during casual clicking.
166-
167-### 6.2 Click Detection (No Drag)
168-
169-If press and release happen at the same position (anchor == active after
170-release), treat it as a click, not a selection. Clear any existing selection
171-and handle the click action (e.g., position cursor, open file link).
172-
173-### 6.3 Double-Click / Triple-Click
174-
175-Crush implements multi-click via timing + spatial tolerance:
176-
177-```go
178-const (
179- doubleClickThreshold = 400 * time.Millisecond
180- clickTolerance = 2 // pixels
181-)
182-```
183-
184-On click, check if the previous click was within threshold and tolerance:
185-- **Double-click**: select word at cursor (using Unicode word boundaries)
186-- **Triple-click**: select entire line
187-
188-Track `lastClickTime`, `lastClickX`, `lastClickY`, `clickCount`.
189-
190-### 6.4 Delayed Single-Click
191-
192-Problem: a single click should position the cursor, but the first click of a
193-double-click should NOT trigger single-click behavior.
194-
195-Solution: on single click, schedule a delayed action after `doubleClickThreshold`.
196-Increment a `pendingClickID`. If a double-click arrives before the delay fires,
197-the ID won't match and the pending action is discarded.
198-
199-### 6.5 Auto-Scroll During Drag
200-
201-When dragging near viewport edges, scroll the content:
202-
203-```go
204-case tea.MouseActionMotion:
205- if msg.Y <= 0 {
206- scrollUp(1)
207- } else if msg.Y >= viewportHeight-1 {
208- scrollDown(1)
209- }
210-```
211-
212-This lets the user drag-select beyond the visible area.
213-
214-## 7. Keyboard Selection (Editors)
215-
216-Keyboard selection uses the same anchor+active model:
217-
218-- **Start selection**: On any shift+movement key, if no selection exists, set
219- anchor = current cursor position. Then move cursor. Set active = new cursor.
220-- **Extend selection**: On shift+movement with existing selection, just move
221- cursor and update active. Anchor stays put.
222-- **Clear selection**: On any non-shift movement or edit, clear the selection.
223-
224-Supported shift+key combinations:
225-
226-| Key | Action |
227-|-----------------|---------------------------|
228-| `shift+left` | Extend selection left 1 |
229-| `shift+right` | Extend selection right 1 |
230-| `shift+up` | Extend selection up 1 row |
231-| `shift+down` | Extend selection down 1 |
232-| `shift+home` | Extend to line start |
233-| `shift+end` | Extend to line end |
234-| `shift+pgup` | Extend up by page |
235-| `shift+pgdown` | Extend down by page |
236-
237-## 8. Clipboard
238-
239-### 8.1 Dual Write for Compatibility
240-
241-Use both OSC 52 and native clipboard for writes:
242-
243-```go
244-func CopyToClipboard(text string) tea.Cmd {
245- return tea.Sequence(
246- tea.SetClipboard(text), // OSC 52 (works through SSH/tmux)
247- func() tea.Msg {
248- _ = clipboard.WriteAll(text) // Native OS clipboard
249- return nil
250- },
251- )
252-}
253-```
254-
255-`tea.SetClipboard()` sends an OSC 52 escape sequence. Many terminals support
256-it, and it works through SSH tunnels and tmux (if configured). The native
257-clipboard call (`github.com/atotto/clipboard`) covers local-only terminals.
258-
259-### 8.2 Copy Trigger
260-
261-Ctrl+Shift+C (not Ctrl+C, which should remain quit/cancel). The top-level
262-handler checks which component has a selection and copies from it.
263-
264-### 8.3 Paste Trigger
265-
266-Ctrl+Shift+V. Read from native clipboard and insert at cursor.
267-
268-## 9. Highlight Rendering
269-
270-### 9.1 Cell-Level Approach (Crush)
271-
272-Crush uses `ultraviolet.ScreenBuffer` — a cell grid where each cell has content,
273-foreground, background, and attributes. Highlighting replaces cell styles in the
274-selected range. This gives perfect per-character accuracy but requires the UV
275-library.
276-
277-### 9.2 ANSI String Approach (Our Stack)
278-
279-Without UV, we work with ANSI-styled strings. To highlight a region within a
280-rendered line:
281-
282-1. Determine which characters fall within the selection range
283-2. Split the line into before / selected / after segments
284-3. Strip existing background from the selected segment
285-4. Apply the selection background style
286-5. Reassemble
287-
288-For syntax-highlighted content, use `ansi.Cut(hlString, start, end)` to extract
289-ANSI substrings at character boundaries, then wrap the selected portion in the
290-highlight style.
291-
292-### 9.3 Selection Style
293-
294-Define a visible but not jarring selection background:
295-
296-```go
297-Selection: lipgloss.NewStyle().Background(lipgloss.Color("#264f78"))
298-```
299-
300-Dark blue (#264f78) is the VS Code default and works well on dark backgrounds.
301-The current `#111111` is too subtle — almost invisible.
302-
303-### 9.4 Per-Row Intersection
304-
305-For each visual row during render, compute the intersection with the selection
306-range:
307-
308-```go
309-// selStart, selEnd are in buffer coordinates (row, col)
310-// vr.bufRow is this visual row's buffer line
311-// vr.segStart, vr.segEnd are the rune range of this segment
312-
313-if vr.bufRow < selStart.row || vr.bufRow > selEnd.row {
314- // No selection on this row
315-} else {
316- colStart := 0
317- if vr.bufRow == selStart.row { colStart = selStart.col - vr.segStart }
318- colEnd := segLen
319- if vr.bufRow == selEnd.row { colEnd = selEnd.col - vr.segStart }
320- // Clamp to segment bounds, then render highlight
321-}
322-```
323-
324-## 10. Cross-Component Selection
325-
326-Our app has 3 selectable regions: editor, conversation, input. Only one can
327-have an active selection at a time. When a mouse press or shift+key starts a
328-selection in one region, clear any selection in the others.
329-
330-The top-level model owns this coordination:
331-
332-```go
333-func (m *Model) clearAllSelections() {
334- m.editor.ClearSelection()
335- m.agentInput.ClearSelection()
336- m.convSelection = nil
337-}
338-```
339-
340-On Ctrl+Shift+C, check each component in priority order and copy from the
341-first one with an active selection.
342-
343-## 11. Common Pitfalls
344-
345-1. **Auto-copy on mouse release**: Don't. It overwrites the clipboard on every
346- casual click-drag. Copy should be explicit (Ctrl+Shift+C) or delayed.
347-
348-2. **Clearing selection on release**: Don't. The user expects to see what they
349- selected, then press a key to copy. Only clear on next click or edit.
350-
351-3. **Not translating coordinates**: Mouse events use screen-absolute positions.
352- Always subtract the component's layout origin before forwarding.
353-
354-4. **Selection during scroll**: Mouse wheel should NOT affect selection state.
355- The selection anchors are in buffer coordinates, not screen coordinates, so
356- they survive scrolling.
357-
358-5. **Forgetting to clamp**: Selection endpoints must be clamped to valid buffer
359- ranges. Off-by-one errors here cause panics or garbled rendering.
360-
361-6. **Highlight on trailing whitespace**: Crush explicitly avoids highlighting
362- trailing whitespace on each line. Track `lastContentX` and only highlight
363- up to that point. This looks much cleaner.