editor.go 8.0 KB

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