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
Provenance
Commit
71bd542
Tree
6307038
Author
Christian Rocha <christian@rocha.is>
Committer
Christian Rocha <christian@rocha.is>
Parent
51e97bb
1 file changed+104 added−0 removed
added:examples/result/main.go+104 added
1+package main2+3+// 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.7+8+import (9+ "fmt"10+ "os"11+ "strings"12+13+ tea "github.com/charmbracelet/bubbletea"14+)15+16+var (17+ choices = []string{"Taro", "Coffee", "Lychee"}18+)19+20+type model struct {21+ cursor int22+ choice chan string23+}24+25+func 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)29+30+ // 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+ }36+37+ // Print out the final choice.38+ if r := <-result; r != "" {39+ fmt.Printf("\n---\nYou chose %s!\n", r)40+ }41+}42+43+// 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.46+func 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+}51+52+func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {53+ m, _ := mdl.(model)54+55+ switch msg := msg.(type) {56+ case tea.KeyMsg:57+ switch msg.String() {58+59+ case "ctrl+c", "q":60+ close(m.choice) // If we're quitting just chose the channel.61+ return m, tea.Quit62+63+ case "enter":64+ // Send the choice on the channel and exit.65+ m.choice <- choices[m.cursor]66+ return m, tea.Quit67+68+ case "down", "j":69+ m.cursor++70+ if m.cursor >= len(choices) {71+ m.cursor = 072+ }73+74+ case "up", "k":75+ m.cursor--76+ if m.cursor < 0 {77+ m.cursor = len(choices) - 178+ }79+ }80+81+ }82+83+ return m, nil84+}85+86+func view(mdl tea.Model) string {87+ m, _ := mdl.(model)88+89+ s := strings.Builder{}90+ s.WriteString("What kind of Bubble Tea would you like to order?\n\n")91+92+ 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")102+103+ return s.String()104+}