bubbletea/example/main.go

71 lines
1017 B
Go
Raw Normal View History

2020-01-10 16:02:04 -05:00
package main
import (
"fmt"
"tea"
)
type Model int
func main() {
p := tea.NewProgram(0, update, view)
p.Start()
}
func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
m, _ := model.(Model)
switch msg := msg.(type) {
case tea.KeyPressMsg:
switch msg {
case "j":
2020-01-10 23:12:25 -05:00
fallthrough
case "down":
2020-01-10 16:02:04 -05:00
m += 1
if m > 3 {
m = 3
}
case "k":
2020-01-10 23:12:25 -05:00
fallthrough
case "up":
2020-01-10 16:02:04 -05:00
m -= 1
if m < 0 {
m = 0
}
case "q":
return m, tea.Quit
}
}
return m, nil
}
func view(model tea.Model) string {
m, _ := model.(Model)
choices := fmt.Sprintf(
"%s\n%s\n%s\n%s",
checkbox("Plant carrots", m == 0),
checkbox("Go to the market", m == 1),
checkbox("Read something", m == 2),
checkbox("See friends", m == 3),
)
return fmt.Sprintf(
2020-01-10 23:12:25 -05:00
"What to do today?\n\n%s\n\n(press j/k or up/down to select, q to quit)",
2020-01-10 16:02:04 -05:00
choices,
)
}
func checkbox(label string, checked bool) string {
check := " "
if checked {
check = "x"
}
return fmt.Sprintf("[%s] %s", check, label)
}