Debian Codegraph @

form.go

raw symbols SCIP
1 package huh
2
3 import (
4 "cmp"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "sync"
11 "time"
12
13 "github.com/charmbracelet/bubbles/help"
14 "github.com/charmbracelet/bubbles/key"
15 tea "github.com/charmbracelet/bubbletea"
16 "github.com/charmbracelet/huh/internal/selector"
17 )
18
19 const defaultWidth = 80
20
21 // Internal ID management. Used during animating to ensure that frame messages
22 // are received only by spinner components that sent them.
23 var (
24 lastID int
25 idMtx sync.Mutex
26 )
27
28 // Return the next ID we should use on the Model.
29 func nextID() int {
30 idMtx.Lock()
31 defer idMtx.Unlock()
32 lastID++
33 return lastID
34 }
35
36 // FormState represents the current state of the form.
37 type FormState int
38
39 const (
40 // StateNormal is when the user is completing the form.
41 StateNormal FormState = iota
42
43 // StateCompleted is when the user has completed the form.
44 StateCompleted
45
46 // StateAborted is when the user has aborted the form.
47 StateAborted
48 )
49
50 // ErrUserAborted is the error returned when a user exits the form before submitting.
51 var ErrUserAborted = errors.New("user aborted")
52
53 // ErrTimeout is the error returned when the timeout is reached.
54 var ErrTimeout = errors.New("timeout")
55
56 // ErrTimeoutUnsupported is the error returned when timeout is used while in accessible mode.
57 var ErrTimeoutUnsupported = errors.New("timeout is not supported in accessible mode")
58
59 // Form is a collection of groups that are displayed one at a time on a "page".
60 //
61 // The form can navigate between groups and is complete once all the groups are
62 // complete.
63 type Form struct {
64 // collection of groups
65 selector *selector.Selector[*Group]
66
67 results map[string]any
68
69 // callbacks
70 SubmitCmd tea.Cmd
71 CancelCmd tea.Cmd
72
73 State FormState
74
75 // whether or not to use bubble tea rendering for accessibility
76 // purposes, if true, the form will render with basic prompting primitives
77 // to be more accessible to screen readers.
78 accessible bool
79
80 quitting bool
81 aborted bool
82
83 // options
84 width int
85 height int
86 theme *Theme
87 keymap *KeyMap
88 timeout time.Duration
89 teaOptions []tea.ProgramOption
90
91 layout Layout
92
93 // accessible mode IO
94 output io.Writer
95 input io.Reader
96 }
97
98 // NewForm returns a form with the given groups and default themes and
99 // keybindings.
100 //
101 // Use With* methods to customize the form with options, such as setting
102 // different themes and keybindings.
103 func NewForm(groups ...*Group) *Form {
104 selector := selector.NewSelector(groups)
105
106 f := &Form{
107 selector: selector,
108 keymap: NewDefaultKeyMap(),
109 results: make(map[string]any),
110 layout: LayoutDefault,
111 teaOptions: []tea.ProgramOption{
112 tea.WithOutput(os.Stderr),
113 tea.WithReportFocus(),
114 },
115 }
116
117 // NB: If dynamic forms come into play this will need to be applied when
118 // groups and fields are added.
119 f.WithKeyMap(f.keymap)
120 f.WithWidth(f.width)
121 f.WithHeight(f.height)
122 f.UpdateFieldPositions()
123
124 if os.Getenv("TERM") == "dumb" {
125 f.WithWidth(defaultWidth)
126 f.WithAccessible(true)
127 }
128
129 return f
130 }
131
132 // Field is a primitive of a form.
133 //
134 // A field represents a single input control on a form such as a text input,
135 // confirm button, select option, etc...
136 //
137 // Each field implements the Bubble Tea Model interface.
138 type Field interface {
139 // Bubble Tea Model
140 Init() tea.Cmd
141 Update(tea.Msg) (tea.Model, tea.Cmd)
142 View() string
143
144 // Bubble Tea Events
145 Blur() tea.Cmd
146 Focus() tea.Cmd
147
148 // Errors and Validation
149 Error() error
150
151 // Run runs the field individually.
152 Run() error
153
154 // RunAccessible runs the field in accessible mode with the given IO.
155 RunAccessible(w io.Writer, r io.Reader) error
156
157 // Skip returns whether this input should be skipped or not.
158 Skip() bool
159
160 // Zoom returns whether this input should be zoomed or not.
161 // Zoom allows the field to take focus of the group / form height.
162 Zoom() bool
163
164 // KeyBinds returns help keybindings.
165 KeyBinds() []key.Binding
166
167 // WithTheme sets the theme on a field.
168 WithTheme(*Theme) Field
169
170 // WithAccessible sets whether the field should run in accessible mode.
171 //
172 // Deprecated: you may now call [Field.RunAccessible] directly to run the field in accessible mode.
173 WithAccessible(bool) Field
174
175 // WithKeyMap sets the keymap on a field.
176 WithKeyMap(*KeyMap) Field
177
178 // WithWidth sets the width of a field.
179 WithWidth(int) Field
180
181 // WithHeight sets the height of a field.
182 WithHeight(int) Field
183
184 // WithPosition tells the field the index of the group and position it is in.
185 WithPosition(FieldPosition) Field
186
187 // GetKey returns the field's key.
188 GetKey() string
189
190 // GetValue returns the field's value.
191 GetValue() any
192 }
193
194 // FieldPosition is positional information about the given field and form.
195 type FieldPosition struct {
196 Group int
197 Field int
198 FirstField int
199 LastField int
200 GroupCount int
201 FirstGroup int
202 LastGroup int
203 }
204
205 // IsFirst returns whether a field is the form's first field.
206 func (p FieldPosition) IsFirst() bool {
207 return p.Field == p.FirstField && p.Group == p.FirstGroup
208 }
209
210 // IsLast returns whether a field is the form's last field.
211 func (p FieldPosition) IsLast() bool {
212 return p.Field == p.LastField && p.Group == p.LastGroup
213 }
214
215 // nextGroupMsg is a message to move to the next group.
216 type nextGroupMsg struct{}
217
218 // prevGroupMsg is a message to move to the previous group.
219 type prevGroupMsg struct{}
220
221 // nextGroup is the command to move to the next group.
222 func nextGroup() tea.Msg {
223 return nextGroupMsg{}
224 }
225
226 // prevGroup is the command to move to the previous group.
227 func prevGroup() tea.Msg {
228 return prevGroupMsg{}
229 }
230
231 // WithAccessible sets the form to run in accessible mode to avoid redrawing the
232 // views which makes it easier for screen readers to read and describe the form.
233 //
234 // This avoids using the Bubble Tea renderer and instead simply uses basic
235 // terminal prompting to gather input which degrades the user experience but
236 // provides accessibility.
237 func (f *Form) WithAccessible(accessible bool) *Form {
238 f.accessible = accessible
239 return f
240 }
241
242 // WithShowHelp sets whether or not the form should show help.
243 //
244 // This allows the form groups and field to show what keybindings are available
245 // to the user.
246 func (f *Form) WithShowHelp(v bool) *Form {
247 f.selector.Range(func(_ int, group *Group) bool {
248 group.WithShowHelp(v)
249 return true
250 })
251 return f
252 }
253
254 // WithShowErrors sets whether or not the form should show errors.
255 //
256 // This allows the form groups and fields to show errors when the Validate
257 // function returns an error.
258 func (f *Form) WithShowErrors(v bool) *Form {
259 f.selector.Range(func(_ int, group *Group) bool {
260 group.WithShowErrors(v)
261 return true
262 })
263 return f
264 }
265
266 // WithTheme sets the theme on a form.
267 //
268 // This allows all groups and fields to be themed consistently, however themes
269 // can be applied to each group and field individually for more granular
270 // control.
271 func (f *Form) WithTheme(theme *Theme) *Form {
272 if theme == nil {
273 return f
274 }
275 f.theme = theme
276 f.selector.Range(func(_ int, group *Group) bool {
277 group.WithTheme(theme)
278 return true
279 })
280 return f
281 }
282
283 // WithKeyMap sets the keymap on a form.
284 //
285 // This allows customization of the form key bindings.
286 func (f *Form) WithKeyMap(keymap *KeyMap) *Form {
287 if keymap == nil {
288 return f
289 }
290 f.keymap = keymap
291 f.selector.Range(func(_ int, group *Group) bool {
292 group.WithKeyMap(keymap)
293 return true
294 })
295 f.UpdateFieldPositions()
296 return f
297 }
298
299 // WithWidth sets the width of a form.
300 //
301 // This allows all groups and fields to be sized consistently, however width
302 // can be applied to each group and field individually for more granular
303 // control.
304 func (f *Form) WithWidth(width int) *Form {
305 if width <= 0 {
306 return f
307 }
308 f.width = width
309 f.selector.Range(func(_ int, group *Group) bool {
310 width := f.layout.GroupWidth(f, group, width)
311 group.WithWidth(width)
312 return true
313 })
314 return f
315 }
316
317 // WithHeight sets the height of a form.
318 func (f *Form) WithHeight(height int) *Form {
319 if height <= 0 {
320 return f
321 }
322 f.height = height
323 f.selector.Range(func(_ int, group *Group) bool {
324 group.WithHeight(height)
325 return true
326 })
327 return f
328 }
329
330 // WithOutput sets the io.Writer to output the form.
331 // Default is STDOUT when [Form] is accessible (set with [Form.WithAccessible], STDERR otherwise.
332 func (f *Form) WithOutput(w io.Writer) *Form {
333 f.output = w
334 f.teaOptions = append(f.teaOptions, tea.WithOutput(w))
335 return f
336 }
337
338 // WithInput sets the io.Reader to the input form.
339 // Default is STDIN.
340 func (f *Form) WithInput(r io.Reader) *Form {
341 f.input = r
342 f.teaOptions = append(f.teaOptions, tea.WithInput(r))
343 return f
344 }
345
346 // WithTimeout sets the duration for the form to be killed.
347 func (f *Form) WithTimeout(t time.Duration) *Form {
348 f.timeout = t
349 return f
350 }
351
352 // WithProgramOptions sets the tea options of the form.
353 func (f *Form) WithProgramOptions(opts ...tea.ProgramOption) *Form {
354 f.teaOptions = opts
355 return f
356 }
357
358 // WithLayout sets the layout on a form.
359 //
360 // This allows customization of the form group layout.
361 func (f *Form) WithLayout(layout Layout) *Form {
362 f.layout = layout
363 return f
364 }
365
366 // UpdateFieldPositions sets the position on all the fields.
367 func (f *Form) UpdateFieldPositions() *Form {
368 firstGroup := 0
369 lastGroup := f.selector.Total() - 1
370
371 // determine the first non-hidden group.
372 f.selector.Range(func(_ int, g *Group) bool {
373 if !f.isGroupHidden(g) {
374 return false
375 }
376 firstGroup++
377 return true
378 })
379
380 // determine the last non-hidden group.
381 f.selector.ReverseRange(func(_ int, g *Group) bool {
382 if !f.isGroupHidden(g) {
383 return false
384 }
385 lastGroup--
386 return true
387 })
388
389 f.selector.Range(func(g int, group *Group) bool {
390 // determine the first non-skippable field.
391 var firstField int
392 group.selector.Range(func(_ int, field Field) bool {
393 if !field.Skip() || group.selector.Total() == 1 {
394 return false
395 }
396 firstField++
397 return true
398 })
399
400 // determine the last non-skippable field.
401 var lastField int
402 group.selector.ReverseRange(func(i int, field Field) bool {
403 lastField = i
404 if !field.Skip() || group.selector.Total() == 1 {
405 return false
406 }
407 return true
408 })
409
410 group.selector.Range(func(i int, field Field) bool {
411 field.WithPosition(FieldPosition{
412 Group: g,
413 Field: i,
414 FirstField: firstField,
415 LastField: lastField,
416 FirstGroup: firstGroup,
417 LastGroup: lastGroup,
418 })
419 return true
420 })
421
422 return true
423 })
424 return f
425 }
426
427 // Errors returns the current groups' errors.
428 func (f *Form) Errors() []error {
429 return f.selector.Selected().Errors()
430 }
431
432 // Help returns the current groups' help.
433 func (f *Form) Help() help.Model {
434 return f.selector.Selected().help
435 }
436
437 // KeyBinds returns the current fields' keybinds.
438 func (f *Form) KeyBinds() []key.Binding {
439 group := f.selector.Selected()
440 return group.selector.Selected().KeyBinds()
441 }
442
443 // Get returns a result from the form.
444 func (f *Form) Get(key string) any {
445 return f.results[key]
446 }
447
448 // GetString returns a result as a string from the form.
449 func (f *Form) GetString(key string) string {
450 v, ok := f.results[key].(string)
451 if !ok {
452 return ""
453 }
454 return v
455 }
456
457 // GetInt returns a result as a int from the form.
458 func (f *Form) GetInt(key string) int {
459 v, ok := f.results[key].(int)
460 if !ok {
461 return 0
462 }
463 return v
464 }
465
466 // GetBool returns a result as a string from the form.
467 func (f *Form) GetBool(key string) bool {
468 v, ok := f.results[key].(bool)
469 if !ok {
470 return false
471 }
472 return v
473 }
474
475 // NextGroup moves the form to the next group.
476 func (f *Form) NextGroup() tea.Cmd {
477 _, cmd := f.Update(nextGroup())
478 return cmd
479 }
480
481 // PrevGroup moves the form to the next group.
482 func (f *Form) PrevGroup() tea.Cmd {
483 _, cmd := f.Update(prevGroup())
484 return cmd
485 }
486
487 // NextField moves the form to the next field.
488 func (f *Form) NextField() tea.Cmd {
489 _, cmd := f.Update(NextField())
490 return cmd
491 }
492
493 // PrevField moves the form to the next field.
494 func (f *Form) PrevField() tea.Cmd {
495 _, cmd := f.Update(PrevField())
496 return cmd
497 }
498
499 // GetFocusedField returns the focused form field.
500 func (f *Form) GetFocusedField() Field {
501 return f.selector.Selected().selector.Selected()
502 }
503
504 // Init initializes the form.
505 func (f *Form) Init() tea.Cmd {
506 var cmds []tea.Cmd
507 f.selector.Range(func(i int, group *Group) bool {
508 if i == 0 {
509 group.active = true
510 }
511 cmds = append(cmds, group.Init())
512 return true
513 })
514
515 if f.isGroupHidden(f.selector.Selected()) {
516 cmds = append(cmds, nextGroup)
517 }
518
519 cmds = append(cmds, tea.WindowSize())
520 return tea.Sequence(cmds...)
521 }
522
523 // Update updates the form.
524 func (f *Form) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
525 // If the form is aborted or completed there's no need to update it.
526 if f.State != StateNormal {
527 return f, nil
528 }
529
530 group := f.selector.Selected()
531
532 switch msg := msg.(type) {
533 case tea.WindowSizeMsg:
534 if f.width == 0 {
535 f.selector.Range(func(_ int, group *Group) bool {
536 width := f.layout.GroupWidth(f, group, msg.Width)
537 group.WithWidth(width)
538 return true
539 })
540 }
541 if f.height == 0 {
542 // calculate the needed height, which is the height of the
543 // heightest group, accounting for the width, wraps, etc.
544 neededHeight := 0
545 f.selector.Range(func(_ int, group *Group) bool {
546 neededHeight = max(neededHeight, group.rawHeight())
547 return true
548 })
549
550 f.selector.Range(func(_ int, group *Group) bool {
551 group.WithHeight(min(neededHeight, msg.Height))
552 return true
553 })
554 }
555
556 case tea.KeyMsg:
557 switch {
558 case key.Matches(msg, f.keymap.Quit):
559 f.aborted = true
560 f.quitting = true
561 f.State = StateAborted
562 return f, f.CancelCmd
563 }
564
565 case nextFieldMsg:
566 // Form is progressing to the next field, let's save the value of the current field.
567 field := group.selector.Selected()
568 f.results[field.GetKey()] = field.GetValue()
569
570 case nextGroupMsg:
571 if len(group.Errors()) > 0 {
572 return f, nil
573 }
574
575 submit := func() (tea.Model, tea.Cmd) {
576 f.quitting = true
577 f.State = StateCompleted
578 return f, f.SubmitCmd
579 }
580
581 if f.selector.OnLast() {
582 return submit()
583 }
584
585 for i := f.selector.Index() + 1; i < f.selector.Total(); i++ {
586 if !f.isGroupHidden(f.selector.Get(i)) {
587 f.selector.SetIndex(i)
588 break
589 }
590 // all subsequent groups are hidden, so we must act as
591 // if we were in the last one.
592 if i == f.selector.Total()-1 {
593 return submit()
594 }
595 }
596 f.selector.Selected().active = true
597 return f, f.selector.Selected().Init()
598
599 case prevGroupMsg:
600 if len(group.Errors()) > 0 {
601 return f, nil
602 }
603
604 for i := f.selector.Index() - 1; i >= 0; i-- {
605 if !f.isGroupHidden(f.selector.Get(i)) {
606 f.selector.SetIndex(i)
607 break
608 }
609 }
610
611 f.selector.Selected().active = true
612 return f, f.selector.Selected().Init()
613 }
614
615 m, cmd := group.Update(msg)
616 f.selector.Set(f.selector.Index(), m.(*Group))
617
618 // A user input a key, this could hide or show other groups,
619 // let's update all of their positions.
620 switch msg.(type) {
621 case tea.KeyMsg:
622 f.UpdateFieldPositions()
623 }
624
625 return f, cmd
626 }
627
628 func (f *Form) isGroupHidden(group *Group) bool {
629 hide := group.hide
630 if hide == nil {
631 return false
632 }
633 return hide()
634 }
635
636 func (f *Form) getTheme() *Theme {
637 if f.theme != nil {
638 return f.theme
639 }
640 return ThemeCharm()
641 }
642
643 func (f *Form) styles() FormStyles {
644 return f.getTheme().Form
645 }
646
647 // View renders the form.
648 func (f *Form) View() string {
649 if f.quitting {
650 return ""
651 }
652
653 return f.styles().Base.Render(f.layout.View(f))
654 }
655
656 // Run runs the form.
657 func (f *Form) Run() error {
658 return f.RunWithContext(context.Background())
659 }
660
661 // RunWithContext runs the form with the given context.
662 func (f *Form) RunWithContext(ctx context.Context) error {
663 f.SubmitCmd = tea.Quit
664 f.CancelCmd = tea.Interrupt
665
666 if f.selector.Total() == 0 {
667 return nil
668 }
669
670 if f.accessible {
671 return f.runAccessible(
672 cmp.Or[io.Writer](f.output, os.Stdout),
673 cmp.Or[io.Reader](f.input, os.Stdin),
674 )
675 }
676
677 return f.run(ctx)
678 }
679
680 // run runs the form in normal mode.
681 func (f *Form) run(ctx context.Context) error {
682 var cancel context.CancelFunc
683 if f.timeout > 0 {
684 ctx, cancel = context.WithTimeout(ctx, f.timeout)
685 defer cancel()
686 }
687
688 f.teaOptions = append(f.teaOptions, tea.WithContext(ctx))
689 m, err := tea.NewProgram(f, f.teaOptions...).Run()
690 if m.(*Form).aborted || errors.Is(err, tea.ErrInterrupted) {
691 return ErrUserAborted
692 }
693 if errors.Is(err, tea.ErrProgramKilled) {
694 return ErrTimeout
695 }
696 if err != nil {
697 return fmt.Errorf("huh: %w", err)
698 }
699 return nil
700 }
701
702 // runAccessible runs the form in accessible mode.
703 func (f *Form) runAccessible(w io.Writer, r io.Reader) error {
704 // Timeouts are not supported in this mode.
705 if f.timeout > 0 {
706 return ErrTimeoutUnsupported
707 }
708
709 f.selector.Range(func(_ int, group *Group) bool {
710 group.selector.Range(func(_ int, field Field) bool {
711 field.Init()
712 field.Focus()
713 _ = field.WithAccessible(true).RunAccessible(w, r)
714 _, _ = fmt.Fprintln(w)
715 return true
716 })
717 return true
718 })
719
720 return nil
721 }