2020-01-15 16:44:11 -05:00
|
|
|
package main
|
|
|
|
|
|
|
|
// A simple program that counts down from 5 and then exits.
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"time"
|
2020-01-18 11:15:55 -05:00
|
|
|
|
2020-05-12 16:39:08 -04:00
|
|
|
"github.com/charmbracelet/boba"
|
2020-01-15 16:44:11 -05:00
|
|
|
)
|
|
|
|
|
2020-01-18 11:42:19 -05:00
|
|
|
// A model can be more or less any type of data. It holds all the data for a
|
|
|
|
// program, so often it's a struct. For this simple example, however, all
|
|
|
|
// we'll need is a simple integer.
|
2020-05-12 17:56:30 -04:00
|
|
|
type model int
|
2020-01-15 16:44:11 -05:00
|
|
|
|
2020-01-18 11:42:19 -05:00
|
|
|
// Messages are events that we respond to in our Update function. This
|
|
|
|
// particular one indicates that the timer has ticked.
|
2020-05-05 14:26:06 -04:00
|
|
|
type tickMsg time.Time
|
2020-01-15 16:44:11 -05:00
|
|
|
|
|
|
|
func main() {
|
2020-01-18 11:42:19 -05:00
|
|
|
// Initialize our program
|
2020-05-12 17:56:30 -04:00
|
|
|
p := boba.NewProgram(initialize, update, view)
|
2020-01-18 11:42:19 -05:00
|
|
|
if err := p.Start(); err != nil {
|
2020-01-15 16:44:11 -05:00
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-12 16:39:08 -04:00
|
|
|
func initialize() (boba.Model, boba.Cmd) {
|
2020-05-12 17:56:30 -04:00
|
|
|
return model(5), tick
|
2020-01-18 22:18:19 -05:00
|
|
|
}
|
|
|
|
|
2020-01-18 11:42:19 -05:00
|
|
|
// Update is called when messages are recived. The idea is that you inspect
|
|
|
|
// the message and update the model (or send back a new one) accordingly. You
|
|
|
|
// can also return a commmand, which is a function that peforms I/O and
|
|
|
|
// returns a message.
|
2020-05-12 17:56:30 -04:00
|
|
|
func update(msg boba.Msg, mdl boba.Model) (boba.Model, boba.Cmd) {
|
|
|
|
m, _ := mdl.(model)
|
2020-01-15 16:44:11 -05:00
|
|
|
|
|
|
|
switch msg.(type) {
|
2020-05-12 16:39:08 -04:00
|
|
|
case boba.KeyMsg:
|
|
|
|
return m, boba.Quit
|
2020-05-05 14:26:06 -04:00
|
|
|
case tickMsg:
|
2020-01-15 16:44:11 -05:00
|
|
|
m -= 1
|
|
|
|
if m <= 0 {
|
2020-05-12 16:39:08 -04:00
|
|
|
return m, boba.Quit
|
2020-01-15 16:44:11 -05:00
|
|
|
}
|
2020-05-12 17:56:30 -04:00
|
|
|
return m, tick
|
2020-01-15 16:44:11 -05:00
|
|
|
}
|
|
|
|
return m, nil
|
|
|
|
}
|
|
|
|
|
2020-01-18 11:42:19 -05:00
|
|
|
// Views take data from the model and return a string which will be rendered
|
|
|
|
// to the terminal.
|
2020-05-12 17:56:30 -04:00
|
|
|
func view(mdl boba.Model) string {
|
|
|
|
m, _ := mdl.(model)
|
2020-05-12 17:05:16 -04:00
|
|
|
return fmt.Sprintf("Hi. This program will exit in %d seconds. To quit sooner press any key.\n", m)
|
2020-01-15 16:44:11 -05:00
|
|
|
}
|
|
|
|
|
2020-05-12 17:56:30 -04:00
|
|
|
func tick() boba.Msg {
|
|
|
|
time.Sleep(time.Second)
|
|
|
|
return tickMsg{}
|
2020-01-15 16:44:11 -05:00
|
|
|
}
|