xonecas.io
5119
Lh

lazy-history / files

lazy-history / internal / list / list.go

2.4 KB
1package internal_list
2
3import (
4	"bytes"
5	"fmt"
6	"io"
7	"os/exec"
8	"strings"
9
10	"github.com/charmbracelet/bubbles/list"
11	tea "github.com/charmbracelet/bubbletea"
12	"github.com/charmbracelet/lipgloss"
13	"github.com/sacenox/lazy-history/internal/debug"
14	"github.com/samber/lo"
15)
16
17type item string
18
19func (i item) FilterValue() string {
20	return ""
21}
22
23type itemDelegate struct{}
24
25func (d itemDelegate) Height() int {
26	return 1
27}
28
29func (d itemDelegate) Spacing() int {
30	return 0
31}
32
33func (d itemDelegate) Update(msg tea.Msg, m *list.Model) tea.Cmd {
34	return nil
35}
36
37func (d itemDelegate) Render(w io.Writer, m list.Model, index int, listItem list.Item) {
38	i, ok := listItem.(item)
39	if !ok {
40		return
41	}
42
43	if index == m.Index() {
44		fmt.Fprint(w, " → ")
45	}
46
47	fmt.Fprint(w, i)
48}
49
50type model struct {
51	list   list.Model
52	choice string
53	output *bytes.Buffer
54}
55
56type ExecuteMessage struct {
57	Error error
58}
59
60func (m model) Init() tea.Cmd {
61	return nil
62}
63
64func (m model) Execute(command string) tea.Cmd {
65	parts := strings.Split(command, " ")
66	cmd := exec.Command(parts[0], parts[1:]...)
67	cmd.Stdout = m.output
68
69	return tea.ExecProcess(cmd, func(err error) tea.Msg {
70		return ExecuteMessage{Error: err}
71	})
72}
73
74func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
75	switch msg := msg.(type) {
76
77	case ExecuteMessage:
78		if msg.Error != nil {
79			debug.Debugf("Error executing command: %v", msg.Error)
80			return m, tea.Quit
81		}
82		return m, tea.Quit
83
84	case tea.WindowSizeMsg:
85		m.list.SetWidth(msg.Width)
86		return m, nil
87
88	case tea.KeyMsg:
89		switch keypress := msg.String(); keypress {
90		case "q", "ctrl+c":
91			return m, tea.Quit
92
93		case "enter":
94			i, ok := m.list.SelectedItem().(item)
95			if ok {
96				m.choice = string(i)
97			}
98			return m, m.Execute(m.choice)
99		}
100	}
101
102	var cmd tea.Cmd
103	m.list, cmd = m.list.Update(msg)
104	return m, cmd
105}
106
107func (m model) View() string {
108	debug.Debugf("view called")
109	output := m.output.String()
110	if output != "" {
111		return output
112	}
113
114	return "\n" + m.list.View()
115}
116
117func New(lines []string) model {
118	items := lo.Map(lines, func(line string, _ int) list.Item {
119		return item(line)
120	})
121
122	highlight := "13"
123	height := 20
124	width := 80
125
126	l := list.New(items, itemDelegate{}, width, height)
127	l.Title = "—  Lazy History —"
128	l.Styles.Title = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color(highlight))
129	l.SetFilteringEnabled(false)
130	l.SetShowStatusBar(false)
131
132	return model{
133		list:   l,
134		output: &bytes.Buffer{},
135	}
136}