Debian Codegraph @

README.md

raw symbols SCIP
1 # Huh?
2
3 <p>
4 <img alt="Hey there! I’m Glenn!" title="Hey there! I’m Glenn!" src="https://stuff.charm.sh/huh/glenn.png" width="400" />
5 <br><br>
6 <a href="https://github.com/charmbracelet/huh/releases"><img src="https://img.shields.io/github/release/charmbracelet/huh.svg" alt="Latest Release"></a>
7 <a href="https://pkg.go.dev/github.com/charmbracelet/huh?tab=doc"><img src="https://godoc.org/github.com/golang/gddo?status.svg" alt="Go Docs"></a>
8 <a href="https://github.com/charmbracelet/huh/actions"><img src="https://github.com/charmbracelet/huh/actions/workflows/build.yml/badge.svg?branch=main" alt="Build Status"></a>
9 </p>
10
11 A simple, powerful library for building interactive forms and prompts in the terminal.
12
13 <img alt="Running a burger form" width="600" src="https://vhs.charm.sh/vhs-3J4i6HE3yBmz6SUO3HqILr.gif">
14
15 `huh?` is easy to use in a standalone fashion, can be
16 [integrated into a Bubble Tea application](#what-about-bubble-tea), and contains
17 a first-class [accessible mode](#accessibility) for screen readers.
18
19 The above example is running from a single Go program ([source](./examples/burger/main.go)).
20
21 ## Tutorial
22
23 Let’s build a form for ordering burgers. To start, we’ll import the library and
24 define a few variables where we'll store answers.
25
26 ```go
27 package main
28
29 import "github.com/charmbracelet/huh"
30
31 var (
32 burger string
33 toppings []string
34 sauceLevel int
35 name string
36 instructions string
37 discount bool
38 )
39 ```
40
41 `huh?` separates forms into groups (you can think of groups as pages). Groups
42 are made of fields (e.g. `Select`, `Input`, `Text`). We will set up three
43 groups for the customer to fill out.
44
45 ```go
46 form := huh.NewForm(
47 huh.NewGroup(
48 // Ask the user for a base burger and toppings.
49 huh.NewSelect[string]().
50 Title("Choose your burger").
51 Options(
52 huh.NewOption("Charmburger Classic", "classic"),
53 huh.NewOption("Chickwich", "chickwich"),
54 huh.NewOption("Fishburger", "fishburger"),
55 huh.NewOption("Charmpossible™ Burger", "charmpossible"),
56 ).
57 Value(&burger), // store the chosen option in the "burger" variable
58
59 // Let the user select multiple toppings.
60 huh.NewMultiSelect[string]().
61 Title("Toppings").
62 Options(
63 huh.NewOption("Lettuce", "lettuce").Selected(true),
64 huh.NewOption("Tomatoes", "tomatoes").Selected(true),
65 huh.NewOption("Jalapeños", "jalapeños"),
66 huh.NewOption("Cheese", "cheese"),
67 huh.NewOption("Vegan Cheese", "vegan cheese"),
68 huh.NewOption("Nutella", "nutella"),
69 ).
70 Limit(4). // there’s a 4 topping limit!
71 Value(&toppings),
72
73 // Option values in selects and multi selects can be any type you
74 // want. We’ve been recording strings above, but here we’ll store
75 // answers as integers. Note the generic "[int]" directive below.
76 huh.NewSelect[int]().
77 Title("How much Charm Sauce do you want?").
78 Options(
79 huh.NewOption("None", 0),
80 huh.NewOption("A little", 1),
81 huh.NewOption("A lot", 2),
82 ).
83 Value(&sauceLevel),
84 ),
85
86 // Gather some final details about the order.
87 huh.NewGroup(
88 huh.NewInput().
89 Title("What’s your name?").
90 Value(&name).
91 // Validating fields is easy. The form will mark erroneous fields
92 // and display error messages accordingly.
93 Validate(func(str string) error {
94 if str == "Frank" {
95 return errors.New("Sorry, we don’t serve customers named Frank.")
96 }
97 return nil
98 }),
99
100 huh.NewText().
101 Title("Special Instructions").
102 CharLimit(400).
103 Value(&instructions),
104
105 huh.NewConfirm().
106 Title("Would you like 15% off?").
107 Value(&discount),
108 ),
109 )
110 ```
111
112 Finally, run the form:
113
114 ```go
115 err := form.Run()
116 if err != nil {
117 log.Fatal(err)
118 }
119
120 if !discount {
121 fmt.Println("What? You didn’t take the discount?!")
122 }
123 ```
124
125 And that’s it! For more info see [the full source][burgersource] for this
126 example as well as [the docs][docs].
127
128 If you need more dynamic forms that change based on input from previous fields,
129 check out the [dynamic forms](#dynamic-forms) example.
130
131 [burgersource]: ./examples/burger/main.go
132 [docs]: https://pkg.go.dev/github.com/charmbracelet/huh?tab=doc
133
134 ## Field Reference
135
136 - [`Input`](#input): single line text input
137 - [`Text`](#text): multi-line text input
138 - [`Select`](#select): select an option from a list
139 - [`MultiSelect`](#multiple-select): select multiple options from a list
140 - [`Confirm`](#confirm): confirm an action (yes or no)
141
142 > [!TIP]
143 > Just want to prompt the user with a single field? Each field has a `Run`
144 > method that can be used as a shorthand for gathering quick and easy input.
145
146 ```go
147 var name string
148
149 huh.NewInput().
150 Title("What’s your name?").
151 Value(&name).
152 Run() // this is blocking...
153
154 fmt.Printf("Hey, %s!\n", name)
155 ```
156
157 ### Input
158
159 Prompt the user for a single line of text.
160
161 <img alt="Input field" width="600" src="https://vhs.charm.sh/vhs-1ULe9JbTHfwFmm3hweRVtD.gif">
162
163 ```go
164 huh.NewInput().
165 Title("What’s for lunch?").
166 Prompt("?").
167 Validate(isFood).
168 Value(&lunch)
169 ```
170
171 ### Text
172
173 Prompt the user for multiple lines of text.
174
175 <img alt="Text field" width="600" src="https://vhs.charm.sh/vhs-2rrIuVSEf38bT0cwc8hfEG.gif">
176
177 ```go
178 huh.NewText().
179 Title("Tell me a story.").
180 Validate(checkForPlagiarism).
181 Value(&story)
182 ```
183
184 ### Select
185
186 Prompt the user to select a single option from a list.
187
188 <img alt="Select field" width="600" src="https://vhs.charm.sh/vhs-7wFqZlxMWgbWmOIpBqXJTi.gif">
189
190 ```go
191 huh.NewSelect[string]().
192 Title("Pick a country.").
193 Options(
194 huh.NewOption("United States", "US"),
195 huh.NewOption("Germany", "DE"),
196 huh.NewOption("Brazil", "BR"),
197 huh.NewOption("Canada", "CA"),
198 ).
199 Value(&country)
200 ```
201
202 ### Multiple Select
203
204 Prompt the user to select multiple (zero or more) options from a list.
205
206 <img alt="Multiselect field" width="600" src="https://vhs.charm.sh/vhs-3TLImcoexOehRNLELysMpK.gif">
207
208 ```go
209 huh.NewMultiSelect[string]().
210 Options(
211 huh.NewOption("Lettuce", "Lettuce").Selected(true),
212 huh.NewOption("Tomatoes", "Tomatoes").Selected(true),
213 huh.NewOption("Charm Sauce", "Charm Sauce"),
214 huh.NewOption("Jalapeños", "Jalapeños"),
215 huh.NewOption("Cheese", "Cheese"),
216 huh.NewOption("Vegan Cheese", "Vegan Cheese"),
217 huh.NewOption("Nutella", "Nutella"),
218 ).
219 Title("Toppings").
220 Limit(4).
221 Value(&toppings)
222 ```
223
224 ### Confirm
225
226 Prompt the user to confirm (Yes or No).
227
228 <img alt="Confirm field" width="600" src="https://vhs.charm.sh/vhs-2HeX5MdOxLsrWwsa0TNMIL.gif">
229
230 ```go
231 huh.NewConfirm().
232 Title("Are you sure?").
233 Affirmative("Yes!").
234 Negative("No.").
235 Value(&confirm)
236 ```
237
238 ## Accessibility
239
240 `huh?` has a special rendering option designed specifically for screen readers.
241 You can enable it with `form.WithAccessible(true)`.
242
243 > [!TIP]
244 > We recommend setting this through an environment variable or configuration
245 > option to allow the user to control accessibility.
246
247 ```go
248 accessibleMode := os.Getenv("ACCESSIBLE") != ""
249 form.WithAccessible(accessibleMode)
250 ```
251
252 Accessible forms will drop TUIs in favor of standard prompts, providing better
253 dictation and feedback of the information on screen for the visually impaired.
254
255 <img alt="Accessible cuisine form" width="600" src="https://vhs.charm.sh/vhs-19xEBn4LgzPZDtgzXRRJYS.gif">
256
257 ## Themes
258
259 `huh?` contains a powerful theme abstraction. Supply your own custom theme or
260 choose from one of the five predefined themes:
261
262 - `Charm`
263 - `Dracula`
264 - `Catppuccin`
265 - `Base 16`
266 - `Default`
267
268 <br />
269 <p>
270 <img alt="Charm-themed form" width="400" src="https://stuff.charm.sh/huh/themes/charm-theme.png">
271 <img alt="Dracula-themed form" width="400" src="https://stuff.charm.sh/huh/themes/dracula-theme.png">
272 <img alt="Catppuccin-themed form" width="400" src="https://stuff.charm.sh/huh/themes/catppuccin-theme.png">
273 <img alt="Base 16-themed form" width="400" src="https://stuff.charm.sh/huh/themes/basesixteen-theme.png">
274 <img alt="Default-themed form" width="400" src="https://stuff.charm.sh/huh/themes/default-theme.png">
275 </p>
276
277 Themes can take advantage of the full range of
278 [Lip Gloss][lipgloss] style options. For a high level theme reference see
279 [the docs](https://pkg.go.dev/github.com/charmbracelet/huh#Theme).
280
281 [lipgloss]: https://github.com/charmbracelet/lipgloss
282
283 ## Dynamic Forms
284
285 `huh?` forms can be as dynamic as your heart desires. Simply replace properties
286 with their equivalent `Func` to recompute the properties value every time a
287 different part of your form changes.
288
289 Here’s how you would build a simple country + state / province picker.
290
291 First, define some variables that we’ll use to store the user selection.
292
293 ```go
294 var country string
295 var state string
296 ```
297
298 Define your country select as you normally would:
299
300 ```go
301 huh.NewSelect[string]().
302 Options(huh.NewOptions("United States", "Canada", "Mexico")...).
303 Value(&country).
304 Title("Country").
305 ```
306
307 Define your state select with `TitleFunc` and `OptionsFunc` instead of `Title`
308 and `Options`. This will allow you to change the title and options based on the
309 selection of the previous field, i.e. `country`.
310
311 To do this, we provide a `func() string` and a `binding any` to `TitleFunc`. The
312 function defines what to show for the title and the binding specifies what value
313 needs to change for the function to recompute. So if `country` changes (e.g. the
314 user changes the selection) we will recompute the function.
315
316 For `OptionsFunc`, we provide a `func() []Option[string]` and a `binding any`.
317 We’ll fetch the country’s states, provinces, or territories from an API. `huh`
318 will automatically handle caching for you.
319
320 > [!IMPORTANT]
321 > We have to pass `&country` as the binding to recompute the function only when
322 > `country` changes, otherwise we will hit the API too often.
323
324 ```go
325 huh.NewSelect[string]().
326 Value(&state).
327 Height(8).
328 TitleFunc(func() string {
329 switch country {
330 case "United States":
331 return "State"
332 case "Canada":
333 return "Province"
334 default:
335 return "Territory"
336 }
337 }, &country).
338 OptionsFunc(func() []huh.Option[string] {
339 opts := fetchStatesForCountry(country)
340 return huh.NewOptions(opts...)
341 }, &country),
342 ```
343
344 Lastly, run the `form` with these inputs.
345
346 ```go
347 err := form.Run()
348 if err != nil {
349 log.Fatal(err)
350 }
351 ```
352
353 <img width="600" src="https://vhs.charm.sh/vhs-6FRmBjNi2aiRb4INPXwIjo.gif" alt="Country / State form with dynamic inputs running.">
354
355 ## Bonus: Spinner
356
357 `huh?` ships with a standalone spinner package. It’s useful for indicating
358 background activity after a form is submitted.
359
360 <img alt="Spinner while making a burger" width="600" src="https://vhs.charm.sh/vhs-6HvYomAFP6H8mngOYWXvwJ.gif">
361
362 Create a new spinner, set a title, set the action (or provide a `Context`), and run the spinner:
363
364 <table>
365
366 <tr>
367 <td> <strong>Action Style</strong> </td><td> <strong>Context Style</strong> </td></tr>
368 <tr>
369 <td>
370
371 ```go
372 err := spinner.New().
373 Title("Making your burger...").
374 Action(makeBurger).
375 Run()
376
377 fmt.Println("Order up!")
378 ```
379
380 </td>
381 <td>
382
383 ```go
384 go makeBurger()
385
386 err := spinner.New().
387 Type(spinner.Line).
388 Title("Making your burger...").
389 Context(ctx).
390 Run()
391
392 fmt.Println("Order up!")
393 ```
394
395 </td>
396 </tr>
397 </table>
398
399 For more on Spinners see the [spinner examples](./spinner/examples) and
400 [the spinner docs](https://pkg.go.dev/github.com/charmbracelet/huh/spinner).
401
402 ## What about Bubble Tea?
403
404 <img alt="Bubbletea + Huh?" width="174" src="https://stuff.charm.sh/huh/bubbletea-huh.png">
405
406 Huh is built on [Bubble Tea][tea] and, in addition to its standalone mode,
407 `huh?` has first-class support and can be easily integrated into
408 Bubble Tea applications. It’s very useful in portions of your Bubble Tea
409 application that need form-like input, and for times when you need more
410 flexibility than `huh?` alone can offer.
411
412 <img alt="Bubble Tea embedded form example" width="800" src="https://vhs.charm.sh/vhs-3wGaB7EUKWmojeaHpARMUv.gif">
413
414 A `huh.Form` is just a `tea.Model`, so you can use it just as
415 you would any other [Bubble](https://github.com/charmbracelet/bubbles).
416
417 ```go
418 type Model struct {
419 form *huh.Form // huh.Form is just a tea.Model
420 }
421
422 func NewModel() Model {
423 return Model{
424 form: huh.NewForm(
425 huh.NewGroup(
426 huh.NewSelect[string]().
427 Key("class").
428 Options(huh.NewOptions("Warrior", "Mage", "Rogue")...).
429 Title("Choose your class"),
430
431 huh.NewSelect[int]().
432 Key("level").
433 Options(huh.NewOptions(1, 20, 9999)...).
434 Title("Choose your level"),
435 ),
436 )
437 }
438 }
439
440 func (m Model) Init() tea.Cmd {
441 return m.form.Init()
442 }
443
444 func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
445 // ...
446
447 form, cmd := m.form.Update(msg)
448 if f, ok := form.(*huh.Form); ok {
449 m.form = f
450 }
451
452 return m, cmd
453 }
454
455 func (m Model) View() string {
456 if m.form.State == huh.StateCompleted {
457 class := m.form.GetString("class")
458 level := m.form.GetInt("level")
459 return fmt.Sprintf("You selected: %s, Lvl. %d", class, level)
460 }
461 return m.form.View()
462 }
463
464 ```
465
466 For more info in using `huh?` in Bubble Tea applications see [the full Bubble
467 Tea example][example].
468
469 [tea]: https://github.com/charmbracelet/bubbletea
470 [bubbles]: https://github.com/charmbracelet/bubbles
471 [example]: https://github.com/charmbracelet/huh/blob/main/examples/bubbletea/main.go
472
473 ## `Huh?` in the Wild
474
475 For some `Huh?` programs in production, see:
476
477 * [glyphs](https://github.com/maaslalani/glyphs): a unicode symbol picker
478 * [meteor](https://github.com/stefanlogue/meteor): a highly customisable conventional commit message tool
479 * [freeze](https://github.com/charmbracelet/freeze): a tool for generating images of code and terminal output
480 * [savvy](https://github.com/getsavvyinc/savvy-cli): the easiest way to create, share, and run runbooks in the terminal
481
482 ## Contributing
483
484 See [contributing][contribute].
485
486 [contribute]: https://github.com/charmbracelet/huh/contribute
487
488 ## Feedback
489
490 We’d love to hear your thoughts on this project. Feel free to drop us a note!
491
492 - [Twitter](https://twitter.com/charmcli)
493 - [The Fediverse](https://mastodon.social/@charmcli)
494 - [Discord](https://charm.sh/chat)
495
496 ## Acknowledgments
497
498 `huh?` is inspired by the wonderful [Survey][survey] library by Alec Aivazis.
499
500 [survey]: https://github.com/AlecAivazis/survey
501
502 ## License
503
504 [MIT](https://github.com/charmbracelet/bubbletea/raw/master/LICENSE)
505
506 ---
507
508 Part of [Charm](https://charm.sh).
509
510 <a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>
511
512 Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة