Skip to content
Myr

main.go

This file

Path

examples/send-msg/main.go

133 lines · 2.7 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 send messages to a Bubble Tea program4// from outside the program using Program.Send(Msg).56import (7	"fmt"8	"math/rand"9	"os"10	"strings"11	"time"1213	"charm.land/bubbles/v2/spinner"14	tea "charm.land/bubbletea/v2"15	"charm.land/lipgloss/v2"16)1718var (19	spinnerStyle  = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))20	helpStyle     = lipgloss.NewStyle().Foreground(lipgloss.Color("241")).Margin(1, 0)21	dotStyle      = helpStyle.UnsetMargins()22	durationStyle = dotStyle23	appStyle      = lipgloss.NewStyle().Margin(1, 2, 0, 2)24)2526type resultMsg struct {27	duration time.Duration28	food     string29}3031func (r resultMsg) String() string {32	if r.duration == 0 {33		return dotStyle.Render(strings.Repeat(".", 30))34	}35	return fmt.Sprintf("🍔 Ate %s %s", r.food,36		durationStyle.Render(r.duration.String()))37}3839type model struct {40	spinner  spinner.Model41	results  []resultMsg42	quitting bool43}4445func newModel() model {46	const numLastResults = 547	s := spinner.New()48	s.Style = spinnerStyle49	return model{50		spinner: s,51		results: make([]resultMsg, numLastResults),52	}53}5455func (m model) Init() tea.Cmd {56	return m.spinner.Tick57}5859func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {60	switch msg := msg.(type) {61	case tea.KeyPressMsg:62		m.quitting = true63		return m, tea.Quit64	case resultMsg:65		m.results = append(m.results[1:], msg)66		return m, nil67	case spinner.TickMsg:68		var cmd tea.Cmd69		m.spinner, cmd = m.spinner.Update(msg)70		return m, cmd71	default:72		return m, nil73	}74}7576func (m model) View() tea.View {77	var b strings.Builder7879	if m.quitting {80		b.WriteString("That's all for today!")81	} else {82		b.WriteString(m.spinner.View())83		b.WriteString(" Eating food...")84	}8586	b.WriteString("\n\n")8788	for _, res := range m.results {89		b.WriteString(res.String())90		b.WriteString("\n")91	}9293	if !m.quitting {94		b.WriteString(helpStyle.Render("Press any key to exit"))95	}9697	if m.quitting {98		b.WriteString("\n")99	}100101	return tea.NewView(appStyle.Render(b.String()))102}103104func main() {105	p := tea.NewProgram(newModel())106107	// Simulate activity108	go func() {109		for {110			pause := time.Duration(rand.Int63n(899)+100) * time.Millisecond // nolint:gosec111			time.Sleep(pause)112113			// Send the Bubble Tea program a message from outside the114			// tea.Program. This will block until it is ready to receive115			// messages.116			p.Send(resultMsg{food: randomFood(), duration: pause})117		}118	}()119120	if _, err := p.Run(); err != nil {121		fmt.Println("Error running program:", err)122		os.Exit(1)123	}124}125126func randomFood() string {127	food := []string{128		"an apple", "a pear", "a gherkin", "a party gherkin",129		"a kohlrabi", "some spaghetti", "tacos", "a currywurst", "some curry",130		"a sandwich", "some peanut butter", "some cashews", "some ramen",131	}132	return food[rand.Intn(len(food))] // nolint:gosec133}