@asaidimu/ui-wizard
v1.1.0
Published
Schema-driven, headless multi-step wizard state machine with validation, async step hooks and a React adapter.
Maintainers
Readme
@asaidimu/ui-wizard
Schema-driven, headless multi-step workflows for TypeScript.
The package is split into a framework-agnostic core and a thin React adapter:
| Entry point | Contents | Requires React |
| --------------------------- | ----------------------------------------------------------------------- | -------------- |
| @asaidimu/ui-wizard/core | The wizard state machine, validation pipeline, persistence and actions. | No |
| @asaidimu/ui-wizard/react | createWizardReact(), a hook built on @asaidimu/react-store. | Yes |
| @asaidimu/ui-wizard | Everything from both entry points. | Yes |
Use the /core entry point in server code, tests, background workers, or a
different UI framework. The core is built on
@asaidimu/ui-store, which is itself framework-agnostic.
Installation
bun add @asaidimu/ui-wizard
# or: npm install @asaidimu/ui-wizardReact is a peer dependency (>=18). The React entry point also installs
@asaidimu/react-store.
Mental model
A wizard is a state machine, not a bag of booleans in a component.
datais the canonical workflow document.stepsdeclares the ordered transitions and each step's schema.stepis the projection ofdatafor the active step:id,index,state,issues, andschema.statusisstepwhile the flow is active anddoneafter the last transition.navigation.forwardIssues/navigation.backwardIssueshold issues from the most recent attempt to move forward or back.activityis the execution lifecycle: whether a transition is in flight (pending) or a hook threw (error). It is runtime-only and never persisted.invocationstracks free-standing operations started withinvoke(), keyed by name.progressis the canonical0..100completion value derived from the step index (doneis always100).
status is control state; activity is execution state. Keeping them separate
is what lets the UI render a pending/error snapshot without corrupting the
persisted flow.
status: 'step' --NEXT(valid)--> 'step' (index + 1)
status: 'step' --NEXT(valid on last step)--> 'done'
status: 'done' --BACK--> 'step' (last index)
status: 'done' --REJECT--> 'step' (last index, with issues)Quick start (React)
import { createWizard } from "@asaidimu/ui-wizard";
import type { SchemaDefinition } from "@asaidimu/anansi";
type Signup = {
name: string;
email: string;
workspace: string;
};
const profileSchema: SchemaDefinition = {
name: "Profile",
version: "1.0.0",
fields: {
name: { name: "name", type: "string", required: true },
email: { name: "email", type: "string", required: true },
},
};
const wizard = createWizard<Signup>({
initialState: { name: "", email: "", workspace: "" },
steps: [
{
id: "profile",
schema: profileSchema,
onValidate: ({ data, issues }) => ({
issues: {
...issues,
...(data.email.includes("@")
? {}
: { email: "Enter a valid email." }),
},
}),
},
{ id: "workspace" },
],
persistenceKey: "signup",
persistenceVersion: "1.0.0",
});
export function SignupFlow() {
const { select, actions, isReady, selectors } = wizard.useWizard();
const status = select((state) => state.status);
const step = select((state) => state.step);
const data = select((state) => state.data);
const busy = select(selectors.isBusy);
const error = select(selectors.error);
if (!isReady) return <p>Loading…</p>;
if (status === "done") return <p>All done.</p>;
return (
<form
onSubmit={(event) => {
event.preventDefault();
void actions.next();
}}
onReset={(event) => {
event.preventDefault();
void actions.reset();
}}
>
<h2>{step.id}</h2>
<label>
Name
<input
value={data.name}
onChange={(event) => {
void actions.update({ name: event.target.value });
}}
/>
</label>
{step.issues.name && <p role="alert">{step.issues.name}</p>}
{error && (
<p role="alert">
{error.message}{" "}
<button type="button" onClick={() => void actions.retry()}>
Retry
</button>
</p>
)}
<button type="submit" disabled={busy || !wizard.can("NEXT")}>
{busy ? "Working…" : "Next"}
</button>
<button type="button" onClick={() => void actions.back()} disabled={busy}>
Back
</button>
<button type="reset" disabled={busy}>
Reset
</button>
</form>
);
}
actions.update()stays synchronous inside the action body so form inputs commit immediately; the bound action still returns a promise. Await it only when you need the committed state.A failed hook no longer rejects
actions.next(). It setsactivitytoerrorand leaves the control state untouched; read it throughselect(selectors.error)orstate().activity.
Core usage (no React)
import { createWizardCore } from "@asaidimu/ui-wizard/core";
const wizard = createWizardCore<{ name: string; workspace: string }>({
initialState: { name: "", workspace: "" },
steps: [{ id: "profile" }, { id: "workspace" }],
});
await wizard.actions.update({ name: "Ada" });
await wizard.actions.next();
console.log(wizard.getState().step.index); // 1
const issues = await wizard.validateCurrent();
if (Object.keys(issues).length === 0) {
// submit wizard.getState().data
}
await wizard.dispose();Always call dispose() when the wizard is no longer needed. It unregisters
middleware and action listeners, aborts in-flight invocations, releases
artifacts, and flushes pending persistence work.
Step definitions
Schemas are plain @asaidimu/anansi
SchemaDefinition values. Import the type from Anansi directly — the wizard
accepts schemas but deliberately does not re-export Anansi types.
type WizardStepDefinition<TState> = {
id: string;
schema?: SchemaDefinition;
onEnter?: (ctx) => Partial<TState> | void | Promise<Partial<TState> | void>;
onNormalize?: (ctx) => Partial<TState> | void | Promise<Partial<TState> | void>;
onValidate?: (ctx) => { issues?: WizardIssueMap } | void | Promise<{ issues?: WizardIssueMap } | void>;
canLeave?: (ctx) => {
allow?: boolean;
data?: Partial<TState>;
issues?: WizardIssueMap;
} | void | Promise<...>;
};Every hook receives:
type WizardStepContext<TState> = {
/** Full wizard state, including data, activity, and navigation issues. */
state: WizardState<TState>;
/** Fields owned by this step (schema projection, or all data without a schema). */
data: Partial<TState>;
/** Aborts when `cancel()` is called or a newer dispatch supersedes this one. */
signal: AbortSignal;
};Forward signal to fetch and other I/O so cancel() stops the work instead
of leaving it running:
{
id: "documents",
onNormalize: async ({ data, signal }) => {
const uploaded = await upload(data.file, { signal });
return { uploadedDocumentId: uploaded.id };
},
}Hook order
Forward navigation (next) runs:
onNormalize— may perform I/O and return values that are merged intodatabefore validation.- Schema validation — the step's
schema, if any. onValidate— receives the schema issues and may add or override them. It must not mutatedata.canLeave— may veto navigation with{ allow: false }, mergedatawhen allowing, or block with{ issues }.
If issues remain, the wizard stays on the step and writes them to
step.issues and navigation.forwardIssues. If canLeave vetoes, the wizard
stays without clearing existing issues.
A hook may throw. The wizard does not propagate the rejection to the
caller: it normalises the value into WizardFailure, moves activity to
error, and leaves the control state unchanged. Attach issues to the thrown
value to instead merge them into step.issues and stay idle:
const error = new Error("Name is already taken.");
Object.assign(error, { issues: { name: "Name is already taken." } });
throw error;Backward navigation (back) from a step runs canLeave on the current step,
then onEnter on the destination. Returning from the terminal done state to
the last step is a pure transition and runs no hooks.
enter is a self-transition: it re-runs onEnter on the current step without
changing the index and preserves issues.
Validation and issues
WizardIssueMap is Record<string, string> mapping a field name to a
human-readable message. Keys may be dotted paths (address.zip,
lines.0.qty).
Updating a field clears that field's issues and any dotted descendants. For
example, updating lines clears lines, lines.0.qty, and
lines.1.price; updating lines.0.qty clears only that leaf.
Use issuesUnder() to read a subtree:
import { issuesUnder } from "@asaidimu/ui-wizard/core";
const rowIssues = issuesUnder(wizard.getState().step.issues, "lines.0");Blur-time validation
actions.validate() re-runs validation without navigating. It skips
onNormalize by default because preparation may perform I/O. Pass
{ runNormalize: true } to run the complete pipeline.
await wizard.actions.validate();
await wizard.actions.validate({ runNormalize: true });wizard.validateCurrent() is the imperative equivalent and runs
onNormalize by default (pass { runNormalize: false } for a pure schema
check). It returns the issues without mutating state.
Server rejections
Use reject() to apply issues returned by a backend without discarding the
draft. From done, it returns to the last step so the user can correct the
offending fields.
await wizard.actions.reject({ email: "This email is already registered." });Navigation and dirty tracking
| Action | Description |
| ----------------------- | -------------------------------------------------------------------- |
| next() | Runs the validation pipeline and advances or marks the flow done. |
| back() | Moves backward without discarding data. No-op on the first step. |
| enter() | Re-runs the current step's onEnter. |
| update(partial) | Merges a payload into data and clears matching issues. |
| validate(options?) | Re-runs validation in place. |
| reject(issues) | Applies external issues. |
| markClean() | Resets the dirty baseline to the current data. |
| reset() | Returns to the initial step and initial data. |
| dispatch(event) | Dispatches a raw machine event. |
| retry() | Re-runs the failed transition (or resumes a failed run()). |
| cancel() | Aborts the in-flight transition and returns activity to idle. |
| clearError() | Dismisses the current error activity. |
| run(options?) | Drives the flow forward until done, until, or the first failure. |
| invoke(name, fn) | Runs a named free-standing operation with its own lifecycle. |
| clearInvocation(name) | Clears (and aborts) a named invocation. |
isDirty is true when data differs from the last clean baseline. The
baseline starts at initialState, is reset by markClean() and reset(), and
is advanced by enter() while the flow is clean, so mount-time onEnter
defaults do not mark the flow dirty.
can(eventType) reports whether an event is accepted in the current status.
Async lifecycle
Every async action (next, back, enter, validate, reject, dispatch)
shares one lifecycle:
- If a transition is already pending, the call is a no-op. Concurrent
next()calls cannot race. activitybecomes{ phase: "pending", event, stepId, targetStepId }synchronously, before any hook runs.- Hooks run with an
AbortSignal. - On success
activityreturns toidleand the control state commits. On failureactivitybecomes{ phase: "error", event, stepId, error }and the control state is unchanged.
type WizardActivity =
| { phase: "idle" }
| {
phase: "pending";
event: WizardActivityEvent; // NEXT | BACK | ENTER | UPDATE | REJECT | RESET | VALIDATE
stepId: string;
targetStepId: string | null;
}
| {
phase: "error";
event: WizardActivityEvent;
stepId: string;
error: WizardFailure; // { message, cause?, issues? }
};WizardFailure.cause is the original thrown value, preserved by reference.
Selectors
The core exposes canonical selectors so every consumer computes progress, busy-ness, and errors the same way:
const { selectors } = wizard;
selectors.activity(state); // WizardActivity
selectors.progress(state); // 0..100
selectors.currentStepNumber(state); // 1-based, clamped to steps.length
selectors.isBusy(state); // activity.phase === "pending"
selectors.canInteract(state); // activity.phase === "idle"
selectors.error(state); // WizardFailure | nullprogress is Math.round(index / steps.length * 100), with done always
100. For three steps it is 0 → 33 → 67 → 100.
Retry and cancel
retry() re-dispatches the last failed event. When the failure came from
run(), it resumes the whole pipeline from the current step. cancel() aborts
the in-flight hooks and invalidates their results, so a hook that ignores its
signal cannot overwrite the cancelled state.
const result = await wizard.actions.run();
if (result.status === "error") {
console.error(result.stepId, result.error.message);
await wizard.actions.retry();
}Running to completion
run() calls enter() on the current step, then next() until the flow is
done, the until step is reached, or a transition fails/blocks. It resolves
with a result instead of throwing:
type WizardRunResult =
| { status: "done"; results: Partial<Record<string, unknown>> }
| { status: "error"; stepId: string; error: WizardFailure };results is read from data.results when present, so a final step can write a
submission result into the document.
Free-standing operations
invoke(name, fn) tracks an operation that is not a transition (upload,
cleanup, polling) without touching data or the control state:
const upload = await wizard.actions.invoke("upload", async ({ signal }) => {
const file = await uploadFile(data.file, { signal });
return file.id;
});
if (upload.ok) {
await wizard.actions.update({ uploadedDocumentId: upload.value });
}Invocations are keyed by name. A newer invocation with the same name aborts the
previous one. Failures are recorded per name in invocations[name] until
cleared with clearInvocation(name).
Persistence
Set persistenceKey (and optionally persistenceVersion) to hydrate and
persist the whole wizard state through localStorage. Persistence is disabled
during SSR, where window is unavailable.
const wizard = createWizardCore({
initialState: { name: "" },
steps: [{ id: "profile" }],
persistenceKey: "onboarding",
persistenceVersion: "1.0.0",
});Await wizard.ready before rendering hydrated state. Use wizard.store.flush()
and wizard.dispose() during teardown.
Only the control/document state is persisted. activity and invocations are
runtime-only, so a hydrated wizard always starts idle. progress is derived
and recomputed on hydrate.
React adapter
createWizard() composes the core with
@asaidimu/react-store.
If you already have a core instance, wrap it directly:
import { createWizardCore } from "@asaidimu/ui-wizard/core";
import { createWizardReact } from "@asaidimu/ui-wizard/react";
const core = createWizardCore(options);
const { useWizard } = createWizardReact(core);The hook returns the react-store surface plus the wizard lifecycle:
| Member | Description |
| ------------------------------- | ------------------------------------------------------------------------------- |
| select(selector) | Reactive selection over WizardState (persisted state + lifecycle). |
| selectBase(selector) | Reactive selection over the persisted state only (upstream react-store path). |
| state() | Non-reactive snapshot of the combined view. |
| actions | Bound wizard actions with the async lifecycle. |
| activity / invocations | Live lifecycle snapshots (already subscribed). |
| selectors | Canonical selectors (isBusy, progress, error, …). |
| store / artifacts | Underlying store and artifact container. |
| isReady | Whether persistence has initialised. |
| watch(action) | Reactive loading state for an action. |
| resolve(key) / require(key) | Artifact resolvers. |
function Step() {
const { select, actions, selectors } = wizard.useWizard();
const step = select((state) => state.step);
const isDirty = select((state) => state.isDirty);
const busy = select(selectors.isBusy);
const error = select(selectors.error);
return (
<section>
<h2>{step.id}</h2>
{isDirty && <span>Unsaved changes</span>}
{error && <p role="alert">{error.message}</p>}
<button disabled={busy} onClick={() => void actions.next()}>
Continue
</button>
</section>
);
}select evaluates against the combined view, so it accepts comparisons and
arithmetic (selectors.isBusy, selectors.progress). It does not go through
react-store's static path analyser. Use selectBase when you only need plain
property access on the persisted state.
Return a stable value from the selector — a property, a primitive, or one of the
canonical selectors. Avoid constructing a new object on every call, because
useSyncExternalStore compares snapshots by reference.
Selectors rely on referential stability. The core reuses the previous step,
step.state, and empty issues objects when nothing relevant changed, so
select((state) => state.step.issues) does not re-render on every update.
activity and invocations keep the same reference until they actually
change.
State shape
type WizardState<TState> = {
status: "step" | "done";
data: TState;
step: {
id: string;
index: number;
state: Partial<TState>;
issues: WizardIssueMap;
schema?: SchemaDefinition;
};
navigation: {
forwardIssues: WizardIssueMap;
backwardIssues: WizardIssueMap;
};
isDirty: boolean;
progress: number; // 0..100
activity: WizardActivity; // runtime-only
invocations: Record<string, InvocationActivity>; // runtime-only
};WizardBaseState<TState> is the persisted subset (status, data, step,
navigation, isDirty, progress). getState() returns the combined
WizardState view.
Invariants:
step.stateis always a projection ofdataonto the active step's schema.- Empty issue maps share a frozen reference for selector stability.
- When
statusisdone,stepstill points at the last step, butstep.issuesis empty. activityandinvocationsnever appear in persisted state.
Testing
bunx vitest run src/wizardLicense
MIT
