opencode/packages/tui/internal/components/chat/editor.go

455 lines
12 KiB
Go
Raw Normal View History

2025-04-12 00:54:13 +08:00
package chat
import (
2025-05-03 04:23:58 +08:00
"fmt"
2025-05-17 03:31:50 +08:00
"log/slog"
"os"
"os/exec"
"strings"
2025-06-12 18:35:40 +08:00
"github.com/charmbracelet/bubbles/v2/key"
"github.com/charmbracelet/bubbles/v2/spinner"
"github.com/charmbracelet/bubbles/v2/textarea"
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/charmbracelet/lipgloss/v2"
2025-06-04 22:20:42 +08:00
"github.com/sst/opencode/internal/app"
"github.com/sst/opencode/internal/components/dialog"
"github.com/sst/opencode/internal/image"
"github.com/sst/opencode/internal/layout"
2025-05-13 23:02:39 +08:00
"github.com/sst/opencode/internal/status"
2025-06-04 22:20:42 +08:00
"github.com/sst/opencode/internal/styles"
"github.com/sst/opencode/internal/theme"
"github.com/sst/opencode/internal/util"
2025-04-12 00:54:13 +08:00
)
2025-06-06 04:44:20 +08:00
type editorComponent struct {
width int
height int
app *app.App
textarea textarea.Model
2025-05-30 04:37:06 +08:00
attachments []app.Attachment
deleteMode bool
history []string
historyIndex int
currentMessage string
2025-06-06 04:44:20 +08:00
spinner spinner.Model
2025-04-12 00:54:13 +08:00
}
2025-04-23 18:15:23 +08:00
type EditorKeyMaps struct {
2025-05-29 04:36:31 +08:00
Send key.Binding
OpenEditor key.Binding
Paste key.Binding
HistoryUp key.Binding
HistoryDown key.Binding
2025-04-12 02:31:24 +08:00
}
type bluredEditorKeyMaps struct {
Send key.Binding
Focus key.Binding
OpenEditor key.Binding
2025-04-12 02:31:24 +08:00
}
2025-05-03 04:23:58 +08:00
type DeleteAttachmentKeyMaps struct {
AttachmentDeleteMode key.Binding
Escape key.Binding
DeleteAllAttachments key.Binding
}
2025-04-12 02:31:24 +08:00
2025-04-23 18:15:23 +08:00
var editorMaps = EditorKeyMaps{
2025-04-12 02:31:24 +08:00
Send: key.NewBinding(
2025-06-12 20:23:49 +08:00
key.WithKeys("enter"),
2025-04-23 18:15:23 +08:00
key.WithHelp("enter", "send message"),
2025-04-12 02:31:24 +08:00
),
OpenEditor: key.NewBinding(
2025-06-12 20:23:49 +08:00
key.WithKeys("f12"),
key.WithHelp("f12", "open editor"),
),
2025-05-17 03:31:50 +08:00
Paste: key.NewBinding(
key.WithKeys("ctrl+v"),
key.WithHelp("ctrl+v", "paste content"),
),
HistoryUp: key.NewBinding(
key.WithKeys("up"),
key.WithHelp("up", "previous message"),
),
HistoryDown: key.NewBinding(
key.WithKeys("down"),
key.WithHelp("down", "next message"),
),
}
2025-05-03 04:23:58 +08:00
var DeleteKeyMaps = DeleteAttachmentKeyMaps{
AttachmentDeleteMode: key.NewBinding(
key.WithKeys("ctrl+r"),
key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
),
Escape: key.NewBinding(
key.WithKeys("esc"),
key.WithHelp("esc", "cancel delete mode"),
),
DeleteAllAttachments: key.NewBinding(
key.WithKeys("r"),
2025-05-15 15:55:06 +08:00
key.WithHelp("ctrl+r+r", "delete all attachments"),
2025-05-03 04:23:58 +08:00
),
}
const (
maxAttachments = 5
)
2025-06-06 04:44:20 +08:00
func (m *editorComponent) Init() tea.Cmd {
return tea.Batch(textarea.Blink, m.spinner.Tick)
2025-04-12 08:01:45 +08:00
}
2025-06-06 04:44:20 +08:00
func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmds []tea.Cmd
2025-04-12 00:54:13 +08:00
var cmd tea.Cmd
2025-04-12 02:31:24 +08:00
switch msg := msg.(type) {
2025-04-28 21:46:09 +08:00
case dialog.ThemeChangedMsg:
2025-06-06 04:44:20 +08:00
m.textarea = createTextArea(&m.textarea)
case dialog.CompletionSelectedMsg:
existingValue := m.textarea.Value()
modifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)
m.textarea.SetValue(modifiedValue)
2025-04-28 21:46:09 +08:00
return m, nil
2025-05-03 04:23:58 +08:00
case dialog.AttachmentAddedMsg:
if len(m.attachments) >= maxAttachments {
2025-05-09 01:03:59 +08:00
status.Error(fmt.Sprintf("cannot add more than %d images", maxAttachments))
2025-05-03 04:23:58 +08:00
return m, cmd
}
m.attachments = append(m.attachments, msg.Attachment)
2025-04-12 02:31:24 +08:00
case tea.KeyMsg:
2025-06-12 20:23:49 +08:00
switch msg.String() {
case "shift+enter":
value := m.textarea.Value()
m.textarea.SetValue(value + "\n")
return m, nil
}
2025-05-03 04:23:58 +08:00
if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
m.deleteMode = true
return m, nil
}
if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
m.deleteMode = false
m.attachments = nil
return m, nil
}
2025-06-12 18:35:40 +08:00
// if m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {
// num := int(msg.Runes[0] - '0')
// m.deleteMode = false
// if num < 10 && len(m.attachments) > num {
// if num == 0 {
// m.attachments = m.attachments[num+1:]
// } else {
// m.attachments = slices.Delete(m.attachments, num, num+1)
// }
// return m, nil
// }
// }
2025-04-23 18:08:45 +08:00
if key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||
key.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {
return m, nil
}
2025-04-23 18:15:23 +08:00
if key.Matches(msg, editorMaps.OpenEditor) {
2025-06-05 02:52:23 +08:00
if m.app.IsBusy() {
status.Warn("Agent is working, please wait...")
return m, nil
}
2025-05-01 20:58:27 +08:00
value := m.textarea.Value()
m.textarea.Reset()
2025-05-03 04:23:58 +08:00
return m, m.openEditor(value)
}
if key.Matches(msg, DeleteKeyMaps.Escape) {
m.deleteMode = false
return m, nil
}
2025-05-17 03:31:50 +08:00
if key.Matches(msg, editorMaps.Paste) {
imageBytes, text, err := image.GetImageFromClipboard()
if err != nil {
slog.Error(err.Error())
return m, cmd
}
if len(imageBytes) != 0 {
attachmentName := fmt.Sprintf("clipboard-image-%d", len(m.attachments))
2025-05-30 04:37:06 +08:00
attachment := app.Attachment{FilePath: attachmentName, FileName: attachmentName, Content: imageBytes, MimeType: "image/png"}
2025-05-17 03:31:50 +08:00
m.attachments = append(m.attachments, attachment)
} else {
m.textarea.SetValue(m.textarea.Value() + text)
}
return m, cmd
}
// Handle history navigation with up/down arrow keys
// Only handle history navigation if the filepicker is not open and completion dialog is not open
if m.textarea.Focused() && key.Matches(msg, editorMaps.HistoryUp) && !m.app.IsFilepickerOpen() && !m.app.IsCompletionDialogOpen() {
// Get the current line number
currentLine := m.textarea.Line()
2025-05-29 04:36:31 +08:00
// Only navigate history if we're at the first line
if currentLine == 0 && len(m.history) > 0 {
// Save current message if we're just starting to navigate
if m.historyIndex == len(m.history) {
m.currentMessage = m.textarea.Value()
}
2025-05-29 04:36:31 +08:00
// Go to previous message in history
if m.historyIndex > 0 {
m.historyIndex--
m.textarea.SetValue(m.history[m.historyIndex])
}
return m, nil
}
}
2025-05-29 04:36:31 +08:00
if m.textarea.Focused() && key.Matches(msg, editorMaps.HistoryDown) && !m.app.IsFilepickerOpen() && !m.app.IsCompletionDialogOpen() {
// Get the current line number and total lines
currentLine := m.textarea.Line()
value := m.textarea.Value()
lines := strings.Split(value, "\n")
totalLines := len(lines)
2025-05-29 04:36:31 +08:00
// Only navigate history if we're at the last line
if currentLine == totalLines-1 {
if m.historyIndex < len(m.history)-1 {
// Go to next message in history
m.historyIndex++
m.textarea.SetValue(m.history[m.historyIndex])
} else if m.historyIndex == len(m.history)-1 {
// Return to the current message being composed
m.historyIndex = len(m.history)
m.textarea.SetValue(m.currentMessage)
}
return m, nil
}
}
2025-04-23 18:08:45 +08:00
// Handle Enter key
2025-04-23 18:15:23 +08:00
if m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {
2025-04-23 18:08:45 +08:00
value := m.textarea.Value()
if len(value) > 0 && value[len(value)-1] == '\\' {
// If the last character is a backslash, remove it and add a newline
m.textarea.SetValue(value[:len(value)-1] + "\n")
return m, nil
} else {
// Otherwise, send the message
return m, m.send()
}
2025-04-12 02:31:24 +08:00
}
}
2025-06-06 04:44:20 +08:00
m.spinner, cmd = m.spinner.Update(msg)
cmds = append(cmds, cmd)
2025-04-12 08:01:45 +08:00
m.textarea, cmd = m.textarea.Update(msg)
2025-06-06 04:44:20 +08:00
cmds = append(cmds, cmd)
return m, tea.Batch(cmds...)
2025-04-12 00:54:13 +08:00
}
2025-06-06 04:44:20 +08:00
func (m *editorComponent) View() string {
2025-04-28 21:46:09 +08:00
t := theme.CurrentTheme()
2025-06-06 04:44:20 +08:00
base := styles.BaseStyle().Render
muted := styles.Muted().Render
promptStyle := lipgloss.NewStyle().
2025-04-28 21:46:09 +08:00
Padding(0, 0, 0, 1).
Bold(true).
Foreground(t.Primary())
2025-06-06 04:44:20 +08:00
prompt := promptStyle.Render(">")
2025-04-12 00:54:13 +08:00
2025-06-06 04:44:20 +08:00
textarea := lipgloss.JoinHorizontal(
lipgloss.Top,
prompt,
m.textarea.View(),
)
textarea = styles.BaseStyle().
2025-06-12 19:06:53 +08:00
Width(m.width).
2025-06-06 04:44:20 +08:00
Border(lipgloss.NormalBorder(), true, true).
BorderForeground(t.Border()).
Render(textarea)
hint := base("enter") + muted(" send ") + base("shift") + muted("+") + base("enter") + muted(" newline")
if m.app.IsBusy() {
hint = muted("working") + m.spinner.View() + muted(" ") + base("esc") + muted(" interrupt")
}
model := ""
if m.app.Model != nil {
model = base(*m.app.Model.Name) + muted(" • /model")
2025-05-03 04:23:58 +08:00
}
2025-06-06 04:44:20 +08:00
space := m.width - 2 - lipgloss.Width(model) - lipgloss.Width(hint)
spacer := lipgloss.NewStyle().Width(space).Render("")
info := lipgloss.JoinHorizontal(lipgloss.Left, hint, spacer, model)
info = styles.Padded().Render(info)
content := lipgloss.JoinVertical(
lipgloss.Top,
// m.attachmentsContent(),
textarea,
info,
)
2025-06-12 18:35:40 +08:00
return content
2025-04-12 00:54:13 +08:00
}
2025-06-06 04:44:20 +08:00
func (m *editorComponent) SetSize(width, height int) tea.Cmd {
2025-05-03 04:23:58 +08:00
m.width = width
m.height = height
2025-06-06 04:44:20 +08:00
m.textarea.SetWidth(width - 5) // account for the prompt and padding right
m.textarea.SetHeight(height - 3) // account for info underneath
return nil
2025-04-12 00:54:13 +08:00
}
2025-06-06 04:44:20 +08:00
func (m *editorComponent) GetSize() (int, int) {
return m.width, m.height
2025-04-12 00:54:13 +08:00
}
2025-06-06 04:44:20 +08:00
func (m *editorComponent) BindingKeys() []key.Binding {
bindings := []key.Binding{}
bindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)
bindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)
return bindings
}
func (m *editorComponent) openEditor(value string) tea.Cmd {
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "nvim"
}
tmpfile, err := os.CreateTemp("", "msg_*.md")
tmpfile.WriteString(value)
if err != nil {
status.Error(err.Error())
return nil
}
tmpfile.Close()
c := exec.Command(editor, tmpfile.Name()) //nolint:gosec
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return tea.ExecProcess(c, func(err error) tea.Msg {
if err != nil {
status.Error(err.Error())
return nil
}
content, err := os.ReadFile(tmpfile.Name())
if err != nil {
status.Error(err.Error())
return nil
}
if len(content) == 0 {
status.Warn("Message is empty")
return nil
}
os.Remove(tmpfile.Name())
attachments := m.attachments
m.attachments = nil
return SendMsg{
Text: string(content),
Attachments: attachments,
}
})
}
func (m *editorComponent) send() tea.Cmd {
value := m.textarea.Value()
m.textarea.Reset()
attachments := m.attachments
// Save to history if not empty and not a duplicate of the last entry
if value != "" {
if len(m.history) == 0 || m.history[len(m.history)-1] != value {
m.history = append(m.history, value)
}
m.historyIndex = len(m.history)
m.currentMessage = ""
}
m.attachments = nil
if value == "" {
return nil
}
return tea.Batch(
util.CmdHandler(SendMsg{
Text: value,
Attachments: attachments,
}),
)
}
func (m *editorComponent) attachmentsContent() string {
if len(m.attachments) == 0 {
return ""
}
2025-05-03 04:23:58 +08:00
t := theme.CurrentTheme()
2025-06-06 04:44:20 +08:00
var styledAttachments []string
2025-05-03 04:23:58 +08:00
attachmentStyles := styles.BaseStyle().
MarginLeft(1).
Background(t.TextMuted()).
Foreground(t.Text())
for i, attachment := range m.attachments {
var filename string
if len(attachment.FileName) > 10 {
filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
} else {
filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
}
if m.deleteMode {
filename = fmt.Sprintf("%d%s", i, filename)
}
styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
}
content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
return content
}
2025-06-06 04:44:20 +08:00
func createTextArea(existing *textarea.Model) textarea.Model {
2025-04-28 21:46:09 +08:00
t := theme.CurrentTheme()
bgColor := t.Background()
textColor := t.Text()
textMutedColor := t.TextMuted()
ta := textarea.New()
2025-06-06 04:44:20 +08:00
ta.Placeholder = "It's prompting time..."
2025-06-12 18:35:40 +08:00
ta.Styles.Blurred.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
ta.Styles.Blurred.CursorLine = styles.BaseStyle().Background(bgColor)
ta.Styles.Blurred.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
ta.Styles.Blurred.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
ta.Styles.Focused.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
ta.Styles.Focused.CursorLine = styles.BaseStyle().Background(bgColor)
ta.Styles.Focused.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
ta.Styles.Focused.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
2025-04-28 21:46:09 +08:00
ta.Prompt = " "
ta.ShowLineNumbers = false
ta.CharLimit = -1
if existing != nil {
ta.SetValue(existing.Value())
ta.SetWidth(existing.Width())
ta.SetHeight(existing.Height())
}
ta.Focus()
return ta
}
2025-06-12 18:35:40 +08:00
func NewEditorComponent(app *app.App) layout.ModelWithView {
2025-06-06 04:44:20 +08:00
s := spinner.New(spinner.WithSpinner(spinner.Ellipsis), spinner.WithStyle(styles.Muted().Width(3)))
ta := createTextArea(nil)
return &editorComponent{
2025-05-29 04:36:31 +08:00
app: app,
textarea: ta,
history: []string{},
historyIndex: 0,
currentMessage: "",
2025-06-06 04:44:20 +08:00
spinner: s,
2025-04-12 00:54:13 +08:00
}
}