textinput

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 8, 2023 License: MIT Imports: 12 Imported by: 41

Documentation

Overview

Package textinput implements prompt for a string input that can also be used for secret strings such as passwords. It also offers customizable appreance as well as optional support for input validation and a customizable key map.

Index

Constants

View Source
const (
	// DefaultTemplate defines the default appearance of the text input and can
	// be copied as a starting point for a custom template.
	DefaultTemplate = `` /* 159-byte string literal not displayed */

	// DefaultResultTemplate defines the default appearance with which the
	// finale result of the prompt is presented.
	DefaultResultTemplate = `
	{{- print .Prompt " " (Foreground "32"  (Mask .FinalValue)) "\n" -}}
	`

	// DefaultMask specified the character with which the input is masked by
	// default if Hidden is true.
	DefaultMask = '●'
)

Variables

View Source
var ErrInputValidation = fmt.Errorf("validation error")

ErrInputValidation is a generic input validation error. For more detailed diagnosis, feel free to return any custom error instead.

Functions

func AutoCompleteFromSlice added in v0.7.0

func AutoCompleteFromSlice(choices []string) func(string) []string

AutoCompleteFromSlice creates a case-insensitive auto-complete function from a slice of choices.

func AutoCompleteFromSliceWithDefault added in v0.7.0

func AutoCompleteFromSliceWithDefault(
	choices []string, defaultValue string,
) func(string) []string

AutoCompleteFromSliceWithDefault creates a case-insensitive auto-complete function from a slice of choices with a default completion value that is inserted if the function is called on an empty input.

func CaseSensitiveAutoCompleteFromSlice added in v0.7.0

func CaseSensitiveAutoCompleteFromSlice(choices []string) func(string) []string

CaseSensitiveAutoCompleteFromSlice creates a case-sensitive auto-complete function from a slice of choices.

func CaseSensitiveAutoCompleteFromSliceWithDefault added in v0.7.0

func CaseSensitiveAutoCompleteFromSliceWithDefault(
	choices []string, defaultValue string,
) func(string) []string

CaseSensitiveAutoCompleteFromSliceWithDefault creates a case-sensitive auto-complete function from a slice of choices with a default completion value that is inserted if the function is called on an empty input.

func ValidateNotEmpty added in v0.7.0

func ValidateNotEmpty(s string) error

ValidateNotEmpty is a validation function that ensures that the input is not empty.

Types

type KeyMap

type KeyMap struct {
	MoveBackward           []string
	MoveForward            []string
	JumpToBeginning        []string
	JumpToEnd              []string
	DeleteBeforeCursor     []string
	DeleteWordBeforeCursor []string
	DeleteUnderCursor      []string
	DeleteAllAfterCursor   []string
	DeleteAllBeforeCursor  []string
	AutoComplete           []string
	Paste                  []string
	Clear                  []string
	Reset                  []string
	Submit                 []string
	Abort                  []string
}

KeyMap defines the keys that trigger certain actions.

func NewDefaultKeyMap

func NewDefaultKeyMap() *KeyMap

NewDefaultKeyMap returns a KeyMap with sensible default key mappings that can also be used as a starting point for customization.

type Model

type Model struct {
	*TextInput

	// Err holds errors that may occur during the execution of
	// the textinput.
	Err error

	// MaxWidth limits the width of the view using the TextInput's WrapMode.
	MaxWidth int
	// contains filtered or unexported fields
}

Model implements the bubbletea.Model for a text input.

func NewModel

func NewModel(textInput *TextInput) *Model

NewModel returns a new model based on the provided text input.

func (*Model) Init

func (m *Model) Init() tea.Cmd

Init initializes the text input model.

func (*Model) Update

func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update updates the model based on the received message.

func (*Model) Value

func (m *Model) Value() (string, error)

Value returns the current value and error.

func (*Model) View

func (m *Model) View() string

View renders the text input.

type TextInput

