editor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. package chat
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "log/slog"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "github.com/charmbracelet/bubbles/v2/spinner"
  11. tea "github.com/charmbracelet/bubbletea/v2"
  12. "github.com/charmbracelet/lipgloss/v2"
  13. "github.com/google/uuid"
  14. "github.com/sst/opencode-sdk-go"
  15. "github.com/sst/opencode/internal/app"
  16. "github.com/sst/opencode/internal/clipboard"
  17. "github.com/sst/opencode/internal/commands"
  18. "github.com/sst/opencode/internal/components/dialog"
  19. "github.com/sst/opencode/internal/components/textarea"
  20. "github.com/sst/opencode/internal/styles"
  21. "github.com/sst/opencode/internal/theme"
  22. "github.com/sst/opencode/internal/util"
  23. )
  24. type EditorComponent interface {
  25. tea.Model
  26. View(width int) string
  27. Content(width int) string
  28. Lines() int
  29. Value() string
  30. Length() int
  31. Focused() bool
  32. Focus() (tea.Model, tea.Cmd)
  33. Blur()
  34. Submit() (tea.Model, tea.Cmd)
  35. Clear() (tea.Model, tea.Cmd)
  36. Paste() (tea.Model, tea.Cmd)
  37. Newline() (tea.Model, tea.Cmd)
  38. SetInterruptKeyInDebounce(inDebounce bool)
  39. SetExitKeyInDebounce(inDebounce bool)
  40. }
  41. type editorComponent struct {
  42. app *app.App
  43. textarea textarea.Model
  44. spinner spinner.Model
  45. interruptKeyInDebounce bool
  46. exitKeyInDebounce bool
  47. }
  48. func (m *editorComponent) Init() tea.Cmd {
  49. return tea.Batch(m.textarea.Focus(), m.spinner.Tick, tea.EnableReportFocus)
  50. }
  51. func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  52. var cmds []tea.Cmd
  53. var cmd tea.Cmd
  54. switch msg := msg.(type) {
  55. case spinner.TickMsg:
  56. m.spinner, cmd = m.spinner.Update(msg)
  57. return m, cmd
  58. case tea.KeyPressMsg:
  59. // Maximize editor responsiveness for printable characters
  60. if msg.Text != "" {
  61. m.textarea, cmd = m.textarea.Update(msg)
  62. cmds = append(cmds, cmd)
  63. return m, tea.Batch(cmds...)
  64. }
  65. case tea.PasteMsg:
  66. text := string(msg)
  67. text = strings.ReplaceAll(text, "\\", "")
  68. text, err := strconv.Unquote(`"` + text + `"`)
  69. if err != nil {
  70. slog.Error("Failed to unquote text", "error", err)
  71. m.textarea.InsertRunesFromUserInput([]rune(msg))
  72. return m, nil
  73. }
  74. if _, err := os.Stat(text); err != nil {
  75. slog.Error("Failed to paste file", "error", err)
  76. m.textarea.InsertRunesFromUserInput([]rune(msg))
  77. return m, nil
  78. }
  79. filePath := text
  80. ext := strings.ToLower(filepath.Ext(filePath))
  81. mediaType := ""
  82. switch ext {
  83. case ".jpg":
  84. mediaType = "image/jpeg"
  85. case ".png", ".jpeg", ".gif", ".webp":
  86. mediaType = "image/" + ext[1:]
  87. case ".pdf":
  88. mediaType = "application/pdf"
  89. default:
  90. attachment := &textarea.Attachment{
  91. ID: uuid.NewString(),
  92. Display: "@" + filePath,
  93. URL: fmt.Sprintf("file://./%s", filePath),
  94. Filename: filePath,
  95. MediaType: "text/plain",
  96. }
  97. m.textarea.InsertAttachment(attachment)
  98. m.textarea.InsertString(" ")
  99. return m, nil
  100. }
  101. fileBytes, err := os.ReadFile(filePath)
  102. if err != nil {
  103. slog.Error("Failed to read file", "error", err)
  104. m.textarea.InsertRunesFromUserInput([]rune(msg))
  105. return m, nil
  106. }
  107. base64EncodedFile := base64.StdEncoding.EncodeToString(fileBytes)
  108. url := fmt.Sprintf("data:%s;base64,%s", mediaType, base64EncodedFile)
  109. attachmentCount := len(m.textarea.GetAttachments())
  110. attachmentIndex := attachmentCount + 1
  111. label := "File"
  112. if strings.HasPrefix(mediaType, "image/") {
  113. label = "Image"
  114. }
  115. attachment := &textarea.Attachment{
  116. ID: uuid.NewString(),
  117. MediaType: mediaType,
  118. Display: fmt.Sprintf("[%s #%d]", label, attachmentIndex),
  119. URL: url,
  120. Filename: filePath,
  121. }
  122. m.textarea.InsertAttachment(attachment)
  123. m.textarea.InsertString(" ")
  124. case tea.ClipboardMsg:
  125. text := string(msg)
  126. m.textarea.InsertRunesFromUserInput([]rune(text))
  127. case dialog.ThemeSelectedMsg:
  128. m.textarea = m.resetTextareaStyles()
  129. m.spinner = createSpinner()
  130. return m, tea.Batch(m.spinner.Tick, m.textarea.Focus())
  131. case dialog.CompletionSelectedMsg:
  132. switch msg.ProviderID {
  133. case "commands":
  134. commandName := strings.TrimPrefix(msg.CompletionValue, "/")
  135. updated, cmd := m.Clear()
  136. m = updated.(*editorComponent)
  137. cmds = append(cmds, cmd)
  138. cmds = append(cmds, util.CmdHandler(commands.ExecuteCommandMsg(m.app.Commands[commands.CommandName(commandName)])))
  139. return m, tea.Batch(cmds...)
  140. case "files":
  141. atIndex := m.textarea.LastRuneIndex('@')
  142. if atIndex == -1 {
  143. // Should not happen, but as a fallback, just insert.
  144. m.textarea.InsertString(msg.CompletionValue + " ")
  145. return m, nil
  146. }
  147. // The range to replace is from the '@' up to the current cursor position.
  148. // Replace the search term (e.g., "@search") with an empty string first.
  149. cursorCol := m.textarea.CursorColumn()
  150. m.textarea.ReplaceRange(atIndex, cursorCol, "")
  151. // Now, insert the attachment at the position where the '@' was.
  152. // The cursor is now at `atIndex` after the replacement.
  153. filePath := msg.CompletionValue
  154. extension := filepath.Ext(filePath)
  155. mediaType := ""
  156. switch extension {
  157. case ".jpg":
  158. mediaType = "image/jpeg"
  159. case ".png", ".jpeg", ".gif", ".webp":
  160. mediaType = "image/" + extension[1:]
  161. case ".pdf":
  162. mediaType = "application/pdf"
  163. default:
  164. mediaType = "text/plain"
  165. }
  166. attachment := &textarea.Attachment{
  167. ID: uuid.NewString(),
  168. Display: "@" + filePath,
  169. URL: fmt.Sprintf("file://./%s", filePath),
  170. Filename: filePath,
  171. MediaType: mediaType,
  172. }
  173. m.textarea.InsertAttachment(attachment)
  174. m.textarea.InsertString(" ")
  175. return m, nil
  176. default:
  177. existingValue := m.textarea.Value()
  178. lastSpaceIndex := strings.LastIndex(existingValue, " ")
  179. if lastSpaceIndex == -1 {
  180. m.textarea.SetValue(msg.CompletionValue + " ")
  181. } else {
  182. modifiedValue := existingValue[:lastSpaceIndex+1] + msg.CompletionValue
  183. m.textarea.SetValue(modifiedValue + " ")
  184. }
  185. return m, nil
  186. }
  187. }
  188. m.spinner, cmd = m.spinner.Update(msg)
  189. cmds = append(cmds, cmd)
  190. m.textarea, cmd = m.textarea.Update(msg)
  191. cmds = append(cmds, cmd)
  192. return m, tea.Batch(cmds...)
  193. }
  194. func (m *editorComponent) Content(width int) string {
  195. t := theme.CurrentTheme()
  196. base := styles.NewStyle().Foreground(t.Text()).Background(t.Background()).Render
  197. muted := styles.NewStyle().Foreground(t.TextMuted()).Background(t.Background()).Render
  198. promptStyle := styles.NewStyle().Foreground(t.Primary()).
  199. Padding(0, 0, 0, 1).
  200. Bold(true)
  201. prompt := promptStyle.Render(">")
  202. m.textarea.SetWidth(width - 6)
  203. textarea := lipgloss.JoinHorizontal(
  204. lipgloss.Top,
  205. prompt,
  206. m.textarea.View(),
  207. )
  208. textarea = styles.NewStyle().
  209. Background(t.BackgroundElement()).
  210. Width(width).
  211. PaddingTop(1).
  212. PaddingBottom(1).
  213. BorderStyle(lipgloss.ThickBorder()).
  214. BorderForeground(t.Border()).
  215. BorderBackground(t.Background()).
  216. BorderLeft(true).
  217. BorderRight(true).
  218. Render(textarea)
  219. hint := base(m.getSubmitKeyText()) + muted(" send ")
  220. if m.exitKeyInDebounce {
  221. keyText := m.getExitKeyText()
  222. hint = base(keyText+" again") + muted(" to exit")
  223. } else if m.app.IsBusy() {
  224. keyText := m.getInterruptKeyText()
  225. if m.interruptKeyInDebounce {
  226. hint = muted(
  227. "working",
  228. ) + m.spinner.View() + muted(
  229. " ",
  230. ) + base(
  231. keyText+" again",
  232. ) + muted(
  233. " interrupt",
  234. )
  235. } else {
  236. hint = muted("working") + m.spinner.View() + muted(" ") + base(keyText) + muted(" interrupt")
  237. }
  238. }
  239. model := ""
  240. if m.app.Model != nil {
  241. model = muted(m.app.Provider.Name) + base(" "+m.app.Model.Name)
  242. }
  243. space := width - 2 - lipgloss.Width(model) - lipgloss.Width(hint)
  244. spacer := styles.NewStyle().Background(t.Background()).Width(space).Render("")
  245. info := hint + spacer + model
  246. info = styles.NewStyle().Background(t.Background()).Padding(0, 1).Render(info)
  247. content := strings.Join([]string{"", textarea, info}, "\n")
  248. return content
  249. }
  250. func (m *editorComponent) View(width int) string {
  251. if m.Lines() > 1 {
  252. return lipgloss.Place(
  253. width,
  254. 5,
  255. lipgloss.Center,
  256. lipgloss.Center,
  257. "",
  258. styles.WhitespaceStyle(theme.CurrentTheme().Background()),
  259. )
  260. }
  261. return m.Content(width)
  262. }
  263. func (m *editorComponent) Focused() bool {
  264. return m.textarea.Focused()
  265. }
  266. func (m *editorComponent) Focus() (tea.Model, tea.Cmd) {
  267. return m, m.textarea.Focus()
  268. }
  269. func (m *editorComponent) Blur() {
  270. m.textarea.Blur()
  271. }
  272. func (m *editorComponent) Lines() int {
  273. return m.textarea.LineCount()
  274. }
  275. func (m *editorComponent) Value() string {
  276. return m.textarea.Value()
  277. }
  278. func (m *editorComponent) Length() int {
  279. return m.textarea.Length()
  280. }
  281. func (m *editorComponent) Submit() (tea.Model, tea.Cmd) {
  282. value := strings.TrimSpace(m.Value())
  283. if value == "" {
  284. return m, nil
  285. }
  286. if len(value) > 0 && value[len(value)-1] == '\\' {
  287. // If the last character is a backslash, remove it and add a newline
  288. m.textarea.ReplaceRange(len(value)-1, len(value), "")
  289. m.textarea.InsertString("\n")
  290. return m, nil
  291. }
  292. var cmds []tea.Cmd
  293. attachments := m.textarea.GetAttachments()
  294. fileParts := make([]opencode.FilePartParam, 0)
  295. for _, attachment := range attachments {
  296. fileParts = append(fileParts, opencode.FilePartParam{
  297. Type: opencode.F(opencode.FilePartTypeFile),
  298. Mime: opencode.F(attachment.MediaType),
  299. URL: opencode.F(attachment.URL),
  300. Filename: opencode.F(attachment.Filename),
  301. })
  302. }
  303. updated, cmd := m.Clear()
  304. m = updated.(*editorComponent)
  305. cmds = append(cmds, cmd)
  306. cmds = append(cmds, util.CmdHandler(app.SendMsg{Text: value, Attachments: fileParts}))
  307. return m, tea.Batch(cmds...)
  308. }
  309. func (m *editorComponent) Clear() (tea.Model, tea.Cmd) {
  310. m.textarea.Reset()
  311. return m, nil
  312. }
  313. func (m *editorComponent) Paste() (tea.Model, tea.Cmd) {
  314. imageBytes := clipboard.Read(clipboard.FmtImage)
  315. if imageBytes != nil {
  316. attachmentCount := len(m.textarea.GetAttachments())
  317. attachmentIndex := attachmentCount + 1
  318. base64EncodedFile := base64.StdEncoding.EncodeToString(imageBytes)
  319. attachment := &textarea.Attachment{
  320. ID: uuid.NewString(),
  321. MediaType: "image/png",
  322. Display: fmt.Sprintf("[Image #%d]", attachmentIndex),
  323. Filename: fmt.Sprintf("image-%d.png", attachmentIndex),
  324. URL: fmt.Sprintf("data:image/png;base64,%s", base64EncodedFile),
  325. }
  326. m.textarea.InsertAttachment(attachment)
  327. m.textarea.InsertString(" ")
  328. return m, nil
  329. }
  330. textBytes := clipboard.Read(clipboard.FmtText)
  331. if textBytes != nil {
  332. m.textarea.InsertRunesFromUserInput([]rune(string(textBytes)))
  333. return m, nil
  334. }
  335. // fallback to reading the clipboard using OSC52
  336. return m, tea.ReadClipboard
  337. }
  338. func (m *editorComponent) Newline() (tea.Model, tea.Cmd) {
  339. m.textarea.Newline()
  340. return m, nil
  341. }
  342. func (m *editorComponent) SetInterruptKeyInDebounce(inDebounce bool) {
  343. m.interruptKeyInDebounce = inDebounce
  344. }
  345. func (m *editorComponent) SetExitKeyInDebounce(inDebounce bool) {
  346. m.exitKeyInDebounce = inDebounce
  347. }
  348. func (m *editorComponent) getInterruptKeyText() string {
  349. return m.app.Commands[commands.SessionInterruptCommand].Keys()[0]
  350. }
  351. func (m *editorComponent) getSubmitKeyText() string {
  352. return m.app.Commands[commands.InputSubmitCommand].Keys()[0]
  353. }
  354. func (m *editorComponent) getExitKeyText() string {
  355. return m.app.Commands[commands.AppExitCommand].Keys()[0]
  356. }
  357. func (m *editorComponent) resetTextareaStyles() textarea.Model {
  358. t := theme.CurrentTheme()
  359. bgColor := t.BackgroundElement()
  360. textColor := t.Text()
  361. textMutedColor := t.TextMuted()
  362. ta := m.textarea
  363. ta.Styles.Blurred.Base = styles.NewStyle().Foreground(textColor).Background(bgColor).Lipgloss()
  364. ta.Styles.Blurred.CursorLine = styles.NewStyle().Background(bgColor).Lipgloss()
  365. ta.Styles.Blurred.Placeholder = styles.NewStyle().
  366. Foreground(textMutedColor).
  367. Background(bgColor).
  368. Lipgloss()
  369. ta.Styles.Blurred.Text = styles.NewStyle().Foreground(textColor).Background(bgColor).Lipgloss()
  370. ta.Styles.Focused.Base = styles.NewStyle().Foreground(textColor).Background(bgColor).Lipgloss()
  371. ta.Styles.Focused.CursorLine = styles.NewStyle().Background(bgColor).Lipgloss()
  372. ta.Styles.Focused.Placeholder = styles.NewStyle().
  373. Foreground(textMutedColor).
  374. Background(bgColor).
  375. Lipgloss()
  376. ta.Styles.Focused.Text = styles.NewStyle().Foreground(textColor).Background(bgColor).Lipgloss()
  377. ta.Styles.Attachment = styles.NewStyle().
  378. Foreground(t.Secondary()).
  379. Background(bgColor).
  380. Lipgloss()
  381. ta.Styles.SelectedAttachment = styles.NewStyle().
  382. Foreground(t.Text()).
  383. Background(t.Secondary()).
  384. Lipgloss()
  385. ta.Styles.Cursor.Color = t.Primary()
  386. return ta
  387. }
  388. func createSpinner() spinner.Model {
  389. t := theme.CurrentTheme()
  390. return spinner.New(
  391. spinner.WithSpinner(spinner.Ellipsis),
  392. spinner.WithStyle(
  393. styles.NewStyle().
  394. Background(t.Background()).
  395. Foreground(t.TextMuted()).
  396. Width(3).
  397. Lipgloss(),
  398. ),
  399. )
  400. }
  401. func NewEditorComponent(app *app.App) EditorComponent {
  402. s := createSpinner()
  403. ta := textarea.New()
  404. ta.Prompt = " "
  405. ta.ShowLineNumbers = false
  406. ta.CharLimit = -1
  407. m := &editorComponent{
  408. app: app,
  409. textarea: ta,
  410. spinner: s,
  411. interruptKeyInDebounce: false,
  412. }
  413. m.resetTextareaStyles()
  414. return m
  415. }