Fix and improve spinner example

This commit is contained in:
Christian Rocha 2020-05-04 18:33:17 -04:00
parent 39ec5b5233
commit dada718393
No known key found for this signature in database
GPG Key ID: D6CC7A16E5878018
1 changed files with 13 additions and 2 deletions

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"errors"
"fmt" "fmt"
"log" "log"
@ -15,8 +16,11 @@ var (
type Model struct { type Model struct {
spinner spinner.Model spinner spinner.Model
err error
} }
type errMsg error
func main() { func main() {
p := tea.NewProgram(initialize, update, view, subscriptions) p := tea.NewProgram(initialize, update, view, subscriptions)
if err := p.Start(); err != nil { if err := p.Start(); err != nil {
@ -53,6 +57,10 @@ func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
return m, nil return m, nil
} }
case errMsg:
m.err = msg
return m, nil
default: default:
m.spinner, _ = spinner.Update(msg, m.spinner) m.spinner, _ = spinner.Update(msg, m.spinner)
return m, nil return m, nil
@ -63,7 +71,10 @@ func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
func view(model tea.Model) string { func view(model tea.Model) string {
m, ok := model.(Model) m, ok := model.(Model)
if !ok { if !ok {
return tea.ModelAssertionErr.String() return "could not perform assertion on model in view"
}
if m.err != nil {
return m.err.Error()
} }
s := termenv. s := termenv.
String(spinner.View(m.spinner)). String(spinner.View(m.spinner)).
@ -77,7 +88,7 @@ func subscriptions(_ tea.Model) tea.Subs {
"tick": func(model tea.Model) tea.Msg { "tick": func(model tea.Model) tea.Msg {
m, ok := model.(Model) m, ok := model.(Model)
if !ok { if !ok {
return tea.ModelAssertionErr return errMsg(errors.New("could perform assertion on model in subscription"))
} }
return spinner.Sub(m.spinner) return spinner.Sub(m.spinner)
}, },