chat.go

  1package model
  2
  3import (
  4	tea "charm.land/bubbletea/v2"
  5	"github.com/charmbracelet/crush/internal/ui/anim"
  6	"github.com/charmbracelet/crush/internal/ui/chat"
  7	"github.com/charmbracelet/crush/internal/ui/common"
  8	"github.com/charmbracelet/crush/internal/ui/list"
  9	uv "github.com/charmbracelet/ultraviolet"
 10	"github.com/charmbracelet/x/ansi"
 11)
 12
 13// Chat represents the chat UI model that handles chat interactions and
 14// messages.
 15type Chat struct {
 16	com      *common.Common
 17	list     *list.List
 18	idInxMap map[string]int // Map of message IDs to their indices in the list
 19
 20	// Animation visibility optimization: track animations paused due to items
 21	// being scrolled out of view. When items become visible again, their
 22	// animations are restarted.
 23	pausedAnimations map[string]struct{}
 24
 25	// Mouse state
 26	mouseDown     bool
 27	mouseDownItem int // Item index where mouse was pressed
 28	mouseDownX    int // X position in item content (character offset)
 29	mouseDownY    int // Y position in item (line offset)
 30	mouseDragItem int // Current item index being dragged over
 31	mouseDragX    int // Current X in item content
 32	mouseDragY    int // Current Y in item
 33}
 34
 35// NewChat creates a new instance of [Chat] that handles chat interactions and
 36// messages.
 37func NewChat(com *common.Common) *Chat {
 38	c := &Chat{
 39		com:              com,
 40		idInxMap:         make(map[string]int),
 41		pausedAnimations: make(map[string]struct{}),
 42	}
 43	l := list.NewList()
 44	l.SetGap(1)
 45	l.RegisterRenderCallback(c.applyHighlightRange)
 46	c.list = l
 47	c.mouseDownItem = -1
 48	c.mouseDragItem = -1
 49	return c
 50}
 51
 52// Height returns the height of the chat view port.
 53func (m *Chat) Height() int {
 54	return m.list.Height()
 55}
 56
 57// Draw renders the chat UI component to the screen and the given area.
 58func (m *Chat) Draw(scr uv.Screen, area uv.Rectangle) {
 59	uv.NewStyledString(m.list.Render()).Draw(scr, area)
 60}
 61
 62// SetSize sets the size of the chat view port.
 63func (m *Chat) SetSize(width, height int) {
 64	m.list.SetSize(width, height)
 65}
 66
 67// Len returns the number of items in the chat list.
 68func (m *Chat) Len() int {
 69	return m.list.Len()
 70}
 71
 72// SetMessages sets the chat messages to the provided list of message items.
 73func (m *Chat) SetMessages(msgs ...chat.MessageItem) {
 74	m.idInxMap = make(map[string]int)
 75	m.pausedAnimations = make(map[string]struct{})
 76
 77	items := make([]list.Item, len(msgs))
 78	for i, msg := range msgs {
 79		m.idInxMap[msg.ID()] = i
 80		items[i] = msg
 81	}
 82	m.list.SetItems(items...)
 83	m.list.ScrollToBottom()
 84}
 85
 86// AppendMessages appends a new message item to the chat list.
 87func (m *Chat) AppendMessages(msgs ...chat.MessageItem) {
 88	items := make([]list.Item, len(msgs))
 89	indexOffset := m.list.Len()
 90	for i, msg := range msgs {
 91		m.idInxMap[msg.ID()] = indexOffset + i
 92		items[i] = msg
 93	}
 94	m.list.AppendItems(items...)
 95}
 96
 97// Animate animates items in the chat list. Only propagates animation messages
 98// to visible items to save CPU. When items are not visible, their animation ID
 99// is tracked so it can be restarted when they become visible again.
