Skip to content
Myr

main.go

This file

Path

examples/result/main.go

86 lines · 1.5 KiB · Go

Last changed by

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

History of this file

Take it

1package main23// A simple example that shows how to retrieve a value from a Bubble Tea4// program after the Bubble Tea has exited.56import (7	"fmt"8	"os"9	"strings"1011	tea "charm.land/bubbletea/v2"12)1314var choices = []string{"Taro", "Coffee", "Lychee"}1516type model struct {17	cursor int18	choice string19}2021func (m model) Init() tea.Cmd {22	return nil23}2425func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {26	switch msg := msg.(type) {27	case tea.KeyPressMsg:28		switch msg.String() {29		case "ctrl+c", "q", "esc":30			return m, tea.Quit3132		case "enter":33			// Send the choice on the channel and exit.34			m.choice = choices[m.cursor]35			return m, tea.Quit3637		case "down", "j":38			m.cursor++39			if m.cursor >= len(choices) {40				m.cursor = 041			}4243		case "up", "k":44			m.cursor--45			if m.cursor < 0 {46				m.cursor = len(choices) - 147			}48		}49	}5051	return m, nil52}5354func (m model) View() tea.View {55	s := strings.Builder{}56	s.WriteString("What kind of Bubble Tea would you like to order?\n\n")5758	for i := range choices {59		if m.cursor == i {60			s.WriteString("(•) ")61		} else {62			s.WriteString("( ) ")63		}64		s.WriteString(choices[i])65		s.WriteString("\n")66	}67	s.WriteString("\n(press q to quit)\n")6869	return tea.NewView(s.String())70}7172func main() {73	p := tea.NewProgram(model{})7475	// Run returns the model as a tea.Model.76	m, err := p.Run()77	if err != nil {78		fmt.Println("Oh no:", err)79		os.Exit(1)80	}8182	// Assert the final tea.Model to our local model and print the choice.83	if m, ok := m.(model); ok && m.choice != "" {84		fmt.Printf("\n---\nYou chose %s!\n", m.choice)85	}86}