editor.go 13 KB

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