Skip to content
Myr

Document simple example to hopefully explain how things work

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 fac654d · Browse files · 1 file+24 added−10 removed
This commit

State

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

Diff stats

1 file+24 added−10 removed

  • other:+24 added−10 removed

1 file+24 added−10 removed

modified:examples/simple/main.go+24 added-10 removed
8 unmodified lines
910 "github.com/charmbracelet/tea"11)1213// A model can be more or less any type of data. It holds all the data for a14// program, so often it's a struct. For this simple example, however, all15// we'll need is a simple integer.13type model int16type Model int1718// Messages are events that we respond to in our Update function. This19// particular one indicates that the timer has ticked.15type tickMsg struct{}20type TickMsg struct{}2122func main() {18 err := tea.NewProgram(model(5), update, view, []tea.Sub{tick}).Start()19 if err != nil {23 // Initialize our program24 p := tea.NewProgram(Model(5), update, view, []tea.Sub{tick})25 if err := p.Start(); err != nil {26 log.Fatal(err)27 }28}2930// Update is called when messages are recived. The idea is that you inspect31// the message and update the model (or send back a new one) accordingly. You32// can also return a commmand, which is a function that peforms I/O and33// returns a message.24func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {25 m, _ := mdl.(model)34func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {35 m, _ := model.(Model)3637 switch msg.(type) {28 case tickMsg:38 case TickMsg:39 m -= 140 if m <= 0 {41 return m, tea.Quit42 }43 }44 return m, nil45}4647// Views take data from the model and return a string which will be rendered48// to the terminal.37func view(mdl tea.Model) string {38 m, _ := mdl.(model)49func view(model tea.Model) string {50 m, _ := model.(Model)51 return fmt.Sprintf("Hi. This program will exit in %d seconds...", m)52}5354// This is a subscription which we setup in NewProgram(). It waits for one55// second, sends a tick, and then restarts.56func tick(_ tea.Model) tea.Msg {57 time.Sleep(time.Second)44 return tickMsg{}58 return TickMsg{}59}