editor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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/textarea"
  12. tea "github.com/charmbracelet/bubbletea"
  13. "github.com/charmbracelet/lipgloss"
  14. "github.com/sst/opencode/internal/app"
  15. "github.com/sst/opencode/internal/components/dialog"
  16. "github.com/sst/opencode/internal/image"
  17. "github.com/sst/opencode/internal/layout"
  18. "github.com/sst/opencode/internal/status"
  19. "github.com/sst/opencode/internal/styles"
  20. "github.com/sst/opencode/internal/theme"
  21. "github.com/sst/opencode/internal/util"
  22. )
  23. type editorCmp struct {
  24. width int
  25. height int
  26. app *app.App
  27. textarea textarea.Model
  28. attachments []app.Attachment
  29. deleteMode bool
  30. history []string
  31. historyIndex int
  32. currentMessage string
  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 *editorCmp) openEditor(value string) tea.Cmd {
  91. editor := os.Getenv("EDITOR")
  92. if editor == "" {
  93. editor = "nvim"
  94. }
  95. tmpfile, err := os.CreateTemp("", "msg_*.md")
  96. tmpfile.WriteString(value)
  97. if err != nil {
  98. status.Error(err.Error())
  99. return nil
  100. }
  101. tmpfile.Close()
  102. c := exec.Command(editor, tmpfile.Name()) //nolint:gosec
  103. c.Stdin = os.Stdin
  104. c.Stdout = os.Stdout
  105. c.Stderr = os.Stderr
  106. return tea.ExecProcess(c, func(err error) tea.Msg {
  107. if err != nil {
  108. status.Error(err.Error())
  109. return nil
  110. }
  111. content, err := os.ReadFile(tmpfile.Name())
  112. if err != nil {
  113. status.Error(err.Error())
  114. return nil
  115. }
  116. if len(content) == 0 {
  117. status.Warn("Message is empty")
  118. return nil
  119. }
  120. os.Remove(tmpfile.Name())
  121. attachments := m.attachments
  122. m.attachments = nil
  123. return SendMsg{
  124. Text: string(content),
  125. Attachments: attachments,
  126. }
  127. })
  128. }
  129. func (m *editorCmp) Init() tea.Cmd {
  130. return textarea.Blink
  131. }
  132. func (m *editorCmp) send() tea.Cmd {
  133. value := m.textarea.Value()
  134. m.textarea.Reset()
  135. attachments := m.attachments
  136. // Save to history if not empty and not a duplicate of the last entry
  137. if value != "" {
  138. if len(m.history) == 0 || m.history[len(m.history)-1] != value {
  139. m.history = append(m.history, value)
  140. }
  141. m.historyIndex = len(m.history)
  142. m.currentMessage = ""
  143. }
  144. m.attachments = nil
  145. if value == "" {
  146. return nil
  147. }
  148. return tea.Batch(
  149. util.CmdHandler(SendMsg{
  150. Text: value,
  151. Attachments: attachments,
  152. }),
  153. )
  154. }
  155. func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  156. var cmd tea.Cmd
  157. switch msg := msg.(type) {
  158. case dialog.ThemeChangedMsg:
  159. m.textarea = CreateTextArea(&m.textarea)
  160. case dialog.CompletionSelectedMsg:
  161. existingValue := m.textarea.Value()
  162. modifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)
  163. m.textarea.SetValue(modifiedValue)
  164. return m, nil
  165. case dialog.AttachmentAddedMsg:
  166. if len(m.attachments) >= maxAttachments {
  167. status.Error(fmt.Sprintf("cannot add more than %d images", maxAttachments))
  168. return m, cmd
  169. }
  170. m.attachments = append(m.attachments, msg.Attachment)
  171. case tea.KeyMsg:
  172. if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
  173. m.deleteMode = true
  174. return m, nil
  175. }
  176. if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
  177. m.deleteMode = false
  178. m.attachments = nil
  179. return m, nil
  180. }
  181. if m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {
  182. num := int(msg.Runes[0] - '0')
  183. m.deleteMode = false
  184. if num < 10 && len(m.attachments) > num {
  185. if num == 0 {
  186. m.attachments = m.attachments[num+1:]
  187. } else {
  188. m.attachments = slices.Delete(m.attachments, num, num+1)
  189. }
  190. return m, nil
  191. }
  192. }
  193. if key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||
  194. key.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {
  195. return m, nil
  196. }
  197. if key.Matches(msg, editorMaps.OpenEditor) {
  198. if m.app.IsBusy() {
  199. status.Warn("Agent is working, please wait...")
  200. return m, nil
  201. }
  202. value := m.textarea.Value()
  203. m.textarea.Reset()
  204. return m, m.openEditor(value)
  205. }
  206. if key.Matches(msg, DeleteKeyMaps.Escape) {
  207. m.deleteMode = false
  208. return m, nil
  209. }
  210. if key.Matches(msg, editorMaps.Paste) {
  211. imageBytes, text, err := image.GetImageFromClipboard()
  212. if err != nil {
  213. slog.Error(err.Error())
  214. return m, cmd
  215. }
  216. if len(imageBytes) != 0 {
  217. attachmentName := fmt.Sprintf("clipboard-image-%d", len(m.attachments))
  218. attachment := app.Attachment{FilePath: attachmentName, FileName: attachmentName, Content: imageBytes, MimeType: "image/png"}
  219. m.attachments = append(m.attachments, attachment)
  220. } else {
  221. m.textarea.SetValue(m.textarea.Value() + text)
  222. }
  223. return m, cmd
  224. }
  225. // Handle history navigation with up/down arrow keys
  226. // Only handle history navigation if the filepicker is not open and completion dialog is not open
  227. if m.textarea.Focused() && key.Matches(msg, editorMaps.HistoryUp) && !m.app.IsFilepickerOpen() && !m.app.IsCompletionDialogOpen() {
  228. // Get the current line number
  229. currentLine := m.textarea.Line()
  230. // Only navigate history if we're at the first line
  231. if currentLine == 0 && len(m.history) > 0 {
  232. // Save current message if we're just starting to navigate
  233. if m.historyIndex == len(m.history) {
  234. m.currentMessage = m.textarea.Value()
  235. }
  236. // Go to previous message in history
  237. if m.historyIndex > 0 {
  238. m.historyIndex--
  239. m.textarea.SetValue(m.history[m.historyIndex])
  240. }
  241. return m, nil
  242. }
  243. }
  244. if m.textarea.Focused() && key.Matches(msg, editorMaps.HistoryDown) && !m.app.IsFilepickerOpen() && !m.app.IsCompletionDialogOpen() {
  245. // Get the current line number and total lines
  246. currentLine := m.textarea.Line()
  247. value := m.textarea.Value()
  248. lines := strings.Split(value, "\n")
  249. totalLines := len(lines)
  250. // Only navigate history if we're at the last line
  251. if currentLine == totalLines-1 {
  252. if m.historyIndex < len(m.history)-1 {
  253. // Go to next message in history
  254. m.historyIndex++
  255. m.textarea.SetValue(m.history[m.historyIndex])
  256. } else if m.historyIndex == len(m.history)-1 {
  257. // Return to the current message being composed
  258. m.historyIndex = len(m.history)
  259. m.textarea.SetValue(m.currentMessage)
  260. }
  261. return m, nil
  262. }
  263. }
  264. // Handle Enter key
  265. if m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {
  266. value := m.textarea.Value()
  267. if len(value) > 0 && value[len(value)-1] == '\\' {
  268. // If the last character is a backslash, remove it and add a newline
  269. m.textarea.SetValue(value[:len(value)-1] + "\n")
  270. return m, nil
  271. } else {
  272. // Otherwise, send the message
  273. return m, m.send()
  274. }
  275. }
  276. }
  277. m.textarea, cmd = m.textarea.Update(msg)
  278. return m, cmd
  279. }
  280. func (m *editorCmp) View() string {
  281. t := theme.CurrentTheme()
  282. // Style the prompt with theme colors
  283. style := lipgloss.NewStyle().
  284. Padding(0, 0, 0, 1).
  285. Bold(true).
  286. Foreground(t.Primary())
  287. if len(m.attachments) == 0 {
  288. return lipgloss.JoinHorizontal(lipgloss.Top, style.Render(">"), m.textarea.View())
  289. }
  290. m.textarea.SetHeight(m.height - 1)
  291. return lipgloss.JoinVertical(lipgloss.Top,
  292. m.attachmentsContent(),
  293. lipgloss.JoinHorizontal(lipgloss.Top, style.Render(">"),
  294. m.textarea.View()),
  295. )
  296. }
  297. func (m *editorCmp) SetSize(width, height int) tea.Cmd {
  298. m.width = width
  299. m.height = height
  300. m.textarea.SetWidth(width - 3) // account for the prompt and padding right
  301. m.textarea.SetHeight(height)
  302. return nil
  303. }
  304. func (m *editorCmp) GetSize() (int, int) {
  305. return m.textarea.Width(), m.textarea.Height()
  306. }
  307. func (m *editorCmp) attachmentsContent() string {
  308. var styledAttachments []string
  309. t := theme.CurrentTheme()
  310. attachmentStyles := styles.BaseStyle().
  311. MarginLeft(1).
  312. Background(t.TextMuted()).
  313. Foreground(t.Text())
  314. for i, attachment := range m.attachments {
  315. var filename string
  316. if len(attachment.FileName) > 10 {
  317. filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
  318. } else {
  319. filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
  320. }
  321. if m.deleteMode {
  322. filename = fmt.Sprintf("%d%s", i, filename)
  323. }
  324. styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
  325. }
  326. content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
  327. return content
  328. }
  329. func (m *editorCmp) BindingKeys() []key.Binding {
  330. bindings := []key.Binding{}
  331. bindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)
  332. bindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)
  333. return bindings
  334. }
  335. func CreateTextArea(existing *textarea.Model) textarea.Model {
  336. t := theme.CurrentTheme()
  337. bgColor := t.Background()
  338. textColor := t.Text()
  339. textMutedColor := t.TextMuted()
  340. ta := textarea.New()
  341. ta.BlurredStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  342. ta.BlurredStyle.CursorLine = styles.BaseStyle().Background(bgColor)
  343. ta.BlurredStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  344. ta.BlurredStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  345. ta.FocusedStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  346. ta.FocusedStyle.CursorLine = styles.BaseStyle().Background(bgColor)
  347. ta.FocusedStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  348. ta.FocusedStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  349. ta.Prompt = " "
  350. ta.ShowLineNumbers = false
  351. ta.CharLimit = -1
  352. if existing != nil {
  353. ta.SetValue(existing.Value())
  354. ta.SetWidth(existing.Width())
  355. ta.SetHeight(existing.Height())
  356. }
  357. ta.Focus()
  358. return ta
  359. }
  360. func NewEditorCmp(app *app.App) tea.Model {
  361. ta := CreateTextArea(nil)
  362. return &editorCmp{
  363. app: app,
  364. textarea: ta,
  365. history: []string{},
  366. historyIndex: 0,
  367. currentMessage: "",
  368. }
  369. }