editor.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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", "ctrl+s"),
  54. key.WithHelp("enter", "send message"),
  55. ),
  56. OpenEditor: key.NewBinding(
  57. key.WithKeys("ctrl+e"),
  58. key.WithHelp("ctrl+e", "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. if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
  112. m.deleteMode = true
  113. return m, nil
  114. }
  115. if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
  116. m.deleteMode = false
  117. m.attachments = nil
  118. return m, nil
  119. }
  120. // if m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {
  121. // num := int(msg.Runes[0] - '0')
  122. // m.deleteMode = false
  123. // if num < 10 && len(m.attachments) > num {
  124. // if num == 0 {
  125. // m.attachments = m.attachments[num+1:]
  126. // } else {
  127. // m.attachments = slices.Delete(m.attachments, num, num+1)
  128. // }
  129. // return m, nil
  130. // }
  131. // }
  132. if key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||
  133. key.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {
  134. return m, nil
  135. }
  136. if key.Matches(msg, editorMaps.OpenEditor) {
  137. if m.app.IsBusy() {
  138. status.Warn("Agent is working, please wait...")
  139. return m, nil
  140. }
  141. value := m.textarea.Value()
  142. m.textarea.Reset()
  143. return m, m.openEditor(value)
  144. }
  145. if key.Matches(msg, DeleteKeyMaps.Escape) {
  146. m.deleteMode = false
  147. return m, nil
  148. }
  149. if key.Matches(msg, editorMaps.Paste) {
  150. imageBytes, text, err := image.GetImageFromClipboard()
  151. if err != nil {
  152. slog.Error(err.Error())
  153. return m, cmd
  154. }
  155. if len(imageBytes) != 0 {
  156. attachmentName := fmt.Sprintf("clipboard-image-%d", len(m.attachments))
  157. attachment := app.Attachment{FilePath: attachmentName, FileName: attachmentName, Content: imageBytes, MimeType: "image/png"}
  158. m.attachments = append(m.attachments, attachment)
  159. } else {
  160. m.textarea.SetValue(m.textarea.Value() + text)
  161. }
  162. return m, cmd
  163. }
  164. // Handle history navigation with up/down arrow keys
  165. // Only handle history navigation if the filepicker is not open and completion dialog is not open
  166. if m.textarea.Focused() && key.Matches(msg, editorMaps.HistoryUp) && !m.app.IsFilepickerOpen() && !m.app.IsCompletionDialogOpen() {
  167. // Get the current line number
  168. currentLine := m.textarea.Line()
  169. // Only navigate history if we're at the first line
  170. if currentLine == 0 && len(m.history) > 0 {
  171. // Save current message if we're just starting to navigate
  172. if m.historyIndex == len(m.history) {
  173. m.currentMessage = m.textarea.Value()
  174. }
  175. // Go to previous message in history
  176. if m.historyIndex > 0 {
  177. m.historyIndex--
  178. m.textarea.SetValue(m.history[m.historyIndex])
  179. }
  180. return m, nil
  181. }
  182. }
  183. if m.textarea.Focused() && key.Matches(msg, editorMaps.HistoryDown) && !m.app.IsFilepickerOpen() && !m.app.IsCompletionDialogOpen() {
  184. // Get the current line number and total lines
  185. currentLine := m.textarea.Line()
  186. value := m.textarea.Value()
  187. lines := strings.Split(value, "\n")
  188. totalLines := len(lines)
  189. // Only navigate history if we're at the last line
  190. if currentLine == totalLines-1 {
  191. if m.historyIndex < len(m.history)-1 {
  192. // Go to next message in history
  193. m.historyIndex++
  194. m.textarea.SetValue(m.history[m.historyIndex])
  195. } else if m.historyIndex == len(m.history)-1 {
  196. // Return to the current message being composed
  197. m.historyIndex = len(m.history)
  198. m.textarea.SetValue(m.currentMessage)
  199. }
  200. return m, nil
  201. }
  202. }
  203. // Handle Enter key
  204. if m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {
  205. value := m.textarea.Value()
  206. if len(value) > 0 && value[len(value)-1] == '\\' {
  207. // If the last character is a backslash, remove it and add a newline
  208. m.textarea.SetValue(value[:len(value)-1] + "\n")
  209. return m, nil
  210. } else {
  211. // Otherwise, send the message
  212. return m, m.send()
  213. }
  214. }
  215. }
  216. m.spinner, cmd = m.spinner.Update(msg)
  217. cmds = append(cmds, cmd)
  218. m.textarea, cmd = m.textarea.Update(msg)
  219. cmds = append(cmds, cmd)
  220. return m, tea.Batch(cmds...)
  221. }
  222. func (m *editorComponent) View() string {
  223. t := theme.CurrentTheme()
  224. base := styles.BaseStyle().Render
  225. muted := styles.Muted().Render
  226. promptStyle := lipgloss.NewStyle().
  227. Padding(0, 0, 0, 1).
  228. Bold(true).
  229. Foreground(t.Primary())
  230. prompt := promptStyle.Render(">")
  231. textarea := lipgloss.JoinHorizontal(
  232. lipgloss.Top,
  233. prompt,
  234. m.textarea.View(),
  235. )
  236. textarea = styles.BaseStyle().
  237. Width(m.width).
  238. Border(lipgloss.NormalBorder(), true, true).
  239. BorderForeground(t.Border()).
  240. Render(textarea)
  241. hint := base("enter") + muted(" send ") + base("shift") + muted("+") + base("enter") + muted(" newline")
  242. if m.app.IsBusy() {
  243. hint = muted("working") + m.spinner.View() + muted(" ") + base("esc") + muted(" interrupt")
  244. }
  245. model := ""
  246. if m.app.Model != nil {
  247. model = base(*m.app.Model.Name) + muted(" • /model")
  248. }
  249. space := m.width - 2 - lipgloss.Width(model) - lipgloss.Width(hint)
  250. spacer := lipgloss.NewStyle().Width(space).Render("")
  251. info := lipgloss.JoinHorizontal(lipgloss.Left, hint, spacer, model)
  252. info = styles.Padded().Render(info)
  253. content := lipgloss.JoinVertical(
  254. lipgloss.Top,
  255. // m.attachmentsContent(),
  256. textarea,
  257. info,
  258. )
  259. return content
  260. }
  261. func (m *editorComponent) SetSize(width, height int) tea.Cmd {
  262. m.width = width
  263. m.height = height
  264. m.textarea.SetWidth(width - 5) // account for the prompt and padding right
  265. m.textarea.SetHeight(height - 3) // account for info underneath
  266. return nil
  267. }
  268. func (m *editorComponent) GetSize() (int, int) {
  269. return m.width, m.height
  270. }
  271. func (m *editorComponent) BindingKeys() []key.Binding {
  272. bindings := []key.Binding{}
  273. bindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)
  274. bindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)
  275. return bindings
  276. }
  277. func (m *editorComponent) openEditor(value string) tea.Cmd {
  278. editor := os.Getenv("EDITOR")
  279. if editor == "" {
  280. editor = "nvim"
  281. }
  282. tmpfile, err := os.CreateTemp("", "msg_*.md")
  283. tmpfile.WriteString(value)
  284. if err != nil {
  285. status.Error(err.Error())
  286. return nil
  287. }
  288. tmpfile.Close()
  289. c := exec.Command(editor, tmpfile.Name()) //nolint:gosec
  290. c.Stdin = os.Stdin
  291. c.Stdout = os.Stdout
  292. c.Stderr = os.Stderr
  293. return tea.ExecProcess(c, func(err error) tea.Msg {
  294. if err != nil {
  295. status.Error(err.Error())
  296. return nil
  297. }
  298. content, err := os.ReadFile(tmpfile.Name())
  299. if err != nil {
  300. status.Error(err.Error())
  301. return nil
  302. }
  303. if len(content) == 0 {
  304. status.Warn("Message is empty")
  305. return nil
  306. }
  307. os.Remove(tmpfile.Name())
  308. attachments := m.attachments
  309. m.attachments = nil
  310. return SendMsg{
  311. Text: string(content),
  312. Attachments: attachments,
  313. }
  314. })
  315. }
  316. func (m *editorComponent) send() tea.Cmd {
  317. value := m.textarea.Value()
  318. m.textarea.Reset()
  319. attachments := m.attachments
  320. // Save to history if not empty and not a duplicate of the last entry
  321. if value != "" {
  322. if len(m.history) == 0 || m.history[len(m.history)-1] != value {
  323. m.history = append(m.history, value)
  324. }
  325. m.historyIndex = len(m.history)
  326. m.currentMessage = ""
  327. }
  328. m.attachments = nil
  329. if value == "" {
  330. return nil
  331. }
  332. return tea.Batch(
  333. util.CmdHandler(SendMsg{
  334. Text: value,
  335. Attachments: attachments,
  336. }),
  337. )
  338. }
  339. func (m *editorComponent) attachmentsContent() string {
  340. if len(m.attachments) == 0 {
  341. return ""
  342. }
  343. t := theme.CurrentTheme()
  344. var styledAttachments []string
  345. attachmentStyles := styles.BaseStyle().
  346. MarginLeft(1).
  347. Background(t.TextMuted()).
  348. Foreground(t.Text())
  349. for i, attachment := range m.attachments {
  350. var filename string
  351. if len(attachment.FileName) > 10 {
  352. filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
  353. } else {
  354. filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
  355. }
  356. if m.deleteMode {
  357. filename = fmt.Sprintf("%d%s", i, filename)
  358. }
  359. styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
  360. }
  361. content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
  362. return content
  363. }
  364. func createTextArea(existing *textarea.Model) textarea.Model {
  365. t := theme.CurrentTheme()
  366. bgColor := t.Background()
  367. textColor := t.Text()
  368. textMutedColor := t.TextMuted()
  369. ta := textarea.New()
  370. ta.Placeholder = "It's prompting time..."
  371. ta.Styles.Blurred.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  372. ta.Styles.Blurred.CursorLine = styles.BaseStyle().Background(bgColor)
  373. ta.Styles.Blurred.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  374. ta.Styles.Blurred.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  375. ta.Styles.Focused.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  376. ta.Styles.Focused.CursorLine = styles.BaseStyle().Background(bgColor)
  377. ta.Styles.Focused.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  378. ta.Styles.Focused.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  379. ta.Prompt = " "
  380. ta.ShowLineNumbers = false
  381. ta.CharLimit = -1
  382. if existing != nil {
  383. ta.SetValue(existing.Value())
  384. ta.SetWidth(existing.Width())
  385. ta.SetHeight(existing.Height())
  386. }
  387. ta.Focus()
  388. return ta
  389. }
  390. func NewEditorComponent(app *app.App) layout.ModelWithView {
  391. s := spinner.New(spinner.WithSpinner(spinner.Ellipsis), spinner.WithStyle(styles.Muted().Width(3)))
  392. ta := createTextArea(nil)
  393. return &editorComponent{
  394. app: app,
  395. textarea: ta,
  396. history: []string{},
  397. historyIndex: 0,
  398. currentMessage: "",
  399. spinner: s,
  400. }
  401. }