huh

package module
v0.0.0-...-ef9ddd6 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2024 License: MIT Imports: 24 Imported by: 0

README

Huh?



Latest Release Go Docs Build Status

A simple, powerful library for building interactive forms and prompts in the terminal.

Running a burger form

huh? is easy to use in a standalone fashion, can be integrated into a Bubble Tea application, and contains a first-class accessible mode for screen readers.

The above example is running from a single Go program (source).

Tutorial

Let’s build a form for ordering burgers. To start, we’ll import the library and define a few variables where’ll we store answers.

package main

import "github.com/charmbracelet/huh"

var (
    burger       string
    toppings     []string
    sauceLevel   int
    name         string
    instructions string
    discount     bool
)

huh? separates forms into groups (you can think of groups as pages). Groups are made of fields (e.g. Select, Input, Text). We will set up three groups for the customer to fill out.

form := huh.NewForm(
    huh.NewGroup(
        // Ask the user for a base burger and toppings.
        huh.NewSelect[string]().
            Title("Choose your burger").
            Options(
                huh.NewOption("Charmburger Classic", "classic"),
                huh.NewOption("Chickwich", "chickwich"),
                huh.NewOption("Fishburger", "fishburger"),
                huh.NewOption("Charmpossible™ Burger", "charmpossible"),
            ).
            Value(&burger), // store the chosen option in the "burger" variable

        // Let the user select multiple toppings.
        huh.NewMultiSelect[string]().
            Title("Toppings").
            Options(
                huh.NewOption("Lettuce", "lettuce").Selected(true),
                huh.NewOption("Tomatoes", "tomatoes").Selected(true),
                huh.NewOption("Jalapeños", "jalapeños"),
                huh.NewOption("Cheese", "cheese"),
                huh.NewOption("Vegan Cheese", "vegan cheese"),
                huh.NewOption("Nutella", "nutella"),
            ).
            Limit(4). // there’s a 4 topping limit!
            Value(&toppings),

        // Option values in selects and multi selects can be any type you
        // want. We’ve been recording strings above, but here we’ll store
        // answers as integers. Note the generic "[int]" directive below.
        huh.NewSelect[int]().
            Title("How much Charm Sauce do you want?").
            Options(
                huh.NewOption("None", 0),
                huh.NewOption("A little", 1),
                huh.NewOption("A lot", 2),
            ).
            Value(&sauceLevel),
    ),

    // Gather some final details about the order.
    huh.NewGroup(
        huh.NewInput().
            Title("What’s your name?").
            Value(&name).
            // Validating fields is easy. The form will mark erroneous fields
            // and display error messages accordingly.
            Validate(func(str string) error {
                if str == "Frank" {
                    return errors.New("Sorry, we don’t serve customers named Frank.")
                }
                return nil
            }),

        huh.NewText().
            Title("Special Instructions").
            CharLimit(400).
            Value(&instructions),

        huh.NewConfirm().
            Title("Would you like 15% off?").
            Value(&discount),
    ),
)

Finally, run the form:

err := form.Run()
if err != nil {
    log.Fatal(err)
}

if !discount {
    fmt.Println("What? You didn’t take the discount?!")
}

And that’s it! For more info see the full source for this example as well as the docs.

If you need more dynamic forms that change based on input from previous fields, check out the dynamic forms example.

Field Reference

  • Input: single line text input
  • Text: multi-line text input
  • Select: select an option from a list
  • MultiSelect: select multiple options from a list
  • Confirm: confirm an action (yes or no)

[!TIP] Just want to prompt the user with a single field? Each field has a Run method that can be used as a shorthand for gathering quick and easy input.

var name string

huh.NewInput().
    Title("What’s your name?").
    Value(&name).
    Run() // this is blocking...

fmt.Printf("Hey, %s!\n", name)
Input

Prompt the user for a single line of text.

Input field
huh.NewInput().
    Title("What’s for lunch?").
    Prompt("?").
    Validate(isFood).
    Value(&lunch)
Text

Prompt the user for multiple lines of text.

Text field
huh.NewText().
    Title("Tell me a story.").
    Validate(checkForPlagiarism).
    Value(&story)
Select

Prompt the user to select a single option from a list.

Select field
huh.NewSelect[string]().
    Title("Pick a country.").
    Options(
        huh.NewOption("United States", "US"),
        huh.NewOption("Germany", "DE"),
        huh.NewOption("Brazil", "BR"),
        huh.NewOption("Canada", "CA"),
    ).
    Value(&country)
Multiple Select

Prompt the user to select multiple (zero or more) options from a list.

Multiselect field
huh.NewMultiSelect[string]().
    Options(
        huh.NewOption("Lettuce", "Lettuce").Selected(true),
        huh.NewOption("Tomatoes", "Tomatoes").Selected(true),
        huh.NewOption("Charm Sauce", "Charm Sauce"),
        huh.NewOption("Jalapeños", "Jalapeños"),
        huh.NewOption("Cheese", "Cheese"),
        huh.NewOption("Vegan Cheese", "Vegan Cheese"),
        huh.NewOption("Nutella", "Nutella"),
    ).
    Title("Toppings").
    Limit(4).
    Value(&toppings)
Confirm

Prompt the user to confirm (Yes or No).

Confirm field
huh.NewConfirm().
    Title("Are you sure?").
    Affirmative("Yes!").
    Negative("No.").
    Value(&confirm)

Accessibility

huh? has a special rendering option designed specifically for screen readers. You can enable it with form.WithAccessible(true).

[!TIP] We recommend setting this through an environment variable or configuration option to allow the user to control accessibility.

accessibleMode := os.Getenv("ACCESSIBLE") != ""
form.WithAccessible(accessibleMode)

Accessible forms will drop TUIs in favor of standard prompts, providing better dictation and feedback of the information on screen for the visually impaired.

Accessible cuisine form

Themes

huh? contains a powerful theme abstraction. Supply your own custom theme or choose from one of the five predefined themes:

  • Charm
  • Dracula
  • Catppuccin
  • Base 16
  • Default

Charm-themed form Dracula-themed form Catppuccin-themed form Base 16-themed form Default-themed form

Themes can take advantage of the full range of Lip Gloss style options. For a high level theme reference see the docs.

Dynamic Forms

huh? forms can be as dynamic as your heart desires. Simply replace properties with their equivalent Func to recompute the properties value every time a different part of your form changes.

Here’s how you would build a simple country + state / province picker.

First, define some variables that we’ll use to store the user selection.

var country string
var state string

Define your country select as you normally would:

huh.NewSelect[string]().
    Options(huh.NewOptions("United States", "Canada", "Mexico")...).
    Value(&country).
    Title("Country").

Define your state select with TitleFunc and OptionsFunc instead of Title and Options. This will allow you to change the title and options based on the selection of the previous field, i.e. country.

To do this, we provide a func() string and a binding any to TitleFunc. The function defines what to show for the title and the binding specifies what value needs to change for the function to recompute. So if country changes (e.g. the user changes the selection) we will recompute the function.

For OptionsFunc, we provide a func() []Option[string] and a binding any. We’ll fetch the country’s states, provinces, or territories from an API. huh will automatically handle caching for you.

[!IMPORTANT] We have to pass &country as the binding to recompute the function only when country changes, otherwise we will hit the API too often.

huh.NewSelect[string]().
    Value(&state).
    Height(8).
    TitleFunc(func() string {
        switch country {
        case "United States":
            return "State"
        case "Canada":
            return "Province"
        default:
            return "Territory"
        }
    }, &country).
    OptionsFunc(func() []huh.Option[string] {
        opts := fetchStatesForCountry(country)
        return huh.NewOptions(opts...)
    }, &country),

Lastly, run the form with these inputs.

err := form.Run()
if err != nil {
    log.Fatal(err)
}
Country / State form with dynamic inputs running.

Bonus: Spinner

huh? ships with a standalone spinner package. It’s useful for indicating background activity after a form is submitted.

