editor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 "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().Background(t.Background()).Render
  240. muted := styles.Muted().Background(t.Background()).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 ")
  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().Background(t.Background()).Width(space).Render("")
  270. info := hint + spacer + model
  271. info = styles.Padded().Background(t.Background()).Render(info)
  272. content := strings.Join([]string{"", textarea, info}, "\n")
  273. return content
  274. }
  275. func (m *editorComponent) SetSize(width, height int) tea.Cmd {
  276. m.width = width
  277. m.height = height
  278. m.textarea.SetWidth(width - 5) // account for the prompt and padding right
  279. m.textarea.SetHeight(height - 4) // account for info underneath
  280. return nil
  281. }
  282. func (m *editorComponent) GetSize() (int, int) {
  283. return m.width, m.height
  284. }
  285. func (m *editorComponent) openEditor(value string) tea.Cmd {
  286. editor := os.Getenv("EDITOR")
  287. if editor == "" {
  288. editor = "nvim"
  289. }
  290. tmpfile, err := os.CreateTemp("", "msg_*.md")
  291. tmpfile.WriteString(value)
  292. if err != nil {
  293. status.Error(err.Error())
  294. return nil
  295. }
  296. tmpfile.Close()
  297. c := exec.Command(editor, tmpfile.Name()) //nolint:gosec
  298. c.Stdin = os.Stdin
  299. c.Stdout = os.Stdout
  300. c.Stderr = os.Stderr
  301. return tea.ExecProcess(c, func(err error) tea.Msg {
  302. if err != nil {
  303. status.Error(err.Error())
  304. return nil
  305. }
  306. content, err := os.ReadFile(tmpfile.Name())
  307. if err != nil {
  308. status.Error(err.Error())
  309. return nil
  310. }
  311. if len(content) == 0 {
  312. status.Warn("Message is empty")
  313. return nil
  314. }
  315. os.Remove(tmpfile.Name())
  316. attachments := m.attachments
  317. m.attachments = nil
  318. return SendMsg{
  319. Text: string(content),
  320. Attachments: attachments,
  321. }
  322. })
  323. }
  324. func (m *editorComponent) send() tea.Cmd {
  325. value := strings.TrimSpace(m.textarea.Value())
  326. m.textarea.Reset()
  327. attachments := m.attachments
  328. // Save to history if not empty and not a duplicate of the last entry
  329. if value != "" {
  330. if len(m.history) == 0 || m.history[len(m.history)-1] != value {
  331. m.history = append(m.history, value)
  332. }
  333. m.historyIndex = len(m.history)
  334. m.currentMessage = ""
  335. }
  336. m.attachments = nil
  337. if value == "" {
  338. return nil
  339. }
  340. // Check for slash command
  341. // if strings.HasPrefix(value, "/") {
  342. // commandName := strings.TrimPrefix(value, "/")
  343. // if _, ok := m.app.Commands[commandName]; ok {
  344. // return util.CmdHandler(commands.ExecuteCommandMsg{Name: commandName})
  345. // }
  346. // }
  347. slog.Info("Send message", "value", value)
  348. return tea.Batch(
  349. util.CmdHandler(SendMsg{
  350. Text: value,
  351. Attachments: attachments,
  352. }),
  353. )
  354. }
  355. func (m *editorComponent) attachmentsContent() string {
  356. if len(m.attachments) == 0 {
  357. return ""
  358. }
  359. t := theme.CurrentTheme()
  360. var styledAttachments []string
  361. attachmentStyles := styles.BaseStyle().
  362. MarginLeft(1).
  363. Background(t.TextMuted()).
  364. Foreground(t.Text())
  365. for i, attachment := range m.attachments {
  366. var filename string
  367. if len(attachment.FileName) > 10 {
  368. filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
  369. } else {
  370. filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
  371. }
  372. if m.deleteMode {
  373. filename = fmt.Sprintf("%d%s", i, filename)
  374. }
  375. styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
  376. }
  377. content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
  378. return content
  379. }
  380. func createTextArea(existing *textarea.Model) textarea.Model {
  381. t := theme.CurrentTheme()
  382. bgColor := t.BackgroundElement()
  383. textColor := t.Text()
  384. textMutedColor := t.TextMuted()
  385. ta := textarea.New()
  386. ta.Styles.Blurred.Base = lipgloss.NewStyle().Background(bgColor).Foreground(textColor)
  387. ta.Styles.Blurred.CursorLine = lipgloss.NewStyle().Background(bgColor)
  388. ta.Styles.Blurred.Placeholder = lipgloss.NewStyle().Background(bgColor).Foreground(textMutedColor)
  389. ta.Styles.Blurred.Text = lipgloss.NewStyle().Background(bgColor).Foreground(textColor)
  390. ta.Styles.Focused.Base = lipgloss.NewStyle().Background(bgColor).Foreground(textColor)
  391. ta.Styles.Focused.CursorLine = lipgloss.NewStyle().Background(bgColor)
  392. ta.Styles.Focused.Placeholder = lipgloss.NewStyle().Background(bgColor).Foreground(textMutedColor)
  393. ta.Styles.Focused.Text = lipgloss.NewStyle().Background(bgColor).Foreground(textColor)
  394. ta.Styles.Cursor.Color = t.Primary()
  395. ta.Prompt = " "
  396. ta.ShowLineNumbers = false
  397. ta.CharLimit = -1
  398. if existing != nil {
  399. ta.SetValue(existing.Value())
  400. ta.SetWidth(existing.Width())
  401. ta.SetHeight(existing.Height())
  402. }
  403. ta.Focus()
  404. return ta
  405. }
  406. func (m *editorComponent) GetValue() string {
  407. return m.textarea.Value()
  408. }
  409. func NewEditorComponent(app *app.App) layout.ModelWithView {
  410. s := spinner.New(spinner.WithSpinner(spinner.Ellipsis), spinner.WithStyle(styles.Muted().Width(3)))
  411. ta := createTextArea(nil)
  412. return &editorComponent{
  413. app: app,
  414. textarea: ta,
  415. history: []string{},
  416. historyIndex: 0,
  417. currentMessage: "",
  418. spinner: s,
  419. }
  420. }