SugarForms
Interactive forms + foundation form primitives
Form engine built on SugarCraft — multi-page Group wizards, seven themes, per-field validators, conditional hide predicates. The form is itself a Model — drop it into a Program. Also the foundation for the raw form / input primitives that sugar-widgets re-exports, folded together with the interactive form library into a single standalone dependency.
Install
composer require sugarcraft/sugar-forms
Until a 1.0 tag exists the package publishes only dev-master, so a consumer's own composer.json needs "minimum-stability": "dev" with "prefer-stable": true (Composer's documented default refuses a dev-only package at plain stable).
Quickstart
use SugarCraft\Forms\Form;
use SugarCraft\Core\Program;
use SugarCraft\Forms\Field\{Input, Confirm, Select, Note};
use SugarCraft\Forms\Validator\{Required, Email, MinLength};
use SugarCraft\Fuzzy\Matcher\SmithWatermanMatcher;
$form = Form::new(
Note::new('welcome')
->withTitle('Onboarding')
->withDescription('A few quick questions.'),
Input::new('name')
->withTitle('Your name?')
->withPlaceholder('Ada Lovelace')
->withValidator(new Required())
->withValidator(new MinLength(2)),
Input::new('email')
->withTitle('Email address')
->withPlaceholder('you@example.com')
->withValidator(new Required())
->withValidator(new Email()),
Select::new('lang')
->withTitle('Favorite language?')
->withOptions('PHP', 'Go', 'Rust', 'Python')
->withFuzzySuggestions(['PHP', 'Go', 'Rust', 'Python', 'JavaScript', 'TypeScript']),
);
// $form is a SugarCraft Model — drive it with a Program. The Model is
// immutable: Program drives a COPY and run() returns the final model, so
// capture it before reading values back.
$final = (new Program($form))->run();
$done = $final instanceof Form ? $final : throw new RuntimeException('not a Form');
if ($done->isSubmitted()) {
echo $done->values()['name'], "\n";
}
// Async suggestions:
$form = Form::new(
Input::new('repo')
->withTitle('Repository')
->withAsyncSuggestions(fn($q) => fetchRepos($q), 150),
);
// Fuzzy scoring — sugar-fuzzy, the engine behind withFuzzySuggestions():
$matcher = SmithWatermanMatcher::new();
$score = $matcher->score('js', 'JavaScript'); // 3
$best = $matcher->matchAll('py', ['Python', 'PHP', 'Ruby'])[0]; // MatchResult: Python, score 11
What's in the box
Form honors Field::isHidden() in values, errors, validation, navigation, submit and view; focus never rests on a hidden field and fully hidden groups are skipped. A Group::withHideFunc() predicate sees the same view values() returns — the visible fields of every visible earlier group.charLimit budget; TextArea counts newlines against it, while TextInput strips them at insert — a single-line field cannot represent them. TextArea pans to keep the cursor row visible.->withValidator(Validator | \Closure) — a closure returns null to pass or an error string to block submit; Input chains multiple attachments in order. The predicate form ->withValidation(callable $predicate, string $errorMessage) (Input and Text) takes a boolean instead: true passes. These contracts are not interchangeable — a hypothetical withValidate that returned null/error string renamed to withValidation would INVERT the return semantics (null/string vs bool). Five built-in validators: Required, Email, MinLength, MaxLength, Pattern. Cross-field validation via Form::validateAll(): array<string,string> after submit. Enable error summary with Form::withErrorSummary(true) to show all errors at once.->withFuzzySuggestions([...]) on Input and Select — Smith-Waterman scoring ranks candidates by match quality (extracted to sugar-fuzzy). Use sugar-fuzzy’s SmithWatermanMatcher directly for programmatic scoring: $matcher->score($query, $candidate).->withAsyncSuggestions(callable $fetcher, int $debounceMs = 150, ?WorkerPool $workerPool = null, ?float $fetchTimeoutSeconds = null) on Input and Select — fetches suggestions asynchronously with a configurable debounce delay. The two optional knobs are tuning surfaces: leave them null unless you know why — $fetchTimeoutSeconds races each in-flight fetch against a wall-clock ceiling (a breach surfaces as the fetcher failing); $workerPool is reserved (stored, never consulted). The SugarCraft\Forms\FormSuggestionsReadyMsg envelope (carrying the fetch generation — superseded or unfocused arrivals are discarded, SF-52) is dispatched via the event loop when results are available.->withAsyncValidator(Closure): PromiseInterface<?string> on the async-capable fields (Input, Text). Enter runs the sync gate; when async validators are still answering, the form parks the submit in a pending round, verdicts paint inline and in the summary, a clean round fires the deferred submit, and any edit clears the overlay. Field-level verdicts judge the bytes dispatched, not the bytes live when they land: direct validateAsync() callers must discard a resolution whose value changed mid-flight.j / k navigate, Space toggles selection — mirrors vim-style keybindings.Select::withEnum(\BackedEnum::class) coerces the selected value to the given enum type automatically.Group::new(Field ...$fields) stacks fields into one page; a multi-page wizard is built with Form::groups(Group ...$groups). Conditional ->withHideFunc(?\Closure) HIDES the whole group — it drops out of the focus walk and its values are excluded — there is no skip function.Form::view() threads the theme into every field body (titles, cursor surface, options, inline errors). Summary block and per-field bullet ride the Theme->errorSummary / Theme->errorSummaryItem slot pair.$form->values() or typed accessors string() / int() / bool() / array() / get(string $key, mixed $default = null) once the Program ends — no submit-hook callback API exists.Form::withKeyMap(?KeyMap) rebinds Next / Prev / Submit / Abort per form.ActionSpinner) with a bounded runtime ceiling — the long-running spin primitive folded in from the retired prompt façade.Accessible mode. Form::withAccessible() flips the form to plain-text rendering — useful when you detect NO_COLOR=1 or TERM=dumb. The accessible line is scoped to the focused field only: no group titles, no Step X of Y pagination, no error-summary block.
Security & trust boundary. Form content is frequently model- or network-produced, so every display surface runs hostile bytes through RenderSafe::clean(): C0/DEL bytes are stripped (TAB and LF survive) and every ESC-introduced sequence is disarmed except true SGR, so theme color renders while screen clears, cursor moves and OSC payloads become inert text; the sweep is idempotent and UTF-8 safe. The boundary is the display, never the buffer — value() returns pasted bytes verbatim, and dev-authored placeholders render raw.
Use it for
- Declarative form wizards — multi-page Groups, validation, themes, fuzzy / async suggestions, out of the box.
- Standalone form primitives — when you want the raw inputs without sugar-widgets overhead.
- Custom form engines — build your own form system on top of the Field interface.
- Spinner and progress components — standalone spinner and the fork-safe ActionSpinner live here, previously in sugar-widgets / the retired prompt façade.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by huh (Go); SugarCraft is developed as a native PHP project.
API reference
| Class | Method | Description |
|---|---|---|
| Form | new(Field ...$fields) | Create a single-group form with fields |
| Form | groups(Group ...$groups) | Create a multi-page form |
| Form | values() / string() / int() / bool() / array() | Submitted values of visible, non-skippable fields — hidden fields, hidden groups and skippable Note fields are excluded (legacy getString() & friends remain as deprecated forwarders, to be removed in 2.0.0) |
| Form | get(key, default = null) | Value of one field, or the fallback when the key is absent |
| Form | validateAll() | Run all field validators, return [fieldKey => errorMessage] |
| Form | withErrorSummary(bool) | Show all current validation errors at once, without waiting for submit |
| Form | withKeyMap(?KeyMap) | Rebind Next / Prev / Submit / Abort per form |
| Group | new(Field ...$fields) / withHideFunc(?\Closure(array): bool) | A page of fields; the predicate receives the visible values collected before this group |
| Field\Input | new(string) | Create a text input field |
| Field\Input | withFuzzySuggestions(list) | Filter suggestions by fuzzy match score |
| Field\Input | withAsyncSuggestions(callable, int = 150, ?WorkerPool = null, ?float = null) | Async suggestions with debounce |
| Field\Input | withAsyncValidator(Closure): PromiseInterface<?string> | Async validation blocks submit until it answers |
| Field\Confirm | new(string) | Create a confirmation field |
| Field\Select | new(string)->withOptions(string ...) | Create a select field |
| Field\Select | withFuzzySuggestions(list) | Filter options by fuzzy match score |
| Field\Select | withAsyncSuggestions(callable, int = 150, ?WorkerPool = null, ?float = null) | Async suggestions with debounce |
| Field\Select | withEnum(BackedEnum::class) | Coerce selected value to enum type |
| Field\MultiSelect | new(key, ...options) | Create multi-select field (j/k nav, Space toggle) |
| Field\Note | new(key) | Create note field — text set via withTitle/withDescription; plain notes never appear in values() (a withNext(true) note contributes a null entry) |
| Validator\Required | validate(string): true|string | true to pass, or the error string when the value is empty |
| Validator\Email | validate(string): true|string | true to pass, or the error string when the value is not a valid email |
| Spinner\Spinner | new(?Style) | Create a spinner with style |
| ActionSpinner | new() / run() | Fork-isolated spinner action with a bounded runtime ceiling; the verdict arrives as a SpinnerResult |
| Fuzzy\FuzzyMatcher (deprecated shim) | score(query, candidate) | Smith-Waterman alignment score (int) — delegates to sugar-fuzzy |
| Fuzzy\FuzzyMatcher (deprecated shim) | match(query, candidates): list<[string, int]> | Legacy ranking shape — for ?MatchResult / matchAll() use sugar-fuzzy's SmithWatermanMatcher directly |
| Theme | errorSummary | Renderable slot for custom error summary display |
Configuration
Each option is set through a fluent builder method on Form, TextInput or an async-capable field. The defaults are the values the classes ship with.
Form::withAccessible(bool): bool, defaultfalse. Switches to the single-line plain-text view of the focused field.Form::withShowHelp(bool): bool, defaulttrue. Shows theStep X of Yindicator on multi-group forms. A single-group form renders the same either way, and the form never draws key-help rows (keyBinds()returns them for the host to draw).Form::withShowErrors(bool): bool, defaulttrue. Paints each field's inline error.Form::withErrorSummary(bool): bool, defaultfalse. Lists every current validation error at once as soon as a visible field fails, with no submit needed.Form::withTheme(Theme):Theme, defaultTheme::ansi(). Sets the palette every field is painted with.Form::withKeyMap(?KeyMap):?KeyMap, defaultnull, which usesKeyMap::new(). Rebinds Next, Prev, Submit and Abort.TextInput::charLimit(int): int, default4096. Bounds a paste or insert to this many characters.0turns the bound off.withAsyncSuggestions(callable, int $debounceMs): int, default150. Milliseconds to wait after the last keystroke before a suggestion fetch starts.withAsyncSuggestions(..., ?float $fetchTimeoutSeconds): ?float, defaultnull. Wall-clock ceiling per fetch.nulladds no timeout.
Keys
The default KeyMap::new() binds the following keys.
- Next:
Tab,↓ - Prev:
Shift+Tab,Alt+Tab,↑ - Submit:
Enter - Abort:
Esc,Ctrl+C
MultiSelect adds j and k for cursor movement and Space to toggle an option. KeyMap::withNext(), withPrev(), withSubmit() and withAbort() each replace one binding list, and Form::withKeyMap() installs the result. Passing null restores the defaults.
Theming
Seven presets are available as static factories on Theme: ansi() (the default), plain(), charm(), dracula(), catppuccin(), base16() and base(). Theme::catalog() returns their names. Apply one with Form::withTheme():
use SugarCraft\Forms\Form;
use SugarCraft\Forms\Field\Input;
use SugarCraft\Forms\Theme;
$form = Form::new(Input::new('name')->withTitle('Your name?'))
->withTheme(Theme::dracula());
Examples
Each file in examples/ runs from the library root as php examples/<name>.php.
burger.php: The canonical burger order form from the huh README, built from four fields: bun, patty, extras and a Confirm. Renders the first frame.confirm.php: The Confirm field in three states: default-no, default-yes and custom labels.form.php: A static render of one form made of an Input, a Select and a Confirm.hide.php: Conditional visibility throughwithHideFunc().input.php: The Input field with a title, description and placeholder.multi-page-form.php: A multi-page form with conditional show and hide.multi-select.php: The MultiSelect field with min and max bounds.no-color.php: How a program readsNO_COLORandCLICOLORthrough sugar-core and renders to match.select.php: The single-choice Select field.spinner.php: A blockingActionSpinnerthat runs a worker callable while it spins on STDERR.text.php: The multi-line Text field.themes.php: The same form rendered under five built-in themes.
Testing
cd sugar-forms
composer install
vendor/bin/phpunit
The suite boots through tests/bootstrap.php, which calls SugarCraft\Testing\LoopPin::pinStableClock() before any test touches the event loop, because the async-suggestion tests arm debounce and timeout timers on it. sugar-testing is a require-dev dependency, and tests/GoldenRenderTest.php uses its golden-file helpers.
Only methods declared in sugar-forms/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\Forms
ActionSpinner final class
Blocking "loading" prompt with a spinner. Mirrors charmbracelet/huh.huh.NewSpinner().Title(...).Action(fn).Run() — schedules a worker callable, animates a \SugarCraft\Forms\Spinner\Style frame sequence while it runs, and returns once the action completes.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct() | |
static new(): self | |
withTitle(string $t): self | |
withStyle(SpinnerStyle $s): self | |
withAction(\Closure $fn): self | |
withMaxRuntimeSeconds(float $seconds): self | Bound the FORKED action's lifetime (E711). See self::MAX_RUNTIME_SECONDS for what the bound is and the class docblock for why the inline fallback stays unbounded. On hosts without pcntl_fork the ceiling is INERT: the action runs inline with no timer and no ladder, and nothing can set SpinnerResult::$timedOut — only wallSeconds measures such a run. |
run(): SpinnerResult | Run the action, animating the spinner on STDERR until it returns. STDERR is used so stdout stays clean for piped output. |
AsyncValidatable interface
A Field that can also answer "is this value acceptable?" off the event loop (plan 5.2, round 89 lane y3).
| Method | Summary |
|---|---|
validateAsync(): PromiseInterface | Resolve with the validation error message, or null when the value is acceptable. Rejects when the attached async validator itself fails — rejection means "could not answer", never "invalid". |
key(): string | Stable identifier used by the form to key Form::values(). |
value(): mixed | Current value (string / bool / array / etc., field-specific). |
focus(): array | Take focus. Returns the new (focused) field plus an optional Cmd the runtime should schedule (cursor-blink, autocomplete-fetch, etc.). |
blur(): Field | Release focus. Returns a new (unfocused) field. |
update(Msg $msg): array | Apply a bubbletea message and return [$next, $cmd]. Mirrors the charmbracelet/bubbletea Model.Update(msg) shape. |
view(bool $showErrors = true, ?Theme $theme = null): string | Render the field as a multi-line ANSI string. $showErrors is the enclosing form's \SugarCraft\Forms\Form::withShowErrors() knob: false suppresses the inline ! error row and its ? help satellite (the form's error SUMMARY is a separate composer, always rendered when enabled). Default true keeps a standalone field's render byte-identical to the pre-SF-7 shape. |
isFocused(): bool | True while this field currently holds keyboard focus. |
getTitle(): string | Static title (the *Func form is resolved separately at view time). |
description(): string | Static description, same shape as getTitle(). |
error(): ?string | Latest validator error, or null when the value passes validation. |
getDescription(): string | |
getError(): ?string | |
skippable(): bool | Notes / separators / hidden fields skip Tab navigation. |
consumes(Msg $msg): bool | True if the field is in a state where the given Msg has internal meaning that should override Form-level handling. The Form checks this for keys it would otherwise capture (Enter / Escape) so that inner widgets can consume them — e.g. an ItemList in filter mode uses Enter to leave filter mode and Escape to clear it. |
isHidden(array $values): bool | Runtime visibility predicate. The form skips fields whose isHidden(values) returns true; both navigation and the values collector treat them as if they didn't exist. |
revalidate(): Field | Re-run validators/constraints against the current value and return a new field instance with the recomputed error. Idempotent: if no error exists and the value is unchanged, returns $this. Does not alter focus. |
CarriesNonCtorState trait
Carrier mixin for Field implementations that rebuild themselves through new self(...): copies the state that lives OUTSIDE the private constructor — the HasHideFunc / HasDynamicLabels closures — onto the freshly constructed instance.
Field interface
One field in a Form.
| Method | Summary |
|---|---|
key(): string | Stable identifier used by the form to key Form::values(). |
value(): mixed | Current value (string / bool / array / etc., field-specific). |
focus(): array | Take focus. Returns the new (focused) field plus an optional Cmd the runtime should schedule (cursor-blink, autocomplete-fetch, etc.). |
blur(): Field | Release focus. Returns a new (unfocused) field. |
update(Msg $msg): array | Apply a bubbletea message and return [$next, $cmd]. Mirrors the charmbracelet/bubbletea Model.Update(msg) shape. |
view(bool $showErrors = true, ?Theme $theme = null): string | Render the field as a multi-line ANSI string. $showErrors is the enclosing form's \SugarCraft\Forms\Form::withShowErrors() knob: false suppresses the inline ! error row and its ? help satellite (the form's error SUMMARY is a separate composer, always rendered when enabled). Default true keeps a standalone field's render byte-identical to the pre-SF-7 shape. |
isFocused(): bool | True while this field currently holds keyboard focus. |
getTitle(): string | Static title (the *Func form is resolved separately at view time). |
description(): string | Static description, same shape as getTitle(). |
error(): ?string | Latest validator error, or null when the value passes validation. |
getDescription(): string | |
getError(): ?string | |
skippable(): bool | Notes / separators / hidden fields skip Tab navigation. |
consumes(Msg $msg): bool | True if the field is in a state where the given Msg has internal meaning that should override Form-level handling. The Form checks this for keys it would otherwise capture (Enter / Escape) so that inner widgets can consume them — e.g. an ItemList in filter mode uses Enter to leave filter mode and Escape to clear it. |
isHidden(array $values): bool | Runtime visibility predicate. The form skips fields whose isHidden(values) returns true; both navigation and the values collector treat them as if they didn't exist. |
revalidate(): Field | Re-run validators/constraints against the current value and return a new field instance with the recomputed error. Idempotent: if no error exists and the value is unchanged, returns $this. Does not alter focus. |
Form final class
Top-level form container.
| Method | Summary |
|---|---|
static new(Field ...$fields): self | Single-page form. Equivalent to Form::groups(Group::new(...$fields)) — kept as the primary factory for backwards compatibility. |
static groups(Group ...$groups): self | Multi-page form. Each Group renders on its own page; the user advances with Tab past the last field on the page and pops back with Shift-Tab. Mirrors charmbracelet/huh.multi-group flow. |
init(): ?\Closure | Cmd returned the first time the runtime polls — typically the focused field's focus-Cmd (cursor blink, autocomplete preload). Mirrors sugar-core's Model::init(). |
withTheme(Theme $theme): self | Set the global theme. Per-Group overrides take priority via activeTheme(). Mirrors charmbracelet/huh.WithTheme. |
withAccessible(bool $on = true): self | Toggle accessibility mode. When on, the Form's view() degrades to a single-line "label: value" plain-text rendering for the focused field — designed for screen readers / non-TUI contexts. Mirrors charmbracelet/huh.WithAccessible. |
withShowHelp(bool $on = true): self | Show / hide the Step X of Y indicator drawn at the foot of a multi-group form's view. It paints only when the form has more than one group and the group's own help flag is on, so a single-group form renders the same either way. The form never draws key-help rows; those come from keyBinds() for the host to draw. Default on. Mirrors charmbracelet/huh.WithShowHelp. |
withShowErrors(bool $on = true): self | Show / hide the inline ! error line (and its ? help satellite) rendered by fields with active validation errors: Form::view() passes this flag into every field's view($showErrors). The end-of-form error withErrorSummary() block is a separate composer and is NOT affected. Default on. Mirrors charmbracelet/huh.WithShowErrors. |
withErrorSummary(bool $on = true): self | Show / hide an error summary at the end of the form after all fields are rendered. When enabled and validation errors exist, displays a list of field titles with their error messages. Default off. Mirrors charmbracelet/huh.WithErrorSummary. |
withWidth(int $cells): self | Pin the rendered width to $cells cells (clamped to 0). The budget is a CEILING, never an enlargement: each width-aware field keeps its own narrower budget where it set one. Choice lists cap and clip their lines at it, text fields scroll inside it, Slider/RadioPills size their track/row to it; every rendered line of a width-aware field — including its title, description and error rows — never exceeds it. The form's own chrome (group title/description, help footer, error summary) is clipped to it as well. Confirm, Note, Date, Color and FilePicker render at natural width: they carry no meaningful width knob, so the budget does not bind them (documented exemption, not a silent surprise). Default 0 = no budget: every line ships exactly as the field painted it. Mirrors charmbracelet/huh.WithWidth. |
withHeight(int $rows): self | Pin the rendered height. Currently advisory — fields decide how to use the budget. Default 0 = no cap. Mirrors charmbracelet/huh.WithHeight. |
withTimeout(int $ms): self | Auto-abort after $ms milliseconds of wall-clock time. The form stores the budget for the runtime to consult — it does not start a timer itself. Default 0 = no timeout. Mirrors charmbracelet/huh.WithTimeout(time.Duration). |
withKeyMap(?KeyMap $keyMap): self | Replace the form's KeyMap — the bindings for next / prev / submit / abort. Pass null to fall back to KeyMap::new(). |
withConstraints(?array $constraints): self | Store an explicit constraint set from sugar-constraints. |
activeKeyMap(): KeyMap | Resolved keymap — the configured override if set, else the default. |
theme(Theme $t): self | |
accessible(bool $on = true): self | |
showHelp(bool $on = true): self | |
showErrors(bool $on = true): self | |
errorSummary(bool $on = true): self | |
width(int $cells): self | |
height(int $rows): self | |
timeout(int $ms): self | |
keyMap(?KeyMap $keyMap): self | |
constraints(?array $constraints): self | |
focus(string $key): self | |
timeoutMs(): int | Configured timeout in milliseconds; 0 means none. |
activeTheme(): Theme | Resolved theme for the active group: the group's Group::withTheme() override when set, otherwise the form-level theme. |
nextGroup(): self | Advance to the next non-hidden group. No-op (returns the same instance) when already on the last group. Validators / hide-funcs on the current group are evaluated before the move. |
prevGroup(): self | Mirror of nextGroup() stepping backwards. |
activeGroupIndex(): int | Index of the active group, 0-based. |
totalGroups(): int | Total number of groups (including hidden ones). |
activeGroup(): Group | The Group struct that owns the currently-focused field. |
activeFields(): array | Field list for the active group, in declaration order. |
update(Msg $msg): array | Bubble-Tea Model update entry point. Routes the message to the focused field, applies form-level navigation (Tab / Shift-Tab / Up / Down) + abort (Esc / Ctrl-C) + submit (Enter on the last field), and returns [$next, $cmd]. |
view(): string | Render the form as a multi-line ANSI string. Honours the withAccessible() switch — when on, degrades to a single "label: value" line for the focused field (screen-reader friendly). |
values(): array | Final value map keyed on each field's Field::key(). Hidden groups, hidden fields and skippable fields (notes, separators) are excluded — only fields that participate in the user-driven flow appear in the result. |
hydrate(array $values): self | Restore values from a persisted snapshot (E736 5.9, round 89; hook is SF-23, sugar-forms-025) — the symmetric counterpart of values(): hydrate($form->values()) round-trips every field. Dispatch is on the Hydratable capability interface (the Field interface stays un-widened): Input / Text / Color / Select take stringables, MultiSelect takes its option string list, Confirm takes a bool, Slider takes int|float, NumberField takes int|float|null (null restores the empty box), Date and FilePicker take null|string (FilePicker the selected path — never navigation state), RadioPills takes a null|string option label. Third-party fields hydrate identically by implementing Hydratable. |
get(string $key, mixed $default = null): mixed | Untyped value lookup by key. Returns the field's raw value() for the given key, or $default when the key is unknown or the containing group is hidden. |
string(string $key, string $default = ''): string | String accessor — coerces scalar or stringable values; arrays are imploded with , to mirror charmbracelet/huh GetString. Returns $default on missing key or values that don't coerce sensibly. |
getString(string $key, string $default = ''): string | |
int(string $key, int $default = 0): int | Int accessor — coerces numeric values via (int) $v. Strings that aren't numeric return $default. |
getInt(string $key, int $default = 0): int | |
bool(string $key, bool $default = false): bool | Bool accessor — true / false / "true" / "false" / "yes" / "no" / "1" / "0" / 1 / 0. Anything else returns $default. |
getBool(string $key, bool $default = false): bool | |
array(string $key): array | Array accessor — returns a list when the underlying value is an array (multi-select); a single-element list when the value is a non-empty scalar; an empty list otherwise. |
getArray(string $key): array | |
isSubmitted(): bool | True after the last interactive field's Enter — values() is final. |
isAborted(): bool | True after Esc / Ctrl-C — partial values may still be available via values(). |
focusedField(): ?Field | The focused field, or null when the form is empty / submitted / aborted. |
getFocusedField(): ?Field | |
withFocus(string $key): self | Move focus to the field with the given key (E736 5.3, round 89). |
focusField(string $key): array | Programmatic focus with the TEA-shaped return (E736 5.3, round 89). Same rules as withFocus(); additionally surfaces the focused field's focus Cmd (blink / preload) so the runtime can schedule it. |
errors(): array | Validation errors keyed by field key. Hidden groups, hidden fields and skippable fields (Note) are excluded. Empty when every visible field validates cleanly. Mirrors charmbracelet/huh.Errors(). |
hasErrors(): bool | True when any visible field has a non-empty validation error. |
validateAll(): array | Run all field validators and return the full error map. Unlike errors() which only reports per-field inline errors (min/max violations, format errors), this also triggers any attached validators so cross-field constraints are evaluated. Returns array<fieldKey, errorMessage> for fields that fail. Mirrors charmbracelet/huh.ValidateAll(). |
validateAsync(): PromiseInterface | Async counterpart to validateAll() (plan 5.2, round 89 lane y3): walks the SAME progressive pass (hidden groups skipped, skippable fields skipped, values accumulated as it goes) but resolves through the event loop instead of returning inline. Fields implementing AsyncValidatable answer with a promise; every other field is resolved immediately from its synchronous revalidate() — so a form of purely synchronous fields settles in one microtask with EXACTLY the map validateAll() returns (parity pinned in FormAsyncValidateTest). |
keyBinds(): array | Currently-applicable key bindings rendered as [label, keys] rows suitable for a HOST status / help bar — the form's own view() never draws them (the showHelp flag gates only the Step-of indicator). The four navigation rows are derived live from self::activeKeyMap() (m21) — the labels follow whatever map the form actually uses, including custom bindings — followed by the advisory Enter row (SF-107: the split advance/submit role) and, when the form spans groups, the fixed next-page / prev-page rows. Label copy is catalogued (SF-33); the keys column of the derived rows stays the physical spelling. There is no per-field extras channel: keys a field consumes beyond the map live in that field's own update() (the README field-types table inventories them) and are deliberately not rendered here. Mirrors the surface of charmbracelet/huh.KeyBinds(). |
help(): string | Single-line help string composed from keyBinds(). Useful for host status bars / footers — like keyBinds(), the form's own view() never renders it; calling it is the host's choice. Mirrors charmbracelet/huh.Help(). |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
FormAsyncValidatedMsg final readonly class
Settlement envelope of a form-level async validation round (sugar-forms-020): Form::update() dispatched the batch on the Enter/submit path, and this message carries the verdicts back when every per-field AsyncValidatable::validateAsync() promise has settled.
| Method | Summary |
|---|---|
__construct(public array $errors, public int $seq) |
FormSuggestionsReadyMsg final readonly class
Async suggestions landed on a field — the forms-side delivery envelope carrying the fetch generation.
| Method | Summary |
|---|---|
__construct(public string $fieldKey, public array $suggestions, public int $seq = 0) |
Group final class
One page of fields in a multi-page Form.
| Method | Summary |
|---|---|
static new(Field ...$fields): self | |
static fromList(array $fields): self | |
withTitle(string $title): self | Set the page title rendered above the field list. |
withDescription(string $desc): self | Set the page description (sub-line under the title). |
withShowHelp(bool $on = true): self | Per-group help-bar toggle. When false, the Form suppresses the help line while this group is active. Default true. Mirrors charmbracelet/huh Group.WithShowHelp. |
withTheme(?Theme $theme): self | Override the Form theme while this group is active. Useful when a particular page wants a different palette (e.g. a "danger" page in red). Pass null to inherit the form-level theme. Mirrors charmbracelet/huh Group.WithTheme. |
withHideFunc(?\Closure $fn): self | Predicate evaluated on page transitions; receives the values collected so far (keyed by field key) and returns true to hide the group. "So far" is the same view navigation, rendering and Form::values() share: the visible fields of every visible group before this one — a field hidden by its own hide func, and any field of this or a later group, is never in the map. Hidden groups are skipped — both their fields and their values are excluded from the final form result. |
isHidden(array $values): bool | Evaluate withHideFunc() against the values collected so far. Returns true when the predicate is set and returned true — false otherwise (no predicate ⇒ never hidden). |
withFields(array $fields): self | Replace the field list. Useful when building groups from runtime data (e.g. one Confirm per row of a query result). |
title(string $t): self | |
desc(string $d): self | |
showHelp(bool $on = true): self | |
theme(?Theme $t): self | |
hideIf(?\Closure $fn): self | |
fields(array $fields): self |
HasAsyncValidation trait
Public face of async validation (plan 5.2, round 89 lane y3) for AsyncValidatable fields.
| Method | Summary |
|---|---|
withAsyncValidator(\Closure $fn): static | Attach the async leg of validation. Replaces any previous async validator; the synchronous validators stay in place and keep running first. |
asyncValidator(): ?\Closure | |
validateAsync(): PromiseInterface | Synchronous gate first, async leg second (see the interface docblock for why). VERDICT AUTHORITY (sugar-forms-055): the resolved string is the authoritative verdict for the value judged HERE; the field copy a host still holds keeps its pre-call error() until a revalidating path (the submit gate's re-apply) lands it — immutability gives this method no instance-return channel, and binding the verdict to an instance is the queued tuple upgrade (sugar-forms-49), not an accident to paper — until that ships, the DISCARD LAW in the trait docblock is what makes the shape safe (pins in tests/AsyncValidationVerdictIdentityTest.php). With no async validator attached this is exactly resolve(revalidate()->error()) — the async view of a purely synchronous field. |
HasDynamicLabels trait
Mixin trait for Field implementations: provides chainable withTitleFunc() / withDescriptionFunc() setters that evaluate at render time, mirroring huh's *Func setters.
| Method | Summary |
|---|---|
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool |
HasErrorHelp trait
Public face of the per-error help line (plan 5.11, round 89 lane y3).
| Method | Summary |
|---|---|
withErrorHelp(?string $help): static | Help line shown beside a validation error. null (the default) renders nothing; pass null again to clear. |
errorHelp(): ?string |
HasHideFunc trait
Mixin trait for Field implementations: provides a chainable withHideFunc() setter and the matching isHidden() accessor. Field classes use HasHideFunc; to opt into the runtime visibility predicate without re-implementing it.
| Method | Summary |
|---|---|
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool |
HasHydration trait
Stateless snapshot-parsing helpers for Hydratable fields (SF-23, sugar-forms-025).
HasKeyOverrides trait
Per-widget key-override maps (E736 plan 5.4, round 89).
| Method | Summary |
|---|---|
withKeyOverrides(array $map): static | Replace the binding map (canonical spellings documented on parseKeyOverrides()). The widget's stored keyOverrides stays the parsed canonical form; consult it with keyOverrides(). |
keyOverrides(): array | The parsed canonical map: ['ctrl+u' => 'move_end', ...]. Empty (default) means every key falls through to the widget's built-in handling. |
HasReadonly trait
Mixin trait for Field implementations: read-only mode. A read-only field still takes part in the form (focus, Tab navigation, render, value reporting) but refuses the keys that would change its value, mirroring the keepFilter precedent in \SugarCraft\Forms\ItemList\ItemList — the control keeps walking, only the mutation door closes (E736 5.10, round 89; upstream bubbles/huh has no readonly mode, so this is a SugarCraft-native extension).
| Method | Summary |
|---|---|
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
HasThemeChrome trait
Shared theme-application seam for SF-9 (sugar-forms-007/-029/-094).
Hydratable interface
A Field that can restore itself from a persisted snapshot value (SF-23, sugar-forms-025).
| Method | Summary |
|---|---|
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. |
key(): string | Stable identifier used by the form to key Form::values(). |
value(): mixed | Current value (string / bool / array / etc., field-specific). |
focus(): array | Take focus. Returns the new (focused) field plus an optional Cmd the runtime should schedule (cursor-blink, autocomplete-fetch, etc.). |
blur(): Field | Release focus. Returns a new (unfocused) field. |
update(Msg $msg): array | Apply a bubbletea message and return [$next, $cmd]. Mirrors the charmbracelet/bubbletea Model.Update(msg) shape. |
view(bool $showErrors = true, ?Theme $theme = null): string | Render the field as a multi-line ANSI string. $showErrors is the enclosing form's \SugarCraft\Forms\Form::withShowErrors() knob: false suppresses the inline ! error row and its ? help satellite (the form's error SUMMARY is a separate composer, always rendered when enabled). Default true keeps a standalone field's render byte-identical to the pre-SF-7 shape. |
isFocused(): bool | True while this field currently holds keyboard focus. |
getTitle(): string | Static title (the *Func form is resolved separately at view time). |
description(): string | Static description, same shape as getTitle(). |
error(): ?string | Latest validator error, or null when the value passes validation. |
getDescription(): string | |
getError(): ?string | |
skippable(): bool | Notes / separators / hidden fields skip Tab navigation. |
consumes(Msg $msg): bool | True if the field is in a state where the given Msg has internal meaning that should override Form-level handling. The Form checks this for keys it would otherwise capture (Enter / Escape) so that inner widgets can consume them — e.g. an ItemList in filter mode uses Enter to leave filter mode and Escape to clear it. |
isHidden(array $values): bool | Runtime visibility predicate. The form skips fields whose isHidden(values) returns true; both navigation and the values collector treat them as if they didn't exist. |
revalidate(): Field | Re-run validators/constraints against the current value and return a new field instance with the recomputed error. Idempotent: if no error exists and the value is unchanged, returns $this. Does not alter focus. |
KeyMap final class
Form-level key bindings — defines which keys advance / retreat / submit / abort a Form.
| Method | Summary |
|---|---|
__construct(public readonly array $next, public readonly array $prev, public readonly array $submit, public readonly array $abort) | |
static new(): self | Default huh-style bindings (the canonical factory — AGENTS.md naming: ::new() default, never ::default(); round-90 audit rename, no cross-lib callers existed): |
isNext(KeyMsg $msg): bool | True when $msg matches any of the entries in the next list. |
isPrev(KeyMsg $msg): bool | True when $msg matches any of the entries in the prev list. |
isSubmit(KeyMsg $msg): bool | True when $msg matches any of the entries in the submit list. |
isAbort(KeyMsg $msg): bool | True when $msg matches any of the entries in the abort list. |
labelsFor(string $binding): array | Human-readable key labels for one binding list, in the order they are bound — the surface Form::keyBinds() renders so help text always reflects the ACTIVE map, never a hardcoded string (m21). Modifier prefixes follow KeyMsg::string()'s ctrl+ / alt+ / shift+ order. |
withNext(array $entries): self | Replace the next binding list. |
withPrev(array $entries): self | Replace the prev binding list. |
withSubmit(array $entries): self | Replace the submit binding list. |
withAbort(array $entries): self | Replace the abort binding list. |
Lang final class
Per-library translation facade for sugar-forms.
SpinnerResult final class
Outcome of one ActionSpinner::run() — SF-46 (sugar-forms-067).
| Method | Summary |
|---|---|
static new(?int $exitCode, ?int $signal, bool $timedOut, float $wallSeconds): self | |
ok(): bool | Clean success: exited normally with status 0, not signal-killed, not timed out. |
throwIfFailed(): void | Opt into the old throw-on-failure contract (SF-35 copy intact): throws the localized spinner.action_failed row for a non-zero exit. A signal-killed child (exitCode null, signal set) and the timed-out case are NOT re-thrown here — the first never had a throw contract (it fell through as success pre-SF-46), the second throws from ActionSpinner::run() itself. |
Theme final class
Stylesheet for Form rendering. Each slot is a Style for one element type — title, description, focused/blurred field titles, cursor, options, error message, etc.
| Method | Summary |
|---|---|
__construct(public readonly Style $title, public readonly Style $description, public readonly Style $focusedTitle, public readonly Style $blurredTitle, public readonly Style $error, public readonly Style $errorSummary, public readonly Style $cursor, public readonly Style $option, public readonly Style $selectedOption, public readonly Style $help, public readonly Style $prompt, ?Style $errorSummaryItem = null, ?Style $submitted = null, ?Style $aborted = null) | |
static ansi(): self | Default coloured theme. Bright pink accents on the chrome. |
static plain(): self | No-style theme — every slot renders text verbatim. |
static charm(): self | Charm-brand pink + cyan. |
static dracula(): self | Dracula palette — dark magenta / cyan / green. |
static catppuccin(): self | Catppuccin "Mocha" pastel palette. |
static base16(): self | Base16 default — neutral and broadly compatible. |
static base(): self | Bare-bones monochrome — bold focus + reverse cursor, no colour. |
static catalog(): array | Returns a list of all available theme names. |
SugarCraft\Forms\Cursor
BlinkMsg final class
Cursor blink pulse for the cursor with id $id.
| Method | Summary |
|---|---|
__construct(public readonly int $id) |
Cursor final class
Text-cursor primitive used inside \SugarCraft\Forms\TextInput\TextInput (and similar). Renders the cell under it either highlighted (reverse video) or plain depending on $mode and the current blink state.
| Method | Summary |
|---|---|
__clone(): void | A direct clone is a NEW lineage: without re-keying, the copy would share the original's id and a BlinkMsg aimed at either one would toggle both (clone-collision case, E736 plan 3.1). PHP 8.3 permits re-initialising a readonly property inside __clone() precisely for this situation. Note this does NOT fire for shallow field clones — cloning a field copies the cursor REFERENCE, preserving the lineage, which is the intended TEA semantics. |
static new(string $char = ' ', Mode $mode = Mode::Blink, float $blinkSpeed = 0.5): self | Construct a fresh instance with default state. |
init(): ?\Closure | Bubble-Tea Init — returns the bootstrap Cmd (cursor blink, first tick, etc.) or null. |
update(Msg $msg): array | |
view(): string | Render the component as a multi-line ANSI string. |
focus(): array | Focus the cursor and (for blink mode) start the blink loop. |
blur(): self | Release focus; companion to { focus()}. |
setChar(string $c): self | |
setMode(Mode $m): self | |
withStyle(?Style $s): self | Highlight style — used when the cursor cell is "on" (focused + static mode, or blink-on). Default null = reverse video. |
withTextStyle(?Style $s): self | Off-state style — used when the cursor cell is "off" (unfocused, blink-off, or Hidden mode). Default null = bare char. |
id(): int | Stable per-lineage ID — identical across every immutable snapshot of one cursor; a direct clone re-keys to a fresh lineage. Mirror upstream Bubbles ID(). |
mode(): Mode | Current cursor mode. |
blinkSpeed(): float | Configured blink interval in seconds. Mirrors charmbracelet/bubbles.BlinkSpeed. |
isBlinked(): bool | True when the cursor is currently in the "off" half of a blink cycle (the cell is rendered without highlight). Mirrors charmbracelet/bubbles. IsBlinked(). |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
Mode enum
How a Cursor should render the cell under it:
Cases: Blink · Static · Hidden
PHP also provides cases(), from() and tryFrom().
SugarCraft\Forms\Field
AsyncFetcher final class
Shared execution guard for the async-suggestions fetcher (SF-004/SF-019).
| Method | Summary |
|---|---|
static runAndSettle(callable $fetcher, mixed $input, string $fieldKey, ?float $timeoutSeconds, Deferred $deferred, int $seq = 0): void | Invoke the fetcher inside the loop, then settle $deferred with its outcome. Any throw (including a non-promise return) rejects the deferred; a fulfilled non-array payload rejects with a typed message naming the key. The opt-in wall-clock ceiling is applied here too, belt-braced, because AsyncOps::withTimeout() raises synchronously on a non-positive/non-finite ceiling — a value that could reach this path only through a host that bypassed the setter validation. |
static validateConfig(string $fieldKey, int $debounceMs, ?float $fetchTimeoutSeconds): void | Config-time validation shared by both withAsyncSuggestions doors (SF-019: the same blast radius as a throwing fetcher, detonating at keystroke time instead of at the call site that made the mistake). |
Color final class
xterm-256 color swatch grid (E736 Phase-5 row 5.8, r88-x4). Mirrors the keyboard model of the charmbracelet/bubbles colorpicker: the 6x6x6 color cube, one 6x6 plane of red per page.
| Method | Summary |
|---|---|
static new(string $key, string|null $initial = null): self | |
withTitle(string $t): self | |
withDescription(string $d): self | |
withValue(string $hex): self | Accept #rrggbb or bare rrggbb (either case); each channel snaps to the nearest cube level, so the picker always displays a colour it can actually represent. The closest level wins ties (e.g. 115 → 95). |
withTruecolor(bool $on = true): self | Paint swatches with 24-bit 48;2 backgrounds instead of 48;5. |
title(string $t): self | |
desc(string $d): self | |
truecolor(bool $on = true): self | |
key(): string | |
value(): mixed | |
hex(): string | The committed colour, lowercase #rrggbb of the current cube corner. |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
view(bool $showErrors = true, ?Theme $theme = null): string | Title / description, the 6x6 plane (rows = blue, columns = green), then the value line #rrggbb R<r> G<g> B<b>. The cursor cell keeps its background code but adds REVERSE, so it renders as a hollow slot punched out of the painted plane. |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
getError(): ?string | |
skippable(): bool | |
consumes(Msg $msg): bool | Claims only what the default KeyMap would otherwise steal (see Select). |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — accepts a stringable snapshot value; the picker's hex shape is enforced by withValue() as always (SF-23). |
withValidator(Validator|\Closure|null $validator): self | Attach a validator (replaces the previous one; null clears). The new rule judges the current value immediately — the Confirm attach precedent — so a form restored over bad data shows its error on the first frame, not after the first edit. |
validator(Validator|\Closure|null $validator): self | Short-form alias for withValidator (README :124 alias contract). |
error(): ?string | Latest validator verdict, or null when the value passes validation. |
revalidate(): \SugarCraft\Forms\Field | The submit gate's re-judgement: run the rule against the current value. Idempotent — a verdict identical to the stored one returns $this (the Field contract's identity law, E736 1.3). |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
Confirm final class
Yes / No question. The user toggles the answer with ←/→, h/l, y / n, or Tab — with the honest caveat that Tab is the qualified one: consumes() never claims it, so under the default KeyMap Tab is routed to navigation at the form door and the toggle arm below is unreachable (the README row carries the same sentence — this docblock used to advertise the bare promise, the divergence SF-26 closed). The arm fires only when a custom map frees Tab from navigation; both polarities are pinned in tests/FormKeyDispatchTest.php.
| Method | Summary |
|---|---|
static new(string $key, bool $default = false): self | |
withTitle(string $t): self | |
withDescription(string $d): self | |
withLabels(string $yes, string $no): self | |
withDefault(bool $v): self | |
withValidator(Validator|\Closure|null $validator): self | Run the validator on every value change. Returns null on valid, a non-empty error string on invalid. Mirrors charmbracelet/huh.WithValidator on Confirm. |
title(string $t): self | |
desc(string $d): self | |
labels(string $yes, string $no): self | |
default(bool $v): self | |
validator(Validator|\Closure|null $fn): self | |
key(): string | |
value(): mixed | |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
view(bool $showErrors = true, ?Theme $theme = null): string | Render the prompt with the affirm/deny pills, the selected one in reverse video. |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | |
getDescription(): string | |
error(): ?string | |
getError(): ?string | |
skippable(): bool | |
consumes(Msg $msg): bool | |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — Confirm answers bool (SF-23). |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
revalidate(): Field | Re-run validators/constraints against the current value and return a new field instance with the recomputed error. Idempotent: if no error exists and the value is unchanged, returns $this. Does not alter focus. |
Date final class
Calendar-grid date picker (E736 Phase-5 row 5.6, r88-x4). Mirrors the keyboard model of the charmbracelet/bubbles datepicker reduced to the date half of HTML's date input: the value is a YYYY-MM-DD string, the grid walks it with arrows, and every movement commits.
| Method | Summary |
|---|---|
static new(string $key, ?string $initial = null): self | |
withTitle(string $t): self | |
withDescription(string $d): self | |
withValue(?string $date): self | Set (or with null, clear) the committed date. Setting also jumps the cursor to the new value so the grid always shows it. |
withValidator(Validator|\Closure|null $v): self | Attach a validator (null clears). A Validator instance is fed the committed value as a string — empty string while nothing is committed — so \SugarCraft\Forms\Validator\Required means "a date must be chosen". A Closure receives the ?string directly. Attaching re-judges the current value immediately (mirrors Confirm::withValidator()). |
title(string $t): self | |
desc(string $d): self | |
validator(Validator|\Closure|null $v): self | |
key(): string | |
value(): mixed | |
cursorDate(): string | The highlighted day (Y-m-d) — the grid's anchor. |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
view(bool $showErrors = true, ?Theme $theme = null): string | Render title / description, the month header, the weekday row and the calendar grid (Sunday-first; seven right-aligned two-character day cells joined by single-space gutters), then the committed-value line. The cursor cell carries the same reverse-video highlight Confirm uses for its pill — these widgets have no themeable style slots (the E736 3.9 rationale applies verbatim). |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
error(): ?string | Latest validator error, or null when the value passes validation. |
getError(): ?string | |
skippable(): bool | |
consumes(Msg $msg): bool | The default KeyMap binds Up/Down to form navigation; like Select in list mode the picker claims exactly those while focused (every other binding — arrows are its only collision) and Tab keeps leaving the field. |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — accepts string|null (SF-23). |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
revalidate(): Field | Re-run validators/constraints against the current value and return a new field instance with the recomputed error. Idempotent: if no error exists and the value is unchanged, returns $this. Does not alter focus. |
FilePicker final class
File-system picker field. Wraps PickerWidget; the field's value is whatever path the picker has selected (null until the user confirms a choice).
| Method | Summary |
|---|---|
static new(string $key, ?string $cwd = null): self | |
withTitle(string $t): self | |
withDescription(string $d): self | |
withShowHidden(bool $on): self | |
withAllowedExtensions(array $exts): self | |
withDirAllowed(bool $on): self | |
withFileAllowed(bool $on): self | |
withHeight(int $h): self | |
title(string $t): self | |
desc(string $d): self | |
showHidden(bool $on): self | |
exts(array $exts): self | |
dirAllowed(bool $on): self | |
fileAllowed(bool $on): self | |
height(int $h): self | |
key(): string | |
value(): mixed | |
path(): ?string | Selected path (the self::value() read under its domain name). |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
view(bool $showErrors = true, ?Theme $theme = null): string | |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
getError(): ?string | |
skippable(): bool | |
consumes(Msg $msg): bool | Enter (descend / select) and Backspace (ascend) are owned by the picker; the form must not absorb them. Up / Down move the cursor between entries and must not be stolen for between-field nav. |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — accepts string|null: the selected path restores WITHOUT moving navigation, the deliberate asymmetry of saving only the value half of the picker (SF-23). |
withValidator(Validator|\Closure|null $validator): self | Attach a validator (replaces the previous one; null clears). The new rule judges the current value immediately — the Confirm attach precedent — so a form restored over bad data shows its error on the first frame, not after the first edit. |
validator(Validator|\Closure|null $validator): self | Short-form alias for withValidator (README :124 alias contract). |
error(): ?string | Latest validator verdict, or null when the value passes validation. |
revalidate(): \SugarCraft\Forms\Field | The submit gate's re-judgement: run the rule against the current value. Idempotent — a verdict identical to the stored one returns $this (the Field contract's identity law, E736 1.3). |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
HasValidation trait
Single-slot validation machinery for the selectable fields that never carried a validator surface (sugar-forms-026).
| Method | Summary |
|---|---|
withValidator(Validator|\Closure|null $validator): self | Attach a validator (replaces the previous one; null clears). The new rule judges the current value immediately — the Confirm attach precedent — so a form restored over bad data shows its error on the first frame, not after the first edit. |
validator(Validator|\Closure|null $validator): self | Short-form alias for withValidator (README :124 alias contract). |
error(): ?string | Latest validator verdict, or null when the value passes validation. |
revalidate(): \SugarCraft\Forms\Field | The submit gate's re-judgement: run the rule against the current value. Idempotent — a verdict identical to the stored one returns $this (the Field contract's identity law, E736 1.3). |
Input final class
Single-line text field. Wraps a TextInput and exposes an optional validator that runs on every keystroke.
| Method | Summary |
|---|---|
static new(string $key): self | |
withTitle(string $t): self | |
withDescription(string $d): self | |
withPlaceholder(string $p): self | |
withValue(string $value): self | Pre-fill the editable text with an initial value. Unlike a placeholder this is the actual submitted value until the user edits it. Pass an empty string to clear. |
withPrompt(string $p): self | |
withCharLimit(int $n): self | |
withWidth(int $w): self | |
withKeyOverrides(array $map): self | E736 5.4 — rebind keys inside this field's input domain. The map lives on the inner TextInput (single owner of the edit primitives); spellings + actions are validated at set time — see \SugarCraft\Forms\HasKeyOverrides. |
keyOverrides(): array | The parsed override map carried by the inner widget. @return array<string,string> |
withHistory(array $history): self | Populate the recall history for the inner text input (SF-40 / sugar-forms-022: the field-level door — the widget has always had withHistory, the Field API never exposed it). Up/Down recall is a key-map contract: under the default map those chords drive field navigation, so recall lands when a custom map frees them (or when the host forwards them here). |
addToHistory(string $entry): self | Append one entry to the recall history (dedupe and the history limit are the widget's; not wired into Enter automatically — same discipline as TextInput::addToHistory()). |
title(string $t): self | |
desc(string $d): self | |
placeholder(string $p): self | |
prompt(string $p): self | |
charLimit(int $n): self | |
width(int $w): self | |
password(bool $on = true, string $echoChar = '*'): self | |
suggest(array $candidates): self | |
fuzzy(array $candidates): self | |
validator(\Closure $fn): self | |
validation(callable $predicate, string $errorMessage): self | |
required(): self | |
email(): self | |
minlength(int $n): self | |
maxlength(int $n): self | |
passwordMask(?string $pattern, string $echoChar = '*'): self | |
suggestionsFunc(\Closure $fn): self | |
validateOn(ValidateOn $when): self | |
history(array $history): self | |
withPassword(bool $on = true, string $echoChar = '*'): self | Mask the rendered value with a fixed echo character. Mirrors charmbracelet/huh.Password() modifier — handy for token / passphrase prompts. Pass an empty echo char to fall back to the default * (the value stays masked); clearing masking itself is withPassword(false) or withPasswordMask(null) on this field. |
withPasswordMask(?string $pattern, string $echoChar = '*'): self | E736 5.5 — the pattern-based upgrade of withPassword(): matched characters echo as $echoChar, the rest render verbatim (partial masks like 4111 **** **** 1111). Mirrors charmbracelet/huh.Password() in spirit; the pattern granularity is the SugarCraft extension. Null clears back to plain rendering. The pattern is compile-checked at this door (with the renderer's own /u flags) and throws loudly — it can never silently disable masking. |
withSuggestions(array $candidates): self | Provide an autocomplete pool that the user can cycle with the default TextInput suggestion bindings. Pass an empty list (or omit) to disable. Mirrors charmbracelet/huh.Suggestions([]string). |
withSuggestionsFunc(\Closure $fn): self | Dynamic suggestions: the closure receives the current input value (post-keystroke) and returns the candidate list to display. Mirrors charmbracelet/huh SuggestionsFunc. The closure is re-evaluated on every keystroke so callers can hit a remote completion endpoint, etc. |
withFuzzySuggestions(array $candidates): self | Provide an autocomplete pool that is filtered and ranked by fuzzy substring match (Smith-Waterman scoring) against the current input value. The user picks from the ranked suggestion list via arrow keys. Mirrors charmbracelet/huh.WithFuzzySuggestions([]string). |
withAsyncSuggestions(callable $fetcher, int $debounceMs = 150, ?WorkerPool $workerPool = null, ?float $fetchTimeoutSeconds = null): self | Async suggestions via a callable that returns a Promise. Debounces for $debounceMs after each keystroke, then calls the fetcher. Mirrors charmbracelet/huh.async suggestion pattern. |
async(callable $fetcher, int $debounceMs = 150, ?WorkerPool $workerPool = null, ?float $fetchTimeoutSeconds = null): self | Short-form alias for withAsyncSuggestions. |
withValidator(Validator|\Closure $validator): self | Attach a validator. Accepts a Validator instance or a closure. Multiple calls chain validators together — each runs in sequence and the first error message is returned. |
withValidateOn(ValidateOn $timing): self | Control WHEN the Field-level validator chain runs. Mirrors the timing modes of the inner TextInput but applies to the Field's own validators (which run independently of the TextInput's). |
withValidation(callable $predicate, string $errorMessage): self | Attach a validation rule using a predicate + error message. The predicate receives the current value and returns true if valid, false if invalid. When invalid the $errorMessage is displayed. |
key(): string | |
value(): mixed | |
displayValue(): string | Echo-safe display projection (SF-2): password/mask fields yield the same characters a sighted user sees, never the raw secret. Normal fields return the value verbatim. |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
view(bool $showErrors = true, ?Theme $theme = null): string | |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
error(): ?string | Latest validator error, or null when the value passes validation. |
getError(): ?string | |
revalidate(): Field | |
skippable(): bool | |
consumes(Msg $msg): bool | Claims the async-resolution envelope addressed to this field — the message update() special-handles (sugar-forms-056(a): the unconditional false lied to the router at Form.php:378). |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — accepts a stringable snapshot value (SF-23). |
withAsyncValidator(\Closure $fn): static | Attach the async leg of validation. Replaces any previous async validator; the synchronous validators stay in place and keep running first. |
asyncValidator(): ?\Closure | |
validateAsync(): PromiseInterface | Synchronous gate first, async leg second (see the interface docblock for why). VERDICT AUTHORITY (sugar-forms-055): the resolved string is the authoritative verdict for the value judged HERE; the field copy a host still holds keeps its pre-call error() until a revalidating path (the submit gate's re-apply) lands it — immutability gives this method no instance-return channel, and binding the verdict to an instance is the queued tuple upgrade (sugar-forms-49), not an accident to paper — until that ships, the DISCARD LAW in the trait docblock is what makes the shape safe (pins in tests/AsyncValidationVerdictIdentityTest.php). With no async validator attached this is exactly resolve(revalidate()->error()) — the async view of a purely synchronous field. |
withErrorHelp(?string $help): static | Help line shown beside a validation error. null (the default) renders nothing; pass null again to clear. |
errorHelp(): ?string | |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
MultiSelect final class
Multi-checkbox picker. Cursor moves with ↑↓/jk, Space toggles the highlighted item. Optional withMin() / withMax() constrain the number of selected items (0 = unlimited).
| Method | Summary |
|---|---|
static new(string $key, array|string ...$options): self | |
withOptions(string ...$options): self | |
withWidth(int $w): self | Choice lines budget in terminal cells (0 = natural width). |
withTitle(string $t): self | |
withDescription(string $d): self | |
withMin(int $n): self | Force at least N selections (0 = no minimum). |
withValue(array $selectedOptions): self | Set the selection from option STRINGS (E736 5.9: the hydration setter — round-trips what value() returns). An option string the field does not offer fails loud, naming it: silence here would ship a "saved" form that quietly loses picks on restore. The min/max constraint error is recomputed so a restored selection that no longer fits the caps surfaces instead of masquerading as valid. |
withMax(int $n): self | Cap selections at N (0 = no limit). |
withLimit(int $n): self | huh-style combined cap: a single integer that sets both the minimum (0) and maximum to the same value when positive. Matches charmbracelet/huh WithLimit shape — convenient when you want "exactly N or fewer" as one call. Pass 0 to clear both. |
title(string $t): self | |
desc(string $d): self | |
options(string ...$options): self | |
width(int $w): self | |
min(int $n): self | |
max(int $n): self | |
limit(int $n): self | |
key(): string | |
value(): mixed | |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
view(bool $showErrors = true, ?Theme $theme = null): string | |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
error(): ?string | Latest validator error, or null when the value passes validation. |
getError(): ?string | |
revalidate(): Field | |
skippable(): bool | |
consumes(Msg $msg): bool | Up / Down / j / k move the inner cursor; without claiming them the form would steal the keys for between-field navigation, leaving the checkbox cursor unreachable. |
withValidator(?\Closure $validator): self | SF-24 custom slot alongside the count constraint. The rule receives the list of selected option labels (option order); the min/max bounds are judged first — a count violation owns the row. Replaces the previous rule; null clears. Deliberately closure-only: the subject is a LIST, which the string-typed Validator contract cannot express (the trait's alias fails loud here by TypeError, which is the point). |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — accepts a list of stringable option values (SF-23). |
validator(Validator|\Closure|null $validator): self | Short-form alias for withValidator (README :124 alias contract). |
withErrorHelp(?string $help): static | Help line shown beside a validation error. null (the default) renders nothing; pass null again to clear. |
errorHelp(): ?string | |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
Note final class
Read-only paragraph. Renders title + description; tab navigation skips over the field by default. When withNext() is enabled, the Note becomes interactive: a labelled button is rendered after the description and Enter activates it — through the Form's generic advance arm, not a Note-level binding (Space is bound nowhere) (mirrors charmbracelet/huh Note.Next / NextLabel).
| Method | Summary |
|---|---|
__construct(public readonly string $key, public readonly string $title = '', public readonly string $description = '', public readonly int $height = 0, public readonly bool $next = false, public readonly string $nextLabel = '', public readonly bool $focused = false) | |
static new(string $key): self | |
withTitle(string $t): self | |
withDescription(string $d): self | |
withHeight(int $rows): self | Pin the rendered note to a fixed row count. Padding-only — short content is bottom-padded with blanks; over-long content still renders in full so callers don't lose information silently. Default 0 = render at natural height. Mirrors charmbracelet/huh.Note.Height. |
withNext(bool $on = true): self | Show a confirm-style button after the description. When on, the Note participates in form navigation (no longer skippable) and Enter advances to the next field — through the Form's generic advance arm; Space is bound nowhere (lane p4, F-P4-3 truth-flip). Mirrors charmbracelet/huh.Note.Next(bool). |
withNextLabel(string $label): self | Override the button label rendered by withNext(). Default Next. Mirrors charmbracelet/huh.Note.NextLabel. |
title(string $t): self | |
desc(string $d): self | |
height(int $rows): self | |
next(bool $on = true): self | |
nextLabel(string $l): self | |
getNextLabel(): string | NOTE (accessor era, 2026-10-24): this getNextLabel() read cannot lose its get* prefix — the bare nextLabel() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. — Resolved button label (post-default). |
isNext(): bool | True when the Next button is rendered & participates in nav. |
getHeight(): int | NOTE (accessor era, 2026-10-24): this getHeight() read cannot lose its get* prefix — the bare height() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. — Configured row budget; 0 means natural height. |
key(): string | |
value(): mixed | |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
view(bool $showErrors = true, ?Theme $theme = null): string | |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
error(): ?string | Latest validator error, or null when the value passes validation. |
getError(): ?string | |
revalidate(): Field | |
skippable(): bool | |
consumes(Msg $msg): bool | |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
NumberField final class
Bounded numeric field (crush_media W3.3, plan :433-445). Where a Slider is structurally wrong — an A1111-style seed is an int64, not a draggable ratio — this is the truthful widget: a text draft composed over TextInput plus Slider's normalisation surface for everything the draft is not.
| Method | Summary |
|---|---|
static new(string $key, int|float $min = 0, int|float $max = 100, int|float $step = 1, int|float|null $initial = null): self | |
withTitle(string $t): self | |
withDescription(string $d): self | |
withPlaceholder(string $p): self | |
withPrompt(string $p): self | |
withWidth(int $w): self | |
withValue(int|float $v): self | Commit a number: coerce onto the lattice, re-draw the draft, clear any error. |
withoutValue(): self | Return to the never-set state: value null, draft empty, error cleared. The distinct absence of a value — hasValue() — is the point (empty box ≠ 0, both in the model and on screen). |
withMin(int|float $m): self | Move a bound; the committed value re-coerces against the new lattice. |
withMax(int|float $m): self | |
withStep(int|float $s): self | |
title(string $t): self | |
desc(string $d): self | |
placeholder(string $p): self | |
prompt(string $p): self | |
width(int $w): self | |
min(int|float $m): self | |
max(int|float $m): self | |
step(int|float $s): self | |
key(): string | |
value(): mixed | |
hasValue(): bool | |
draft(): string | The uncommitted draft text exactly as displayed. |
focus(): array | |
blur(): Field | Release focus — a commit point: the draft is judged on the way out. |
update(Msg $msg): array | |
view(bool $showErrors = true, ?Theme $theme = null): string | Render title/description, the draft line, then any parse error. |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
error(): ?string | Latest validator error, or null when the value passes validation. |
getError(): ?string | |
skippable(): bool | |
consumes(Msg $msg): bool | |
revalidate(): Field | The Form's submit gate calls this: an uncommitted draft is judged, so an invalid box surfaces its error at submit instead of silently shipping its last good value. Idempotent once the draft matches the committed display ($this survives — the contract's identity law). |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — accepts int|float|null; null restores the never-set empty box rather than writing a zero (SF-23). |
withValidator(Validator|\Closure|null $validator): self | Attach a validator (replaces the previous one; null clears). The new rule judges the current value immediately — the Confirm attach precedent — so a form restored over bad data shows its error on the first frame, not after the first edit. |
validator(Validator|\Closure|null $validator): self | Short-form alias for withValidator (README :124 alias contract). |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
RadioPills final class
Horizontal radio-pill row (crush_media W3.3, droppable half of plan :433-445): a single-choice widget in the A1111 mask-mode-radio shape — Confirm's raw-reverse pill idiom stretched over an option list.
| Method | Summary |
|---|---|
static new(string $key, array|string ...$options): self | |
withTitle(string $t): self | |
withDescription(string $d): self | |
withWidth(int $w): self | Budget in cells available to the pill row (minimum 1). A roster that fits renders whole; one that does not is windowed around the selection with ellipsis markers on the clipped sides. Null (the default) keeps the full unwindowed line. |
withOptions(string ...$options): self | Replace the option list. The current selection survives by LABEL when the new list still carries it — pill identity is the label, so a re-order re-points the cursor and a removal falls back to option 0. |
title(string $t): self | |
desc(string $d): self | |
options(string ...$options): self | Alias of withOptions(), family shape (Select::options()). |
width(int $w): self | Alias of withWidth(), family shape (Slider::width()). |
withValue(mixed $label): self | Jump the selection to a label; an unknown label is a refusal (same instance). |
key(): string | |
value(): mixed | The selected label — the widget's whole value; null while the row is empty. |
cursor(): int | Index of the selected pill (0 on an empty row — only value() distinguishes). |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
handleZoneMouse(MouseMsg $msg, int $zoneLeft): ?self | Host-callable zone click, the Slider W3.2 ruling mirrored: the host owns the hit-test geometry and passes the row's left column; press, motion and release behave identically, wheel and non-left refuse, and read-only refuses the whole message (moving the cursor IS committing). |
view(bool $showErrors = true, ?Theme $theme = null): string | Title / description, then the pill row — the selected pill in raw reverse video, the rest plain, separated by three dead cells (the Confirm idiom, deliberately unpainted: E736 3.9 — these widgets carry no themeable style slots). |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the Field interface declares getTitle() as the contract read, and eleven sibling fields have the bare title() slot taken by a live fluent setter, so the family cannot go bare class-by-class. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
getError(): ?string | |
skippable(): bool | |
consumes(Msg $msg): bool | |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — accepts string|null option labels; null restores the cursor-less nothing-selected state. An unknown label declines via the SF-22 notes channel exactly like Select (SF-23). |
withValidator(Validator|\Closure|null $validator): self | Attach a validator (replaces the previous one; null clears). The new rule judges the current value immediately — the Confirm attach precedent — so a form restored over bad data shows its error on the first frame, not after the first edit. |
validator(Validator|\Closure|null $validator): self | Short-form alias for withValidator (README :124 alias contract). |
error(): ?string | Latest validator verdict, or null when the value passes validation. |
revalidate(): \SugarCraft\Forms\Field | The submit gate's re-judgement: run the rule against the current value. Idempotent — a verdict identical to the stored one returns $this (the Field contract's identity law, E736 1.3). |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
Select final class
Single-choice picker. Wraps ItemList; the field's value is the highlighted item's title (or null when empty).
| Method | Summary |
|---|---|
static new(string $key, array|string ...$options): self | |
withOptions(string ...$options): self | |
withFuzzySuggestions(array $candidates): self | Provide a candidate pool that is filtered and ranked by fuzzy substring match (Smith-Waterman scoring) against the user's filter keystrokes. The suggestion list ranks by score; user picks via arrow keys. Mirrors charmbracelet/huh.WithFuzzySuggestions([]string). |
withAsyncSuggestions(callable $fetcher, int $debounceMs = 150, ?WorkerPool $workerPool = null, ?float $fetchTimeoutSeconds = null): self | Async suggestions via a callable that returns a Promise. Debounces for $debounceMs after each filter keystroke, then calls the fetcher. The fetcher receives the current filter text and returns a promise of suggestions. Mirrors charmbracelet/huh.async suggestion pattern. |
async(callable $fetcher, int $debounceMs = 150, ?WorkerPool $workerPool = null, ?float $fetchTimeoutSeconds = null): self | Short-form alias for withAsyncSuggestions. |
withTitle(string $t): self | |
withDescription(string $d): self | |
withHeight(int $h): self | |
withVisibleLines(int $lines): self | Opt the dropdown into a strict LINES page budget instead of the item-count height (SF-27, sugar-forms-031 — with descriptions on, item-count height can paint up to twice the lines it nominally budgets). 0 restores item-count windowing. |
withWidth(int $w): self | Clip list lines to this cell budget (ItemList honours it in view — SF-05's per-line clip). The height slot rides through untouched. |
withSelectedIndex(int $index): self | Pre-select an option by its 0-based index. Negative indices clamp to 0; the inner ItemList clamps the upper bound. Handy for showing a form's current value before the user touches it. |
withSelected(string $value): self | Pre-select the option whose value matches $value. When the value is not among the field's options the selection is left unchanged. Delegates to withSelectedIndex() once the index is resolved. |
withEnum(string $enumClass): self | When a backed enum class is provided, the selected value is projected to the enum via EnumClass::tryFrom($stringValue) (unmappable titles read null — see value()). The option titles must match the enum case values exactly. Mirrors no upstream symbol: huh has no enum option mode (SugarCraft-native, modeled on tty-prompt enum_select per docs/research/libraries/sugar-forms-huh-research.md §3.6). |
title(string $t): self | |
desc(string $d): self | |
height(int $h): self | |
width(int $w): self | |
options(string ...$options): self | |
fuzzy(array $candidates): self | |
enum(string $enumClass): self | |
selected(string $v): self | |
selectedIndex(int $index): self | |
visibleLines(int $lines): self | |
key(): string | |
value(): mixed | Enum mode projects through \BackedEnum::tryFrom(), NOT from(): an option title that drifted off the enum (the pool was re-armed with a subset, the enum gained/renamed cases) projects to null so the frame path Form::values() never explodes (sugar-forms-024). The option titles are expected to match enum case values exactly; a null read IS the divergence signal, and hydrate surfaces the absent-value note (sugar-forms-072) via Form::$hydrateNotes. |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
view(bool $showErrors = true, ?Theme $theme = null): string | |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
getError(): ?string | |
skippable(): bool | |
consumes(Msg $msg): bool | In filter mode the inner ItemList uses Enter to leave the filter and Escape to clear it; both must be consumed locally so the Form doesn't advance/abort while the user is filtering. Up / Down also belong to the list — without consuming them the form would steal arrow keys for between-field navigation. |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — accepts a stringable option value. An absent option declines the restore via the SF-22 notes channel instead of throwing (SF-23). |
withValidator(Validator|\Closure|null $validator): self | Attach a validator (replaces the previous one; null clears). The new rule judges the current value immediately — the Confirm attach precedent — so a form restored over bad data shows its error on the first frame, not after the first edit. |
validator(Validator|\Closure|null $validator): self | Short-form alias for withValidator (README :124 alias contract). |
error(): ?string | Latest validator verdict, or null when the value passes validation. |
revalidate(): \SugarCraft\Forms\Field | The submit gate's re-judgement: run the rule against the current value. Idempotent — a verdict identical to the stored one returns $this (the Field contract's identity law, E736 1.3). |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
Slider final class
Horizontal handle slider (E736 Phase-5 row 5.7, r88-x4). Mirrors charmbracelet/bubbles' slider: a [███◆░░░] track over an inclusive numeric range with a fixed step lattice.
| Method | Summary |
|---|---|
static new(string $key, int|float $min = 0, int|float $max = 100, int|float $step = 1, int|float|null $initial = null): self | |
withTitle(string $t): self | |
withDescription(string $d): self | |
withValue(int|float $v): self | Seed/clamp/re-align the value. Out-of-range numbers are pulled into range and off-lattice numbers snapped to the nearest step — the widget cannot hold an unrepresentable state, so the setter never throws on a mere number. |
withMin(int|float $m): self | Move the lower bound; the value re-normalises against the new lattice. |
withMax(int|float $m): self | Move the upper bound; the value re-normalises against the new lattice. |
withStep(int|float $s): self | Change the step lattice; the value snaps to the nearest new step. |
withWidth(int $w): self | Track width in cells, handle included (minimum 1). |
withValidator(Validator|\Closure|null $v): self | Attach a validator (null clears). A Validator instance is fed the number as a display string (int stays 7, float prints its shortest form); a Closure receives the raw int|float. Attaching re-judges the current value immediately (mirrors Confirm::withValidator()). |
title(string $t): self | |
desc(string $d): self | |
width(int $w): self | |
default(int|float $v): self | |
min(int|float $m): self | |
max(int|float $m): self | |
step(int|float $s): self | |
validator(Validator|\Closure|null $v): self | |
key(): string | |
value(): mixed | |
position(): int | Lattice index of the current value: 0 == min, steps() == top. |
steps(): int | Number of step increments between min and max (lattice top index). |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
handleZoneMouse(MouseMsg $msg, int $zoneLeft, int $zoneWidth): ?self | Host-callable zone drag (crush_media W3.2, plan :417-431). This is the Shape-A-vs-B of widget mouse support and the ruling lands on B-plus-A: Slider stays dependency-free — it types sugar-core's own MouseMsg (already a required sibling, zero new composer requires), so a host on the TEA channel just forwards messages to update(), while a host that owns the layout geometry (candy-code runs sugar-mouse and knows the track's absolute screen rect) hit-tests itself and calls THIS method with the zone it computed. |
view(bool $showErrors = true, ?Theme $theme = null): string | Title / description, then the track: '[' + filled blocks + handle + empty blocks + ']' followed by the value label. The glyphs are the bubbles look (U+2588 / U+2591) with a U+25C6 diamond handle, unpainted like Confirm's raw-reverse pills — these widgets carry no themeable style slots (E736 3.9 rationale). |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
error(): ?string | Latest validator error, or null when the value passes validation. |
getError(): ?string | |
skippable(): bool | |
consumes(Msg $msg): bool | |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — accepts int|float (SF-23). |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
revalidate(): Field | Re-run validators/constraints against the current value and return a new field instance with the recomputed error. Idempotent: if no error exists and the value is unchanged, returns $this. Does not alter focus. |
Text final class
Multi-line text field. Wraps a TextArea; Enter inserts a newline inside the field rather than advancing the form, so the field declares itself a consumer of Enter via consumes().
| Method | Summary |
|---|---|
static new(string $key): self | |
withTitle(string $t): self | |
withDescription(string $d): self | |
withPlaceholder(string $p): self | |
withValue(string $value): self | Pre-fill the editable text (E736 5.9: the hydration setter). Pass an empty string to clear. |
withCharLimit(int $n): self | |
withWidth(int $w): self | |
withHeight(int $h): self | |
withKeyOverrides(array $map): self | E736 5.4 — rebind keys inside this field's input domain (row-relative semantics — see \SugarCraft\Forms\TextArea\TextArea::keyOverrideActions()). |
keyOverrides(): array | The parsed override map carried by the inner widget. @return array<string,string> |
withValidator(\Closure $fn): self | Attach the validation closure (sugar-forms-026 warning): Text holds ONE closure-only slot and a second call REPLACES the first — unlike Input, which chains appends and keeps the first-error-wins order. There is no Validator-instance path and no null-to-clear here: pass a closure, or pass a fresh one to swap it. |
withValidateOn(ValidateOn $timing): self | Control WHEN the validator runs. Defaults to validate-on-every-keystroke. ValidateOn::Blur / ValidateOn::Submit defer validation to blur() / revalidate() so an expensive validator isn't paid on every keypress. Mirrors Input::withValidateOn(). |
withValidation(callable $predicate, string $errorMessage): self | Attach a validation rule using a predicate + error message. The predicate receives the current value and returns true if valid, false if invalid. When invalid the $errorMessage is displayed. |
title(string $t): self | |
desc(string $d): self | |
placeholder(string $p): self | |
charLimit(int $n): self | |
width(int $w): self | |
height(int $h): self | |
validator(\Closure $fn): self | |
validation(callable $predicate, string $errorMessage): self | |
validateOn(ValidateOn $when): self | |
key(): string | |
value(): mixed | |
focus(): array | |
blur(): Field | |
update(Msg $msg): array | |
view(bool $showErrors = true, ?Theme $theme = null): string | |
isFocused(): bool | |
getTitle(): string | NOTE (accessor era, 2026-10-24): this getTitle() read cannot lose its get* prefix — the bare title() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
description(): string | Static description, same shape as getTitle(). |
getDescription(): string | |
error(): ?string | Latest validator error, or null when the value passes validation. |
getError(): ?string | |
revalidate(): Field | |
skippable(): bool | |
consumes(Msg $msg): bool | Enter inside a Text field inserts a newline rather than advancing the form. Up / Down move the inner cursor between lines and must not be hijacked by the form's between-field navigation. |
hydrateValue(mixed $raw, array &$notes = []): static | Return a field carrying the snapshot's value for this field. — accepts a stringable snapshot value (SF-23). |
withAsyncValidator(\Closure $fn): static | Attach the async leg of validation. Replaces any previous async validator; the synchronous validators stay in place and keep running first. |
asyncValidator(): ?\Closure | |
validateAsync(): PromiseInterface | Synchronous gate first, async leg second (see the interface docblock for why). VERDICT AUTHORITY (sugar-forms-055): the resolved string is the authoritative verdict for the value judged HERE; the field copy a host still holds keeps its pre-call error() until a revalidating path (the submit gate's re-apply) lands it — immutability gives this method no instance-return channel, and binding the verdict to an instance is the queued tuple upgrade (sugar-forms-49), not an accident to paper — until that ships, the DISCARD LAW in the trait docblock is what makes the shape safe (pins in tests/AsyncValidationVerdictIdentityTest.php). With no async validator attached this is exactly resolve(revalidate()->error()) — the async view of a purely synchronous field. |
withErrorHelp(?string $help): static | Help line shown beside a validation error. null (the default) renders nothing; pass null again to clear. |
errorHelp(): ?string | |
withHideFunc(?\Closure $fn): static | |
hideFunc(?\Closure $fn): static | Short-form alias of withHideFunc() (SF-44 alias grid). |
isHidden(array $values): bool | |
withTitleFunc(?\Closure $fn): static | |
titleFunc(?\Closure $fn): static | Short-form alias of withTitleFunc() (SF-44 alias grid). |
withDescriptionFunc(?\Closure $fn): static | |
descriptionFunc(?\Closure $fn): static | Short-form alias of withDescriptionFunc() (SF-44 alias grid). |
resolveTitle(string $static): string | Resolve the title — closure wins when set, otherwise the static field string. Field bodies should call this from getTitle() / view() instead of reading $this->title directly. |
resolveDescription(string $static): string | Mirror of resolveTitle() for the description slot — same RenderSafe::clean() sanitisation, for the same reason. |
hasTitleFunc(): bool | |
hasDescriptionFunc(): bool | |
withReadonly(bool $on = true): static | Flip read-only mode. Like HasHideFunc's withHideFunc, the clone + direct write is the trait's sanctioned pattern: the write lands on the fresh clone before it is returned, so no other reference can observe a half-mutated object. |
readonly(bool $on = true): static | Short-form alias of withReadonly() (SF-44 alias grid). The reserved word is legal as a method name since PHP 7.0 and the read keeps isReadonly() — no squat to route around. |
isReadonly(): bool | True while the field refuses mutating input. |
static isReadonlyMutatingMsg(Msg $msg): bool | The read-only mutation door: does $msg carry a payload that can WRITE this field's value buffer? Keys, bracketed paste (E736 5.13) and the external-editor round-trip (TextAreaEditedMsg) all do — a gate that only pattern-matches KeyMsg leaves the paste/editor writes wide open on a supposedly-frozen buffer, which is exactly the round-90 audit finding on \SugarCraft\Forms\Field\Text. Everything that merely animates (BlinkMsg) or reports the environment is inert and keeps flowing. Async results (FormSuggestionsReadyMsg) are delivered on an arm that runs BEFORE this door — harmless for a text editor (it only fills the suggestion popup, never the value buffer), but a picker whose value IS the highlighted entry re-points it, so \SugarCraft\Forms\Field\Select refuses that arm while read-only itself (round-90 review follow-up) rather than through this classifier. |
static isReadonlyNavigationKey(Msg $msg): bool | Cursor-motion keys accepted while a picker is read-only: the exact motion set ItemList's own arms and MultiSelect's match consume — Up/Down/Home/End/PageUp/PageDown and their vim runes j k g G. These never toggle a selection, but for a picker whose value IS the highlighted item they still drift the reported value — accepted by the 5.10 ruling (navigation stays free while read-only; only mutation is frozen). Toggle and filter keys deliberately fall through as "not navigation". |
SugarCraft\Forms\FilePicker
Entry final class
One filesystem entry the FilePicker has discovered.
| Method | Summary |
|---|---|
__construct(public readonly string $name, public readonly bool $isDir, public readonly bool $isHidden, public readonly int $size = 0, public readonly int $mtime = 0) | |
path(string $cwd): string | |
static join(string $cwd, string $name): string | Join a directory and entry name using the separator the caller's path already speaks. On Windows DIRECTORY_SEPARATOR is '\' yet callers may hold slash-shaped paths (forwarded dial strings, '/'-typed cwds, test fixtures); gluing those with '\' produces mixed paths that is_dir() and string comparisons then miss. A path with any '/' in it is treated as slash-shaped; otherwise the platform separator rules. |
display(): string | |
icon(): string | Suggest a single-character icon for this entry — directory, common file-type extensions, or a generic file glyph. |
formatSize(): string | Format $size as a short SI-style string ("4.2K", "1.7M"). Bubble Tea's filepicker uses the same compact form. |
FilePicker final class
Directory browser. Lists the entries under $cwd, lets the user navigate with arrow keys, descend into directories with Enter, and pop back up with Backspace. selected() returns the path of the highlighted entry the next time the user presses Enter on a file (or any entry, when $dirAllowed is true).
| Method | Summary |
|---|---|
static new(?string $cwd = null, int $height = 10): self | Construct a fresh instance with default state. |
init(): ?\Closure | Bubble-Tea Init — returns the bootstrap Cmd (cursor blink, first tick, etc.) or null. |
update(Msg $msg): array | |
view(?Theme $theme = null): string | Render the component as a multi-line ANSI string. SF-9: the theme threads through from the FilePicker field — cursor rows ride the theme cursor slot, entry rows the option slot, the error row the error slot; null keeps the legacy hard-coded bytes. |
selected(): ?string | |
withSelected(?string $path): self | Restore the selected path without moving navigation (SF-23). SugarCraft extension — charmbracelet/bubbles' filepicker persists no selection at all, so there is no upstream symbol to mirror; this is the value-half of the save/restore symmetry \SugarCraft\Forms\Field\FilePicker hands to Form::hydrate(). The listing, cursor and cwd stay untouched. |
highlightedEntry(): ?Entry | |
highlightedPath(): ?string | Absolute path of the currently-highlighted entry, or null when the listing is empty. Mirrors charmbracelet/bubbles.HighlightedPath. |
height(): int | Configured viewport height. Mirrors charmbracelet/bubbles.Height(). |
width(): int | Configured viewport width in cells (0 = natural). Mirrors charmbracelet/bubbles.Width(). |
focus(): array | |
blur(): self | Release focus; companion to { focus()}. |
withCwd(string $path): self | |
setCwd(string $path): self | |
refresh(): self | |
withShowHidden(bool $on): self | |
withAllowedExtensions(array $exts): self | Display filter only — hides files whose FINAL extension is not listed; never a sandbox (see the TRUST MODEL block in the class doc: evil.sh.png passes ['png'], directories are exempt, the walk reaches anywhere the process can read). Enforce/contain the selected path in your own code. |
withMaxEntries(int $limit): self | Tune the entry cap of the synchronous walk (sugar-forms-084): at most $limit candidates are kept in scan order per refresh and the rest are counted, not stat-ed, and reported as a trailing "… N more" row. 0 means unbounded — a documented escape hatch for hosts on tame filesystems that want the full listing. Past the cap the extension filter stops applying (it needs a stat); the dot-hidden filter still does. |
withDirAllowed(bool $on): self | |
withFileAllowed(bool $on): self | |
withHeight(int $h): self | |
withWidth(int $cells): self | Cap every rendered row at $cells terminal cells (0 restores the natural width). Long paths are MIDDLE-truncated so the filename tail — the part that identifies the entry — stays visible (sugar-forms-076, the Bubbles recipe). |
withShowIcons(bool $on = true): self | Render a per-entry icon glyph. Off by default. |
withShowSize(bool $on = true): self | Append a right-aligned size column for files. Off by default. |
withDirectoryFirst(bool $first = true): self | Show directories before files. Enabled by default. |
withSortMode(SortMode $mode, bool $reverse = false): self | Choose the secondary sort criterion (directories always group first, regardless). Pass $reverse: true to flip order. Mirrors Bubbles' sort options. |
error(): ?string | Latest filesystem error (e.g. unreadable directory). |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
SortMode enum
Sort criterion for FilePicker::withSortMode(). Directories always group first regardless of mode, matching Bubbles' default behaviour; the mode controls the secondary sort within each group.
Cases: Name · Size · MTime
PHP also provides cases(), from() and tryFrom().
SugarCraft\Forms\Fuzzy
FuzzyMatcher final class
Fuzzy substring matcher using Smith-Waterman-style local alignment scoring.
| Method | Summary |
|---|---|
__construct() | |
score(string $query, string $candidate): int | Score a candidate against a query using Smith-Waterman local alignment. Only considers alignments where the query characters appear in ORDER within the candidate (not necessarily contiguously). |
match(string $query, array $candidates): array | Filter and rank candidates by fuzzy match score against the query. Returns candidates sorted by score descending (best matches first). Only returns candidates with a score > 0. |
SugarCraft\Forms\ItemList
Item interface
One row in an ItemList.
| Method | Summary |
|---|---|
title(): string | |
description(): string | |
filterValue(): string |
ItemList final class
Selectable, scrollable, filterable list of Items.
| Method | Summary |
|---|---|
static new(array $items = [], int $width = 60, int $height = 10): self | |
init(): ?\Closure | Bubble-Tea Init — returns the bootstrap Cmd (cursor blink, first tick, etc.) or null. |
update(Msg $msg): array | |
view(?Theme $theme = null): string | Render the component as a multi-line ANSI string. |
selectedItem(): ?Item | |
visibleItems(): array | |
index(): int | |
focus(): array | |
blur(): self | Release focus; companion to { focus()}. |
withItems(array $items): self | |
setItems(array $items): self | |
withItem(int $index, Item $item): self | Replace a single item in place. Negative indices count from the end (Pythonic). Out-of-range indices are silently ignored, matching upstream charmbracelet/bubbles SetItem. |
setItem(int $index, Item $item): self | |
insertItem(int $index, Item ...$items): self | Insert one or more items at the given position. Negative indices count from the end; an index >= count appends. Cursor / offset are re-clamped against the new length. |
removeItem(int $index): self | Remove the item at the given index. Negative indices count from the end. Out-of-range indices are silently ignored. Cursor stays on the same logical position where possible (clamps when removing the last visible item). |
items(): array | |
cursorUp(int $n = 1): self | Move cursor up $n rows. Mirrors charmbracelet/bubbles.CursorUp. |
cursorDown(int $n = 1): self | Move cursor down $n rows. Mirrors charmbracelet/bubbles.CursorDown. |
goToStart(): self | Jump to row 0. Mirrors charmbracelet/bubbles list GoToStart. |
goToEnd(): self | Jump to last row. Mirrors charmbracelet/bubbles list GoToEnd. |
prevPage(): self | Page back by $height rows. Mirrors charmbracelet/bubbles list PrevPage. |
nextPage(): self | Page forward by $height rows. Mirrors charmbracelet/bubbles list NextPage. |
select(int $index): self | Move the cursor directly to $index (0-based, clamped). Mirrors charmbracelet/bubbles.Select(int). |
resetSelected(): self | Reset the selection to row 0. Mirrors charmbracelet/bubbles list ResetSelected. |
resetFilter(): self | Drop the active filter text and exit filter mode. Mirrors charmbracelet/bubbles ResetFilter. Equivalent to clearFilter(). |
isFiltered(): bool | True when a filter is currently typed. Mirrors charmbracelet/bubbles list IsFiltered. |
filterValue(): string | Currently typed filter text. Mirrors charmbracelet/bubbles list FilterValue. |
settingFilter(): bool | True when the user is actively typing into the filter buffer (vs viewing filtered results). Mirrors charmbracelet/bubbles list SettingFilter. |
setSize(int $width, int $height): self | Resize the viewport. height is a count of ITEMS per page — with showDescription on, a described item paints two lines, so a height-8 list can emit up to 16 lines (the honest line budget is withVisibleLines(), SF-27). Negative dimensions throw; zero means unbounded. |
withVisibleLines(int $lines): self | Opt into a strict LINES budget for the page (SF-27, sugar-forms-031): height counts ITEMS, so with showDescription on a height-8 list paints up to 16 lines. withVisibleLines(8) renders exactly 4 described items (or 8 plain ones) — the number the layout budget actually occupies. 0 (default) keeps the historical item-count windowing byte-for-byte; a budget of 1 pins one item per page whatever it costs. |
renderedLineCount(): int | How many lines view() currently paints for this list — the honest budget figure callers laying out panes need (header, filter row, windowed item lines, status row). |
withTitle(string $t): self | |
withShowDescription(bool $on): self | |
withShowStatusBar(bool $on): self | |
withShowHelp(bool $on): self | Reserved surface (SF-9, M18): the stored flag is never read — no ItemList render path draws a help row. Kept for shape stability; implement-then-keep or remove in 2.0.0 is an owner decision (recorded in the docs-fix 1104 lane report). |
withShowFilter(bool $on): self | |
withInfiniteScrolling(bool $on): self | |
withKeepFilter(bool $on): self | |
withHasMore(bool $on = true): self | Opt into the E736 5.15 load-more trigger: true declares the host has more pages beyond what is loaded. Each navigation that ARRIVES the cursor on the last visible item then yields a LoadMoreMsg through update()'s Cmd slot (see loadMoreEdge()). Default false — every pre-5.15 host behaves byte-identically. |
hasMore(): bool | Whether the host declared more pages beyond the loaded ones. |
withCursorPrefix(string $glyph): self | Glyph rendered before the highlighted (cursor) item. Default '> ' (two cells: arrow + space). The string is taken verbatim — pass the trailing space yourself if you want one. No 2-cell assumption is baked into the layout math (sugar-forms-075): the prefix's cost rides the width clip as a measured cell run, and rows are hit by line only, so a wide or styled prefix shifts what the clip trims, never where a click lands. |
withUnselectedPrefix(string $glyph): self | Glyph rendered before non-cursor items. Default ' ' (two spaces, matching the cursor prefix's width). |
withStatusMessageLifetime(float $seconds): self | Default lifetime (in seconds) of a status message set via newStatusMessage(). Default 1.0s. |
newStatusMessage(string $msg): self | Set a transient status message rendered in the status bar. Expires statusMessageLifetime seconds later (the model expires it on its next view() / status accessor; callers driving via Cmds should pair this with Cmd::tick() for a hard refresh). |
status(): string | Status string rendered in the status bar — composes the cursor position, total count, filter state, and any active transient status message (only while it hasn't expired). |
clearFilter(): self | |
isFiltering(): bool | |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
LoadMoreMsg final class
Delivered to the host when an ItemList cursor ARRIVES on the last visible item while ItemList::hasMore() is true — the list has run out of loaded entries but the host said more pages exist.
StringItem final class
Convenience Item carrying just a single string. Useful when you want to populate an ItemList from a flat list of choices.
| Method | Summary |
|---|---|
__construct(public readonly string $value) | |
title(): string | |
description(): string | |
filterValue(): string |
SugarCraft\Forms\Scrollbar
Scrollbar final class
Standalone vertical (or horizontal) scrollbar widget.
| Method | Summary |
|---|---|
static vertical(): self | Construct a vertical scrollbar with defaults. |
static horizontal(): self | Construct a horizontal scrollbar with defaults. |
withTrackChar(string $char): self | |
withThumbChar(string $char): self | |
withArrows(bool $show): self | |
view(ScrollbarState $state, int $height): string | Render the scrollbar into $height rows. |
ScrollbarState final readonly class
Immutable scrollbar state carrying total content lines, the current vertical offset, and the number of visible lines in the viewport.
| Method | Summary |
|---|---|
__construct(int $total, int $position, int $viewport) | |
static new(int $total = 0, int $position = 0, int $viewport = 0): self | Factory constructor with defaults: total=0, position=0, viewport=0. |
SugarCraft\Forms\Spinner
Spinner final class
Animated spinner. Implements Model so it can be embedded in any SugarCraft app: return its init() Cmd from your model, forward TickMsgs into its update(), and call its view() wherever you want the spinner to appear.
| Method | Summary |
|---|---|
static new(?Style $style = null): self | Construct a fresh instance with default state. |
init(): ?\Closure | Bubble-Tea Init — returns the bootstrap Cmd (cursor blink, first tick, etc.) or null. |
update(Msg $msg): array | |
view(): string | Render the component as a multi-line ANSI string. |
tick(): \Closure | Schedule the next tick. Returned as a Cmd from update() or init(). |
id(): int | Stable per-instance ID — used by TickMsg routing so two spinners on the same loop don't both step on every tick. Mirrors charmbracelet/bubbles.ID(). |
style(): Style | Read-only access to the active Style. Mirrors the charmbracelet/bubbles spinner public Spinner field, which callers inspect to read frame counts, colour, FPS, etc. The same data is reachable via the already-public style property; the method form is provided for parity with the rest of the read-only API surface. |
static frames(?Style $style = null): array | Frames-only accessor for static one-shot render paths (print mode, snapshots) that pick a glyph by index without running the tick loop. |
static intervalMs(?Style $style = null): int | Milliseconds per frame for a style (default dot), companion to frames(). |
frame(): int | Current frame index (0-based, modulo count(style->frames)). |
withStyle(Style $style): self | Swap the spinner style mid-flight. Frame index resets to 0 so the new style starts from its first frame. The next tick adopts the new style's interval automatically. Mirrors the mutable charmbracelet/bubbles spinner Spinner field assignment (rendered immutable here so snapshot- based tests stay deterministic). |
subscriptions(): ?\SugarCraft\Core\Subscriptions |
Style final class
A spinner style: an ordered list of frames and a per-frame interval.
| Method | Summary |
|---|---|
__construct(public readonly array $frames, public readonly float $fps = 10.0) | |
static line(): self | |
static dot(): self | |
static miniDot(): self | |
static points(): self | |
static pulse(): self | |
static globe(): self | |
static meter(): self | |
static jump(): self | Bouncing dot: ⢄ ⢂ ⢁ ⡁ ⡈ ⡐ ⡠ — used by charmbracelet/bubbles Jump. |
static moon(): self | Moon-phase rotation: 🌑 🌒 🌓 🌔 🌕 🌖 🌗 🌘 — charmbracelet/bubbles Moon. |
static monkey(): self | Walking monkey: 🙈 🙉 🙊 — charmbracelet/bubbles Monkey. |
static hamburger(): self | Sliding hamburger bars: ☱ ☲ ☴ ☲ — charmbracelet/bubbles Hamburger. |
static ellipsis(): self | Animated dots: , ., .., ... — charmbracelet/bubbles Ellipsis. |
static catalog(): array | Returns a list of all available spinner style names. |
interval(): float |
TickMsg final class
Animation tick for a specific spinner instance, identified by $id. Each Spinner ignores ticks for other ids so multiple spinners can share an event loop without cross-talk.
| Method | Summary |
|---|---|
__construct(public readonly int $id) |
SugarCraft\Forms\TextArea
TextArea final class
Multi-line text input. Holds a list of lines and a (row, col) cursor. Enter splits the current line; Backspace at the start of a line merges with the previous one. All edits are multibyte-safe (mb_substr / mb_strlen), so wide characters (日本) navigate as single graphemes.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
static new(): self | Construct a fresh instance with default state. |
init(): ?\Closure | Bubble-Tea Init — returns the bootstrap Cmd (cursor blink, first tick, etc.) or null. |
update(Msg $msg): array | |
withVimMode(bool $enabled = true): self | Enable or disable vim keybindings mode. Mirrors \SugarCraft\Forms\TextInput\TextInput::withVimMode(): arming starts in normal mode, and the widget's own navigation primitives (j/k rows, w/b, 0/$, i/a/A/I, x, Escape, visual selection via v) come from the shared VimKeyHandler rather than a per-widget binding table. |
vimMode(bool $enabled = true): self | Short-form alias for withVimMode() (TextInput's twin alias). |
view(): string | Render the component as a multi-line ANSI string. |
focus(): array | |
blur(): self | Release focus; companion to { focus()}. Resets the vim mode to normal (TextInput's twin). |
setValue(string $v): self | |
value(): string | |
reset(): self | |
withPlaceholder(string $p): self | |
withCharLimit(int $n): self | |
withWidth(int $w): self | |
withHeight(int $h): self | |
withMaxWidth(int $w): self | |
withMaxHeight(int $h): self | |
withDynamic(bool $on = true): self | Toggle dynamic-height mode. When on, view() renders only as many rows as the content has, capped at $maxHeight (0 means uncapped). When off (default), $height is the fixed row count and short content gets padded with end-of-buffer glyphs. |
dynamic(bool $on = true): self | Short alias for withDynamic(). |
withEditorExtension(string $ext): self | Filename suffix used when Ctrl+O opens the buffer in the user's external $EDITOR. Pass with the leading dot ('.md') or without ('md'); both are accepted. Empty string skips the suffix entirely. Mirrors the editor-example pattern in charmbracelet/bubbles textarea. |
editorExtension(string $ext): self | Short alias for withEditorExtension(). |
effectiveHeight(): int | Number of rows view() will render given the current mode. In static mode (dynamic=false) returns $height; in dynamic mode returns min(maxHeight ?: ∞, max(1, line count)) — at least one row, at most maxHeight if set, otherwise content count. |
withShowLineNumbers(bool $on = true): self | Show 1-based line numbers in a left gutter. Default off. |
showLineNumbers(bool $on = true): self | |
withEndOfBufferCharacter(string $c): self | Character drawn for empty rows beyond the last line of content (the "end of buffer" filler vim shows). Defaults to ~. |
withPrompt(string $p): self | Static prefix prepended to every line. Mirrors charmbracelet/bubbles.Prompt. |
setPromptFunc(?\Closure $fn): self | Dynamic prompt: closure fn(int $rowIndex, string $line): string. Called once per visible row to compute the line prefix. When set, wins over the static withPrompt() prefix. Pass null to clear and revert to the static prompt. Mirrors charmbracelet/bubbles. SetPromptFunc (with the row-index argument also exposed so callers can render > on the active row, elsewhere). |
withValidator(?\Closure $fn): self | Set a validator. Receives the joined value, returns an error message or null. Re-runs after every edit; result is exposed via err(). |
placeholder(string $p): self | |
charLimit(int $n): self | |
width(int $w): self | |
height(int $h): self | |
maxWidth(int $w): self | |
maxHeight(int $h): self | |
prompt(string $p): self | |
validator(?\Closure $fn): self | |
error(): ?string | Latest validator error, or null when the buffer passes. |
err(): ?string | |
setCursor(int $row, int $col): self | Move the cursor to ($row, $col); both clamp to range. |
setCursorColumn(int $col): self | Clamp the cursor's column on the current row. |
withSelect(int $row, int $col): self | Anchor a selection at ($row, $col); both clamp into the live buffer. The ACTIVE end follows the caret from now on, so a caller implementing shift-selection calls this on press, then lets arrows move the caret. Re-anchoring at the caret position clears the selection (empty span). |
clearSelection(): self | Drop the selection anchor; the caret itself is untouched. Idempotent. |
hasSelection(): bool | True when anchor and caret delimit a non-empty span. |
selectedText(): string | The selected text, lines joined with "\n"; '' when there is no selection. Anchor/caret order is normalised — a backwards drag (anchor below the caret) selects the same span as a forwards one. |
cursorUp(): self | Move cursor up one row, preserving column where possible. Mirrors charmbracelet/bubbles.CursorUp. Clamps at the first row. |
cursorDown(): self | Move cursor down one row, preserving column where possible. Mirrors charmbracelet/bubbles.CursorDown. Clamps at the last row. |
moveToBegin(): self | Jump to (0, 0). Mirrors charmbracelet/bubbles.MoveToBegin. |
moveToEnd(): self | Jump to the last row, end of last line. Mirrors charmbracelet/bubbles.MoveToEnd. |
pageUp(): self | Move cursor up by the configured display height (one viewport). Mirrors charmbracelet/bubbles.PageUp. Falls back to a single row when height is unset (height = 0). |
pageDown(): self | Move cursor down by the configured display height. Mirrors charmbracelet/bubbles PageDown. |
insertRune(string $rune): self | Insert a single rune (one or more bytes — multibyte safe) at the cursor. Mirrors charmbracelet/bubbles.InsertRune. |
word(): string | Return the word containing the cursor — a maximal run of non-whitespace characters that the cursor sits in or adjacent to. Mirrors charmbracelet/bubbles.Word. Returns the empty string when the cursor is on whitespace. |
insertString(string $text): self | Insert a string at the cursor; embedded newlines split lines. Mirrors charmbracelet/bubbles.InsertString / InsertRune. |
lineInfo(): array | Pixel/cell width of the current line up to the cursor. |
lineCount(): int | |
focused(): bool | Mirrors charmbracelet/bubbles.Focused() — true when the area accepts input. |
cursor(): Cursor | Read-only access to the embedded Cursor. |
line(): int | Currently-active line (0-based). Mirrors charmbracelet/bubbles.Line(). |
column(): int | Cursor column on line() (0-based, codepoint count). Mirrors charmbracelet/bubbles.Column(). |
visualColumn(): int | Cursor column measured in DISPLAY CELLS rather than codepoints — the x-offset the caret paints at once wide characters (CJK, emoji) and zero-width marks are accounted for. column() stays the codepoint offset the flat draft-index math (and candy-code's seekInput) relies on; this is the presentation-side companion, wrapping aside (each visual row restarts at 0 — add wrapSegments() offsets to locate the caret inside a soft-wrapped line). |
getWidth(): int | NOTE (accessor era, 2026-10-24): this getWidth() read cannot lose its get* prefix — the bare width() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. — Configured visible width in cells (0 = unbounded). |
getHeight(): int | NOTE (accessor era, 2026-10-24): this getHeight() read cannot lose its get* prefix — the bare height() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. — Configured visible height in rows (0 = unbounded). |
getRowOffset(): int | Vertical scroll offset (0-based row index of the topmost visible line). Follows the caret automatically: every edit/navigation snapshot pans it so the cursor row stays inside the effectiveHeight() window. |
rowOffset(): int | Bare scroll-offset accessor (E736 F4). The get-form on the property violated the house no-get rule; width/height have no twin here because those bare names are already the setters (E736 1.x aliases) — read them off the public readonly properties instead. |
setWidth(int $w): self | |
setHeight(int $h): self | |
subscriptions(): ?\SugarCraft\Core\Subscriptions | |
withKeyOverrides(array $map): static | Replace the binding map (canonical spellings documented on parseKeyOverrides()). The widget's stored keyOverrides stays the parsed canonical form; consult it with keyOverrides(). |
keyOverrides(): array | The parsed canonical map: ['ctrl+u' => 'move_end', ...]. Empty (default) means every key falls through to the widget's built-in handling. |
TextAreaEditedMsg final class
Dispatched after the external editor opened via Ctrl+O exits with status 0. Carries the file's final contents; TextArea::update() replaces its current value with $value on receipt.
| Method | Summary |
|---|---|
__construct(public readonly string $value) |
SugarCraft\Forms\TextInput
EchoMode enum
How a TextInput renders its value.
Cases: Normal · Password · Mask · None
PHP also provides cases(), from() and tryFrom().
Styles final class
Styles for TextInput: one slot per visible element. All default to a no-op Style so callers / snapshots that never touch styling stay byte-for-byte unchanged. Pass non-default styles to TextInput::withStyles() to customise.
| Method | Summary |
|---|---|
__construct(?Style $prompt = null, ?Style $placeholder = null, ?Style $text = null, ?Style $cursor = null) |
TextInput final class
Single-line text input.
| Method | Summary |
|---|---|
static new(): self | Construct a fresh instance with default state. |
init(): ?\Closure | Bubble-Tea Init — returns the bootstrap Cmd (cursor blink, first tick, etc.) or null. |
update(Msg $msg): array | |
view(): string | Render the component as a multi-line ANSI string. |
focus(): array | |
blur(): self | Release focus; companion to { focus()}. |
setValue(string $v): self | |
reset(): self | |
withPlaceholder(string $p): self | |
withPrompt(string $p): self | |
getWidth(): int | NOTE (accessor era, 2026-10-24): this getWidth() read cannot lose its get* prefix — the bare width() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. — Configured display width. 0 = no cap. Mirrors charmbracelet/bubbles.Width(). |
position(): int | Cursor position (0-based char index). Mirrors charmbracelet/bubbles.Position(). |
isFocused(): bool | Mirror of $focused. Mirrors charmbracelet/bubbles.Focused(). |
cursor(): Cursor | Read-only accessor for the underlying Cursor. |
availableSuggestions(): array | Full configured suggestion list. Mirrors charmbracelet/bubbles. AvailableSuggestions(). |
currentSuggestionIndex(): int | Index of the currently-highlighted suggestion. |
withStyles(?Styles $styles): self | Apply per-element styling. Mirrors charmbracelet/bubbles.Styles struct + SetStyles. Pass null to clear. |
getStyles(): ?Styles | NOTE (accessor era, 2026-10-24): this getStyles() read cannot lose its get* prefix — the bare styles() slot is a live fluent setter defined above, and PHP admits one method per name. Treated as the documented legal exception (sugar-style precedent); owner-pending and rostered in tests/AccessorDeprecationTest.php until a vocabulary ruling lands. |
withPlaceholderStyle(Style $style): self | Set the style used to render placeholder text when the input is empty. Defaults to a faint (dim) style. |
withPrefix(string $prefix): self | Set a fixed prefix string rendered before the input text. The prefix is not editable and is not part of the value. |
withSuffix(string $suffix): self | Set a fixed suffix string rendered after the input text. The suffix is not editable and is not part of the value. |
withHistory(array $history): self | Set the input history for up/down arrow navigation. When history is set, pressing Up/Down arrows will cycle through previous entries. The most recent entry (last in array) is shown first when pressing Up. |
withHistoryLimit(int $limit): self | Set the maximum number of history entries to retain. When the limit is reached, oldest entries are discarded. A limit of 0 means unlimited (default). |
addToHistory(string $entry): self | Add an entry to the history. NOT wired into Enter automatically — handleEnter only submits; the host app owns which submissions are worth remembering and calls this on its own submit path (round-90 audit truth-flip: the old "called automatically when the user presses Enter" claim described no existing code path). You can also call it manually to pre-populate history. |
withCharLimit(int $n): self | |
withWidth(int $w): self | |
withEchoMode(EchoMode $m): self | |
withEchoChar(string $c): self | |
withVimMode(bool $enabled = true): self | Enable or disable vim keybindings mode. |
vimMode(bool $enabled = true): self | Short-form alias for withVimMode. |
withSuggestions(array $candidates): self | Replace the suggestion pool. Call withShowSuggestions() to enable rendering of the matching subset. |
setSuggestions(array $candidates): self | |
withShowSuggestions(bool $on = true): self | Toggle whether suggestions render below the input. Default off. |
showSuggestions(bool $on = true): self | |
matchedSuggestions(): array | Filter the suggestion pool by current prefix, case-insensitively. |
currentSuggestion(): ?string | Currently-highlighted suggestion (or null when none match). |
withValidator(?\Closure $fn): self | Set a validator. Receives the current value, returns an error message (string) for invalid input or null for valid. The latest message is exposed via err() after every edit. |
withValidateOn(ValidateOn $timing): self | Set when validation fires. |
withRestrict(string $pattern): self | Set a regex pattern that filters which keystrokes are accepted. Only characters matching the pattern enter the buffer. An empty string (default) accepts all characters. |
withMask(string $pattern, string $echoChar = '*'): self | E736 5.5 — pattern-based masking (upstream charmbracelet/huh has only the all-or-nothing Password mode; this is the SugarCraft partial-mask extension behind EchoMode::Mask). Characters matched by the pattern render as $echoChar; everything else stays visible, so a card field can echo 4111 **** **** 1111. |
clearMask(): self | Leave Mask mode: back to Normal rendering with the pattern forgotten. A no-op on unmasked widgets keeps withers composable. |
placeholder(string $p): self | |
prompt(string $p): self | |
charLimit(int $n): self | |
width(int $w): self | |
echoMode(EchoMode $m): self | |
echoChar(string $c): self | |
suggest(array $candidates): self | |
validator(?\Closure $fn): self | |
styles(?Styles $styles): self | |
prefix(string $p): self | |
suffix(string $s): self | |
placeholderStyle(Style $s): self | |
error(): ?string | Latest validator error or null. |
err(): ?string | |
setCursor(int $pos): self | Manually move the cursor (clamped to [0, length()] and snapped down to the start of the cluster at the target). |
cursorStart(): self | |
cursorEnd(): self | |
paste(string $text): self | Insert $text at the cursor position. Newlines are stripped (a single-line input can't represent them). Honors charLimit and — rune by rune, exactly like typing — restrict (E736 F2). |
nextSuggestion(): self | Cycle to the next matching suggestion. No-op when none match. |
prevSuggestion(): self | |
acceptSuggestion(): self | Replace the current value with the highlighted suggestion. |
length(): int | Buffer length in codepoints — O(1) via the constructor-derived cache; the public contract is unchanged from the old live mb_strlen($this->value) (E736 plan 8.5). |
displayedValue(): string | Echo-safe projection of the buffer for every display surface: Normal passes through, Password renders echoChar × length, Mask renders the masked runs, None renders empty. The raw secret never leaves through a display path — consumers that need the real value read value(). |
subscriptions(): ?\SugarCraft\Core\Subscriptions | |
withKeyOverrides(array $map): static | Replace the binding map (canonical spellings documented on parseKeyOverrides()). The widget's stored keyOverrides stays the parsed canonical form; consult it with keyOverrides(). |
keyOverrides(): array | The parsed canonical map: ['ctrl+u' => 'move_end', ...]. Empty (default) means every key falls through to the widget's built-in handling. |
ValidateOn enum
When validation fires on a TextInput.
Cases: None · Blur · Change · Submit
PHP also provides cases(), from() and tryFrom().
SugarCraft\Forms\Util
RenderSafe final class
Strips C0 control bytes and every ESC-introduced sequence *except* true SGR from untrusted display strings.
| Method | Summary |
|---|---|
static clean(string $s): string | Strip dangerous control bytes from an untrusted string. |
ViewportPan final class
Shared window-pan math for cursor/offset pairs (E736 plan 3.7).
| Method | Summary |
|---|---|
static offsetFor(int $cursor, int $offset, int $height): int | Offset of the first visible row after cursor must be on screen. |
SugarCraft\Forms\Validator
Email final class
Validates that input is a valid email address.
| Method | Summary |
|---|---|
validate(string $input): true|string |
MaxLength final class
Validates that input does not exceed a maximum length.
| Method | Summary |
|---|---|
__construct(public readonly int $max) | |
validate(string $input): true|string |
MinLength final class
Validates that input meets a minimum length.
| Method | Summary |
|---|---|
__construct(public readonly int $min) | |
validate(string $input): true|string |
Pattern final class
Validates that input matches a given regex pattern.
| Method | Summary |
|---|---|
__construct(public readonly string $pattern, public readonly ?string $message = null, ?int $backtrackLimit = null, ?int $recursionLimit = null) | |
validate(string $input): true|string |
Required final class
Validates that input is not empty.
| Method | Summary |
|---|---|
validate(string $input): true|string |
Validator interface
Input validator for Field\Input.
| Method | Summary |
|---|---|
validate(string $input): true|string |
SugarCraft\Forms\Viewport
Viewport final class
Scrollable text area. Holds a fixed-size window over arbitrarily long content; navigation methods (lineUp/lineDown/pageUp/…) advance the window, clamped so the viewport never goes past the start or end.
Not listed: the methods of SugarCraft\Core\SubscriptionCapable, a trait declared outside src/.
| Method | Summary |
|---|---|
static new(int $width = 80, int $height = 24): self | Construct a fresh instance with default state. |
init(): ?\Closure | Bubble-Tea Init — returns the bootstrap Cmd (cursor blink, first tick, etc.) or null. |
update(Msg $msg): array | |
view(): string | Render the component as a multi-line ANSI string. |
setContent(string $content): self | |
withContent(string|array $content): self | Immutable content replacement. Mirrors charmbracelet/bubbles viewport.Model.SetContent, spelled as a with*() setter so a caller can chain Viewport::new()->withContent($lines)->scrollBy($n) without reaching for the set* family. |
scrollBy(int $n): self | Immutable relative vertical scroll: a positive $n moves the window down, a negative one moves it up, and the result is clamped to [0, maxOffset]. Mirrors charmbracelet/bubbles viewport.Model.ScrollDown / ScrollUp folded into one signed step. |
withSize(int $width, int $height): self | |
setWidth(int $width): self | Resize only the visible width. Mirrors charmbracelet/bubbles. Viewport.SetWidth(int) — separate from SetHeight so callers can resize one axis at a time without rebuilding the whole geometry. Negative values throw. |
setHeight(int $height): self | Resize only the visible height. Mirrors charmbracelet/bubbles. Viewport.SetHeight(int). Negative values throw. |
width(): int | Read-only accessor for the configured visible width (cells). |
height(): int | Read-only accessor for the configured visible height (rows). |
getWidth(): int | |
getHeight(): int | |
setYOffset(int $offset): self | Direct seek to $offset. Clamped to [0, maxOffset]. |
yOffset(): int | |
setXOffset(int $offset): self | Direct seek of the horizontal offset, clamped to [0, maxXOffset]. |
xOffset(): int | |
withHorizontalStep(int $step): self | Cells advanced per scrollLeft() / scrollRight(). Default 6. |
withMouseWheelEnabled(bool $on): self | |
withMouseWheelDelta(int $delta): self | Lines moved per wheel notch. Default 3. |
withScrollbar(bool $on = true): self | Render a vertical scrollbar in the rightmost column. Default off. |
withScrollbarRunes(string $thumb, string $track): self | |
withVerticalScrollbar(Scrollbar $scrollbar): self | Inject a Scrollbar component to render the vertical scrollbar. |
withSmoothScroll(bool $enable = true): self | Enable smooth scrolling for programmatic position changes. Default off. |
lineUp(int $n = 1): self | |
lineDown(int $n = 1): self | |
halfPageUp(): self | |
halfPageDown(): self | |
pageUp(): self | |
pageDown(): self | |
scrollLeft(int $n = 0): self | |
scrollRight(int $n = 0): self | |
gotoTop(): self | |
gotoBottom(): self | |
totalLineCount(): int | |
visibleLineCount(): int | |
atTop(): bool | |
atBottom(): bool | |
atLeftmost(): bool | True when the horizontal offset is at the leftmost column (0). |
atRightmost(): bool | True when the horizontal offset is at the maximum needed for any line. |
scrollPercent(): float | Scroll position 0.0 (top) → 1.0 (bottom). 1.0 when content fits. |
horizontalScrollPercent(): float | Horizontal scroll position 0.0 (leftmost) → 1.0 (rightmost). |
ViewportTickMsg final class
Animation tick for the Viewport's smooth scroll feature. Used to advance the lerp animation on each frame.
SugarCraft\Forms\Vim
TextObject final class
A resolved vim text object: a character range over a single-line buffer.
| Method | Summary |
|---|---|
static isTarget(string $key): bool | Whether the key names a supported text-object target (delimiter or w). |
static resolve(string $buffer, int $cursor, TextObjectScope $scope, string $target): ?self | Resolve a text object at the cursor into a character range, or null when no object exists there (unmatched delimiter, cursor outside every pair, empty buffer). |
TextObjectScope enum
Scope selector for vim text objects: i (inner) vs a (around).
Cases: Inner · Around
PHP also provides cases(), from() and tryFrom().
| Method | Summary |
|---|---|
static fromKey(string $key): ?self | Map a scope key (i / a) to its scope, or null when the key is not a text-object scope selector. |
VimAction enum
Actions returned by VimKeyHandler after processing a key in a given VimState.
Cases: CursorLeft · CursorRight · CursorUp · CursorDown · CursorWordForward · CursorWordBackward · CursorLineStart · CursorLineEnd · DeleteChar · DeleteToStart · DeleteToEnd · DeleteLine · YankLine · ChangeLine · DeleteTextObject · ChangeTextObject · YankTextObject · DeleteSelection · YankSelection · Paste · EnterInsertMode · EnterNormalMode · EnterVisualMode · EnterVisualLineMode · HistoryUp · HistoryDown · Undo · Redo · NoOp
PHP also provides cases(), from() and tryFrom().
VimKeyHandler final class
Unified vim keybinding handler.
| Method | Summary |
|---|---|
static handle(string $key, VimState $state, int $features = self::FEAT_ALL, bool $ctrl = false): ?VimAction | |
static handleTextObject(VimOperator $operator, TextObjectScope $scope, string $targetKey, string $buffer, int $cursor): array | Resolve a completed operator + scope + target text-object sequence (e.g. c + i + " for ci") against the buffer. |
static normalizeKeyMsg(KeyMsg $msg): array | Convert a KeyMsg to a normalized key string for VimKeyHandler. |
VimOperator enum
Vim pending operators that combine with a motion or text object.
Cases: Change · Delete · Yank
PHP also provides cases(), from() and tryFrom().
| Method | Summary |
|---|---|
static fromKey(string $key): ?self | Map an operator key to its VimOperator, or null when the key is not an operator. |
VimState enum
Vim editing states.
Cases: Insert · Normal · Visual · VisualLine
PHP also provides cases(), from() and tryFrom().
Troubleshooting
values() has no entry for a field
A field is left out of values() when it, or the group it sits in, is hidden through withHideFunc(), and when it is a plain Note, which never contributes a value. A Note built with withNext(true) adds a null entry instead. get() returns its fallback for an absent key, so a default there can hide the omission. Check the field's visibility before reading the key.
A boolean predicate goes to withValidator()
withValidator() takes a closure that returns null to pass or an error string to block. A closure that returns true or false is not read as a predicate: its return value goes into the field's error slot, which holds only a string or null, so the validation pass that runs it throws a TypeError. For a true/false predicate use withValidation() on Input or Text, which passes on true.
Pasted text is cut short, or newlines disappear
TextInput clips a paste or insert to the remaining charLimit budget, which defaults to 4096 characters. It also strips CR and LF at insert, because a single-line field cannot hold them. Raise the limit with charLimit(), or pass 0 to turn the bound off. For multi-line input use Text, which wraps a TextArea and counts newlines against its own budget. That budget defaults to 65536 characters, not 4096. charLimit() on Text changes it, and passing 0 turns it off.
Suggestions never arrive, or a fetch fails after a timeout
A fetch that breaches $fetchTimeoutSeconds surfaces as the fetcher failing. Results that arrive after a newer keystroke or after the field loses focus are discarded by design (the generation check from SF-52), so a slow fetch can look like no fetch at all. A zero, negative or non-finite timeout throws \InvalidArgumentException when the field is built, and so does a negative debounce. Leave $workerPool null: it is stored but never consulted.
NO_COLOR or TERM=dumb still gets colored output
The form does not read the environment itself. Turn accessible mode on from your own check, for example withAccessible(getenv('NO_COLOR') !== false || getenv('TERM') === 'dumb'). Accessible mode is a single-line plain-text view of the focused field, so the group titles and error summary disappear with the colors.
Values read as empty after the program ends
Form is immutable, and the run() method of sugar-core's Program drives a copy and returns the final model. The $form you built before the run never holds the submitted values. Capture the return value and read it, and check isSubmitted() first, because an aborted form returns too.
Upstream mapping
The engine ports charmbracelet/huh, and the primitives port charmbracelet/bubbles. Most class docblocks cite the upstream method they mirror, written as Mirrors charmbracelet/....
Form(withwithTheme,withAccessible,withErrorSummary):huh.FormwithWithTheme,WithAccessible,WithErrorSummaryGroup:huh.GroupTheme:huh.ThemeField\Note:huh.NoteSpinner\SpinnerandSpinner\TickMsg:bubblesspinnerTextArea\TextArea:bubblestextareaViewport\Viewport:bubblesviewportCursor\Cursor:bubblescursor
Changelog and versioning
The package has no separate changelog file and no release tag yet, so it publishes only dev-master. Its history is the commit log of sugar-forms/ in the monorepo, which the split mirror on GitHub records. The API table above marks the deprecated accessors on Form and the Fuzzy\FuzzyMatcher shim. Every deprecation whose docblock reads REMOVED-IN: 2.0.0 retires in 2.0.0. That covers the getString(), getInt(), getBool(), getArray() and getFocusedField() accessors on Form, the getDescription() and getError() accessors on Field and its subclasses, the getWidth() and getHeight() accessors on Viewport, and the legacy setters and accessors on TextArea, TextInput, ItemList and FilePicker. The Fuzzy\FuzzyMatcher shim, which delegates to sugar-fuzzy, has no removal version yet, so do not plan its removal for 2.0.0.
Demos.
VHS-recorded GIFs — eight tapes covering the library's examples; the burger, hide and spinner demos ship without a recording. Regenerated automatically on every push that touches the source.
Form
Static frame of a full form — Input, Select and Confirm.
Input
Single-line text with validation.
Confirm
Y/N boolean.
Select
Single-choice list.
MultiSelect
Toggle multiple options.
Text
Multi-line text input.
Themes
Five of the seven themes side-by-side — base, charm, dracula, base16 and catppuccin; ansi and plain are omitted from the recording.