Spinner while making a burger

Create a new spinner, set a title, set the action (or provide a Context), and run the spinner:

Action Style Context Style
err := spinner.New().
    Title("Making your burger...").
    Action(makeBurger).
    Run()

fmt.Println("Order up!")
go makeBurger()

err := spinner.New().
    Type(spinner.Line).
    Title("Making your burger...").
    Context(ctx).
    Run()

fmt.Println("Order up!")

For more on Spinners see the spinner examples and the spinner docs.

What about Bubble Tea?

In addition to its standalone mode, huh? has first-class support for Bubble Tea and can be easily integrated into Bubble Tea applications. It’s incredibly useful in portions of your Bubble Tea application that need form-like input.

Bubble Tea embedded form example

A huh.Form is merely a tea.Model, so you can use it just as you would any other Bubble.

type Model struct {
    form *huh.Form // huh.Form is just a tea.Model
}

func NewModel() Model {
    return Model{
        form: huh.NewForm(
            huh.NewGroup(
                huh.NewSelect[string]().
                    Key("class").
                    Options(huh.NewOptions("Warrior", "Mage", "Rogue")...).
                    Title("Choose your class"),

            huh.NewSelect[int]().
                Key("level").
                Options(huh.NewOptions(1, 20, 9999)...).
                Title("Choose your level"),
            ),
        )
    }
}

func (m Model) Init() tea.Cmd {
    return m.form.Init()
}

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

    form, cmd := m.form.Update(msg)
    if f, ok := form.(*huh.Form); ok {
        m.form = f
    }

    return m, cmd
}

func (m Model) View() string {
    if m.form.State == huh.StateCompleted {
        class := m.form.GetString("class")
        level := m.form.GetString("level")
        return fmt.Sprintf("You selected: %s, Lvl. %d", class, level)
    }
    return m.form.View()
}

For more info in using huh? in Bubble Tea applications see the full Bubble Tea example.

Huh? in the Wild

For some Huh? programs in production, see:

  • glyphs: a unicode symbol picker
  • meteor: a highly customisable conventional commit message tool
  • freeze: a tool for generating images of code and terminal output
  • gum: a tool for glamorous shell scripts
  • savvy: the easiest way to create, share, and run runbooks in the terminal

Feedback

We’d love to hear your thoughts on this project. Feel free to drop us a note!

Acknowledgments

huh? is inspired by the wonderful Survey library by Alec Aivazis.

License

MIT


Part of Charm.

The Charm logo

Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrTimeout = errors.New("timeout")

ErrTimeout is the error returned when the timeout is reached.

View Source
var ErrTimeoutUnsupported = errors.New("timeout is not supported in accessible mode")

ErrTimeoutUnsupported is the error returned when timeout is used while in accessible mode.

View Source
var ErrUserAborted = errors.New("user aborted")

ErrUserAborted is the error returned when a user exits the form before submitting.

Functions

func NextField

func NextField() tea.Msg

NextField is the command to move to the next field.

func PrevField

func PrevField() tea.Msg

PrevField is the command to move to the previous field.

func Run

func Run(field Field) error

Run runs a single field by wrapping it within a group and a form.

func ValidateLength

func ValidateLength(min, max int) func(s string) error

ValidateLength checks if the length of the input is within the specified range.

func ValidateMaxLength

func ValidateMaxLength(max int) func(s string) error

ValidateMaxLength checks if the length of the input is at most max.

func ValidateMinLength

func ValidateMinLength(min int) func(s string) error

ValidateMinLength checks if the length of the input is at least min.

func ValidateNotEmpty

func ValidateNotEmpty() func(s string) error

ValidateNotEmpty checks if the input is not empty.

func ValidateOneOf

func ValidateOneOf(options ...string) func(string) error

ValidateOneOf checks if a string is one of the specified options.

Types

type Accessor

type Accessor[T any] interface {
	Get() T
	Set(value T)
}

Accessor give read/write access to field values.

type Confirm

type Confirm struct {
	// contains filtered or unexported fields
}

Confirm is a form confirm field.

func NewConfirm

func NewConfirm() *Confirm

NewConfirm returns a new confirm field.

func (*Confirm) Accessor

func (c *Confirm) Accessor(accessor Accessor[bool]) *Confirm

Accessor sets the accessor of the confirm field.

func (*Confirm) Affirmative

func (c *Confirm) Affirmative(affirmative string) *Confirm

Affirmative sets the affirmative value of the confirm field.

func (*Confirm) Blur

func (c *Confirm) Blur() tea.Cmd

Blur blurs the confirm field.

func (*Confirm) Description

func (c *Confirm) Description(description string) *Confirm

Description sets the description of the confirm field.

func (*Confirm) DescriptionFunc

func (c *Confirm) DescriptionFunc(f func() string, bindings any) *Confirm

DescriptionFunc sets the description function of the confirm field.

func (*Confirm) Error

func (c *Confirm) Error() error

Error returns the error of the confirm field.

func (*Confirm) Focus

func (c *Confirm) Focus() tea.Cmd

Focus focuses the confirm field.

func (*Confirm) GetKey

func (c *Confirm) GetKey() string

GetKey returns the key of the field.

func (*Confirm) GetValue

func (c *Confirm) GetValue() any

GetValue returns the value of the field.

func (*Confirm) Init

func (c *Confirm) Init() tea.Cmd

Init initializes the confirm field.

func (*Confirm) Inline

func (c *Confirm) Inline(inline bool) *Confirm

Inline sets whether the field should be inline.

func (*Confirm) Key

func (c *Confirm) Key(key string) *Confirm

Key sets the key of the confirm field.

func (*Confirm) KeyBinds

func (c *Confirm) KeyBinds() []key.Binding

KeyBinds returns the help message for the confirm field.

func (*Confirm) Negative

func (c *Confirm) Negative(negative string) *Confirm

Negative sets the negative value of the confirm field.

func (*Confirm) Run

func (c *Confirm) Run() error

Run runs the confirm field in accessible mode.

func (*Confirm) Skip

func (*Confirm) Skip() bool

Skip returns whether the confirm should be skipped or should be blocking.

func (*Confirm) String

func (c *Confirm) String() string

func (*Confirm) Title

func (c *Confirm) Title(title string) *Confirm

Title sets the title of the confirm field.

func (*Confirm) TitleFunc

func (c *Confirm) TitleFunc(f func() string, bindings any) *Confirm

TitleFunc sets the title func of the confirm field.

func (*Confirm) Update

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

Update updates the confirm field.

func (*Confirm) Validate

func (c *Confirm) Validate(validate func(bool) error) *Confirm

Validate sets the validation function of the confirm field.

func (*Confirm) Value

func (c *Confirm) Value(value *bool) *Confirm

Value sets the value of the confirm field.

func (*Confirm) View

func (c *Confirm) View() string

View renders the confirm field.

func (*Confirm) WithAccessible

func (c *Confirm) WithAccessible(accessible bool) Field

WithAccessible sets the accessible mode of the confirm field.

func (*Confirm) WithHeight

func (c *Confirm) WithHeight(height int) Field

WithHeight sets the height of the confirm field.

func (*Confirm) WithKeyMap

func (c *Confirm) WithKeyMap(k *KeyMap) Field

WithKeyMap sets the keymap of the confirm field.

func (*Confirm) WithPosition

func (c *Confirm) WithPosition(p FieldPosition) Field

WithPosition sets the position of the confirm field.

func (*Confirm) WithTheme

func (c *Confirm) WithTheme(theme *Theme) Field

WithTheme sets the theme of the confirm field.

func (*Confirm) WithWidth

func (c *Confirm) WithWidth(width int) Field

WithWidth sets the width of the confirm field.

func (*Confirm) Zoom

func (*Confirm) Zoom() bool

Zoom returns whether the input should be zoomed.

type ConfirmKeyMap

type ConfirmKeyMap struct {
	Next   key.Binding
	Prev   key.Binding
	Toggle key.Binding
	Submit key.Binding
	Accept key.Binding
	Reject key.Binding
}

