editor.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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/styles"
  18. "github.com/sst/opencode/internal/theme"
  19. "github.com/sst/opencode/internal/util"
  20. )
  21. type EditorComponent interface {
  22. tea.Model
  23. tea.ViewModel
  24. Value() string
  25. }
  26. type editorComponent struct {
  27. width int
  28. height int
  29. app *app.App
  30. textarea textarea.Model
  31. attachments []app.Attachment
  32. deleteMode bool
  33. history []string
  34. historyIndex int
  35. currentMessage string
  36. spinner spinner.Model
  37. }
  38. type EditorKeyMaps struct {
  39. Send key.Binding
  40. OpenEditor key.Binding
  41. Paste key.Binding
  42. HistoryUp key.Binding
  43. HistoryDown key.Binding
  44. }
  45. type DeleteAttachmentKeyMaps struct {
  46. AttachmentDeleteMode key.Binding
  47. Escape key.Binding
  48. DeleteAllAttachments key.Binding
  49. }
  50. var editorMaps = EditorKeyMaps{
  51. Send: key.NewBinding(
  52. key.WithKeys("enter"),
  53. key.WithHelp("enter", "send message"),
  54. ),
  55. OpenEditor: key.NewBinding(
  56. key.WithKeys("f12"),
  57. key.WithHelp("f12", "open editor"),
  58. ),
  59. Paste: key.NewBinding(
  60. key.WithKeys("ctrl+v"),
  61. key.WithHelp("ctrl+v", "paste content"),
  62. ),
  63. HistoryUp: key.NewBinding(
  64. key.WithKeys("up"),
  65. key.WithHelp("up", "previous message"),
  66. ),
  67. HistoryDown: key.NewBinding(
  68. key.WithKeys("down"),
  69. key.WithHelp("down", "next message"),
  70. ),
  71. }
  72. var DeleteKeyMaps = DeleteAttachmentKeyMaps{
  73. AttachmentDeleteMode: key.NewBinding(
  74. key.WithKeys("ctrl+r"),
  75. key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
  76. ),
  77. Escape: key.NewBinding(
  78. key.WithKeys("esc"),
  79. key.WithHelp("esc", "cancel delete mode"),
  80. ),
  81. DeleteAllAttachments: key.NewBinding(
  82. key.WithKeys("r"),
  83. key.WithHelp("ctrl+r+r", "delete all attachments"),
  84. ),
  85. }
  86. const (
  87. maxAttachments = 5
  88. )
  89. func (m *editorComponent) Init() tea.Cmd {
  90. return tea.Batch(textarea.Blink, m.spinner.Tick, tea.EnableReportFocus)
  91. }
  92. func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  93. var cmds []tea.Cmd
  94. var cmd tea.Cmd
  95. switch msg := msg.(type) {
  96. case dialog.ThemeSelectedMsg:
  97. m.textarea = createTextArea(&m.textarea)
  98. m.spinner = createSpinner()
  99. return m, m.spinner.Tick
  100. case dialog.CompletionSelectedMsg:
  101. if msg.IsCommand {
  102. // Execute the command directly
  103. commandName := strings.TrimPrefix(msg.CompletionValue, "/")
  104. m.textarea.Reset()
  105. return m, util.CmdHandler(commands.ExecuteCommandMsg{Name: commandName})
  106. } else {
  107. // For files, replace the text in the editor
  108. existingValue := m.textarea.Value()
  109. modifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)
  110. m.textarea.SetValue(modifiedValue)
  111. return m, nil
  112. }
  113. case tea.KeyMsg:
  114. switch msg.String() {
  115. case "ctrl+c":
  116. if m.textarea.Value() != "" {
  117. m.textarea.Reset()
  118. return m, func() tea.Msg {
  119. return nil
  120. }
  121. }
  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().Background(t.Background()).Render
  245. muted := styles.Muted().Background(t.Background()).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 ")
  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().Background(t.Background()).Width(space).Render("")
  275. info := hint + spacer + model
  276. info = styles.Padded().Background(t.Background()).Render(info)
  277. content := strings.Join([]string{"", textarea, info}, "\n")
  278. return content
  279. }
  280. func (m *editorComponent) SetSize(width, height int) tea.Cmd {
  281. m.width = width
  282. m.height = height
  283. m.textarea.SetWidth(width - 5) // account for the prompt and padding right
  284. m.textarea.SetHeight(height - 4) // account for info underneath
  285. return nil
  286. }
  287. func (m *editorComponent) GetSize() (int, int) {
  288. return m.width, m.height
  289. }
  290. func (m *editorComponent) openEditor(value string) tea.Cmd {
  291. editor := os.Getenv("EDITOR")
  292. if editor == "" {
  293. editor = "nvim"
  294. }
  295. tmpfile, err := os.CreateTemp("", "msg_*.md")
  296. tmpfile.WriteString(value)
  297. if err != nil {
  298. // status.Error(err.Error())
  299. return nil
  300. }
  301. tmpfile.Close()
  302. c := exec.Command(editor, tmpfile.Name()) //nolint:gosec
  303. c.Stdin = os.Stdin
  304. c.Stdout = os.Stdout
  305. c.Stderr = os.Stderr
  306. return tea.ExecProcess(c, func(err error) tea.Msg {
  307. if err != nil {
  308. // status.Error(err.Error())
  309. return nil
  310. }
  311. content, err := os.ReadFile(tmpfile.Name())
  312. if err != nil {
  313. // status.Error(err.Error())
  314. return nil
  315. }
  316. if len(content) == 0 {
  317. // status.Warn("Message is empty")
  318. return nil
  319. }
  320. os.Remove(tmpfile.Name())
  321. attachments := m.attachments
  322. m.attachments = nil
  323. return SendMsg{
  324. Text: string(content),
  325. Attachments: attachments,
  326. }
  327. })
  328. }
  329. func (m *editorComponent) send() tea.Cmd {
  330. value := strings.TrimSpace(m.textarea.Value())
  331. m.textarea.Reset()
  332. attachments := m.attachments
  333. // Save to history if not empty and not a duplicate of the last entry
  334. if value != "" {
  335. if len(m.history) == 0 || m.history[len(m.history)-1] != value {
  336. m.history = append(m.history, value)
  337. }
  338. m.historyIndex = len(m.history)
  339. m.currentMessage = ""
  340. }
  341. m.attachments = nil
  342. if value == "" {
  343. return nil
  344. }
  345. // Check for slash command
  346. // if strings.HasPrefix(value, "/") {
  347. // commandName := strings.TrimPrefix(value, "/")
  348. // if _, ok := m.app.Commands[commandName]; ok {
  349. // return util.CmdHandler(commands.ExecuteCommandMsg{Name: commandName})
  350. // }
  351. // }
  352. return tea.Batch(
  353. util.CmdHandler(SendMsg{
  354. Text: value,
  355. Attachments: attachments,
  356. }),
  357. )
  358. }
  359. func createTextArea(existing *textarea.Model) textarea.Model {
  360. t := theme.CurrentTheme()
  361. bgColor := t.BackgroundElement()
  362. textColor := t.Text()
  363. textMutedColor := t.TextMuted()
  364. ta := textarea.New()
  365. ta.Styles.Blurred.Base = lipgloss.NewStyle().Background(bgColor).Foreground(textColor)
  366. ta.Styles.Blurred.CursorLine = lipgloss.NewStyle().Background(bgColor)
  367. ta.Styles.Blurred.Placeholder = lipgloss.NewStyle().Background(bgColor).Foreground(textMutedColor)
  368. ta.Styles.Blurred.Text = lipgloss.NewStyle().Background(bgColor).Foreground(textColor)
  369. ta.Styles.Focused.Base = lipgloss.NewStyle().Background(bgColor).Foreground(textColor)
  370. ta.Styles.Focused.CursorLine = lipgloss.NewStyle().Background(bgColor)
  371. ta.Styles.Focused.Placeholder = lipgloss.NewStyle().Background(bgColor).Foreground(textMutedColor)
  372. ta.Styles.Focused.Text = lipgloss.NewStyle().Background(bgColor).Foreground(textColor)
  373. ta.Styles.Cursor.Color = t.Primary()
  374. ta.Prompt = " "
  375. ta.ShowLineNumbers = false
  376. ta.CharLimit = -1
  377. if existing != nil {
  378. ta.SetValue(existing.Value())
  379. ta.SetWidth(existing.Width())
  380. ta.SetHeight(existing.Height())
  381. }
  382. ta.Focus()
  383. return ta
  384. }
  385. func createSpinner() spinner.Model {
  386. return spinner.New(
  387. spinner.WithSpinner(spinner.Ellipsis),
  388. spinner.WithStyle(
  389. styles.
  390. Muted().
  391. Background(theme.CurrentTheme().Background()).
  392. Width(3)),
  393. )
  394. }
  395. func (m *editorComponent) Value() string {
  396. return m.textarea.Value()
  397. }
  398. func NewEditorComponent(app *app.App) EditorComponent {
  399. s := createSpinner()
  400. ta := createTextArea(nil)
  401. return &editorComponent{
  402. app: app,
  403. textarea: ta,
  404. history: []string{},
  405. historyIndex: 0,
  406. currentMessage: "",
  407. spinner: s,
  408. }
  409. }