editor.go 12 KB

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