z_mirror/pesticide

git clone https://git.raiguard.me/z_mirror/pesticide

Caleb HeuerUpdate Go module for Codeberg388f8ba

trunk
1.5 KiB68 linesraw
1package ui
2
3import (
4	"log"
5
6	"github.com/charmbracelet/bubbles/textinput"
7	tea "github.com/charmbracelet/bubbletea"
8	"github.com/charmbracelet/lipgloss"
9	"codeberg.org/raiguard/pesticide/command"
10)
11
12type prompt struct {
13	commandHistory CommandHistory
14	textinput      textinput.Model
15}
16
17func (p *prompt) Init() {
18	p.textinput = textinput.New()
19	p.textinput.Prompt = lipgloss.NewStyle().Foreground(lipgloss.Color("12")).Render("(pesticide) ")
20	p.textinput.Focus()
21}
22
23func (p *prompt) Update(msg tea.Msg, cmds *[]tea.Cmd) command.Command {
24	var cmd tea.Cmd
25	p.textinput, cmd = p.textinput.Update(msg)
26	if cmd != nil {
27		*cmds = append(*cmds, cmd)
28	}
29	keyMsg, ok := msg.(tea.KeyMsg)
30	if !ok {
31		return nil
32	}
33	switch keyMsg.Type {
34	case tea.KeyCtrlC:
35		p.textinput.SetValue("")
36	case tea.KeyEnter:
37		input := p.textinput.Value()
38		*cmds = append(*cmds, tea.Println(p.textinput.Prompt, input))
39		if len(input) == 0 {
40			p.commandHistory.Up()
41			input = p.commandHistory.Get()
42			p.commandHistory.Down()
43		} else {
44			p.commandHistory.Append(input)
45		}
46		p.textinput.SetValue("")
47		cmd, err := command.Parse(input)
48		if err != nil {
49			*cmds = append(*cmds, tea.Println(err))
50			break
51		}
52		log.Printf("Command: %s", input)
53		return cmd
54	case tea.KeyUp, tea.KeyCtrlP:
55		p.commandHistory.Up()
56		p.textinput.SetValue(p.commandHistory.Get())
57		p.textinput.SetCursor(999)
58	case tea.KeyDown, tea.KeyCtrlN:
59		p.commandHistory.Down()
60		p.textinput.SetValue(p.commandHistory.Get())
61		p.textinput.SetCursor(999)
62	}
63	return nil
64}
65
66func (p *prompt) View() string {
67	return p.textinput.View()
68}