forms

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2026 License: MIT Imports: 10 Imported by: 4 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package forms provides keys.Action-driven forms and confirm dialogs for viewkit terminal UIs.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool added in v0.1.6

func Bool(vals map[string]any, key string) bool

Bool returns the boolean value stored under key. Missing keys and non-bool values yield false.

func Int added in v0.1.6

func Int(vals map[string]any, key string) int

Int returns the value stored under key as an integer. Text fields hold strings, so the common case parses base-10 text, but already-numeric values are accepted too. Missing keys and unparsable text yield 0.

func Match added in v0.1.9

func Match(vals []string, prefix string) []string

Match filters vals down to those extending prefix, case-insensitively. An exact match is dropped: there is nothing left to complete. Results are deduplicated and sorted so the candidate list does not reorder as the vocabulary is rebuilt.

func Raw added in v0.1.9

func Raw(vals map[string]any, key string) string

Raw returns the string value stored under key verbatim. Seeding a rebuilt form uses it rather than Str, so a trailing delimiter or space the user deliberately typed survives the rebuild.

func SelectFirst added in v0.1.6

func SelectFirst(options []string, cur string) []string

SelectFirst returns options reordered so cur leads, for select fields that should open on their current value. The relative order of the remaining options is preserved, and duplicates of cur beyond the first are kept. The result is always a fresh slice; options is never mutated.

func SelectIndex added in v0.1.6

func SelectIndex(options []string, want string) int

SelectIndex returns the position of want in options, for seeding Field.Selected. Unknown and empty values select the first option.

func Str added in v0.1.6

func Str(vals map[string]any, key string) string

Str returns the string value stored under key, with surrounding whitespace trimmed. Missing keys and non-string values yield "".

func Strings added in v0.1.6

func Strings(vals map[string]any, key string) []string

Strings returns the multi-select value stored under key. Missing keys and values of other types yield nil.

Types

type Confirm

type Confirm struct {
	Title    string
	Message  string
	YesLabel string
	NoLabel  string
	Yes      bool
}

Confirm is a modal yes/no dialog. The zero value is usable: YesLabel and NoLabel default to "Yes" and "No", and Yes holds the current selection.

func (*Confirm) Handle

func (c *Confirm) Handle(a keys.Action) Result

Handle applies a key action: Left/Dec selects yes, Right/Inc selects no, Confirm returns Submitted (with the answer left in c.Yes), and Cancel returns Cancelled. Every other action leaves the dialog Pending.

func (Confirm) Overlay

func (c Confirm) Overlay(bg string, f layout.Frame, pos ...layout.OverlayPos) string

Overlay renders the dialog and composes it over the background bg with layout.Overlay, placed at pos (centered by default).

func (Confirm) Render

func (c Confirm) Render(f layout.Frame) string

Render draws the dialog as a titled panel sized to f: the optional Message followed by the yes/no toggle.

type Field

type Field struct {
	// Key names the field's entry in Form.Values.
	Key string
	// Label is the caption rendered next to (or above) the input.
	Label string
	// Kind selects the widget; the zero value is FieldText.
	Kind FieldKind

	// Options are the choices for select, multiselect, and radio fields.
	Options []string

	// Text is the current content of text and multiline fields.
	Text string
	// On is the state of a toggle field.
	On bool
	// Selected indexes Options: the value of select and radio fields, and
	// the highlight cursor of multiselect fields.
	Selected int
	// Checked marks which Options indices a multiselect field has on.
	Checked map[int]bool

	// Secret masks text as bullets when rendering and disables suggestions.
	Secret bool

	// Suggest proposes completions for the token being typed. Text and
	// multiline fields only; a nil Suggester disables completion.
	Suggest Suggester
	// Delim splits the field into independently completed tokens, e.g. ","
	// for a comma-separated list or " " for a search expression. Empty means
	// the whole text is one token.
	Delim string
}

Field is a single input in a Form. Key, Label, and Kind describe it; the remaining fields hold per-kind state and can be pre-set to seed a value.

func Multiline added in v0.2.0

func Multiline(key, label string) Field

Multiline builds a multi-line text field.

func Multiselect added in v0.2.0

func Multiselect(key, label string, options ...string) Field

Multiselect builds a multi-choice field over options.

func Radio added in v0.2.0

func Radio(key, label string, options ...string) Field

Radio builds a one-of field over options rendered as radio buttons.

func Select added in v0.2.0

func Select(key, label string, options ...string) Field

Select builds a single-choice field over options.

func Text added in v0.2.0

func Text(key, label string) Field

Text builds a single-line text field.

func Toggle added in v0.2.0

func Toggle(key, label string, on bool) Field

Toggle builds an on/off field starting at on.

func (*Field) Value

func (fd *Field) Value() any

Value returns the field's current value by kind: bool for toggles, the selected option for select and radio ("" when Selected is out of range), []string of checked options for multiselect, and the raw Text otherwise.

func (Field) WithDelim added in v0.2.0

func (fd Field) WithDelim(d string) Field

WithDelim splits the text into independently completed tokens.

func (Field) WithSecret added in v0.2.0

func (fd Field) WithSecret() Field

WithSecret masks the field's input.

func (Field) WithSelected added in v0.2.0

func (fd Field) WithSelected(i int) Field

WithSelected pre-selects the option at index i (select and radio fields).

func (Field) WithSuggest added in v0.2.0

func (fd Field) WithSuggest(s Suggester) Field

WithSuggest attaches a completion source (text and multiline fields).

func (Field) WithText added in v0.2.0

func (fd Field) WithText(v string) Field

WithText seeds the field's text value.

type FieldKind

type FieldKind int

