selection

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 13 Imported by: 67

Documentation

Overview

Package selection implements a selection prompt that allows users to select one of the pre-defined choices. It also offers customizable appreance and key map as well as optional support for pagination, filtering.

Index

Constants

View Source
const (
	// DefaultMultiTemplate defines the default appearance of the multi-selection
	// prompt and can be copied as a starting point for a custom template.
	DefaultMultiTemplate = `` /* 1503-byte string literal not displayed */

	// DefaultMultiResultTemplate defines the default appearance with which the
	// final result of the multi-selection prompt is presented.
	DefaultMultiResultTemplate = `
	{{- print .Prompt " " .FinalChoicesStr "\n" -}}
	`
)
View Source
const (
	// DefaultTemplate defines the default appearance of the selection and can
	// be copied as a starting point for a custom template.
	DefaultTemplate = `` /* 527-byte string literal not displayed */

	// DefaultResultTemplate defines the default appearance with which the
	// finale result of the selection is presented.
	DefaultResultTemplate = `
	{{- print .Prompt " " (Final .FinalChoice) "\n" -}}
	`

	// DefaultFilterPrompt is the default prompt for the filter input when
	// filtering is enabled.
	DefaultFilterPrompt = "Filter:"

	// DefaultFilterPlaceholder is printed by default when no filter text was
	// entered yet.
	DefaultFilterPlaceholder = "Type to filter choices"
)

Variables

This section is empty.

Functions

func DefaultCursorMarkedChoiceStyle added in v0.12.0

func DefaultCursorMarkedChoiceStyle[T any](c *Choice[T]) string

DefaultCursorMarkedChoiceStyle is the default style for a marked choice at the cursor position.

func DefaultFinalChoiceStyle added in v0.5.0

func DefaultFinalChoiceStyle[T any](c *Choice[T]) string

DefaultFinalChoiceStyle is the default style for final choices.

func DefaultMarkedChoiceStyle added in v0.12.0

func DefaultMarkedChoiceStyle[T any](c *Choice[T]) string

DefaultMarkedChoiceStyle is the default style for marked choices.

func DefaultSelectedChoiceStyle added in v0.5.0

func DefaultSelectedChoiceStyle[T any](c *Choice[T]) string

DefaultSelectedChoiceStyle is the default style for selected choices.

func FilterContainsCaseInsensitive

func FilterContainsCaseInsensitive[T any](filter string, choice *Choice[T]) bool

FilterContainsCaseInsensitive returns true if the string representation of the choice contains the filter string without regard for capitalization.

func FilterContainsCaseSensitive

func FilterContainsCaseSensitive[T any](filter string, choice *Choice[T]) bool

FilterContainsCaseSensitive returns true if the string representation of the choice contains the filter string respecting capitalization.

func PreSelect added in v0.12.0

func PreSelect[T comparable](preSelectedValues ...T) func(c *Choice[T]) bool

Types

type Choice

type Choice[T any] struct {
	String string
	Value  T
	// contains filtered or unexported fields
}

Choice represents a single choice. This type used as an input for the selection prompt, for filtering and as a result value.

func (*Choice[T]) Index

func (c *Choice[T]) Index() int

Index returns the current index of the choice.

type KeyMap

