editor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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.Item.GetProviderID() {
  133. case "commands":
  134. commandName := strings.TrimPrefix(msg.Item.GetValue(), "/")
  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.Item.GetValue() + " ")
  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.Item.GetValue()
  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. case "symbols":
  177. atIndex := m.textarea.LastRuneIndex('@')
  178. if atIndex == -1 {
  179. // Should not happen, but as a fallback, just insert.
  180. m.textarea.InsertString(msg.Item.GetValue() + " ")
  181. return m, nil
  182. }
  183. cursorCol := m.textarea.CursorColumn()
  184. m.textarea.ReplaceRange(atIndex, cursorCol, "")
  185. symbol := msg.Item.GetRaw().(opencode.Symbol)
  186. parts := strings.Split(symbol.Name, ".")
  187. lastPart := parts[len(parts)-1]
  188. attachment := &textarea.Attachment{
  189. ID: uuid.NewString(),
  190. Display: "@" + lastPart,
  191. URL: msg.Item.GetValue(),
  192. Filename: lastPart,
  193. MediaType: "text/plain",
  194. }
  195. m.textarea.InsertAttachment(attachment)
  196. m.textarea.InsertString(" ")
  197. return m, nil
  198. default:
  199. slog.Debug("Unknown provider", "provider", msg.Item.GetProviderID())
  200. return m, nil
  201. }
  202. }
  203. m.spinner, cmd = m.spinner.Update(msg)
  204. cmds = append(cmds, cmd)
  205. m.textarea, cmd = m.textarea.Update(msg)
  206. cmds = append(cmds, cmd)
  207. return m, tea.Batch(cmds...)
  208. }
  209. func (m *editorComponent) Content(width int) string {
  210. t := theme.CurrentTheme()
  211. base := styles.NewStyle().Foreground(t.Text()).Background(t.Background()).Render
  212. muted := styles.NewStyle().Foreground(t.TextMuted()).Background(t.Background()).Render
  213. promptStyle := styles.NewStyle().Foreground(t.Primary()).
  214. Padding(0, 0, 0, 1).
  215. Bold(true)
  216. prompt := promptStyle.Render(">")
  217. m.textarea.SetWidth(width - 6)
  218. textarea := lipgloss.JoinHorizontal(
  219. lipgloss.Top,
  220. prompt,
  221. m.textarea.View(),
  222. )
  223. textarea = styles.NewStyle().
  224. Background(t.BackgroundElement()).
  225. Width(width).
  226. PaddingTop(1).
  227. PaddingBottom(1).
  228. BorderStyle(lipgloss.ThickBorder()).
  229. BorderForeground(t.Border()).
  230. BorderBackground(t.Background()).
  231. BorderLeft(true).
  232. BorderRight(true).
  233. Render(textarea)
  234. hint := base(m.getSubmitKeyText()) + muted(" send ")
  235. if m.exitKeyInDebounce {
  236. keyText := m.getExitKeyText()
  237. hint = base(keyText+" again") + muted(" to exit")
  238. } else if m.app.IsBusy() {
  239. keyText := m.getInterruptKeyText()
  240. if m.interruptKeyInDebounce {
  241. hint = muted(
  242. "working",
  243. ) + m.spinner.View() + muted(
  244. " ",
  245. ) + base(
  246. keyText+" again",
  247. ) + muted(
  248. " interrupt",
  249. )
  250. } else {
  251. hint = muted("working") + m.spinner.View() + muted(" ") + base(keyText) + muted(" interrupt")
  252. }
  253. }
  254. model := ""
  255. if m.app.Model != nil {
  256. model = muted(m.app.Provider.Name) + base(" "+m.app.Model.Name)
  257. }
  258. space := width - 2 - lipgloss.Width(model) - lipgloss.Width(hint)
  259. spacer := styles.NewStyle().Background(t.Background()).Width(space).Render("")
  260. info := hint + spacer + model
  261. info = styles.NewStyle().Background(t.Background()).Padding(0, 1).Render(info)
  262. content := strings.Join([]string{"", textarea, info}, "\n")
  263. return content
  264. }
  265. func (m *editorComponent) View(width int) string {
  266. if m.Lines() > 1 {
  267. return lipgloss.Place(
  268. width,
  269. 5,
  270. lipgloss.Center,
  271. lipgloss.Center,
  272. "",
  273. styles.WhitespaceStyle(theme.CurrentTheme().Background()),
  274. )
  275. }
  276. return m.Content(width)
  277. }
  278. func (m *editorComponent) Focused() bool {
  279. return m.textarea.Focused()
  280. }
  281. func (m *editorComponent) Focus() (tea.Model, tea.Cmd) {
  282. return m, m.textarea.Focus()
  283. }
  284. func (m *editorComponent) Blur() {
  285. m.textarea.Blur()
  286. }
  287. func (m *editorComponent) Lines() int {
  288. return m.textarea.LineCount()
  289. }
  290. func (m *editorComponent) Value() string {
  291. return m.textarea.Value()
  292. }
  293. func (m *editorComponent) Length() int {
  294. return m.textarea.Length()
  295. }
  296. func (m *editorComponent) Submit() (tea.Model, tea.Cmd) {
  297. value := strings.TrimSpace(m.Value())
  298. if value == "" {
  299. return m, nil
  300. }
  301. if len(value) > 0 && value[len(value)-1] == '\\' {
  302. // If the last character is a backslash, remove it and add a newline
  303. m.textarea.ReplaceRange(len(value)-1, len(value), "")
  304. m.textarea.InsertString("\n")
  305. return m, nil
  306. }
  307. var cmds []tea.Cmd
  308. attachments := m.textarea.GetAttachments()
  309. fileParts := make([]opencode.FilePartParam, 0)
  310. for _, attachment := range attachments {
  311. fileParts = append(fileParts, opencode.FilePartParam{
  312. Type: opencode.F(opencode.FilePartTypeFile),
  313. Mime: opencode.F(attachment.MediaType),
  314. URL: opencode.F(attachment.URL),
  315. Filename: opencode.F(attachment.Filename),
  316. })
  317. }
  318. updated, cmd := m.Clear()
  319. m = updated.(*editorComponent)
  320. cmds = append(cmds, cmd)
  321. cmds = append(cmds, util.CmdHandler(app.SendMsg{Text: value, Attachments: fileParts}))
  322. return m, tea.Batch(cmds...)
  323. }
  324. func (m *editorComponent) Clear() (tea.Model, tea.Cmd) {
  325. m.textarea.Reset()
  326. return m, nil
  327. }
  328. func (m *editorComponent) Paste() (tea.Model, tea.Cmd) {
  329. imageBytes := clipboard.Read(clipboard.FmtImage)
  330. if imageBytes != nil {
  331. attachmentCount := len(m.textarea.GetAttachments())
  332. attachmentIndex := attachmentCount + 1
  333. base64EncodedFile := base64.StdEncoding.EncodeToString(imageBytes)
  334. attachment := &textarea.Attachment{
  335. ID: uuid.NewString(),
  336. MediaType: "image/png",
  337. Display: fmt.Sprintf("[Image #%d]", attachmentIndex),
  338. Filename: fmt.Sprintf("image-%d.png", attachmentIndex),
  339. URL: fmt.Sprintf("data:image/png;base64,%s", base64EncodedFile),
  340. }
  341. m.textarea.InsertAttachment(attachment)
  342. m.textarea.InsertString(" ")
  343. return m, nil
  344. }
  345. textBytes := clipboard.Read(clipboard.FmtText)
  346. if textBytes != nil {
  347. m.textarea.InsertRunesFromUserInput([]rune(string(textBytes)))
  348. return m, nil
  349. }
  350. // fallback to reading the clipboard using OSC52
  351. return m, tea.ReadClipboard
  352. }
  353. func (m *editorComponent) Newline() (tea.Model, tea.Cmd) {
  354. m.textarea.Newline()
  355. return m, nil
  356. }
  357. func (m *editorComponent) SetInterruptKeyInDebounce(inDebounce bool) {
  358. m.interruptKeyInDebounce = inDebounce
  359. }
  360. func (m *editorComponent) SetExitKeyInDebounce(inDebounce bool) {
  361. m.exitKeyInDebounce = inDebounce
  362. }
  363. func (m *editorComponent) getInterruptKeyText() string {
  364. return m.app.Commands[commands.SessionInterruptCommand].Keys()[0]
  365. }
  366. func (m *editorComponent) getSubmitKeyText() string {
  367. return m.app.Commands[commands.InputSubmitCommand].Keys()[0]
  368. }
  369. func (m *editorComponent) getExitKeyText() string {
  370. return m.app.Commands[commands.AppExitCommand].Keys()[0]
  371. }
  372. func (m *editorComponent) resetTextareaStyles() textarea.Model {
  373. t := theme.CurrentTheme()
  374. bgColor := t.BackgroundElement()
  375. textColor := t.Text()
  376. textMutedColor := t.TextMuted()
  377. ta := m.textarea
  378. ta.Styles.Blurred.Base = styles.NewStyle().Foreground(textColor).Background(bgColor).Lipgloss()
  379. ta.Styles.Blurred.CursorLine = styles.NewStyle().Background(bgColor).Lipgloss()
  380. ta.Styles.Blurred.Placeholder = styles.NewStyle().
  381. Foreground(textMutedColor).
  382. Background(bgColor).
  383. Lipgloss()
  384. ta.Styles.Blurred.Text = styles.NewStyle().Foreground(textColor).Background(bgColor).Lipgloss()
  385. ta.Styles.Focused.Base = styles.NewStyle().Foreground(textColor).Background(bgColor).Lipgloss()
  386. ta.Styles.Focused.CursorLine = styles.NewStyle().Background(bgColor).Lipgloss()
  387. ta.Styles.Focused.Placeholder = styles.NewStyle().
  388. Foreground(textMutedColor).
  389. Background(bgColor).
  390. Lipgloss()
  391. ta.Styles.Focused.Text = styles.NewStyle().Foreground(textColor).Background(bgColor).Lipgloss()
  392. ta.Styles.Attachment = styles.NewStyle().
  393. Foreground(t.Secondary()).
  394. Background(bgColor).
  395. Lipgloss()
  396. ta.Styles.SelectedAttachment = styles.NewStyle().
  397. Foreground(t.Text()).
  398. Background(t.Secondary()).
  399. Lipgloss()
  400. ta.Styles.Cursor.Color = t.Primary()
  401. return ta
  402. }
  403. func createSpinner() spinner.Model {
  404. t := theme.CurrentTheme()
  405. return spinner.New(
  406. spinner.WithSpinner(spinner.Ellipsis),
  407. spinner.WithStyle(
  408. styles.NewStyle().
  409. Background(t.Background()).
  410. Foreground(t.TextMuted()).
  411. Width(3).
  412. Lipgloss(),
  413. ),
  414. )
  415. }
  416. func NewEditorComponent(app *app.App) EditorComponent {
  417. s := createSpinner()
  418. ta := textarea.New()
  419. ta.Prompt = " "
  420. ta.ShowLineNumbers = false
  421. ta.CharLimit = -1
  422. m := &editorComponent{
  423. app: app,
  424. textarea: ta,
  425. spinner: s,
  426. interruptKeyInDebounce: false,
  427. }
  428. m.resetTextareaStyles()
  429. return m
  430. }