-
Notifications
You must be signed in to change notification settings - Fork 0
/
select.go
86 lines (78 loc) · 1.69 KB
/
select.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package tui
import (
tea "github.com/charmbracelet/bubbletea"
"strings"
)
func NewSelect(choices []string) *SelectModel {
return &SelectModel{
Choices: choices,
}
}
type SelectModel struct {
Choices []string
selected []string
SelectedItem int
KeyHandler KeyHandler
NewKey tea.Key
IsQuit bool
Title string
}
func (m *SelectModel) Init() tea.Cmd {
m.SelectedItem = 0
return nil
}
func (m *SelectModel) View() string {
var view strings.Builder
view.WriteString(m.Title)
view.WriteRune('\n')
if len(m.selected) > 0 {
view.WriteString("[x] ")
view.WriteString(m.selected[0])
view.WriteRune('\n')
} else {
for i, choice := range m.Choices {
if i == m.SelectedItem {
view.WriteString("[x] ")
} else {
view.WriteString("[ ] ")
}
view.WriteString(choice)
view.WriteRune('\n')
}
}
return view.String()
}
type KeyHandler func(*SelectModel, tea.Msg) (tea.Model, tea.Cmd)
func (m *SelectModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyEsc, tea.KeyCtrlC, tea.KeyCtrlQ:
return m, tea.Quit
case tea.KeyUp:
m.SelectedItem--
if m.SelectedItem < 0 {
m.SelectedItem = len(m.Choices) - 1
}
return m, nil
case tea.KeyDown:
m.SelectedItem++
if m.SelectedItem >= len(m.Choices) {
m.SelectedItem = 0
}
return m, nil
case tea.KeyEnter:
if m.SelectedItem >= 0 && m.SelectedItem < len(m.Choices) {
m.selected = []string{m.Choices[m.SelectedItem]}
}
return m, tea.Quit
case m.NewKey.Type:
newModel, _ := m.KeyHandler(m, msg)
if m.IsQuit {
return newModel, tea.Quit
}
return newModel, nil
}
}
return m, nil
}