Debian Codegraph @

field_confirm.go

raw symbols SCIP
1 package huh
2
3 import (
4 "cmp"
5 "io"
6 "os"
7 "strings"
8
9 "github.com/charmbracelet/bubbles/key"
10 tea "github.com/charmbracelet/bubbletea"
11 "github.com/charmbracelet/huh/internal/accessibility"
12 "github.com/charmbracelet/lipgloss"
13 )
14
15 // Confirm is a form confirm field.
16 type Confirm struct {
17 accessor Accessor[bool]
18 key string
19 id int
20
21 // customization
22 title Eval[string]
23 description Eval[string]
24 affirmative string
25 negative string
26
27 // error handling
28 validate func(bool) error
29 err error
30
31 // state
32 focused bool
33
34 // options
35 width int
36 height int
37 inline bool
38 accessible bool // Deprecated: use RunAccessible instead.
39 theme *Theme
40 keymap ConfirmKeyMap
41 buttonAlignment lipgloss.Position
42 }
43
44 // NewConfirm returns a new confirm field.
45 func NewConfirm() *Confirm {
46 return &Confirm{
47 accessor: &EmbeddedAccessor[bool]{},
48 id: nextID(),
49 title: Eval[string]{cache: make(map[uint64]string)},
50 description: Eval[string]{cache: make(map[uint64]string)},
51 affirmative: "Yes",
52 negative: "No",
53 validate: func(bool) error { return nil },
54 buttonAlignment: lipgloss.Center,
55 }
56 }
57
58 // Validate sets the validation function of the confirm field.
59 func (c *Confirm) Validate(validate func(bool) error) *Confirm {
60 c.validate = validate
61 return c
62 }
63
64 // Error returns the error of the confirm field.
65 func (c *Confirm) Error() error {
66 return c.err
67 }
68
69 // Skip returns whether the confirm should be skipped or should be blocking.
70 func (*Confirm) Skip() bool {
71 return false
72 }
73
74 // Zoom returns whether the input should be zoomed.
75 func (*Confirm) Zoom() bool {
76 return false
77 }
78
79 // Affirmative sets the affirmative value of the confirm field.
80 func (c *Confirm) Affirmative(affirmative string) *Confirm {
81 c.affirmative = affirmative
82 return c
83 }
84
85 // Negative sets the negative value of the confirm field.
86 func (c *Confirm) Negative(negative string) *Confirm {
87 c.negative = negative
88 return c
89 }
90
91 // Value sets the value of the confirm field.
92 func (c *Confirm) Value(value *bool) *Confirm {
93 return c.Accessor(NewPointerAccessor(value))
94 }
95
96 // Accessor sets the accessor of the confirm field.
97 func (c *Confirm) Accessor(accessor Accessor[bool]) *Confirm {
98 c.accessor = accessor
99 return c
100 }
101
102 // Key sets the key of the confirm field.
103 func (c *Confirm) Key(key string) *Confirm {
104 c.key = key
105 return c
106 }
107
108 // Title sets the title of the confirm field.
109 func (c *Confirm) Title(title string) *Confirm {
110 c.title.val = title
111 c.title.fn = nil
112 return c
113 }
114
115 // TitleFunc sets the title func of the confirm field.
116 func (c *Confirm) TitleFunc(f func() string, bindings any) *Confirm {
117 c.title.fn = f
118 c.title.bindings = bindings
119 return c
120 }
121
122 // Description sets the description of the confirm field.
123 func (c *Confirm) Description(description string) *Confirm {
124 c.description.val = description
125 c.description.fn = nil
126 return c
127 }
128
129 // DescriptionFunc sets the description function of the confirm field.
130 func (c *Confirm) DescriptionFunc(f func() string, bindings any) *Confirm {
131 c.description.fn = f
132 c.description.bindings = bindings
133 return c
134 }
135
136 // Inline sets whether the field should be inline.
137 func (c *Confirm) Inline(inline bool) *Confirm {
138 c.inline = inline
139 return c
140 }
141
142 // Focus focuses the confirm field.
143 func (c *Confirm) Focus() tea.Cmd {
144 c.focused = true
145 return nil
146 }
147
148 // Blur blurs the confirm field.
149 func (c *Confirm) Blur() tea.Cmd {
150 c.focused = false
151 c.err = c.validate(c.accessor.Get())
152 return nil
153 }
154
155 // KeyBinds returns the help message for the confirm field.
156 func (c *Confirm) KeyBinds() []key.Binding {
157 return []key.Binding{c.keymap.Toggle, c.keymap.Prev, c.keymap.Submit, c.keymap.Next, c.keymap.Accept, c.keymap.Reject}
158 }
159
160 // Init initializes the confirm field.
161 func (c *Confirm) Init() tea.Cmd {
162 return nil
163 }
164
165 // Update updates the confirm field.
166 func (c *Confirm) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
167 var cmds []tea.Cmd
168
169 switch msg := msg.(type) {
170 case updateFieldMsg:
171 if ok, hash := c.title.shouldUpdate(); ok {
172 c.title.bindingsHash = hash
173 if !c.title.loadFromCache() {
174 c.title.loading = true
175 cmds = append(cmds, func() tea.Msg {
176 return updateTitleMsg{id: c.id, title: c.title.fn(), hash: hash}
177 })
178 }
179 }
180 if ok, hash := c.description.shouldUpdate(); ok {
181 c.description.bindingsHash = hash
182 if !c.description.loadFromCache() {
183 c.description.loading = true
184 cmds = append(cmds, func() tea.Msg {
185 return updateDescriptionMsg{id: c.id, description: c.description.fn(), hash: hash}
186 })
187 }
188 }
189
190 case updateTitleMsg:
191 if msg.id == c.id && msg.hash == c.title.bindingsHash {
192 c.title.val = msg.title
193 c.title.loading = false
194 }
195 case updateDescriptionMsg:
196 if msg.id == c.id && msg.hash == c.description.bindingsHash {
197 c.description.val = msg.description
198 c.description.loading = false
199 }
200 case tea.KeyMsg:
201 c.err = nil
202 switch {
203 case key.Matches(msg, c.keymap.Toggle):
204 if c.negative == "" {
205 break
206 }
207 c.accessor.Set(!c.accessor.Get())
208 case key.Matches(msg, c.keymap.Prev):
209 cmds = append(cmds, PrevField)
210 case key.Matches(msg, c.keymap.Next, c.keymap.Submit):
211 cmds = append(cmds, NextField)
212 case key.Matches(msg, c.keymap.Accept):
213 c.accessor.Set(true)
214 cmds = append(cmds, NextField)
215 case key.Matches(msg, c.keymap.Reject):
216 c.accessor.Set(false)
217 cmds = append(cmds, NextField)
218 }
219 }
220
221 return c, tea.Batch(cmds...)
222 }
223
224 func (c *Confirm) activeStyles() *FieldStyles {
225 theme := c.theme
226 if theme == nil {
227 theme = ThemeCharm()
228 }
229 if c.focused {
230 return &theme.Focused
231 }
232 return &theme.Blurred
233 }
234
235 // View renders the confirm field.
236 func (c *Confirm) View() string {
237 styles := c.activeStyles()
238 maxWidth := c.width - styles.Base.GetHorizontalFrameSize()
239
240 var wroteHeader bool
241 var sb strings.Builder
242 if c.title.val != "" {
243 sb.WriteString(styles.Title.Render(wrap(c.title.val, maxWidth)))
244 wroteHeader = true
245 }
246 if c.err != nil {
247 sb.WriteString(styles.ErrorIndicator.String())
248 wroteHeader = true
249 }
250
251 if c.description.val != "" {
252 description := styles.Description.Render(wrap(c.description.val, maxWidth))
253 if !c.inline && (c.description.val != "" || c.description.fn != nil) {
254 sb.WriteString("\n")
255 }
256 sb.WriteString(description)
257 wroteHeader = true
258 }
259
260 if !c.inline && wroteHeader {
261 sb.WriteString("\n")
262 sb.WriteString("\n")
263 }
264
265 var negative string
266 var affirmative string
267 if c.negative != "" {
268 if c.accessor.Get() {
269 affirmative = styles.FocusedButton.Render(c.affirmative)
270 negative = styles.BlurredButton.Render(c.negative)
271 } else {
272 affirmative = styles.BlurredButton.Render(c.affirmative)
273 negative = styles.FocusedButton.Render(c.negative)
274 }
275 c.keymap.Reject.SetHelp("n", c.negative)
276 } else {
277 affirmative = styles.FocusedButton.Render(c.affirmative)
278 c.keymap.Reject.SetEnabled(false)
279 }
280
281 c.keymap.Accept.SetHelp("y", c.affirmative)
282
283 buttonsRow := lipgloss.JoinHorizontal(c.buttonAlignment, affirmative, negative)
284
285 promptWidth := lipgloss.Width(sb.String())
286 buttonsWidth := lipgloss.Width(buttonsRow)
287
288 renderWidth := max(buttonsWidth, promptWidth)
289
290 style := lipgloss.NewStyle().Width(renderWidth).Align(c.buttonAlignment)
291
292 sb.WriteString(style.Render(buttonsRow))
293 return styles.Base.Width(c.width).Height(c.height).
294 Render(sb.String())
295 }
296
297 // Run runs the confirm field in accessible mode.
298 func (c *Confirm) Run() error {
299 if c.accessible { // TODO: remove in a future release.
300 return c.RunAccessible(os.Stdout, os.Stdin)
301 }
302 return Run(c)
303 }
304
305 // RunAccessible runs the confirm field in accessible mode.
306 func (c *Confirm) RunAccessible(w io.Writer, r io.Reader) error {
307 styles := c.activeStyles()
308 defaultValue := c.GetValue().(bool)
309 opts := "[y/N]"
310 if defaultValue {
311 opts = "[Y/n]"
312 }
313 prompt := styles.Title.
314 PaddingRight(1).
315 Render(cmp.Or(c.title.val, "Choose"), opts)
316 c.accessor.Set(accessibility.PromptBool(w, r, prompt, defaultValue))
317 return nil
318 }
319
320 func (c *Confirm) String() string {
321 if c.accessor.Get() {
322 return c.affirmative
323 }
324 return c.negative
325 }
326
327 // WithTheme sets the theme of the confirm field.
328 func (c *Confirm) WithTheme(theme *Theme) Field {
329 if c.theme != nil {
330 return c
331 }
332 c.theme = theme
333 return c
334 }
335
336 // WithKeyMap sets the keymap of the confirm field.
337 func (c *Confirm) WithKeyMap(k *KeyMap) Field {
338 c.keymap = k.Confirm
339 return c
340 }
341
342 // WithAccessible sets the accessible mode of the confirm field.
343 //
344 // Deprecated: you may now call [Confirm.RunAccessible] directly to run the
345 // field in accessible mode.
346 func (c *Confirm) WithAccessible(accessible bool) Field {
347 c.accessible = accessible
348 return c
349 }
350
351 // WithWidth sets the width of the confirm field.
352 func (c *Confirm) WithWidth(width int) Field {
353 c.width = width
354 return c
355 }
356
357 // WithHeight sets the height of the confirm field.
358 func (c *Confirm) WithHeight(height int) Field {
359 c.height = height
360 return c
361 }
362
363 // WithPosition sets the position of the confirm field.
364 func (c *Confirm) WithPosition(p FieldPosition) Field {
365 c.keymap.Prev.SetEnabled(!p.IsFirst())
366 c.keymap.Next.SetEnabled(!p.IsLast())
367 c.keymap.Submit.SetEnabled(p.IsLast())
368 return c
369 }
370
371 // WithButtonAlignment sets the button position of the confirm field.
372 func (c *Confirm) WithButtonAlignment(p lipgloss.Position) *Confirm {
373 c.buttonAlignment = p
374 return c
375 }
376
377 // GetKey returns the key of the field.
378 func (c *Confirm) GetKey() string {
379 return c.key
380 }
381
382 // GetValue returns the value of the field.
383 func (c *Confirm) GetValue() any {
384 return c.accessor.Get()
385 }