items.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. package list
  2. import (
  3. "image/color"
  4. tea "github.com/charmbracelet/bubbletea/v2"
  5. "github.com/charmbracelet/crush/internal/tui/components/core"
  6. "github.com/charmbracelet/crush/internal/tui/components/core/layout"
  7. "github.com/charmbracelet/crush/internal/tui/styles"
  8. "github.com/charmbracelet/crush/internal/tui/util"
  9. "github.com/charmbracelet/lipgloss/v2"
  10. "github.com/charmbracelet/x/ansi"
  11. "github.com/google/uuid"
  12. "github.com/rivo/uniseg"
  13. )
  14. type Indexable interface {
  15. SetIndex(int)
  16. }
  17. type CompletionItem[T any] interface {
  18. FilterableItem
  19. layout.Focusable
  20. layout.Sizeable
  21. HasMatchIndexes
  22. Value() T
  23. Text() string
  24. }
  25. type completionItemCmp[T any] struct {
  26. width int
  27. id string
  28. text string
  29. value T
  30. focus bool
  31. matchIndexes []int
  32. bgColor color.Color
  33. shortcut string
  34. }
  35. type options struct {
  36. id string
  37. text string
  38. bgColor color.Color
  39. matchIndexes []int
  40. shortcut string
  41. }
  42. type CompletionItemOption func(*options)
  43. func WithCompletionBackgroundColor(c color.Color) CompletionItemOption {
  44. return func(cmp *options) {
  45. cmp.bgColor = c
  46. }
  47. }
  48. func WithCompletionMatchIndexes(indexes ...int) CompletionItemOption {
  49. return func(cmp *options) {
  50. cmp.matchIndexes = indexes
  51. }
  52. }
  53. func WithCompletionShortcut(shortcut string) CompletionItemOption {
  54. return func(cmp *options) {
  55. cmp.shortcut = shortcut
  56. }
  57. }
  58. func WithCompletionID(id string) CompletionItemOption {
  59. return func(cmp *options) {
  60. cmp.id = id
  61. }
  62. }
  63. func NewCompletionItem[T any](text string, value T, opts ...CompletionItemOption) CompletionItem[T] {
  64. c := &completionItemCmp[T]{
  65. text: text,
  66. value: value,
  67. }
  68. o := &options{}
  69. for _, opt := range opts {
  70. opt(o)
  71. }
  72. if o.id == "" {
  73. o.id = uuid.NewString()
  74. }
  75. c.id = o.id
  76. c.bgColor = o.bgColor
  77. c.matchIndexes = o.matchIndexes
  78. c.shortcut = o.shortcut
  79. return c
  80. }
  81. // Init implements CommandItem.
  82. func (c *completionItemCmp[T]) Init() tea.Cmd {
  83. return nil
  84. }
  85. // Update implements CommandItem.
  86. func (c *completionItemCmp[T]) Update(tea.Msg) (util.Model, tea.Cmd) {
  87. return c, nil
  88. }
  89. // View implements CommandItem.
  90. func (c *completionItemCmp[T]) View() string {
  91. t := styles.CurrentTheme()
  92. itemStyle := t.S().Base.Padding(0, 1).Width(c.width)
  93. innerWidth := c.width - 2 // Account for padding
  94. if c.shortcut != "" {
  95. innerWidth -= lipgloss.Width(c.shortcut)
  96. }
  97. titleStyle := t.S().Text.Width(innerWidth)
  98. titleMatchStyle := t.S().Text.Underline(true)
  99. if c.bgColor != nil {
  100. titleStyle = titleStyle.Background(c.bgColor)
  101. titleMatchStyle = titleMatchStyle.Background(c.bgColor)
  102. itemStyle = itemStyle.Background(c.bgColor)
  103. }
  104. if c.focus {
  105. titleStyle = t.S().TextSelected.Width(innerWidth)
  106. titleMatchStyle = t.S().TextSelected.Underline(true)
  107. itemStyle = itemStyle.Background(t.Primary)
  108. }
  109. var truncatedTitle string
  110. if len(c.matchIndexes) > 0 && len(c.text) > innerWidth {
  111. // Smart truncation: ensure the last matching part is visible
  112. truncatedTitle = c.smartTruncate(c.text, innerWidth, c.matchIndexes)
  113. } else {
  114. // No matches, use regular truncation
  115. truncatedTitle = ansi.Truncate(c.text, innerWidth, "…")
  116. }
  117. text := titleStyle.Render(truncatedTitle)
  118. if len(c.matchIndexes) > 0 {
  119. var ranges []lipgloss.Range
  120. for _, rng := range matchedRanges(c.matchIndexes) {
  121. // ansi.Cut is grapheme and ansi sequence aware, we match against a ansi.Stripped string, but we might still have graphemes.
  122. // all that to say that rng is byte positions, but we need to pass it down to ansi.Cut as char positions.
  123. // so we need to adjust it here:
  124. start, stop := bytePosToVisibleCharPos(truncatedTitle, rng)
  125. ranges = append(ranges, lipgloss.NewRange(start, stop+1, titleMatchStyle))
  126. }
  127. text = lipgloss.StyleRanges(text, ranges...)
  128. }
  129. parts := []string{text}
  130. if c.shortcut != "" {
  131. // Add the shortcut at the end
  132. shortcutStyle := t.S().Muted
  133. if c.focus {
  134. shortcutStyle = t.S().TextSelected
  135. }
  136. parts = append(parts, shortcutStyle.Render(c.shortcut))
  137. }
  138. item := itemStyle.Render(
  139. lipgloss.JoinHorizontal(
  140. lipgloss.Left,
  141. parts...,
  142. ),
  143. )
  144. return item
  145. }
  146. // Blur implements CommandItem.
  147. func (c *completionItemCmp[T]) Blur() tea.Cmd {
  148. c.focus = false
  149. return nil
  150. }
  151. // Focus implements CommandItem.
  152. func (c *completionItemCmp[T]) Focus() tea.Cmd {
  153. c.focus = true
  154. return nil
  155. }
  156. // GetSize implements CommandItem.
  157. func (c *completionItemCmp[T]) GetSize() (int, int) {
  158. return c.width, 1
  159. }
  160. // IsFocused implements CommandItem.
  161. func (c *completionItemCmp[T]) IsFocused() bool {
  162. return c.focus
  163. }
  164. // SetSize implements CommandItem.
  165. func (c *completionItemCmp[T]) SetSize(width int, height int) tea.Cmd {
  166. c.width = width
  167. return nil
  168. }
  169. func (c *completionItemCmp[T]) MatchIndexes(indexes []int) {
  170. c.matchIndexes = indexes
  171. }
  172. func (c *completionItemCmp[T]) FilterValue() string {
  173. return c.text
  174. }
  175. func (c *completionItemCmp[T]) Value() T {
  176. return c.value
  177. }
  178. // smartTruncate implements fzf-style truncation that ensures the last matching part is visible
  179. func (c *completionItemCmp[T]) smartTruncate(text string, width int, matchIndexes []int) string {
  180. if width <= 0 {
  181. return ""
  182. }
  183. textLen := ansi.StringWidth(text)
  184. if textLen <= width {
  185. return text
  186. }
  187. if len(matchIndexes) == 0 {
  188. return ansi.Truncate(text, width, "…")
  189. }
  190. // Find the last match position
  191. lastMatchPos := matchIndexes[len(matchIndexes)-1]
  192. // Convert byte position to visual width position
  193. lastMatchVisualPos := 0
  194. bytePos := 0
  195. gr := uniseg.NewGraphemes(text)
  196. for bytePos < lastMatchPos && gr.Next() {
  197. bytePos += len(gr.Str())
  198. lastMatchVisualPos += max(1, gr.Width())
  199. }
  200. // Calculate how much space we need for the ellipsis
  201. ellipsisWidth := 1 // "…" character width
  202. availableWidth := width - ellipsisWidth
  203. // If the last match is within the available width, truncate from the end
  204. if lastMatchVisualPos < availableWidth {
  205. return ansi.Truncate(text, width, "…")
  206. }
  207. // Calculate the start position to ensure the last match is visible
  208. // We want to show some context before the last match if possible
  209. startVisualPos := max(0, lastMatchVisualPos-availableWidth+1)
  210. // Convert visual position back to byte position
  211. startBytePos := 0
  212. currentVisualPos := 0
  213. gr = uniseg.NewGraphemes(text)
  214. for currentVisualPos < startVisualPos && gr.Next() {
  215. startBytePos += len(gr.Str())
  216. currentVisualPos += max(1, gr.Width())
  217. }
  218. // Extract the substring starting from startBytePos
  219. truncatedText := text[startBytePos:]
  220. // Truncate to fit width with ellipsis
  221. truncatedText = ansi.Truncate(truncatedText, availableWidth, "")
  222. truncatedText = "…" + truncatedText
  223. return truncatedText
  224. }
  225. func matchedRanges(in []int) [][2]int {
  226. if len(in) == 0 {
  227. return [][2]int{}
  228. }
  229. current := [2]int{in[0], in[0]}
  230. if len(in) == 1 {
  231. return [][2]int{current}
  232. }
  233. var out [][2]int
  234. for i := 1; i < len(in); i++ {
  235. if in[i] == current[1]+1 {
  236. current[1] = in[i]
  237. } else {
  238. out = append(out, current)
  239. current = [2]int{in[i], in[i]}
  240. }
  241. }
  242. out = append(out, current)
  243. return out
  244. }
  245. func bytePosToVisibleCharPos(str string, rng [2]int) (int, int) {
  246. bytePos, byteStart, byteStop := 0, rng[0], rng[1]
  247. pos, start, stop := 0, 0, 0
  248. gr := uniseg.NewGraphemes(str)
  249. for byteStart > bytePos {
  250. if !gr.Next() {
  251. break
  252. }
  253. bytePos += len(gr.Str())
  254. pos += max(1, gr.Width())
  255. }
  256. start = pos
  257. for byteStop > bytePos {
  258. if !gr.Next() {
  259. break
  260. }
  261. bytePos += len(gr.Str())
  262. pos += max(1, gr.Width())
  263. }
  264. stop = pos
  265. return start, stop
  266. }
  267. // ID implements CompletionItem.
  268. func (c *completionItemCmp[T]) ID() string {
  269. return c.id
  270. }
  271. func (c *completionItemCmp[T]) Text() string {
  272. return c.text
  273. }
  274. type ItemSection interface {
  275. Item
  276. layout.Sizeable
  277. Indexable
  278. SetInfo(info string)
  279. }
  280. type itemSectionModel struct {
  281. width int
  282. title string
  283. inx int
  284. id string
  285. info string
  286. }
  287. // ID implements ItemSection.
  288. func (m *itemSectionModel) ID() string {
  289. return m.id
  290. }
  291. func NewItemSection(title string) ItemSection {
  292. return &itemSectionModel{
  293. title: title,
  294. inx: -1,
  295. id: uuid.NewString(),
  296. }
  297. }
  298. func (m *itemSectionModel) Init() tea.Cmd {
  299. return nil
  300. }
  301. func (m *itemSectionModel) Update(tea.Msg) (util.Model, tea.Cmd) {
  302. return m, nil
  303. }
  304. func (m *itemSectionModel) View() string {
  305. t := styles.CurrentTheme()
  306. title := ansi.Truncate(m.title, m.width-2, "…")
  307. style := t.S().Base.Padding(1, 1, 0, 1)
  308. if m.inx == 0 {
  309. style = style.Padding(0, 1, 0, 1)
  310. }
  311. title = t.S().Muted.Render(title)
  312. section := ""
  313. if m.info != "" {
  314. section = core.SectionWithInfo(title, m.width-2, m.info)
  315. } else {
  316. section = core.Section(title, m.width-2)
  317. }
  318. return style.Render(section)
  319. }
  320. func (m *itemSectionModel) GetSize() (int, int) {
  321. return m.width, 1
  322. }
  323. func (m *itemSectionModel) SetSize(width int, height int) tea.Cmd {
  324. m.width = width
  325. return nil
  326. }
  327. func (m *itemSectionModel) IsSectionHeader() bool {
  328. return true
  329. }
  330. func (m *itemSectionModel) SetInfo(info string) {
  331. m.info = info
  332. }
  333. func (m *itemSectionModel) SetIndex(inx int) {
  334. m.inx = inx
  335. }