ConfirmKeyMap is the keybindings for confirm fields.

type EchoMode

type EchoMode textinput.EchoMode

EchoMode sets the input behavior of the text Input field.

const (
	// EchoNormal displays text as is.
	// This is the default behavior.
	EchoModeNormal EchoMode = EchoMode(textinput.EchoNormal)

	// EchoPassword displays the EchoCharacter mask instead of actual characters.
	// This is commonly used for password fields.
	EchoModePassword EchoMode = EchoMode(textinput.EchoPassword)

	// EchoNone displays nothing as characters are entered.
	// This is commonly seen for password fields on the command line.
	EchoModeNone EchoMode = EchoMode(textinput.EchoNone)
)

type EmbeddedAccessor

type EmbeddedAccessor[T any] struct {
	// contains filtered or unexported fields
}

EmbeddedAccessor is a basic accessor, acting as the default one for fields.

func (*EmbeddedAccessor[T]) Get

func (a *EmbeddedAccessor[T]) Get() T

Get gets the value.

func (*EmbeddedAccessor[T]) Set

func (a *EmbeddedAccessor[T]) Set(value T)

Set sets the value.

type Eval

type Eval[T any] struct {
	// contains filtered or unexported fields
}

Eval is an evaluatable value, it stores a cached value and a function to recompute it. It's bindings are what we check to see if we need to recompute the value.

By default it is also cached.

type Field

type Field interface {
	// Bubble Tea Model
	Init() tea.Cmd
	Update(tea.Msg) (tea.Model, tea.Cmd)
	View() string

	// Bubble Tea Events
	Blur() tea.Cmd
	Focus() tea.Cmd

	// Errors and Validation
	Error() error

	// Run runs the field individually.
	Run() error

	// Skip returns whether this input should be skipped or not.
	Skip() bool

	// Zoom returns whether this input should be zoomed or not.
	// Zoom allows the field to take focus of the group / form height.
	Zoom() bool

	// KeyBinds returns help keybindings.
	KeyBinds() []key.Binding

	// WithTheme sets the theme on a field.
	WithTheme(*Theme) Field

	// WithAccessible sets whether the field should run in accessible mode.
	WithAccessible(bool) Field

	// WithKeyMap sets the keymap on a field.
	WithKeyMap(*KeyMap) Field

	// WithWidth sets the width of a field.
	WithWidth(int) Field

	// WithHeight sets the height of a field.
	WithHeight(int) Field

	// WithPosition tells the field the index of the group and position it is in.
	WithPosition(FieldPosition) Field

	// GetKey returns the field's key.
	GetKey() string

	// GetValue returns the field's value.
	GetValue() any
}

Field is a primitive of a form.

A field represents a single input control on a form such as a text input, confirm button, select option, etc...

Each field implements the Bubble Tea Model interface.

type FieldPosition

type FieldPosition struct {
	Group      int
	Field      int
	FirstField int
	LastField  int
	GroupCount int
	FirstGroup int
	LastGroup  int
}

FieldPosition is positional information about the given field and form.

func (FieldPosition) IsFirst

func (p FieldPosition) IsFirst() bool

IsFirst returns whether a field is the form's first field.

func (FieldPosition) IsLast

func (p FieldPosition) IsLast() bool

IsLast returns whether a field is the form's last field.

type FieldStyles

type FieldStyles struct {
	Base           lipgloss.Style
	Title          lipgloss.Style
	Description    lipgloss.Style
	ErrorIndicator lipgloss.Style
	ErrorMessage   lipgloss.Style

	// Select styles.
	SelectSelector lipgloss.Style // Selection indicator
	Option         lipgloss.Style // Select options
	NextIndicator  lipgloss.Style
	PrevIndicator  lipgloss.Style

	// FilePicker styles.
	Directory lipgloss.Style
	File      lipgloss.Style

	// Multi-select styles.
	MultiSelectSelector lipgloss.Style
	SelectedOption      lipgloss.Style
	SelectedPrefix      lipgloss.Style
	UnselectedOption    lipgloss.Style
	UnselectedPrefix    lipgloss.Style

	// Textinput and teatarea styles.
	TextInput TextInputStyles

	// Confirm styles.
	FocusedButton lipgloss.Style
	BlurredButton lipgloss.Style

	// Card styles.
	Card      lipgloss.Style
	NoteTitle lipgloss.Style
	Next      lipgloss.Style
}

FieldStyles are the styles for input fields.

type FilePicker

type FilePicker struct {
	// contains filtered or unexported fields
}

FilePicker is a form file file field.

func NewFilePicker

func NewFilePicker() *FilePicker

NewFilePicker returns a new file field.

func (*FilePicker) Accessor

func (f *FilePicker) Accessor(accessor Accessor[string]) *FilePicker

Accessor sets the accessor of the file field.

func (*FilePicker) AllowedTypes

func (f *FilePicker) AllowedTypes(types []string) *FilePicker

AllowedTypes sets the allowed types of the file field. These will be the only valid file types accepted, other files will show as disabled.

func (*FilePicker) Blur

func (f *FilePicker) Blur() tea.Cmd

Blur blurs the file field.

func (*FilePicker) CurrentDirectory

func (f *FilePicker) CurrentDirectory(directory string) *FilePicker

CurrentDirectory sets the directory of the file field.

func (*FilePicker) Description

func (f *FilePicker) Description(description string) *FilePicker

Description sets the description of the file field.

func (*FilePicker) DirAllowed

func (f *FilePicker) DirAllowed(v bool) *FilePicker

DirAllowed sets whether to allow files to be selected.

func (*FilePicker) Error

func (f *FilePicker) Error() error

Error returns the error of the file field.

func (*FilePicker) FileAllowed

func (f *FilePicker) FileAllowed(v bool) *FilePicker

FileAllowed sets whether to allow files to be selected.

func (*FilePicker) Focus

func (f *FilePicker) Focus() tea.Cmd

Focus focuses the file field.

func (*FilePicker) GetKey

func (f *FilePicker) GetKey() string

GetKey returns the key of the field.

func (*FilePicker) GetValue

func (f *FilePicker) GetValue() any

GetValue returns the value of the field.

func (*FilePicker) Height

func (f *FilePicker) Height(height int) *FilePicker

Height sets the height of the file field. If the number of options exceeds the height, the file field will become scrollable.

func (*FilePicker) Init

func (f *FilePicker) Init() tea.Cmd

Init initializes the file field.

func (*FilePicker) Key

func (f *FilePicker) Key(key string) *FilePicker

Key sets the key of the file field which can be used to retrieve the value after submission.

func (*FilePicker) KeyBinds

func (f *FilePicker) KeyBinds() []key.Binding

KeyBinds returns the help keybindings for the file field.

func (*FilePicker) Picking

func (f *FilePicker) Picking(v bool) *FilePicker

Picking sets whether the file picker should be in the picking files state.

func (*FilePicker) Run

func (f *FilePicker) Run() error

Run runs the file field.

func (*FilePicker) ShowHidden

func (f *FilePicker) ShowHidden(v bool) *FilePicker

ShowHidden sets whether to show hidden files.

func (*FilePicker) ShowPermissions

func (f *FilePicker) ShowPermissions(v bool) *FilePicker

ShowPermissions sets whether to show file permissions.

func (*FilePicker) ShowSize

func (f *FilePicker) ShowSize(v bool) *FilePicker

ShowSize sets whether to show file sizes.

func (*FilePicker) Skip

func (*FilePicker) Skip() bool

Skip returns whether the file should be skipped or should be blocking.

func (*FilePicker) Title

func (f *FilePicker) Title(title string) *FilePicker

Title sets the title of the file field.

func (*FilePicker) Update

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

Update updates the file field.

func (*FilePicker) Validate

func (f *FilePicker) Validate(validate func(string) error) *FilePicker

Validate sets the validation function of the file field.

func (*FilePicker) Value

func (f *FilePicker) Value(value *string) *FilePicker

Value sets the value of the file field.

func (*FilePicker) View

func (f *FilePicker) View() string

View renders the file field.

func (*FilePicker) WithAccessible

func (f *FilePicker) WithAccessible(accessible bool) Field

WithAccessible sets the accessible mode of the file field.

func (*FilePicker) WithHeight

func (f *FilePicker) WithHeight(height int) Field

WithHeight sets the height of the file field.

func (*FilePicker) WithKeyMap

func (f *FilePicker) WithKeyMap(k *KeyMap) Field

WithKeyMap sets the keymap on a file field.

func (*FilePicker) WithPosition

func (f *FilePicker) WithPosition(p FieldPosition) Field

WithPosition sets the position of the file field.

func (*FilePicker) WithTheme

func (f *FilePicker) WithTheme(theme *Theme) Field

WithTheme sets the theme of the file field.

func (*FilePicker) WithWidth

func (f *FilePicker) WithWidth(width int) Field

WithWidth sets the width of the file field.

func (*FilePicker) Zoom

func (f *FilePicker) Zoom() bool

Zoom returns whether the input should be zoomed.

type FilePickerKeyMap

type FilePickerKeyMap struct {
	Open     key.Binding
	Close    key.Binding
	GoToTop  key.Binding
	GoToLast key.Binding
	PageUp   key.Binding
	PageDown key.Binding
	Back     key.Binding
	Select   key.Binding
	Up       key.Binding
	Down     key.Binding
	Prev     key.Binding
	Next     key.Binding
	Submit   key.Binding
}

FilePickerKey is the keybindings for filepicker fields.

type Form

type Form struct {

	// callbacks
	SubmitCmd tea.Cmd
	CancelCmd tea.Cmd

	State FormState
	// contains filtered or unexported fields
}

Form is a collection of groups that are displayed one at a time on a "page".

The form can navigate between groups and is complete once all the groups are complete.

func NewForm

func NewForm(groups ...*Group) *Form

NewForm returns a form with the given groups and default themes and keybindings.

Use With* methods to customize the form with options, such as setting different themes and keybindings.

func (*Form) Errors

func (f *Form) Errors() []error

Errors returns the current groups' errors.

func (*Form) Get

func (f *Form) Get(key string) any

Get returns a result from the form.

func (*Form) GetBool

func (f *Form) GetBool(key string) bool

GetBool returns a result as a string from the form.

func (*Form) GetInt

func (f *Form) GetInt(key string) int

GetInt returns a result as a int from the form.

func (*Form) GetString

func (f *Form) GetString(key string) string

GetString returns a result as a string from the form.

func (*Form) Help

func (f *Form) Help() help.Model

Help returns the current groups' help.

func (*Form) Init

func (f *Form) Init() tea.Cmd

Init initializes the form.

func (*Form) KeyBinds

func (f *Form) KeyBinds() []key.Binding

KeyBinds returns the current fields' keybinds.

func (*Form) NextField

func (f *Form) NextField() tea.Cmd

NextField moves the form to the next field.

func (*Form) NextGroup

func (f *Form) NextGroup() tea.Cmd

NextGroup moves the form to the next group.

func (*Form) PrevField

func (f *Form) PrevField() tea.Cmd

NextField moves the form to the next field.

func (*Form) PrevGroup

func (f *Form) PrevGroup() tea.Cmd

PrevGroup moves the form to the next group.

func (*Form) Run

func (f *Form) Run() error

Run runs the form.

func (*Form) RunWithContext

func (f *Form) RunWithContext(ctx context.Context) error

RunWithContext runs the form with the given context.

func (*Form) Update

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

Update updates the form.

func (*Form) UpdateFieldPositions

func (f *Form) UpdateFieldPositions() *Form

UpdateFieldPositions sets the position on all the fields.

func (*Form) View

func (f *Form) View() string

View renders the form.

func (*Form) WithAccessible

func (f *Form) WithAccessible(accessible bool) *Form

WithAccessible sets the form to run in accessible mode to avoid redrawing the views which makes it easier for screen readers to read and describe the form.

This avoids using the Bubble Tea renderer and instead simply uses basic terminal prompting to gather input which degrades the user experience but provides accessibility.

func (*Form) WithHeight

func (f *Form) WithHeight(height int) *Form

WithHeight sets the height of a form.

func (*Form) WithInput

func (f *Form) WithInput(r io.Reader) *Form

WithInput sets the io.Reader to the input form.

func (*Form) WithKeyMap

func (f *Form) WithKeyMap(keymap *KeyMap) *Form

WithKeyMap sets the keymap on a form.

This allows customization of the form key bindings.

func (*Form) WithLayout

func (f *Form) WithLayout(layout Layout) *Form

WithLayout sets the layout on a form.

This allows customization of the form group layout.

func (*Form) WithOutput

func (f *Form) WithOutput(w io.Writer) *Form

WithOutput sets the io.Writer to output the form.

func (*Form) WithProgramOptions

func (f *Form) WithProgramOptions(opts ...tea.ProgramOption) *Form

WithProgramOptions sets the tea options of the form.

func (*Form) WithShowErrors

func (f *Form) WithShowErrors(v bool) *Form

WithShowErrors sets whether or not the form should show errors.

This allows the form groups and fields to show errors when the Validate function returns an error.

func (*Form) WithShowHelp

func (f *Form) WithShowHelp(v bool) *Form

WithShowHelp sets whether or not the form should show help.

This allows the form groups and field to show what keybindings are available to the user.

func (*Form) WithTheme

func (f *Form) WithTheme(theme *Theme) *Form

WithTheme sets the theme on a form.

This allows all groups and fields to be themed consistently, however themes can be applied to each group and field individually for more granular control.

func (*Form) WithTimeout

func (f *Form) WithTimeout(t time.Duration) *Form

WithTimeout sets the duration for the form to be killed.

func (*Form) WithWidth

func (f *Form) WithWidth(width int) *Form

WithWidth sets the width of a form.

This allows all groups and fields to be sized consistently, however width can be applied to each group and field individually for more granular control.

type FormState

type FormState int

FormState represents the current state of the form.

const (
	// StateNormal is when the user is completing the form.
	StateNormal FormState = iota

	// StateCompleted is when the user has completed the form.
	StateCompleted

	// StateAborted is when the user has aborted the form.
	StateAborted
)

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group is a collection of fields that are displayed together with a page of the form. While a group is displayed the form completer can switch between fields in the group.

If any of the fields in a group have errors, the form will not be able to progress to the next group.

func NewGroup

func NewGroup(fields ...Field) *Group

NewGroup returns a new group with the given fields.

func (*Group) Content

func (g *Group) Content() string

Content renders the group's content only (no footer).

func (*Group) Description

func (g *Group) Description(description string) *Group

Description sets the group's description.

func (*Group) Errors

func (g *Group) Errors() []error

Errors returns the groups' fields' errors.

func (*Group) Footer

func (g *Group) Footer() string

Footer renders the group's footer only (no content).

func (*Group) Init

func (g *Group) Init() tea.Cmd

Init initializes the group.

func (*Group) Title

func (g *Group) Title(title string) *Group

Title sets the group's title.

func (*Group) Update

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

Update updates the group.

func (*Group) View

func (g *Group) View() string

View renders the group.

func (*Group) WithHeight

func (g *Group) WithHeight(height int) *Group

WithHeight sets the height on a group.

func (*Group) WithHide

func (g *Group) WithHide(hide bool) *Group

WithHide sets whether this group should be skipped.

func (*Group) WithHideFunc

func (g *Group) WithHideFunc(hideFunc func() bool) *Group

WithHideFunc sets the function that checks if this group should be skipped.

func (*Group) WithKeyMap

func (g *Group) WithKeyMap(k *KeyMap) *Group

WithKeyMap sets the keymap on a group.

func (*Group) WithShowErrors

