termform

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 9 Imported by: 0 modules, 0 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 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

Constants

This section is empty.

Variables

View Source
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.

View Source
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.

View Source
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

func ClusterWidth(cluster string) int

ClusterWidth is one grapheme cluster's width in terminal cells.

func Command

func Command(event Event, kind EventType, keys ...string) bool

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

func DecodedKey(event Event) string

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.

func Graphemes

func Graphemes(text string) []string

Graphemes and ClusterWidth re-export the two measurements the fields make, so a caller measuring a rendered field line uses the SAME implementation the field laid it out with.

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

func NewBase(key, label string, value any) Base

NewBase fills the defaults a caller almost always wants: visible, enabled, not required.

func (*Base) CursorFor

func (b *Base) CursorFor(any, Context) *int

func (*Base) FocusGained

func (b *Base) FocusGained(any, Context)

func (*Base) HandleEvent

func (b *Base) HandleEvent(Event, any, Context) *Result

func (*Base) Initial

func (b *Base) Initial() any

func (*Base) InitialBaseline

func (b *Base) InitialBaseline() any

func (*Base) IsEnabled

func (b *Base) IsEnabled(context Context) bool

func (*Base) IsRequired

func (b *Base) IsRequired(context Context) bool

func (*Base) IsVisible

func (b *Base) IsVisible(context Context) bool

func (*Base) Key

func (b *Base) Key() string

func (*Base) LabelFor

func (b *Base) LabelFor(Context) string

func (*Base) Metadata

func (b *Base) Metadata() map[string]any

func (*Base) MetadataFor

func (b *Base) MetadataFor(any, Context) map[string]any

func (*Base) NormalizeValue

func (b *Base) NormalizeValue(value any) any

func (*Base) SyncValue

func (b *Base) SyncValue(any)

func (*Base) ValidationErrors

func (b *Base) ValidationErrors(value any, context Context) []string

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

func CalendarFor(date temporal.Date) Calendar

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) Query

func (c *ChoiceField) Query() string

Query is the live search text.

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

type Confirm struct {
	Base
	YesLabel    string
	NoLabel     string
	Consequence string
}

Confirm is a yes/no field.

func NewConfirm

func NewConfirm(base Base, yesLabel, noLabel string) *Confirm

NewConfirm builds one.

func (*Confirm) HandleEvent

func (c *Confirm) HandleEvent(event Event, value any, _ Context) *Result

HandleEvent accepts y/n, left/right, space and Return.

func (*Confirm) MetadataFor

func (c *Confirm) MetadataFor(value any, _ Context) map[string]any

MetadataFor publishes the two labels and which one is selected.

func (*Confirm) NormalizeValue

func (c *Confirm) NormalizeValue(value any) any

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) AnyDirty

func (c Context) AnyDirty() bool

AnyDirty reports whether ANY field differs from its baseline.

func (Context) Baseline

func (c Context) Baseline(key string) any

Baseline is the last persisted value for a key.

func (Context) ChangedKeys

func (c Context) ChangedKeys() []string

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.

func (Context) Dirty

func (c Context) Dirty(key string) bool

Dirty reports whether one field's buffer differs from its baseline.

func (Context) Get

func (c Context) Get(key string) any

Get is Ruby's `context[:key]`.

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) Cursor

func (d *DateInput) Cursor() int

Cursor is the caret offset.

func (*DateInput) CursorFor

func (d *DateInput) CursorFor(any, Context) *int

CursorFor hides the text caret while the calendar owns the keyboard.

func (*DateInput) HandleEvent

func (d *DateInput) HandleEvent(event Event, value any, context Context) *Result

HandleEvent types into the buffer, or drives the calendar when it is open.

func (*DateInput) MetadataFor

func (d *DateInput) MetadataFor(value any, _ Context) map[string]any

MetadataFor publishes the buffer, the preview, the suggestions and — when it is open — the whole calendar the renderer paints.

func (*DateInput) NormalizeValue

func (d *DateInput) NormalizeValue(value any) any

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

func (d *DateInput) PickerDate() (temporal.Date, bool)

PickerDate is the calendar's highlighted day.

func (*DateInput) PickerOpen

func (d *DateInput) PickerOpen() bool

PickerOpen reports whether the calendar is showing.

func (*DateInput) SetText

func (d *DateInput) SetText(text string)

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.

func (*DateInput) SyncValue

func (d *DateInput) SyncValue(value any)

SyncValue adopts a form value into the buffer.

func (*DateInput) Text

func (d *DateInput) Text() string

Text is the buffer.

func (*DateInput) ValidationErrors

func (d *DateInput) ValidationErrors(value any, context Context) []string

ValidationErrors adds "that is not a date" for leftover unparseable text.

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.

func KeyEvent

func KeyEvent(key string) Event

KeyEvent builds the event for one named key or raw sequence.

func PasteEvent

func PasteEvent(text string) Event

PasteEvent builds a paste.

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

func NewForm(groups []Group, focus string, keyMap *KeyMap) (*Form, error)

