editor.go 13 KB

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