sugarcraft / candy-forms
Canonical form engine (port of charmbracelet/huh) and foundation lib for form primitives (TextInput, TextArea, ItemList, Viewport, FilePicker, Field interface, Confirm, Form); sugar-widgets re-exports it via 22 class_alias shims.
Requires
- php: ^8.3
- sugarcraft/sugar-async: dev-master
- sugarcraft/sugar-cellbuffer: dev-master
- sugarcraft/sugar-colorprofile: dev-master
- sugarcraft/sugar-constraints: dev-master
- sugarcraft/sugar-core: dev-master
- sugarcraft/sugar-fuzzy: dev-master
- sugarcraft/sugar-style: dev-master
Requires (Dev)
- phpunit/phpunit: ^10.5
- sugarcraft/sugar-testing: dev-master
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-20 19:10:57 UTC
README
Formerly published as
sugarcraft/candy-forms(renamed 2026-10).
Form library (port of charmbracelet/huh)
and foundation lib for form and input primitives; the raw component
implementations are what sugar-widgets re-exports. The former standalone
prompt façade has been folded in here, so the full interactive form engine
and its primitives ship as 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); see Versioning below.
Role
SugarForms owns the full primitive + form surface:
- Input primitives —
TextInput,TextArea,ItemList,Viewport,FilePicker,Cursor,Scrollbar,Spinner. - Form engine —
Fieldinterface +Field\{Input,Text,Confirm,Select, MultiSelect,Note,FilePicker,Date,Slider,Color,NumberField,RadioPills},Form,Group,KeyMap,Theme,Fuzzy\FuzzyMatcher, andValidator\{Required,Email,MinLength,MaxLength,Pattern}.
sugar-widgets (SugarCraft\Widgets\*) exposes these classes as thin
class_alias shims pointing back here, so existing imports keep working
while the canonical implementation lives in SugarCraft\Forms\*.
Quickstart
A single-field form:
<?php use SugarCraft\Core\Program; use SugarCraft\Forms\Field\Input; use SugarCraft\Forms\Form; use SugarCraft\Forms\Validator\Required; $form = Form::new( Input::new('name') ->withTitle('What is your name?') ->withValidator(new Required()) ); $form = (new Program($form))->run(); // Program drives a COPY; run() returns the final model /** @var Form $form */ if ($form->isSubmitted()) { echo $form->values()['name'], "\n"; }
echo $form->view() on its own renders one static frame; the form is a
SugarCraft Model, so Program::run() is what drives it interactively. The
Model is immutable, so Program rebinds its own copy on every update — the
$form you pass in never observes the typing, validation, or submission that
happened during the run. Capture run()'s return value and use that as the
final model. For a complete reference — multi-group paging and conditional
visibility — see examples/multi-page-form.php (php examples/multi-page-form.php); the examples/ directory holds twelve
runnable demos — including no-color.php, which shows the NO_COLOR /
CLICOLOR capability negotiation a host program is expected to run before
styling anything.
Pre-filling fields
Show a form's current values before the user touches anything — handy for
"edit settings" screens. Input::withValue() seeds the editable text (it is
the submitted value until edited; pass '' to clear). Select pre-selects
by value with withSelected() (no-op when the value isn't an option) or by
0-based index with withSelectedIndex() (negatives clamp to the first option).
use SugarCraft\Forms\Field\Input; use SugarCraft\Forms\Field\Select; Input::new('name')->withValue('Ada'); // edit box starts as "Ada" Select::new('theme')->withOptions('Nocturne', 'Daylight', 'Midnight') ->withSelected('Midnight'); // or ->withSelectedIndex(2)
Standalone spinner (moved here from sugar-widgets):
<?php use SugarCraft\Forms\Spinner\Spinner; use SugarCraft\Forms\Spinner\Style; $spinner = Spinner::new(Style::dot()); // in your model's init(): return $spinner->init(); // in your model's update(): [$spinner, $cmd] = $spinner->update($msg); // in your model's view(): "loading {$spinner->view()}"
Forms (huh-style)
Multi-page Group wizards, seven themes, per-field validators, conditional skip predicates. The form is itself a SugarCraft Model — drop it into a Program.
use SugarCraft\Forms\Form; use SugarCraft\Forms\Field\{Input, Confirm, Select, Note}; $form = Form::new( Note::new('welcome')->title('Onboarding')->desc('A few quick questions.'), Input::new('name')->title('Your name?')->placeholder('Ada Lovelace'), Confirm::new('newsletter')->title('Subscribe to the newsletter?'), Select::new('lang')->title('Favorite language?')->options('PHP', 'Go', 'Rust', 'Python'), );
Where a field supports a knob, it also exposes a short-form alias for it (
title,desc,placeholder,width,height,validator,options,min,max, …): the short form delegates to the longwith*name (withTitle,withDescription, …). Pick whichever reads better at the call site. The grid is enforced bytests/ShortAliasMatrixTest.php: every publicwith*knob has its short form or a dated exemption (a name squatted by the field'svalue()read, or an@internalwiring channel). The three picker fields construct identically:Select::new($key, 'a', 'b'),MultiSelect::new($key, ['a', 'b']),RadioPills::new($key, 'a', 'b').
Field types
| Field | Description | Notable knobs | Keys consumed |
|---|---|---|---|
Input |
Single-line text (wraps SugarCraft\Forms\TextInput\TextInput) |
withPlaceholder, withCharLimit, withWidth, withPrompt, withValidator(Validator|\Closure) (chains; first error wins), withTitleFunc / withDescriptionFunc, withPassword(bool $on = true, string $echoChar = '*'), withPasswordMask(?string $pattern, string $echoChar = '*'), withSuggestions(list<string>), withSuggestionsFunc(\Closure(string):list<string>), withFuzzySuggestions(list<string>), withAsyncSuggestions(callable $fetcher, int $debounceMs = 150, …), withHistory(list<string>) / addToHistory(string) (recall past the newest entry restores the in-progress draft) |
typing, Home/End, Left/Right, Backspace/Delete, ctrl+a / ctrl+e / ctrl+u / ctrl+k; Up/Down history recall and the Enter submit-validator run only when a custom key map frees those keys (by default they drive field navigation); a host PasteMsg is consumed as typed text (CR/LF stripped) |
Text |
Multi-line text editor | withCharLimit, withHeight, withWidth, withValidator(closure only; replaces) |
full buffer editing; Enter newline and Up/Down caret rows are claimed (they arrive despite nav); ctrl+a/e/u/k + ctrl+c/x/o chords (under the default map Ctrl+C is abort — the copy/cut chords need a custom map that frees Ctrl+C); a host PasteMsg replaces the selection; Tab indents only when a custom map frees it (default: Tab navigates) |
Confirm |
Yes/no boolean | withLabels(affirmative, negative), withDefault(bool), withValidator(Validator|\Closure(bool):?string|null) (replaces; null clears), withTitleFunc, withDescriptionFunc |
Left/Right or h/l answer, y / n answer; Tab toggles only when a custom map frees it (default: Tab navigates) |
Select |
Single-choice list (wraps SugarCraft\Forms\ItemList\ItemList) |
withOptions(...), withWidth(int), withVisibleLines(int) (page by LINES, not items — withHeight counts items, so described entries can double the painted rows), withTitleFunc, withDescriptionFunc, withFuzzySuggestions(list<string>), withAsyncSuggestions(callable $fetcher, int $debounceMs = 150, …), withEnum(\BackedEnum::class), withValidator(Validator|\Closure|null) (replaces; null clears) |
list keys Up/Down or k/j, PageUp/PageDown, Home/g, End/G; the / key opens the filter (typing + Backspace narrow, Enter/Escape end it — claimed); click to position when focused |
MultiSelect |
Multi-choice list (k/j vim keys + space to toggle) | withOptions(...), withWidth(int), withLimit(int), withValidator(\Closure|null) (custom slot; closure-only, see matrix) |
Up/Down or k/j, Home/g, End/G, Space toggles the cursor, digits 1-9 toggle the option in that slot (first option = 1; a digit past the list end is inert, modified digits stay free) |
Note |
Read-only paragraph; skipped by tab navigation | withTitle, withDescription, withHeight(int), withNext(bool), withNextLabel(string) (turns it into an interactive button page) |
none (inert) |
FilePicker |
Filesystem picker (wraps SugarCraft\Forms\FilePicker\FilePicker) |
withDirAllowed, withFileAllowed, withAllowedExtensions (a display filter only — see FilePicker trust model below, never a sandbox), withShowHidden (starting directory via FilePicker::new($key, $cwd)), withValidator(Validator|\Closure|null) (replaces; null clears) |
Up/Down or k/j, Home/End, Enter selects or enters a directory, Backspace/Left ascend, Right enters; no filter typing, no mouse |
Date |
Calendar-grid date picker (YYYY-MM-DD value, arrow-walked grid) |
withValue(?string), withValidator(Validator|\Closure|null) (replaces; null clears) |
Left/Right or h/l day, Up/Down or k/j week (claimed arrows); Shift+Left/Right and PageUp/PageDown month, Home/End month edges, Space commits; movement auto-commits |
Slider |
Numeric range slider (keyboard drag, snapping step) | withMin / withMax / withStep, withValue(int|float), withValidator(Validator|\Closure|null) (replaces; null clears) |
Left/Right or h/l step, Home/End clamp; mouse only when the host routes MouseMsg or calls the zone-drag API — the widget never negotiates drag itself |
Color |
Hex color picker with swatch preview | withValue(string $hex), withTruecolor(bool), withValidator(Validator|\Closure|null) (replaces; null clears) |
Left/Right or h/l green, Up/Down or k/j blue (claimed arrows); PageUp/PageDown red, Home/End clamp green |
NumberField |
Bounded numeric input — draft text + committed value aligned to withStep() multiples |
withMin / withMax / withStep, withValue(int|float), withoutValue() (never-set ≠ 0), withPlaceholder, withWidth, withValidator(Validator|\Closure|null) (judges the committed value; null clears) |
Up/Down plus or minus 1 (claimed arrows), PageUp/PageDown by tens, Home/End clamp; typing and editing ride the inner Input; Enter commits only when a custom map frees it (default: Enter submits or advances) |
RadioPills |
Horizontal pill row, single choice by arrows or mouse; windows the roster around the selection when a width is set | withOptions(...), withValue(label), withTitle, withDescription, withTitleFunc / withDescriptionFunc, withWidth, withValidator(Validator|\Closure|null) (replaces; null clears) |
Left/Right or h/l, Home/End; pill-zone clicks when the host routes MouseMsg (press, drag and release equivalent) |
FilePicker trust model
FilePicker is a whole-filesystem browser by design. withAllowedExtensions
(and withShowHidden) are a display filter — not a sandbox: they hide
entries from the list, they never refuse them. A spoof like evil.sh.png
passes a ['png'] allow-list (the filter reads the final extension),
directories are exempt from the extension filter entirely, and the user can
walk anywhere the process can read — descending symlinked directories with
Enter, ascending to the filesystem root with Backspace. Nothing in the
picker confines the chosen path: applications that need a bounded picker
must enforce their own containment on the selected value (realpath,
prefix-check the resolved directory, re-verify the extension with a
trailing-dot-safe matcher) before acting on it.
Synchronous walk and entry cap. The listing is a synchronous scandir()
plus per-entry stats on the live loop: a huge, FUSE, or network-mounted
directory stalls rendering for the duration of the walk (an async,
fetcher-style leg is future work). The blast radius is bounded — the walk
keeps the first maxEntries candidates in scan order and stops stat-ing the
rest, reporting them as a trailing … N more row. Tune with
withMaxEntries(int) (default 512; 0 means unbounded). Past the cap the
extension filter stops applying (it needs a stat), so the marker counts
dot-hidden-filter survivors only; the cursor, window, and selection machinery
never see the truncated remainder.
All fields share a common navigation contract: Tab / ↓ advances,
Shift+Tab / ↑ retreats (Shift+Tab arrives on the wire as CSI Z,
decoded to Tab with shift: true; Alt+Tab remains an accepted
alias), Enter advances focus on non-final fields and submits on the last
interactive field, Esc / Ctrl+C
aborts. Skippable fields (e.g. plain Notes) are passed over silently.
The bindings live in a {@see \SugarCraft\Forms\KeyMap} — pass your own
via Form::withKeyMap() and {@see \SugarCraft\Forms\Form::keyBinds()}
renders the active set, never the defaults. keyBinds() also appends an
advisory enter row spelling out that split role, and every label it
renders is catalogued — host-facing chrome localizes with the active
locale, the keys column stays the physical spelling.
Keyboard & wire shapes
- Form-level chords come from the active KeyMap (defaults: tab,
shift+tab — with alt+tab kept as a legacy alias entry — enter, esc and
ctrl+c;
keyBinds()renders the live set, seeForm::withKeyMap()). - Wire spellings: Shift+Tab arrives on the wire as the two-byte CSI Z
sequence (
\x1b[Z) which the host decoder turns into Tab carrying shift; sugar-forms itself negotiates no kitty keyboard-protocol flags, so whether disambiguated chord forms (CSI 27;5u-style) ever arrive is the host reader's decision. - The eat order: a field that claims a nav-bound key through
consumes()sees it before the form (Text, FilePicker and the focused Select filter claim Enter; Date, Color, MultiSelect, NumberField, Select, Text and FilePicker claim the arrows). A field withconsumes() === false— Input, Confirm, Slider, RadioPills, Note — can never see a default-bound key: tab, enter, esc, ctrl+c and the arrows stop at the form door. Pass a custom map viawithKeyMap()to free a key for the field; the field-types table above marks which arms need that.tests/FormKeyDispatchTest.phpverifies both directions. - Paste: the terminal sends pastes as a PasteMsg and both text surfaces consume it: TextArea replaces the selection (or inserts at the caret), TextInput splices the payload in as typed text — CR/LF stripped (it is a single-line buffer), every remaining rune facing the same restrict gate, charLimit budget and mask/echo projection as keystrokes. NumberField's typing surface rides the same TextInput pipeline.
- History recall: TextInput's Up/Down browse a host-populated list
(
withHistory()/addToHistory()feed it); under the default map the arrows are navigation, so recall needs a freed map (or vim-insert's ctrl+p / ctrl+n chords where the host drives the VimKeyHandler).
Forms and groups
Form::new(...$fields) is a single-page form. For multi-page flows build
with Form::groups(Group::new(...$fields), …). Each group carries its own
title / description / hide-predicate / theme override:
Form::groups( Group::new( Input::new('name')->withTitle('Your name?'), Confirm::new('proceed')->withTitle('Continue?'), )->withTitle('Step 1'), Group::new( Note::new('done')->withTitle('Thanks!')->withNext()->withNextLabel('Finish'), ) ->withTheme(Theme::dracula()) ->withShowHelp(false) ->withHideFunc(fn (array $v) => $v['proceed'] !== true), );
Form-level chainables
| Method | What it does |
|---|---|
withTheme(Theme) |
Switch the colour palette. |
withAccessible(bool) |
Render one label: value line for the focused field — for screen readers / dumb terminals. Echo-mode fields project their display characters via displayValue(); the stored secret is never read aloud. |
withShowHelp(bool) |
Toggles the multi-group Step X of Y indicator (view() consults it only alongside more-than-one group and the group's own help flag). It renders no footer: keyBinds() / help() compose host-facing binding rows that view() never draws. |
withShowErrors(bool) |
False suppresses the inline ! error row (and its ? help line) that every field with an active verdict prints in its view() — since SF-24 that covers the whole selectable roster, not just the text surfaces, and the same row in the accessible view; the error summary block from withErrorSummary() is a separate composer and stays rendered. |
withWidth(int), withHeight(int) |
Pin the rendered geometry. Width is a ceiling: it threads into the width-aware fields (Input/Text/NumberField/Select/MultiSelect/Slider/RadioPills — each keeps its own narrower budget where set) and clips the form's own chrome; Confirm, Note, Date, Color and FilePicker render at natural width. Height stays advisory. |
withTimeout(int $ms) |
Stores a wall-clock budget (ms) for the host runtime to consult; the Form model itself starts no timer. |
withKeyMap(?KeyMap) |
Override the bindings for Next / Prev / Submit / Abort on a single form. |
validateAll(): array<string,string> |
Run all field validators and return [fieldKey => errorMessage] for fields that failed. Use at the Program-run boundary (once the Program ends) to collect cross-field validation failures that cannot be expressed per-field. |
Reading values after submit
A run can end in submission or in abort, so gate the read on
isSubmitted() before touching values() — after an abort the fields were
never validated and values()['name'] would be an unguarded lookup of a key
whose value was never accepted. The captured final model makes the check
honest:
$form = (new Program($form))->run(); if ($form->isSubmitted()) { echo $form->values()['name'], "\n"; } else { echo "Form aborted.\n"; }
values() returns every visible field keyed by key(). For typed access
call string(), int(), bool(), array(), or the keyed lookup
get(string $key, mixed $default = null) — the only accessor that returns the raw untyped value with
a fallback. For inspecting state during a run use errors(), hasErrors(),
focusedField(), keyBinds(), help().
(getString() and friends are deprecated forwarders, to be removed in 2.0.0.)
Save/restore
hydrate(array $values) is the symmetric counterpart of values():
save the map, hand it back later, and the form comes back to life —
hydrate($form->values()) round-trips every field. Each field parses its
own snapshot: Input/Text/Color/Select accept stringables (numbers
and BackedEnum cases included, bools refused — '1' from true is how
persistence bugs are born), MultiSelect a list of option strings,
Confirm a bool, Slider an int|float, NumberField an int|float
or null (null restores the never-set empty box, and off-lattice floats
commit onto the step exactly like withValue() does), Date and
FilePicker a string|null (the picker restores the selected path,
never the directory navigation), RadioPills an option label. Keys the
map cannot answer — unknown key, skippable key, wrong shape, or a field
that never opted in — throw an InvalidArgumentException naming the key
BEFORE any field is touched, so a bad snapshot can never half-hydrate.
Third-party fields opt in by implementing SugarCraft\Forms\Hydratable
— the hydrateValue(mixed $raw, array &$notes = []): static hook — and
hydrate identically to the shipped ones. The hook lives on a capability
interface (like AsyncValidatable) rather than on Field itself, so
existing custom fields keep compiling; a plain Field implementation
that never opted in fails loud by name instead of silently skipping.
A field that would rather decline than throw (a Select/RadioPills
whose snapshot value left the option pool) restores what it can and
records a human-readable note in $notes; those surface on the returned
form's hydrateNotes map — told, not thrown.
Themes & accessibility
Stock themes ship as static factories on SugarCraft\Forms\Theme:
ansi() (default), plain(), charm(), dracula(), catppuccin(),
base16(), base(). Pass one to Form::withTheme(...) — the theme is a
render context: Form::view() threads it into every field, so the slots
paint the field bodies too: focused/blurred titles, the cursor surface
(list rows, Confirm/RadioPills pills, the Date cursor cell), option rows,
the focused-Select caret (prompt slot), checked boxes (selectedOption),
the inline ! error row (error), and the summary bullets
(errorSummaryItem — split from the errorSummary block slot), plus the two
terminal [submitted] / [aborted] lines (submitted / aborted slots,
SF-33 — plain in every shipped preset, so the chrome bytes do not move
until a host styles them). The shipped
ansi() default keeps every existing field-body byte identical (its field
slots are the plain styles the legacy code hard-coded); pick any other
preset — or Theme::plain() for a zero-SGR render — and the body
repaints. The accessibility
mode flips the entire 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; runnable full-page shapes live under examples/.
Validators and dynamic labels
Every selectable field answers withValidator (sugar-forms-026 closed
the lumpy matrix — Note remains the one inert display field, with nothing
to judge). The full shipped matrix, re-derived from code:
| Field | Slot shape | Validator instance |
Closure subject | When the rule runs |
|---|---|---|---|---|
Input |
chains — every call appends, first error wins | yes (string) | string buffer |
per keystroke by default; withValidateOn defers to blur/submit |
Text |
single — a second call REPLACES the first; no null arm (closure-only, Validator not accepted) |
no | string buffer |
per keystroke by default; withValidateOn defers |
Confirm |
single; null clears |
yes — bool reads '1'/'' |
bool answer |
attach, every toggle, submit gate |
Select |
single; null clears |
yes — null selection reads '' |
selected label (string|null; BackedEnum in enum mode) |
attach, every value flip, submit gate |
MultiSelect |
single custom slot, null clears — the min/max COUNT check judges first and owns the row |
no (the subject is a list; pass a closure) | list<string> selected labels |
attach, every toggle, submit gate |
FilePicker |
single; null clears |
yes — unpicked reads '' |
selected path (string|null) |
attach, every selection move, submit gate |
Date |
single; null clears |
yes | ?string (YYYY-MM-DD) |
attach, every day commit, submit gate |
Slider |
single; null clears |
yes (number string-cast) | int|float |
attach, every step, submit gate |
Color |
single; null clears |
yes | hex string (#rrggbb) |
attach, every axis move, submit gate |
NumberField |
single; null clears |
yes (number string-cast) | committed int|float (never-set box carries no verdict) |
commit only — Enter, blur, submit gate; a draft edit clears the row |
RadioPills |
single; null clears |
yes — empty row reads '' |
selected label (string|null) |
attach, every pill move, submit gate |
The rules return null for valid or an error string; the verdict renders
inline beneath the field (governed by withShowErrors) and shows up in
Form::errors() / Form::validateAll().
Use withTitleFunc(\Closure(): string) / withDescriptionFunc(...) on any
field to compute labels lazily — handy when the label depends on values from
a previous group.
Built-in validators
SugarCraft\Forms\Validator provides five ready-made validators
(Required, Email, MinLength, MaxLength, Pattern). All implement the
Validator interface (returns true on valid, an error string on
invalid). On Input, multiple withValidator() calls chain — each call appends
to the validator list and the first error wins. On every other validating field
a second call replaces the first: Text holds one closure-only slot (no null
arm), the rest hold a single Validator\|\Closure\|null slot (null clears).
MultiSelect's slot sits alongside — not inside — its withMin/withMax
count constraint: a count violation owns the row, the rule runs only once the
selection is within bounds.
| Class | Error message | Notes |
|---|---|---|
Required |
Value is required |
Fails on empty string only |
Email |
Must be a valid email address |
Skipped when empty; uses filter_var |
MinLength(int $min) |
Must be at least N characters |
Uses mb_strlen (UTF-8 safe) |
MaxLength(int $max) |
Must be no more than N characters |
Uses mb_strlen (UTF-8 safe) |
Pattern(string $pattern, ?string $message = null, ?int $backtrackLimit = null, ?int $recursionLimit = null) |
$message, else the validator.pattern locale text |
Skipped when empty. Uses preg_match under a bounded PCRE budget (see below) |
Pattern compiles once at construction — an invalid pattern throws
InvalidArgumentException at the door. Every match then runs under a bounded
PCRE budget (200,000 backtrack / 100,000 recursion steps by default, overridable
per instance), applied via a scoped ini_set that is restored in a finally.
A pattern that exhausts its budget is reported as a validation failure — the
check fails closed, so a catastrophic pattern cannot hang the render loop.
Custom validators implement SugarCraft\Forms\Validator\Validator:
final class NoSpaces implements Validator { public function validate(string $input): true|string { if (str_contains($input, ' ')) { return 'Spaces are not allowed'; } return true; } }
Predicate validation and error summaries
Input / Text also take withValidation(fn($v) => bool, $message) — a
predicate alternative to withValidator. Form::withErrorSummary(true)
renders every failed field's message above the form when submit fails.
Fuzzy suggestions
Input and Select support withFuzzySuggestions() — candidates are
ranked by Smith-Waterman local-alignment score (sugar-fuzzy) and filtered to
positive scores. The fuzzy() short alias is equivalent. For programmatic
scoring use SugarCraft\Fuzzy\Matcher\SmithWatermanMatcher directly
(the deprecated SugarCraft\Forms\Fuzzy\FuzzyMatcher is a delegating shim over
it, not an alias — see Shared foundations;
scoring defaults in SugarCraft\Fuzzy\ScoringProfile: match +3,
mismatch -3, gap open -5, gap extend -1, adjacent bonus +5).
Async suggestions
The shipped signature has four parameters (the table cell abbreviates with
…): withAsyncSuggestions(callable $fetcher, int $debounceMs = 150, ?WorkerPool $workerPool = null, ?float $fetchTimeoutSeconds = null)
(alias async()) fetches list<string> suggestions off the keystroke path with a
debounce; SugarCraft\Forms\FormSuggestionsReadyMsg (the forms-side
envelope, SF-52) arrives via the event loop when fresh results land. The
envelope carries the fetch GENERATION: an arrival whose seq no longer
matches the field's newest scheduled flight — or whose field is no longer
focused (you arrowed away while the fetch was in flight) — is discarded
instead of popping an overlay nobody is looking at.
The two optional parameters are tuning surfaces, not part of the fetcher contract — leave them null unless you know why you are touching them:
$fetchTimeoutSeconds— when set, each in-flight fetch is raced against this wall-clock ceiling viaAsyncOps::withTimeout(); a breach rejects the race and surfaces as the fetcher failing (the same shape any other fetcher failure takes). The default null awaits the fetcher promise with no added timeout. Both arguments are validated at the setter door (fail-fast on negative debounce / non-positive timeout).$workerPool— RESERVED: stored on the model, never consulted (pool offload is not wired). The knob exists so a future offload can arrive without a signature break; passing a pool today changes nothing.
The precise shapes live in the Field\Input::withAsyncSuggestions() and
Field\Select::withAsyncSuggestions() docblocks.
Async validation gate
withAsyncValidator(Closure $validator) on the async-capable fields (Input
and Text — they implement SugarCraft\Forms\AsyncValidatable) registers a
check returning PromiseInterface<?string> (null/empty verdict = clean, a
string = blocking). Enter on the last field runs the sync gate first; when
sync is clean but async validators are still answering the form does not
submit: it parks in a pending round (a validating… hint paints while the
batch is in flight, and further Enter is ignored until it settles). Verdicts
return as one FormAsyncValidatedMsg: rejections keep the form open, paint
the blocking verdict on the field (and in the error summary when enabled)
and move focus to the first failing field; a clean round fires the deferred
submit. Any value edit clears the overlay — verdicts judged pre-edit bytes.
A validator that fails to answer BLOCKS with a typed verdict (an unanswered
check never waves data through), and a seq generation guard drops late
verdicts aimed at superseded or resolved forms. The public
Form::validateAsync() dispatches UNBOUNDED: every async validator of the
form fires simultaneously (a 20-field form issues 20 requests at once), and
after the first rejection the remaining promises drain — they run to
completion and their verdicts are dropped, uncancellable (both shapes
pinned in tests/FormAsyncValidateTest.php). Throttle in your fetcher if
that fan-out is too hot for the endpoint.
Verdicts carry an identity law (SF-49): a promise answers the bytes it
dispatched, not the bytes the field holds when it lands, and there is no
channel to re-land it on your copy. If you call validateAsync() on a field
directly, capture its value() before dispatch and discard the resolution —
including a clean null, which is exactly how a mid-flight edit would sneak
unvalidated bytes through — if the value changed in the meantime. The form's
submit gate carries this duty for you (edits clear the pending-round overlay;
the seq guard drops superseded verdicts); direct callers bear it by hand. The
race is pinned in tests/AsyncValidationVerdictIdentityTest.php; folding the
judged value into the promise payload itself is an owner-gated tuple upgrade.
ActionSpinner
A standalone blocking spinner for scripts and CLIs that need a visible
"working…" indicator without a full Model–Update–View program. It was folded
in from the retired prompt façade; the canonical class is
SugarCraft\Forms\ActionSpinner:
use SugarCraft\Forms\ActionSpinner; use SugarCraft\Forms\Spinner\Style as SpinnerStyle; ActionSpinner::new() ->withTitle('Crunching numbers...') ->withStyle(SpinnerStyle::dot()) ->withAction(static function () { // ... long-running work ... // Communicate results out-of-band: the action runs in a forked // child on pcntl hosts; in-memory mutations are not visible to // the parent after run() returns. }) ->run(); // returns SpinnerResult: exitCode / signal / timedOut / wallSeconds
Fork semantics on pcntl hosts: the action executes in a forked child.
Return values and in-memory mutations are not visible to the parent; a
throwing action surfaces as a non-zero exitCode on the SpinnerResult
run() returns (the original exception type/message cannot cross the fork
boundary), and a signal-killed child reports its signal instead of looking
like success. Callers that prefer the old exception style opt in with
->run()->throwIfFailed(), which throws the same localized failure row. The child is bounded
by a wall-clock ceiling (default 600 s; tune with
withMaxRuntimeSeconds()). On expiry the reaper escalates TERM→KILL and
run() throws — "was terminated" (child reaped) or "could not be
terminated" with the abandoned child's pid named. Communicate results via
tempfile, pipe, database, or other out-of-band mechanism. On hosts without
pcntl_fork, the action runs inline (no animation, no fork) and exceptions
propagate normally — but the inline fallback is unbounded: the wall-clock
ceiling can only rein in the forked child, so a hung action on a pcntl-less
host blocks forever.
Internationalization (i18n)
Every user-facing string — validation messages, key-bind labels, the
Step x of y footer, the [submitted]/[aborted] terminal lines, the empty-list
copy — routes through SugarCraft\Forms\Lang::t(), a thin per-library facade
(src/Lang.php) over the shared SugarCraft\Core\I18n\T registry with the forms
namespace baked in. The catalogue lives in lang/en.php and interpolates
{placeholder} tokens: Lang::t('form.step_of', ['current' => 1, 'total' => 3]).
The host selects a locale process-wide on the registry:
use SugarCraft\Core\I18n\T; T::setLocale('de'); // explicit T::setLocale(T::detect()); // from $LANG / $LC_ALL
Lookup order is exact locale → base language (de-at falls back to de) →
en → the raw dotted key, returned verbatim when the catalogue has no such entry
at all.
Today lang/ ships only en.php — the catalogue is English-only. Additional
locales seed over time following the house add-locale pattern (copy en.php,
translate values only, keep every key and {placeholder} token verbatim). Until a
locale is seeded, a non-en setting resolves through the en fallback: translated
output arrives only once the matching file lands, and nothing crashes on a missing
one.
Demos
Security & trust boundary
Form content is frequently model- or network-produced (agent UIs), 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 (\x1b\[[0-9;]*m), so theme colour renders while
screen clears, cursor moves and OSC payloads (e.g. OSC-8 hyperlinks) become
inert text. The sweep is idempotent and UTF-8 safe (C1 bytes are kept — they
overlap multi-byte sequences).
Cleaned at render: dynamic labels/descriptions, per-field error lines,
Confirm button labels, RadioPills and MultiSelect options, ItemList rows
behind Select, FilePicker cwd/entries/selection, errorHelp rows, the text
echo (Normal and Mask arms of TextInput::displayedValue()), the TextArea
render, the accessible view line, and the error summary.
The boundary is the display, never the buffer: value() returns pasted
bytes verbatim, and dev-authored strings (placeholder text) render raw —
they are trusted input by construction. Mirrors upstream bubbletea's
Viewport sanitisation for externally-sourced content.
Shared foundations
sugar-forms is built on six shared sibling packages:
- sugar-core — the Model–Update–View
runtime and message vocabulary (
Msg,Cmd,AsyncCmd) thatFormand every field ride (src/Form.php,src/KeyMap.php,src/Lang.php, the cursor layer). - sugar-style — declarative
Styleprimitives;Theme, the cursor blink and the text widgets render through them. - sugar-cellbuffer — Cell-grid model +
Buffer::toAnsi()for rendering glyphs and styles to ANSI bytes. TextInput / TextArea use the buffer path internally; their snapshot tests pin byte-for-byte output. - sugar-constraints —
LayoutSolver+ constraint types (Constraint::length,Constraint::fill, etc.).Form::withConstraints()stores an explicit constraint set on the form; solver region routing is a reserved surface —Form::view()does not consult it yet, so greedy vertical stacking is always used today. - sugar-fuzzy —
SmithWatermanMatcherscoring, used ONLY bySelect::withFuzzySuggestions()to rank the suggestion candidates. The ranking itself happens in the update arm —SmithWatermanMatcher::matchAllatsrc/Field/Select.php:350feeds the suggestion list; thewithFuzzySuggestions()setter (:131-135) only stores the candidate pool. The Select list filter itself is the plain case-insensitive substring match overItem::filterValue()inside this lib (src/ItemList/ItemList.php:248-251) — typing k finds Kitchen because 'kitchen' contains 'k', not by scoring. There is no public injection point for an alternative matcher, and MultiSelect does no fuzzy matching at all (k is cursor-up there; digits 1-9 are jump-toggles). - sugar-async —
AsyncOps+CancellationSourcefor async suggestion fetchers (the lib's failure vocabulary isOperationCancelledExceptionandTimeoutException).withAsyncSuggestionsstores aCancellationSourceon the model and cancels the previous in-flight fetch before starting the next. The debounce timer itself is never cancelled — each armed timer fires at most once into a cancellation check, so rapid keystrokes collapse to one live request. An already-started fetch runs to completion; passfetchTimeoutSecondsto bound it.
The lib also ships a shared vim keybinding layer: VimKeyHandler provides a
shared vim mode handler (VimState: Insert/Normal/Visual/VisualLine; VimAction:
CursorLeft, CursorRight, CursorUp, CursorDown, DeleteChar, YankLine, …). Vim mode
is an opt-in on the inner text widgets themselves — each runs on it when you arm
TextInput::withVimMode(true) (single-line) or the TextArea equivalent (j/k
rows, v visual selection) — and sugar-readline's vi mode delegates to this same
handler; sugar-widgets re-exports the fields unchanged and carries no vim layer of
its own. New bindings reach TextInput, TextArea and sugar-readline at once. In VisualLine mode, however,
j/k step between ENTRIES (the pinned horizontal CursorLeft/CursorRight
vocabulary), not rows, and V currently aliases v into character-wise
selection. Text objects (ci", da{, yiw, …) resolve through
VimKeyHandler::handleTextObject(): VimOperator (c/d/y) + TextObjectScope
(i/a) + a target key feed TextObject::resolve(), which returns the
[start, end) character range on the buffer — innermost bracket pair wins, quotes
pair left-to-right, unmatched delimiters return null (vim's beep).
The legacy SugarCraft\Forms\Fuzzy\FuzzyMatcher remains as a deprecated
back-compat shim. It is a delegating final class, not an alias: scoring runs on
the canonical SugarCraft\Fuzzy\Matcher\SmithWatermanMatcher, and the shim
survives only to preserve two legacy shapes — the
match(string, array): list<[string, int]> return the SSOT no longer exposes,
and the negative score for empty candidates (where the SSOT returns 0).
Accessor deprecation (2026-10-24)
The house accessor era (sugar-style precedent) renames get* reads to
bare twins. In sugar-forms, 34 reads were renamed to bare twins with a
one-line @deprecated forwarder (each marked REMOVED-IN: 2.0.0) riding the
old name; 19 name-blocked reads keep their get* prefix as documented legal
exceptions because the bare slot is a live fluent setter (or the Field
contract itself binds the name) — PHP admits one method per name.
The Field interface carries two abstract contract members, swept in the
same era: getDescription() and getError() are now @deprecated contract
members whose canonical spelling is description() / error(). getTitle()
is an interface-level exception: all twelve implementing fields
bind the bare title(string $title): self setter, so the interface cannot
adopt a bare read. Renamed class-level pairs:
| Legacy read | Bare read |
|---|---|
Color::getDescription() |
description() |
Color::getError() |
error() |
Confirm::getDescription() |
description() |
Confirm::getError() |
error() |
Date::getDescription() |
description() |
Date::getError() |
error() |
FilePicker::getDescription() |
description() |
FilePicker::getError() |
error() |
Input::getDescription() |
description() |
Input::getError() |
error() |
MultiSelect::getDescription() |
description() |
MultiSelect::getError() |
error() |
Note::getDescription() |
description() |
Note::getError() |
error() |
NumberField::getDescription() |
description() |
NumberField::getError() |
error() |
RadioPills::getDescription() |
description() |
RadioPills::getError() |
error() |
Select::getDescription() |
description() |
Select::getError() |
error() |
Slider::getDescription() |
description() |
Slider::getError() |
error() |
Text::getDescription() |
description() |
Text::getError() |
error() |
Form::getArray() |
array() |
Form::getBool() |
bool() |
Form::getFocusedField() |
focusedField() |
Form::getInt() |
int() |
Form::getString() |
string() |
TextArea::getRowOffset() |
rowOffset() |
Viewport::getHeight() |
height() |
Viewport::getWidth() |
width() |
Roster and shapes are pinned by tests/AccessorDeprecationTest.php (census,
markers, forwarder delegation, BC identity, and the exception list with its
collision reasons).
Mutator law completion (2026-11-13)
The same immutability logic applies to the write side: seven methods carried
in-place set*/show* names while returning mutate-clones like every other
with* — the discarded-return footgun. Each gained a canonical with*
spelling; the old name remains as a silent @deprecated delegator marked
REMOVED-IN: 2.0.0 (pinned by tests/AccessorDeprecationTest.php alongside
the get* census, which the sweep left at 53):
| Footgun name | Canonical |
|---|---|
ItemList::setItems() |
withItems() |
ItemList::setItem() |
withItem() |
FilePicker::setCwd() (widget) |
withCwd() |
TextArea::setWidth() / setHeight() |
withWidth() / withHeight() |
TextArea::showLineNumbers() |
withShowLineNumbers() |
TextInput::setSuggestions() |
withSuggestions() |
TextInput::showSuggestions() |
withShowSuggestions() |
The error readers were the third spelling drift (getError() / error() /
err()): the widgets' err() folds onto the family's error() with err()
kept as a deprecated alias, so error() is the one read everywhere while the
validators' true|string return remains the value shape, not a name.
Dependencies
Runtime requires (see composer.json):
sugarcraft/sugar-core— Model–Update–View TUI runtimesugarcraft/sugar-style— Declarative stylingsugarcraft/sugar-async— async suggestion support (cancellation sources)sugarcraft/sugar-cellbuffer— cell-grid rendering for the raw widgetssugarcraft/sugar-constraints— constraint types stored byForm::withConstraints()(solver routing reserved, not yet wired)sugarcraft/sugar-fuzzy— Smith-Waterman suggestion scoring
(sugarcraft/sugar-testing is a dev-only require, used by the golden
snapshot tests.)
Versioning
Sibling sugarcraft/* requirements are pinned to dev-master and the
manifest carries minimum-stability: dev. That is intentional while the
monorepo pre-dates 1.0: every library moves together and published installs
resolve siblings from Packagist dev-master (path repositories are
injected by CI at build time, never committed). At the stable release the
pins become proper ^1.0 constraints — track this in the release plan.
Consumer projects install under the same rule: see the Install note
above for the minimum-stability duty while no 1.0 tag exists.
Testing & CI
cd sugar-forms && composer install && vendor/bin/phpunit
CI runs this library's suite per push as one of the per-library matrix
jobs in .github/workflows/ci.yml (which libraries are discovered
dynamically via scripts/affected-libs.php). The sharded parallel runner
(scripts/parallel-tests.sh with its durations manifest) is specific to
the candy-code job and does not apply here — this suite runs whole.
Snapshot tests
Render output is covered by golden-file snapshot tests. Fixture files live
in tests/fixtures/ with a .golden extension and are compared against
actual ANSI byte output via SugarCraft\Testing\Snapshot\Assertions::assertGoldenAnsi().
To re-record a fixture after an intentional output change, delete the golden
first — UPDATE_GOLDENS=1 only creates missing goldens and never overwrites
an existing one:
rm tests/fixtures/<name>.golden UPDATE_GOLDENS=1 vendor/bin/phpunit
License
MIT
Credits & inspiration
Originally inspired by the Go Charm ecosystem; SugarCraft is developed as a native PHP project.







