Skip to content
Myr

Add Treilik-inspired example for sending value along on exit

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Christian Rocha · committed by Christian Rocha · parent 51e97bb · Browse files · 1 file+104 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+104 added−0 removed

  • other:+104 added−0 removed

1 file+104 added−0 removed

added:examples/result/main.go+104 added
1package main23// A simple example that shows how to retrieve a value from a Bubble Tea4// program after the Bubble Tea has exited.5//6// Thanks to Treilik for this one.78import (9 "fmt"10 "os"11 "strings"1213 tea "github.com/charmbracelet/bubbletea"14)1516var (17 choices = []string{"Taro", "Coffee", "Lychee"}18)1920type model struct {21 cursor int22 choice chan string23}2425func main() {26 // This is where we'll listen for the choice the user makes in the Bubble27 // Tea program.28 result := make(chan string, 1)2930 // Pass the channel to the initialize function so our Bubble Tea program31 // can send the final choice along when the time comes.32 if err := tea.NewProgram(initialize(result), update, view).Start(); err != nil {33 fmt.Println("Oh no:", err)34 os.Exit(1)35 }3637 // Print out the final choice.38 if r := <-result; r != "" {39 fmt.Printf("\n---\nYou chose %s!\n", r)40 }41}4243// Pass a channel to the model to listen to the result value. This is a44// function that returns the initialize function and is typically how you would45// pass arguments to a tea.Init function.46func initialize(choice chan string) func() (tea.Model, tea.Cmd) {47 return func() (tea.Model, tea.Cmd) {48 return model{cursor: 0, choice: choice}, nil49 }50}5152func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {53 m, _ := mdl.(model)5455 switch msg := msg.(type) {56 case tea.KeyMsg:57 switch msg.String() {5859 case "ctrl+c", "q":60 close(m.choice) // If we're quitting just chose the channel.61 return m, tea.Quit6263 case "enter":64 // Send the choice on the channel and exit.65 m.choice <- choices[m.cursor]66 return m, tea.Quit6768 case "down", "j":69 m.cursor++70 if m.cursor >= len(choices) {71 m.cursor = 072 }7374 case "up", "k":75 m.cursor--76 if m.cursor < 0 {77 m.cursor = len(choices) - 178 }79 }8081 }8283 return m, nil84}8586func view(mdl tea.Model) string {87 m, _ := mdl.(model)8889 s := strings.Builder{}90 s.WriteString("What kind of Bubble Tea would you like to order?\n\n")9192 for i := 0; i < len(choices); i++ {93 if m.cursor == i {94 s.WriteString("(•) ")95 } else {96 s.WriteString("( ) ")97 }98 s.WriteString(choices[i])99 s.WriteString("\n")100 }101 s.WriteString("\n(press q to quit)\n")102103 return s.String()104}