type KeyMap struct {
	Down        []string
	Up          []string
	Select      []string
	Abort       []string
	ClearFilter []string
	ScrollDown  []string
	ScrollUp    []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[T any] struct {
	*Selection[T]

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

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

Model implements the bubbletea.Model for a selection prompt.

func NewModel

func NewModel[T any](selection *Selection[T]) *Model[T]

NewModel returns a new selection prompt model for the provided choices.

func (*Model[T]) Init

func (m *Model[T]) Init() tea.Cmd

Init initializes the selection prompt model.

func (*Model[T]) Update

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

Update updates the model based on the received message.

func (*Model[T]) Value

func (m *Model[T]) Value() (T, error)

Value returns the choice that is currently selected or the final choice after the prompt has concluded.

func (*Model[T]) ValueAsChoice added in v0.8.0

func (m *Model[T]) ValueAsChoice() (*Choice[T], error)

ValueAsChoice returns the selected value wrapped in a Choice struct.

func (*Model[T]) View

func (m *Model[T]) View() tea.View

View renders the selection prompt.

type MultiKeyMap added in v0.12.0

type MultiKeyMap struct {
	KeyMap
	Toggle []string
}

MultiKeyMap defines the keys that trigger actions in the multi-selection prompt. It extends KeyMap with a Toggle key for marking and unmarking choices.

func NewDefaultMultiKeyMap added in v0.12.0

func NewDefaultMultiKeyMap() *MultiKeyMap

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

type MultiModel added in v0.12.0

type MultiModel[T any] struct {
	*MultiSelection[T]

	// Err holds errors that may occur during the execution of the
	// multi-selection prompt.
	Err error

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

MultiModel implements the bubbletea.Model for a multi-selection prompt.

func NewMultiModel added in v0.12.0

func NewMultiModel[T any](ms *MultiSelection[T]) *MultiModel[T]

NewMultiModel returns a new multi-selection prompt model for the provided choices.

func (*MultiModel[T]) Init added in v0.12.0

func (m *MultiModel[T]) Init() tea.Cmd

Init initializes the multi-selection prompt model.

func (*MultiModel[T]) Update added in v0.12.0

func (m *MultiModel[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update updates the model based on the received message.

func (*MultiModel[T]) Values added in v0.12.0

func (m *MultiModel[T]) Values() ([]T, error)

Values returns the marked values in original choice order.

func (*MultiModel[T]) ValuesAsChoices added in v0.12.0

func (m *MultiModel[T]) ValuesAsChoices() ([]*Choice[T], error)

ValuesAsChoices returns the marked choices in original choice order.

func (*MultiModel[T]) View added in v0.12.0

func (m *MultiModel[T]) View() tea.View

View renders the multi-selection prompt.

type MultiSelection added in v0.12.0

type MultiSelection[T any] struct {

	// Prompt holds the prompt text or question that is to be answered by
	// marking one or more of the choices.
	Prompt string

	// FilterPrompt is the prompt for the filter if filtering is enabled.
	FilterPrompt string

	// Filter is a function that decides whether a given choice should be
	// displayed based on the text entered by the user into the filter input
	// field. If Filter is nil, filtering will be disabled. By default the
	// filter FilterContainsCaseInsensitive is used.
	Filter func(filterText string, choice *Choice[T]) bool

	// FilterPlaceholder holds the text that is displayed in the filter input
	// field when no text was entered by the user yet. If empty, the
	// DefaultFilterPlaceholder is used. If Filter is nil, filtering is
	// disabled and FilterPlaceholder does nothing.
	FilterPlaceholder string

	// PreSelected is an optional function that decided whether an option should
	// be pre-selected. It can easily be populated from a single choice value or
	// a slice of choice values using the selection.PreSelected helper.
	PreSelected func(c *Choice[T]) bool

	// PageSize is the number of choices that are displayed at once. If
	// PageSize is smaller than the number of choices, pagination is enabled.
	// If PageSize is 0, pagination is disabled. Regardless of the value of
	// PageSize, pagination is always enabled when the prompt does not fit the
	// terminal.
	PageSize int

	// LoopCursor enables the cursor to loop around to the first choice when
	// navigating down from the last choice and the other way around.
	LoopCursor bool

	// MinSelections is the minimum number of choices that must be marked
	// before the prompt can be confirmed. A value of 0 allows confirming with
	// no choices marked. The default is 1.
	MinSelections int

	// MaxSelections is the maximum number of choices that can be marked. Once
	// the limit is reached, toggling unmarked choices has no effect. A value
	// of 0 means there is no limit.
	MaxSelections int

	// Template holds the display template. A custom template can be used to
	// completely customize the appearance of the multi-selection prompt. If
	// empty, DefaultMultiTemplate is used. The following variables and
	// functions are available:
	//
	//  * Prompt string: The configured prompt.
	//  * IsFiltered bool: Whether or not filtering is enabled.
	//  * FilterPrompt string: The configured filter prompt.
	//  * FilterInput string: The view of the filter input model.
	//  * Choices []*Choice: The choices on the current page.
	//  * NChoices int: The number of choices on the current page.
	//  * SelectedIndex int: The index of the cursor in the current page.
	//  * PageSize int: The configured page size.
	//  * IsPaged bool: Whether pagination is currently active.
	//  * AllChoices []*Choice: All configured choices.
	//  * NAllChoices int: The number of configured choices.
	//  * MarkedChoices []*Choice: All currently marked choices in original order.
	//  * NMarkedChoices int: The number of currently marked choices.
	//  * OffscreenMarkedChoices []*Choice: Marked choices not visible in the current
	//    page because they are scrolled out of view or filtered out.
	//  * NOffscreenMarkedChoices int: The number of offscreen marked choices.
	//  * TerminalWidth int: The width of the terminal.
	//  * KeyMap *MultiKeyMap: The configured key map.
	//  * IsMarked(*Choice) bool: Whether the given choice is marked.
	//  * Cursor(*Choice) string: The configured CursorChoiceStyle.
	//  * CursorMarked(*Choice) string: The configured CursorMarkedChoiceStyle.
	//  * Marked(*Choice) string: The configured MarkedChoiceStyle.
	//  * Unmarked(*Choice) string: The configured UnmarkedChoiceStyle.
	//  * IsScrollDownHintPosition(idx int) bool: Returns whether the scroll
	//    down hint should be displayed at the given index.
	//  * IsScrollUpHintPosition(idx int) bool: Returns whether the scroll up
	//    hint should be displayed at the given index.
	//  * 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 the choices have been confirmed.
	// It is intended to permanently indicate the result of the prompt when the
	// selection itself has disappeared. This template is only rendered in the
	// RunPrompt() method and NOT when the prompt is used as a model. The
	// following variables and functions are available:
	//
	//  * FinalChoices []*Choice: The marked choices in original order.
	//  * FinalChoicesStr string: The marked choices rendered with FinalChoiceStyle
	//    and joined by ", ".
	//  * Prompt string: The configured prompt.
	//  * AllChoices []*Choice: All configured choices.
	//  * NAllChoices int: The number of configured choices.
	//  * TerminalWidth int: The width of the terminal.
	//  * KeyMap *MultiKeyMap: The configured key map.
	//  * Final(*Choice) string: The configured FinalChoiceStyle.
	//  * 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 filter input field. These will be applied as inline
	// styles.
	//
	// For an introduction to styling with Lip Gloss see:
	// https://github.com/charmbracelet/lipgloss
	FilterInputTextStyle        lipgloss.Style
	FilterInputBackgroundStyle  lipgloss.Style // Deprecated: This property is not used anymore.
	FilterInputPlaceholderStyle lipgloss.Style
	FilterInputCursorStyle      lipgloss.Style

	// CursorChoiceStyle allows customizing the appearance of the choice at the
	// cursor position when it is not marked. If nil, no style is applied and
	// the plain string representation is used. This style is available as the
	// template function Cursor.
	CursorChoiceStyle func(*Choice[T]) string

	// CursorMarkedChoiceStyle allows customizing the appearance of the choice
	// at the cursor position when it is marked. By default
	// DefaultCursorMarkedChoiceStyle is used. If nil, no style is applied.
	// This style is available as the template function CursorMarked.
	CursorMarkedChoiceStyle func(*Choice[T]) string

	// MarkedChoiceStyle allows customizing the appearance of marked choices
	// that are not at the cursor position. By default DefaultMarkedChoiceStyle
	// is used. If nil, no style is applied. This style is available as the
	// template function Marked.
	MarkedChoiceStyle func(*Choice[T]) string

	// UnmarkedChoiceStyle allows customizing the appearance of choices that
	// are neither marked nor at the cursor position. If nil, no style is
	// applied and the plain string representation is used. This style is
	// available as the template function Unmarked.
	UnmarkedChoiceStyle func(*Choice[T]) string

	// FinalChoiceStyle allows customizing the appearance of the confirmed
	// choices in the result template. By default DefaultMarkedChoiceStyle is
	// used. If nil, no style is applied. This style is available as the
	// template function Final.
	FinalChoiceStyle func(*Choice[T]) string

	// KeyMap determines with which keys the multi-selection prompt is
	// controlled. By default, DefaultMultiKeyMap is used.
	KeyMap *MultiKeyMap

	// 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.Truncate. 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
	// contains filtered or unexported fields
}

MultiSelection represents a configurable multi-selection prompt.

func NewMulti added in v0.12.0

func NewMulti[T any](prompt string, choices []T) *MultiSelection[T]

NewMulti creates a new multi-selection prompt. See the MultiSelection properties for more documentation.

func (*MultiSelection[T]) RunPrompt added in v0.12.0

func (s *MultiSelection[T]) RunPrompt() ([]T, error)

RunPrompt executes the multi-selection prompt.

type Selection

type Selection[T any] struct {

	// Prompt holds the prompt text or question that is to be answered by one of
	// the choices.
	Prompt string

	// FilterPrompt is the prompt for the filter if filtering is enabled.
	FilterPrompt string

	// Filter is a function that decides whether a given choice should be
	// displayed based on the text entered by the user into the filter input
	// field. If Filter is nil, filtering will be disabled. By default the
	// filter FilterContainsCaseInsensitive is used.
	Filter func(filterText string, choice *Choice[T]) bool

	// FilterPlaceholder holds the text that is displayed in the filter input
	// field when no text was entered by the user yet. If empty, the
	// DefaultFilterPlaceholder is used. If Filter is nil, filtering is disabled
	// and FilterPlaceholder does nothing.
	FilterPlaceholder string

	// PageSize is the number of choices that are displayed at once. If PageSize
	// is smaller than the number of choices, pagination is enabled. If PageSize
	// is 0, pagination is disabled. Regardless of the value of PageSize,
	// pagination is always enabled when the prompt does not fit the terminal.
	PageSize int

	// LoopCursor enables the cursor to loop around to the first choice when
	// navigating down from the last choice and the other way around.
	LoopCursor bool

	// Template holds the display template. A custom template can be used to
	// completely customize the appearance of the selection prompt. If empty,
	// the DefaultTemplate is used. The following variables and functions are
	// available:
	//
	//  * Prompt string: The configured prompt.
	//  * IsFiltered bool: Whether or not filtering is enabled.
	//  * FilterPrompt string: The configured filter prompt.
	//  * FilterInput string: The view of the filter input model.
	//  * Choices []*Choice: The choices on the current page.
	//  * NChoices int: The number of choices on the current page.
	//  * SelectedIndex int: The index that is currently selected.
	//  * PageSize int: The configured page size.
	//  * IsPaged bool: Whether pagination is currently active.
	//  * AllChoices []*Choice: All configured choices.
	//  * NAllChoices int: The number of configured choices.
	//  * TerminalWidth int: The width of the terminal.
	//  * KeyMap *KeyMap: The configured key map.
	//  * Selected(*Choice) string: The configured SelectedChoiceStyle.
	//  * Unselected(*Choice) string: The configured UnselectedChoiceStyle.
	//  * IsScrollDownHintPosition(idx int) bool: Returns whether
	//    the scroll down hint should be displayed at the given index.
	//  * IsScrollUpHintPosition(idx int) bool: Returns whether the
	//    scroll up hint should be displayed at the given index).
	//  * 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 choice has been selected.
	// It is intended to permanently indicate the result of the prompt when the
	// selection itself has disappeared. This template is only rendered in the
	// Run() method and NOT when the selection prompt 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.
	//  * AllChoices []*Choice: All configured choices.
	//  * NAllChoices int: The number of configured choices.
	//  * TerminalWidth int: The width of the terminal.
	//  * Final(*Choice) string: The configured FinalChoiceStyle.
	//  * 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 filter input field. These will be applied as inline styles.
	//
	// For an introduction to styling with Lip Gloss see:
	// https://github.com/charmbracelet/lipgloss
	FilterInputTextStyle        lipgloss.Style
	FilterInputBackgroundStyle  lipgloss.Style // Deprecated: This property is not used anymore.
	FilterInputPlaceholderStyle lipgloss.Style
	FilterInputCursorStyle      lipgloss.Style

	// SelectedChoice style allows to customize the appearance of the currently
	// selected choice. By default DefaultSelectedChoiceStyle is used. If it is
	// nil, no style will be applied and the plain string representation of the
	// choice will be used. This style will be available as the template
	// function Selected. Custom templates may or may not use this function.
	SelectedChoiceStyle func(*Choice[T]) string

	// UnselectedChoiceStyle style allows to customize the appearance of the
	// currently unselected choice. By default it is nil, such that no style
	// will be applied and the plain string representation of the choice will be
	// used. This style will be available as the template function Unselected.
	// Custom templates may or may not use this function.
	UnselectedChoiceStyle func(*Choice[T]) string

	// FinalChoiceStyle style allows to customize the appearance of the choice
	// that was ultimately chosen. By default DefaultFinalChoiceStyle is used.
	// If it is nil, no style will be applied and the plain string
	// representation of the choice will be used. This style will be available
	// as the template function Final. Custom templates may or may not use this
	// function.
	FinalChoiceStyle func(*Choice[T]) string

	// KeyMap determines with which keys the selection prompt 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
	// contains filtered or unexported fields
}

Selection represents a configurable selection prompt.

func New

func New[T any](prompt string, choices []T) *Selection[T]

New creates a new selection prompt. See the Selection properties for more documentation.

func (*Selection[T]) RunPrompt

func (s *Selection[T]) RunPrompt() (T, error)

RunPrompt executes the selection prompt.

Jump to

Keyboard shortcuts

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