generated from tbistr/golang-vscode-devcontainer
/
ui.go
122 lines (102 loc) · 2.34 KB
/
ui.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package ui
import (
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/tbistr/inc"
)
// RunSelector runs the default selector UI.
func RunSelector(e *inc.Engine) (Model, error) {
m, err := tea.NewProgram(NewModel(e), tea.WithAltScreen()).Run()
return m.(Model), err
}
type keyMap struct {
Up,
Down,
Enter,
Quit key.Binding
}
var keys = keyMap{
Up: key.NewBinding(key.WithKeys("up")),
Down: key.NewBinding(key.WithKeys("down")),
Enter: key.NewBinding(key.WithKeys("enter")),
Quit: key.NewBinding(key.WithKeys("ctrl+c", "esc")),
}
type Model struct {
engine *inc.Engine
input textinput.Model
list list.Model
keys keyMap
Selected inc.Candidate
Canceled bool
}
func NewModel(e *inc.Engine) Model {
ti := textinput.New()
ti.Placeholder = "Enter a query"
ti.Focus()
ti.Width = 20
cands := e.Candidates()
items := make([]list.Item, len(cands))
for i, c := range cands {
items[i] = item{c}
}
return Model{
engine: e,
input: ti,
list: NewList(e),
keys: keys,
}
}
var _ tea.Model = Model{}
func (m Model) Init() tea.Cmd {
return textinput.Blink
}
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.input.Width = msg.Width
m.list.SetWidth(msg.Width)
m.list.SetHeight(msg.Height - 1)
case tea.KeyMsg:
switch {
case key.Matches(msg, m.keys.Up):
m.list.CursorUp()
case key.Matches(msg, m.keys.Down):
m.list.CursorDown()
case key.Matches(msg, m.keys.Enter):
return m, tea.Quit
case key.Matches(msg, m.keys.Quit):
m.Canceled = true
return m, tea.Quit
}
}
var cmdI, cmdL tea.Cmd
m.input, cmdI = m.input.Update(msg)
m.engine.DelQuery()
for _, r := range m.input.Value() {
m.engine.AddQuery(r)
}
cands := m.engine.Candidates()
items := []list.Item{}
for _, c := range cands {
if c.Matched {
items = append(items, item{c})
}
}
m.list.SetItems(items)
if _, ok := msg.(tea.KeyMsg); !ok {
m.list, cmdL = m.list.Update(msg)
}
if len(m.engine.Matched()) > m.list.Index() {
m.Selected = m.engine.Matched()[m.list.Index()]
} else {
m.Selected = inc.Candidate{}
}
return m, tea.Batch(cmdI, cmdL)
}
func (m Model) View() string {
return m.input.View() +
"\n" +
m.list.View()
}