Convert remaining examples to Model interface-based structure

This commit is contained in:
Christian Rocha
2020-10-15 19:48:42 -04:00
parent 7530fb0112
commit 847787e46d
8 changed files with 78 additions and 138 deletions

View File

@@ -4,7 +4,6 @@ package main
// component library.
import (
"errors"
"fmt"
"log"
@@ -12,48 +11,39 @@ import (
tea "github.com/charmbracelet/bubbletea"
)
type Model struct {
textInput input.Model
err error
}
type tickMsg struct{}
type errMsg error
func main() {
p := tea.NewProgram(
initialize,
update,
view,
)
p := tea.NewProgram(initialModel())
if err := p.Start(); err != nil {
log.Fatal(err)
}
}
func initialize() (tea.Model, tea.Cmd) {
type tickMsg struct{}
type errMsg error
type model struct {
textInput input.Model
err error
}
func initialModel() model {
inputModel := input.NewModel()
inputModel.Placeholder = "Pikachu"
inputModel.Focus()
return Model{
return model{
textInput: inputModel,
err: nil,
}, input.Blink(inputModel)
}
}
func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
func (m model) Init() tea.Cmd {
return input.Blink(m.textInput)
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
m, ok := model.(Model)
if !ok {
// When we encounter errors in Update we simply add the error to the
// model so we can handle it in the view. We could also return a command
// that does something else with the error, like logs it via IO.
return Model{
err: errors.New("could not perform assertion on model in update"),
}, nil
}
switch msg := msg.(type) {
case tea.KeyMsg:
@@ -76,13 +66,7 @@ func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
return m, cmd
}
func view(model tea.Model) string {
m, ok := model.(Model)
if !ok {
return "Oh no: could not perform assertion on model."
} else if m.err != nil {
return fmt.Sprintf("Uh oh: %s", m.err)
}
func (m model) View() string {
return fmt.Sprintf(
"Whats your favorite Pokémon?\n\n%s\n\n%s",
input.View(m.textInput),