editor.go 12 KB

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