chat.go 23 KB

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