1package editor
  2
  3import (
  4	"fmt"
  5	"os"
  6	"os/exec"
  7	"runtime"
  8	"slices"
  9	"strings"
 10	"unicode"
 11
 12	"github.com/charmbracelet/bubbles/v2/key"
 13	"github.com/charmbracelet/bubbles/v2/textarea"
 14	tea "github.com/charmbracelet/bubbletea/v2"
 15	"github.com/charmbracelet/crush/internal/app"
 16	"github.com/charmbracelet/crush/internal/fsext"
 17	"github.com/charmbracelet/crush/internal/message"
 18	"github.com/charmbracelet/crush/internal/session"
 19	"github.com/charmbracelet/crush/internal/tui/components/chat"
 20	"github.com/charmbracelet/crush/internal/tui/components/completions"
 21	"github.com/charmbracelet/crush/internal/tui/components/dialogs"
 22	"github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
 23	"github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
 24	"github.com/charmbracelet/crush/internal/tui/styles"
 25	"github.com/charmbracelet/crush/internal/tui/util"
 26	"github.com/charmbracelet/lipgloss/v2"
 27)
 28
 29type FileCompletionItem struct {
 30	Path string // The file path
 31}
 32
 33type editorCmp struct {
 34	width       int
 35	height      int
 36	x, y        int
 37	app         *app.App
 38	session     session.Session
 39	textarea    textarea.Model
 40	attachments []message.Attachment
 41	deleteMode  bool
 42
 43	keyMap EditorKeyMap
 44
 45	// File path completions
 46	currentQuery          string
 47	completionsStartIndex int
 48	isCompletionsOpen     bool
 49}
 50
 51var DeleteKeyMaps = DeleteAttachmentKeyMaps{
 52	AttachmentDeleteMode: key.NewBinding(
 53		key.WithKeys("ctrl+r"),
 54		key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
 55	),
 56	Escape: key.NewBinding(
 57		key.WithKeys("esc"),
 58		key.WithHelp("esc", "cancel delete mode"),
 59	),
 60	DeleteAllAttachments: key.NewBinding(
 61		key.WithKeys("r"),
 62		key.WithHelp("ctrl+r+r", "delete all attchments"),
 63	),
 64}
 65
 66const (
 67	maxAttachments = 5
 68)
 69
 70func (m *editorCmp) openEditor(value string) tea.Cmd {
 71	editor := os.Getenv("EDITOR")
 72	if editor == "" {
 73		// Use platform-appropriate default editor
 74		if runtime.GOOS == "windows" {
 75			editor = "notepad"
 76		} else {
 77			editor = "nvim"
 78		}
 79	}
 80
 81	tmpfile, err := os.CreateTemp("", "msg_*.md")
 82	if err != nil {
 83		return util.ReportError(err)
 84	}
 85	defer tmpfile.Close() //nolint:errcheck
 86	if _, err := tmpfile.WriteString(value); err != nil {
 87		return util.ReportError(err)
 88	}
 89	c := exec.Command(editor, tmpfile.Name())
 90	c.Stdin = os.Stdin
 91	c.Stdout = os.Stdout
 92	c.Stderr = os.Stderr
 93	return tea.ExecProcess(c, func(err error) tea.Msg {
 94		if err != nil {
 95			return util.ReportError(err)
 96		}
 97		content, err := os.ReadFile(tmpfile.Name())
 98		if err != nil {
 99			return util.ReportError(err)
100		}
101		if len(content) == 0 {
102			return util.ReportWarn("Message is empty")
103		}
104		os.Remove(tmpfile.Name())
105		attachments := m.attachments
106		m.attachments = nil
107		return chat.SendMsg{
108			Text:        string(content),
109			Attachments: attachments,
110		}
111	})
112}
113
114func (m *editorCmp) Init() tea.Cmd {
115	return nil
116}
117
118func (m *editorCmp) send() tea.Cmd {
119	if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
120		return util.ReportWarn("Agent is working, please wait...")
121	}
122
123	value := m.textarea.Value()
124	value = strings.TrimSpace(value)
125
126	switch value {
127	case "exit", "quit":
128		m.textarea.Reset()
129		return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
130	}
131
132	m.textarea.Reset()
133	attachments := m.attachments
134
135	m.attachments = nil
136	if value == "" {
137		return nil
138	}
139	return tea.Batch(
140		util.CmdHandler(chat.SendMsg{
141			Text:        value,
142			Attachments: attachments,
143		}),
144	)
145}
146
147func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
148	var cmd tea.Cmd
149	var cmds []tea.Cmd
150	switch msg := msg.(type) {
151	case tea.KeyboardEnhancementsMsg:
152		m.keyMap.keyboard = msg
153		return m, nil
154	case chat.SessionSelectedMsg:
155		if msg.ID != m.session.ID {
156			m.session = msg
157		}
158		return m, nil
159	case filepicker.FilePickedMsg:
160		if len(m.attachments) >= maxAttachments {
161			return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
162		}
163		m.attachments = append(m.attachments, msg.Attachment)
164		return m, nil
165	case completions.CompletionsClosedMsg:
166		m.isCompletionsOpen = false
167		m.currentQuery = ""
168		m.completionsStartIndex = 0
169	case completions.SelectCompletionMsg:
170		if !m.isCompletionsOpen {
171			return m, nil
172		}
173		if item, ok := msg.Value.(FileCompletionItem); ok {
174			// If the selected item is a file, insert its path into the textarea
175			value := m.textarea.Value()
176			value = value[:m.completionsStartIndex]
177			if len(value) > 0 && value[len(value)-1] != ' ' {
178				value += " "
179			}
180			value += item.Path
181			m.textarea.SetValue(value)
182			m.isCompletionsOpen = false
183			m.currentQuery = ""
184			m.completionsStartIndex = 0
185			return m, nil
186		}
187	case tea.KeyPressMsg:
188		switch {
189		// Completions
190		case msg.String() == "/" && !m.isCompletionsOpen:
191			m.isCompletionsOpen = true
192			m.currentQuery = ""
193			cmds = append(cmds, m.startCompletions)
194			m.completionsStartIndex = len(m.textarea.Value())
195		case msg.String() == "space" && m.isCompletionsOpen:
196			m.isCompletionsOpen = false
197			m.currentQuery = ""
198			m.completionsStartIndex = 0
199			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
200		case m.isCompletionsOpen && m.textarea.Cursor().X <= m.completionsStartIndex:
201			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
202		case msg.String() == "backspace" && m.isCompletionsOpen:
203			if len(m.currentQuery) > 0 {
204				m.currentQuery = m.currentQuery[:len(m.currentQuery)-1]
205				cmds = append(cmds, util.CmdHandler(completions.FilterCompletionsMsg{
206					Query: m.currentQuery,
207				}))
208			} else {
209				m.isCompletionsOpen = false
210				m.currentQuery = ""
211				m.completionsStartIndex = 0
212				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
213			}
214		default:
215			if m.isCompletionsOpen {
216				m.currentQuery += msg.String()
217				cmds = append(cmds, util.CmdHandler(completions.FilterCompletionsMsg{
218					Query: m.currentQuery,
219				}))
220			}
221		}
222		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
223			m.deleteMode = true
224			return m, nil
225		}
226		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
227			m.deleteMode = false
228			m.attachments = nil
229			return m, nil
230		}
231		rune := msg.Code
232		if m.deleteMode && unicode.IsDigit(rune) {
233			num := int(rune - '0')
234			m.deleteMode = false
235			if num < 10 && len(m.attachments) > num {
236				if num == 0 {
237					m.attachments = m.attachments[num+1:]
238				} else {
239					m.attachments = slices.Delete(m.attachments, num, num+1)
240				}
241				return m, nil
242			}
243		}
244		if key.Matches(msg, m.keyMap.OpenEditor) {
245			if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
246				return m, util.ReportWarn("Agent is working, please wait...")
247			}
248			return m, m.openEditor(m.textarea.Value())
249		}
250		if key.Matches(msg, DeleteKeyMaps.Escape) {
251			m.deleteMode = false
252			return m, nil
253		}
254		if key.Matches(msg, m.keyMap.Newline) {
255			m.textarea.InsertRune('\n')
256		}
257		// Handle Enter key
258		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
259			value := m.textarea.Value()
260			if len(value) > 0 && value[len(value)-1] == '\\' {
261				// If the last character is a backslash, remove it and add a newline
262				m.textarea.SetValue(value[:len(value)-1] + "\n")
263				return m, nil
264			} else {
265				// Otherwise, send the message
266				return m, m.send()
267			}
268		}
269	}
270
271	m.textarea, cmd = m.textarea.Update(msg)
272	cmds = append(cmds, cmd)
273	return m, tea.Batch(cmds...)
274}
275
276func (m *editorCmp) Cursor() *tea.Cursor {
277	cursor := m.textarea.Cursor()
278	if cursor != nil {
279		cursor.X = cursor.X + m.x + 1
280		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
281	}
282	return cursor
283}
284
285func (m *editorCmp) View() string {
286	t := styles.CurrentTheme()
287	if len(m.attachments) == 0 {
288		content := t.S().Base.Padding(1).Render(
289			m.textarea.View(),
290		)
291		return content
292	}
293	content := t.S().Base.Padding(0, 1, 1, 1).Render(
294		lipgloss.JoinVertical(lipgloss.Top,
295			m.attachmentsContent(),
296			m.textarea.View(),
297		),
298	)
299	return content
300}
301
302func (m *editorCmp) SetSize(width, height int) tea.Cmd {
303	m.width = width
304	m.height = height
305	m.textarea.SetWidth(width - 2)   // adjust for padding
306	m.textarea.SetHeight(height - 2) // adjust for padding
307	return nil
308}
309
310func (m *editorCmp) GetSize() (int, int) {
311	return m.textarea.Width(), m.textarea.Height()
312}
313
314func (m *editorCmp) attachmentsContent() string {
315	var styledAttachments []string
316	t := styles.CurrentTheme()
317	attachmentStyles := t.S().Base.
318		MarginLeft(1).
319		Background(t.FgMuted).
320		Foreground(t.FgBase)
321	for i, attachment := range m.attachments {
322		var filename string
323		if len(attachment.FileName) > 10 {
324			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
325		} else {
326			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
327		}
328		if m.deleteMode {
329			filename = fmt.Sprintf("%d%s", i, filename)
330		}
331		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
332	}
333	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
334	return content
335}
336
337func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
338	m.x = x
339	m.y = y
340	return nil
341}
342
343func (m *editorCmp) startCompletions() tea.Msg {
344	files, _, _ := fsext.ListDirectory(".", []string{}, 0)
345	completionItems := make([]completions.Completion, 0, len(files))
346	for _, file := range files {
347		file = strings.TrimPrefix(file, "./")
348		completionItems = append(completionItems, completions.Completion{
349			Title: file,
350			Value: FileCompletionItem{
351				Path: file,
352			},
353		})
354	}
355
356	x := m.textarea.Cursor().X + m.x + 1
357	y := m.textarea.Cursor().Y + m.y + 1
358	return completions.OpenCompletionsMsg{
359		Completions: completionItems,
360		X:           x,
361		Y:           y,
362	}
363}
364
365// Blur implements Container.
366func (c *editorCmp) Blur() tea.Cmd {
367	c.textarea.Blur()
368	return nil
369}
370
371// Focus implements Container.
372func (c *editorCmp) Focus() tea.Cmd {
373	return c.textarea.Focus()
374}
375
376// IsFocused implements Container.
377func (c *editorCmp) IsFocused() bool {
378	return c.textarea.Focused()
379}
380
381// Bindings implements Container.
382func (c *editorCmp) Bindings() []key.Binding {
383	return c.keyMap.KeyBindings()
384}
385
386func NewEditorCmp(app *app.App) util.Model {
387	t := styles.CurrentTheme()
388	ta := textarea.New()
389	ta.SetStyles(t.S().TextArea)
390	ta.SetPromptFunc(4, func(lineIndex int, focused bool) string {
391		if lineIndex == 0 {
392			return "  > "
393		}
394		if focused {
395			return t.S().Base.Foreground(t.GreenDark).Render("::: ")
396		} else {
397			return t.S().Muted.Render("::: ")
398		}
399	})
400	ta.ShowLineNumbers = false
401	ta.CharLimit = -1
402	ta.Placeholder = "Tell me more about this project..."
403	ta.SetVirtualCursor(false)
404	ta.Focus()
405
406	return &editorCmp{
407		app:      app,
408		textarea: ta,
409		keyMap:   DefaultEditorKeyMap(),
410	}
411}