bubbletea/examples/textinput/main.go

75 lines
1.2 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 (
"fmt"
"log"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
2020-01-17 22:21:51 -05:00
)
func main() {
p := tea.NewProgram(initialModel())
2020-01-17 22:21:51 -05:00
if err := p.Start(); err != nil {
log.Fatal(err)
}
}
type (
errMsg error
)
type model struct {
textInput textinput.Model
err error
}
func initialModel() model {
ti := textinput.New()
ti.Placeholder = "Pikachu"
ti.Focus()
ti.CharLimit = 156
ti.Width = 20
2020-02-01 22:28:31 -05:00
return model{
textInput: ti,
2020-04-22 11:00:30 -04:00
err: nil,
}
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
2020-01-17 22:21:51 -05:00
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
2021-05-01 09:28:58 -04:00
case tea.KeyEnter, tea.KeyCtrlC, tea.KeyEsc:
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
}
m.textInput, cmd = m.textInput.Update(msg)
2020-01-17 22:21:51 -05:00
return m, cmd
}
func (m model) View() string {
return fmt.Sprintf(
"Whats your favorite Pokémon?\n\n%s\n\n%s",
m.textInput.View(),
"(esc to quit)",
) + "\n"
2020-01-17 22:21:51 -05:00
}