editor.go 12 KB

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