From 0350ef67c9301eb2daa88c9ff37d5ecbe128c4e3 Mon Sep 17 00:00:00 2001 From: Christian Rocha Date: Wed, 24 Jan 2024 17:53:13 -0500 Subject: [PATCH] docs(example): simple example showing conditional options (#75) * docs(example): simple example showing conditional options * refactor: conditional to use WithHideFunc groups this allows the form to be navigated and the user to choose another option by going back. --------- Co-authored-by: Maas Lalani --- examples/conditional/main.go | 87 ++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 examples/conditional/main.go diff --git a/examples/conditional/main.go b/examples/conditional/main.go new file mode 100644 index 00000000..36db9176 --- /dev/null +++ b/examples/conditional/main.go @@ -0,0 +1,87 @@ +package main + +import ( + "fmt" + "os" + + "github.com/charmbracelet/huh" +) + +type consumable int + +const ( + fruits consumable = iota + vegetables + drinks +) + +func (c consumable) String() string { + return [...]string{"fruit", "vegetable", "drink"}[c] +} + +func main() { + + var category consumable + type opts []huh.Option[string] + + var choice string + + // Then ask for a specific food item based on the previous answer. + 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"), + ). + 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"), + ). + 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"), + ). + Value(&choice), + ).WithHideFunc(func() bool { return category != drinks }), + ).Run() + + if err != nil { + fmt.Println("Trouble in food paradise:", err) + os.Exit(1) + } + + fmt.Printf("One %s coming right up!\n", choice) +}