Skip to content
Myr

input.go

This file

Path

input/input.go

102 lines · 2.2 KiB · Go

Last changed by

chore: update to bubbletea v2 (#1112)Drew Smirnoffbefore adoptionf6dd28e

History of this file

Take it

1// Package input provides a shell script interface for the text input bubble.2// https://github.com/charmbracelet/bubbles/tree/master/textinput3//4// It can be used to prompt the user for some input. The text the user entered5// will be sent to stdout.6//7// $ gum input --placeholder "What's your favorite gum?" > answer.text8package input910import (11	"charm.land/bubbles/v2/help"12	"charm.land/bubbles/v2/key"13	"charm.land/bubbles/v2/textinput"14	tea "charm.land/bubbletea/v2"15	"charm.land/lipgloss/v2"16)1718type keymap textinput.KeyMap1920func defaultKeymap() keymap {21	k := textinput.DefaultKeyMap()22	return keymap(k)23}2425// FullHelp implements help.KeyMap.26func (k keymap) FullHelp() [][]key.Binding { return nil }2728// ShortHelp implements help.KeyMap.29func (k keymap) ShortHelp() []key.Binding {30	return []key.Binding{31		key.NewBinding(32			key.WithKeys("enter"),33			key.WithHelp("enter", "submit"),34		),35	}36}3738type model struct {39	autoWidth   bool40	header      string41	padding     []int42	headerStyle lipgloss.Style43	textinput   textinput.Model44	quitting    bool45	submitted   bool46	showHelp    bool47	help        help.Model48	keymap      keymap49}5051func (m model) Init() tea.Cmd { return textinput.Blink }5253func (m model) View() tea.View {54	if m.quitting {55		return tea.NewView("")56	}57	var parts []string58	if m.header != "" {59		parts = append(parts, m.headerStyle.Render(m.header))60	}6162	parts = append(parts, m.textinput.View())63	if m.showHelp {64		parts = append(parts, "", m.help.View(m.keymap))65	}66	v := tea.NewView(lipgloss.NewStyle().67		Padding(m.padding...).68		Render(lipgloss.JoinVertical(69			lipgloss.Top,70			parts...,71		)))72	v.ReportFocus = true73	return v74}7576func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {77	switch msg := msg.(type) {78	case tea.WindowSizeMsg:79		if m.autoWidth {80			m.textinput.SetWidth(msg.Width - 1 -81				lipgloss.Width(m.textinput.Prompt) -82				m.padding[1] - m.padding[3])83		}84	case tea.KeyPressMsg:85		switch msg.String() {86		case "ctrl+c":87			m.quitting = true88			return m, tea.Interrupt89		case "esc":90			m.quitting = true91			return m, tea.Quit92		case "enter":93			m.quitting = true94			m.submitted = true95			return m, tea.Quit96		}97	}9899	var cmd tea.Cmd100	m.textinput, cmd = m.textinput.Update(msg)101	return m, cmd102}