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
| 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 errors at once on submit failure |
| 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(name) | 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 |
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.