11package components
22
33import (
4+ "reflect"
5+ "strings"
6+
7+ "github.com/charmbracelet/bubbles/key"
48 tea "github.com/charmbracelet/bubbletea"
59 "github.com/charmbracelet/huh"
610)
@@ -9,6 +13,7 @@ import (
913type Form struct {
1014 Form * huh.Form
1115 OnSubmit func ()
16+ Validate func () error
1217}
1318
1419// Init initializes the huh form.
@@ -18,8 +23,31 @@ func (f *Form) Init() tea.Cmd {
1823
1924// Update delegates key inputs to Huh and triggers submission.
2025func (f * Form ) Update (msg tea.Msg ) (tea.Cmd , bool ) {
21- if keyMsg , ok := msg .(tea.KeyMsg ); ok && keyMsg .String () == keyEsc {
22- return nil , true
26+ if keyMsg , ok := msg .(tea.KeyMsg ); ok {
27+ switch keyMsg .String () {
28+ case keyEsc :
29+ return nil , true
30+
31+ case "alt+enter" , "ctrl+s" :
32+ if focused := f .Form .GetFocusedField (); focused != nil {
33+ _ = focused .Blur ()
34+ }
35+
36+ if f .Validate != nil {
37+ if err := f .Validate (); err != nil {
38+ if focused := f .Form .GetFocusedField (); focused != nil {
39+ _ = focused .Focus ()
40+ }
41+ return nil , false
42+ }
43+ }
44+
45+ f .Form .State = huh .StateCompleted
46+ if f .OnSubmit != nil {
47+ f .OnSubmit ()
48+ }
49+ return nil , true
50+ }
2351 }
2452
2553 newForm , cmd := f .Form .Update (msg )
@@ -38,7 +66,46 @@ func (f *Form) Update(msg tea.Msg) (tea.Cmd, bool) {
3866 return cmd , false
3967}
4068
41- // View renders the huh form.
69+ // View renders the huh form with a custom help footer .
4270func (f * Form ) View (_ int ) string {
43- return f .Form .View ()
71+ formView := f .Form .View ()
72+ if f .Form .State != huh .StateNormal {
73+ return formView
74+ }
75+
76+ var bindings []key.Binding
77+
78+ bindings = append (bindings , key .NewBinding (
79+ key .WithKeys ("ctrl+s" , "alt+enter" ),
80+ key .WithHelp ("ctrl+s/alt+enter" , "save" ),
81+ ))
82+
83+ if focused := f .Form .GetFocusedField (); focused != nil {
84+ focusedType := reflect .TypeOf (focused ).String ()
85+ if strings .Contains (focusedType , "Select" ) {
86+ bindings = append (bindings , key .NewBinding (
87+ key .WithKeys ("enter" ),
88+ key .WithHelp ("enter" , "select" ),
89+ ))
90+ } else {
91+ bindings = append (bindings , key .NewBinding (
92+ key .WithKeys ("enter" , "tab" ),
93+ key .WithHelp ("enter" , "next" ),
94+ ))
95+ }
96+ }
97+
98+ bindings = append (bindings , key .NewBinding (
99+ key .WithKeys ("shift+tab" ),
100+ key .WithHelp ("shift+tab" , "back" ),
101+ ))
102+
103+ bindings = append (bindings , key .NewBinding (
104+ key .WithKeys ("esc" ),
105+ key .WithHelp ("esc" , "exit" ),
106+ ))
107+
108+ helpView := f .Form .Help ().ShortHelpView (bindings )
109+
110+ return formView + "\n \n " + helpView
44111}
0 commit comments