complete.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package dialog
  2. import (
  3. "log/slog"
  4. "sort"
  5. "strings"
  6. "github.com/charmbracelet/bubbles/v2/key"
  7. "github.com/charmbracelet/bubbles/v2/textarea"
  8. tea "github.com/charmbracelet/bubbletea/v2"
  9. "github.com/charmbracelet/lipgloss/v2"
  10. "github.com/lithammer/fuzzysearch/fuzzy"
  11. "github.com/muesli/reflow/truncate"
  12. "github.com/sst/opencode/internal/completions"
  13. "github.com/sst/opencode/internal/components/list"
  14. "github.com/sst/opencode/internal/styles"
  15. "github.com/sst/opencode/internal/theme"
  16. "github.com/sst/opencode/internal/util"
  17. )
  18. type CompletionSelectedMsg struct {
  19. Item completions.CompletionSuggestion
  20. SearchString string
  21. }
  22. type CompletionDialogCompleteItemMsg struct {
  23. Value string
  24. }
  25. type CompletionDialogCloseMsg struct{}
  26. type CompletionDialog interface {
  27. tea.Model
  28. tea.ViewModel
  29. SetWidth(width int)
  30. IsEmpty() bool
  31. }
  32. type completionDialogComponent struct {
  33. query string
  34. providers []completions.CompletionProvider
  35. width int
  36. height int
  37. pseudoSearchTextArea textarea.Model
  38. list list.List[completions.CompletionSuggestion]
  39. trigger string
  40. }
  41. type completionDialogKeyMap struct {
  42. Complete key.Binding
  43. Cancel key.Binding
  44. }
  45. var completionDialogKeys = completionDialogKeyMap{
  46. Complete: key.NewBinding(
  47. key.WithKeys("tab", "enter", "right"),
  48. ),
  49. Cancel: key.NewBinding(
  50. key.WithKeys("space", " ", "esc", "backspace", "ctrl+h", "ctrl+c"),
  51. ),
  52. }
  53. func (c *completionDialogComponent) Init() tea.Cmd {
  54. return nil
  55. }
  56. func (c *completionDialogComponent) getAllCompletions(query string) tea.Cmd {
  57. return func() tea.Msg {
  58. allItems := make([]completions.CompletionSuggestion, 0)
  59. // Collect results from all providers
  60. for _, provider := range c.providers {
  61. items, err := provider.GetChildEntries(query)
  62. if err != nil {
  63. slog.Error(
  64. "Failed to get completion items",
  65. "provider",
  66. provider.GetId(),
  67. "error",
  68. err,
  69. )
  70. continue
  71. }
  72. allItems = append(allItems, items...)
  73. }
  74. // If there's a query, use fuzzy ranking to sort results
  75. if query != "" && len(allItems) > 0 && len(c.providers) > 1 {
  76. t := theme.CurrentTheme()
  77. baseStyle := styles.NewStyle().Background(t.BackgroundElement())
  78. // Create a slice of display values for fuzzy matching
  79. displayValues := make([]string, len(allItems))
  80. for i, item := range allItems {
  81. displayValues[i] = item.Display(baseStyle)
  82. }
  83. matches := fuzzy.RankFindFold(query, displayValues)
  84. sort.Sort(matches)
  85. // Reorder items based on fuzzy ranking
  86. rankedItems := make([]completions.CompletionSuggestion, 0, len(matches))
  87. for _, match := range matches {
  88. rankedItems = append(rankedItems, allItems[match.OriginalIndex])
  89. }
  90. return rankedItems
  91. }
  92. return allItems
  93. }
  94. }
  95. func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  96. var cmds []tea.Cmd
  97. switch msg := msg.(type) {
  98. case []completions.CompletionSuggestion:
  99. c.list.SetItems(msg)
  100. case tea.KeyMsg:
  101. if c.pseudoSearchTextArea.Focused() {
  102. if !key.Matches(msg, completionDialogKeys.Complete) {
  103. var cmd tea.Cmd
  104. c.pseudoSearchTextArea, cmd = c.pseudoSearchTextArea.Update(msg)
  105. cmds = append(cmds, cmd)
  106. fullValue := c.pseudoSearchTextArea.Value()
  107. query := strings.TrimPrefix(fullValue, c.trigger)
  108. if query != c.query {
  109. c.query = query
  110. cmds = append(cmds, c.getAllCompletions(query))
  111. }
  112. u, cmd := c.list.Update(msg)
  113. c.list = u.(list.List[completions.CompletionSuggestion])
  114. cmds = append(cmds, cmd)
  115. }
  116. switch {
  117. case key.Matches(msg, completionDialogKeys.Complete):
  118. item, i := c.list.GetSelectedItem()
  119. if i == -1 {
  120. return c, nil
  121. }
  122. return c, c.complete(item)
  123. case key.Matches(msg, completionDialogKeys.Cancel):
  124. value := c.pseudoSearchTextArea.Value()
  125. width := lipgloss.Width(value)
  126. triggerWidth := lipgloss.Width(c.trigger)
  127. // Only close on backspace when there are no characters left, unless we're back to just the trigger
  128. if (msg.String() != "backspace" && msg.String() != "ctrl+h") || (width <= triggerWidth && value != c.trigger) {
  129. return c, c.close()
  130. }
  131. }
  132. return c, tea.Batch(cmds...)
  133. } else {
  134. cmds = append(cmds, c.getAllCompletions(""))
  135. cmds = append(cmds, c.pseudoSearchTextArea.Focus())
  136. return c, tea.Batch(cmds...)
  137. }
  138. }
  139. return c, tea.Batch(cmds...)
  140. }
  141. func (c *completionDialogComponent) View() string {
  142. t := theme.CurrentTheme()
  143. c.list.SetMaxWidth(c.width)
  144. return styles.NewStyle().
  145. Padding(0, 1).
  146. Foreground(t.Text()).
  147. Background(t.BackgroundElement()).
  148. BorderStyle(lipgloss.ThickBorder()).
  149. BorderLeft(true).
  150. BorderRight(true).
  151. BorderForeground(t.Border()).
  152. BorderBackground(t.Background()).
  153. Width(c.width).
  154. Render(c.list.View())
  155. }
  156. func (c *completionDialogComponent) SetWidth(width int) {
  157. c.width = width
  158. }
  159. func (c *completionDialogComponent) IsEmpty() bool {
  160. return c.list.IsEmpty()
  161. }
  162. func (c *completionDialogComponent) complete(item completions.CompletionSuggestion) tea.Cmd {
  163. value := c.pseudoSearchTextArea.Value()
  164. return tea.Batch(
  165. util.CmdHandler(CompletionSelectedMsg{
  166. SearchString: value,
  167. Item: item,
  168. }),
  169. c.close(),
  170. )
  171. }
  172. func (c *completionDialogComponent) close() tea.Cmd {
  173. c.pseudoSearchTextArea.Reset()
  174. c.pseudoSearchTextArea.Blur()
  175. return util.CmdHandler(CompletionDialogCloseMsg{})
  176. }
  177. func NewCompletionDialogComponent(
  178. trigger string,
  179. providers ...completions.CompletionProvider,
  180. ) CompletionDialog {
  181. ti := textarea.New()
  182. ti.SetValue(trigger)
  183. // Use a generic empty message if we have multiple providers
  184. emptyMessage := "no matching items"
  185. if len(providers) == 1 {
  186. emptyMessage = providers[0].GetEmptyMessage()
  187. }
  188. // Define render function for completion suggestions
  189. renderFunc := func(item completions.CompletionSuggestion, selected bool, width int, baseStyle styles.Style) string {
  190. t := theme.CurrentTheme()
  191. style := baseStyle
  192. if selected {
  193. style = style.Background(t.BackgroundElement()).Foreground(t.Primary())
  194. } else {
  195. style = style.Background(t.BackgroundElement()).Foreground(t.Text())
  196. }
  197. // The item.Display string already has any inline colors from the provider
  198. truncatedStr := truncate.String(item.Display(style), uint(width-4))
  199. return style.Width(width - 4).Render(truncatedStr)
  200. }
  201. // Define selectable function - all completion suggestions are selectable
  202. selectableFunc := func(item completions.CompletionSuggestion) bool {
  203. return true
  204. }
  205. li := list.NewListComponent(
  206. list.WithItems([]completions.CompletionSuggestion{}),
  207. list.WithMaxVisibleHeight[completions.CompletionSuggestion](7),
  208. list.WithFallbackMessage[completions.CompletionSuggestion](emptyMessage),
  209. list.WithAlphaNumericKeys[completions.CompletionSuggestion](false),
  210. list.WithRenderFunc(renderFunc),
  211. list.WithSelectableFunc(selectableFunc),
  212. )
  213. c := &completionDialogComponent{
  214. query: "",
  215. providers: providers,
  216. pseudoSearchTextArea: ti,
  217. list: li,
  218. trigger: trigger,
  219. }
  220. // Load initial items from all providers
  221. go func() {
  222. allItems := make([]completions.CompletionSuggestion, 0)
  223. for _, provider := range providers {
  224. items, err := provider.GetChildEntries("")
  225. if err != nil {
  226. slog.Error(
  227. "Failed to get completion items",
  228. "provider",
  229. provider.GetId(),
  230. "error",
  231. err,
  232. )
  233. continue
  234. }
  235. allItems = append(allItems, items...)
  236. }
  237. li.SetItems(allItems)
  238. }()
  239. return c
  240. }