editor.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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/message"
  14. "github.com/opencode-ai/opencode/internal/session"
  15. "github.com/opencode-ai/opencode/internal/status"
  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. status.Error(err.Error())
  81. return nil
  82. }
  83. tmpfile.Close()
  84. c := exec.Command(editor, tmpfile.Name()) //nolint:gosec
  85. c.Stdin = os.Stdin
  86. c.Stdout = os.Stdout
  87. c.Stderr = os.Stderr
  88. return tea.ExecProcess(c, func(err error) tea.Msg {
  89. if err != nil {
  90. status.Error(err.Error())
  91. return nil
  92. }
  93. content, err := os.ReadFile(tmpfile.Name())
  94. if err != nil {
  95. status.Error(err.Error())
  96. return nil
  97. }
  98. if len(content) == 0 {
  99. status.Warn("Message is empty")
  100. return nil
  101. }
  102. os.Remove(tmpfile.Name())
  103. attachments := m.attachments
  104. m.attachments = nil
  105. return SendMsg{
  106. Text: string(content),
  107. Attachments: attachments,
  108. }
  109. })
  110. }
  111. func (m *editorCmp) Init() tea.Cmd {
  112. return textarea.Blink
  113. }
  114. func (m *editorCmp) send() tea.Cmd {
  115. if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
  116. status.Warn("Agent is working, please wait...")
  117. return nil
  118. }
  119. value := m.textarea.Value()
  120. m.textarea.Reset()
  121. attachments := m.attachments
  122. m.attachments = nil
  123. if value == "" {
  124. return nil
  125. }
  126. return tea.Batch(
  127. util.CmdHandler(SendMsg{
  128. Text: value,
  129. Attachments: attachments,
  130. }),
  131. )
  132. }
  133. func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  134. var cmd tea.Cmd
  135. switch msg := msg.(type) {
  136. case dialog.ThemeChangedMsg:
  137. m.textarea = CreateTextArea(&m.textarea)
  138. return m, nil
  139. case SessionSelectedMsg:
  140. if msg.ID != m.session.ID {
  141. m.session = msg
  142. }
  143. return m, nil
  144. case dialog.AttachmentAddedMsg:
  145. if len(m.attachments) >= maxAttachments {
  146. status.Error(fmt.Sprintf("cannot add more than %d images", maxAttachments))
  147. return m, cmd
  148. }
  149. m.attachments = append(m.attachments, msg.Attachment)
  150. case tea.KeyMsg:
  151. if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
  152. m.deleteMode = true
  153. return m, nil
  154. }
  155. if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
  156. m.deleteMode = false
  157. m.attachments = nil
  158. return m, nil
  159. }
  160. if m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {
  161. num := int(msg.Runes[0] - '0')
  162. m.deleteMode = false
  163. if num < 10 && len(m.attachments) > num {
  164. if num == 0 {
  165. m.attachments = m.attachments[num+1:]
  166. } else {
  167. m.attachments = slices.Delete(m.attachments, num, num+1)
  168. }
  169. return m, nil
  170. }
  171. }
  172. if key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||
  173. key.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {
  174. return m, nil
  175. }
  176. if key.Matches(msg, editorMaps.OpenEditor) {
  177. if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
  178. status.Warn("Agent is working, please wait...")
  179. return m, nil
  180. }
  181. value := m.textarea.Value()
  182. m.textarea.Reset()
  183. return m, m.openEditor(value)
  184. }
  185. if key.Matches(msg, DeleteKeyMaps.Escape) {
  186. m.deleteMode = false
  187. return m, nil
  188. }
  189. // Handle Enter key
  190. if m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {
  191. value := m.textarea.Value()
  192. if len(value) > 0 && value[len(value)-1] == '\\' {
  193. // If the last character is a backslash, remove it and add a newline
  194. m.textarea.SetValue(value[:len(value)-1] + "\n")
  195. return m, nil
  196. } else {
  197. // Otherwise, send the message
  198. return m, m.send()
  199. }
  200. }
  201. }
  202. m.textarea, cmd = m.textarea.Update(msg)
  203. return m, cmd
  204. }
  205. func (m *editorCmp) View() string {
  206. t := theme.CurrentTheme()
  207. // Style the prompt with theme colors
  208. style := lipgloss.NewStyle().
  209. Padding(0, 0, 0, 1).
  210. Bold(true).
  211. Foreground(t.Primary())
  212. if len(m.attachments) == 0 {
  213. return lipgloss.JoinHorizontal(lipgloss.Top, style.Render(">"), m.textarea.View())
  214. }
  215. m.textarea.SetHeight(m.height - 1)
  216. return lipgloss.JoinVertical(lipgloss.Top,
  217. m.attachmentsContent(),
  218. lipgloss.JoinHorizontal(lipgloss.Top, style.Render(">"),
  219. m.textarea.View()),
  220. )
  221. }
  222. func (m *editorCmp) SetSize(width, height int) tea.Cmd {
  223. m.width = width
  224. m.height = height
  225. m.textarea.SetWidth(width - 3) // account for the prompt and padding right
  226. m.textarea.SetHeight(height)
  227. m.textarea.SetWidth(width)
  228. return nil
  229. }
  230. func (m *editorCmp) GetSize() (int, int) {
  231. return m.textarea.Width(), m.textarea.Height()
  232. }
  233. func (m *editorCmp) attachmentsContent() string {
  234. var styledAttachments []string
  235. t := theme.CurrentTheme()
  236. attachmentStyles := styles.BaseStyle().
  237. MarginLeft(1).
  238. Background(t.TextMuted()).
  239. Foreground(t.Text())
  240. for i, attachment := range m.attachments {
  241. var filename string
  242. if len(attachment.FileName) > 10 {
  243. filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
  244. } else {
  245. filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
  246. }
  247. if m.deleteMode {
  248. filename = fmt.Sprintf("%d%s", i, filename)
  249. }
  250. styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
  251. }
  252. content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
  253. return content
  254. }
  255. func (m *editorCmp) BindingKeys() []key.Binding {
  256. bindings := []key.Binding{}
  257. bindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)
  258. bindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)
  259. return bindings
  260. }
  261. func CreateTextArea(existing *textarea.Model) textarea.Model {
  262. t := theme.CurrentTheme()
  263. bgColor := t.Background()
  264. textColor := t.Text()
  265. textMutedColor := t.TextMuted()
  266. ta := textarea.New()
  267. ta.BlurredStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  268. ta.BlurredStyle.CursorLine = styles.BaseStyle().Background(bgColor)
  269. ta.BlurredStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  270. ta.BlurredStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  271. ta.FocusedStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  272. ta.FocusedStyle.CursorLine = styles.BaseStyle().Background(bgColor)
  273. ta.FocusedStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  274. ta.FocusedStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  275. ta.Prompt = " "
  276. ta.ShowLineNumbers = false
  277. ta.CharLimit = -1
  278. if existing != nil {
  279. ta.SetValue(existing.Value())
  280. ta.SetWidth(existing.Width())
  281. ta.SetHeight(existing.Height())
  282. }
  283. ta.Focus()
  284. return ta
  285. }
  286. func NewEditorCmp(app *app.App) tea.Model {
  287. ta := CreateTextArea(nil)
  288. return &editorCmp{
  289. app: app,
  290. textarea: ta,
  291. }
  292. }