100func (m *Chat) Animate(msg anim.StepMsg) tea.Cmd {
101	idx, ok := m.idInxMap[msg.ID]
102	if !ok {
103		return nil
104	}
105
106	animatable, ok := m.list.ItemAt(idx).(chat.Animatable)
107	if !ok {
108		return nil
109	}
110
111	// Check if item is currently visible.
112	startIdx, endIdx := m.list.VisibleItemIndices()
113	isVisible := idx >= startIdx && idx <= endIdx
114
115	if !isVisible {
116		// Item not visible - pause animation by not propagating.
117		// Track it so we can restart when it becomes visible.
118		m.pausedAnimations[msg.ID] = struct{}{}
119		return nil
120	}
121
122	// Item is visible - remove from paused set and animate.
123	delete(m.pausedAnimations, msg.ID)
124	return animatable.Animate(msg)
125}
126
127// RestartPausedVisibleAnimations restarts animations for items that were paused
128// due to being scrolled out of view but are now visible again.
129func (m *Chat) RestartPausedVisibleAnimations() tea.Cmd {
130	if len(m.pausedAnimations) == 0 {
131		return nil
132	}
133
134	startIdx, endIdx := m.list.VisibleItemIndices()
135	var cmds []tea.Cmd
136
137	for id := range m.pausedAnimations {
138		idx, ok := m.idInxMap[id]
139		if !ok {
140			// Item no longer exists.
141			delete(m.pausedAnimations, id)
142			continue
143		}
144
145		if idx >= startIdx && idx <= endIdx {
146			// Item is now visible - restart its animation.
147			if animatable, ok := m.list.ItemAt(idx).(chat.Animatable); ok {
148				if cmd := animatable.StartAnimation(); cmd != nil {
149					cmds = append(cmds, cmd)
150				}
151			}
152			delete(m.pausedAnimations, id)
153		}
154	}
155
156	if len(cmds) == 0 {
157		return nil
158	}
159	return tea.Batch(cmds...)
160}
161
162// Focus sets the focus state of the chat component.
163func (m *Chat) Focus() {
164	m.list.Focus()
165}
166
167// Blur removes the focus state from the chat component.
168func (m *Chat) Blur() {
169	m.list.Blur()
170}
171
172// ScrollToTop scrolls the chat view to the top and returns a command to restart
173// any paused animations that are now visible.
174func (m *Chat) ScrollToTop() tea.Cmd {
175	m.list.ScrollToTop()
176	return m.RestartPausedVisibleAnimations()
177}
178
179// ScrollToBottom scrolls the chat view to the bottom and returns a command to
180// restart any paused animations that are now visible.
181func (m *Chat) ScrollToBottom() tea.Cmd {
182	m.list.ScrollToBottom()
183	return m.RestartPausedVisibleAnimations()
184}
185
186// ScrollBy scrolls the chat view by the given number of line deltas and returns
187// a command to restart any paused animations that are now visible.
188func (m *Chat) ScrollBy(lines int) tea.Cmd {
189	m.list.ScrollBy(lines)
190	return m.RestartPausedVisibleAnimations()
191}
192
193// ScrollToSelected scrolls the chat view to the selected item and returns a
194// command to restart any paused animations that are now visible.
195func (m *Chat) ScrollToSelected() tea.Cmd {
196	m.list.ScrollToSelected()
197	return m.RestartPausedVisibleAnimations()
198}
199
200// SelectedItemInView returns whether the selected item is currently in view.
201func (m *Chat) SelectedItemInView() bool {
202	return m.list.SelectedItemInView()
203}
204
205// SetSelected sets the selected message index in the chat list.
206func (m *Chat) SetSelected(index int) {
207	m.list.SetSelected(index)
208}
209
210// SelectPrev selects the previous message in the chat list.
211func (m *Chat) SelectPrev() {
212	m.list.SelectPrev()
213}
214
215// SelectNext selects the next message in the chat list.
216func (m *Chat) SelectNext() {
217	m.list.SelectNext()
218}
219
220// SelectFirst selects the first message in the chat list.
221func (m *Chat) SelectFirst() {
222	m.list.SelectFirst()
223}
224
225// SelectLast selects the last message in the chat list.
226func (m *Chat) SelectLast() {
227	m.list.SelectLast()
228}
229
230// SelectFirstInView selects the first message currently in view.
231func (m *Chat) SelectFirstInView() {
232	m.list.SelectFirstInView()
233}
234
235// SelectLastInView selects the last message currently in view.
236func (m *Chat) SelectLastInView() {
237	m.list.SelectLastInView()
238}
239
240// GetMessageItem returns the message item at the given id.
241func (m *Chat) GetMessageItem(id string) chat.MessageItem {
242	idx, ok := m.idInxMap[id]
243	if !ok {
244		return nil
245	}
246	item, ok := m.list.ItemAt(idx).(chat.MessageItem)
247	if !ok {
248		return nil
249	}
250	return item
251}
252
253// HandleMouseDown handles mouse down events for the chat component.
254func (m *Chat) HandleMouseDown(x, y int) bool {
255	if m.list.Len() == 0 {
256		return false
257	}
258
259	itemIdx, itemY := m.list.ItemIndexAtPosition(x, y)
260	if itemIdx < 0 {
261		return false
262	}
263
264	m.mouseDown = true
265	m.mouseDownItem = itemIdx
266	m.mouseDownX = x
267	m.mouseDownY = itemY
268	m.mouseDragItem = itemIdx
269	m.mouseDragX = x
270	m.mouseDragY = itemY
271
272	// Select the item that was clicked
273	m.list.SetSelected(itemIdx)
274
275	if clickable, ok := m.list.SelectedItem().(list.MouseClickable); ok {
276		return clickable.HandleMouseClick(ansi.MouseButton1, x, itemY)
277	}
278
279	return true
280}
281
282// HandleMouseUp handles mouse up events for the chat component.
283func (m *Chat) HandleMouseUp(x, y int) bool {
284	if !m.mouseDown {
285		return false
286	}
287
288	// TODO: Handle the behavior when mouse is released after a drag selection
289	// (e.g., copy selected text to clipboard)
290
291	m.mouseDown = false
292	return true
293}
294
295// HandleMouseDrag handles mouse drag events for the chat component.
296func (m *Chat) HandleMouseDrag(x, y int) bool {
297	if !m.mouseDown {
298		return false
299	}
300
301	if m.list.Len() == 0 {
302		return false
303	}
304
305	itemIdx, itemY := m.list.ItemIndexAtPosition(x, y)
306	if itemIdx < 0 {
307		return false
308	}
309
310	m.mouseDragItem = itemIdx
311	m.mouseDragX = x
312	m.mouseDragY = itemY
313
314	return true
315}
316
317// ClearMouse clears the current mouse interaction state.
318func (m *Chat) ClearMouse() {
319	m.mouseDown = false
320	m.mouseDownItem = -1
321	m.mouseDragItem = -1
322}
323
324// applyHighlightRange applies the current highlight range to the chat items.
325func (m *Chat) applyHighlightRange(idx, selectedIdx int, item list.Item) list.Item {
326	if hi, ok := item.(list.Highlightable); ok {
327		// Apply highlight
328		startItemIdx, startLine, startCol, endItemIdx, endLine, endCol := m.getHighlightRange()
329		sLine, sCol, eLine, eCol := -1, -1, -1, -1
330		if idx >= startItemIdx && idx <= endItemIdx {
331			if idx == startItemIdx && idx == endItemIdx {
332				// Single item selection
333				sLine = startLine
334				sCol = startCol
335				eLine = endLine
336				eCol = endCol
337			} else if idx == startItemIdx {
338				// First item - from start position to end of item
339				sLine = startLine
340				sCol = startCol
341				eLine = -1
342				eCol = -1
343			} else if idx == endItemIdx {
344				// Last item - from start of item to end position
345				sLine = 0
346				sCol = 0
347				eLine = endLine
348				eCol = endCol
349			} else {
350				// Middle item - fully highlighted
351				sLine = 0
352				sCol = 0
353				eLine = -1
354				eCol = -1
355			}
356		}
357
358		hi.Highlight(sLine, sCol, eLine, eCol)
359		return hi.(list.Item)
360	}
361
362	return item
363}
364
365// getHighlightRange returns the current highlight range.
366func (m *Chat) getHighlightRange() (startItemIdx, startLine, startCol, endItemIdx, endLine, endCol int) {
367	if m.mouseDownItem < 0 {
368		return -1, -1, -1, -1, -1, -1
369	}
370
371	downItemIdx := m.mouseDownItem
372	dragItemIdx := m.mouseDragItem
373
374	// Determine selection direction
375	draggingDown := dragItemIdx > downItemIdx ||
376		(dragItemIdx == downItemIdx && m.mouseDragY > m.mouseDownY) ||
377		(dragItemIdx == downItemIdx && m.mouseDragY == m.mouseDownY && m.mouseDragX >= m.mouseDownX)
378
379	if draggingDown {
380		// Normal forward selection
381		startItemIdx = downItemIdx
382		startLine = m.mouseDownY
383		startCol = m.mouseDownX
384		endItemIdx = dragItemIdx
385		endLine = m.mouseDragY
386		endCol = m.mouseDragX
387	} else {
388		// Backward selection (dragging up)
389		startItemIdx = dragItemIdx
390		startLine = m.mouseDragY
391		startCol = m.mouseDragX
392		endItemIdx = downItemIdx
393		endLine = m.mouseDownY
394		endCol = m.mouseDownX
395	}
396
397	return startItemIdx, startLine, startCol, endItemIdx, endLine, endCol
398}