editor.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package chat
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "os"
  6. "os/exec"
  7. "slices"
  8. "strings"
  9. "unicode"
  10. "github.com/charmbracelet/bubbles/key"
  11. "github.com/charmbracelet/bubbles/textarea"
  12. tea "github.com/charmbracelet/bubbletea"
  13. "github.com/charmbracelet/lipgloss"
  14. "github.com/sst/opencode/internal/app"
  15. "github.com/sst/opencode/internal/message"
  16. "github.com/sst/opencode/internal/status"
  17. "github.com/sst/opencode/internal/tui/components/dialog"
  18. "github.com/sst/opencode/internal/tui/image"
  19. "github.com/sst/opencode/internal/tui/layout"
  20. "github.com/sst/opencode/internal/tui/styles"
  21. "github.com/sst/opencode/internal/tui/theme"
  22. "github.com/sst/opencode/internal/tui/util"
  23. )
  24. type editorCmp struct {
  25. width int
  26. height int
  27. app *app.App
  28. textarea textarea.Model
  29. attachments []message.Attachment
  30. deleteMode bool
  31. }
  32. type EditorKeyMaps struct {
  33. Send key.Binding
  34. OpenEditor key.Binding
  35. Paste key.Binding
  36. }
  37. type bluredEditorKeyMaps struct {
  38. Send key.Binding
  39. Focus key.Binding
  40. OpenEditor 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", "ctrl+s"),
  50. key.WithHelp("enter", "send message"),
  51. ),
  52. OpenEditor: key.NewBinding(
  53. key.WithKeys("ctrl+e"),
  54. key.WithHelp("ctrl+e", "open editor"),
  55. ),
  56. Paste: key.NewBinding(
  57. key.WithKeys("ctrl+v"),
  58. key.WithHelp("ctrl+v", "paste content"),
  59. ),
  60. }
  61. var DeleteKeyMaps = DeleteAttachmentKeyMaps{
  62. AttachmentDeleteMode: key.NewBinding(
  63. key.WithKeys("ctrl+r"),
  64. key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
  65. ),
  66. Escape: key.NewBinding(
  67. key.WithKeys("esc"),
  68. key.WithHelp("esc", "cancel delete mode"),
  69. ),
  70. DeleteAllAttachments: key.NewBinding(
  71. key.WithKeys("r"),
  72. key.WithHelp("ctrl+r+r", "delete all attchments"),
  73. ),
  74. }
  75. const (
  76. maxAttachments = 5
  77. )
  78. func (m *editorCmp) openEditor(value string) tea.Cmd {
  79. editor := os.Getenv("EDITOR")
  80. if editor == "" {
  81. editor = "nvim"
  82. }
  83. tmpfile, err := os.CreateTemp("", "msg_*.md")
  84. tmpfile.WriteString(value)
  85. if err != nil {
  86. status.Error(err.Error())
  87. return nil
  88. }
  89. tmpfile.Close()
  90. c := exec.Command(editor, tmpfile.Name()) //nolint:gosec
  91. c.Stdin = os.Stdin
  92. c.Stdout = os.Stdout
  93. c.Stderr = os.Stderr
  94. return tea.ExecProcess(c, func(err error) tea.Msg {
  95. if err != nil {
  96. status.Error(err.Error())
  97. return nil
  98. }
  99. content, err := os.ReadFile(tmpfile.Name())
  100. if err != nil {
  101. status.Error(err.Error())
  102. return nil
  103. }
  104. if len(content) == 0 {
  105. status.Warn("Message is empty")
  106. return nil
  107. }
  108. os.Remove(tmpfile.Name())
  109. attachments := m.attachments
  110. m.attachments = nil
  111. return SendMsg{
  112. Text: string(content),
  113. Attachments: attachments,
  114. }
  115. })
  116. }
  117. func (m *editorCmp) Init() tea.Cmd {
  118. return textarea.Blink
  119. }
  120. func (m *editorCmp) send() tea.Cmd {
  121. if m.app.PrimaryAgent.IsSessionBusy(m.app.CurrentSession.ID) {
  122. status.Warn("Agent is working, please wait...")
  123. return nil
  124. }
  125. value := m.textarea.Value()
  126. m.textarea.Reset()
  127. attachments := m.attachments
  128. m.attachments = nil
  129. if value == "" {
  130. return nil
  131. }
  132. return tea.Batch(
  133. util.CmdHandler(SendMsg{
  134. Text: value,
  135. Attachments: attachments,
  136. }),
  137. )
  138. }
  139. func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  140. var cmd tea.Cmd
  141. switch msg := msg.(type) {
  142. case dialog.ThemeChangedMsg:
  143. m.textarea = CreateTextArea(&m.textarea)
  144. case dialog.CompletionSelectedMsg:
  145. existingValue := m.textarea.Value()
  146. modifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)
  147. m.textarea.SetValue(modifiedValue)
  148. return m, nil
  149. case dialog.AttachmentAddedMsg:
  150. if len(m.attachments) >= maxAttachments {
  151. status.Error(fmt.Sprintf("cannot add more than %d images", maxAttachments))
  152. return m, cmd
  153. }
  154. m.attachments = append(m.attachments, msg.Attachment)
  155. case tea.KeyMsg:
  156. if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
  157. m.deleteMode = true
  158. return m, nil
  159. }
  160. if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
  161. m.deleteMode = false
  162. m.attachments = nil
  163. return m, nil
  164. }
  165. if m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {
  166. num := int(msg.Runes[0] - '0')
  167. m.deleteMode = false
  168. if num < 10 && len(m.attachments) > num {
  169. if num == 0 {
  170. m.attachments = m.attachments[num+1:]
  171. } else {
  172. m.attachments = slices.Delete(m.attachments, num, num+1)
  173. }
  174. return m, nil
  175. }
  176. }
  177. if key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||
  178. key.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {
  179. return m, nil
  180. }
  181. if key.Matches(msg, editorMaps.OpenEditor) {
  182. if m.app.PrimaryAgent.IsSessionBusy(m.app.CurrentSession.ID) {
  183. status.Warn("Agent is working, please wait...")
  184. return m, nil
  185. }
  186. value := m.textarea.Value()
  187. m.textarea.Reset()
  188. return m, m.openEditor(value)
  189. }
  190. if key.Matches(msg, DeleteKeyMaps.Escape) {
  191. m.deleteMode = false
  192. return m, nil
  193. }
  194. if key.Matches(msg, editorMaps.Paste) {
  195. imageBytes, text, err := image.GetImageFromClipboard()
  196. if err != nil {
  197. slog.Error(err.Error())
  198. return m, cmd
  199. }
  200. if len(imageBytes) != 0 {
  201. attachmentName := fmt.Sprintf("clipboard-image-%d", len(m.attachments))
  202. attachment := message.Attachment{FilePath: attachmentName, FileName: attachmentName, Content: imageBytes, MimeType: "image/png"}
  203. m.attachments = append(m.attachments, attachment)
  204. } else {
  205. m.textarea.SetValue(m.textarea.Value() + text)
  206. }
  207. return m, cmd
  208. }
  209. // Handle Enter key
  210. if m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {
  211. value := m.textarea.Value()
  212. if len(value) > 0 && value[len(value)-1] == '\\' {
  213. // If the last character is a backslash, remove it and add a newline
  214. m.textarea.SetValue(value[:len(value)-1] + "\n")
  215. return m, nil
  216. } else {
  217. // Otherwise, send the message
  218. return m, m.send()
  219. }
  220. }
  221. }
  222. m.textarea, cmd = m.textarea.Update(msg)
  223. return m, cmd
  224. }
  225. func (m *editorCmp) View() string {
  226. t := theme.CurrentTheme()
  227. // Style the prompt with theme colors
  228. style := lipgloss.NewStyle().
  229. Padding(0, 0, 0, 1).
  230. Bold(true).
  231. Foreground(t.Primary())
  232. if len(m.attachments) == 0 {
  233. return lipgloss.JoinHorizontal(lipgloss.Top, style.Render(">"), m.textarea.View())
  234. }
  235. m.textarea.SetHeight(m.height - 1)
  236. return lipgloss.JoinVertical(lipgloss.Top,
  237. m.attachmentsContent(),
  238. lipgloss.JoinHorizontal(lipgloss.Top, style.Render(">"),
  239. m.textarea.View()),
  240. )
  241. }
  242. func (m *editorCmp) SetSize(width, height int) tea.Cmd {
  243. m.width = width
  244. m.height = height
  245. m.textarea.SetWidth(width - 3) // account for the prompt and padding right
  246. m.textarea.SetHeight(height)
  247. return nil
  248. }
  249. func (m *editorCmp) GetSize() (int, int) {
  250. return m.textarea.Width(), m.textarea.Height()
  251. }
  252. func (m *editorCmp) attachmentsContent() string {
  253. var styledAttachments []string
  254. t := theme.CurrentTheme()
  255. attachmentStyles := styles.BaseStyle().
  256. MarginLeft(1).
  257. Background(t.TextMuted()).
  258. Foreground(t.Text())
  259. for i, attachment := range m.attachments {
  260. var filename string
  261. if len(attachment.FileName) > 10 {
  262. filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
  263. } else {
  264. filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
  265. }
  266. if m.deleteMode {
  267. filename = fmt.Sprintf("%d%s", i, filename)
  268. }
  269. styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
  270. }
  271. content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
  272. return content
  273. }
  274. func (m *editorCmp) BindingKeys() []key.Binding {
  275. bindings := []key.Binding{}
  276. bindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)
  277. bindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)
  278. return bindings
  279. }
  280. func CreateTextArea(existing *textarea.Model) textarea.Model {
  281. t := theme.CurrentTheme()
  282. bgColor := t.Background()
  283. textColor := t.Text()
  284. textMutedColor := t.TextMuted()
  285. ta := textarea.New()
  286. ta.BlurredStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  287. ta.BlurredStyle.CursorLine = styles.BaseStyle().Background(bgColor)
  288. ta.BlurredStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  289. ta.BlurredStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  290. ta.FocusedStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  291. ta.FocusedStyle.CursorLine = styles.BaseStyle().Background(bgColor)
  292. ta.FocusedStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  293. ta.FocusedStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  294. ta.Prompt = " "
  295. ta.ShowLineNumbers = false
  296. ta.CharLimit = -1
  297. if existing != nil {
  298. ta.SetValue(existing.Value())
  299. ta.SetWidth(existing.Width())
  300. ta.SetHeight(existing.Height())
  301. }
  302. ta.Focus()
  303. return ta
  304. }
  305. func NewEditorCmp(app *app.App) tea.Model {
  306. ta := CreateTextArea(nil)
  307. return &editorCmp{
  308. app: app,
  309. textarea: ta,
  310. }
  311. }