main.go
This file
Path
examples/simple/main.go
78 lines · 1.9 KiB · Go
Last changed by
Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
History of this fileTake it
1package main23// A simple program that counts down from 5 and then exits.45import (6 "fmt"7 "log"8 "os"9 "time"1011 tea "charm.land/bubbletea/v2"12)1314func main() {15 // Log to a file. Useful in debugging since you can't really log to stdout.16 // Not required.17 logfilePath := os.Getenv("BUBBLETEA_LOG")18 if logfilePath != "" {19 if _, err := tea.LogToFile(logfilePath, "simple"); err != nil {20 log.Fatal(err)21 }22 }2324 // Initialize our program25 p := tea.NewProgram(model(5))26 if _, err := p.Run(); err != nil {27 log.Fatal(err)28 }29}3031// A model can be more or less any type of data. It holds all the data for a32// program, so often it's a struct. For this simple example, however, all33// we'll need is a simple integer.34type model int3536// Init optionally returns an initial command we should run. In this case we37// want to start the timer.38func (m model) Init() tea.Cmd {39 return tick40}4142// Update is called when messages are received. The idea is that you inspect the43// message and send back an updated model accordingly. You can also return44// a command, which is a function that performs I/O and returns a message.45func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {46 switch msg := msg.(type) {47 case tea.KeyPressMsg:48 switch msg.String() {49 case "ctrl+c", "q":50 return m, tea.Quit51 case "ctrl+z":52 return m, tea.Suspend53 }5455 case tickMsg:56 m--57 if m <= 0 {58 return m, tea.Quit59 }60 return m, tick61 }62 return m, nil63}6465// View returns a string based on data in the model. That string which will be66// rendered to the terminal.67func (m model) View() tea.View {68 return tea.NewView(fmt.Sprintf("Hi. This program will exit in %d seconds.\n\nTo quit sooner press ctrl-c, or press ctrl-z to suspend...\n", m))69}7071// Messages are events that we respond to in our Update function. This72// particular one indicates that the timer has ticked.73type tickMsg time.Time7475func tick() tea.Msg {76 time.Sleep(time.Second)77 return tickMsg{}78}