This big news in this release is that forms in Huh can now be dynamic. Read on for more:
Dynamic Forms 🪄
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!
- Form Layouts by @adamdottv in #274
CursorText
style by @nervo in #259WithInput
by @Delta456 in #271WithTimeout
by @Delta456 in #276- Introduce
accessor
by @nervo in #263 - Introduce
accessor
by @nervo in #263 - Set filtering state of select on init by @PJGaetan in #179
Fixed
- Aborting a form returned a timeout error by @Sculas in #287
- Resolve conflict between select and filter by @MikaelFangel in #252
- Adjust input width to char limit by @nervo in #260
New Contributors
- @MikaelFangel made their first contribution in #252
- @nervo made their first contribution in #253
- @shedyfreak made their first contribution in #230
- @Delta456 made their first contribution in #271
- @abradley2 made their first contribution in #280
- @PJGaetan made their first contribution in #179
- @Sculas made their first contribution in #287
Full Changelog: v0.4.2...v0.5.0
Thoughts? Questions? We love hearing from you. Feel free to reach out on Twitter, The Fediverse, or Slack.