|
| 1 | +package huhtest |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/charmbracelet/huh" |
| 10 | + "github.com/stretchr/testify/require" |
| 11 | +) |
| 12 | + |
| 13 | +var t = new(testing.T) |
| 14 | + |
| 15 | +func ExampleNewResponder() { |
| 16 | + // Arrange |
| 17 | + var ( |
| 18 | + howAreYouFeelingAnswer string |
| 19 | + areYouReadyAnswer bool |
| 20 | + sleptWellAnswer string |
| 21 | + activitiesAnswer []string |
| 22 | + ) |
| 23 | + |
| 24 | + myForm := huh.NewForm( |
| 25 | + huh.NewGroup( |
| 26 | + huh.NewInput(). |
| 27 | + Title("How Are You Feeling?"). |
| 28 | + Value(&howAreYouFeelingAnswer), |
| 29 | + huh.NewConfirm(). |
| 30 | + Title("Are you ready?"). |
| 31 | + Value(&areYouReadyAnswer), |
| 32 | + huh.NewSelect[string](). |
| 33 | + Title("Have you slept well?"). |
| 34 | + Options( |
| 35 | + huh.NewOption("Well!", "well"), |
| 36 | + huh.NewOption("Terribly!", "terrible"), |
| 37 | + huh.NewOption("It was OK!", "ok"), |
| 38 | + ). |
| 39 | + Value(&sleptWellAnswer), |
| 40 | + ), |
| 41 | + huh.NewGroup( |
| 42 | + huh.NewMultiSelect[string](). |
| 43 | + Title("What are your favourite activities?"). |
| 44 | + Options( |
| 45 | + huh.NewOption("Cycling", "bike"), |
| 46 | + huh.NewOption("Sleeping", "sleep"), |
| 47 | + huh.NewOption("Boating", "boat"), |
| 48 | + huh.NewOption("Gaming", "game"), |
| 49 | + huh.NewOption("Flying", "fly"), |
| 50 | + ). |
| 51 | + Value(&activitiesAnswer), |
| 52 | + ), |
| 53 | + ) |
| 54 | + |
| 55 | + stdin, stdout, cancel := NewResponder(). |
| 56 | + AddResponse("How Are You Feeling?", "Great"). |
| 57 | + AddConfirm("Are you ready?", ConfirmAffirm). |
| 58 | + AddMultiSelect("activities", []int{1, 2, 4}). |
| 59 | + AddSelect("Have you slept well", 2). |
| 60 | + Start(t, 1*time.Second) |
| 61 | + |
| 62 | + defer cancel() |
| 63 | + |
| 64 | + // Act |
| 65 | + err := myForm.WithInput(stdin).WithOutput(stdout).Run() |
| 66 | + |
| 67 | + // Assert |
| 68 | + require.NoError(t, err) |
| 69 | + |
| 70 | + fmt.Println("How are you feeling?", howAreYouFeelingAnswer) |
| 71 | + fmt.Println("Are you ready?", areYouReadyAnswer) |
| 72 | + fmt.Println("Have you slept well?", sleptWellAnswer) |
| 73 | + fmt.Println("What are your favourite activities?", strings.Join(activitiesAnswer, ", ")) |
| 74 | + |
| 75 | + // Output: |
| 76 | + // How are you feeling? Great |
| 77 | + // Are you ready? true |
| 78 | + // Have you slept well? ok |
| 79 | + // What are your favourite activities? sleep, boat, fly |
| 80 | +} |
0 commit comments