bubbletea/examples/textinput/main.go

92 lines
1.8 KiB
Go
Raw Normal View History

2020-01-17 22:21:51 -05:00
package main
// A simple program demonstrating the text input component from the Bubbles
// component library.
2020-01-17 22:21:51 -05:00
import (
"errors"
2020-01-17 22:21:51 -05:00
"fmt"
"log"
input "github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
2020-01-17 22:21:51 -05:00
)
type Model struct {
2020-04-22 11:00:30 -04:00
textInput input.Model
err error
2020-01-17 22:21:51 -05:00
}
type tickMsg struct{}
2020-04-22 11:00:30 -04:00
type errMsg error
2020-01-17 22:21:51 -05:00
func main() {
p := tea.NewProgram(
initialize,
2020-01-17 22:21:51 -05:00
update,
view,
)
if err := p.Start(); err != nil {
log.Fatal(err)
}
}
func initialize() (tea.Model, tea.Cmd) {
inputModel := input.NewModel()
2020-02-01 22:28:31 -05:00
inputModel.Placeholder = "Pikachu"
inputModel.Focus()
2020-02-01 22:28:31 -05:00
return Model{
2020-04-22 11:00:30 -04:00
textInput: inputModel,
err: nil,
}, input.Blink(inputModel)
}
func update(msg tea.Msg, model tea.Model) (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.
2020-04-22 11:00:30 -04:00
return Model{
err: errors.New("could not perform assertion on model in update"),
}, nil
}
2020-01-17 22:21:51 -05:00
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyCtrlC:
2020-01-17 22:21:51 -05:00
fallthrough
case tea.KeyEsc:
fallthrough
case tea.KeyEnter:
return m, tea.Quit
2020-01-17 22:21:51 -05:00
}
// We handle errors just like any other message
2020-04-22 11:00:30 -04:00
case errMsg:
m.err = msg
return m, nil
2020-01-17 22:21:51 -05:00
}
2020-04-22 11:00:30 -04:00
m.textInput, cmd = input.Update(msg, m.textInput)
2020-01-17 22:21:51 -05:00
return m, cmd
}
func view(model tea.Model) string {
m, ok := model.(Model)
if !ok {
return "Oh no: could not perform assertion on model."
2020-04-22 11:00:30 -04:00
} else if m.err != nil {
return fmt.Sprintf("Uh oh: %s", m.err)
2020-01-17 23:27:54 -05:00
}
return fmt.Sprintf(
"Whats your favorite Pokémon?\n\n%s\n\n%s",
2020-04-22 11:00:30 -04:00
input.View(m.textInput),
"(esc to quit)",
) + "\n"
2020-01-17 22:21:51 -05:00
}