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 // Register nested tool IDs for tools that contain nested tools.
81 if container, ok := msg.(chat.NestedToolContainer); ok {
82 for _, nested := range container.NestedTools() {
83 m.idInxMap[nested.ID()] = i
84 }
85 }
86 items[i] = msg
87 }
88 m.list.SetItems(items...)
89 m.list.ScrollToBottom()
90}
91
92// AppendMessages appends a new message item to the chat list.
93func (m *Chat) AppendMessages(msgs ...chat.MessageItem) {
94 items := make([]list.Item, len(msgs))
95 indexOffset := m.list.Len()
96 for i, msg := range msgs {
97 m.idInxMap[msg.ID()] = indexOffset + i
98 // Register nested tool IDs for tools that contain nested tools.
99 if container, ok := msg.(chat.NestedToolContainer); ok {
100 for _, nested := range container.NestedTools() {
101 m.idInxMap[nested.ID()] = indexOffset + i
102 }
103 }
104 items[i] = msg
105 }
106 m.list.AppendItems(items...)
107}
108
109// UpdateNestedToolIDs updates the ID map for nested tools within a container.
110// Call this after modifying nested tools to ensure animations work correctly.
111func (m *Chat) UpdateNestedToolIDs(containerID string) {
112 idx, ok := m.idInxMap[containerID]
113 if !ok {
114 return
115 }
116
117 item, ok := m.list.ItemAt(idx).(chat.MessageItem)
118 if !ok {
119 return
120 }
121
122 container, ok := item.(chat.NestedToolContainer)
123 if !ok {
124 return
125 }
126
127 // Register all nested tool IDs to point to the container's index.
128 for _, nested := range container.NestedTools() {
129 m.idInxMap[nested.ID()] = idx
130 }
131}
132
133// Animate animates items in the chat list. Only propagates animation messages
134// to visible items to save CPU. When items are not visible, their animation ID
135// is tracked so it can be restarted when they become visible again.
136func (m *Chat) Animate(msg anim.StepMsg) tea.Cmd {
137 idx, ok := m.idInxMap[msg.ID]
138 if !ok {
139 return nil
140 }
141
142 animatable, ok := m.list.ItemAt(idx).(chat.Animatable)
143 if !ok {
144 return nil
145 }
146
147 // Check if item is currently visible.
148 startIdx, endIdx := m.list.VisibleItemIndices()
149 isVisible := idx >= startIdx && idx <= endIdx
150
151 if !isVisible {
152 // Item not visible - pause animation by not propagating.
153 // Track it so we can restart when it becomes visible.
154 m.pausedAnimations[msg.ID] = struct{}{}
155 return nil
156 }
157
158 // Item is visible - remove from paused set and animate.
159 delete(m.pausedAnimations, msg.ID)
160 return animatable.Animate(msg)
161}
162
163// RestartPausedVisibleAnimations restarts animations for items that were paused
164// due to being scrolled out of view but are now visible again.
165func (m *Chat) RestartPausedVisibleAnimations() tea.Cmd {
166 if len(m.pausedAnimations) == 0 {
167 return nil
168 }
169
170 startIdx, endIdx := m.list.VisibleItemIndices()
171 var cmds []tea.Cmd
172
173 for id := range m.pausedAnimations {
174 idx, ok := m.idInxMap[id]
175 if !ok {
176 // Item no longer exists.
177 delete(m.pausedAnimations, id)
178 continue
179 }
180
181 if idx >= startIdx && idx <= endIdx {
182 // Item is now visible - restart its animation.
183 if animatable, ok := m.list.ItemAt(idx).(chat.Animatable); ok {
184 if cmd := animatable.StartAnimation(); cmd != nil {
185 cmds = append(cmds, cmd)
186 }
187 }
188 delete(m.pausedAnimations, id)
189 }
190 }
191
192 if len(cmds) == 0 {
193 return nil
194 }
195 return tea.Batch(cmds...)
196}
197
198// Focus sets the focus state of the chat component.
199func (m *Chat) Focus() {
200 m.list.Focus()
201}
202
203// Blur removes the focus state from the chat component.
204func (m *Chat) Blur() {
205 m.list.Blur()
206}
207
208// ScrollToTopAndAnimate scrolls the chat view to the top and returns a command to restart
209// any paused animations that are now visible.
210func (m *Chat) ScrollToTopAndAnimate() tea.Cmd {
211 m.list.ScrollToTop()
212 return m.RestartPausedVisibleAnimations()
213}
214
215// ScrollToBottomAndAnimate scrolls the chat view to the bottom and returns a command to
216// restart any paused animations that are now visible.
217func (m *Chat) ScrollToBottomAndAnimate() tea.Cmd {
218 m.list.ScrollToBottom()
219 return m.RestartPausedVisibleAnimations()
220}
221
222// ScrollByAndAnimate scrolls the chat view by the given number of line deltas and returns
223// a command to restart any paused animations that are now visible.
224func (m *Chat) ScrollByAndAnimate(lines int) tea.Cmd {
225 m.list.ScrollBy(lines)
226 return m.RestartPausedVisibleAnimations()
227}
228
229// ScrollToSelectedAndAnimate scrolls the chat view to the selected item and returns a
230// command to restart any paused animations that are now visible.
231func (m *Chat) ScrollToSelectedAndAnimate() tea.Cmd {
232 m.list.ScrollToSelected()
233 return m.RestartPausedVisibleAnimations()
234}
235
236// SelectedItemInView returns whether the selected item is currently in view.
237func (m *Chat) SelectedItemInView() bool {
238 return m.list.SelectedItemInView()
239}
240
241// SetSelected sets the selected message index in the chat list.
242func (m *Chat) SetSelected(index int) {
243 m.list.SetSelected(index)
244}
245
246// SelectPrev selects the previous message in the chat list.
247func (m *Chat) SelectPrev() {
248 m.list.SelectPrev()
249}
250
251// SelectNext selects the next message in the chat list.
252func (m *Chat) SelectNext() {
253 m.list.SelectNext()
254}
255
256// SelectFirst selects the first message in the chat list.
257func (m *Chat) SelectFirst() {
258 m.list.SelectFirst()
259}
260
261// SelectLast selects the last message in the chat list.
262func (m *Chat) SelectLast() {
263 m.list.SelectLast()
264}
265
266// SelectFirstInView selects the first message currently in view.
267func (m *Chat) SelectFirstInView() {
268 m.list.SelectFirstInView()
269}
270
271// SelectLastInView selects the last message currently in view.
272func (m *Chat) SelectLastInView() {
273 m.list.SelectLastInView()
274}
275
276// ClearMessages removes all messages from the chat list.
277func (m *Chat) ClearMessages() {
278 m.idInxMap = make(map[string]int)
279 m.pausedAnimations = make(map[string]struct{})
280 m.list.SetItems()
281 m.ClearMouse()
282}
283
284// RemoveMessage removes a message from the chat list by its ID.
285func (m *Chat) RemoveMessage(id string) {
286 idx, ok := m.idInxMap[id]
287 if !ok {
288 return
289 }
290
291 // Remove from list
292 m.list.RemoveItem(idx)
293
294 // Remove from index map
295 delete(m.idInxMap, id)
296
297 // Rebuild index map for all items after the removed one
298 for i := idx; i < m.list.Len(); i++ {
299 if item, ok := m.list.ItemAt(i).(chat.MessageItem); ok {
300 m.idInxMap[item.ID()] = i
301 }
302 }
303
304 // Clean up any paused animations for this message
305 delete(m.pausedAnimations, id)
306}
307
308// MessageItem returns the message item with the given ID, or nil if not found.
309func (m *Chat) MessageItem(id string) chat.MessageItem {
310 idx, ok := m.idInxMap[id]
311 if !ok {
312 return nil
313 }
314 item, ok := m.list.ItemAt(idx).(chat.MessageItem)
315 if !ok {
316 return nil
317 }
318 return item
319}
320
321// ToggleExpandedSelectedItem expands the selected message item if it is expandable.
322func (m *Chat) ToggleExpandedSelectedItem() {
323 if expandable, ok := m.list.SelectedItem().(chat.Expandable); ok {
324 expandable.ToggleExpanded()
325 }
326}
327
328// HandleMouseDown handles mouse down events for the chat component.
329func (m *Chat) HandleMouseDown(x, y int) bool {
330 if m.list.Len() == 0 {
331 return false
332 }
333
334 itemIdx, itemY := m.list.ItemIndexAtPosition(x, y)
335 if itemIdx < 0 {
336 return false
337 }
338
339 m.mouseDown = true
340 m.mouseDownItem = itemIdx
341 m.mouseDownX = x
342 m.mouseDownY = itemY
343 m.mouseDragItem = itemIdx
344 m.mouseDragX = x
345 m.mouseDragY = itemY
346
347 // Select the item that was clicked
348 m.list.SetSelected(itemIdx)
349
350 if clickable, ok := m.list.SelectedItem().(list.MouseClickable); ok {
351 return clickable.HandleMouseClick(ansi.MouseButton1, x, itemY)
352 }
353
354 return true
355}
356
357// HandleMouseUp handles mouse up events for the chat component.
358func (m *Chat) HandleMouseUp(x, y int) bool {
359 if !m.mouseDown {
360 return false
361 }
362
363 // TODO: Handle the behavior when mouse is released after a drag selection
364 // (e.g., copy selected text to clipboard)
365
366 m.mouseDown = false
367 return true
368}
369
370// HandleMouseDrag handles mouse drag events for the chat component.
371func (m *Chat) HandleMouseDrag(x, y int) bool {
372 if !m.mouseDown {
373 return false
374 }
375
376 if m.list.Len() == 0 {
377 return false
378 }
379
380 itemIdx, itemY := m.list.ItemIndexAtPosition(x, y)
381 if itemIdx < 0 {
382 return false
383 }
384
385 m.mouseDragItem = itemIdx
386 m.mouseDragX = x
387 m.mouseDragY = itemY
388
389 return true
390}
391
392// ClearMouse clears the current mouse interaction state.
393func (m *Chat) ClearMouse() {
394 m.mouseDown = false
395 m.mouseDownItem = -1
396 m.mouseDragItem = -1
397}
398
399// applyHighlightRange applies the current highlight range to the chat items.
400func (m *Chat) applyHighlightRange(idx, selectedIdx int, item list.Item) list.Item {
401 if hi, ok := item.(list.Highlightable); ok {
402 // Apply highlight
403 startItemIdx, startLine, startCol, endItemIdx, endLine, endCol := m.getHighlightRange()
404 sLine, sCol, eLine, eCol := -1, -1, -1, -1
405 if idx >= startItemIdx && idx <= endItemIdx {
406 if idx == startItemIdx && idx == endItemIdx {
407 // Single item selection
408 sLine = startLine
409 sCol = startCol
410 eLine = endLine
411 eCol = endCol
412 } else if idx == startItemIdx {
413 // First item - from start position to end of item
414 sLine = startLine
415 sCol = startCol
416 eLine = -1
417 eCol = -1
418 } else if idx == endItemIdx {
419 // Last item - from start of item to end position
420 sLine = 0
421 sCol = 0
422 eLine = endLine
423 eCol = endCol
424 } else {
425 // Middle item - fully highlighted
426 sLine = 0
427 sCol = 0
428 eLine = -1
429 eCol = -1
430 }
431 }
432
433 hi.Highlight(sLine, sCol, eLine, eCol)
434 return hi.(list.Item)
435 }
436
437 return item
438}
439
440// getHighlightRange returns the current highlight range.
441func (m *Chat) getHighlightRange() (startItemIdx, startLine, startCol, endItemIdx, endLine, endCol int) {
442 if m.mouseDownItem < 0 {
443 return -1, -1, -1, -1, -1, -1
444 }
445
446 downItemIdx := m.mouseDownItem
447 dragItemIdx := m.mouseDragItem
448
449 // Determine selection direction
450 draggingDown := dragItemIdx > downItemIdx ||
451 (dragItemIdx == downItemIdx && m.mouseDragY > m.mouseDownY) ||
452 (dragItemIdx == downItemIdx && m.mouseDragY == m.mouseDownY && m.mouseDragX >= m.mouseDownX)
453
454 if draggingDown {
455 // Normal forward selection
456 startItemIdx = downItemIdx
457 startLine = m.mouseDownY
458 startCol = m.mouseDownX
459 endItemIdx = dragItemIdx
460 endLine = m.mouseDragY
461 endCol = m.mouseDragX
462 } else {
463 // Backward selection (dragging up)
464 startItemIdx = dragItemIdx
465 startLine = m.mouseDragY
466 startCol = m.mouseDragX
467 endItemIdx = downItemIdx
468 endLine = m.mouseDownY
469 endCol = m.mouseDownX
470 }
471
472 return startItemIdx, startLine, startCol, endItemIdx, endLine, endCol
473}