Skip to content

Commit

Permalink
refactor: conditional to use WithHideFunc groups
Browse files Browse the repository at this point in the history
this allows the form to be navigated and the user to choose another
option by going back.
  • Loading branch information
maaslalani committed Jan 24, 2024
1 parent 364c1ed commit 7e9cbd3
Showing 1 changed file with 38 additions and 39 deletions.
77 changes: 38 additions & 39 deletions examples/conditional/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,62 +22,61 @@ func (c consumable) String() string {
func main() {

var category consumable

// First, ask for a broad food category.
err := huh.NewSelect[consumable]().
Title("What are you in the mood for?").
Value(&category).
Options(
huh.NewOption("Some fruit", fruits),
huh.NewOption("A vegetable", vegetables),
huh.NewOption("A drink", drinks),
).
Run()

if err != nil {
fmt.Println("Decision trouble:", err)
os.Exit(1)
}

type opts []huh.Option[string]

var choice string

// Then ask for a specific food item based on the previous answer.
err = huh.NewSelect[string]().
Title(fmt.Sprintf("Okay, what kind of %s are you in the mood for?", category)).
Value(&choice).
Options(
func(c consumable) opts {
switch c {
case fruits:
return opts{
err :=
huh.NewForm(
huh.NewGroup(
huh.NewSelect[consumable]().
Title("What are you in the mood for?").
Value(&category).
Options(
huh.NewOption("Some fruit", fruits),
huh.NewOption("A vegetable", vegetables),
huh.NewOption("A drink", drinks),
),
),

huh.NewGroup(
huh.NewSelect[string]().
Title("Okay, what kind of fruit are you in the mood for?").
Options(
huh.NewOption("Tangerine", "tangerine"),
huh.NewOption("Canteloupe", "canteloupe"),
huh.NewOption("Pomelo", "pomelo"),
huh.NewOption("Grapefruit", "grapefruit"),
}
case vegetables:
return opts{
huh.NewOption("Tangerine", "carrot"),
).
Value(&choice),
).WithHideFunc(func() bool { return category != fruits }),

huh.NewGroup(
huh.NewSelect[string]().
Title("Okay, what kind of vegetable are you in the mood for?").
Options(
huh.NewOption("Carrot", "carrot"),
huh.NewOption("Jicama", "jicama"),
huh.NewOption("Kohlrabi", "kohlrabi"),
huh.NewOption("Fennel", "fennel"),
huh.NewOption("Ginger", "ginger"),
}
case drinks:
return opts{
).
Value(&choice),
).WithHideFunc(func() bool { return category != vegetables }),

huh.NewGroup(
huh.NewSelect[string]().
Title(fmt.Sprintf("Okay, what kind of %s are you in the mood for?", category)).
Options(
huh.NewOption("Coffee", "coffee"),
huh.NewOption("Tea", "tea"),
huh.NewOption("Bubble Tea", "bubble tea"),
huh.NewOption("Agua Fresca", "agua-fresca"),
}
default:
return nil
}
}(category)...,
).
Run()
).
Value(&choice),
).WithHideFunc(func() bool { return category != drinks }),
).Run()

if err != nil {
fmt.Println("Trouble in food paradise:", err)
Expand Down

0 comments on commit 7e9cbd3

Please sign in to comment.