forked from AlecAivazis/survey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselect.go
263 lines (239 loc) · 6.46 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
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package survey
import (
"errors"
"os"
"strings"
"gopkg.in/AlecAivazis/survey.v1/core"
"gopkg.in/AlecAivazis/survey.v1/terminal"
)
/*
Select is a prompt that presents a list of various options to the user
for them to select using the arrow keys and enter. Response type is a string.
color := ""
prompt := &survey.Select{
Message: "Choose a color:",
Options: []string{"red", "blue", "green"},
}
survey.AskOne(prompt, &color, nil)
*/
type Select struct {
core.Renderer
Message string
Options []string
Default string
Help string
PageSize int
VimMode bool
FilterMessage string
filter string
selectedIndex int
useDefault bool
showingHelp bool
}
// the data available to the templates when processing
type SelectTemplateData struct {
Select
PageEntries []string
SelectedIndex int
Answer string
ShowAnswer bool
ShowHelp bool
}
var SelectQuestionTemplate = `
{{- if .ShowHelp }}{{- color "cyan"}}{{ HelpIcon }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}}
{{- color "green+hb"}}{{ QuestionIcon }} {{color "reset"}}
{{- color "default+hb"}}{{ .Message }}{{ .FilterMessage }}{{color "reset"}}
{{- if .ShowAnswer}}{{color "cyan"}} {{.Answer}}{{color "reset"}}{{"\n"}}
{{- else}}
{{- " "}}{{- color "cyan"}}[Use arrows to move, type to filter{{- if and .Help (not .ShowHelp)}}, {{ HelpInputRune }} for more help{{end}}]{{color "reset"}}
{{- "\n"}}
{{- range $ix, $choice := .PageEntries}}
{{- if eq $ix $.SelectedIndex}}{{color "cyan+b"}}{{ SelectFocusIcon }} {{else}}{{color "default+hb"}} {{end}}
{{- $choice}}
{{- color "reset"}}{{"\n"}}
{{- end}}
{{- end}}`
// OnChange is called on every keypress.
func (s *Select) OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool) {
options := s.filterOptions()
oldFilter := s.filter
// if the user pressed the enter key
if key == terminal.KeyEnter {
if s.selectedIndex < len(options) {
return []rune(options[s.selectedIndex]), 0, true
}
// if the user pressed the up arrow or 'k' to emulate vim
} else if key == terminal.KeyArrowUp || (s.VimMode && key == 'k') {
s.useDefault = false
// if we are at the top of the list
if s.selectedIndex == 0 {
// start from the button
s.selectedIndex = len(options) - 1
} else {
// otherwise we are not at the top of the list so decrement the selected index
s.selectedIndex--
}
// if the user pressed down or 'j' to emulate vim
} else if key == terminal.KeyArrowDown || (s.VimMode && key == 'j') {
s.useDefault = false
// if we are at the bottom of the list
if s.selectedIndex == len(options)-1 {
// start from the top
s.selectedIndex = 0
} else {
// increment the selected index
s.selectedIndex++
}
// only show the help message if we have one
} else if key == core.HelpInputRune && s.Help != "" {
s.showingHelp = true
} else if key == terminal.KeyEscape {
s.VimMode = !s.VimMode
} else if key == terminal.KeyDeleteWord || key == terminal.KeyDeleteLine {
s.filter = ""
} else if key == terminal.KeyDelete || key == terminal.KeyBackspace {
if s.filter != "" {
s.filter = s.filter[0 : len(s.filter)-1]
}
} else if key >= terminal.KeySpace {
s.filter += string(key)
s.VimMode = false
}
s.FilterMessage = ""
if s.filter != "" {
s.FilterMessage = " " + s.filter
}
if oldFilter != s.filter {
// filter changed
options = s.filterOptions()
if len(options) > 0 && len(options) <= s.selectedIndex {
s.selectedIndex = len(options) - 1
}
}
// figure out the options and index to render
// TODO if we have started filtering and were looking at the end of a list
// and we have modified the filter then we should move the page back!
opts, idx := paginate(s.PageSize, options, s.selectedIndex)
// render the options
s.Render(
SelectQuestionTemplate,
SelectTemplateData{
Select: *s,
SelectedIndex: idx,
ShowHelp: s.showingHelp,
PageEntries: opts,
},
)
// if we are not pressing ent
if len(options) <= s.selectedIndex {
return []rune{}, 0, false
}
return []rune(options[s.selectedIndex]), 0, true
}
func (s *Select) filterOptions() []string {
filter := strings.ToLower(s.filter)
if filter == "" {
return s.Options
}
answer := []string{}
for _, o := range s.Options {
if strings.Contains(strings.ToLower(o), filter) {
answer = append(answer, o)
}
}
return answer
}
func (s *Select) Prompt() (interface{}, error) {
// if there are no options to render
if len(s.Options) == 0 {
// we failed
return "", errors.New("please provide options to select from")
}
// start off with the first option selected
sel := 0
// if there is a default
if s.Default != "" {
// find the choice
for i, opt := range s.Options {
// if the option correponds to the default
if opt == s.Default {
// we found our initial value
sel = i
// stop looking
break
}
}
}
// save the selected index
s.selectedIndex = sel
// figure out the options and index to render
opts, idx := paginate(s.PageSize, s.Options, sel)
// ask the question
err := s.Render(
SelectQuestionTemplate,
SelectTemplateData{
Select: *s,
PageEntries: opts,
SelectedIndex: idx,
},
)
if err != nil {
return "", err
}
// hide the cursor
terminal.CursorHide()
// show the cursor when we're done
defer terminal.CursorShow()
// by default, use the default value
s.useDefault = true
rr := terminal.NewRuneReader(os.Stdin)
rr.SetTermMode()
defer rr.RestoreTermMode()
// start waiting for input
for {
r, _, err := rr.ReadRune()
if err != nil {
return "", err
}
if r == '\r' || r == '\n' {
break
}
if r == terminal.KeyInterrupt {
return "", terminal.InterruptErr
}
if r == terminal.KeyEndTransmission {
break
}
s.OnChange(nil, 0, r)
}
options := s.filterOptions()
s.filter = ""
s.FilterMessage = ""
var val string
// if we are supposed to use the default value
if s.useDefault || s.selectedIndex >= len(options) {
// if there is a default value
if s.Default != "" {
// use the default value
val = s.Default
} else if len(options) > 0 {
// there is no default value so use the first
val = options[0]
}
// otherwise the selected index points to the value
} else if s.selectedIndex < len(options) {
// the
val = options[s.selectedIndex]
}
return val, err
}
func (s *Select) Cleanup(val interface{}) error {
return s.Render(
SelectQuestionTemplate,
SelectTemplateData{
Select: *s,
Answer: val.(string),
ShowAnswer: true,
},
)
}