editor.go 8.2 KB

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