editor.go 11 KB

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