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		m.list.ScrollToIndex(m.list.Selected())
442	}
443}
444
445// HandleKeyMsg handles key events for the chat component.
446func (m *Chat) HandleKeyMsg(key tea.KeyMsg) (bool, tea.Cmd) {
447	if m.list.Focused() {
448		if handler, ok := m.list.SelectedItem().(chat.KeyEventHandler); ok {
449			return handler.HandleKeyEvent(key)
450		}
451	}
452	return false, nil
453}
454
455// HandleMouseDown handles mouse down events for the chat component.
456// It detects single, double, and triple clicks for text selection.
457// Returns whether the click was handled and an optional command for delayed
458// single-click actions.
459func (m *Chat) HandleMouseDown(x, y int) (bool, tea.Cmd) {
460	if m.list.Len() == 0 {
461		return false, nil
462	}
463
464	itemIdx, itemY := m.list.ItemIndexAtPosition(x, y)
465	if itemIdx < 0 {
466		return false, nil
467	}
468	if !m.isSelectable(itemIdx) {
469		return false, nil
470	}
471
472	// Increment pending click ID to invalidate any previous pending clicks.
473	m.pendingClickID++
474	clickID := m.pendingClickID
475
476	// Detect multi-click (double/triple)
477	now := time.Now()
478	if now.Sub(m.lastClickTime) <= doubleClickThreshold &&
479		abs(x-m.lastClickX) <= clickTolerance &&
480		abs(y-m.lastClickY) <= clickTolerance {
481		m.clickCount++
482	} else {
483		m.clickCount = 1
484	}
485	m.lastClickTime = now
486	m.lastClickX = x
487	m.lastClickY = y
488
489	// Select the item that was clicked
490	m.list.SetSelected(itemIdx)
491
492	var cmd tea.Cmd
493
494	switch m.clickCount {
495	case 1:
496		// Single click - start selection and schedule delayed click action.
497		m.mouseDown = true
498		m.mouseDownItem = itemIdx
499		m.mouseDownX = x
500		m.mouseDownY = itemY
501		m.mouseDragItem = itemIdx
502		m.mouseDragX = x
503		m.mouseDragY = itemY
504
505		// Schedule delayed click action (e.g., expansion) after a short delay.
506		// If a double-click occurs, the clickID will be invalidated.
507		cmd = tea.Tick(doubleClickThreshold, func(t time.Time) tea.Msg {
508			return DelayedClickMsg{
509				ClickID: clickID,
510				ItemIdx: itemIdx,
511				X:       x,
512				Y:       itemY,
513			}
514		})
515	case 2:
516		// Double click - select word (no delayed action)
517		m.selectWord(itemIdx, x, itemY)
518	case 3:
519		// Triple click - select line (no delayed action)
520		m.selectLine(itemIdx, itemY)
521		m.clickCount = 0 // Reset after triple click
522	}
523
524	return true, cmd
525}
526
527// HandleDelayedClick handles a delayed single-click action (like expansion).
528// It only executes if the click ID matches (i.e., no double-click occurred)
529// and no text selection was made (drag to select).
530func (m *Chat) HandleDelayedClick(msg DelayedClickMsg) bool {
531	// Ignore if this click was superseded by a newer click (double/triple).
532	if msg.ClickID != m.pendingClickID {
533		return false
534	}
535
536	// Don't expand if user dragged to select text.
537	if m.HasHighlight() {
538		return false
539	}
540
541	// Execute the click action (e.g., expansion).
542	selectedItem := m.list.SelectedItem()
543	if clickable, ok := selectedItem.(list.MouseClickable); ok {
544		handled := clickable.HandleMouseClick(ansi.MouseButton1, msg.X, msg.Y)
545		// Toggle expansion if applicable.
546		if expandable, ok := selectedItem.(chat.Expandable); ok {
547			expandable.ToggleExpanded()
548		}
549		m.list.ScrollToIndex(m.list.Selected())
550		return handled
551	}
552
553	return false
554}
555
556// HandleMouseUp handles mouse up events for the chat component.
557func (m *Chat) HandleMouseUp(x, y int) bool {
558	if !m.mouseDown {
559		return false
560	}
561
562	m.mouseDown = false
563	return true
564}
565
566// HandleMouseDrag handles mouse drag events for the chat component.
567func (m *Chat) HandleMouseDrag(x, y int) bool {
568	if !m.mouseDown {
569		return false
570	}
571
572	if m.list.Len() == 0 {
573		return false
574	}
575
576	itemIdx, itemY := m.list.ItemIndexAtPosition(x, y)
577	if itemIdx < 0 {
578		return false
579	}
580
581	m.mouseDragItem = itemIdx
582	m.mouseDragX = x
583	m.mouseDragY = itemY
584
585	return true
586}
587
588// HasHighlight returns whether there is currently highlighted content.
589func (m *Chat) HasHighlight() bool {
590	startItemIdx, startLine, startCol, endItemIdx, endLine, endCol := m.getHighlightRange()
591	return startItemIdx >= 0 && endItemIdx >= 0 && (startLine != endLine || startCol != endCol)
592}
593
594// HighlightContent returns the currently highlighted content based on the mouse
595// selection. It returns an empty string if no content is highlighted.
596func (m *Chat) HighlightContent() string {
597	startItemIdx, startLine, startCol, endItemIdx, endLine, endCol := m.getHighlightRange()
598	if startItemIdx < 0 || endItemIdx < 0 || startLine == endLine && startCol == endCol {
599		return ""
600	}
601
602	var sb strings.Builder
603	for i := startItemIdx; i <= endItemIdx; i++ {
604		item := m.list.ItemAt(i)
605		if hi, ok := item.(list.Highlightable); ok {
606			startLine, startCol, endLine, endCol := hi.Highlight()
607			listWidth := m.list.Width()
608			var rendered string
609			if rr, ok := item.(list.RawRenderable); ok {
610				rendered = rr.RawRender(listWidth)
611			} else {
612				rendered = item.Render(listWidth)
613			}
614			sb.WriteString(list.HighlightContent(
615				rendered,
616				uv.Rect(0, 0, listWidth, lipgloss.Height(rendered)),
617				startLine,
618				startCol,
619				endLine,
620				endCol,
621			))
622			sb.WriteString(strings.Repeat("\n", m.list.Gap()))
623		}
624	}
625
626	return strings.TrimSpace(sb.String())
627}
628
629// ClearMouse clears the current mouse interaction state.
630func (m *Chat) ClearMouse() {
631	m.mouseDown = false
632	m.mouseDownItem = -1
633	m.mouseDragItem = -1
634	m.lastClickTime = time.Time{}
635	m.lastClickX = 0
636	m.lastClickY = 0
637	m.clickCount = 0
638	m.pendingClickID++ // Invalidate any pending delayed click
639}
640
641// applyHighlightRange applies the current highlight range to the chat items.
642func (m *Chat) applyHighlightRange(idx, selectedIdx int, item list.Item) list.Item {
643	if hi, ok := item.(list.Highlightable); ok {
644		// Apply highlight
645		startItemIdx, startLine, startCol, endItemIdx, endLine, endCol := m.getHighlightRange()
646		sLine, sCol, eLine, eCol := -1, -1, -1, -1
647		if idx >= startItemIdx && idx <= endItemIdx {
648			if idx == startItemIdx && idx == endItemIdx {
649				// Single item selection
650				sLine = startLine
651				sCol = startCol
652				eLine = endLine
653				eCol = endCol
654			} else if idx == startItemIdx {
655				// First item - from start position to end of item
656				sLine = startLine
657				sCol = startCol
658				eLine = -1
659				eCol = -1
660			} else if idx == endItemIdx {
661				// Last item - from start of item to end position
662				sLine = 0
663				sCol = 0
664				eLine = endLine
665				eCol = endCol
666			} else {
667				// Middle item - fully highlighted
668				sLine = 0
669				sCol = 0
670				eLine = -1
671				eCol = -1
672			}
673		}
674
675		hi.SetHighlight(sLine, sCol, eLine, eCol)
676		return hi.(list.Item)
677	}
678
679	return item
680}
681
682// getHighlightRange returns the current highlight range.
683func (m *Chat) getHighlightRange() (startItemIdx, startLine, startCol, endItemIdx, endLine, endCol int) {
684	if m.mouseDownItem < 0 {
685		return -1, -1, -1, -1, -1, -1
686	}
687
688	downItemIdx := m.mouseDownItem
689	dragItemIdx := m.mouseDragItem
690
691	// Determine selection direction
692	draggingDown := dragItemIdx > downItemIdx ||
693		(dragItemIdx == downItemIdx && m.mouseDragY > m.mouseDownY) ||
694		(dragItemIdx == downItemIdx && m.mouseDragY == m.mouseDownY && m.mouseDragX >= m.mouseDownX)
695
696	if draggingDown {
697		// Normal forward selection
698		startItemIdx = downItemIdx
699		startLine = m.mouseDownY
700		startCol = m.mouseDownX
701		endItemIdx = dragItemIdx
702		endLine = m.mouseDragY
703		endCol = m.mouseDragX
704	} else {
705		// Backward selection (dragging up)
706		startItemIdx = dragItemIdx
707		startLine = m.mouseDragY
708		startCol = m.mouseDragX
709		endItemIdx = downItemIdx
710		endLine = m.mouseDownY
711		endCol = m.mouseDownX
712	}
713
714	return startItemIdx, startLine, startCol, endItemIdx, endLine, endCol
715}
716
717// selectWord selects the word at the given position within an item.
718func (m *Chat) selectWord(itemIdx, x, itemY int) {
719	item := m.list.ItemAt(itemIdx)
720	if item == nil {
721		return
722	}
723
724	// Get the rendered content for this item
725	var rendered string
726	if rr, ok := item.(list.RawRenderable); ok {
727		rendered = rr.RawRender(m.list.Width())
728	} else {
729		rendered = item.Render(m.list.Width())
730	}
731
732	lines := strings.Split(rendered, "\n")
733	if itemY < 0 || itemY >= len(lines) {
734		return
735	}
736
737	// Adjust x for the item's left padding (border + padding) to get content column.
738	// The mouse x is in viewport space, but we need content space for boundary detection.
739	offset := chat.MessageLeftPaddingTotal
740	contentX := x - offset
741	if contentX < 0 {
742		contentX = 0
743	}
744
745	line := ansi.Strip(lines[itemY])
746	startCol, endCol := findWordBoundaries(line, contentX)
747	if startCol == endCol {
748		// No word found at position, fallback to single click behavior
749		m.mouseDown = true
750		m.mouseDownItem = itemIdx
751		m.mouseDownX = x
752		m.mouseDownY = itemY
753		m.mouseDragItem = itemIdx
754		m.mouseDragX = x
755		m.mouseDragY = itemY
756		return
757	}
758
759	// Set selection to the word boundaries (convert back to viewport space).
760	// Keep mouseDown true so HandleMouseUp triggers the copy.
761	m.mouseDown = true
762	m.mouseDownItem = itemIdx
763	m.mouseDownX = startCol + offset
764	m.mouseDownY = itemY
765	m.mouseDragItem = itemIdx
766	m.mouseDragX = endCol + offset
767	m.mouseDragY = itemY
768}
769
770// selectLine selects the entire line at the given position within an item.
771func (m *Chat) selectLine(itemIdx, itemY int) {
772	item := m.list.ItemAt(itemIdx)
773	if item == nil {
774		return
775	}
776
777	// Get the rendered content for this item
778	var rendered string
779	if rr, ok := item.(list.RawRenderable); ok {
780		rendered = rr.RawRender(m.list.Width())
781	} else {
782		rendered = item.Render(m.list.Width())
783	}
784
785	lines := strings.Split(rendered, "\n")
786	if itemY < 0 || itemY >= len(lines) {
787		return
788	}
789
790	// Get line length (stripped of ANSI codes) and account for padding.
791	// SetHighlight will subtract the offset, so we need to add it here.
792	offset := chat.MessageLeftPaddingTotal
793	lineLen := ansi.StringWidth(lines[itemY])
794
795	// Set selection to the entire line.
796	// Keep mouseDown true so HandleMouseUp triggers the copy.
797	m.mouseDown = true
798	m.mouseDownItem = itemIdx
799	m.mouseDownX = 0
800	m.mouseDownY = itemY
801	m.mouseDragItem = itemIdx
802	m.mouseDragX = lineLen + offset
803	m.mouseDragY = itemY
804}
805
806// findWordBoundaries finds the start and end column of the word at the given column.
807// Returns (startCol, endCol) where endCol is exclusive.
808func findWordBoundaries(line string, col int) (startCol, endCol int) {
809	if line == "" || col < 0 {
810		return 0, 0
811	}
812
813	i := displaywidth.StringGraphemes(line)
814	for i.Next() {
815	}
816
817	// Segment the line into words using UAX#29.
818	lineCol := 0 // tracks the visited column widths
819	lastCol := 0 // tracks the start of the current token
820	iter := words.FromString(line)
821	for iter.Next() {
822		token := iter.Value()
823		tokenWidth := displaywidth.String(token)
824
825		graphemeStart := lineCol
826		graphemeEnd := lineCol + tokenWidth
827		lineCol += tokenWidth
828
829		// If clicked before this token, return the previous token boundaries.
830		if col < graphemeStart {
831			return lastCol, lastCol
832		}
833
834		// Update lastCol to the end of this token for next iteration.
835		lastCol = graphemeEnd
836
837		// If clicked within this token, return its boundaries.
838		if col >= graphemeStart && col < graphemeEnd {
839			// If clicked on whitespace, return empty selection.
840			if strings.TrimSpace(token) == "" {
841				return col, col
842			}
843			return graphemeStart, graphemeEnd
844		}
845	}
846
847	return col, col
848}
849
850// abs returns the absolute value of an integer.
851func abs(x int) int {
852	if x < 0 {
853		return -x
854	}
855	return x
856}