FieldKind selects the input widget a Field presents and which of its state fields carry the value.

const (
	// FieldText is a single-line text input; the value lives in Text.
	FieldText FieldKind = iota

	// FieldMultiline is a text input that also accepts newlines.
	FieldMultiline

	// FieldSelect picks one of Options, cycled in place with left/right.
	FieldSelect

	// FieldMultiselect toggles any subset of Options via Checked.
	FieldMultiselect

	// FieldRadio picks one of Options, listed vertically with radio marks.
	FieldRadio

	// FieldToggle is an on/off switch backed by On.
	FieldToggle
)

type Form

type Form struct {
	Fields []Field
	// contains filtered or unexported fields
}

Form is a vertical stack of Fields with a single focus cursor. Build one with NewForm so suggestions for the initially focused field are primed.

Example
package main

import (
	"github.com/codyconfer/viewkit/forms"
	"github.com/codyconfer/viewkit/keys"
	"github.com/codyconfer/viewkit/layout"
)

func main() {
	fm := forms.NewForm(
		forms.Field{Key: "name", Label: "Name", Kind: forms.FieldText},
		forms.Field{
			Key:     "risk",
			Label:   "Risk",
			Kind:    forms.FieldSelect,
			Options: []string{"low", "med", "high"},
		},
		forms.Field{Key: "auto", Label: "Auto", Kind: forms.FieldToggle},
	)

	fm.Insert("example")
	fm.Handle(keys.Down)
	fm.Handle(keys.Right)
	fm.Handle(keys.Down)
	fm.Handle(keys.Confirm)

	_ = fm.Values()
	_ = fm.Render(layout.NewFrame(60), "SETTINGS")
}

func NewForm

func NewForm(fields ...Field) *Form

NewForm builds a form over fields, focused on the first one, and computes its initial suggestion candidates.

func (*Form) AcceptSuggestion added in v0.1.9

func (fm *Form) AcceptSuggestion() bool

AcceptSuggestion writes the active candidate into the focused field, replacing the token being typed. It reports false when there is nothing to accept, which lets a host give the accept key a second meaning.

func (*Form) CycleSuggestion added in v0.1.9

func (fm *Form) CycleSuggestion(delta int)

CycleSuggestion moves through the candidate list. It wraps at both ends rather than clamping like field navigation does: a short list is meant to be cycled repeatedly, and stopping at the last entry hides the first.

func (*Form) FocusKey added in v0.1.13

func (fm *Form) FocusKey(key string) bool

FocusKey moves focus to the field carrying key and reports whether one was found. Focus is left untouched when no field has that key, and an empty key never matches.

func (*Form) Focused

func (fm *Form) Focused() *Field

Focused returns a pointer to the field under the focus cursor (clamping the cursor into range first), or nil when the form has no fields.

func (*Form) FocusedKey added in v0.1.13

func (fm *Form) FocusedKey() string

FocusedKey is the Key of the focused field, or "" when the form has no fields. Paired with FocusKey it lets a host rebuild a form without losing the caret.

func (*Form) Handle

func (fm *Form) Handle(a keys.Action) bool

Handle applies a key action and reports whether it was consumed: Up/Down and FocusPrev/FocusNext move focus, Left/Right (Dec/Inc) adjust the focused field, Erase deletes its last rune, and CompleteNext/CompletePrev cycle suggestions. Confirm activates toggle and multiselect fields; on other kinds it returns false so a host can treat it as form submission.

func (*Form) Insert

func (fm *Form) Insert(s string)

Insert appends s to the end of the focused text or multiline field's Text (there is no in-text caret) and refreshes suggestions. Non-printable runes are dropped, newlines survive only in multiline fields, and other field kinds ignore the input entirely.

func (*Form) Overlay

func (fm *Form) Overlay(bg string, f layout.Frame, title string, pos ...layout.OverlayPos) string

Overlay renders the form and composes it over the background bg with layout.Overlay, placed at pos (centered by default).

func (*Form) Render

func (fm *Form) Render(f layout.Frame, title string) string

Render draws every field as a titled panel sized to f, marking the focused one and listing its suggestion candidates beneath it.

func (*Form) RenderWindow added in v0.1.6

func (fm *Form) RenderWindow(f layout.Frame, title string, maxLines int) string

RenderWindow renders at most maxLines of field rows, scrolled to keep the focused field visible. A maxLines of zero renders every field.

func (*Form) Suggestions added in v0.1.9

func (fm *Form) Suggestions() []string

Suggestions lists the completions offered for the focused field, most relevant first. It is empty when the field has no Suggester or nothing matches what has been typed.

func (*Form) Values

func (fm *Form) Values() map[string]any

Values returns every field's Value keyed by its Key. Fields sharing a key collapse to the last one's value.

type Result

type Result int

Result is the outcome of feeding a key action to a Confirm dialog.

const (
	// Pending means the dialog is still open awaiting a decision.
	Pending Result = iota

	// Submitted means the confirm key was pressed; the chosen answer is in
	// Confirm.Yes.
	Submitted

	// Cancelled means the dialog was dismissed with the cancel key.
	Cancelled
)

type Suggester added in v0.1.9

type Suggester func(prefix string) []string

Suggester proposes completions for the token a text field is currently building. It receives that token — not the whole field — so a delimited field can complete each entry independently.

func Static added in v0.1.9

func Static(vals ...string) Suggester

Static suggests from a fixed vocabulary.

func SuggestFunc added in v0.2.0

func SuggestFunc(load func() []string) Suggester

SuggestFunc suggests from a vocabulary read fresh on every keystroke, for values that change while the form is open.

Jump to

Keyboard shortcuts

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