NewForm builds a form. focus names the field to start on; "" starts on the first focusable field.

func (*Form) AcceptCommit

func (f *Form) AcceptCommit(fresh map[string]any, token int) (Transition, error)

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) AnyDirty

func (f *Form) AnyDirty() bool

AnyDirty reports whether any field does.

func (*Form) Baseline

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

Baseline is one field's last persisted value.

func (*Form) ChangedKeys

func (f *Form) ChangedKeys() []string

ChangedKeys is every dirty key.

func (*Form) Context

func (f *Form) Context() Context

Context is the read-only view fields and validators see.

func (*Form) Dirty

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

Dirty reports whether one field differs from its baseline.

func (*Form) Errors

func (f *Form) Errors() map[string][]string

Errors is the current validation state.

func (*Form) Field

func (f *Form) Field(key string) 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) Fields

func (f *Form) Fields() []Field

Fields is every field, in declaration order.

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) FocusKey

func (f *Form) FocusKey() string

FocusKey is the focused field's key.

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

func (f *Form) FocusableFields() []Field

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) Pending

func (f *Form) Pending() bool

Pending reports whether a save is awaiting the host's answer.

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) Valid

func (f *Form) Valid() bool

Valid reports whether the whole form passes.

func (*Form) Validate

func (f *Form) Validate() map[string][]string

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) Value

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

Value is one field's current buffer.

func (*Form) Values

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

Values is a copy of every buffer.

func (*Form) VisibleFields

func (f *Form) VisibleFields() []Field

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.

func NewGroup

func NewGroup(key, label string, fields ...Field) Group

NewGroup builds a visible, enabled group.

type Input

type Input struct{ TextField }

Input is a single-line text field.

func NewInput

func NewInput(base Base) *Input

NewInput builds one.

func (*Input) Render

func (i *Input) Render(width int) View

Render lays the value out in a window of width cells, scrolling horizontally so the caret stays visible.

type KeyMap

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

KeyMap turns raw bytes into semantic events.

func NewKeyMap

func NewKeyMap(overrides map[string]EventType) *KeyMap

NewKeyMap builds a key map over the defaults.

func (*KeyMap) EventFor

func (k *KeyMap) EventFor(raw string) Event

EventFor maps raw bytes onto a semantic event. Unbound bytes are typed text.

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 Option

type Option struct {
	Value    any
	Label    string
	Metadata map[string]any
}

Option is one choice in a Select or MultiSelect.

func NewOption

func NewOption(value any, label string) Option

NewOption builds an option, defaulting the label to the value.

type RenderGroup

type RenderGroup struct {
	Key      string
	Label    string
	Rows     []Row
	Enabled  bool
	Metadata map[string]any
}

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 ChangedResult(value any) *Result

func HandledResult

func HandledResult(value any) *Result

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.

func (Row) Error

func (r Row) Error() string

Error is the first error, or "".

type Select

type Select struct{ ChoiceField }

Select is a single-choice field.

func NewSelect

func NewSelect(base Base, options func(Context) []Option, searchable bool) *Select

NewSelect builds one.

func (*Select) HandleEvent

func (s *Select) HandleEvent(event Event, value any, context Context) *Result

HandleEvent is the select interaction: arrows highlight, Return opens then picks, Escape closes without changing anything.

type TextArea

type TextArea struct{ TextField }

TextArea is a multi-line text field with wrapped vertical motion.

func NewTextArea

func NewTextArea(base Base) *TextArea

NewTextArea builds one.

func (*TextArea) FocusGained

func (a *TextArea) FocusGained(any, Context)

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

func (a *TextArea) HandleEvent(event Event, value any, context Context) *Result

HandleEvent adds vertical motion on top of the shared text behavior.

func (*TextArea) Render

func (a *TextArea) Render(width, height int) View

Render wraps the value to width and scrolls vertically to keep the caret in the window.

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) Cursor

func (t *TextField) Cursor() int

Cursor is the grapheme offset of the caret.

func (*TextField) CursorFor

func (t *TextField) CursorFor(any, Context) *int

CursorFor exposes the caret to the renderer.

func (*TextField) HandleEvent

func (t *TextField) HandleEvent(event Event, _ any, _ Context) *Result

HandleEvent is the shared text behavior: paste inserts, everything else goes to the editor's own key table.

func (*TextField) HandleRawKey

func (t *TextField) HandleRawKey(key string) input.Result

HandleRawKey applies one raw key to the buffer.

func (*TextField) NormalizeValue

func (t *TextField) NormalizeValue(value any) any

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.

func (*TextField) Paste

func (t *TextField) Paste(text string) input.Result

Paste inserts text at the caret.

func (*TextField) SyncValue

func (t *TextField) SyncValue(value any)

SyncValue adopts a value the form changed underneath the buffer. An UNCHANGED value deliberately leaves the buffer alone, which is what preserves a deliberately placed mid-buffer cursor across a blur and refocus.

func (*TextField) Text

func (t *TextField) Text() string

Text is the current buffer.

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.

Jump to

Keyboard shortcuts

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