func (g *Group) WithShowErrors(show bool) *Group

WithShowErrors sets whether or not the group's errors should be shown.

func (*Group) WithShowHelp

func (g *Group) WithShowHelp(show bool) *Group

WithShowHelp sets whether or not the group's help should be shown.

func (*Group) WithTheme

func (g *Group) WithTheme(t *Theme) *Group

WithTheme sets the theme on a group.

func (*Group) WithWidth

func (g *Group) WithWidth(width int) *Group

WithWidth sets the width on a group.

type Input

type Input struct {
	// contains filtered or unexported fields
}

Input is a input field.

The input field is a field that allows the user to enter text. Use it to user input. It can be used for collecting text, passwords, or other short input.

The input field supports Suggestions, Placeholder, and Validation.

func NewInput

func NewInput() *Input

NewInput creates a new input field.

The input field is a field that allows the user to enter text. Use it to user input. It can be used for collecting text, passwords, or other short input.

The input field supports Suggestions, Placeholder, and Validation.

func (*Input) Accessor

func (i *Input) Accessor(accessor Accessor[string]) *Input

Accessor sets the accessor of the input field.

func (*Input) Blur

func (i *Input) Blur() tea.Cmd

Blur blurs the input field.

func (*Input) CharLimit

func (i *Input) CharLimit(charlimit int) *Input

CharLimit sets the character limit of the input field.

func (*Input) Description

func (i *Input) Description(description string) *Input

Description sets the description of the input field.

The Description is static for dynamic Description use `DescriptionFunc`.

func (*Input) DescriptionFunc

func (i *Input) DescriptionFunc(f func() string, bindings any) *Input

DescriptionFunc sets the description func of the input field.

The DescriptionFunc will be re-evaluated when the binding of the DescriptionFunc changes. This is useful when you want to display dynamic content and update the description when another part of your form changes.

See README#Dynamic for more usage information.

func (*Input) EchoMode

func (i *Input) EchoMode(mode EchoMode) *Input

EchoMode sets the echo mode of the input.

func (*Input) Error

func (i *Input) Error() error

Error returns the error of the input field.

func (*Input) Focus

func (i *Input) Focus() tea.Cmd

Focus focuses the input field.

func (*Input) GetKey

func (i *Input) GetKey() string

GetKey returns the key of the field.

func (*Input) GetValue

func (i *Input) GetValue() any

GetValue returns the value of the field.

func (*Input) Init

func (i *Input) Init() tea.Cmd

Init initializes the input field.

func (*Input) Inline

func (i *Input) Inline(inline bool) *Input

Inline sets whether the title and input should be on the same line.

func (*Input) Key

func (i *Input) Key(key string) *Input

Key sets the key of the input field.

func (*Input) KeyBinds

func (i *Input) KeyBinds() []key.Binding

KeyBinds returns the help message for the input field.

func (*Input) Password deprecated

func (i *Input) Password(password bool) *Input

Password sets whether or not to hide the input while the user is typing.

Deprecated: use EchoMode(EchoPassword) instead.

func (*Input) Placeholder

func (i *Input) Placeholder(str string) *Input

Placeholder sets the placeholder of the text input.

func (*Input) PlaceholderFunc

func (i *Input) PlaceholderFunc(f func() string, bindings any) *Input

PlaceholderFunc sets the placeholder func of the text input.

func (*Input) Prompt

func (i *Input) Prompt(prompt string) *Input

Prompt sets the prompt of the input field.

func (*Input) Run

func (i *Input) Run() error

Run runs the input field in accessible mode.

func (*Input) Skip

func (*Input) Skip() bool

Skip returns whether the input should be skipped or should be blocking.

func (*Input) Suggestions

func (i *Input) Suggestions(suggestions []string) *Input

Suggestions sets the suggestions to display for autocomplete in the input field.

The suggestions are static for dynamic suggestions use `SuggestionsFunc`.

func (*Input) SuggestionsFunc

func (i *Input) SuggestionsFunc(f func() []string, bindings any) *Input

SuggestionsFunc sets the suggestions func to display for autocomplete in the input field.

The SuggestionsFunc will be re-evaluated when the binding of the SuggestionsFunc changes. This is useful when you want to display dynamic suggestions when another part of your form changes.

See README#Dynamic for more usage information.

func (*Input) Title

func (i *Input) Title(title string) *Input

Title sets the title of the input field.

The Title is static for dynamic Title use `TitleFunc`.

func (*Input) TitleFunc

func (i *Input) TitleFunc(f func() string, bindings any) *Input

TitleFunc sets the title func of the input field.

The TitleFunc will be re-evaluated when the binding of the TitleFunc changes. This is useful when you want to display dynamic content and update the title when another part of your form changes.

See README#Dynamic for more usage information.

func (*Input) Update

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

Update updates the input field.

func (*Input) Validate

func (i *Input) Validate(validate func(string) error) *Input

Validate sets the validation function of the input field.

func (*Input) Value

func (i *Input) Value(value *string) *Input

Value sets the value of the input field.

func (*Input) View

func (i *Input) View() string

View renders the input field.

func (*Input) WithAccessible

func (i *Input) WithAccessible(accessible bool) Field

WithAccessible sets the accessible mode of the input field.

func (*Input) WithHeight

func (i *Input) WithHeight(height int) Field

WithHeight sets the height of the input field.

func (*Input) WithKeyMap

func (i *Input) WithKeyMap(k *KeyMap) Field

WithKeyMap sets the keymap on an input field.

func (*Input) WithPosition

func (i *Input) WithPosition(p FieldPosition) Field

WithPosition sets the position of the input field.

func (*Input) WithTheme

func (i *Input) WithTheme(theme *Theme) Field

WithTheme sets the theme of the input field.

func (*Input) WithWidth

func (i *Input) WithWidth(width int) Field

WithWidth sets the width of the input field.

func (*Input) Zoom

func (*Input) Zoom() bool

Zoom returns whether the input should be zoomed.

type InputKeyMap

type InputKeyMap struct {
	AcceptSuggestion key.Binding
	Next             key.Binding
	Prev             key.Binding
	Submit           key.Binding
}

InputKeyMap is the keybindings for input fields.

type KeyMap

type KeyMap struct {
	Quit key.Binding

	Confirm     ConfirmKeyMap
	FilePicker  FilePickerKeyMap
	Input       InputKeyMap
	MultiSelect MultiSelectKeyMap
	Note        NoteKeyMap
	Select      SelectKeyMap
	Text        TextKeyMap
}

KeyMap is the keybindings to navigate the form.

func NewDefaultKeyMap

func NewDefaultKeyMap() *KeyMap

NewDefaultKeyMap returns a new default keymap.

type Layout

type Layout interface {
	View(f *Form) string
	GroupWidth(f *Form, g *Group, w int) int
}

A Layout is responsible for laying out groups in a form.

var LayoutDefault Layout = &layoutDefault{}

Default layout shows a single group at a time.

var LayoutStack Layout = &layoutStack{}

Stack layout stacks all groups on top of each other.

func LayoutColumns

func LayoutColumns(columns int) Layout

Column layout distributes groups in even columns.

func LayoutGrid

func LayoutGrid(rows int, columns int) Layout

Grid layout distributes groups in a grid.

type MultiSelect

type MultiSelect[T comparable] struct {
	// contains filtered or unexported fields
}

MultiSelect is a form multi-select field.

func NewMultiSelect

func NewMultiSelect[T comparable]() *MultiSelect[T]

NewMultiSelect returns a new multi-select field.

func (*MultiSelect[T]) Accessor

func (m *MultiSelect[T]) Accessor(accessor Accessor[[]T]) *MultiSelect[T]

Accessor sets the accessor of the input field.

func (*MultiSelect[T]) Blur

func (m *MultiSelect[T]) Blur() tea.Cmd

Blur blurs the multi-select field.

func (*MultiSelect[T]) Description

func (m *MultiSelect[T]) Description(description string) *MultiSelect[T]

