editor.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. package chat
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "os"
  6. "os/exec"
  7. "slices"
  8. "strings"
  9. "unicode"
  10. "github.com/charmbracelet/bubbles/key"
  11. "github.com/charmbracelet/bubbles/spinner"
  12. "github.com/charmbracelet/bubbles/textarea"
  13. tea "github.com/charmbracelet/bubbletea"
  14. "github.com/charmbracelet/lipgloss"
  15. "github.com/sst/opencode/internal/app"
  16. "github.com/sst/opencode/internal/components/dialog"
  17. "github.com/sst/opencode/internal/image"
  18. "github.com/sst/opencode/internal/layout"
  19. "github.com/sst/opencode/internal/status"
  20. "github.com/sst/opencode/internal/styles"
  21. "github.com/sst/opencode/internal/theme"
  22. "github.com/sst/opencode/internal/util"
  23. )
  24. type editorComponent struct {
  25. width int
  26. height int
  27. app *app.App
  28. textarea textarea.Model
  29. attachments []app.Attachment
  30. deleteMode bool
  31. history []string
  32. historyIndex int
  33. currentMessage string
  34. spinner spinner.Model
  35. }
  36. type EditorKeyMaps struct {
  37. Send key.Binding
  38. OpenEditor key.Binding
  39. Paste key.Binding
  40. HistoryUp key.Binding
  41. HistoryDown key.Binding
  42. }
  43. type bluredEditorKeyMaps struct {
  44. Send key.Binding
  45. Focus key.Binding
  46. OpenEditor key.Binding
  47. }
  48. type DeleteAttachmentKeyMaps struct {
  49. AttachmentDeleteMode key.Binding
  50. Escape key.Binding
  51. DeleteAllAttachments key.Binding
  52. }
  53. var editorMaps = EditorKeyMaps{
  54. Send: key.NewBinding(
  55. key.WithKeys("enter", "ctrl+s"),
  56. key.WithHelp("enter", "send message"),
  57. ),
  58. OpenEditor: key.NewBinding(
  59. key.WithKeys("ctrl+e"),
  60. key.WithHelp("ctrl+e", "open editor"),
  61. ),
  62. Paste: key.NewBinding(
  63. key.WithKeys("ctrl+v"),
  64. key.WithHelp("ctrl+v", "paste content"),
  65. ),
  66. HistoryUp: key.NewBinding(
  67. key.WithKeys("up"),
  68. key.WithHelp("up", "previous message"),
  69. ),
  70. HistoryDown: key.NewBinding(
  71. key.WithKeys("down"),
  72. key.WithHelp("down", "next message"),
  73. ),
  74. }
  75. var DeleteKeyMaps = DeleteAttachmentKeyMaps{
  76. AttachmentDeleteMode: key.NewBinding(
  77. key.WithKeys("ctrl+r"),
  78. key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
  79. ),
  80. Escape: key.NewBinding(
  81. key.WithKeys("esc"),
  82. key.WithHelp("esc", "cancel delete mode"),
  83. ),
  84. DeleteAllAttachments: key.NewBinding(
  85. key.WithKeys("r"),
  86. key.WithHelp("ctrl+r+r", "delete all attachments"),
  87. ),
  88. }
  89. const (
  90. maxAttachments = 5
  91. )
  92. func (m *editorComponent) Init() tea.Cmd {
  93. return tea.Batch(textarea.Blink, m.spinner.Tick)
  94. }
  95. func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  96. var cmds []tea.Cmd
  97. var cmd tea.Cmd
  98. switch msg := msg.(type) {
  99. case dialog.ThemeChangedMsg:
  100. m.textarea = createTextArea(&m.textarea)
  101. case dialog.CompletionSelectedMsg:
  102. existingValue := m.textarea.Value()
  103. modifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)
  104. m.textarea.SetValue(modifiedValue)
  105. return m, nil
  106. case dialog.AttachmentAddedMsg:
  107. if len(m.attachments) >= maxAttachments {
  108. status.Error(fmt.Sprintf("cannot add more than %d images", maxAttachments))
  109. return m, cmd
  110. }
  111. m.attachments = append(m.attachments, msg.Attachment)
  112. case tea.KeyMsg:
  113. if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
  114. m.deleteMode = true
  115. return m, nil
  116. }
  117. if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
  118. m.deleteMode = false
  119. m.attachments = nil
  120. return m, nil
  121. }
  122. if m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {
  123. num := int(msg.Runes[0] - '0')
  124. m.deleteMode = false
  125. if num < 10 && len(m.attachments) > num {
  126. if num == 0 {
  127. m.attachments = m.attachments[num+1:]
  128. } else {
  129. m.attachments = slices.Delete(m.attachments, num, num+1)
  130. }
  131. return m, nil
  132. }
  133. }
  134. if key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||
  135. key.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {
  136. return m, nil
  137. }
  138. if key.Matches(msg, editorMaps.OpenEditor) {
  139. if m.app.IsBusy() {
  140. status.Warn("Agent is working, please wait...")
  141. return m, nil
  142. }
  143. value := m.textarea.Value()
  144. m.textarea.Reset()
  145. return m, m.openEditor(value)
  146. }
  147. if key.Matches(msg, DeleteKeyMaps.Escape) {
  148. m.deleteMode = false
  149. return m, nil
  150. }
  151. if key.Matches(msg, editorMaps.Paste) {
  152. imageBytes, text, err := image.GetImageFromClipboard()
  153. if err != nil {
  154. slog.Error(err.Error())
  155. return m, cmd
  156. }
  157. if len(imageBytes) != 0 {
  158. attachmentName := fmt.Sprintf("clipboard-image-%d", len(m.attachments))
  159. attachment := app.Attachment{FilePath: attachmentName, FileName: attachmentName, Content: imageBytes, MimeType: "image/png"}
  160. m.attachments = append(m.attachments, attachment)
  161. } else {
  162. m.textarea.SetValue(m.textarea.Value() + text)
  163. }
  164. return m, cmd
  165. }
  166. // Handle history navigation with up/down arrow keys
  167. // Only handle history navigation if the filepicker is not open and completion dialog is not open
  168. if m.textarea.Focused() && key.Matches(msg, editorMaps.HistoryUp) && !m.app.IsFilepickerOpen() && !m.app.IsCompletionDialogOpen() {
  169. // Get the current line number
  170. currentLine := m.textarea.Line()
  171. // Only navigate history if we're at the first line
  172. if currentLine == 0 && len(m.history) > 0 {
  173. // Save current message if we're just starting to navigate
  174. if m.historyIndex == len(m.history) {
  175. m.currentMessage = m.textarea.Value()
  176. }
  177. // Go to previous message in history
  178. if m.historyIndex > 0 {
  179. m.historyIndex--
  180. m.textarea.SetValue(m.history[m.historyIndex])
  181. }
  182. return m, nil
  183. }
  184. }
  185. if m.textarea.Focused() && key.Matches(msg, editorMaps.HistoryDown) && !m.app.IsFilepickerOpen() && !m.app.IsCompletionDialogOpen() {
  186. // Get the current line number and total lines
  187. currentLine := m.textarea.Line()
  188. value := m.textarea.Value()
  189. lines := strings.Split(value, "\n")
  190. totalLines := len(lines)
  191. // Only navigate history if we're at the last line
  192. if currentLine == totalLines-1 {
  193. if m.historyIndex < len(m.history)-1 {
  194. // Go to next message in history
  195. m.historyIndex++
  196. m.textarea.SetValue(m.history[m.historyIndex])
  197. } else if m.historyIndex == len(m.history)-1 {
  198. // Return to the current message being composed
  199. m.historyIndex = len(m.history)
  200. m.textarea.SetValue(m.currentMessage)
  201. }
  202. return m, nil
  203. }
  204. }
  205. // Handle Enter key
  206. if m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {
  207. value := m.textarea.Value()
  208. if len(value) > 0 && value[len(value)-1] == '\\' {
  209. // If the last character is a backslash, remove it and add a newline
  210. m.textarea.SetValue(value[:len(value)-1] + "\n")
  211. return m, nil
  212. } else {
  213. // Otherwise, send the message
  214. return m, m.send()
  215. }
  216. }
  217. }
  218. m.spinner, cmd = m.spinner.Update(msg)
  219. cmds = append(cmds, cmd)
  220. m.textarea, cmd = m.textarea.Update(msg)
  221. cmds = append(cmds, cmd)
  222. return m, tea.Batch(cmds...)
  223. }
  224. func (m *editorComponent) View() string {
  225. t := theme.CurrentTheme()
  226. base := styles.BaseStyle().Render
  227. muted := styles.Muted().Render
  228. promptStyle := lipgloss.NewStyle().
  229. Padding(0, 0, 0, 1).
  230. Bold(true).
  231. Foreground(t.Primary())
  232. prompt := promptStyle.Render(">")
  233. textarea := lipgloss.JoinHorizontal(
  234. lipgloss.Top,
  235. prompt,
  236. m.textarea.View(),
  237. )
  238. textarea = styles.BaseStyle().
  239. Width(m.width-2).
  240. Border(lipgloss.NormalBorder(), true, true).
  241. BorderForeground(t.Border()).
  242. Render(textarea)
  243. hint := base("enter") + muted(" send ") + base("shift") + muted("+") + base("enter") + muted(" newline")
  244. if m.app.IsBusy() {
  245. hint = muted("working") + m.spinner.View() + muted(" ") + base("esc") + muted(" interrupt")
  246. }
  247. model := ""
  248. if m.app.Model != nil {
  249. model = base(*m.app.Model.Name) + muted(" • /model")
  250. }
  251. space := m.width - 2 - lipgloss.Width(model) - lipgloss.Width(hint)
  252. spacer := lipgloss.NewStyle().Width(space).Render("")
  253. info := lipgloss.JoinHorizontal(lipgloss.Left, hint, spacer, model)
  254. info = styles.Padded().Render(info)
  255. content := lipgloss.JoinVertical(
  256. lipgloss.Top,
  257. // m.attachmentsContent(),
  258. textarea,
  259. info,
  260. )
  261. return styles.ForceReplaceBackgroundWithLipgloss(
  262. content,
  263. t.Background(),
  264. )
  265. }
  266. func (m *editorComponent) SetSize(width, height int) tea.Cmd {
  267. m.width = width
  268. m.height = height
  269. m.textarea.SetWidth(width - 5) // account for the prompt and padding right
  270. m.textarea.SetHeight(height - 3) // account for info underneath
  271. return nil
  272. }
  273. func (m *editorComponent) GetSize() (int, int) {
  274. return m.width, m.height
  275. }
  276. func (m *editorComponent) BindingKeys() []key.Binding {
  277. bindings := []key.Binding{}
  278. bindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)
  279. bindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)
  280. return bindings
  281. }
  282. func (m *editorComponent) openEditor(value string) tea.Cmd {
  283. editor := os.Getenv("EDITOR")
  284. if editor == "" {
  285. editor = "nvim"
  286. }
  287. tmpfile, err := os.CreateTemp("", "msg_*.md")
  288. tmpfile.WriteString(value)
  289. if err != nil {
  290. status.Error(err.Error())
  291. return nil
  292. }
  293. tmpfile.Close()
  294. c := exec.Command(editor, tmpfile.Name()) //nolint:gosec
  295. c.Stdin = os.Stdin
  296. c.Stdout = os.Stdout
  297. c.Stderr = os.Stderr
  298. return tea.ExecProcess(c, func(err error) tea.Msg {
  299. if err != nil {
  300. status.Error(err.Error())
  301. return nil
  302. }
  303. content, err := os.ReadFile(tmpfile.Name())
  304. if err != nil {
  305. status.Error(err.Error())
  306. return nil
  307. }
  308. if len(content) == 0 {
  309. status.Warn("Message is empty")
  310. return nil
  311. }
  312. os.Remove(tmpfile.Name())
  313. attachments := m.attachments
  314. m.attachments = nil
  315. return SendMsg{
  316. Text: string(content),
  317. Attachments: attachments,
  318. }
  319. })
  320. }
  321. func (m *editorComponent) send() tea.Cmd {
  322. value := m.textarea.Value()
  323. m.textarea.Reset()
  324. attachments := m.attachments
  325. // Save to history if not empty and not a duplicate of the last entry
  326. if value != "" {
  327. if len(m.history) == 0 || m.history[len(m.history)-1] != value {
  328. m.history = append(m.history, value)
  329. }
  330. m.historyIndex = len(m.history)
  331. m.currentMessage = ""
  332. }
  333. m.attachments = nil
  334. if value == "" {
  335. return nil
  336. }
  337. return tea.Batch(
  338. util.CmdHandler(SendMsg{
  339. Text: value,
  340. Attachments: attachments,
  341. }),
  342. )
  343. }
  344. func (m *editorComponent) attachmentsContent() string {
  345. if len(m.attachments) == 0 {
  346. return ""
  347. }
  348. t := theme.CurrentTheme()
  349. var styledAttachments []string
  350. attachmentStyles := styles.BaseStyle().
  351. MarginLeft(1).
  352. Background(t.TextMuted()).
  353. Foreground(t.Text())
  354. for i, attachment := range m.attachments {
  355. var filename string
  356. if len(attachment.FileName) > 10 {
  357. filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
  358. } else {
  359. filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
  360. }
  361. if m.deleteMode {
  362. filename = fmt.Sprintf("%d%s", i, filename)
  363. }
  364. styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
  365. }
  366. content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
  367. return content
  368. }
  369. func createTextArea(existing *textarea.Model) textarea.Model {
  370. t := theme.CurrentTheme()
  371. bgColor := t.Background()
  372. textColor := t.Text()
  373. textMutedColor := t.TextMuted()
  374. ta := textarea.New()
  375. ta.Placeholder = "It's prompting time..."
  376. ta.BlurredStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  377. ta.BlurredStyle.CursorLine = styles.BaseStyle().Background(bgColor)
  378. ta.BlurredStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  379. ta.BlurredStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  380. ta.FocusedStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  381. ta.FocusedStyle.CursorLine = styles.BaseStyle().Background(bgColor)
  382. ta.FocusedStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  383. ta.FocusedStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  384. ta.Prompt = " "
  385. ta.ShowLineNumbers = false
  386. ta.CharLimit = -1
  387. if existing != nil {
  388. ta.SetValue(existing.Value())
  389. ta.SetWidth(existing.Width())
  390. ta.SetHeight(existing.Height())
  391. }
  392. ta.Focus()
  393. return ta
  394. }
  395. func NewEditorComponent(app *app.App) tea.Model {
  396. s := spinner.New(spinner.WithSpinner(spinner.Ellipsis), spinner.WithStyle(styles.Muted().Width(3)))
  397. ta := createTextArea(nil)
  398. return &editorComponent{
  399. app: app,
  400. textarea: ta,
  401. history: []string{},
  402. historyIndex: 0,
  403. currentMessage: "",
  404. spinner: s,
  405. }
  406. }