github charmbracelet/huh v0.5.0

latest releases: v0.6.0, v0.5.3, v0.5.2...
4 months ago

This big news in this release is that forms in Huh can now be dynamic. Read on for more:

Dynamic Forms 🪄

Country / State form with dynamic inputs running.

huh? forms can now react to changes in other parts of the form. Replace properties such as Options, Title, Description with their dynamic counterparts: OptionsFunc, TitleFunc, and DescriptionFunc to recompute properties values on changes when watched variables change.

Let’s build a simple state / province picker.

var country string
var state string

The country select will be static, we’ll use this value to recompute the
options and title for the next input.

huh.NewSelect[string]().
    Options(huh.NewOptions("United States", "Canada", "Mexico")...).
    Value(&country).
    Title("Country").

Define your Select with TitleFunc and OptionsFunc and bind them to the
&country value from the previous field. Whenever the user chooses a different
country, the TitleFunc and OptionsFunc will be recomputed.

Important

We have to pass &country as the binding to recompute the function only when
country changes, otherwise we will hit the API too often.

huh.NewSelect[string]().
    Value(&state).
    Height(8).
    TitleFunc(func() string {
        switch country {
        case "United States":
            return "State"
        case "Canada":
            return "Province"
        default:
            return "Territory"
        }
    }, &country).
    OptionsFunc(func() []huh.Option[string] {
        opts := fetchStatesForCountry(country)
        return huh.NewOptions(opts...)
    }, &country),

Lastly, run the form with these inputs.

err := form.Run()
if err != nil {
    log.Fatal(err)
}

Changelog

New!

Fixed

New Contributors

Full Changelog: v0.4.2...v0.5.0


The Charm logo

Thoughts? Questions? We love hearing from you. Feel free to reach out on Twitter, The Fediverse, or Slack.

Don't miss a new huh release

NewReleases is sending notifications on new releases.