Description sets the description of the multi-select field.

func (*MultiSelect[T]) DescriptionFunc

func (m *MultiSelect[T]) DescriptionFunc(f func() string, bindings any) *MultiSelect[T]

DescriptionFunc sets the description func of the multi-select field.

func (*MultiSelect[T]) Error

func (m *MultiSelect[T]) Error() error

Error returns the error of the multi-select field.

func (*MultiSelect[T]) Filterable

func (m *MultiSelect[T]) Filterable(filterable bool) *MultiSelect[T]

Filterable sets the multi-select field as filterable.

func (*MultiSelect[T]) Filtering

func (m *MultiSelect[T]) Filtering(filtering bool) *MultiSelect[T]

Filtering sets the filtering state of the multi-select field.

func (*MultiSelect[T]) Focus

func (m *MultiSelect[T]) Focus() tea.Cmd

Focus focuses the multi-select field.

func (*MultiSelect[T]) GetKey

func (m *MultiSelect[T]) GetKey() string

GetKey returns the multi-select's key.

func (*MultiSelect[T]) GetValue

func (m *MultiSelect[T]) GetValue() any

GetValue returns the multi-select's value.

func (*MultiSelect[T]) Height

func (m *MultiSelect[T]) Height(height int) *MultiSelect[T]

Height sets the height of the multi-select field.

func (*MultiSelect[T]) Init

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

Init initializes the multi-select field.

func (*MultiSelect[T]) Key

func (m *MultiSelect[T]) Key(key string) *MultiSelect[T]

Key sets the key of the select field which can be used to retrieve the value after submission.

func (*MultiSelect[T]) KeyBinds

func (m *MultiSelect[T]) KeyBinds() []key.Binding

KeyBinds returns the help message for the multi-select field.

func (*MultiSelect[T]) Limit

func (m *MultiSelect[T]) Limit(limit int) *MultiSelect[T]

Limit sets the limit of the multi-select field.

func (*MultiSelect[T]) Options

func (m *MultiSelect[T]) Options(options ...Option[T]) *MultiSelect[T]

Options sets the options of the multi-select field.

func (*MultiSelect[T]) OptionsFunc

func (m *MultiSelect[T]) OptionsFunc(f func() []Option[T], bindings any) *MultiSelect[T]

OptionsFunc sets the options func of the multi-select field.

func (*MultiSelect[T]) Run

func (m *MultiSelect[T]) Run() error

Run runs the multi-select field.

func (*MultiSelect[T]) Skip

func (*MultiSelect[T]) Skip() bool

Skip returns whether the multiselect should be skipped or should be blocking.

func (*MultiSelect[T]) Title

func (m *MultiSelect[T]) Title(title string) *MultiSelect[T]

Title sets the title of the multi-select field.

func (*MultiSelect[T]) TitleFunc

func (m *MultiSelect[T]) TitleFunc(f func() string, bindings any) *MultiSelect[T]

TitleFunc sets the title func of the multi-select field.

func (*MultiSelect[T]) Update

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

Update updates the multi-select field.

func (*MultiSelect[T]) Validate

func (m *MultiSelect[T]) Validate(validate func([]T) error) *MultiSelect[T]

Validate sets the validation function of the multi-select field.

func (*MultiSelect[T]) Value

func (m *MultiSelect[T]) Value(value *[]T) *MultiSelect[T]

Value sets the value of the multi-select field.

func (*MultiSelect[T]) View

func (m *MultiSelect[T]) View() string

View renders the multi-select field.

func (*MultiSelect[T]) WithAccessible

func (m *MultiSelect[T]) WithAccessible(accessible bool) Field

WithAccessible sets the accessible mode of the multi-select field.

func (*MultiSelect[T]) WithHeight

func (m *MultiSelect[T]) WithHeight(height int) Field

WithHeight sets the total height of the multi-select field. Including padding and help menu heights.

func (*MultiSelect[T]) WithKeyMap

func (m *MultiSelect[T]) WithKeyMap(k *KeyMap) Field

WithKeyMap sets the keymap of the multi-select field.

func (*MultiSelect[T]) WithPosition

func (m *MultiSelect[T]) WithPosition(p FieldPosition) Field

WithPosition sets the position of the multi-select field.

func (*MultiSelect[T]) WithTheme

func (m *MultiSelect[T]) WithTheme(theme *Theme) Field

WithTheme sets the theme of the multi-select field.

func (*MultiSelect[T]) WithWidth

func (m *MultiSelect[T]) WithWidth(width int) Field

WithWidth sets the width of the multi-select field.

func (*MultiSelect[T]) Zoom

func (*MultiSelect[T]) Zoom() bool

Zoom returns whether the multiselect should be zoomed.

type MultiSelectKeyMap

type MultiSelectKeyMap struct {
	Next         key.Binding
	Prev         key.Binding
	Up           key.Binding
	Down         key.Binding
	HalfPageUp   key.Binding
	HalfPageDown key.Binding
	GotoTop      key.Binding
	GotoBottom   key.Binding
	Toggle       key.Binding
	Filter       key.Binding
	SetFilter    key.Binding
	ClearFilter  key.Binding
	Submit       key.Binding
	SelectAll    key.Binding
	SelectNone   key.Binding
}

MultiSelectKeyMap is the keybindings for multi-select fields.

type Note

type Note struct {
	// contains filtered or unexported fields
}

Note is a note field.

A note is responsible for displaying information to the user. Use it to provide context around a different field. Generally, the notes are not interacted with unless the note has a next button `Next(true)`.

func NewNote

func NewNote() *Note

NewNote creates a new note field.

A note is responsible for displaying information to the user. Use it to provide context around a different field. Generally, the notes are not interacted with unless the note has a next button `Next(true)`.

func (*Note) Blur

func (n *Note) Blur() tea.Cmd

Blur blurs the note field.

func (*Note) Description

func (n *Note) Description(description string) *Note

Description sets the note field's description.

This description will be static, for dynamic descriptions use `DescriptionFunc`.

func (*Note) DescriptionFunc

func (n *Note) DescriptionFunc(f func() string, bindings any) *Note

DescriptionFunc sets the description func of the note field.

The DescriptionFunc will be re-evaluated when the binding of the DescriptionFunc changes. This is useful when you want to display dynamic content and update the description of a note when another part of your form changes.

For example, you can make a dynamic markdown preview with the following Form & Group.

huh.NewText().Title("Markdown").Value(&md),
huh.NewNote().Height(20).Title("Preview").
  DescriptionFunc(func() string {
      return md
  }, &md),

Notice the `binding` of the Note is the same as the `Value` of the Text field. This binds the two values together, so that when the `Value` of the Text field changes so does the Note description.

func (*Note) Error

func (n *Note) Error() error

Error returns the error of the note field.

func (*Note) Focus

func (n *Note) Focus() tea.Cmd

Focus focuses the note field.

func (*Note) GetKey

func (n *Note) GetKey() string

GetKey satisfies the Field interface, notes do not have keys.

func (*Note) GetValue

func (n *Note) GetValue() any

GetValue satisfies the Field interface, notes do not have values.

func (*Note) Height

func (n *Note) Height(height int) *Note

Height sets the note field's height.

func (*Note) Init

func (n *Note) Init() tea.Cmd

Init initializes the note field.

func (*Note) KeyBinds

func (n *Note) KeyBinds() []key.Binding

KeyBinds returns the help message for the note field.

func (*Note) Next

func (n *Note) Next(show bool) *Note

Next sets whether or not to show the next button.

Title
Description

[ Next ]

func (*Note) NextLabel

func (n *Note) NextLabel(label string) *Note

NextLabel sets the next button label.

func (*Note) Run

func (n *Note) Run() error

Run runs the note field.

func (*Note) Skip

func (n *Note) Skip() bool

Skip returns whether the note should be skipped or should be blocking.

func (*Note) Title

func (n *Note) Title(title string) *Note

Title sets the note field's title.

