editor.go 12 KB

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