z_mirror/pesticide

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

Caleb HeuerUpdate Go module for Codeberg388f8ba

trunk
1.4 KiB66 linesraw
1package ui
2
3import (
4	"github.com/charmbracelet/bubbles/textinput"
5	tea "github.com/charmbracelet/bubbletea"
6	"codeberg.org/raiguard/pesticide/adapter"
7	"codeberg.org/raiguard/pesticide/config"
8)
9
10type Model struct {
11	config         config.Config
12	adapters       map[string]*adapter.Adapter
13	focusedAdapter *adapter.Adapter
14
15	prompt prompt
16}
17
18func New(config config.Config) *tea.Program {
19	return tea.NewProgram(&Model{
20		config:   config,
21		adapters: map[string]*adapter.Adapter{},
22	})
23}
24
25func (m *Model) Init() tea.Cmd {
26	m.prompt.Init()
27	return tea.Batch(textinput.Blink, tea.Println("Type a command and press <ret> to submit"))
28}
29
30func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
31	var cmds []tea.Cmd
32	switch msg := msg.(type) {
33	case tea.KeyMsg:
34		switch msg.Type {
35		case tea.KeyCtrlD:
36			return m, tea.Quit // Escape hatch for development
37		}
38	case adapter.Msg:
39		cmds = append(cmds, m.handleAdapterMessage(msg))
40	}
41	cmd := m.prompt.Update(msg, &cmds)
42	if cmd != nil {
43		cmds = append(cmds, m.handleCommand(cmd))
44	}
45
46	// Bubbletea does not validate sequence commands, so we must do it ourselves to avoid high CPU usage.
47	var validCmds []tea.Cmd //nolint:prealloc
48	for _, c := range cmds {
49		if c == nil {
50			continue
51		}
52		validCmds = append(validCmds, c)
53	}
54	switch len(validCmds) {
55	case 0:
56		return m, nil
57	case 1:
58		return m, validCmds[0]
59	default:
60		return m, tea.Sequence(cmds...)
61	}
62}
63
64func (m *Model) View() string {
65	return m.prompt.View()
66}