Make Spinner more idomatic Bubble Tea (per v0.12.x)

This commit is contained in:
Christian Rocha 2020-10-27 16:36:29 -04:00 committed by Christian Rocha
parent 0fd072ddcc
commit 9e1e435bba
2 changed files with 23 additions and 15 deletions

View File

@ -19,7 +19,7 @@ const (
Dots
)
// Model is the Tea model for this user interface.
// Model is the Bubble Tea model for this user interface.
type Model struct {
Type Type
Page int

View File

@ -7,9 +7,7 @@ import (
"github.com/muesli/termenv"
)
const (
defaultFPS = time.Second / 10
)
const defaultFPS = time.Second / 10
// Spinner is a set of frames used in animating the spinner.
type Spinner = []string
@ -150,33 +148,39 @@ type TickMsg struct {
Time time.Time
}
type startTick struct{}
// Update is the Tea update function. This will advance the spinner one frame
// every time it's called, regardless the message passed, so be sure the logic
// is setup so as not to call this Update needlessly.
func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
if _, ok := msg.(TickMsg); ok {
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
switch msg.(type) {
case startTick:
return m, m.tick()
case TickMsg:
m.frame++
if m.frame >= len(m.Frames) {
m.frame = 0
}
return m, Tick(m)
return m, m.tick()
default:
return m, nil
}
return m, nil
}
// View renders the model's view.
func View(model Model) string {
if model.frame >= len(model.Frames) {
func (m Model) View() string {
if m.frame >= len(m.Frames) {
return "error"
}
frame := model.Frames[model.frame]
frame := m.Frames[m.frame]
if model.ForegroundColor != "" || model.BackgroundColor != "" {
if m.ForegroundColor != "" || m.BackgroundColor != "" {
return termenv.
String(frame).
Foreground(color(model.ForegroundColor)).
Background(color(model.BackgroundColor)).
Foreground(color(m.ForegroundColor)).
Background(color(m.BackgroundColor)).
String()
}
@ -184,7 +188,11 @@ func View(model Model) string {
}
// Tick is the command used to advance the spinner one frame.
func Tick(m Model) tea.Cmd {
func Tick() tea.Msg {
return startTick{}
}
func (m Model) tick() tea.Cmd {
return tea.Tick(m.FPS, func(t time.Time) tea.Msg {
return TickMsg{
Time: t,