editor.go 8.2 KB

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