editor.go 12 KB

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