Documentation
¶
Overview ¶
Package termform is the persistence-neutral form engine the TUI's editor and popups are built from — the Go port of Ruby's lib/term_form/.
It owns four things and nothing else: the event vocabulary, the field protocol, the focus/commit lifecycle, and a renderer-neutral render model. It knows nothing about tasks, terminals, colors, or files. That separation is what makes SAVE ON BLUR testable: the whole "leaving a dirty field asks the host to persist it, and the host answers accept or reject" handshake is a pure state machine here, and the task-domain adapter above it only supplies values and answers.
The one structural difference from Ruby: Ruby's values are untyped objects and every field asserts the shape it accepts. Go has no such thing, so values are `any` and each field normalizes into its OWN shape (string, bool, []string, *temporal.Value). Equality — which decides dirty, which decides whether a commit is even requested — therefore goes through equalValues rather than `==`, because two []string values that are `==` in Ruby are two different slice headers here.
Index ¶
- Variables
- func ClusterWidth(cluster string) int
- func Command(event Event, kind EventType, keys ...string) bool
- func DecodedKey(event Event) string
- func Graphemes(text string) []string
- type Base
- func (b *Base) CursorFor(any, Context) *int
- func (b *Base) FocusGained(any, Context)
- func (b *Base) HandleEvent(Event, any, Context) *Result
- func (b *Base) Initial() any
- func (b *Base) InitialBaseline() any
- func (b *Base) IsEnabled(context Context) bool
- func (b *Base) IsRequired(context Context) bool
- func (b *Base) IsVisible(context Context) bool
- func (b *Base) Key() string
- func (b *Base) LabelFor(Context) string
- func (b *Base) Metadata() map[string]any
- func (b *Base) MetadataFor(any, Context) map[string]any
- func (b *Base) NormalizeValue(value any) any
- func (b *Base) SyncValue(any)
- func (b *Base) ValidationErrors(value any, context Context) []string
- type Calendar
- type ChoiceField
- func (c *ChoiceField) CursorFor(any, Context) *int
- func (c *ChoiceField) FilteredOptions(context Context) []Option
- func (c *ChoiceField) HighlightIndex() int
- func (c *ChoiceField) HighlightedOption(context Context) *Option
- func (c *ChoiceField) MetadataFor(value any, context Context) map[string]any
- func (c *ChoiceField) Open() bool
- func (c *ChoiceField) Options(context Context) []Option
- func (c *ChoiceField) Query() string
- func (c *ChoiceField) ValidationErrors(value any, context Context) []string
- type CommitRequest
- type Confirm
- type Context
- type DateHooks
- type DateInput
- func (d *DateInput) Cursor() int
- func (d *DateInput) CursorFor(any, Context) *int
- func (d *DateInput) HandleEvent(event Event, value any, context Context) *Result
- func (d *DateInput) MetadataFor(value any, _ Context) map[string]any
- func (d *DateInput) NormalizeValue(value any) any
- func (d *DateInput) PickerDate() (temporal.Date, bool)
- func (d *DateInput) PickerOpen() bool
- func (d *DateInput) SetText(text string)
- func (d *DateInput) SyncValue(value any)
- func (d *DateInput) Text() string
- func (d *DateInput) ValidationErrors(value any, context Context) []string
- type Event
- type EventType
- type Field
- type Form
- func (f *Form) AcceptCommit(fresh map[string]any, token int) (Transition, error)
- func (f *Form) AnyDirty() bool
- func (f *Form) Baseline(key string) any
- func (f *Form) ChangedKeys() []string
- func (f *Form) Context() Context
- func (f *Form) Dirty(key string) bool
- func (f *Form) Errors() map[string][]string
- func (f *Form) Field(key string) Field
- func (f *Form) Fields() []Field
- func (f *Form) Focus(key string, event Event, direction string) Transition
- func (f *Form) FocusKey() string
- func (f *Form) FocusNext(event Event) Transition
- func (f *Form) FocusPrevious(event Event) Transition
- func (f *Form) FocusableFields() []Field
- func (f *Form) Handle(event Event) Transition
- func (f *Form) HandleKey(raw string) Transition
- func (f *Form) Pending() bool
- func (f *Form) PendingCommit() *CommitRequest
- func (f *Form) Refresh(fresh map[string]any) (Transition, error)
- func (f *Form) RejectCommit(fieldErrors map[string][]string, message string, token int) (Transition, error)
- func (f *Form) RenderModel() RenderModel
- func (f *Form) RequestCommit(intendedFocus, direction, fieldKey string, event Event) Transition
- func (f *Form) SetValue(key string, value any, event Event) Transition
- func (f *Form) Valid() bool
- func (f *Form) Validate() map[string][]string
- func (f *Form) Value(key string) any
- func (f *Form) Values() map[string]any
- func (f *Form) VisibleFields() []Field
- type Group
- type Input
- type KeyMap
- type MultiSelect
- type Option
- type RenderGroup
- type RenderModel
- type Result
- type Row
- type Select
- type TextArea
- type TextField
- func (t *TextField) Cursor() int
- func (t *TextField) CursorFor(any, Context) *int
- func (t *TextField) HandleEvent(event Event, _ any, _ Context) *Result
- func (t *TextField) HandleRawKey(key string) input.Result
- func (t *TextField) NormalizeValue(value any) any
- func (t *TextField) Paste(text string) input.Result
- func (t *TextField) SyncValue(value any)
- func (t *TextField) Text() string
- type Transition
- type TransitionType
- type View
Constants ¶
This section is empty.
Variables ¶
var ( ErrDuplicateKey = errors.New("duplicate termform key") ErrUnknownKey = errors.New("unknown termform field key") ErrNoPending = errors.New("no commit is pending") ErrStaleToken = errors.New("commit token does not match") )
ErrDuplicateKey and friends are the construction refusals. They are errors rather than panics because a form is built from data (a task snapshot) and a malformed one must be reportable, not fatal.
var DefaultBindings = map[string]EventType{ "\t": EventNext, "\x1b[B": EventNext, "\x1b[Z": EventPrevious, "\x1b[A": EventPrevious, "\r": EventCommit, "\n": EventCommit, "\x1b": EventCancel, "\x1b\x1b": EventCancel, }
DefaultBindings is Ruby's KeyMap::DEFAULT_BINDINGS. Tab and ↓ both mean "next": a form is a vertical list, and a user who presses ↓ in it expects to leave the field — which is what makes save-on-blur reachable without tab.
var KeyBytes = input.KeyBytes
KeyBytes is the byte sequence a named key sends, Ruby's Event::KEY_BYTES. It is re-exported from the input primitive rather than re-declared, so the editor and the form engine can never disagree about what "up" means.
Functions ¶
func ClusterWidth ¶
ClusterWidth is one grapheme cluster's width in terminal cells.
func Command ¶
Command reports Ruby's DecodedEvent.command?: the event IS the semantic command, or it is a key event carrying one of the raw sequences that mean it.
func DecodedKey ¶
DecodedKey is Fields::DecodedEvent.key: the byte sequence a field should act on, following the DECODED semantics rather than the transport bytes.
The distinction matters at exactly one place and it is load-bearing: the default key map folds ↑/↓ into :previous/:next navigation events, and a text area still has to be able to read them as vertical cursor motion. So a navigation event exposes its raw bytes and nothing else.
Types ¶
type Base ¶
type Base struct {
FieldKey string
Label string
Value any
// Baseline defaults to Value when BaselineSet is false, which is Ruby's
// `baseline: UNSET` sentinel: a field with no separate baseline starts clean.
Baseline any
BaselineSet bool
// Visible, Enabled and Required are the reactive properties. A nil func is
// the constant in VisibleFixed/EnabledFixed/RequiredFixed.
Visible func(Context) bool
VisibleFixed bool
Enabled func(Context) bool
EnabledFixed bool
Required func(Context) bool
RequiredFixed bool
// Validate is the field's own rules. Each returns "" for "no problem".
Validate []func(value any, context Context) string
Meta map[string]any
}
Base is the default Field implementation every concrete field embeds.
func NewBase ¶
NewBase fills the defaults a caller almost always wants: visible, enabled, not required.
func (*Base) FocusGained ¶
func (*Base) InitialBaseline ¶
func (*Base) IsRequired ¶
func (*Base) NormalizeValue ¶
func (*Base) ValidationErrors ¶
ValidationErrors is the required check plus the field's own validators, in Ruby's order — "is required" first, so an empty required field says the obvious thing rather than a parse complaint about "".
type Calendar ¶
type Calendar struct {
Month temporal.Date
Selected temporal.Date
WeekdayLabels []string
Weeks [][]temporal.Date
}
Calendar is a month grid for the picker.
func CalendarFor ¶
CalendarFor builds the six-week grid around a date, Monday first.
type ChoiceField ¶
type ChoiceField struct {
Base
// contains filtered or unexported fields
}
ChoiceField is the shared searchable-option behavior.
func (*ChoiceField) CursorFor ¶
func (c *ChoiceField) CursorFor(any, Context) *int
CursorFor exposes the search caret only when the field is searchable.
func (*ChoiceField) FilteredOptions ¶
func (c *ChoiceField) FilteredOptions(context Context) []Option
FilteredOptions is the option set narrowed by the live query.
func (*ChoiceField) HighlightIndex ¶
func (c *ChoiceField) HighlightIndex() int
HighlightIndex is the highlighted option's position in the filtered list.
func (*ChoiceField) HighlightedOption ¶
func (c *ChoiceField) HighlightedOption(context Context) *Option
HighlightedOption is the option the cursor is on, or nil.
func (*ChoiceField) MetadataFor ¶
func (c *ChoiceField) MetadataFor(value any, context Context) map[string]any
MetadataFor publishes the option list, selection and open state the renderer paints from.
func (*ChoiceField) Open ¶
func (c *ChoiceField) Open() bool
Open reports whether the option list is showing.
func (*ChoiceField) Options ¶
func (c *ChoiceField) Options(context Context) []Option
Options is the full option set for the current context.
func (*ChoiceField) ValidationErrors ¶
func (c *ChoiceField) ValidationErrors(value any, context Context) []string
ValidationErrors adds "this selection no longer exists" to the base rules, which is what catches a context or tag deleted while the form was open.
type CommitRequest ¶
type CommitRequest struct {
Token int
Values map[string]any
ChangedKeys []string
FocusKey string
FieldKey string
ProposedValue any
ExpectedBaseline any
IntendedFocus string
Direction string
}
CommitRequest is one save-on-blur handshake in flight.
It carries the EXPECTED BASELINE as well as the proposed value, because the host's answer arrives later and the field may have been refreshed in between. Without the expectation, accepting a stale commit would silently overwrite an external edit — the exact failure save-on-blur exists to prevent.
type Confirm ¶
Confirm is a yes/no field.
func NewConfirm ¶
NewConfirm builds one.
func (*Confirm) HandleEvent ¶
HandleEvent accepts y/n, left/right, space and Return.
func (*Confirm) MetadataFor ¶
MetadataFor publishes the two labels and which one is selected.
func (*Confirm) NormalizeValue ¶
NormalizeValue coerces anything to a bool.
type Context ¶
type Context struct {
Values map[string]any
Baselines map[string]any
FocusedKey string
Errors map[string][]string
}
Context is the read-only view of the form a field sees while deciding anything: every value, every baseline, who has focus, and the current errors.
It is passed BY VALUE and never mutated, which is what lets a field's validator read a sibling field — "a recurrence needs one of the two date fields" is a rule about the form, not about the field.
func (Context) ChangedKeys ¶
ChangedKeys is every dirty key, in a stable order. Ruby iterates a Hash whose order is insertion order; a Go map's is randomized, so this sorts — otherwise two runs over identical data would produce different commit requests.
type DateHooks ¶
type DateHooks struct {
// Parse turns typed text into a value, or reports why it cannot.
Parse func(text string, today temporal.Date) (any, error)
// Format renders a value as the text the editor holds.
Format func(value any) string
// Parsed reports whether a value is a real parsed value rather than
// leftover unparseable text.
Parsed func(value any) bool
// DateOf extracts the calendar date a value sits on.
DateOf func(value any) (temporal.Date, bool)
// WithDate rebuilds a value on a different calendar date, keeping
// everything else the value carries.
WithDate func(date temporal.Date, current any) any
}
DateHooks are the four things a date field's HOST owns: how text becomes a value, how a value becomes text, and how a value and a calendar date convert into each other.
They are a struct of functions rather than subclass overrides because the task editor's date value is not a Date — it is a whole temporal value with a wall time and a zone — and the calendar picker still has to be able to move it a day at a time without losing the rest.
type DateInput ¶
type DateInput struct {
Base
// contains filtered or unexported fields
}
DateInput is a text field that also opens a calendar picker.
func NewDateInput ¶
func NewDateInput(base Base, hooks DateHooks, today func() temporal.Date, suggestions []string, exposeParseErrors bool) *DateInput
NewDateInput builds one.
func (*DateInput) HandleEvent ¶
HandleEvent types into the buffer, or drives the calendar when it is open.
func (*DateInput) MetadataFor ¶
MetadataFor publishes the buffer, the preview, the suggestions and — when it is open — the whole calendar the renderer paints.
func (*DateInput) NormalizeValue ¶
NormalizeValue turns text into a parsed value where it can, and leaves unparseable text as text so the user can see and fix what they typed.
func (*DateInput) PickerDate ¶
PickerDate is the calendar's highlighted day.
func (*DateInput) PickerOpen ¶
PickerOpen reports whether the calendar is showing.
func (*DateInput) SetText ¶
SetText rewrites the buffer from a host that owns a richer control over the same value — the structured temporal picker writes the canonical spelling back after every arrow step, so the text and the control never disagree.
type Event ¶
type Event struct {
Type EventType
// Key is the semantic key name for a :key event ("up", "return"), or the
// raw bytes when the host had no name for it.
Key string
// Text is the typed or pasted text for :input and :paste events.
Text string
// Raw is the transport bytes, retained for diagnostics and as the fallback
// a field reads when a default binding collapsed an arrow into navigation.
Raw string
// IntendedFocus is the field a :commit event wants focus to land on.
IntendedFocus string
// Direction rides along with a :focus event.
Direction string
// Value rides along with a :change event.
Value any
}
Event is one normalized input. Ruby carries an arbitrary payload Hash; the three payload keys any field actually reads are named fields here, so a typo is a compile error rather than a silently absent value.
type EventType ¶
type EventType string
EventType is the event vocabulary.
const ( EventKey EventType = "key" EventInput EventType = "input" EventPaste EventType = "paste" EventNext EventType = "next" EventPrevious EventType = "previous" EventFocus EventType = "focus" EventChange EventType = "change" EventCommit EventType = "commit" EventCancel EventType = "cancel" )
The event types, in the order lib/term_form/event.rb uses them.
type Field ¶
type Field interface {
Key() string
LabelFor(context Context) string
IsVisible(context Context) bool
IsEnabled(context Context) bool
IsRequired(context Context) bool
Initial() any
InitialBaseline() any
Metadata() map[string]any
MetadataFor(value any, context Context) map[string]any
CursorFor(value any, context Context) *int
// HandleEvent consumes one event, or returns nil to leave it to Form's
// navigation and commit protocol.
HandleEvent(event Event, value any, context Context) *Result
NormalizeValue(value any) any
// SyncValue reconciles a stateful field's private editing buffer after the
// form's value changed underneath it.
SyncValue(value any)
// FocusGained lets a field position its private cursor for entry. It must
// tolerate repeats — initial focus and commit round-trips both re-apply it.
FocusGained(value any, context Context)
ValidationErrors(value any, context Context) []string
}
Field is one editable value plus its behavior.
Ruby subclasses a Field class; Go composes. Every field embeds Base, which supplies the whole default protocol, and overrides only what it owns. The interface is what Form talks to.
type Form ¶
type Form struct {
// contains filtered or unexported fields
}
Form is the focus and commit lifecycle over a set of grouped fields.
The single most important behavior in this file is request_focus: leaving a DIRTY field does not move focus, it asks the host to persist the field and waits. That is save-on-blur, and it is why the editor never needs an explicit save key — and why a rejected save leaves the cursor exactly where the user can fix it.
func NewForm ¶
NewForm builds a form. focus names the field to start on; "" starts on the first focusable field.
func (*Form) AcceptCommit ¶
AcceptCommit resolves a pending save with the host's fresh values.
The committed field is reconciled against the expectation the request carried; every OTHER key in the fresh set updates its baseline, and updates its buffer only if that buffer was clean. That is the rule that lets an external edit land in the form without discarding what the user is typing.
func (*Form) Field ¶
Field looks one up. A missing key is a programming error in the adapter above, so it returns nil rather than raising — the caller decides.
func (*Form) Focus ¶
func (f *Form) Focus(key string, event Event, direction string) Transition
Focus moves to a named field, going through the save-on-blur handshake when the field being left is dirty.
func (*Form) FocusNext ¶
func (f *Form) FocusNext(event Event) Transition
FocusNext and FocusPrevious walk the focusable fields, wrapping.
func (*Form) FocusPrevious ¶
func (f *Form) FocusPrevious(event Event) Transition
func (*Form) FocusableFields ¶
FocusableFields is every field a cursor may land on right now.
func (*Form) Handle ¶
func (f *Form) Handle(event Event) Transition
Handle routes one event: the focused field first, then the navigation and commit protocol.
func (*Form) HandleKey ¶
func (f *Form) HandleKey(raw string) Transition
HandleKey routes one raw byte sequence.
func (*Form) PendingCommit ¶
func (f *Form) PendingCommit() *CommitRequest
PendingCommit is the in-flight save, or nil.
func (*Form) Refresh ¶
func (f *Form) Refresh(fresh map[string]any) (Transition, error)
Refresh adopts fresh host values. Same rule as AcceptCommit's other keys: a dirty buffer keeps its text, every baseline moves.
func (*Form) RejectCommit ¶
func (f *Form) RejectCommit(fieldErrors map[string][]string, message string, token int) (Transition, error)
RejectCommit resolves a pending save with the host's refusal. The buffer is untouched — a rejected save must never cost the user what they typed.
func (*Form) RenderModel ¶
func (f *Form) RenderModel() RenderModel
RenderModel projects the whole form for a renderer.
func (*Form) RequestCommit ¶
func (f *Form) RequestCommit(intendedFocus, direction, fieldKey string, event Event) Transition
RequestCommit asks the host to persist the focused field.
Validation runs FIRST and a failure never opens a request: a host must not be asked to write a value the form already knows is wrong, and the focus lands on the first offending field so the user is looking at the problem.
func (*Form) SetValue ¶
func (f *Form) SetValue(key string, value any, event Event) Transition
SetValue writes one field's buffer.
func (*Form) Validate ¶
Validate recomputes the error set over the focusable fields. A hidden or disabled field is deliberately not validated: refusing a save because of a rule the user cannot see or reach is a dead end.
func (*Form) VisibleFields ¶
VisibleFields is every field the renderer should paint.
type Group ¶
type Group struct {
Key string
Label string
Fields []Field
Visible func(Context) bool
Enabled func(Context) bool
VisibleFixed bool
EnabledFixed bool
Meta map[string]any
}
Group is a named run of fields. It exists so a whole section can be hidden or disabled together, and so the renderer has a heading to paint.
type KeyMap ¶
type KeyMap struct {
// contains filtered or unexported fields
}
KeyMap turns raw bytes into semantic events.
type MultiSelect ¶
type MultiSelect struct {
ChoiceField
// Creatable lets a typed token that matches nothing become a new value —
// which is how a brand-new @context is added without leaving the editor.
Creatable bool
// contains filtered or unexported fields
}
MultiSelect is a multiple-choice field whose value is an ordered token list.
func NewMultiSelect ¶
func NewMultiSelect(base Base, options func(Context) []Option, searchable, creatable bool, normalizer func(string) string) *MultiSelect
NewMultiSelect builds one.
func (*MultiSelect) HandleEvent ¶
func (m *MultiSelect) HandleEvent(event Event, value any, context Context) *Result
HandleEvent is the multi-select interaction. Backspace on an empty query pops the last token, which is the one gesture that makes a token list feel like text rather than a form control.
func (*MultiSelect) MetadataFor ¶
func (m *MultiSelect) MetadataFor(value any, context Context) map[string]any
MetadataFor adds the token list the renderer draws as chips.
func (*MultiSelect) NormalizeValue ¶
func (m *MultiSelect) NormalizeValue(value any) any
NormalizeValue trims, normalizes and de-duplicates the token list. The order of what survives is the order it was given in, so a user's arrangement of tags is not silently re-sorted.
type RenderGroup ¶
RenderGroup is one group's rows.
type RenderModel ¶
type RenderModel struct {
Groups []RenderGroup
Rows []Row
FocusedKey string
Errors map[string][]string
// contains filtered or unexported fields
}
RenderModel is the whole form, renderer-neutral.
func (RenderModel) FocusedRow ¶
func (m RenderModel) FocusedRow() *Row
FocusedRow is the row with focus, or nil.
func (RenderModel) FocusedRowIndex ¶
func (m RenderModel) FocusedRowIndex() int
FocusedRowIndex is the focused row's index, or -1.
type Result ¶
type Result struct {
// Status is Handled or Changed.
Status TransitionType
Value any
}
Result is what a field's HandleEvent returns: nil means "not mine".
func ChangedResult ¶
func HandledResult ¶
HandledResult and ChangedResult build the two shapes.
type Row ¶
type Row struct {
Key string
GroupKey string
Label string
Value any
Index int
Enabled bool
Focused bool
// Pending marks the field whose commit the host has not answered yet. It
// keeps rendering even if reactivity hid it, because a request the user
// cannot see is a request they cannot resolve.
Pending bool
Dirty bool
Required bool
Errors []string
Cursor *int
Metadata map[string]any
}
Row is one field as the renderer sees it. Every decision the renderer makes is answered here, so the renderer never asks the form a question.
type Select ¶
type Select struct{ ChoiceField }
Select is a single-choice field.
type TextArea ¶
type TextArea struct{ TextField }
TextArea is a multi-line text field with wrapped vertical motion.
func (*TextArea) FocusGained ¶
FocusGained shows a tall value from the TOP. The cursor after a sync sits at end-of-buffer, which would scroll a long note so only its last lines are visible — the opposite of what someone opening a note wants to see.
func (*TextArea) HandleEvent ¶
HandleEvent adds vertical motion on top of the shared text behavior.
type TextField ¶
type TextField struct {
Base
// contains filtered or unexported fields
}
TextField is the shared behavior of the single-line and multi-line editors. The editing buffer is PRIVATE to the field; the form's value is the text it produces. That is what makes cursor position survive a refresh that did not change the text.
func (*TextField) HandleEvent ¶
HandleEvent is the shared text behavior: paste inserts, everything else goes to the editor's own key table.
func (*TextField) HandleRawKey ¶
HandleRawKey applies one raw key to the buffer.
func (*TextField) NormalizeValue ¶
NormalizeValue runs a value through the same sanitizer the editor applies, so a host-supplied value with a tab in it cannot differ from the same value typed by hand.
type Transition ¶
type Transition struct {
Type TransitionType
Event Event
FocusKey string
RenderModel RenderModel
Request *CommitRequest
Errors map[string][]string
ChangedKey string
}
Transition is the answer to one event.
func (Transition) IsChanged ¶
func (t Transition) IsChanged() bool
IsChanged, IsFocusChanged and friends read as Ruby's predicate methods do.
func (Transition) IsFocusChanged ¶
func (t Transition) IsFocusChanged() bool
func (Transition) IsInvalid ¶
func (t Transition) IsInvalid() bool
func (Transition) IsUnhandled ¶
func (t Transition) IsUnhandled() bool
type TransitionType ¶
type TransitionType string
TransitionType is what one handled event did.
const ( Unhandled TransitionType = "unhandled" Handled TransitionType = "handled" Changed TransitionType = "changed" FocusChanged TransitionType = "focus_changed" Invalid TransitionType = "invalid" CommitRequested TransitionType = "commit_requested" CommitPending TransitionType = "commit_pending" CommitAccepted TransitionType = "commit_accepted" CommitRejected TransitionType = "commit_rejected" CancelRequested TransitionType = "cancel_requested" Refreshed TransitionType = "refreshed" )
The transition types, in the order lib/term_form/event.rb declares them.
type View ¶
type View struct {
Lines []string
CursorRow int
CursorColumn int
VirtualCursorRow int
VirtualCursorColumn int
RowOffset int
ColumnOffset int
Width int
Height int
}
View is one field's laid-out window: the visible lines plus where the cursor sits in them and where it sits in the whole value.
The two cursors are both needed. CursorRow/Column is where to put the terminal caret; VirtualCursorRow/Column is where the cursor is in the value, which is what scrolling decisions are made from. Collapsing them would make a scrolled field's caret follow the viewport instead of the text.