-
Notifications
You must be signed in to change notification settings - Fork 20
/
model.go
319 lines (258 loc) · 6.82 KB
/
model.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package textinput
import (
"bytes"
"fmt"
"strings"
"text/template"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/erikgeiser/promptkit"
"github.com/muesli/termenv"
)
// Model implements the bubbletea.Model for a text input.
type Model struct {
*TextInput
// Err holds errors that may occur during the execution of
// the textinput.
Err error
// MaxWidth limits the width of the view using the TextInput's WrapMode.
MaxWidth int
input textinput.Model
tmpl *template.Template
resultTmpl *template.Template
autoCompleteTriggered bool
autoCompleteIndecisive bool
quitting bool
width int
}
// ensure that the Model interface is implemented.
var _ tea.Model = &Model{}
// NewModel returns a new model based on the provided text input.
func NewModel(textInput *TextInput) *Model {
return &Model{TextInput: textInput}
}
// Init initializes the text input model.
func (m *Model) Init() tea.Cmd {
m.tmpl, m.Err = m.initTemplate()
if m.Err != nil {
return tea.Quit
}
m.resultTmpl, m.Err = m.initResultTemplate()
if m.Err != nil {
return tea.Quit
}
m.input = m.initInput()
return textinput.Blink
}
func (m *Model) initTemplate() (*template.Template, error) {
tmpl := template.New("view")
tmpl.Funcs(termenv.TemplateFuncs(m.ColorProfile))
tmpl.Funcs(promptkit.UtilFuncMap())
tmpl.Funcs(m.ExtendedTemplateFuncs)
tmpl.Funcs(template.FuncMap{
"Mask": m.mask,
"AutoCompleteSuggestions": func() []string {
return m.AutoComplete(m.input.Value())
},
})
return tmpl.Parse(m.Template)
}
func (m *Model) initResultTemplate() (*template.Template, error) {
if m.ResultTemplate == "" {
return nil, nil
}
tmpl := template.New("result")
tmpl.Funcs(termenv.TemplateFuncs(m.ColorProfile))
tmpl.Funcs(promptkit.UtilFuncMap())
tmpl.Funcs(m.ExtendedTemplateFuncs)
tmpl.Funcs(template.FuncMap{
"Mask": m.mask,
})
return tmpl.Parse(m.ResultTemplate)
}
func (m *Model) initInput() textinput.Model {
input := textinput.New()
input.Prompt = ""
input.Placeholder = m.Placeholder
input.CharLimit = m.CharLimit
input.Width = m.InputWidth
input.TextStyle = m.InputTextStyle
input.PlaceholderStyle = m.InputPlaceholderStyle
input.Cursor.Style = m.InputCursorStyle
if m.Hidden {
input.EchoMode = textinput.EchoPassword
input.EchoCharacter = m.HideMask
}
input.SetValue(m.InitialValue)
input.Focus()
return input
}
// Update updates the model based on the received message.
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if m.Err != nil {
return m, tea.Quit
}
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
m.autoCompleteTriggered = false
m.autoCompleteIndecisive = false
switch {
case keyMatches(msg, m.KeyMap.Submit):
if m.Validate == nil || m.Validate(m.input.Value()) == nil {
m.quitting = true
return m, tea.Quit
}
case keyMatches(msg, m.KeyMap.AutoComplete):
if m.AutoComplete != nil {
m.input.SetValue(m.autoCompleteResult(m.input.Value()))
m.input.CursorEnd()
}
case keyMatches(msg, m.KeyMap.Abort):
m.Err = promptkit.ErrAborted
m.quitting = true
return m, tea.Quit
case keyMatches(msg, m.KeyMap.Reset):
m.input.SetValue(m.InitialValue)
m.input.CursorStart()
return m, cmd
case keyMatches(msg, m.KeyMap.Clear):
m.input.SetValue("")
return m, cmd
case keyMatches(msg, m.KeyMap.DeleteAllAfterCursor):
msg.Type = tea.KeyCtrlK
case keyMatches(msg, m.KeyMap.DeleteAllBeforeCursor):
msg.Type = tea.KeyCtrlU
case keyMatches(msg, m.KeyMap.DeleteWordBeforeCursor):
msg.Type = tea.KeyCtrlW
case keyMatches(msg, m.KeyMap.DeleteUnderCursor):
msg.Type = tea.KeyDelete
case keyMatches(msg, m.KeyMap.DeleteBeforeCursor):
msg.Type = tea.KeyBackspace
case keyMatches(msg, m.KeyMap.MoveBackward):
msg.Type = tea.KeyLeft
case keyMatches(msg, m.KeyMap.MoveForward):
msg.Type = tea.KeyRight
case keyMatches(msg, m.KeyMap.JumpToBeginning):
msg.Type = tea.KeyHome
case keyMatches(msg, m.KeyMap.JumpToEnd):
msg.Type = tea.KeyEnd
case keyMatches(msg, m.KeyMap.Paste):
msg.Type = tea.KeyCtrlV
case keyMatchesUpstreamKeyMap(msg):
return m, cmd // do not pass to bubbles/textinput
default: // do nothing
}
case tea.WindowSizeMsg:
m.width = zeroAwareMin(msg.Width, m.MaxWidth)
case error:
m.Err = msg
return m, tea.Quit
}
m.input, cmd = m.input.Update(msg)
return m, cmd
}
// View renders the text input.
func (m *Model) View() string {
if m.quitting {
view, err := m.resultView()
if err != nil {
m.Err = err
return ""
}
return m.wrap(view)
}
// avoid panics if Quit is sent during Init
if m.tmpl == nil {
return ""
}
viewBuffer := &bytes.Buffer{}
var validationErr error
if m.Validate != nil {
validationErr = m.Validate(m.input.Value())
}
err := m.tmpl.Execute(viewBuffer, map[string]interface{}{
"Prompt": m.Prompt,
"InitialValue": m.InitialValue,
"Placeholder": m.Placeholder,
"Input": m.input.View(),
"ValidationError": validationErr,
"TerminalWidth": m.width,
"AutoCompleteTriggered": m.autoCompleteTriggered,
"AutoCompleteIndecisive": m.autoCompleteIndecisive,
})
if err != nil {
m.Err = err
return "Template Error: " + err.Error()
}
return m.wrap(viewBuffer.String())
}
func (m *Model) resultView() (string, error) {
viewBuffer := &bytes.Buffer{}
if m.ResultTemplate == "" {
return "", nil
}
if m.resultTmpl == nil {
return "", fmt.Errorf("rendering confirmation without loaded template")
}
value, err := m.Value()
if err != nil {
return "", err
}
err = m.resultTmpl.Execute(viewBuffer, map[string]interface{}{
"FinalValue": value,
"Prompt": m.Prompt,
"InitialValue": m.InitialValue,
"Placeholder": m.Placeholder,
"Hidden": m.Hidden,
"TerminalWidth": m.width,
})
if err != nil {
return "", fmt.Errorf("execute confirmation template: %w", err)
}
return viewBuffer.String(), nil
}
func (m *Model) wrap(text string) string {
if m.WrapMode == nil {
return text
}
return m.WrapMode(text, m.width)
}
// Value returns the current value and error.
func (m *Model) Value() (string, error) {
return m.input.Value(), m.Err
}
// mask replaces each character with HideMask if Hidden is true.
func (m *Model) mask(s string) string {
if !m.Hidden {
return s
}
return strings.Repeat(string(m.HideMask), len(s))
}
func (m *Model) autoCompleteResult(input string) string {
m.autoCompleteTriggered = true
if m.AutoComplete == nil {
return input
}
switch candidates := m.AutoComplete(input); len(candidates) {
case 0:
return input
case 1:
return candidates[0]
default:
m.autoCompleteIndecisive = true
return commonPrefix(candidates)
}
}
func zeroAwareMin(a int, b int) int {
switch {
case a == 0:
return b
case b == 0:
return a
case a > b:
return b
default:
return a
}
}