Skip to content
Myr

Msgs can now be sent to Programs with Program.Send(Msg)

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 b957c32 · Browse files · 2 files+169 added−8 removed
This commit

State

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

Diff stats

2 files+169 added−8 removed

  • other:+169 added−8 removed

2 files+169 added−8 removed

added:examples/send-msg/main.go+141 added
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 "github.com/charmbracelet/bubbles/spinner"14 tea "github.com/charmbracelet/bubbletea"15 "github.com/charmbracelet/lipgloss"16)1718var (19 spinnerStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))20 helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241")).Margin(1, 0)21 dotStyle = helpStyle.Copy().UnsetMargins()22 foodStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("36"))23 durationStyle = dotStyle.Copy()24 appStyle = lipgloss.NewStyle().Margin(1, 2, 0, 2)25)2627type resultMsg struct {28 duration time.Duration29 food string30}3132func (r resultMsg) String() string {33 if r.duration == 0 {34 return dotStyle.Render(strings.Repeat(".", 30))35 }36 return fmt.Sprintf("🍔 Ate %s %s", r.food,37 durationStyle.Render(r.duration.String()))38}3940type model struct {41 spinner spinner.Model42 results []resultMsg43 quitting bool44}4546func newModel() model {47 const numLastResults = 548 s := spinner.NewModel()49 s.Style = spinnerStyle50 return model{51 spinner: s,52 results: make([]resultMsg, numLastResults),53 }54}5556func (m model) Init() tea.Cmd {57 return spinner.Tick58}5960func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {61 switch msg := msg.(type) {62 case tea.KeyMsg:63 m.quitting = true64 return m, tea.Quit65 case resultMsg:66 m.results = append(m.results[1:], msg)67 return m, nil68 case spinner.TickMsg:69 var cmd tea.Cmd70 m.spinner, cmd = m.spinner.Update(msg)71 return m, cmd72 default:73 return m, nil74 }75}7677func (m model) View() string {78 var s string7980 if m.quitting {81 s += "That’s all for today!"82 } else {83 s += m.spinner.View() + " Eating food..."84 }8586 s += "\n\n"8788 for _, res := range m.results {89 s += res.String() + "\n"90 }9192 if !m.quitting {93 s += helpStyle.Render("Press any key to exit")94 }9596 if m.quitting {97 s += "\n"98 }99100 return appStyle.Render(s)101}102103func main() {104 rand.Seed(time.Now().UTC().UnixNano())105106 done := make(chan struct{})107108 p := tea.NewProgram(newModel())109 go func() {110 if err := p.Start(); err != nil {111 fmt.Println("Error running program:", err)112 os.Exit(1)113 }114 close(done)115 }()116117 // Simulate activity118 go func() {119 for {120 pause := time.Duration(rand.Int63n(899)+100) * time.Millisecond121 time.Sleep(pause)122123 // Send the Bubble Tea program a message from outside the program.124 p.Send(resultMsg{food: randomFood(), duration: pause})125 }126 }()127128 <-done129}130131func randomEmoji() string {132 emojis := []rune("🍦🧋🍡🤠👾😭🦊🐯🦆🥨🎏🍔🍒🍥🎮📦🦁🐶🐸🍕🥐🧲🚒🥇🏆🌽")133 return string(emojis[rand.Intn(len(emojis))])134}135136func randomFood() string {137 food := []string{"an apple", "a pear", "a gherkin", "a party gherkin",138 "a kohlrabi", "some spaghetti", "tacos", "a currywurst", "some curry",139 "a sandwich", "some peanut butter", "some cashews", "some ramen"}140 return string(food[rand.Intn(len(food))])141}
modified:tea.go+28 added-8 removed
213 unmodified lines
214215 mtx *sync.Mutex216 done chan struct{}217218 msgs chan Msg219220 output io.Writer // where to send output. this will usually be os.Stdout.221 input io.Reader // this will usually be os.Stdin.222 renderer renderer223 altScreenActive bool
148 unmodified lines
372 mtx: &sync.Mutex{},373 initialModel: model,374 output: os.Stdout,375 input: os.Stdin,374 done: make(chan struct{}),376 CatchPanics: true,377 }378379 // Apply all options to program
5 unmodified lines
385}386387// Start initializes the program.388func (p *Program) Start() error {389 p.msgs = make(chan Msg)390 p.done = make(chan struct{})391392 var (393 cmds = make(chan Cmd)390 msgs = make(chan Msg)394 errs = make(chan error)395396 // If output is a file (e.g. os.Stdout) then this will be set397 // accordingly. Most of the time you should refer to p.outputIsTTY
39 unmodified lines
437438 select {439 case <-ctx.Done():440 case <-sig:438 msgs <- quitMsg{}441 p.msgs <- quitMsg{}442 }443 }()444445 if p.CatchPanics {
58 unmodified lines
504 break505 }506 errs <- err507 }505 msgs <- msg508 p.msgs <- msg509 }510 }()511 }512
3 unmodified lines
516 w, h, err := term.GetSize(int(outputAsFile.Fd()))517 if err != nil {518 errs <- err519 }517 msgs <- WindowSizeMsg{w, h}520 p.msgs <- WindowSizeMsg{w, h}521 }()522523 // Listen for window resizes521 go listenForResize(outputAsFile, msgs, errs)524 go listenForResize(outputAsFile, p.msgs, errs)525 }526527 // Process commands528 go func() {
3 unmodified lines
532 return533 case cmd := <-cmds:534 if cmd != nil {535 go func() {533 msgs <- cmd()536 p.msgs <- cmd()537 }()538 }539 }540 }
4 unmodified lines
545 select {546 case err := <-errs:547 p.shutdown(false)548 return err546 case msg := <-msgs:549 case msg := <-p.msgs:550551 // Handle special internal messages552 switch msg := msg.(type) {553 case quitMsg:
41 unmodified lines
595 }596 }597}598599// Send sends a message to the main update function, effectively allowing600// messages to be injected from outside the program for interoperability601// purposes.602//603// If the program is not running this this will be a no-op, so it's safe to604// send messages if the program is unstarted, or has exited.605//606// This method is currently provisional. The method signature may alter607// slightly, or it may be removed in a future version of this package.608func (p *Program) Send(msg Msg) {609 if p.msgs != nil {610 p.msgs <- msg611 }612}613614// shutdown performs operations to free up resources and restore the terminal615// to its original state.616func (p *Program) shutdown(kill bool) {617 if kill {
1 unmodified line
619 } else {620 p.renderer.stop()621 }622 close(p.done)623 close(p.msgs)624 p.msgs = nil625 p.ExitAltScreen()626 p.DisableMouseCellMotion()627 p.DisableMouseAllMotion()628 _ = p.restoreTerminal()
82 unmodified lines