type TextInput struct {
	// Prompt holds the prompt text or question that is printed above the
	// choices in the default template (if not empty).
	Prompt string

	// Placeholder holds the text that is displayed in the input field when the
	// input data is empty, e.g. when no text was entered yet.
	Placeholder string

	// InitialValue is similar to Placeholder, however, the actual input data is
	// set to InitialValue such that as if it was entered by the user. This can
	// be used to provide an editable default value.
	InitialValue string

	// Validate is a function that validates whether the current input data is
	// valid. If it is not, the data cannot be submitted. By default, Validate
	// ensures that the input data is not empty. If Validate is set to nil, no
	// validation is performed.
	Validate func(string) error

	// AutoComplete is a function that suggests multiple candidates for
	// auto-completion based on a given input. If it returns only a single
	// candidate, this candidate is auto-completed. If it returns multiple
	// candidates, these candidates may be displayed in custom templates using
	// the variables AutoCompleteTriggered, AutoCompleteIndecisive as well as
	// the function AutoCompleteSuggestions. If AutoComplete is nil, no
	// auto-completion is performed.
	AutoComplete func(string) []string

	// Hidden specified whether or not the input data is considered secret and
	// should be masked. This is useful for password prompts.
	Hidden bool

	// HideMask specified the character with which the input data should be
	// masked when Hidden is set to true.
	HideMask rune

	// CharLimit is the maximum amount of characters this input element will
	// accept. If 0 or less, there's no limit.
	CharLimit int

	// InputWidth is the maximum number of characters that can be displayed at
	// once. It essentially treats the text field like a horizontally scrolling
	// viewport. If 0 or less this setting is ignored.
	InputWidth int

	// Template holds the display template. A custom template can be used to
	// completely customize the appearance of the text input. If empty,
	// the DefaultTemplate is used. The following variables and functions are
	// available:
	//
	//  * Prompt string: The configured prompt.
	//  * InitialValue string: The configured initial value of the input.
	//  * Placeholder string: The configured placeholder of the input.
	//  * Input string: The actual input field.
	//  * ValidationError error: The error value returned by Validate.
	//    to the configured Validate function.
	//  * TerminalWidth int: The width of the terminal.
	//  * promptkit.UtilFuncMap: Handy helper functions.
	//  * termenv TemplateFuncs (see https://github.com/muesli/termenv).
	//  * The functions specified in ExtendedTemplateFuncs.
	Template string

	// ResultTemplate is rendered as soon as a input has been confirmed.
	// It is intended to permanently indicate the result of the prompt when the
	// input itself has disappeared. This template is only rendered in the Run()
	// method and NOT when the text input is used as a model. The following
	// variables and functions are available:
	//
	//  * FinalChoice: The choice that was selected by the user.
	//  * Prompt string: The configured prompt.
	//  * InitialValue string: The configured initial value of the input.
	//  * Placeholder string: The configured placeholder of the input.
	//  * TerminalWidth int: The width of the terminal.
	//  * AutoCompleteTriggered bool: An indication that auto-complete was
	//    just triggered by the user. It resets after further input.
	//  * AutoCompleteIndecisive bool: An indication that auto-complete was
	//    just triggered by the user with an indecisive results. It resets
	//    after further input.
	//  * AutoCompleteSuggestions() []string: A function that returns the
	//    auto-complete suggestions for the current input.
	//  * Mask(string) string: A function that replaces all characters of
	//    a string with the character specified in HideMask if Hidden is
	//    true and returns the input string if Hidden is false.
	//  * promptkit.UtilFuncMap: Handy helper functions.
	//  * termenv TemplateFuncs (see https://github.com/muesli/termenv).
	//  * The functions specified in ExtendedTemplateFuncs.
	ResultTemplate string

	// ExtendedTemplateFuncs can be used to add additional functions to the
	// evaluation scope of the templates.
	ExtendedTemplateFuncs template.FuncMap

	// Styles of the actual input field. These will be applied as inline styles.
	//
	// For an introduction to styling with Lip Gloss see:
	// https://github.com/charmbracelet/lipgloss
	InputTextStyle        lipgloss.Style
	InputBackgroundStyle  lipgloss.Style // Deprecated: This property is not used anymore.
	InputPlaceholderStyle lipgloss.Style
	InputCursorStyle      lipgloss.Style

	// KeyMap determines with which keys the text input is controlled. By
	// default, DefaultKeyMap is used.
	KeyMap *KeyMap

	// WrapMode decides which way the prompt view is wrapped if it does not fit
	// the terminal. It can be a WrapMode provided by promptkit or a custom
	// function. By default it is promptkit.WordWrap. It can also be nil which
	// disables wrapping and likely causes output glitches.
	WrapMode promptkit.WrapMode

	// Output is the output writer, by default os.Stdout is used.
	Output io.Writer
	// Input is the input reader, by default, os.Stdin is used.
	Input io.Reader

	// ColorProfile determines how colors are rendered. By default, the terminal
	// is queried.
	ColorProfile termenv.Profile
}

TextInput represents a configurable selection prompt.

func New

func New(prompt string) *TextInput

New creates a new text input. See the TextInput properties for more documentation.

func (*TextInput) RunPrompt

func (t *TextInput) RunPrompt() (string, error)

RunPrompt executes the text input prompt.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL