chat.go

  1package model
  2
  3import (
  4	"strings"
  5	"time"
  6
  7	tea "charm.land/bubbletea/v2"
  8	"charm.land/lipgloss/v2"
  9	"github.com/charmbracelet/crush/internal/ui/anim"
 10	"github.com/charmbracelet/crush/internal/ui/chat"
 11	"github.com/charmbracelet/crush/internal/ui/common"
 12	"github.com/charmbracelet/crush/internal/ui/list"
 13	uv "github.com/charmbracelet/ultraviolet"
 14	"github.com/charmbracelet/x/ansi"
 15	"github.com/clipperhouse/displaywidth"
 16	"github.com/clipperhouse/uax29/v2/words"
 17)
 18
 19// Constants for multi-click detection.
 20const (
 21	doubleClickThreshold = 400 * time.Millisecond // 0.4s is typical double-click threshold
 22	clickTolerance       = 2                      // x,y tolerance for double/tripple click
 23)
 24
 25// DelayedClickMsg is sent after the double-click threshold to trigger a
 26// single-click action (like expansion) if no double-click occurred.
 27type DelayedClickMsg struct {
 28	ClickID int
 29	ItemIdx int
 30	X, Y    int
 31}
 32
 33// Chat represents the chat UI model that handles chat interactions and
 34// messages.
 35type Chat struct {
 36	com      *common.Common
 37	list     *list.List
 38	idInxMap map[string]int // Map of message IDs to their indices in the list
 39
 40	// Animation visibility optimization: track animations paused due to items
 41	// being scrolled out of view. When items become visible again, their
 42	// animations are restarted.
 43	pausedAnimations map[string]struct{}
 44
 45	// Mouse state
 46	mouseDown     bool
 47	mouseDownItem int // Item index where mouse was pressed
 48	mouseDownX    int // X position in item content (character offset)
 49	mouseDownY    int // Y position in item (line offset)
 50	mouseDragItem int // Current item index being dragged over
 51	mouseDragX    int // Current X in item content
 52	mouseDragY    int // Current Y in item
 53
 54	// Click tracking for double/triple clicks
 55	lastClickTime time.Time
 56	lastClickX    int
 57	lastClickY    int
 58	clickCount    int
 59
 60	// Pending single click action (delayed to detect double-click)
 61	pendingClickID int // Incremented on each click to invalidate old pending clicks
 62}
 63
 64// NewChat creates a new instance of [Chat] that handles chat interactions and
 65// messages.
 66func NewChat(com *common.Common) *Chat {
 67	c := &Chat{
 68		com:              com,
 69		idInxMap:         make(map[string]int),
 70		pausedAnimations: make(map[string]struct{}),
 71	}
 72	l := list.NewList()
 73	l.SetGap(1)
 74	l.RegisterRenderCallback(c.applyHighlightRange)
 75	l.RegisterRenderCallback(list.FocusedRenderCallback(l))
 76	c.list = l
 77	c.mouseDownItem = -1
 78	c.mouseDragItem = -1
 79	return c
 80}
 81
 82// Height returns the height of the chat view port.
 83func (m *Chat) Height() int {
 84	return m.list.Height()
 85}
 86
 87// Draw renders the chat UI component to the screen and the given area.
 88func (m *Chat) Draw(scr uv.Screen, area uv.Rectangle) {
 89	uv.NewStyledString(m.list.Render()).Draw(scr, area)
 90}
 91
 92// SetSize sets the size of the chat view port.
 93func (m *Chat) SetSize(width, height int) {
 94	m.list.SetSize(width, height)
 95	// Anchor to bottom if we were at the bottom.
 96	if m.list.AtBottom() {
 97		m.list.ScrollToBottom()
 98	}
 99}
100
101// Len returns the number of items in the chat list.
102func (m *Chat) Len() int {
103	return m.list.Len()
104}
105
106// SetMessages sets the chat messages to the provided list of message items.
107func (m *Chat) SetMessages(msgs ...chat.MessageItem) {
108	m.idInxMap = make(map[string]int)
109	m.pausedAnimations = make(map[string]struct{})
110
111	items := make([]list.Item, len(msgs))
112	for i, msg := range msgs {
113		m.idInxMap[msg.ID()] = i
114		// Register nested tool IDs for tools that contain nested tools.
115		if container, ok := msg.(chat.NestedToolContainer); ok {
116			for _, nested := range container.NestedTools() {
117				m.idInxMap[nested.ID()] = i
118			}
119		}
120		items[i] = msg
121	}
122	m.list.SetItems(items...)
123	m.list.ScrollToBottom()
124}
125
126// AppendMessages appends a new message item to the chat list.
127func (m *Chat) AppendMessages(msgs ...chat.MessageItem) {
128	items := make([]list.Item, len(msgs))
129	indexOffset := m.list.Len()
130	for i, msg := range msgs {
131		m.idInxMap[msg.ID()] = indexOffset + i
132		// Register nested tool IDs for tools that contain nested tools.
133		if container, ok := msg.(chat.NestedToolContainer); ok {
134			for _, nested := range container.NestedTools() {
135				m.idInxMap[nested.ID()] = indexOffset + i
136			}
137		}
138		items[i] = msg
139	}
140	m.list.AppendItems(items...)
141}
142
143// UpdateNestedToolIDs updates the ID map for nested tools within a container.
144// Call this after modifying nested tools to ensure animations work correctly.
145func (m *Chat) UpdateNestedToolIDs(containerID string) {
146	idx, ok := m.idInxMap[containerID]
147	if !ok {
148		return
149	}
150
151	item, ok := m.list.ItemAt(idx).(chat.MessageItem)
152	if !ok {
153		return
154	}
155
156	container, ok := item.(chat.NestedToolContainer)
157	if !ok {
158		return
159	}
160
161	// Register all nested tool IDs to point to the container's index.
162	for _, nested := range container.NestedTools() {
163		m.idInxMap[nested.ID()] = idx
164	}
165}
166
167// Animate animates items in the chat list. Only propagates animation messages
168// to visible items to save CPU. When items are not visible, their animation ID
169// is tracked so it can be restarted when they become visible again.
170func (m *Chat) Animate(msg anim.StepMsg) tea.Cmd {
171	idx, ok := m.idInxMap[msg.ID]
172	if !ok {
173		return nil
174	}
175
176	animatable, ok := m.list.ItemAt(idx).(chat.Animatable)
177	if !ok {
178		return nil
179	}
180
181	// Check if item is currently visible.
182	startIdx, endIdx := m.list.VisibleItemIndices()
183	isVisible := idx >= startIdx && idx <= endIdx
184
185	if !isVisible {
186		// Item not visible - pause animation by not propagating.
187		// Track it so we can restart when it becomes visible.
188		m.pausedAnimations[msg.ID] = struct{}{}
189		return nil
190	}
191
192	// Item is visible - remove from paused set and animate.
193	delete(m.pausedAnimations, msg.ID)
194	return animatable.Animate(msg)
195}
196
197// RestartPausedVisibleAnimations restarts animations for items that were paused
198// due to being scrolled out of view but are now visible again.
199func (m *Chat) RestartPausedVisibleAnimations() tea.Cmd {
200	if len(m.pausedAnimations) == 0 {
201		return nil
202	}
203
204	startIdx, endIdx := m.list.VisibleItemIndices()
205	var cmds []tea.Cmd
206
207	for id := range m.pausedAnimations {
208		idx, ok := m.idInxMap[id]
209		if !ok {
210			// Item no longer exists.
211			delete(m.pausedAnimations, id)
212			continue
213		}
214
215		if idx >= startIdx && idx <= endIdx {
216			// Item is now visible - restart its animation.
217			if animatable, ok := m.list.ItemAt(idx).(chat.Animatable); ok {
218				if cmd := animatable.StartAnimation(); cmd != nil {
219					cmds = append(cmds, cmd)
220				}
221			}
222			delete(m.pausedAnimations, id)
223		}
224	}
225
226	if len(cmds) == 0 {
227		return nil
228	}
229	return tea.Batch(cmds...)
230}
231
232// Focus sets the focus state of the chat component.
233func (m *Chat) Focus() {
234	m.list.Focus()
235}
236
237// Blur removes the focus state from the chat component.
238func (m *Chat) Blur() {
239	m.list.Blur()
240}
241
242// ScrollToTopAndAnimate scrolls the chat view to the top and returns a command to restart
243// any paused animations that are now visible.
244func (m *Chat) ScrollToTopAndAnimate() tea.Cmd {
245	m.list.ScrollToTop()
246	return m.RestartPausedVisibleAnimations()
247}
248
249// ScrollToBottomAndAnimate scrolls the chat view to the bottom and returns a command to
250// restart any paused animations that are now visible.
251func (m *Chat) ScrollToBottomAndAnimate() tea.Cmd {
252	m.list.ScrollToBottom()
253	return m.RestartPausedVisibleAnimations()
254}
255
256// ScrollByAndAnimate scrolls the chat view by the given number of line deltas and returns
257// a command to restart any paused animations that are now visible.
258func (m *Chat) ScrollByAndAnimate(lines int) tea.Cmd {
259	m.list.ScrollBy(lines)
260	return m.RestartPausedVisibleAnimations()
261}
262
263// ScrollToSelectedAndAnimate scrolls the chat view to the selected item and returns a
264// command to restart any paused animations that are now visible.
265func (m *Chat) ScrollToSelectedAndAnimate() tea.Cmd {
266	m.list.ScrollToSelected()
267	return m.RestartPausedVisibleAnimations()
268}
269
270// SelectedItemInView returns whether the selected item is currently in view.
271func (m *Chat) SelectedItemInView() bool {
272	return m.list.SelectedItemInView()
273}
274
275func (m *Chat) isSelectable(index int) bool {
276	item := m.list.ItemAt(index)
277	if item == nil {
278		return false
279	}
280	_, ok := item.(list.Focusable)
281	return ok
282}
283
284// SetSelected sets the selected message index in the chat list.
285func (m *Chat) SetSelected(index int) {
286	m.list.SetSelected(index)
287	if index < 0 || index >= m.list.Len() {
288		return
289	}
290	for {
291		if m.isSelectable(m.list.Selected()) {
292			return
293		}
294		if m.list.SelectNext() {
295			continue
296		}
297		// If we're at the end and the last item isn't selectable, walk backwards
298		// to find the nearest selectable item.
299		for {
300			if !m.list.SelectPrev() {
301				return
302			}
303			if m.isSelectable(m.list.Selected()) {
304				return
305			}
306		}
307	}
308}
309
310// SelectPrev selects the previous message in the chat list.
311func (m *Chat) SelectPrev() {
312	for {
313		if !m.list.SelectPrev() {
314			return
315		}
316		if m.isSelectable(m.list.Selected()) {
317			return
318		}
319	}
320}
321
322// SelectNext selects the next message in the chat list.
323func (m *Chat) SelectNext() {
324	for {
325		if !m.list.SelectNext() {
326			return
327		}
328		if m.isSelectable(m.list.Selected()) {
329			return
330		}
331	}
332}
333
334// SelectFirst selects the first message in the chat list.
335func (m *Chat) SelectFirst() {
336	if !m.list.SelectFirst() {
337		return
338	}
339	if m.isSelectable(m.list.Selected()) {
340		return
341	}
342	for {
343		if !m.list.SelectNext() {
344			return
345		}
346		if m.isSelectable(m.list.Selected()) {
347			return
348		}
349	}
350}
351
352// SelectLast selects the last message in the chat list.
353func (m *Chat) SelectLast() {
354	if !m.list.SelectLast() {
355		return
356	}
357	if m.isSelectable(m.list.Selected()) {
358		return
359	}
360	for {
361		if !m.list.SelectPrev() {
362			return
363		}
364		if m.isSelectable(m.list.Selected()) {
365			return
366		}
367	}
368}
369
370// SelectFirstInView selects the first message currently in view.
371func (m *Chat) SelectFirstInView() {
372	startIdx, endIdx := m.list.VisibleItemIndices()
373	for i := startIdx; i <= endIdx; i++ {
374		if m.isSelectable(i) {
375			m.list.SetSelected(i)
376			return
377		}
378	}
379}
380
381// SelectLastInView selects the last message currently in view.
382func (m *Chat) SelectLastInView() {
383	startIdx, endIdx := m.list.VisibleItemIndices()
384	for i := endIdx; i >= startIdx; i-- {
385		if m.isSelectable(i) {
386			m.list.SetSelected(i)
387			return
388		}
389	}
390}
391
392// ClearMessages removes all messages from the chat list.
393func (m *Chat) ClearMessages() {
394	m.idInxMap = make(map[string]int)
395	m.pausedAnimations = make(map[string]struct{})
396	m.list.SetItems()
397	m.ClearMouse()
398}
399
400// RemoveMessage removes a message from the chat list by its ID.
401func (m *Chat) RemoveMessage(id string) {
402	idx, ok := m.idInxMap[id]
403	if !ok {
404		return
405	}
406
407	// Remove from list
408	m.list.RemoveItem(idx)
409
410	// Remove from index map
411	delete(m.idInxMap, id)
412
413	// Rebuild index map for all items after the removed one
414	for i := idx; i < m.list.Len(); i++ {
415		if item, ok := m.list.ItemAt(i).(chat.MessageItem); ok {
416			m.idInxMap[item.ID()] = i
417		}
418	}
419
420	// Clean up any paused animations for this message
421	delete(m.pausedAnimations, id)
422}
423
424// MessageItem returns the message item with the given ID, or nil if not found.
425func (m *Chat) MessageItem(id string) chat.MessageItem {
426	idx, ok := m.idInxMap[id]
427	if !ok {
428		return nil
429	}
430	item, ok := m.list.ItemAt(idx).(chat.MessageItem)
431	if !ok {
432		return nil
433	}
434	return item
435}
436
437// ToggleExpandedSelectedItem expands the selected message item if it is expandable.
438func (m *Chat) ToggleExpandedSelectedItem() {
439	if expandable, ok := m.list.SelectedItem().(chat.Expandable); ok {
440		expandable.ToggleExpanded()
441	}
442}
443
444// HandleKeyMsg handles key events for the chat component.
445func (m *Chat) HandleKeyMsg(key tea.KeyMsg) (bool, tea.Cmd) {
446	if m.list.Focused() {
447		if handler, ok := m.list.SelectedItem().(chat.KeyEventHandler); ok {
448			return handler.HandleKeyEvent(key)
449		}
450	}
451	return false, nil
452}
453
454// HandleMouseDown handles mouse down events for the chat component.
455// It detects single, double, and triple clicks for text selection.
456// Returns whether the click was handled and an optional command for delayed
457// single-click actions.
458func (m *Chat) HandleMouseDown(x, y int) (bool, tea.Cmd) {
459	if m.list.Len() == 0 {
460		return false, nil
461	}
462
463	itemIdx, itemY := m.list.ItemIndexAtPosition(x, y)
464	if itemIdx < 0 {
465		return false, nil
466	}
467	if !m.isSelectable(itemIdx) {
468		return false, nil
469	}
470
471	// Increment pending click ID to invalidate any previous pending clicks.
472	m.pendingClickID++
473	clickID := m.pendingClickID
474
475	// Detect multi-click (double/triple)
476	now := time.Now()
477	if now.Sub(m.lastClickTime) <= doubleClickThreshold &&
478		abs(x-m.lastClickX) <= clickTolerance &&
479		abs(y-m.lastClickY) <= clickTolerance {
480		m.clickCount++
481	} else {
482		m.clickCount = 1
483	}
484	m.lastClickTime = now
485	m.lastClickX = x
486	m.lastClickY = y
487
488	// Select the item that was clicked
489	m.list.SetSelected(itemIdx)
490
491	var cmd tea.Cmd
492
493	switch m.clickCount {
494	case 1:
495		// Single click - start selection and schedule delayed click action.
496		m.mouseDown = true
497		m.mouseDownItem = itemIdx
498		m.mouseDownX = x
499		m.mouseDownY = itemY
500		m.mouseDragItem = itemIdx
501		m.mouseDragX = x
502		m.mouseDragY = itemY
503
504		// Schedule delayed click action (e.g., expansion) after a short delay.
505		// If a double-click occurs, the clickID will be invalidated.
506		cmd = tea.Tick(doubleClickThreshold, func(t time.Time) tea.Msg {
507			return DelayedClickMsg{
508				ClickID: clickID,
509				ItemIdx: itemIdx,
510				X:       x,
511				Y:       itemY,
512			}
513		})
514	case 2:
515		// Double click - select word (no delayed action)
516		m.selectWord(itemIdx, x, itemY)
517	case 3:
518		// Triple click - select line (no delayed action)
519		m.selectLine(itemIdx, itemY)
520		m.clickCount = 0 // Reset after triple click
521	}
522
523	return true, cmd
524}
525
526// HandleDelayedClick handles a delayed single-click action (like expansion).
527// It only executes if the click ID matches (i.e., no double-click occurred)
528// and no text selection was made (drag to select).
529func (m *Chat) HandleDelayedClick(msg DelayedClickMsg) bool {
530	// Ignore if this click was superseded by a newer click (double/triple).
531	if msg.ClickID != m.pendingClickID {
532		return false
533	}
534
535	// Don't expand if user dragged to select text.
536	if m.HasHighlight() {
537		return false
538	}
539
540	// Execute the click action (e.g., expansion).
541	if clickable, ok := m.list.SelectedItem().(list.MouseClickable); ok {
542		return clickable.HandleMouseClick(ansi.MouseButton1, msg.X, msg.Y)
543	}
544
545	return false
546}
547
548// HandleMouseUp handles mouse up events for the chat component.
549func (m *Chat) HandleMouseUp(x, y int) bool {
550	if !m.mouseDown {
551		return false
552	}
553
554	m.mouseDown = false
555	return true
556}
557
558// HandleMouseDrag handles mouse drag events for the chat component.
559func (m *Chat) HandleMouseDrag(x, y int) bool {
560	if !m.mouseDown {
561		return false
562	}
563
564	if m.list.Len() == 0 {
565		return false
566	}
567
568	itemIdx, itemY := m.list.ItemIndexAtPosition(x, y)
569	if itemIdx < 0 {
570		return false
571	}
572
573	m.mouseDragItem = itemIdx
574	m.mouseDragX = x
575	m.mouseDragY = itemY
576
577	return true
578}
579
580// HasHighlight returns whether there is currently highlighted content.
581func (m *Chat) HasHighlight() bool {
582	startItemIdx, startLine, startCol, endItemIdx, endLine, endCol := m.getHighlightRange()
583	return startItemIdx >= 0 && endItemIdx >= 0 && (startLine != endLine || startCol != endCol)
584}
585
586// HighlightContent returns the currently highlighted content based on the mouse
587// selection. It returns an empty string if no content is highlighted.
588func (m *Chat) HighlightContent() string {
589	startItemIdx, startLine, startCol, endItemIdx, endLine, endCol := m.getHighlightRange()
590	if startItemIdx < 0 || endItemIdx < 0 || startLine == endLine && startCol == endCol {
591		return ""
592	}
593
594	var sb strings.Builder
595	for i := startItemIdx; i <= endItemIdx; i++ {
596		item := m.list.ItemAt(i)
597		if hi, ok := item.(list.Highlightable); ok {
598			startLine, startCol, endLine, endCol := hi.Highlight()
599			listWidth := m.list.Width()
600			var rendered string
601			if rr, ok := item.(list.RawRenderable); ok {
602				rendered = rr.RawRender(listWidth)
603			} else {
604				rendered = item.Render(listWidth)
605			}
606			sb.WriteString(list.HighlightContent(
607				rendered,
608				uv.Rect(0, 0, listWidth, lipgloss.Height(rendered)),
609				startLine,
610				startCol,
611				endLine,
612				endCol,
613			))
614			sb.WriteString(strings.Repeat("\n", m.list.Gap()))
615		}
616	}
617
618	return strings.TrimSpace(sb.String())
619}
620
621// ClearMouse clears the current mouse interaction state.
622func (m *Chat) ClearMouse() {
623	m.mouseDown = false
624	m.mouseDownItem = -1
625	m.mouseDragItem = -1
626	m.lastClickTime = time.Time{}
627	m.lastClickX = 0
628	m.lastClickY = 0
629	m.clickCount = 0
630	m.pendingClickID++ // Invalidate any pending delayed click
631}
632
633// applyHighlightRange applies the current highlight range to the chat items.
634func (m *Chat) applyHighlightRange(idx, selectedIdx int, item list.Item) list.Item {
635	if hi, ok := item.(list.Highlightable); ok {
636		// Apply highlight
637		startItemIdx, startLine, startCol, endItemIdx, endLine, endCol := m.getHighlightRange()
638		sLine, sCol, eLine, eCol := -1, -1, -1, -1
639		if idx >= startItemIdx && idx <= endItemIdx {
640			if idx == startItemIdx && idx == endItemIdx {
641				// Single item selection
642				sLine = startLine
643				sCol = startCol
644				eLine = endLine
645				eCol = endCol
646			} else if idx == startItemIdx {
647				// First item - from start position to end of item
648				sLine = startLine
649				sCol = startCol
650				eLine = -1
651				eCol = -1
652			} else if idx == endItemIdx {
653				// Last item - from start of item to end position
654				sLine = 0
655				sCol = 0
656				eLine = endLine
657				eCol = endCol
658			} else {
659				// Middle item - fully highlighted
660				sLine = 0
661				sCol = 0
662				eLine = -1
663				eCol = -1
664			}
665		}
666
667		hi.SetHighlight(sLine, sCol, eLine, eCol)
668		return hi.(list.Item)
669	}
670
671	return item
672}
673
674// getHighlightRange returns the current highlight range.
675func (m *Chat) getHighlightRange() (startItemIdx, startLine, startCol, endItemIdx, endLine, endCol int) {
676	if m.mouseDownItem < 0 {
677		return -1, -1, -1, -1, -1, -1
678	}
679
680	downItemIdx := m.mouseDownItem
681	dragItemIdx := m.mouseDragItem
682
683	// Determine selection direction
684	draggingDown := dragItemIdx > downItemIdx ||
685		(dragItemIdx == downItemIdx && m.mouseDragY > m.mouseDownY) ||
686		(dragItemIdx == downItemIdx && m.mouseDragY == m.mouseDownY && m.mouseDragX >= m.mouseDownX)
687
688	if draggingDown {
689		// Normal forward selection
690		startItemIdx = downItemIdx
691		startLine = m.mouseDownY
692		startCol = m.mouseDownX
693		endItemIdx = dragItemIdx
694		endLine = m.mouseDragY
695		endCol = m.mouseDragX
696	} else {
697		// Backward selection (dragging up)
698		startItemIdx = dragItemIdx
699		startLine = m.mouseDragY
700		startCol = m.mouseDragX
701		endItemIdx = downItemIdx
702		endLine = m.mouseDownY
703		endCol = m.mouseDownX
704	}
705
706	return startItemIdx, startLine, startCol, endItemIdx, endLine, endCol
707}
708
709// selectWord selects the word at the given position within an item.
710func (m *Chat) selectWord(itemIdx, x, itemY int) {
711	item := m.list.ItemAt(itemIdx)
712	if item == nil {
713		return
714	}
715
716	// Get the rendered content for this item
717	var rendered string
718	if rr, ok := item.(list.RawRenderable); ok {
719		rendered = rr.RawRender(m.list.Width())
720	} else {
721		rendered = item.Render(m.list.Width())
722	}
723
724	lines := strings.Split(rendered, "\n")
725	if itemY < 0 || itemY >= len(lines) {
726		return
727	}
728
729	// Adjust x for the item's left padding (border + padding) to get content column.
730	// The mouse x is in viewport space, but we need content space for boundary detection.
731	offset := chat.MessageLeftPaddingTotal
732	contentX := x - offset
733	if contentX < 0 {
734		contentX = 0
735	}
736
737	line := ansi.Strip(lines[itemY])
738	startCol, endCol := findWordBoundaries(line, contentX)
739	if startCol == endCol {
740		// No word found at position, fallback to single click behavior
741		m.mouseDown = true
742		m.mouseDownItem = itemIdx
743		m.mouseDownX = x
744		m.mouseDownY = itemY
745		m.mouseDragItem = itemIdx
746		m.mouseDragX = x
747		m.mouseDragY = itemY
748		return
749	}
750
751	// Set selection to the word boundaries (convert back to viewport space).
752	// Keep mouseDown true so HandleMouseUp triggers the copy.
753	m.mouseDown = true
754	m.mouseDownItem = itemIdx
755	m.mouseDownX = startCol + offset
756	m.mouseDownY = itemY
757	m.mouseDragItem = itemIdx
758	m.mouseDragX = endCol + offset
759	m.mouseDragY = itemY
760}
761
762// selectLine selects the entire line at the given position within an item.
763func (m *Chat) selectLine(itemIdx, itemY int) {
764	item := m.list.ItemAt(itemIdx)
765	if item == nil {
766		return
767	}
768
769	// Get the rendered content for this item
770	var rendered string
771	if rr, ok := item.(list.RawRenderable); ok {
772		rendered = rr.RawRender(m.list.Width())
773	} else {
774		rendered = item.Render(m.list.Width())
775	}
776
777	lines := strings.Split(rendered, "\n")
778	if itemY < 0 || itemY >= len(lines) {
779		return
780	}
781
782	// Get line length (stripped of ANSI codes) and account for padding.
783	// SetHighlight will subtract the offset, so we need to add it here.
784	offset := chat.MessageLeftPaddingTotal
785	lineLen := ansi.StringWidth(lines[itemY])
786
787	// Set selection to the entire line.
788	// Keep mouseDown true so HandleMouseUp triggers the copy.
789	m.mouseDown = true
790	m.mouseDownItem = itemIdx
791	m.mouseDownX = 0
792	m.mouseDownY = itemY
793	m.mouseDragItem = itemIdx
794	m.mouseDragX = lineLen + offset
795	m.mouseDragY = itemY
796}
797
798// findWordBoundaries finds the start and end column of the word at the given column.
799// Returns (startCol, endCol) where endCol is exclusive.
800func findWordBoundaries(line string, col int) (startCol, endCol int) {
801	if line == "" || col < 0 {
802		return 0, 0
803	}
804
805	i := displaywidth.StringGraphemes(line)
806	for i.Next() {
807	}
808
809	// Segment the line into words using UAX#29.
810	lineCol := 0 // tracks the visited column widths
811	lastCol := 0 // tracks the start of the current token
812	iter := words.FromString(line)
813	for iter.Next() {
814		token := iter.Value()
815		tokenWidth := displaywidth.String(token)
816
817		graphemeStart := lineCol
818		graphemeEnd := lineCol + tokenWidth
819		lineCol += tokenWidth
820
821		// If clicked before this token, return the previous token boundaries.
822		if col < graphemeStart {
823			return lastCol, lastCol
824		}
825
826		// Update lastCol to the end of this token for next iteration.
827		lastCol = graphemeEnd
828
829		// If clicked within this token, return its boundaries.
830		if col >= graphemeStart && col < graphemeEnd {
831			// If clicked on whitespace, return empty selection.
832			if strings.TrimSpace(token) == "" {
833				return col, col
834			}
835			return graphemeStart, graphemeEnd
836		}
837	}
838
839	return col, col
840}
841
842// abs returns the absolute value of an integer.
843func abs(x int) int {
844	if x < 0 {
845		return -x
846	}
847	return x
848}