Skip to content
Myr

main.go

This file

Path

examples/textinput/main.go

80 lines · 1.4 KiB · Go

Last changed by

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

History of this file

Take it

1package main23// A simple program demonstrating the text input component from the Bubbles4// component library.56import (7	"log"89	"charm.land/bubbles/v2/textinput"10	tea "charm.land/bubbletea/v2"11	"charm.land/lipgloss/v2"12)1314func main() {15	p := tea.NewProgram(initialModel())16	if _, err := p.Run(); err != nil {17		log.Fatal(err)18	}19}2021type (22	errMsg error23)2425type model struct {26	textInput textinput.Model27	err       error28	quitting  bool29}3031func initialModel() model {32	ti := textinput.New()33	ti.Placeholder = "Pikachu"34	ti.SetVirtualCursor(false)35	ti.Focus()36	ti.CharLimit = 15637	ti.SetWidth(20)3839	return model{textInput: ti}40}4142func (m model) Init() tea.Cmd {43	return textinput.Blink44}4546func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {47	var cmd tea.Cmd4849	switch msg := msg.(type) {50	case tea.KeyPressMsg:51		switch msg.String() {52		case "enter", "ctrl+c", "esc":53			m.quitting = true54			return m, tea.Quit55		}56	}5758	m.textInput, cmd = m.textInput.Update(msg)59	return m, cmd60}6162func (m model) View() tea.View {63	var c *tea.Cursor64	if !m.textInput.VirtualCursor() {65		c = m.textInput.Cursor()66		c.Y += lipgloss.Height(m.headerView())67	}6869	str := lipgloss.JoinVertical(lipgloss.Top, m.headerView(), m.textInput.View(), m.footerView())70	if m.quitting {71		str += "\n"72	}7374	v := tea.NewView(str)75	v.Cursor = c76	return v77}7879func (m model) headerView() string { return "What’s your favorite Pokémon?\n" }80func (m model) footerView() string { return "\n(esc to quit)" }