Update result example to use StartReturningModel

This commit is contained in:
Christian Rocha 2022-01-10 20:51:54 -05:00
parent 3a1b9fbe9f
commit d266bc1616
1 changed files with 9 additions and 15 deletions

View File

@ -2,8 +2,6 @@ package main
// A simple example that shows how to retrieve a value from a Bubble Tea // A simple example that shows how to retrieve a value from a Bubble Tea
// program after the Bubble Tea has exited. // program after the Bubble Tea has exited.
//
// Thanks to Treilik for this one.
import ( import (
"fmt" "fmt"
@ -17,7 +15,7 @@ var choices = []string{"Taro", "Coffee", "Lychee"}
type model struct { type model struct {
cursor int cursor int
choice chan string choice string
} }
func (m model) Init() tea.Cmd { func (m model) Init() tea.Cmd {
@ -29,12 +27,11 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case tea.KeyMsg: case tea.KeyMsg:
switch msg.String() { switch msg.String() {
case "ctrl+c", "q", "esc": case "ctrl+c", "q", "esc":
close(m.choice) // If we're quitting just close the channel.
return m, tea.Quit return m, tea.Quit
case "enter": case "enter":
// Send the choice on the channel and exit. // Send the choice on the channel and exit.
m.choice <- choices[m.cursor] m.choice = choices[m.cursor]
return m, tea.Quit return m, tea.Quit
case "down", "j": case "down", "j":
@ -74,20 +71,17 @@ func (m model) View() string {
} }
func main() { func main() {
// This is where we'll listen for the choice the user makes in the Bubble p := tea.NewProgram(model{})
// Tea program.
result := make(chan string, 1)
// Pass the channel to the initialize function so our Bubble Tea program // StartReturningModel returns the model as a tea.Model.
// can send the final choice along when the time comes. m, err := p.StartReturningModel()
p := tea.NewProgram(model{cursor: 0, choice: result}) if err != nil {
if err := p.Start(); err != nil {
fmt.Println("Oh no:", err) fmt.Println("Oh no:", err)
os.Exit(1) os.Exit(1)
} }
// Print out the final choice. // Assert the final tea.Model to our local model and print the choice.
if r := <-result; r != "" { if m, ok := m.(model); ok && m.choice != "" {
fmt.Printf("\n---\nYou chose %s!\n", r) fmt.Printf("\n---\nYou chose %s!\n", m.choice)
} }
} }