This title will be static, for dynamic titles use `TitleFunc`.

func (*Note) TitleFunc

func (n *Note) TitleFunc(f func() string, bindings any) *Note

TitleFunc sets the title func of the note field.

The TitleFunc will be re-evaluated when the binding of the TitleFunc changes. This is useful when you want to display dynamic content and update the title of a note when another part of your form changes.

See README.md#Dynamic for more usage information.

func (*Note) Update

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

Update updates the note field.

func (*Note) View

func (n *Note) View() string

View renders the note field.

func (*Note) WithAccessible

func (n *Note) WithAccessible(accessible bool) Field

WithAccessible sets the accessible mode of the note field.

func (*Note) WithHeight

func (n *Note) WithHeight(height int) Field

WithHeight sets the height of the note field.

func (*Note) WithKeyMap

func (n *Note) WithKeyMap(k *KeyMap) Field

WithKeyMap sets the keymap on a note field.

func (*Note) WithPosition

func (n *Note) WithPosition(p FieldPosition) Field

WithPosition sets the position information of the note field.

func (*Note) WithTheme

func (n *Note) WithTheme(theme *Theme) Field

WithTheme sets the theme on a note field.

func (*Note) WithWidth

func (n *Note) WithWidth(width int) Field

WithWidth sets the width of the note field.

func (*Note) Zoom

func (n *Note) Zoom() bool

Zoom returns whether the note should be zoomed.

type NoteKeyMap

type NoteKeyMap struct {
	Next   key.Binding
	Prev   key.Binding
	Submit key.Binding
}

NoteKeyMap is the keybindings for note fields.

type Option

type Option[T comparable] struct {
	Key   string
	Value T
	// contains filtered or unexported fields
}

Option is an option for select fields.

func NewOption

func NewOption[T comparable](key string, value T) Option[T]

NewOption returns a new select option.

func NewOptions

func NewOptions[T comparable](values ...T) []Option[T]

NewOptions returns new options from a list of values.

func (Option[T]) Selected

func (o Option[T]) Selected(selected bool) Option[T]

Selected sets whether the option is currently selected.

func (Option[T]) String

func (o Option[T]) String() string

String returns the key of the option.

type PointerAccessor

type PointerAccessor[T any] struct {
	// contains filtered or unexported fields
}

PointerAccessor allows field value to be exposed as a pointed variable.

func NewPointerAccessor

func NewPointerAccessor[T any](value *T) *PointerAccessor[T]

NewPointerAccessor returns a new pointer accessor.

func (*PointerAccessor[T]) Get

func (a *PointerAccessor[T]) Get() T

Get gets the value.

func (*PointerAccessor[T]) Set

func (a *PointerAccessor[T]) Set(value T)

Set sets the value.

type Select

type Select[T comparable] struct {
	// contains filtered or unexported fields
}

Select is a select field.

A select field is a field that allows the user to select from a list of options. The options can be provided statically or dynamically using Options or OptionsFunc. The options can be filtered using "/" and navigation is done using j/k, up/down, or ctrl+n/ctrl+p keys.

func NewSelect

func NewSelect[T comparable]() *Select[T]

NewSelect creates a new select field.

A select field is a field that allows the user to select from a list of options. The options can be provided statically or dynamically using Options or OptionsFunc. The options can be filtered using "/" and navigation is done using j/k, up/down, or ctrl+n/ctrl+p keys.

func (*Select[T]) Accessor

func (s *Select[T]) Accessor(accessor Accessor[T]) *Select[T]

Accessor sets the accessor of the select field.

func (*Select[T]) Blur

func (s *Select[T]) Blur() tea.Cmd

Blur blurs the select field.

func (*Select[T]) Description

func (s *Select[T]) Description(description string) *Select[T]

Description sets the description of the select field.

This description will be static, for dynamic descriptions use `DescriptionFunc`.

func (*Select[T]) DescriptionFunc

func (s *Select[T]) DescriptionFunc(f func() string, bindings any) *Select[T]

DescriptionFunc sets the description func of the select field.

This DescriptionFunc will be re-evaluated when the binding of the DescriptionFunc changes. This is useful when you want to display dynamic content and update the description when another part of your form changes.

See README#Dynamic for more usage information.

func (*Select[T]) Error

func (s *Select[T]) Error() error

Error returns the error of the select field.

func (*Select[T]) Filtering

func (s *Select[T]) Filtering(filtering bool) *Select[T]

Filtering sets the filtering state of the select field.

func (*Select[T]) Focus

func (s *Select[T]) Focus() tea.Cmd

Focus focuses the select field.

func (*Select[T]) GetKey

func (s *Select[T]) GetKey() string

GetKey returns the key of the field.

func (*Select[T]) GetValue

func (s *Select[T]) GetValue() any

GetValue returns the value of the field.

func (*Select[T]) Height

func (s *Select[T]) Height(height int) *Select[T]

Height sets the height of the select field. If the number of options exceeds the height, the select field will become scrollable.

func (*Select[T]) Init

func (s *Select[T]) Init() tea.Cmd

Init initializes the select field.

func (*Select[T]) Inline

func (s *Select[T]) Inline(v bool) *Select[T]

Inline sets whether the select input should be inline.

func (*Select[T]) Key

func (s *Select[T]) Key(key string) *Select[T]

Key sets the key of the select field which can be used to retrieve the value after submission.

func (*Select[T]) KeyBinds

func (s *Select[T]) KeyBinds() []key.Binding

KeyBinds returns the help keybindings for the select field.

func (*Select[T]) Options

func (s *Select[T]) Options(options ...Option[T]) *Select[T]

Options sets the options of the select field.

This is what your user will select from.

Title Description

-> Option 1
   Option 2
   Option 3

These options will be static, for dynamic options use `OptionsFunc`.

func (*Select[T]) OptionsFunc

func (s *Select[T]) OptionsFunc(f func() []Option[T], bindings any) *Select[T]

OptionsFunc sets the options func of the select field.

This OptionsFunc will be re-evaluated when the binding of the OptionsFunc changes. This is useful when you want to display dynamic content and update the options when another part of your form changes.

For example, changing the state / provinces, based on the selected country.

   huh.NewSelect[string]().
	    Options(huh.NewOptions("United States", "Canada", "Mexico")...).
	    Value(&country).
	    Title("Country").
	    Height(5),

	huh.NewSelect[string]().
	  Title("State / Province"). // This can also be made dynamic with `TitleFunc`.
	  OptionsFunc(func() []huh.Option[string] {
	    s := states[country]
	    time.Sleep(1000 * time.Millisecond)
	    return huh.NewOptions(s...)
	}, &country),

See examples/dynamic/dynamic-country/main.go for the full example.

func (*Select[T]) Run

func (s *Select[T]) Run() error

Run runs the select field.

func (*Select[T]) Skip

func (*Select[T]) Skip() bool

Skip returns whether the select should be skipped or should be blocking.

func (*Select[T]) Title

func (s *Select[T]) Title(title string) *Select[T]

Title sets the title of the select field.

This title will be static, for dynamic titles use `TitleFunc`.

func (*Select[T]) TitleFunc

func (s *Select[T]) TitleFunc(f func() string, bindings any) *Select[T]

TitleFunc sets the title func of the select field.

This TitleFunc will be re-evaluated when the binding of the TitleFunc changes. This when you want to display dynamic content and update the title when another part of your form changes.

See README#Dynamic for more usage information.

func (*Select[T]) Update

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

Update updates the select field.

func (*Select[T]) Validate

func (s *Select[T]) Validate(validate func(T) error) *Select[T]

Validate sets the validation function of the select field.

func (*Select[T]) Value

func (s *Select[T]) Value(value *T) *Select[T]

Value sets the value of the select field.

func (*Select[T]) View

func (s *Select[T]) View() string

View renders the select field.

func (*Select[T]) WithAccessible

func (s *Select[T]) WithAccessible(accessible bool) Field

