All 42 libraries

SugarForms

Interactive forms + foundation form primitives

inspired by charmbracelet/huh foundation forms inputs wizards validation

SugarForms code coverage

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

Input primitivesTextInput, TextArea, ItemList, Viewport, FilePicker, Cursor, Scrollbar, Spinner.
Form engineField interface + Field\{Input, Text, Confirm, Select, MultiSelect, Note, FilePicker, Date, Slider, Color, NumberField, RadioPills\}, Form, Group, KeyMap, Theme.
Hidden fields & groupsForm 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.
Bounded editingTextInput / TextArea clip a paste or insert to the remaining 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.
ValidationAttach validators with ->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.
Fuzzy suggestions->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).
Async suggestions->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.
Async validation gate->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.
MultiSelect vim keysj / k navigate, Space toggles selection — mirrors vim-style keybindings.
Select enum modeSelect::withEnum(\BackedEnum::class) coerces the selected value to the given enum type automatically.
Multi-page GroupsGroup::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.
Seven themesansi (default), plain, charm, dracula, catppuccin, base16, base. Fields are themed end to end: 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.
Tab navTab / Shift+Tab between fields, Enter on the last submits, Esc / Ctrl+C aborts.
Read at the run boundary$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-level KeyMapForm::withKeyMap(?KeyMap) rebinds Next / Prev / Submit / Abort per form.
ActionSpinnerFork-isolated spinner action (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

Try the quickstart →

API

ClassMethodDescription
Formnew(Field ...$fields)Create a single-group form with fields
Formgroups(Group ...$groups)Create a multi-page form
Formvalues() / 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)
Formget(key, default = null)Value of one field, or the fallback when the key is absent
FormvalidateAll()Run all field validators, return [fieldKey => errorMessage]
FormwithErrorSummary(bool)Show all errors at once on submit failure
FormwithKeyMap(?KeyMap)Rebind Next / Prev / Submit / Abort per form
Groupnew(Field ...$fields) / withHideFunc(?\Closure(array): bool)A page of fields; the predicate receives the visible values collected before this group
Field\Inputnew(string)Create a text input field
Field\InputwithFuzzySuggestions(list)Filter suggestions by fuzzy match score
Field\InputwithAsyncSuggestions(callable, int = 150, ?WorkerPool = null, ?float = null)Async suggestions with debounce
Field\InputwithAsyncValidator(Closure): PromiseInterface<?string>Async validation blocks submit until it answers
Field\Confirmnew(string)Create a confirmation field
Field\Selectnew(string)->withOptions(string ...)Create a select field
Field\SelectwithFuzzySuggestions(list)Filter options by fuzzy match score
Field\SelectwithAsyncSuggestions(callable, int = 150, ?WorkerPool = null, ?float = null)Async suggestions with debounce
Field\SelectwithEnum(BackedEnum::class)Coerce selected value to enum type
Field\MultiSelectnew(name)Create multi-select field (j/k nav, Space toggle)
Field\Notenew(key)Create note field — text set via withTitle/withDescription; plain notes never appear in values() (a withNext(true) note contributes a null entry)
Validator\Requiredvalidate(string): true|stringtrue to pass, or the error string when the value is empty
Validator\Emailvalidate(string): true|stringtrue to pass, or the error string when the value is not a valid email
Spinner\Spinnernew(?Style)Create a spinner with style
ActionSpinnernew() / 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
ThemeerrorSummaryRenderable 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

Form

Static frame of a full form — Input, Select and Confirm.
Input

Input

Single-line text with validation.
Confirm

Confirm

Y/N boolean.
Select

Select

Single-choice list.
MultiSelect

MultiSelect

Toggle multiple options.
Text

Text

Multi-line text input.
Themes

Themes

Five of the seven themes side-by-side — base, charm, dracula, base16 and catppuccin; ansi and plain are omitted from the recording.
Multi-page form

Multi-page form

Wizard across multiple Groups, driven through a Program loop.