Skip to content
Myr

Update simple example to use new Model interface-based structure

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 26899c7 · Browse files · 1 file+15 added−18 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+15 added−18 removed

  • other:+15 added−18 removed

1 file+15 added−18 removed

modified:examples/simple/main.go+15 added-18 removed
9 unmodified lines
1011 tea "github.com/charmbracelet/bubbletea"12)1314// A model can be more or less any type of data. It holds all the data for a15// program, so often it's a struct. For this simple example, however, all16// we'll need is a simple integer.17type model int1819// Messages are events that we respond to in our Update function. This20// particular one indicates that the timer has ticked.21type tickMsg time.Time2214func main() {15 // Log to a file. Useful in debugging. Not required.25 logfilePath := os.Getenv("TEA_LOG")16 logfilePath := os.Getenv("BUBBLETEA_LOG")17 if logfilePath != "" {18 if _, err := tea.LogToFile(logfilePath, "simple"); err != nil {19 log.Fatal(err)20 }21 }2223 // Initialize our program33 p := tea.NewProgram(initialize, update, view)24 p := tea.NewProgram(model(5))25 if err := p.Start(); err != nil {26 log.Fatal(err)27 }28}2939func initialize() (tea.Model, tea.Cmd) {40 return model(5), tick30// Messages are events that we respond to in our Update function. This31// particular one indicates that the timer has ticked.32type tickMsg time.Time3334// A model can be more or less any type of data. It holds all the data for a35// program, so often it's a struct. For this simple example, however, all36// we'll need is a simple integer.37type model int3839func (m model) Init() tea.Cmd {40 return tick41}4243// Update is called when messages are recived. The idea is that you inspect44// the message and update the model (or send back a new one) accordingly. You45// can also return a commmand, which is a function that peforms I/O and46// returns a message.47func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {48 m, _ := mdl.(model)4947func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {48 switch msg.(type) {49 case tea.KeyMsg:50 return m, tea.Quit51 case tickMsg:
7 unmodified lines
59}6061// Views take data from the model and return a string which will be rendered62// to the terminal.65func view(mdl tea.Model) string {66 m, _ := mdl.(model)63func (m model) View() string {64 return fmt.Sprintf("Hi. This program will exit in %d seconds. To quit sooner press any key.\n", m)65}6667func tick() tea.Msg {
3 unmodified lines