WithAccessible sets the accessible mode of the select field.

func (*Select[T]) WithHeight

func (s *Select[T]) WithHeight(height int) Field

WithHeight sets the height of the select field.

func (*Select[T]) WithKeyMap

func (s *Select[T]) WithKeyMap(k *KeyMap) Field

WithKeyMap sets the keymap on a select field.

func (*Select[T]) WithPosition

func (s *Select[T]) WithPosition(p FieldPosition) Field

WithPosition sets the position of the select field.

func (*Select[T]) WithTheme

func (s *Select[T]) WithTheme(theme *Theme) Field

WithTheme sets the theme of the select field.

func (*Select[T]) WithWidth

func (s *Select[T]) WithWidth(width int) Field

WithWidth sets the width of the select field.

func (*Select[T]) Zoom

func (*Select[T]) Zoom() bool

Zoom returns whether the input should be zoomed.

type SelectKeyMap

type SelectKeyMap struct {
	Next         key.Binding
	Prev         key.Binding
	Up           key.Binding
	Down         key.Binding
	HalfPageUp   key.Binding
	HalfPageDown key.Binding
	GotoTop      key.Binding
	GotoBottom   key.Binding
	Left         key.Binding
	Right        key.Binding
	Filter       key.Binding
	SetFilter    key.Binding
	ClearFilter  key.Binding
	Submit       key.Binding
}

SelectKeyMap is the keybindings for select fields.

type Text

type Text struct {
	// contains filtered or unexported fields
}

Text is a text field.

A text box is responsible for getting multi-line input from the user. Use it to gather longer-form user input. The Text field can be filled with an EDITOR.

func NewText

func NewText() *Text

NewText creates a new text field.

A text box is responsible for getting multi-line input from the user. Use it to gather longer-form user input. The Text field can be filled with an EDITOR.

func (*Text) Accessor

func (t *Text) Accessor(accessor Accessor[string]) *Text

Accessor sets the accessor of the text field.

func (*Text) Blur

func (t *Text) Blur() tea.Cmd

Blur blurs the text field.

func (*Text) CharLimit

func (t *Text) CharLimit(charlimit int) *Text

CharLimit sets the character limit of the text field.

func (*Text) Description

func (t *Text) Description(description string) *Text

Description sets the description of the text field.

This description will be static, for dynamic description use `DescriptionFunc`.

func (*Text) DescriptionFunc

func (t *Text) DescriptionFunc(f func() string, bindings any) *Text

DescriptionFunc sets the description func of the text field.

The DescriptionFunc will be re-evaluated when the binding of the DescriptionFunc changes. This is useful when you want to display dynamic content and update the description when another part of your form changes.

See README#Dynamic for more usage information.

func (*Text) Editor

func (t *Text) Editor(editor ...string) *Text

Editor specifies which editor to use.

The first argument provided is used as the editor command (vim, nvim, nano, etc...) The following (optional) arguments provided are passed as arguments to the editor command.

func (*Text) EditorExtension

func (t *Text) EditorExtension(extension string) *Text

EditorExtension specifies arguments to pass into the editor.

func (*Text) Error

func (t *Text) Error() error

Error returns the error of the text field.

func (*Text) Focus

func (t *Text) Focus() tea.Cmd

Focus focuses the text field.

func (*Text) GetKey

func (t *Text) GetKey() string

GetKey returns the key of the field.

func (*Text) GetValue

func (t *Text) GetValue() any

GetValue returns the value of the field.

func (*Text) Init

func (t *Text) Init() tea.Cmd

Init initializes the text field.

func (*Text) Key

func (t *Text) Key(key string) *Text

Key sets the key of the text field.

func (*Text) KeyBinds

func (t *Text) KeyBinds() []key.Binding

KeyBinds returns the help message for the text field.

func (*Text) Lines

func (t *Text) Lines(lines int) *Text

Lines sets the number of lines to show of the text field.

func (*Text) Placeholder

func (t *Text) Placeholder(str string) *Text

Placeholder sets the placeholder of the text field.

This placeholder will be static, for dynamic placeholders use `PlaceholderFunc`.

func (*Text) PlaceholderFunc

func (t *Text) PlaceholderFunc(f func() string, bindings any) *Text

PlaceholderFunc sets the placeholder func of the text field.

The PlaceholderFunc will be re-evaluated when the binding of the PlaceholderFunc changes. This is useful when you want to display dynamic content and update the placeholder when another part of your form changes.

See README#Dynamic for more usage information.

func (*Text) Run

func (t *Text) Run() error

Run runs the text field.

func (*Text) ShowLineNumbers

func (t *Text) ShowLineNumbers(show bool) *Text

ShowLineNumbers sets whether or not to show line numbers.

func (*Text) Skip

func (*Text) Skip() bool

Skip returns whether the textarea should be skipped or should be blocking.

func (*Text) Title

func (t *Text) Title(title string) *Text

Title sets the text field's title.

This title will be static, for dynamic titles use `TitleFunc`.

func (*Text) TitleFunc

func (t *Text) TitleFunc(f func() string, bindings any) *Text

TitleFunc sets the text field's title func.

The TitleFunc will be re-evaluated when the binding of the TitleFunc changes. This is useful when you want to display dynamic content and update the title when another part of your form changes.

See README#Dynamic for more usage information.

func (*Text) Update

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

Update updates the text field.

func (*Text) Validate

func (t *Text) Validate(validate func(string) error) *Text

Validate sets the validation function of the text field.

func (*Text) Value

func (t *Text) Value(value *string) *Text

Value sets the value of the text field.

func (*Text) View

func (t *Text) View() string

View renders the text field.

func (*Text) WithAccessible

func (t *Text) WithAccessible(accessible bool) Field

WithAccessible sets the accessible mode of the text field.

func (*Text) WithHeight

func (t *Text) WithHeight(height int) Field

WithHeight sets the height of the text field.

func (*Text) WithKeyMap

func (t *Text) WithKeyMap(k *KeyMap) Field

WithKeyMap sets the keymap on a text field.

func (*Text) WithPosition

func (t *Text) WithPosition(p FieldPosition) Field

WithPosition sets the position information of the text field.

func (*Text) WithTheme

func (t *Text) WithTheme(theme *Theme) Field

WithTheme sets the theme on a text field.

func (*Text) WithWidth

func (t *Text) WithWidth(width int) Field

WithWidth sets the width of the text field.

func (*Text) Zoom

func (*Text) Zoom() bool

Zoom returns whether the note should be zoomed.

type TextInputStyles

type TextInputStyles struct {
	Cursor      lipgloss.Style
	CursorText  lipgloss.Style
	Placeholder lipgloss.Style
	Prompt      lipgloss.Style
	Text        lipgloss.Style
}

TextInputStyles are the styles for text inputs.

type TextKeyMap

type TextKeyMap struct {
	Next    key.Binding
	Prev    key.Binding
	NewLine key.Binding
	Editor  key.Binding
	Submit  key.Binding
}

TextKeyMap is the keybindings for text fields.

type Theme

type Theme struct {
	Form           lipgloss.Style
	Group          lipgloss.Style
	FieldSeparator lipgloss.Style
	Blurred        FieldStyles
	Focused        FieldStyles
	Help           help.Styles
}

Theme is a collection of styles for components of the form. Themes can be applied to a form using the WithTheme option.

func ThemeBase

func ThemeBase() *Theme

ThemeBase returns a new base theme with general styles to be inherited by other themes.

func ThemeBase16

func ThemeBase16() *Theme

ThemeBase16 returns a new theme based on the base16 color scheme.

func ThemeCatppuccin

func ThemeCatppuccin() *Theme

ThemeCatppuccin returns a new theme based on the Catppuccin color scheme.

func ThemeCharm

func ThemeCharm() *Theme

ThemeCharm returns a new theme based on the Charm color scheme.

func ThemeDracula

func ThemeDracula() *Theme

ThemeDracula returns a new theme based on the Dracula color scheme.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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