bubbletea/example/main.go

109 lines
1.7 KiB
Go
Raw Normal View History

2020-01-10 16:02:04 -05:00
package main
import (
"fmt"
"tea"
"time"
2020-01-10 16:02:04 -05:00
)
// Model contains the data for our application.
type Model struct {
Choice int
Ticks int
}
// TickMsg signals that the timer has ticked
type TickMsg struct{}
2020-01-10 16:02:04 -05:00
func main() {
p := tea.NewProgram(
Model{0, 10},
update,
view,
[]tea.Sub{tick},
)
if err := p.Start(); err != nil {
fmt.Println("could not start program:", err)
}
2020-01-10 16:02:04 -05:00
}
// Update. Triggered when new messages arrive.
2020-01-10 16:02:04 -05:00
func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
m, _ := model.(Model)
switch msg := msg.(type) {
2020-01-10 16:02:04 -05:00
case tea.KeyPressMsg:
switch msg {
case "j":
2020-01-10 23:12:25 -05:00
fallthrough
case "down":
m.Choice += 1
if m.Choice > 3 {
m.Choice = 3
2020-01-10 16:02:04 -05:00
}
case "k":
2020-01-10 23:12:25 -05:00
fallthrough
case "up":
m.Choice -= 1
if m.Choice < 0 {
m.Choice = 0
2020-01-10 16:02:04 -05:00
}
case "q":
2020-01-10 23:46:46 -05:00
fallthrough
case "esc":
2020-01-11 11:15:01 -05:00
fallthrough
case "ctrl+c":
2020-01-10 16:02:04 -05:00
return m, tea.Quit
}
case TickMsg:
if m.Ticks == 0 {
return m, tea.Quit
}
m.Ticks -= 1
2020-01-10 16:02:04 -05:00
}
return m, nil
}
// Subscription
func tick(_ tea.Model) tea.Msg {
time.Sleep(time.Second)
return TickMsg{}
}
// View template
const tpl = `What to do today?
%s
Program quits in %d seconds.
(press j/k or up/down to select, q or esc to quit)`
// View function. Called after an Update().
2020-01-10 16:02:04 -05:00
func view(model tea.Model) string {
m, _ := model.(Model)
c := m.Choice
2020-01-10 16:02:04 -05:00
choices := fmt.Sprintf(
"%s\n%s\n%s\n%s",
checkbox("Plant carrots", c == 0),
checkbox("Go to the market", c == 1),
checkbox("Read something", c == 2),
checkbox("See friends", c == 3),
2020-01-10 16:02:04 -05:00
)
return fmt.Sprintf(tpl, choices, m.Ticks)
2020-01-10 16:02:04 -05:00
}
// Checkbox widget
2020-01-10 16:02:04 -05:00
func checkbox(label string, checked bool) string {
check := " "
if checked {
check = "x"
}
return fmt.Sprintf("[%s] %s", check, label)
}