Debian Codegraph @

field_input.go

raw symbols SCIP
1 package huh
2
3 import (
4 "cmp"
5 "errors"
6 "fmt"
7 "io"
8 "os"
9 "strings"
10
11 "github.com/charmbracelet/bubbles/key"
12 "github.com/charmbracelet/bubbles/textinput"
13 tea "github.com/charmbracelet/bubbletea"
14 "github.com/charmbracelet/huh/internal/accessibility"
15 "github.com/charmbracelet/lipgloss"
16 )
17
18 // Input is a input field.
19 //
20 // The input field is a field that allows the user to enter text. Use it to user
21 // input. It can be used for collecting text, passwords, or other short input.
22 //
23 // The input field supports Suggestions, Placeholder, and Validation.
24 type Input struct {
25 accessor Accessor[string]
26 key string
27 id int
28
29 title Eval[string]
30 description Eval[string]
31 placeholder Eval[string]
32 suggestions Eval[[]string]
33
34 textinput textinput.Model
35
36 inline bool
37 validate func(string) error
38 err error
39 focused bool
40
41 accessible bool // Deprecated: use RunAccessible instead.
42 width int
43 height int
44
45 theme *Theme
46 keymap InputKeyMap
47 }
48
49 // NewInput creates a new input field.
50 //
51 // The input field is a field that allows the user to enter text. Use it to user
52 // input. It can be used for collecting text, passwords, or other short input.
53 //
54 // The input field supports Suggestions, Placeholder, and Validation.
55 func NewInput() *Input {
56 input := textinput.New()
57
58 i := &Input{
59 accessor: &EmbeddedAccessor[string]{},
60 textinput: input,
61 validate: func(string) error { return nil },
62 id: nextID(),
63 title: Eval[string]{cache: make(map[uint64]string)},
64 description: Eval[string]{cache: make(map[uint64]string)},
65 placeholder: Eval[string]{cache: make(map[uint64]string)},
66 suggestions: Eval[[]string]{cache: make(map[uint64][]string)},
67 }
68
69 return i
70 }
71
72 // Value sets the value of the input field.
73 func (i *Input) Value(value *string) *Input {
74 return i.Accessor(NewPointerAccessor(value))
75 }
76
77 // Accessor sets the accessor of the input field.
78 func (i *Input) Accessor(accessor Accessor[string]) *Input {
79 i.accessor = accessor
80 i.textinput.SetValue(i.accessor.Get())
81 return i
82 }
83
84 // Key sets the key of the input field.
85 func (i *Input) Key(key string) *Input {
86 i.key = key
87 return i
88 }
89
90 // Title sets the title of the input field.
91 //
92 // The Title is static for dynamic Title use `TitleFunc`.
93 func (i *Input) Title(title string) *Input {
94 i.title.val = title
95 i.title.fn = nil
96 return i
97 }
98
99 // Description sets the description of the input field.
100 //
101 // The Description is static for dynamic Description use `DescriptionFunc`.
102 func (i *Input) Description(description string) *Input {
103 i.description.val = description
104 i.description.fn = nil
105 return i
106 }
107
108 // TitleFunc sets the title func of the input field.
109 //
110 // The TitleFunc will be re-evaluated when the binding of the TitleFunc changes.
111 // This is useful when you want to display dynamic content and update the title
112 // when another part of your form changes.
113 //
114 // See README#Dynamic for more usage information.
115 func (i *Input) TitleFunc(f func() string, bindings any) *Input {
116 i.title.fn = f
117 i.title.bindings = bindings
118 return i
119 }
120
121 // DescriptionFunc sets the description func of the input field.
122 //
123 // The DescriptionFunc will be re-evaluated when the binding of the
124 // DescriptionFunc changes. This is useful when you want to display dynamic
125 // content and update the description when another part of your form changes.
126 //
127 // See README#Dynamic for more usage information.
128 func (i *Input) DescriptionFunc(f func() string, bindings any) *Input {
129 i.description.fn = f
130 i.description.bindings = bindings
131 return i
132 }
133
134 // Prompt sets the prompt of the input field.
135 func (i *Input) Prompt(prompt string) *Input {
136 i.textinput.Prompt = prompt
137 return i
138 }
139
140 // CharLimit sets the character limit of the input field.
141 func (i *Input) CharLimit(charlimit int) *Input {
142 i.textinput.CharLimit = charlimit
143 return i
144 }
145
146 // Suggestions sets the suggestions to display for autocomplete in the input
147 // field.
148 //
149 // The suggestions are static for dynamic suggestions use `SuggestionsFunc`.
150 func (i *Input) Suggestions(suggestions []string) *Input {
151 i.suggestions.fn = nil
152
153 i.textinput.ShowSuggestions = len(suggestions) > 0
154 i.textinput.KeyMap.AcceptSuggestion.SetEnabled(len(suggestions) > 0)
155 i.textinput.SetSuggestions(suggestions)
156 return i
157 }
158
159 // SuggestionsFunc sets the suggestions func to display for autocomplete in the
160 // input field.
161 //
162 // The SuggestionsFunc will be re-evaluated when the binding of the
163 // SuggestionsFunc changes. This is useful when you want to display dynamic
164 // suggestions when another part of your form changes.
165 //
166 // See README#Dynamic for more usage information.
167 func (i *Input) SuggestionsFunc(f func() []string, bindings any) *Input {
168 i.suggestions.fn = f
169 i.suggestions.bindings = bindings
170 i.suggestions.loading = true
171
172 i.textinput.KeyMap.AcceptSuggestion.SetEnabled(f != nil)
173 i.textinput.ShowSuggestions = f != nil
174 return i
175 }
176
177 // EchoMode sets the input behavior of the text Input field.
178 type EchoMode textinput.EchoMode
179
180 const (
181 // EchoModeNormal displays text as is.
182 // This is the default behavior.
183 EchoModeNormal EchoMode = EchoMode(textinput.EchoNormal)
184
185 // EchoModePassword displays the EchoCharacter mask instead of actual characters.
186 // This is commonly used for password fields.
187 EchoModePassword EchoMode = EchoMode(textinput.EchoPassword)
188
189 // EchoModeNone displays nothing as characters are entered.
190 // This is commonly seen for password fields on the command line.
191 EchoModeNone EchoMode = EchoMode(textinput.EchoNone)
192 )
193
194 // EchoMode sets the echo mode of the input.
195 func (i *Input) EchoMode(mode EchoMode) *Input {
196 i.textinput.EchoMode = textinput.EchoMode(mode)
197 return i
198 }
199
200 // Password sets whether or not to hide the input while the user is typing.
201 //
202 // Deprecated: use EchoMode(EchoPassword) instead.
203 func (i *Input) Password(password bool) *Input {
204 if password {
205 i.textinput.EchoMode = textinput.EchoPassword
206 } else {
207 i.textinput.EchoMode = textinput.EchoNormal
208 }
209 return i
210 }
211
212 // Placeholder sets the placeholder of the text input.
213 func (i *Input) Placeholder(str string) *Input {
214 i.textinput.Placeholder = str
215 return i
216 }
217
218 // PlaceholderFunc sets the placeholder func of the text input.
219 func (i *Input) PlaceholderFunc(f func() string, bindings any) *Input {
220 i.placeholder.fn = f
221 i.placeholder.bindings = bindings
222 return i
223 }
224
225 // Inline sets whether the title and input should be on the same line.
226 func (i *Input) Inline(inline bool) *Input {
227 i.inline = inline
228 return i
229 }
230
231 // Validate sets the validation function of the input field.
232 func (i *Input) Validate(validate func(string) error) *Input {
233 i.validate = validate
234 return i
235 }
236
237 // Error returns the error of the input field.
238 func (i *Input) Error() error { return i.err }
239
240 // Skip returns whether the input should be skipped or should be blocking.
241 func (*Input) Skip() bool { return false }
242
243 // Zoom returns whether the input should be zoomed.
244 func (*Input) Zoom() bool { return false }
245
246 // Focus focuses the input field.
247 func (i *Input) Focus() tea.Cmd {
248 i.focused = true
249 return i.textinput.Focus()
250 }
251
252 // Blur blurs the input field.
253 func (i *Input) Blur() tea.Cmd {
254 i.focused = false
255 i.accessor.Set(i.textinput.Value())
256 i.textinput.Blur()
257 i.err = i.validate(i.accessor.Get())
258 return nil
259 }
260
261 // KeyBinds returns the help message for the input field.
262 func (i *Input) KeyBinds() []key.Binding {
263 if i.textinput.ShowSuggestions {
264 return []key.Binding{i.keymap.AcceptSuggestion, i.keymap.Prev, i.keymap.Submit, i.keymap.Next}
265 }
266 return []key.Binding{i.keymap.Prev, i.keymap.Submit, i.keymap.Next}
267 }
268
269 // Init initializes the input field.
270 func (i *Input) Init() tea.Cmd {
271 i.textinput.Blur()
272 return nil
273 }
274
275 // Update updates the input field.
276 func (i *Input) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
277 var cmds []tea.Cmd
278 var cmd tea.Cmd
279
280 switch msg := msg.(type) {
281 case updateFieldMsg:
282 var cmds []tea.Cmd
283 if ok, hash := i.title.shouldUpdate(); ok {
284 i.title.bindingsHash = hash
285 if !i.title.loadFromCache() {
286 i.title.loading = true
287 cmds = append(cmds, func() tea.Msg {
288 return updateTitleMsg{id: i.id, title: i.title.fn(), hash: hash}
289 })
290 }
291 }
292 if ok, hash := i.description.shouldUpdate(); ok {
293 i.description.bindingsHash = hash
294 if !i.description.loadFromCache() {
295 i.description.loading = true
296 cmds = append(cmds, func() tea.Msg {
297 return updateDescriptionMsg{id: i.id, description: i.description.fn(), hash: hash}
298 })
299 }
300 }
301 if ok, hash := i.placeholder.shouldUpdate(); ok {
302 i.placeholder.bindingsHash = hash
303 if i.placeholder.loadFromCache() {
304 i.textinput.Placeholder = i.placeholder.val
305 } else {
306 i.placeholder.loading = true
307 cmds = append(cmds, func() tea.Msg {
308 return updatePlaceholderMsg{id: i.id, placeholder: i.placeholder.fn(), hash: hash}
309 })
310 }
311 }
312 if ok, hash := i.suggestions.shouldUpdate(); ok {
313 i.suggestions.bindingsHash = hash
314 if i.suggestions.loadFromCache() {
315 i.textinput.ShowSuggestions = len(i.suggestions.val) > 0
316 i.textinput.SetSuggestions(i.suggestions.val)
317 } else {
318 i.suggestions.loading = true
319 cmds = append(cmds, func() tea.Msg {
320 return updateSuggestionsMsg{id: i.id, suggestions: i.suggestions.fn(), hash: hash}
321 })
322 }
323 }
324 return i, tea.Batch(cmds...)
325 case updateTitleMsg:
326 if i.id == msg.id && i.title.bindingsHash == msg.hash {
327 i.title.update(msg.title)
328 }
329 case updateDescriptionMsg:
330 if i.id == msg.id && i.description.bindingsHash == msg.hash {
331 i.description.update(msg.description)
332 }
333 case updatePlaceholderMsg:
334 if i.id == msg.id && i.placeholder.bindingsHash == msg.hash {
335 i.placeholder.update(msg.placeholder)
336 i.textinput.Placeholder = msg.placeholder
337 }
338 case updateSuggestionsMsg:
339 if i.id == msg.id && i.suggestions.bindingsHash == msg.hash {
340 i.suggestions.update(msg.suggestions)
341 i.textinput.ShowSuggestions = len(msg.suggestions) > 0
342 i.textinput.SetSuggestions(msg.suggestions)
343 }
344 case tea.KeyMsg:
345 i.err = nil
346
347 switch {
348 case key.Matches(msg, i.keymap.Prev):
349 cmds = append(cmds, PrevField)
350 case key.Matches(msg, i.keymap.Next, i.keymap.Submit):
351 value := i.textinput.Value()
352 i.err = i.validate(value)
353 if i.err != nil {
354 return i, nil
355 }
356 cmds = append(cmds, NextField)
357 }
358 }
359
360 i.textinput, cmd = i.textinput.Update(msg)
361 cmds = append(cmds, cmd)
362 i.accessor.Set(i.textinput.Value())
363
364 return i, tea.Batch(cmds...)
365 }
366
367 func (i *Input) activeStyles() *FieldStyles {
368 theme := i.theme
369 if theme == nil {
370 theme = ThemeCharm()
371 }
372 if i.focused {
373 return &theme.Focused
374 }
375 return &theme.Blurred
376 }
377
378 // View renders the input field.
379 func (i *Input) View() string {
380 styles := i.activeStyles()
381 maxWidth := i.width - styles.Base.GetHorizontalFrameSize()
382
383 // NB: since the method is on a pointer receiver these are being mutated.
384 // Because this runs on every render this shouldn't matter in practice,
385 // however.
386 i.textinput.PlaceholderStyle = styles.TextInput.Placeholder
387 i.textinput.PromptStyle = styles.TextInput.Prompt
388 i.textinput.Cursor.Style = styles.TextInput.Cursor
389 i.textinput.Cursor.TextStyle = styles.TextInput.CursorText
390 i.textinput.TextStyle = styles.TextInput.Text
391
392 // Adjust text input size to its char limit if it fit in its width
393 if i.textinput.CharLimit > 0 {
394 i.textinput.Width = max(min(i.textinput.CharLimit, i.textinput.Width, maxWidth), 0)
395 }
396
397 var sb strings.Builder
398 if i.title.val != "" || i.title.fn != nil {
399 sb.WriteString(styles.Title.Render(wrap(i.title.val, maxWidth)))
400 if !i.inline {
401 sb.WriteString("\n")
402 }
403 }
404 if i.description.val != "" || i.description.fn != nil {
405 sb.WriteString(styles.Description.Render(wrap(i.description.val, maxWidth)))
406 if !i.inline {
407 sb.WriteString("\n")
408 }
409 }
410 sb.WriteString(i.textinput.View())
411
412 return styles.Base.
413 Width(i.width).
414 Height(i.height).
415 Render(sb.String())
416 }
417
418 // Run runs the input field in accessible mode.
419 func (i *Input) Run() error {
420 if i.accessible { // TODO: remove in a future release.
421 return i.RunAccessible(os.Stdout, os.Stdin)
422 }
423 return i.run()
424 }
425
426 // run runs the input field.
427 func (i *Input) run() error {
428 return Run(i)
429 }
430
431 // RunAccessible runs the input field in accessible mode.
432 func (i *Input) RunAccessible(w io.Writer, r io.Reader) error {
433 styles := i.activeStyles()
434 validator := func(input string) error {
435 if i.textinput.CharLimit > 0 && len(input) > i.textinput.CharLimit {
436 return fmt.Errorf("Input cannot exceed %d characters", i.textinput.CharLimit)
437 }
438 return i.validate(input)
439 }
440
441 switch i.textinput.EchoMode { //nolint:exhaustive
442 case textinput.EchoNormal:
443 prompt := styles.Title.
444 PaddingRight(1).
445 Render(cmp.Or(i.title.val, "Input:"))
446 value := accessibility.PromptString(w, r, prompt, i.GetValue().(string), validator)
447 i.accessor.Set(value)
448 return nil
449 default:
450 prompt := styles.Title.
451 PaddingRight(1).
452 Render(cmp.Or(i.title.val, "Password:"))
453 if fd, ok := r.(interface{ Fd() uintptr }); ok {
454 value, err := accessibility.PromptPassword(w, fd.Fd(), prompt, validator)
455 if err != nil {
456 return err //nolint:wrapcheck
457 }
458 i.accessor.Set(value)
459 return nil
460 }
461 return errors.New("password asking needs a tty")
462 }
463 }
464
465 // WithKeyMap sets the keymap on an input field.
466 func (i *Input) WithKeyMap(k *KeyMap) Field {
467 i.keymap = k.Input
468 i.textinput.KeyMap.AcceptSuggestion = i.keymap.AcceptSuggestion
469 return i
470 }
471
472 // WithAccessible sets the accessible mode of the input field.
473 //
474 // Deprecated: you may now call [Input.RunAccessible] directly to run the
475 // field in accessible mode.
476 func (i *Input) WithAccessible(accessible bool) Field {
477 i.accessible = accessible
478 return i
479 }
480
481 // WithTheme sets the theme of the input field.
482 func (i *Input) WithTheme(theme *Theme) Field {
483 if i.theme != nil {
484 return i
485 }
486 i.theme = theme
487 return i
488 }
489
490 // WithWidth sets the width of the input field.
491 func (i *Input) WithWidth(width int) Field {
492 styles := i.activeStyles()
493 i.width = width
494 frameSize := styles.Base.GetHorizontalFrameSize()
495 promptWidth := lipgloss.Width(i.textinput.PromptStyle.Render(i.textinput.Prompt))
496 titleWidth := lipgloss.Width(styles.Title.Render(i.title.val))
497 descriptionWidth := lipgloss.Width(styles.Description.Render(i.description.val))
498 i.textinput.Width = width - frameSize - promptWidth - 1
499 if i.inline {
500 i.textinput.Width -= titleWidth
501 i.textinput.Width -= descriptionWidth
502 }
503 return i
504 }
505
506 // WithHeight sets the height of the input field.
507 func (i *Input) WithHeight(height int) Field {
508 i.height = height
509 return i
510 }
511
512 // WithPosition sets the position of the input field.
513 func (i *Input) WithPosition(p FieldPosition) Field {
514 i.keymap.Prev.SetEnabled(!p.IsFirst())
515 i.keymap.Next.SetEnabled(!p.IsLast())
516 i.keymap.Submit.SetEnabled(p.IsLast())
517 return i
518 }
519
520 // GetKey returns the key of the field.
521 func (i *Input) GetKey() string { return i.key }
522
523 // GetValue returns the value of the field.
524 func (i *Input) GetValue() any {
525 return i.accessor.Get()
526 }