Number 19: Form in named steps
Specification
- Catalogue
- No. 19 of 110
- Section
- Forms and inputs
- Interaction
- Type, Feedback, Layout Animation
- Element
- Form, Input
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
A booking split into named steps, with a marker that glides along to show where you are.
The visitor sees what is left before they start, can go back without losing anything, and is told exactly what to fix before moving on.
Marker glides 350ms, cubic-bezier(.77, 0, .175, 1); steps are named, not numbered circles. Visited steps stay clickable; answers are kept when going back. Errors are written next to the field and focus moves to the first one. Height glides with each step (the same mechanism as Height that glides).
Code
React and plain CSS"use client";
import { useEffect, useId, useRef, useState, type ChangeEvent, type CSSProperties } from "react";
import { AutoHeight } from "@/components/pieces/motion-helpers";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "@/components/pieces/styles/form-fields.css";
import "./stepper.css";
const STEPS = ["Details", "Boiler", "Time", "Check"];
type Booking = { name: string; phone: string; boiler: string; age: string; time: string };
const EMPTY: Booking = { name: "", phone: "", boiler: "", age: "", time: "" };
function errorsFor(step: number, b: Booking): Partial<Record<keyof Booking, string>> {
const e: Partial<Record<keyof Booking, string>> = {};
if (step === 0) {
if (!b.name.trim()) e.name = "Enter your name";
if (!/^[0-9 +()-]{10,}$/.test(b.phone.trim())) e.phone = "Enter a phone number, for example 07700 900123";
}
if (step === 1 && !b.boiler) e.boiler = "Choose a boiler type, or Not sure";
if (step === 2 && !b.time) e.time = "Choose a time that suits you";
return e;
}
function StepperDemo() {
const [step, setStep] = useState(0);
const [reached, setReached] = useState(0);
const [b, setB] = useState<Booking>(EMPTY);
const [showErr, setShowErr] = useState(false);
const [booked, setBooked] = useState(false);
const panel = useRef<HTMLDivElement>(null);
const moved = useRef(false);
const focusErr = useRef(false);
const uid = useId();
const errs = errorsFor(step, b);
useEffect(() => {
if (!moved.current) return;
const p = panel.current;
const field = focusErr.current ? p?.querySelector<HTMLElement>('[aria-invalid="true"]') : null;
focusErr.current = false;
(field ?? p?.querySelector<HTMLElement>("h3"))?.focus();
}, [step, booked]);
const go = (to: number) => {
moved.current = true;
setShowErr(false);
setStep(to);
setReached((r) => Math.max(r, to));
};
const next = () => {
if (Object.keys(errs).length) {
setShowErr(true);
const first = Object.keys(errs)[0];
panel.current?.querySelector<HTMLElement>(`[name="${first}"]`)?.focus();
return;
}
go(step + 1);
};
// Details can be changed after a step was passed, so moving forward (by the
// rail or by booking) checks every step before it, not only the current one.
const firstInvalid = (before: number): number | null => {
for (let k = 0; k < before; k++) if (Object.keys(errorsFor(k, b)).length) return k;
return null;
};
const jump = (to: number) => {
const bad = to > step ? firstInvalid(to) : null;
if (bad === null) go(to);
else if (bad === step) next();
else back(bad);
};
// Back to a step whose details no longer pass, with its errors showing.
const back = (to: number) => {
focusErr.current = true;
go(to);
setShowErr(true);
};
const field = (k: keyof Booking) => ({
name: k,
id: `${uid}-${k}`,
value: b[k],
"aria-invalid": showErr && errs[k] ? true : undefined,
"aria-describedby": showErr && errs[k] ? `${uid}-${k}-e` : undefined,
onChange: (e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setB((x) => ({ ...x, [k]: e.target.value })),
});
const err = (k: keyof Booking) =>
showErr && errs[k] ? (
<span className="st-err" id={`${uid}-${k}-e`}>
{errs[k]}
</span>
) : null;
return (
<div className="dm">
<div className="st">
<ol className="st-rail" style={{ "--i": step, "--n": STEPS.length } as CSSProperties}>
{STEPS.map((s, i) => (
<li key={s}>
<button type="button" disabled={i > reached || booked} aria-current={i === step ? "step" : undefined} onClick={() => jump(i)}>
{s}
</button>
</li>
))}
<span className="st-marker" aria-hidden="true" />
</ol>
<AutoHeight>
<div ref={panel} className="st-panel">
{booked ? (
<div role="status" className="st-fields">
<h3 tabIndex={-1}>Booked in</h3>
<p className="dm-small">
{b.name}, we will call {b.phone} to confirm your {b.time.toLowerCase()} visit. (Sample: nothing was sent.)
</p>
</div>
) : (
<form
className="st-fields"
noValidate
onSubmit={(e) => {
e.preventDefault();
const bad = step === 3 ? firstInvalid(3) : null;
if (step < 3) next();
else if (bad !== null) back(bad);
else {
moved.current = true;
setBooked(true);
}
}}
>
<h3 tabIndex={-1} className="sr-only">
Step {step + 1} of {STEPS.length}: {STEPS[step]}
</h3>
{step === 0 && (
<div className="st-grid">
<div className="st-field">
<label htmlFor={`${uid}-name`}>Name</label>
<input {...field("name")} autoComplete="name" />
{err("name")}
</div>
<div className="st-field">
<label htmlFor={`${uid}-phone`}>Phone</label>
<input {...field("phone")} type="tel" autoComplete="tel" inputMode="tel" />
{err("phone")}
</div>
</div>
)}
{step === 1 && (
<div className="st-grid">
<div className="st-field">
<label htmlFor={`${uid}-boiler`}>Boiler type</label>
<select {...field("boiler")}>
<option value="">Choose…</option>
{["Combi", "System", "Regular", "Not sure"].map((o) => (
<option key={o}>{o}</option>
))}
</select>
{err("boiler")}
</div>
<label className="st-field" htmlFor={`${uid}-age`}>
<span>Age (optional)</span>
<select {...field("age")}>
<option value="">Not sure</option>
{["Under 5 years", "5 to 10 years", "Over 10 years"].map((o) => (
<option key={o}>{o}</option>
))}
</select>
</label>
</div>
)}
{step === 2 && (
<fieldset className="st-times" aria-describedby={showErr && errs.time ? `${uid}-time-e` : undefined}>
<legend className="sr-only">Preferred time</legend>
{["Weekday morning", "Weekday afternoon", "Saturday morning"].map((t) => (
<label key={t} className="qz-opt">
<input type="radio" name="time" checked={b.time === t} onChange={() => setB((x) => ({ ...x, time: t }))} />
{t}
</label>
))}
{err("time")}
</fieldset>
)}
{step === 3 && (
<dl className="qz-sum">
{[
["Details", `${b.name}, ${b.phone}`, 0],
["Boiler", `${b.boiler}${b.age ? `, ${b.age.toLowerCase()}` : ""}`, 1],
["Time", b.time, 2],
].map(([k, v, i]) => (
<div key={k as string}>
<dt>{k}</dt>
<dd>
{v}{" "}
<button type="button" className="qz-link" onClick={() => go(i as number)} aria-label={`Change ${k}`}>
Change
</button>
</dd>
</div>
))}
</dl>
)}
<div className="qz-nav">
{step > 0 && (
<button type="button" className="dm-btn" onClick={() => go(step - 1)}>
Back
</button>
)}
<button type="submit" className="dm-btn" data-variant="solid">
{step === 3 ? "Book the service" : "Continue"}
</button>
</div>
</form>
)}
</div>
</AutoHeight>
</div>
</div>
);
}
// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [
{ input: 'input[autocomplete="name"]', value: "Sam Patel", wait: 500 },
{ input: 'input[type="tel"]', value: "07700 900123", wait: 600 },
{ click: 'button[type="submit"]', wait: 1300 },
{ click: 'button[type="submit"]', wait: 1300 },
];
export default function StepperEntry(props: LivePreviewProps) {
return (
<PieceStage {...props} label="Form in named steps" tour={TOUR}>
<StepperDemo />
</PieceStage>
);
}