A long form in steps: each step checks its own fields, optional steps can be skipped, a review at the end, and progress kept across reloads.
import { Command, Component, Mount, UiSchema } from "@effect/ui"import { Html } from "@effect/ui/html"import * as stylex from "@stylexjs/stylex"import { Effect, Option, Schema } from "effect"import { Button } from "./ui/uicontext/components/Button.ts"import { formatCount } from "./ui/uicontext/components/domain/Format.ts"import { FormField, Input, Select } from "./ui/uicontext/components/FormControls.ts"import { clearDraft, readDraft, RestoreDraft, saveDraft } from "./ui/uicontext/components/forms/Draft.ts"import { addRow, fieldId, focusField, focusId, make, removeRow } from "./ui/uicontext/components/forms/Form.ts"import { FieldGrid } from "./ui/uicontext/components/forms/FormLayout.ts"import { RepeatingFields, rowLabel } from "./ui/uicontext/components/forms/RepeatingFields.ts"import { FormWizard, goToStep, nextStep, previousStep, skipStep, startWizard, stepHeadingId, WizardReview, WizardState } from "./ui/uicontext/components/forms/Wizard.ts"import type { Step } from "./ui/uicontext/components/Stepper.ts"import { sx } from "./ui/uicontext/components/Sx.ts"import { color, font, radius, space } from "./ui/uicontext/components/tokens.stylex.ts"// Onboarding: a workspace, then you, then (if you like) your teammates, then a review. Each step// checks only its own fields before it moves on, and the whole thing is kept in this browser as you// go: reload the page and it picks up at the same step.const Onboarding = make( Schema.Struct({ workspace: Schema.Trim.check(Schema.isNonEmpty({ message: "Name your workspace" }), Schema.isMaxLength(48, { message: "Keep it to 48 characters" })).annotate({ title: "Workspace name" }), size: Schema.Literals(["1", "2-10", "11-50", "51-200", "200+"]).annotate({ title: "Team size", message: "Choose how many people will use it" }), name: Schema.Trim.check(Schema.isNonEmpty({ message: "Enter your name" })).annotate({ title: "Your name" }), role: Schema.Literals(["engineering", "design", "product", "support", "other"]).annotate({ title: "Your role", message: "Choose the closest one" }), invites: Schema.Array( Schema.Struct({ id: Schema.String, email: Schema.Trim.check(Schema.isNonEmpty({ message: "Enter an email address, or remove the row" }), Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/u, { message: "Enter an email address, like [email protected]" })).annotate({ title: "Email" }), }), ), }),)const steps: ReadonlyArray<Step> = [ { id: "workspace", title: "Workspace" }, { id: "you", title: "About you" }, { id: "invite", title: "Invite teammates", optional: true }, { id: "review", title: "Review" },]/** The fields each step owns: Next checks these and no others. */const stepFields: Record<string, ReadonlyArray<string>> = { workspace: ["workspace", "size"], you: ["name", "role"], invite: ["invites"], review: [] }const sizes = [["1", "Just me"], ["2-10", "2–10 people"], ["11-50", "11–50 people"], ["51-200", "51–200 people"], ["200+", "More than 200"]] as constconst roles = [["engineering", "Engineering"], ["design", "Design"], ["product", "Product"], ["support", "Support"], ["other", "Something else"]] as constconst labelIn = (list: ReadonlyArray<readonly [string, string]>, value: string) => list.find(([v]) => v === value)?.[1] ?? ""const Draft = Schema.Struct({ form: Onboarding.State, wizard: WizardState, nextId: Schema.Number })const DRAFT = "onboarding-example"const ID = "onboarding"const Message = UiSchema.TaggedEnum({ UpdatedField: { name: Schema.String, value: Schema.String }, BlurredField: { name: Schema.String }, ClickedAddInvite: {}, ClickedRemoveInvite: { id: Schema.String }, Submitted: {}, ClickedBack: {}, ClickedSkip: {}, PickedStep: { id: Schema.String }, FoundDraft: { json: Schema.String }, ClickedStartOver: {}, SucceededCreateWorkspace: {},})class CreateWorkspace extends Command.Service<CreateWorkspace>()("example/OnboardingCreateWorkspace", { args: { workspace: Schema.String }, success: Message,}) { static readonly layer = this.toLayer(() => Effect.sleep("900 millis").pipe(Effect.as(Message.SucceededCreateWorkspace())))}const styles = stylex.create({ card: { display: "grid", gap: space.xl, inlineSize: "min(100%, 40rem)", padding: { default: space.xl, "@media (min-width: 640px)": space.xxl }, borderWidth: 1, borderStyle: "solid", borderColor: color.line, borderRadius: radius.lg, backgroundColor: color.panel }, resumed: { display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: space.md, margin: 0, paddingBlock: space.sm, paddingInline: space.md, borderRadius: radius.md, backgroundColor: color.raised, fontSize: font.sm, color: color.muted }, fields: { display: "grid", gap: space.xl }, done: { display: "grid", gap: space.md, justifyItems: "start" }, doneTitle: { margin: 0, fontSize: font.lg, fontWeight: 600 }, doneText: { margin: 0, fontSize: font.sm, color: color.muted },})const blankInvite = (id: string) => ({ id, email: "" })const fresh = () => ({ form: Onboarding.init({ workspace: "", size: "", name: "", role: "", invites: [blankInvite("i1")] }), wizard: startWizard(steps), nextId: 2,})export const OnboardingWizardNoDeps = Html.component({ name: "OnboardingWizard", model: Schema.Struct({ form: Onboarding.State, wizard: WizardState, nextId: Schema.Number, resumed: Schema.Boolean, // a draft has been kept in this browser kept: Schema.Boolean, finishing: Schema.Boolean, finished: Schema.Boolean, }), message: Message,}).make({ init: () => ({ ...fresh(), resumed: false, kept: false, finishing: false, finished: false }), update: { UpdatedField: ($, { name, value }) => ($.model.finishing ? $.model : $.evolve({ form: (form) => Onboarding.change(form, name, value) })), // leaving a field keeps what was typed, so a reload loses nothing BlurredField: ($, { name }) => { const form = Onboarding.blur($.model.form, name) return $.evolve({ form, kept: true }).run(saveDraft(DRAFT, Draft, { form, wizard: $.model.wizard, nextId: $.model.nextId })) }, ClickedAddInvite: ($) => $.evolve({ form: (form) => addRow(form, "invites", blankInvite(`i${$.model.nextId}`)), nextId: (n) => n + 1 }), ClickedRemoveInvite: ($, { id }) => $.evolve({ form: (form) => removeRow(form, "invites", id) }), // Next, and Finish on the review: the form's own submit Submitted: ($) => { if ($.model.finishing) return $.model const step = $.model.wizard.step if (step === "review") { const value = Onboarding.validate($.model.form).value return Option.isSome(value) ? $.evolve({ finishing: true }).run(CreateWorkspace.make({ workspace: value.value.workspace })) : $.model } const fields = stepFields[step] ?? [] const form = Onboarding.touch($.model.form, fields) const checked = Onboarding.validate(form) if (!checked.passes(fields)) { const first = checked.firstError(fields) return first === undefined ? $.evolve({ form }) : $.evolve({ form }).run(focusField(ID, first)) } const wizard = nextStep(steps, $.model.wizard) return $.evolve({ form, wizard, kept: true }).run(focusId(stepHeadingId(ID)), saveDraft(DRAFT, Draft, { form, wizard, nextId: $.model.nextId })) }, ClickedBack: ($) => { const wizard = previousStep(steps, $.model.wizard) return $.evolve({ wizard, kept: true }).run(focusId(stepHeadingId(ID)), saveDraft(DRAFT, Draft, { form: $.model.form, wizard, nextId: $.model.nextId })) }, // skipping the invites sends none: the rows go, and the review says it was skipped ClickedSkip: ($) => { const wizard = skipStep(steps, $.model.wizard) const form = Onboarding.change($.model.form, "invites", []) return $.evolve({ wizard, form, kept: true }).run(focusId(stepHeadingId(ID)), saveDraft(DRAFT, Draft, { form, wizard, nextId: $.model.nextId })) }, PickedStep: ($, { id }) => { const wizard = goToStep(steps, $.model.wizard, id) // coming back to the invites after skipping them starts with an empty row const form = id === "invite" && $.model.form.values.invites.length === 0 ? addRow($.model.form, "invites", blankInvite(`i${$.model.nextId}`)) : $.model.form return $.evolve({ wizard, form, nextId: (n) => n + 1 }).run(focusId(stepHeadingId(ID))) }, FoundDraft: ($, { json }) => Option.match(readDraft(Draft, json), { onNone: () => $.model, onSome: (draft) => $.evolve({ form: draft.form, wizard: draft.wizard, nextId: draft.nextId, resumed: true, kept: true }), }), ClickedStartOver: ($) => $.set({ ...fresh(), resumed: false, kept: false, finishing: false, finished: false }).run(clearDraft(DRAFT), focusId(stepHeadingId(ID))), SucceededCreateWorkspace: ($) => $.evolve({ finishing: false, finished: true }).run(clearDraft(DRAFT)), }, view: (h, model) => { if (model.finished) { return h.div.attrs(sx(styles.card)).children( h.div.attrs({ role: "status", ...sx(styles.done) }).children( h.h3.attrs(sx(styles.doneTitle)).children(`${model.form.values.workspace.trim()} is ready`), h.p.attrs(sx(styles.doneText)).children( model.form.values.invites.length === 0 ? "Invite your team any time from Settings." : `${formatCount(model.form.values.invites.length, "invite")} sent.`, ), Button(h, {}).on("click", Message.ClickedStartOver()).children("Start again"), ), ) } const checked = Onboarding.validate(model.form) const values = model.form.values const step = model.wizard.step const errorOf = (path: string) => { const e = checked.field(path).error return e === undefined ? {} : { error: e } } const text = (name: "workspace" | "name", label: string, autocomplete: string) => FormField(h, { id: fieldId(ID, name), label, required: true, ...errorOf(name) }, (attrs) => Input(h, { invalid: checked.field(name).error !== undefined }) .attrs({ ...attrs, autocomplete }) .value(values[name]) .on("input", ({ value }) => Message.UpdatedField({ name, value })) .on("blur", Message.BlurredField({ name }))) const choice = (name: "size" | "role", label: string, options: ReadonlyArray<readonly [string, string]>) => FormField(h, { id: fieldId(ID, name), label, required: true, ...errorOf(name) }, (attrs) => Select(h, { invalid: checked.field(name).error !== undefined }) .attrs(attrs) .value(values[name]) .on("change", ({ value }) => Message.UpdatedField({ name, value })) .on("blur", Message.BlurredField({ name })) .children( h.option.attrs({ value: "", disabled: "" }).children("Choose…"), options.map(([value, text]) => h.option.key(value).attrs({ value }).children(text)), )) const body = step === "workspace" ? FieldGrid(h, [text("workspace", "Workspace name", "organization"), choice("size", "Team size", sizes)]) : step === "you" ? FieldGrid(h, [text("name", "Your name", "name"), choice("role", "Your role", roles)]) : step === "invite" ? RepeatingFields(h, { id: `${ID}-invites`, legend: "Teammates", description: "They'll get an email to join. You can invite more later.", rows: values.invites, noun: "teammate", max: 5, columns: "minmax(0, 1fr)", onAdd: Message.ClickedAddInvite(), onRemove: (id) => Message.ClickedRemoveInvite({ id }), row: (row, index) => { const path = `invites.${row.id}.email` return [ FormField(h, { id: fieldId(ID, path), label: "Email", labelStyle: rowLabel, ...errorOf(path) }, (attrs) => Input(h, { invalid: checked.field(path).error !== undefined }) .attrs({ ...attrs, type: "email", autocomplete: "off", placeholder: "[email protected]", "aria-label": `Email, teammate ${index + 1}` }) .value(row.email) .on("input", ({ value }) => Message.UpdatedField({ name: path, value })) .on("blur", Message.BlurredField({ name: path }))), ] }, }) : WizardReview(h, [ { step: steps[0]!, onEdit: Message.PickedStep({ id: "workspace" }), rows: [{ label: "Workspace name", value: values.workspace.trim() }, { label: "Team size", value: labelIn(sizes, values.size) }] }, { step: steps[1]!, onEdit: Message.PickedStep({ id: "you" }), rows: [{ label: "Your name", value: values.name.trim() }, { label: "Your role", value: labelIn(roles, values.role) }] }, { step: steps[2]!, onEdit: Message.PickedStep({ id: "invite" }), skipped: model.wizard.skipped.includes("invite") || values.invites.length === 0, rows: [{ label: formatCount(values.invites.length, "teammate"), value: values.invites.map((i) => i.email.trim()).join(", ") }], }, ]) const lead: Record<string, string> = { workspace: "Where your team's projects and docs will live.", you: "So your teammates know who set this up.", invite: "Work goes better together. Or skip this and invite people later.", review: "Check everything, then create the workspace.", } return h.div.attrs(sx(styles.card)).onMount(RestoreDraft({ key: DRAFT }).pipe(Mount.map(({ json }) => Message.FoundDraft({ json })))).children( model.resumed ? h.p.attrs({ role: "status", ...sx(styles.resumed) }).children( "Picked up where you left off.", Button(h, { size: "sm", emphasis: "ghost" }).on("click", Message.ClickedStartOver()).children("Start over"), ) : null, FormWizard(h, { id: ID, steps, at: model.wizard, lead: lead[step] ?? "", onStep: (id) => Message.PickedStep({ id }), onSubmit: Message.Submitted(), onBack: Message.ClickedBack(), onSkip: Message.ClickedSkip(), busy: model.finishing, nextLabel: step === "review" ? (model.finishing ? "Creating…" : "Create workspace") : "Continue", ...(model.kept ? { saved: "Progress saved in this browser" } : {}), children: [h.div.attrs(sx(styles.fields)).children(body)], }), ) },})export const OnboardingWizard = OnboardingWizardNoDeps.pipe(Component.provide(CreateWorkspace.layer))Installation
pnpm dlx shadcn@latest add checkfu/uicontext/form-wizardUsage
import type { Step } from "./ui/uicontext/components/Stepper.ts"import { FormWizard, nextStep, type WizardState } from "./ui/uicontext/components/forms/Wizard.ts"const steps: ReadonlyArray<Step> = [ { id: "workspace", title: "Workspace" }, { id: "invite", title: "Invite teammates", optional: true }, { id: "review", title: "Review" },]// in update, on the form's submit: touch the step's fields, and move on once they pass// const form = Signup.touch(model.form, ["workspace"])// Signup.validate(form).passes(["workspace"]) ? { form, wizard: nextStep(steps, model.wizard) } : { form }export const advance = (wizard: WizardState) => nextStep(steps, wizard)export const Setup = <M, C extends View.Children<M>>(h: Html.H<M>, wizard: WizardState, body: C, on: { readonly submit: M; readonly back: M; readonly skip: M; readonly step: (id: string) => M }) => FormWizard(h, { id: "setup", steps, at: wizard, onSubmit: on.submit, onBack: on.back, onSkip: on.skip, onStep: on.step, children: body })API reference
Options
| Name | Type | Default | Description |
|---|---|---|---|
idrequired | string | — | The wizard's id: its heading and form ids start with it |
stepsrequired | Step[] | — | — |
atrequired | WizardState | — | — |
lead | string | — | A sentence under the step's title |
childrenrequired | View.Children | — | The current step's fields |
onSteprequired | (id: string) => Message | — | Go back to a step already done |
onSubmitrequired | Message | — | Next and the last step's submit: the form's own submit, so Enter in a field does it too |
onBackrequired | Message | — | — |
onSkip | Message | — | Shows Skip on an optional step |
nextLabel | string | "Continue" | "Continue" by default |
busy | boolean | — | A submit is in flight: Next waits |
saved | string | — | Where saved progress stands: "Progress saved" |
errors | string[] | — | Steps with an error to fix, as the Stepper marks them |
style | Style | — | — |