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
Provenance
- Commit
0886ee2- Tree
c9a28b2- Author
Christian Rocha <christian@rocha.is>- Committer
Christian Rocha <christian@rocha.is>- Parent
b957c32
2 files changed+169 added−8 removed
added:examples/send-msg/main.go+141 added
1+package main2+3+// A simple example that shows how to send messages to a Bubble Tea program4+// from outside the program using Program.Send(Msg).5+6+import (7+ "fmt"8+ "math/rand"9+ "os"10+ "strings"11+ "time"12+13+ "github.com/charmbracelet/bubbles/spinner"14+ tea "github.com/charmbracelet/bubbletea"15+ "github.com/charmbracelet/lipgloss"16+)17+18+var (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+)26+27+type resultMsg struct {28+ duration time.Duration29+ food string30+}31+32+func (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+}39+40+type model struct {41+ spinner spinner.Model42+ results []resultMsg43+ quitting bool44+}45+46+func 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+}55+56+func (m model) Init() tea.Cmd {57+ return spinner.Tick58+}59+60+func (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+}76+77+func (m model) View() string {78+ var s string79+80+ if m.quitting {81+ s += "That’s all for today!"82+ } else {83+ s += m.spinner.View() + " Eating food..."84+ }85+86+ s += "\n\n"87+88+ for _, res := range m.results {89+ s += res.String() + "\n"90+ }91+92+ if !m.quitting {93+ s += helpStyle.Render("Press any key to exit")94+ }95+96+ if m.quitting {97+ s += "\n"98+ }99+100+ return appStyle.Render(s)101+}102+103+func main() {104+ rand.Seed(time.Now().UTC().UnixNano())105+106+ done := make(chan struct{})107+108+ 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+ }()116+117+ // Simulate activity118+ go func() {119+ for {120+ pause := time.Duration(rand.Int63n(899)+100) * time.Millisecond121+ time.Sleep(pause)122+123+ // Send the Bubble Tea program a message from outside the program.124+ p.Send(resultMsg{food: randomFood(), duration: pause})125+ }126+ }()127+128+ <-done129+}130+131+func randomEmoji() string {132+ emojis := []rune("🍦🧋🍡🤠👾😭🦊🐯🦆🥨🎏🍔🍒🍥🎮📦🦁🐶🐸🍕🥐🧲🚒🥇🏆🌽")133+ return string(emojis[rand.Intn(len(emojis))])134+}135+136+func 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 lines214 215 mtx *sync.Mutex216 done chan struct{}217 218+ msgs chan Msg219+220 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 bool148 unmodified lines372 mtx: &sync.Mutex{},373 initialModel: model,374 output: os.Stdout,375 input: os.Stdin,374- done: make(chan struct{}),376 CatchPanics: true,377 }378 379 // Apply all options to program5 unmodified lines385 }386 387 // Start initializes the program.388 func (p *Program) Start() error {389+ p.msgs = make(chan Msg)390+ p.done = make(chan struct{})391+392 var (393 cmds = make(chan Cmd)390- msgs = make(chan Msg)394 errs = make(chan error)395 396 // If output is a file (e.g. os.Stdout) then this will be set397 // accordingly. Most of the time you should refer to p.outputIsTTY39 unmodified lines437 438 select {439 case <-ctx.Done():440 case <-sig:438- msgs <- quitMsg{}441+ p.msgs <- quitMsg{}442 }443 }()444 445 if p.CatchPanics {58 unmodified lines504 break505 }506 errs <- err507 }505- msgs <- msg508+ p.msgs <- msg509 }510 }()511 }512 3 unmodified lines516 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 }()522 523 // Listen for window resizes521- go listenForResize(outputAsFile, msgs, errs)524+ go listenForResize(outputAsFile, p.msgs, errs)525 }526 527 // Process commands528 go func() {3 unmodified lines532 return533 case cmd := <-cmds:534 if cmd != nil {535 go func() {533- msgs <- cmd()536+ p.msgs <- cmd()537 }()538 }539 }540 }4 unmodified lines545 select {546 case err := <-errs:547 p.shutdown(false)548 return err546- case msg := <-msgs:549+ case msg := <-p.msgs:550 551 // Handle special internal messages552 switch msg := msg.(type) {553 case quitMsg:41 unmodified lines595 }596 }597 }598 599+// 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.608+func (p *Program) Send(msg Msg) {609+ if p.msgs != nil {610+ p.msgs <- msg611+ }612+}613+614 // shutdown performs operations to free up resources and restore the terminal615 // to its original state.616 func (p *Program) shutdown(kill bool) {617 if kill {1 unmodified line619 } 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