### Get default KeyMap Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Returns a KeyMap with standard default key bindings. ```go func NewDefaultKeyMap() *KeyMap ``` -------------------------------- ### Get Template Utility Functions Source: https://pkg.go.dev/github.com/erikgeiser/promptkit UtilFuncMap returns a template.FuncMap with handy utility functions for prompt templates. These include string manipulation and arithmetic operations. ```go func UtilFuncMap() template.FuncMap ``` -------------------------------- ### Default Selection Templates - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Defines the default appearance for the selection prompt and its final result. Use DefaultTemplate as a starting point for custom designs. ```go 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" ) ``` -------------------------------- ### Get Selected Value as Choice - Model.ValueAsChoice Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Use ValueAsChoice to get the selected value wrapped within a Choice struct. This method is available from v0.8.0 onwards and returns a pointer to the Choice struct and an error. ```go func (m *Model[T]) ValueAsChoice() (*Choice[T], error) ``` -------------------------------- ### Get Selected Value - Model.Value Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Use Value to retrieve the currently selected choice or the final choice after the prompt concludes. It returns the selected value and any potential error. ```go func (m *Model[T]) Value() (T, error) ``` -------------------------------- ### Get Selection Value - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Retrieves the selected value from the model. Returns an error if no selection has been made or if an error occurred during selection. ```go func (m *Model[T]) Value() (T, error) { if m.Err != nil { var zero T return zero, m.Err } if m.FinalChoice == nil { var zero T return zero, errors.New("no choice selected") } return m.FinalChoice.Value, nil } ``` -------------------------------- ### Get Selection Value as Choice - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Retrieves the selected choice as a Choice object. Returns an error if no selection has been made or if an error occurred. ```go func (m *Model[T]) ValueAsChoice() (*Choice[T], error) { if m.Err != nil { return nil, m.Err } if m.FinalChoice == nil { return nil, errors.New("no choice selected") } return m.FinalChoice, nil } ``` -------------------------------- ### Initialize Model Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Initializes the confirmation prompt model. ```go func (m *Model) Init() tea.Cmd ``` -------------------------------- ### Create new Confirmation prompt Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Initializes a new confirmation prompt instance. ```go func New(prompt string, defaultValue Value) *Confirmation ``` -------------------------------- ### Create new Model Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Initializes a new model for a confirmation prompt. ```go func NewModel(confirmation *Confirmation) *Model ``` -------------------------------- ### Selection Prompt Initialization and Execution Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection How to create and run a new Selection prompt using the PromptKit library. ```APIDOC ## Selection Prompt Initialization and Execution This section covers the creation and execution of the `Selection` prompt. ### Functions #### `New[T any](prompt string, choices []T) *Selection[T]` - **Description**: Creates a new selection prompt. - **Parameters**: - **prompt** (string) - Required - The main prompt message to display to the user. - **choices** ([]T) - Required - A slice of choices for the user to select from. - **Returns**: - **`*Selection[T]`** - A pointer to the newly created selection prompt. #### `(*Selection[T]) RunPrompt() (T, error)` - **Description**: Executes the selection prompt and returns the user's chosen value. - **Returns**: - **`T`** - The type of the selected choice. - **`error`** - An error if the prompt execution fails. ``` -------------------------------- ### Run Model Test Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/test Initializes a model and applies a series of events. ```go func Run(tb testing.TB, model tea.Model, events ...tea.Msg) ``` -------------------------------- ### TextInput Configuration Options Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Configure text input prompts with options for wrapping, input/output streams, and color profiles. Defaults are provided for most options. ```go 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 } ``` -------------------------------- ### Create a new Selection prompt Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Initializes a new selection prompt with a prompt string and a slice of choices. ```go func New[T any](prompt string, choices []T) *Selection[T] ``` -------------------------------- ### Execute the Selection prompt Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Runs the selection prompt and returns the chosen item or an error. ```go func (s *Selection[T]) RunPrompt() (T, error) ``` -------------------------------- ### Execute confirmation prompt Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Runs the confirmation prompt and returns the boolean result or an error. ```go func (c *Confirmation) RunPrompt() (bool, error) ``` -------------------------------- ### Selection Model Initialization - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Initializes the selection prompt model. This function is part of the bubbletea.Model interface. ```go func (m *Model[T]) Init() tea.Cmd { return nil } ``` -------------------------------- ### Selection Constructor - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Creates a new Selection prompt with a given prompt string and a list of choices. The choices can be of any type. ```go func New[T any](prompt string, choices []T) *Selection[T] { // ... initialization ... return &Selection[T]{ Prompt: prompt, Choices: choices, // ... other fields ... } } ``` -------------------------------- ### KeyMap Configuration Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Methods for managing key bindings for the confirmation prompt. ```APIDOC ## NewDefaultKeyMap() ### Description Returns a KeyMap with default key mappings for confirmation actions. ### Response - **KeyMap** (struct) - The default key configuration. ``` -------------------------------- ### Run TextInput Prompt Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Execute the text input prompt and retrieve the user's input string and any potential errors. ```go func (t *TextInput) RunPrompt() (string, error) ``` -------------------------------- ### Define KeyMap struct Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Configures the keys used to control the confirmation prompt. ```go type KeyMap struct { Yes []string No []string SelectYes []string SelectNo []string Toggle []string Submit []string Abort []string } ``` -------------------------------- ### Selection Prompt Overview Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection The selection package implements a prompt that allows users to select one of the pre-defined choices. It offers customizable appearance and key maps, as well as optional support for pagination and filtering. ```APIDOC ## Package selection ### 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. ### Constants ```go 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" ) ``` ### Functions #### func DefaultFinalChoiceStyle ```go func DefaultFinalChoiceStyle[T any](c *Choice[T]) string ``` DefaultFinalChoiceStyle is the default style for final choices. #### func DefaultSelectedChoiceStyle ```go func DefaultSelectedChoiceStyle[T any](c *Choice[T]) string ``` DefaultSelectedChoiceStyle is the default style for selected choices. #### func FilterContainsCaseInsensitive ```go 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 ```go 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. ``` -------------------------------- ### Run TextInput Prompt Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Executes the configured text input prompt and returns the user's input. ```APIDOC ## POST /api/textinput/run ### Description Executes the text input prompt and returns the user's input string and any potential error. ### Method POST ### Endpoint /api/textinput/run ### Parameters This endpoint does not accept path or query parameters. ### Request Body - **t** (*TextInput) - Required - The TextInput object to run. ### Request Example ```json { "t": { "WrapMode": "WordWrap", "Output": null, "Input": null, "ColorProfile": null } } ``` ### Response #### Success Response (200) - **string** (string) - The user's input string. - **error** (error) - An error object if the prompt execution failed, otherwise null. #### Response Example ```json { "string": "User entered text", "error": null } ``` ``` -------------------------------- ### NewModel Constructor Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Creates a new Model instance, initializing it with a provided TextInput. ```go func NewModel(textInput *TextInput) *Model ``` -------------------------------- ### Model View Method Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Renders the confirmation prompt's current view. This method is typically called by the TUI framework to display the prompt to the user. ```go func (m *Model) View() tea.View ``` -------------------------------- ### Create New TextInput Prompt Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Use the New function to create a new text input prompt. Refer to the TextInput properties for detailed configuration options. ```go func New(prompt string) *TextInput ``` -------------------------------- ### Define Default Templates Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Constants defining the default appearance for prompts and their final results. ```go const ( // DefaultTemplate defines the default appearance of the text input and can // be copied as a starting point for a custom template. DefaultTemplate = TemplateArrow // DefaultResultTemplate defines the default appearance with which the // finale result of the prompt is presented. DefaultResultTemplate = ResultTemplateArrow ) ``` -------------------------------- ### Model Methods Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Methods for interacting with the confirmation prompt model. ```APIDOC ## func (*Model) Value ### Description Returns the current value and error of the confirmation prompt. ### Method GET ### Response - **bool** - The current value. - **error** - Any error encountered. ## func (*Model) View ### Description Renders the confirmation prompt view. ### Method GET ### Response - **tea.View** - The rendered view of the confirmation prompt. ``` -------------------------------- ### Define text input constants Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Constants defining default templates and masking characters for text input prompts. ```go 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 = '●' ) ``` -------------------------------- ### Run Selection Prompt - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Executes the selection prompt and returns the user's chosen value. This method blocks until a selection is made or an error occurs. ```go func (s *Selection[T]) RunPrompt() (T, error) { model := NewModel(s) program := tea.NewProgram(model) if _, err := program.Run(); err != nil { return *new(T), err } return model.Value() } ``` -------------------------------- ### Choice Struct - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Represents a single selectable item in the prompt. It includes a string representation, a value, and its current index. ```go type Choice[T any] struct { String string Value T // contains filtered or unexported fields } ``` -------------------------------- ### Model Struct - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Implements the bubbletea.Model interface for the selection prompt. It manages the prompt's state, including errors and maximum width. ```go 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 } ``` -------------------------------- ### Selection Prompt Configuration Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Configuration options for the Selection prompt, allowing customization of appearance, behavior, and input/output. ```APIDOC ## Selection Prompt Configuration This section details the configurable properties of the `Selection` prompt. ### Properties - **UnselectedChoiceStyle** (func(*Choice[T]) string) - Optional - A function to style unselected choices. This is available as the `Unselected` template function. - **FinalChoiceStyle** (func(*Choice[T]) string) - Optional - A function to style the ultimately chosen choice. This is available as the `Final` template function. If nil, no style is applied. - **KeyMap** (*KeyMap) - Optional - Determines the keys used to control the selection prompt. Defaults to `DefaultKeyMap`. - **WrapMode** (promptkit.WrapMode) - Optional - Decides how the prompt view wraps if it doesn't fit the terminal. Defaults to `promptkit.WordWrap`. If nil, wrapping is disabled. - **Output** (io.Writer) - Optional - The output writer for the prompt. Defaults to `os.Stdout`. - **Input** (io.Reader) - Optional - The input reader for the prompt. Defaults to `os.Stdin`. - **ColorProfile** (termenv.Profile) - Optional - Determines how colors are rendered. Defaults to querying the terminal. ``` -------------------------------- ### Define Confirmation struct Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Represents a configurable confirmation prompt with support for custom templates, key maps, and I/O streams. ```go type Confirmation struct { // Prompt holds the question. Prompt string // DefaultValue decides if a value should already be selected at startup. By // default it is Undecided but it can be set to Yes (corresponds to true) // and No (corresponds to false). DefaultValue Value // 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. // * YesSelected bool: Whether or not Yes is the currently selected // value. // * NoSelected bool: Whether or not No is the currently selected // value. // * Undecided bool: Whether or not Undecided is the currently selected // value. // * DefaultYes bool: Whether or not Yes is confiured as default value. // * DefaultNo bool: Whether or not No is confiured as default value. // * DefaultUndecided bool: Whether or not Undecided is confiured as // default value. // * 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: // // * FinalValue bool: The final value of the confirmation. // * FinalValue string: The final value's string representation ("true" // or "false"). // * Prompt string: The configured prompt. // * DefaultYes bool: Whether or not Yes is confiured as default value. // * DefaultNo bool: Whether or not No is confiured as default value. // * DefaultUndecided bool: Whether or not Undecided is confiured as // default value. // * 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. ResultTemplate string // ExtendedTemplateFuncs can be used to add additional functions to the // evaluation scope of the templates. ExtendedTemplateFuncs template.FuncMap // KeyMap determines with which keys the confirmation 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 } ``` -------------------------------- ### Render Prompt View - Model.View Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Use View to render the current state of the selection prompt. This method returns a tea.View, which is used by the TUI framework to display the prompt to the user. ```go func (m *Model[T]) View() tea.View ``` -------------------------------- ### Define Model struct Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Implements the bubbletea.Model interface for the confirmation prompt. ```go type Model struct { *Confirmation // Err holds errors that may occur during the execution of // the confirmation prompt. Err error // MaxWidth limits the width of the view using the Confirmation's WrapMode. MaxWidth int // contains filtered or unexported fields } ``` -------------------------------- ### Create auto-complete functions Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Functions to generate auto-complete logic from a slice of choices, with options for case sensitivity and default values. ```go func AutoCompleteFromSlice(choices []string) func(string) []string ``` ```go func AutoCompleteFromSliceWithDefault( choices []string, defaultValue string, ) func(string) []string ``` ```go func CaseSensitiveAutoCompleteFromSlice(choices []string) func(string) []string ``` ```go func CaseSensitiveAutoCompleteFromSliceWithDefault( choices []string, defaultValue string, ) func(string) []string ``` -------------------------------- ### Value Type and Constructor Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Definition and constructor for the confirmation prompt value. ```APIDOC ## type Value ### Description Represents the value of the confirmation prompt, which can be Undecided, Yes, or No. ## func NewValue ### Description Creates a new Value from a boolean. ### Parameters - **v** (bool) - Required - The boolean value to convert. ``` -------------------------------- ### Update Model Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/test Applies an event to an initialized model. Use Run for uninitialized models. ```go func Update(tb testing.TB, model tea.Model, event tea.Msg) tea.Cmd ``` -------------------------------- ### Generate Key Message Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/test Creates a KeyPressMsg corresponding to a specific rune. ```go func KeyMsg(r rune) tea.Msg ``` -------------------------------- ### View Selection Prompt - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Renders the current state of the selection prompt to be displayed in the terminal. This function is part of the bubbletea.Model interface. ```go func (m *Model[T]) View() tea.View { // ... rendering logic ... return lipgloss.NewRenderer().Render(m.Render()) } ``` -------------------------------- ### Model Struct and Methods Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Overview of the Model struct and its lifecycle methods for managing text input components in a Bubble Tea application. ```APIDOC ## Model Struct ### Description Represents a bubbletea.Model for a text input component. ### Fields - **TextInput** (*TextInput) - The underlying text input component. - **Err** (error) - Holds errors occurring during execution. - **MaxWidth** (int) - Limits the width of the view. ## func NewModel ### Description Creates and returns a new Model instance. ### Parameters - **textInput** (*TextInput) - The text input to wrap. ## func (*Model) Init ### Description Initializes the text input model. ### Returns - **tea.Cmd** - The initialization command. ## func (*Model) Update ### Description Updates the model based on a received message. ### Parameters - **message** (tea.Msg) - The message to process. ### Returns - **tea.Model** - The updated model. - **tea.Cmd** - The command to execute. ## func (*Model) Value ### Description Retrieves the current value and any associated error. ### Returns - **string** - The current input value. - **error** - The error state. ## func (*Model) View ### Description Renders the text input component. ### Returns - **tea.View** - The rendered view. ``` -------------------------------- ### Confirmation Prompt API Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Methods for creating and running a confirmation prompt. ```APIDOC ## New(prompt string, defaultValue Value) ### Description Creates a new confirmation prompt instance. ### Parameters - **prompt** (string) - Required - The question to display. - **defaultValue** (Value) - Required - The initial selection state (Undecided, Yes, or No). ### Response - **Confirmation** (struct) - A pointer to the configured Confirmation instance. ``` ```APIDOC ## RunPrompt() ### Description Executes the confirmation prompt and waits for user input. ### Response - **bool** - The final confirmed value. - **error** - Any error encountered during execution. ``` -------------------------------- ### textinput Package Overview Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Overview of the textinput package components, including key functions for auto-completion and validation. ```APIDOC ## textinput Package ### Description Provides functionality for string input prompts, supporting secret inputs, validation, and custom key maps. ### Functions - **AutoCompleteFromSlice(choices []string)**: Creates a case-insensitive auto-complete function. - **AutoCompleteFromSliceWithDefault(choices []string, defaultValue string)**: Creates a case-insensitive auto-complete function with a default value. - **CaseSensitiveAutoCompleteFromSlice(choices []string)**: Creates a case-sensitive auto-complete function. - **CaseSensitiveAutoCompleteFromSliceWithDefault(choices []string, defaultValue string)**: Creates a case-sensitive auto-complete function with a default value. - **ValidateNotEmpty(s string)**: Validates that the input string is not empty. ### Types - **KeyMap**: Defines key bindings for actions like moving, deleting, auto-completing, and submitting. - **NewDefaultKeyMap()**: Returns a KeyMap with default settings. ``` -------------------------------- ### Default Key Map - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Provides a default set of key mappings for selection prompt actions. This can be used as a base for custom key configurations. ```go func NewDefaultKeyMap() *KeyMap { return &KeyMap{ Down: []string{"down", "j"}, Up: []string{"up", "k"}, Select: []string{"enter", "!"}, Abort: []string{"ctrl+c", "esc"}, ClearFilter: []string{"ctrl+u"}, ScrollDown: []string{"ctrl+d"}, ScrollUp: []string{"ctrl+u"}, } } ``` -------------------------------- ### Confirmation Prompt API Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Functions and types for creating and running binary confirmation prompts. ```APIDOC ## func New(prompt string, defaultValue Value) *Confirmation ### Description Creates a new confirmation prompt instance with a specific prompt string and a default value. ### Parameters - **prompt** (string) - Required - The question text to display to the user. - **defaultValue** (Value) - Required - The initial state of the prompt (Yes, No, or Undecided). ## func (c *Confirmation) RunPrompt() (bool, error) ### Description Executes the confirmation prompt and returns the user's selection. ### Response - **bool** - The final selection (true for Yes, false for No). - **error** - Any error encountered during prompt execution. ``` -------------------------------- ### Define TemplateYN Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Classic template with [yn] indicator where the current value is capitalized and bold. ```go const TemplateYN = `` /* 190-byte string literal not displayed */ ``` -------------------------------- ### New TextInput Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Function to create a new TextInput instance. ```APIDOC ## POST /api/textinput/new ### Description Creates a new text input prompt. ### Method POST ### Endpoint /api/textinput/new ### Parameters #### Query Parameters - **prompt** (string) - Required - The initial prompt message to display to the user. ### Request Body This endpoint does not accept a request body. ### Response #### Success Response (200) - ***TextInput** (object) - A pointer to the newly created TextInput object. ### Response Example ```json { "example": "" } ``` ``` -------------------------------- ### Model Type Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Implements the bubbletea.Model interface for the selection prompt, handling its state and updates. ```APIDOC #### type Model ```go 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 ```go func NewModel[T any](selection *Selection[T]) *Model[T] ``` NewModel returns a new selection prompt model for the provided choices. #### func (*Model[T]) Init ```go func (m *Model[T]) Init() tea.Cmd ``` Init initializes the selection prompt model. #### func (*Model[T]) Update ```go func (m *Model[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) ``` Update updates the model based on the received message. ``` -------------------------------- ### Bubbletea Model Integration Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Methods for integrating the confirmation prompt into a bubbletea application. ```APIDOC ## NewModel(confirmation *Confirmation) ### Description Creates a new bubbletea model based on the provided confirmation prompt. ### Parameters - **confirmation** (*Confirmation) - Required - The confirmation instance to wrap. ### Response - **Model** (struct) - The initialized bubbletea model. ``` ```APIDOC ## Init() ### Description Initializes the confirmation prompt model. ### Response - **tea.Cmd** - The initialization command. ``` ```APIDOC ## Update(msg tea.Msg) ### Description Updates the model based on received messages. ### Parameters - **msg** (tea.Msg) - Required - The message to process. ### Response - **tea.Model** - The updated model. - **tea.Cmd** - The command to execute. ``` -------------------------------- ### Define Test Configuration Variables Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/test Global variables for controlling golden file updates and string inspection during tests. ```go var ( // UpdateGoldenFiles specifies whether the golden files should be updated. UpdateGoldenFiles = flag.Bool("update", false, "update the golden files") // Inspect prints string mismatches escaped such that the differences can be // inspected in detail. Inspect = flag.Bool("inspect", false, "inspect strings in detail") ) ``` -------------------------------- ### NewValue Function Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Creates a new Value of the confirmation prompt from a boolean. This is used to initialize the prompt's state. ```go func NewValue(v bool) Value ``` -------------------------------- ### TextInput Configuration Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Configuration options for the TextInput component. ```APIDOC ## TextInput Configuration ### Description Configurable properties for the TextInput prompt. ### Fields - **WrapMode** (promptkit.WrapMode) - The wrapping mode for the prompt view if it exceeds terminal width. Defaults to `promptkit.WordWrap`. Can be `nil` to disable wrapping. - **Output** (io.Writer) - The output writer for the prompt. Defaults to `os.Stdout`. - **Input** (io.Reader) - The input reader for the prompt. Defaults to `os.Stdin`. - **ColorProfile** (termenv.Profile) - Determines how colors are rendered. Defaults to querying the terminal. ``` -------------------------------- ### Define Confirmation Values Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Variables representing the possible states of a confirmation prompt. ```go var ( // Yes is a possible value of the confirmation prompt that corresponds to // true. Yes = Value(&yes) // No is a possible value of the confirmation prompt that corresponds to // false. No = Value(&no) // Undecided is a possible value of the confirmation prompt that is used // when neither Yes nor No are selected. Undecided = Value(nil) ) ``` -------------------------------- ### TextInput Configuration Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Configuration options for the TextInput component to handle user input, validation, and visual styling. ```APIDOC ## TextInput Configuration ### Description The TextInput struct defines the behavior and appearance of a text input prompt in a terminal interface. ### Parameters - **Prompt** (string) - The text displayed above the input field. - **Placeholder** (string) - Text shown when the input is empty. - **InitialValue** (string) - Pre-filled value for the input. - **Validate** (func(string) error) - Function to validate input data. - **AutoComplete** (func(string) []string) - Function to provide auto-completion suggestions. - **Hidden** (bool) - If true, masks the input (e.g., for passwords). - **HideMask** (rune) - Character used for masking when Hidden is true. - **CharLimit** (int) - Maximum character count allowed. - **InputWidth** (int) - Maximum display width for the input field. - **Template** (string) - Custom display template for the input. - **ResultTemplate** (string) - Template rendered after input confirmation. - **InputTextStyle** (lipgloss.Style) - Styling for the input text. - **InputPlaceholderStyle** (lipgloss.Style) - Styling for the placeholder text. - **InputCursorStyle** (lipgloss.Style) - Styling for the input cursor. ``` -------------------------------- ### TextInput Struct Definition Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput The core configuration structure for defining text input behavior, including validation, templates, and styling. ```go 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 ``` -------------------------------- ### PromptKit Variables Source: https://pkg.go.dev/github.com/erikgeiser/promptkit Variables available in the promptkit package. ```APIDOC ## var ErrAborted ### Description ErrAborted is returned when the prompt was aborted. ### Type ```go var ErrAborted = fmt.Errorf("prompt aborted") ``` ``` -------------------------------- ### Generate Messages from Text Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/test Converts a string into a sequence of KeyPressMsg events. ```go func MsgsFromText(text string) []tea.Msg ``` -------------------------------- ### Model[T] Methods Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Methods for interacting with the Model[T] component to retrieve values and render the UI. ```APIDOC ## GET /Model[T]/Value ### Description Returns the choice that is currently selected or the final choice after the prompt has concluded. ### Method GET ### Response - **T** (generic) - The currently selected value. - **error** (error) - Error if the value cannot be retrieved. --- ## GET /Model[T]/ValueAsChoice ### Description Returns the selected value wrapped in a Choice struct. Added in v0.8.0. ### Method GET ### Response - **Choice[T]** (struct) - The selected value wrapped in a Choice struct. - **error** (error) - Error if the choice cannot be retrieved. --- ## GET /Model[T]/View ### Description View renders the selection prompt. ### Method GET ### Response - **tea.View** (interface) - The rendered view of the selection prompt. ``` -------------------------------- ### Model Value Method Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Returns the current value and error status of the Model. Use this to retrieve the final state after user interaction. ```go func (m *Model) Value() (bool, error) ``` -------------------------------- ### Model Value Method Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput Retrieves the current text input value and any associated error. ```go func (m *Model) Value() (string, error) ``` -------------------------------- ### KeyMap Type Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Defines the key bindings for various actions within the selection prompt, such as navigation, selection, and filtering. ```APIDOC #### type KeyMap ```go 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 ```go func NewDefaultKeyMap() *KeyMap ``` NewDefaultKeyMap returns a KeyMap with sensible default key mappings that can also be used as a starting point for customization. ``` -------------------------------- ### Default Final Choice Style - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Returns the default styling for a choice that has been finalized by the user. ```go func DefaultFinalChoiceStyle[T any](c *Choice[T]) string { return "\033[38;2;150;150;150m" + c.String + "\033[0m" } ``` -------------------------------- ### Test Helper Functions Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/test Provides functions for asserting golden views, indenting text, generating key press messages, running models with events, stripping ANSI sequences, and updating models. ```APIDOC ## func AssertGoldenView ### Description AssertGoldenView compares the view to an expected view in an updatable golden file. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## func Indent ### Description Indent is intended to indent views for easier comparison in test error logs. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## func KeyMsg ### Description KeyMsg returns the KeyPressMsg that corresponds to the given rune. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## func MsgsFromText ### Description MsgsFromText generates KeyPressMsg events from a given text. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## func Run ### Description Run initializes the model and applies all events. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## func StripANSI ### Description StripANSI removes all ANSI sequences from a string. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## func Update ### Description Update applies the event to an already initialized model. If the model was not initialized, use Run instead. ### Method N/A (Function Signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### PromptKit Utility Functions Source: https://pkg.go.dev/github.com/erikgeiser/promptkit Utility functions for text manipulation within prompts. ```APIDOC ## func HardWrap ### Description HardWrap performs a hard wrap at the given width. ### Signature ```go func HardWrap(input string, width int) string ``` ### Parameters * **input** (string) - The string to wrap. * **width** (int) - The maximum width for wrapping. ### Returns * (string) - The wrapped string. ## func Truncate ### Description Truncate cuts the string after the given width. ### Signature ```go func Truncate(input string, width int) string ``` ### Parameters * **input** (string) - The string to truncate. * **width** (int) - The maximum width for truncation. ### Returns * (string) - The truncated string. ## func UtilFuncMap ### Description UtilFuncMap returns a template.FuncMap with handy utility functions for prompt templates. ### Signature ```go func UtilFuncMap() template.FuncMap ``` ### Returns * (template.FuncMap) - A map of utility functions. ### Available Functions in FuncMap * Repeat(string, int) string: Identical to strings.Repeat. * Len(string): reflow/ansi.PrintableRuneWidth, Len works like len but is aware of ansi codes and returns the length of the string as it appears on the screen. * Min(int, int) int: The minimum of two ints. * Max(int, int) int: The maximum of two ints. * Add(int, int) int: The sum of two ints. * Sub(int, int) int: The difference of two ints. * Mul(int, int) int: The product of two ints. ## func WordWrap ### Description WordWrap performs a word wrap on the input and forces a wrap at width if a word is still larger that width after soft wrapping. This is known to cause issues with coloring in some terminals depending on the prompt style. ### Signature ```go func WordWrap(input string, width int) string ``` ### Parameters * **input** (string) - The string to word wrap. * **width** (int) - The maximum width for word wrapping. ### Returns * (string) - The word-wrapped string. ``` -------------------------------- ### Define KeyMap structure Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/textinput The KeyMap struct defines the key bindings for various input actions. ```go 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 } ``` -------------------------------- ### Selection Model Update - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Handles incoming messages and updates the state of the selection prompt model. This function is part of the bubbletea.Model interface. ```go func (m *Model[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) { var cmd tea.Cmd sswitch msg.(type) { case tea.KeyMsg: key := msg.(tea.KeyMsg) // ... handle key presses ... } return m, cmd } ``` -------------------------------- ### Assert Golden View Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/test Compares a model's view against an expected view stored in a golden file. ```go func AssertGoldenView(tb testing.TB, m tea.Model, expectedViewFile string) ``` -------------------------------- ### Define TemplateArrow Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/confirmation Template where the current choice is indicated by an arrow. ```go const TemplateArrow = `` /* 197-byte string literal not displayed */ ``` -------------------------------- ### Default Selected Choice Style - PromptKit Source: https://pkg.go.dev/github.com/erikgeiser/promptkit/selection Returns the default styling for a choice that is currently selected by the user. ```go func DefaultSelectedChoiceStyle[T any](c *Choice[T]) string { return "\033[1m" + c.String + "\033[0m" } ```