bubbletea/examples/textinput/main.go
2025-11-04 15:04:06 -05:00

80 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
// A simple program demonstrating the text input component from the Bubbles
// component library.
import (
"log"
"charm.land/bubbles/v2/textinput"
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
)
func main() {
p := tea.NewProgram(initialModel())
if _, err := p.Run(); err != nil {
log.Fatal(err)
}
}
type (
errMsg error
)
type model struct {
textInput textinput.Model
err error
quitting bool
}
func initialModel() model {
ti := textinput.New()
ti.Placeholder = "Pikachu"
ti.SetVirtualCursor(false)
ti.Focus()
ti.CharLimit = 156
ti.SetWidth(20)
return model{textInput: ti}
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyPressMsg:
switch msg.String() {
case "enter", "ctrl+c", "esc":
m.quitting = true
return m, tea.Quit
}
}
m.textInput, cmd = m.textInput.Update(msg)
return m, cmd
}
func (m model) View() tea.View {
var c *tea.Cursor
if !m.textInput.VirtualCursor() {
c = m.textInput.Cursor()
c.Y += lipgloss.Height(m.headerView())
}
str := lipgloss.JoinVertical(lipgloss.Top, m.headerView(), m.textInput.View(), m.footerView())
if m.quitting {
str += "\n"
}
v := tea.NewView(str)
v.Cursor = c
return v
}
func (m model) headerView() string { return "What’s your favorite Pokémon?\n" }
func (m model) footerView() string { return "\n(esc to quit)" }