Form
A pattern, not a component: Card, Text, Input, Switch and Button composed for one task, with the order, the state changes and the accessibility contract written down. Nothing in the components changes. Switch the brand: the flow stays the same, the tokens behind it change.
Example
Submit it empty, fix one field, then submit a valid form. The request is simulated and always succeeds.
You’re on the list
States
The root's data-state names the state for tests and for your own styles; the pattern's CSS never reads it. Visibility comes from hidden, component states from their own ARIA attributes.
| State | What shows | Focus | A screen reader hears |
|---|---|---|---|
idle | The empty form. No errors, no summary. | Wherever the user leaves it. | Field names, “required”, hints. |
validating | Passes in one task: every field is checked with native validity. | — | — |
error | Each invalid field has aria-invalid="true" and its message; a summary with a link per error opens the form. | The first invalid field. | The field (name, “invalid”, its message), then the whole summary (role="alert"). |
submitting | The button has aria-busy="true" and its loading mark. A second submit is ignored. | Stays where it was. | “busy” on the button. |
success | The form is gone (hidden); the success card enters in its place. | The success heading (tabindex="-1"). | The heading, then the confirmation sentence (role="status"). |
Validation and announcements
- Errors appear on submit only. Typing and leaving a field never add one. A field that shows an error is checked again on every
input, and the error goes as soon as the value is valid;inputcan only remove an error, never add or change one. - Focus goes to the first invalid field, the shortest way to the fix. Its error is part of its description (
aria-describedby). - The summary is a
role="alert"region that is always in the page and empty until an error. Focus is on the field, so the summary cannot take focus too; the alert announces every error without it (WCAG 4.1.3). Each link moves focus to its field. A fixed field leaves the summary silently. - Submitting sets
aria-busy="true"on the button and keeps focus. The submit handler ignores submits while busy, so a click or Enter cannot send twice. - Success replaces the form and moves focus to its heading, because the focused button is gone. Only the confirmation sentence is
role="status", so the heading is not read twice.
Reduced motion
The success card enters with motion.duration.enter and motion.easing.enter: a fade and a short rise. With prefers-reduced-motion: reduce the rise is gone and the fade stays (ADR 0003). Errors appear without motion: feedback should not wait for an animation.
Usage
<link rel="stylesheet" href="@iahola/troupe-tokens/troupe.css">
<link rel="stylesheet" href="@iahola/troupe-components/card/styles.css">
<link rel="stylesheet" href="@iahola/troupe-components/text/styles.css">
<link rel="stylesheet" href="@iahola/troupe-components/input/styles.css">
<link rel="stylesheet" href="@iahola/troupe-components/switch/styles.css">
<link rel="stylesheet" href="@iahola/troupe-components/button/styles.css">
<link rel="stylesheet" href="patterns/form/styles.css"> <!-- copy from the repo -->
<div class="troupe-pattern-form" data-state="idle">
<form class="troupe-pattern-form__form" novalidate aria-labelledby="join-title">
<div class="troupe-card">
<header data-slot="header">
<h2 class="troupe-text" data-variant="title" id="join-title">Join the waiting list</h2>
<p class="troupe-text" data-variant="caption" data-tone="subtle">Fields marked * are required.</p>
</header>
<div data-slot="body">
<div class="troupe-pattern-form__alert" role="alert"></div>
<div class="troupe-pattern-form__fields">
<div class="troupe-input">
<label class="troupe-input__label" for="join-email">Email address</label>
<input class="troupe-input__control" id="join-email" name="email" type="email"
autocomplete="email" required aria-describedby="join-email-hint">
<p class="troupe-input__hint" id="join-email-hint">We send the confirmation here.</p>
</div>
<div class="troupe-input">
<label class="troupe-input__label" for="join-name">Name</label>
<input class="troupe-input__control" id="join-name" name="name" type="text"
autocomplete="name" required>
</div>
<label class="troupe-switch">
<input class="troupe-switch__control" type="checkbox" role="switch" name="reminder">
<span class="troupe-switch__track" aria-hidden="true"><span class="troupe-switch__thumb"></span></span>
<span class="troupe-switch__label">Send me a reminder the day before</span>
</label>
</div>
</div>
<div data-slot="actions">
<button type="submit" class="troupe-button">Join the list</button>
</div>
</div>
</form>
<div class="troupe-pattern-form__success" hidden>
<div class="troupe-card">
<header data-slot="header">
<h2 class="troupe-text" data-variant="title" data-tone="success" id="join-done" tabindex="-1">You’re on the list</h2>
</header>
<div data-slot="body">
<p class="troupe-text" role="status"></p>
</div>
</div>
</div>
</div>Script
Documentation, not a published module: copy it and replace send() with your request. Server-side validation and the real submit are yours.
/**
* Form pattern: example script (packages/patterns/form/README.md, ADR 0005).
*
* Documentation, not a published module: the first release ships no
* JavaScript (ADR 0003). The docs page runs this file and prints it, so what
* the page shows is what it runs. Copy it and replace `send()` with the real
* request.
*
* Everything it touches is the components' own contract: Input's
* aria-invalid / troupe-input__error / aria-describedby, Button's aria-busy.
* It adds no classes to components and never styles them.
*
* State machine on the root's data-state:
* idle -> validating -> error | submitting -> success
* Errors appear only on submit. While a field shows an error, `input` may
* remove it (never add or change one), so typing never produces a new error.
*/
type Rule = 'valueMissing' | 'typeMismatch';
type State = 'idle' | 'validating' | 'error' | 'submitting' | 'success';
/** Field messages by field name: say what to do, not what went wrong. */
const messages: Record<string, Partial<Record<Rule, string>>> = {
email: {
valueMissing: 'Enter your email address.',
typeMismatch: 'Enter an email address like [email protected].',
},
name: {
valueMissing: 'Enter your name.',
},
};
/** Simulated request time. The real request replaces send(). */
const SEND_DELAY_MS = 1200;
const send = (_data: FormData) => new Promise<void>((resolve) => setTimeout(resolve, SEND_DELAY_MS));
/** The first failed rule's message, or null when the field is valid. Native validity, plus: whitespace is not a value. */
function messageFor(field: HTMLInputElement): string | null {
const own = messages[field.name] ?? {};
if (field.required && field.value.trim() === '') return own.valueMissing ?? 'Fill in this field.';
if (field.validity.typeMismatch) return own.typeMismatch ?? 'Check the format of this field.';
return field.validity.valid ? null : field.validationMessage;
}
const errorId = (field: HTMLInputElement) => `${field.id}-error`;
function describedBy(field: HTMLInputElement, id: string, present: boolean) {
const ids = (field.getAttribute('aria-describedby') ?? '').split(/\s+/).filter((x) => x && x !== id);
if (present) ids.push(id); // order: hint, error (Input README)
if (ids.length) field.setAttribute('aria-describedby', ids.join(' '));
else field.removeAttribute('aria-describedby');
}
/** Input contract: aria-invalid, the error message and its aria-describedby entry come and go together. */
function showError(field: HTMLInputElement, message: string) {
let error = document.getElementById(errorId(field));
if (!error) {
error = document.createElement('p');
error.className = 'troupe-input__error';
error.id = errorId(field);
field.closest('.troupe-input')!.append(error);
}
error.textContent = message;
field.setAttribute('aria-invalid', 'true');
describedBy(field, error.id, true);
}
function clearError(field: HTMLInputElement) {
document.getElementById(errorId(field))?.remove();
field.removeAttribute('aria-invalid');
describedBy(field, errorId(field), false);
}
function setup(root: HTMLElement) {
const form = root.querySelector<HTMLFormElement>('.troupe-pattern-form__form')!;
const alert = root.querySelector<HTMLElement>('.troupe-pattern-form__alert')!;
const submit = form.querySelector<HTMLButtonElement>('button[type="submit"]')!;
const success = root.querySelector<HTMLElement>('.troupe-pattern-form__success')!;
const successHeading = success.querySelector<HTMLElement>('[tabindex="-1"]')!;
const successStatus = success.querySelector<HTMLElement>('[role="status"]')!;
const fields = [...form.querySelectorAll<HTMLInputElement>('.troupe-input__control')];
let requests = 0;
const setState = (state: State) => {
root.dataset.state = state;
};
/**
* Error summary in the always-present role="alert" region. Emptied first and
* filled on the next frame, so a second failed submit is announced again.
* The title has no count, so removing a fixed row later changes no text.
*/
function renderSummary(errors: { field: HTMLInputElement; message: string }[]) {
alert.replaceChildren();
requestAnimationFrame(() => {
const box = document.createElement('div');
box.className = 'troupe-pattern-form__summary';
const title = document.createElement('p');
title.className = 'troupe-text';
title.append(Object.assign(document.createElement('strong'), { textContent: 'Check the following:' }));
const list = document.createElement('ul');
list.className = 'troupe-pattern-form__summary-list';
for (const { field, message } of errors) {
const item = document.createElement('li');
item.className = 'troupe-text';
item.dataset.field = field.id;
const link = Object.assign(document.createElement('a'), { href: `#${field.id}`, textContent: message });
item.append(link);
list.append(item);
}
box.append(title, list);
alert.append(box);
});
}
/** A fixed field leaves the summary. Removals are not announced (aria-relevant default), so fixing is silent. */
function dropFromSummary(field: HTMLInputElement) {
alert.querySelector(`li[data-field="${field.id}"]`)?.remove();
if (!alert.querySelector('li')) alert.replaceChildren();
}
// A summary link moves focus to its field; a bare fragment link would only scroll.
alert.addEventListener('click', (event) => {
const link = (event.target as Element).closest<HTMLAnchorElement>('a[href^="#"]');
const field = link && document.getElementById(link.hash.slice(1));
if (!field) return;
event.preventDefault();
field.closest('.troupe-input')?.scrollIntoView({ block: 'nearest' });
field.focus({ preventScroll: true });
});
// Fixing a field removes its error at once. Never adds one.
form.addEventListener('input', (event) => {
const field = event.target;
if (!(field instanceof HTMLInputElement) || field.getAttribute('aria-invalid') !== 'true') return;
if (messageFor(field) !== null) return;
clearError(field);
dropFromSummary(field);
if (!fields.some((f) => f.getAttribute('aria-invalid') === 'true')) setState('idle');
});
form.addEventListener('submit', async (event) => {
event.preventDefault();
// Button README: loading never uses `disabled`; the consumer ignores activations while busy.
// Guarded here, not on click, because Enter in a field submits past the button.
if (submit.getAttribute('aria-busy') === 'true') return;
setState('validating');
const errors: { field: HTMLInputElement; message: string }[] = [];
for (const field of fields) {
const message = messageFor(field);
if (message) {
showError(field, message);
errors.push({ field, message });
} else {
clearError(field);
}
}
if (errors.length) {
setState('error');
// Focus first: the shortest way to the fix. The alert follows on the next frame and carries every error, the focused one included.
errors[0].field.focus();
renderSummary(errors);
return;
}
alert.replaceChildren();
setState('submitting');
submit.setAttribute('aria-busy', 'true');
root.dataset.requests = String(++requests); // docs only: lets the spec count requests
const data = new FormData(form);
await send(data);
submit.removeAttribute('aria-busy');
// Success replaces the form. Focus must move, or it falls to <body> with the hidden button.
form.hidden = true;
success.hidden = false;
setState('success');
successHeading.focus();
// The status region is rendered before it gets text, and only carries what the heading does not say.
requestAnimationFrame(() => {
const reminder = data.get('reminder') === 'on' ? ' You’ll also get a reminder the day before.' : '';
successStatus.textContent = `We’ll email ${String(data.get('email'))} when tickets go on sale.${reminder}`;
});
});
}
document.querySelectorAll<HTMLElement>('.troupe-pattern-form').forEach(setup);
Full specification: packages/patterns/form/README.md.