Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

test(a11y): reusable checkbox-pattern contract across four adopters (#6157)

Cindy Zhang43f4f7d093d0
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 1ccb13226e..5bd1de6b30 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -63,5 +63,14 @@
{
"component": "core/IconButton",
"reason": "IconButton is a thin wrapper that renders Button with `isIconOnly`, adding no layout, no positioning, and no directional affordance of its own, so it inherits `core/Button`'s verification above exactly. Its single icon is centred in a square control, which has no reading direction to mirror."
+ },
+ {
+ "component": "core/SelectableCard",
+ "reason": "SelectableCard renders content in normal flow inside a symmetric Card. Its hover overlay and selected ring cover all four edges equally, its source uses no physical left/right positioning or directional glyphs, and its checkbox interaction uses only pointer, Space, Enter, and Tab rather than inline-direction keys. Every current story therefore has no component-owned visual or behavioral RTL difference for the audit to measure.",
+ "evidence": {
+ "apps/storybook/stories/SelectableCard.stories.tsx": "sha256:35704da575bb80fc580309a5d4182ab4569abbd1449c665f69f1f00767b5790b",
+ "packages/core/src/SelectableCard/SelectableCard.tsx": "sha256:5fa8fcf087296e33415a2696b91e478608b737506f26775715132a3a63e9218e",
+ "packages/core/src/SelectableCard/index.ts": "sha256:9cf677856807a09ee444ce68b21118bca9729592485f892da7e0bb64ee1d7501"
+ }
}
]
diff --git a/apps/storybook/stories/CheckboxA11y.stories.tsx b/apps/storybook/stories/CheckboxA11y.stories.tsx
new file mode 100644
index 0000000000..187f436a53
--- /dev/null
+++ b/apps/storybook/stories/CheckboxA11y.stories.tsx
@@ -0,0 +1,83 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CheckboxA11y.stories.tsx
+ * @input Uses the shared Checkbox binding inventory and render map
+ * @output One checked-in reproduction story for every Checkbox contract state
+ * @position Stable real-browser fixtures required by AST-009 FR30 and AST-021.
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {CHECKBOX_STATE_RENDERS} from '../../../packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.renders';
+import {CHECKBOX_BINDING_STATES} from '../../../packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.states';
+
+function storyFor(id: string): StoryObj {
+ const state = CHECKBOX_BINDING_STATES.find(candidate => candidate.id === id);
+ if (state == null) {
+ throw new Error(`no binding state "${id}" — see Checkbox.a11y.states.ts`);
+ }
+ return {
+ name: `${state.binding} — ${state.id}`,
+ render: () => CHECKBOX_STATE_RENDERS[state.id](),
+ };
+}
+
+const meta: Meta = {
+ title: 'a11y/Checkbox pattern',
+ tags: ['no-visual'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Binding states for the shared checkbox-pattern accessibility contract.',
+ },
+ },
+ },
+};
+
+export default meta;
+
+export const InputUnchecked = storyFor('input-unchecked');
+export const InputChecked = storyFor('input-checked');
+export const InputMixed = storyFor('input-mixed');
+export const InputDescribed = storyFor('input-described');
+export const InputHiddenLabel = storyFor('input-hidden-label');
+export const InputDisabled = storyFor('input-disabled');
+export const InputDisabledWithMessage = storyFor('input-disabled-with-message');
+export const InputLoading = storyFor('input-loading');
+export const InputReadOnly = storyFor('input-read-only');
+export const InputHandlerlessReadOnly = storyFor('input-handlerless-read-only');
+export const InputRequired = storyFor('input-required');
+export const InputInheritedRequiredValid = storyFor(
+ 'input-inherited-required-valid',
+);
+export const InputInvalid = storyFor('input-invalid');
+export const InputWarning = storyFor('input-warning');
+export const InputSuccess = storyFor('input-success');
+
+export const ListItemUnchecked = storyFor('list-item-unchecked');
+export const ListItemChecked = storyFor('list-item-checked');
+export const ListItemMixed = storyFor('list-item-mixed');
+export const ListItemDescribed = storyFor('list-item-described');
+export const ListItemRichLabelMissingName = storyFor(
+ 'list-item-rich-label-missing-name',
+);
+export const ListItemDisabled = storyFor('list-item-disabled');
+export const ListItemLoading = storyFor('list-item-loading');
+export const ListItemReadOnly = storyFor('list-item-read-only');
+export const ListItemHandlerlessReadOnly = storyFor(
+ 'list-item-handlerless-read-only',
+);
+export const ListItemGroupDisabledWithMessage = storyFor(
+ 'list-item-group-disabled-with-message',
+);
+
+export const MenuItemUnchecked = storyFor('menu-item-unchecked');
+export const MenuItemChecked = storyFor('menu-item-checked');
+export const MenuItemDescribed = storyFor('menu-item-described');
+export const MenuItemHandlerlessInert = storyFor('menu-item-handlerless-inert');
+export const MenuItemDisabled = storyFor('menu-item-disabled');
+
+export const CardUnchecked = storyFor('card-unchecked');
+export const CardChecked = storyFor('card-checked');
+export const CardDisabled = storyFor('card-disabled');
diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.md
index f53ed43686..16d7c5d6d6 100644
--- a/internal/a11y-spec/README.md
+++ b/internal/a11y-spec/README.md
@@ -39,19 +39,18 @@ src/
├── spoken.ts how a visible label is compared against a computed name
├── storybook.ts a static server over a built Storybook, for the browser lane
└── patterns/
- ├── switch.ts the switch pattern
- ├── switch.fixtures.ts conforming + deliberately violating fixtures
- ├── switch.jsdom.test.ts the contract's own proof, DOM layer
- ├── switch.chromium.spec.ts the same proof in a real engine
- └── button.* the button pattern, same four files
+ ├── checkbox.* the checkbox pattern, same four files
+ ├── switch.* the switch pattern, same four files
+ └── button.* the button pattern, same four files
```
## The patterns
-| Pattern | Adopted from | Bound by |
-| -------- | -------------------------------------------------------------- | ------------------------------------------------------------------------ |
-| `switch` | [APG switch](https://www.w3.org/WAI/ARIA/apg/patterns/switch/) | Switch |
-| `button` | [APG button](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | Button, IconButton, ClickableCard, SideNavCollapseButton, ChatSendButton |
+| Pattern | Adopted from | Bound by |
+| ---------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------- |
+| `checkbox` | [APG checkbox](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/) | CheckboxInput, CheckboxListItem, DropdownMenuCheckboxItem, SelectableCard |
+| `switch` | [APG switch](https://www.w3.org/WAI/ARIA/apg/patterns/switch/) | Switch |
+| `button` | [APG button](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | Button, IconButton, ClickableCard, SideNavCollapseButton, ChatSendButton |
The button pattern covers the ordinary command button. A toggle button carries
`aria-pressed` and is its own pattern; anything that adopts link semantics — an
@@ -157,11 +156,16 @@ and styling stay in the component's own suite (AST-021 FR5).
## Known failures
A known failure names one expectation, one binding, one state, one evidence
-layer, the user impact, a public issue, and why the migration is not the place
-to fix it. It still runs, it still fails, and it is reported as debt. A
-different message, another state, or a wider failure fails the build anyway, and
-an expectation that starts passing is reported as an unexpected pass so the
-stale record is deleted (AST-021 FR8–FR10).
+layer, the exact standards reference, the user impact, a public issue, and why
+the migration is not the place to fix it. It still runs, it still fails, and is
+reported as debt. The record matches the complete failure message, not a
+substring; a different message, another state, or a wider failure remains a
+`fail` rather than being absorbed by the record. Required failures gate;
+advisory failures remain report-only under AST-020 FR9. A full binding sweep
+also requires every record to match exactly one executed result, so deleted
+states and renamed expectations cannot orphan debt. An expectation that starts
+passing is reported as an unexpected pass so that exact stale record is deleted;
+its issue closes only when no remaining records refer to it (AST-021 FR8–FR10).
## Running
diff --git a/internal/a11y-spec/src/harness/chromium.ts b/internal/a11y-spec/src/harness/chromium.ts
index 32ffde3e6f..d2bd176628 100644
--- a/internal/a11y-spec/src/harness/chromium.ts
+++ b/internal/a11y-spec/src/harness/chromium.ts
@@ -2,8 +2,9 @@
/**
* @file chromium.ts
- * @input Uses a Playwright `Page` and a `Locator` for the subject, and the
- * Chrome DevTools Protocol accessibility domain behind them
+ * @input Uses a Playwright `Page`, the semantic subject `Locator`, optional
+ * binding-owned pointer-target and visible-label `Locator`s, and the Chrome
+ * DevTools Protocol accessibility domain behind them
* @output `createChromiumHarness` — a harness that observes the DOM,
* accessibility-tree, and real-browser layers of a page rendered by a real
* shipping engine — plus `holdMotionStill`, the page setup its specs share.
@@ -209,6 +210,10 @@ export interface ChromiumHarnessOptions {
* expectation under test.
*/
readonly subject: Locator;
+ /** The surface that receives pointer input when it differs from the semantic node. */
+ readonly pointerTarget?: Locator;
+ /** A binding-owned visible label when it is not the subject's DOM label. */
+ readonly visibleLabel?: Locator;
/** A CDP session on `page`, reused across expectations. */
readonly cdp: CDPSession;
}
@@ -216,7 +221,8 @@ export interface ChromiumHarnessOptions {
export function createChromiumHarness(
options: ChromiumHarnessOptions,
): Harness {
- const {page, subject: locator, cdp} = options;
+ const {page, subject: locator, pointerTarget, cdp, visibleLabel} = options;
+ const pointerLocator = pointerTarget ?? locator;
const subject: Subject = {
attribute: name => locator.getAttribute(name),
@@ -236,163 +242,202 @@ export function createChromiumHarness(
attribute,
),
computed: () => computedNode(cdp, locator),
- visibleLabelText: () =>
- locator.evaluate(element => {
- // Whether a person can actually read this text. Two questions, because
- // no single API answers both.
- //
- // `checkVisibility` is the platform's own answer to "is this rendered
- // at all", and it walks ancestors — so a node inside a
- // `visibility: hidden`, `opacity: 0`, or `display: none` wrapper is
- // correctly invisible without this code reimplementing the cascade.
- // What it cannot answer is whether anything of the node LANDS on
- // screen: every sr-only recipe stays "visible" to it. Hence the box.
- /**
- * A wrapper that generates no box of its own and lets its children lay
- * out as if it were not there. Judging it by its own box would be
- * wrong twice over: it has none, and its children may be perfectly
- * readable. Astryx wraps button content in one, so this is not an edge
- * case — it is the common path.
- */
- const isTransparentBox = (node: Element): boolean =>
- getComputedStyle(node).display === 'contents';
+ visibleLabelText: async () => {
+ const explicitLabel =
+ visibleLabel == null ? null : await visibleLabel.elementHandle();
+ try {
+ return await locator.evaluate((element, explicitLabel) => {
+ // Whether a person can actually read this text. Two questions, because
+ // no single API answers both.
+ //
+ // `checkVisibility` is the platform's own answer to "is this rendered
+ // at all", and it walks ancestors — so a node inside a
+ // `visibility: hidden`, `opacity: 0`, or `display: none` wrapper is
+ // correctly invisible without this code reimplementing the cascade.
+ // What it cannot answer is whether anything of the node LANDS on
+ // screen: every sr-only recipe stays "visible" to it. Hence the box.
+ /**
+ * A wrapper that generates no box of its own and lets its children lay
+ * out as if it were not there. Judging it by its own box would be
+ * wrong twice over: it has none, and its children may be perfectly
+ * readable. Astryx wraps button content in one, so this is not an edge
+ * case — it is the common path.
+ */
+ const isTransparentBox = (node: Element): boolean =>
+ getComputedStyle(node).display === 'contents';
- const rendered = (node: Element): boolean => {
- if (isTransparentBox(node)) {
- // Nothing to judge here; each child is judged on its own.
- return true;
- }
- if (
- !node.checkVisibility({
- visibilityProperty: true,
- opacityProperty: true,
- contentVisibilityAuto: true,
- })
- ) {
- return false;
- }
- const box = node.getBoundingClientRect();
- // The sr-only recipe: clipped to a 1px box, still in the tree.
- return box.width > 1 && box.height > 1;
- };
+ const rendered = (node: Element): boolean => {
+ if (isTransparentBox(node)) {
+ // Nothing to judge here; each child is judged on its own.
+ return true;
+ }
+ if (
+ !node.checkVisibility({
+ visibilityProperty: true,
+ opacityProperty: true,
+ contentVisibilityAuto: true,
+ })
+ ) {
+ return false;
+ }
+ const box = node.getBoundingClientRect();
+ // The sr-only recipe: clipped to a 1px box, still in the tree.
+ return box.width > 1 && box.height > 1;
+ };
- /**
- * Whether text sitting directly in this node can be read.
- *
- * Separate from `rendered` because `color` inherits but is overridable:
- * a transparent wrapper whose child re-colours its own text is showing
- * that child's words, and judging the wrapper would erase them. So this
- * asks only about the node the text is actually in.
- *
- * Astryx dims a button's label with `color: transparent` while it waits
- * on an action, so this is a real case, not a hypothetical one.
- */
- const textIsReadable = (node: Element): boolean =>
- !/^rgba\(.*,\s*0\)$/.test(getComputedStyle(node).color);
+ /**
+ * Whether text sitting directly in this node can be read.
+ *
+ * Separate from `rendered` because `color` inherits but is overridable:
+ * a transparent wrapper whose child re-colours its own text is showing
+ * that child's words, and judging the wrapper would erase them. So this
+ * asks only about the node the text is actually in.
+ *
+ * Astryx dims a button's label with `color: transparent` while it waits
+ * on an action, so this is a real case, not a hypothetical one.
+ */
+ const textIsReadable = (node: Element): boolean =>
+ !/^rgba\(.*,\s*0\)$/.test(getComputedStyle(node).color);
- /**
- * Whether the label element as a whole paints anywhere.
- *
- * Sampling catches the case the box cannot: a FULL-SIZE element clipped
- * away entirely (`clip-path: inset(100%)`), which keeps its box and
- * stays "visible" to the platform. If a point over it resolves to the
- * element, to something inside it, or to something covering it, it
- * paints there; if every sample resolves to one of its own ancestors,
- * nothing of it paints.
- *
- * Applied only to the element being measured, never to its descendants:
- * a span inside a button legitimately hit-tests to the button, and
- * treating that as hidden would erase every nested label.
- *
- * Occlusion is deliberately not hiding: a label under an overlay is
- * still a label a person can read when the overlay moves.
- */
- const paints = (node: Element): boolean => {
- if (!rendered(node)) {
- return false;
- }
- if (isTransparentBox(node)) {
- // No box to sample; whether anything shows is up to the children.
- return true;
- }
- const box = node.getBoundingClientRect();
- const samples: ReadonlyArray<readonly [number, number]> = [
- [box.x + box.width / 2, box.y + box.height / 2],
- [box.x + 1, box.y + box.height / 2],
- [box.right - 1, box.y + box.height / 2],
- ];
- return samples.some(([x, y]) => {
- const at = node.ownerDocument.elementFromPoint(x, y);
- if (at == null) {
- // Outside the viewport, so nothing is there to read.
+ /**
+ * Whether the label element as a whole paints anywhere.
+ *
+ * Sampling catches the case the box cannot: a FULL-SIZE element clipped
+ * away entirely (`clip-path: inset(100%)`), which keeps its box and
+ * stays "visible" to the platform. If a point over it resolves to the
+ * element, to something inside it, or to something covering it, it
+ * paints there; if every sample resolves to one of its own ancestors,
+ * nothing of it paints.
+ *
+ * Applied only to the element being measured, never to its descendants:
+ * a span inside a button legitimately hit-tests to the button, and
+ * treating that as hidden would erase every nested label.
+ *
+ * Occlusion is deliberately not hiding: a label under an overlay is
+ * still a label a person can read when the overlay moves.
+ */
+ const paints = (node: Element): boolean => {
+ if (!rendered(node)) {
return false;
}
- return at === node || node.contains(at) || !at.contains(node);
- });
- };
+ if (isTransparentBox(node)) {
+ // No box to sample; whether anything shows is up to the children.
+ return true;
+ }
+ const box = node.getBoundingClientRect();
+ const inlineStyle = (node as HTMLElement).style;
+ const pointerTransparent =
+ getComputedStyle(node).pointerEvents === 'none';
+ const originalPointerEvents =
+ inlineStyle.getPropertyValue('pointer-events');
+ const originalPriority =
+ inlineStyle.getPropertyPriority('pointer-events');
+ if (pointerTransparent) {
+ // Hit testing normally skips pointer-transparent labels even though
+ // they paint. Temporarily make only this node targetable so the
+ // same paint sampling still distinguishes visible text from a
+ // fully clipped box.
+ inlineStyle.setProperty('pointer-events', 'auto', 'important');
+ }
+ try {
+ const samples: ReadonlyArray<readonly [number, number]> = [
+ [box.x + box.width / 2, box.y + box.height / 2],
+ [box.x + 1, box.y + box.height / 2],
+ [box.right - 1, box.y + box.height / 2],
+ ];
+ return samples.some(([x, y]) => {
+ const at = node.ownerDocument.elementFromPoint(x, y);
+ if (at == null) {
+ // Outside the viewport, so nothing is there to read.
+ return false;
+ }
+ return at === node || node.contains(at) || !at.contains(node);
+ });
+ } finally {
+ if (pointerTransparent) {
+ if (originalPointerEvents === '') {
+ inlineStyle.removeProperty('pointer-events');
+ } else {
+ inlineStyle.setProperty(
+ 'pointer-events',
+ originalPointerEvents,
+ originalPriority,
+ );
+ }
+ }
+ }
+ };
- // The text a person can actually READ inside this node.
- //
- // Not `textContent`: a control commonly carries a visually-hidden live
- // region or an sr-only span inside it, and counting that text would
- // report words nobody sees — which then reads as a label mismatch
- // against a name that (correctly) does not contain them. So the walk
- // descends and drops any subtree that is not rendered.
- const visibleTextOf = (node: Element): string => {
- let text = '';
- for (const child of node.childNodes) {
- if (child.nodeType === Node.TEXT_NODE) {
- if (textIsReadable(node)) {
- text += child.nodeValue ?? '';
+ // The text a person can actually READ inside this node.
+ //
+ // Not `textContent`: a control commonly carries a visually-hidden live
+ // region or an sr-only span inside it, and counting that text would
+ // report words nobody sees — which then reads as a label mismatch
+ // against a name that (correctly) does not contain them. So the walk
+ // descends and drops any subtree that is not rendered.
+ const visibleTextOf = (node: Element): string => {
+ let text = '';
+ for (const child of node.childNodes) {
+ if (child.nodeType === Node.TEXT_NODE) {
+ if (textIsReadable(node)) {
+ text += child.nodeValue ?? '';
+ }
+ } else if (
+ child.nodeType === Node.ELEMENT_NODE &&
+ rendered(child as Element)
+ ) {
+ text += ` ${visibleTextOf(child as Element)} `;
}
- } else if (
- child.nodeType === Node.ELEMENT_NODE &&
- rendered(child as Element)
- ) {
- text += ` ${visibleTextOf(child as Element)} `;
}
+ return text.replace(/\s+/g, ' ').trim();
+ };
+ const textOf = (node: Element): string | null => {
+ if (!paints(node)) {
+ return null;
+ }
+ const text = visibleTextOf(node);
+ return text === '' ? null : text;
+ };
+
+ if (explicitLabel != null) {
+ return textOf(explicitLabel);
}
- return text.replace(/\s+/g, ' ').trim();
- };
- const textOf = (node: Element): string | null => {
- if (!paints(node)) {
- return null;
- }
- const text = visibleTextOf(node);
- return text === '' ? null : text;
- };
- // The platform's own labelling order, not any design system's.
- const labelledBy = element.getAttribute('aria-labelledby');
- if (labelledBy != null && labelledBy.trim() !== '') {
- const parts = labelledBy
- .split(/\s+/)
- .filter(Boolean)
- .map(id => element.ownerDocument.getElementById(id))
- .flatMap(target => (target == null ? [] : [textOf(target)]))
- .filter((text): text is string => text != null);
- return parts.length === 0 ? null : parts.join(' ');
- }
- const id = element.getAttribute('id');
- const associated =
- id == null || id === ''
- ? null
- : element.ownerDocument.querySelector(
- // An id is author-supplied and need not be a bare identifier.
- `label[for="${CSS.escape(id)}"]`,
- );
- const wrapping = element.closest('label');
- for (const label of [associated, wrapping]) {
- if (label != null) {
- const text = textOf(label);
- if (text != null) {
- return text;
+ // The platform's own labelling order, not any design system's.
+ const labelledBy = element.getAttribute('aria-labelledby');
+ if (labelledBy != null && labelledBy.trim() !== '') {
+ const parts = labelledBy
+ .split(/\s+/)
+ .filter(Boolean)
+ .map(id => element.ownerDocument.getElementById(id))
+ .flatMap(target => (target == null ? [] : [textOf(target)]))
+ .filter((text): text is string => text != null);
+ return parts.length === 0 ? null : parts.join(' ');
+ }
+ const id = element.getAttribute('id');
+ const associated =
+ id == null || id === ''
+ ? null
+ : element.ownerDocument.querySelector(
+ // An id is author-supplied and need not be a bare identifier.
+ `label[for="${CSS.escape(id)}"]`,
+ );
+ const wrapping = element.closest('label');
+ for (const label of [associated, wrapping]) {
+ if (label != null) {
+ const text = textOf(label);
+ if (text != null) {
+ return text;
+ }
}
}
- }
- // A control that labels itself, e.g. a div with role=switch.
- return textOf(element);
- }),
+ // A control that labels itself, e.g. a div with role=switch.
+ return textOf(element);
+ }, explicitLabel);
+ } finally {
+ await explicitLabel?.dispose();
+ }
+ },
isFocused: () =>
locator.evaluate(
element => element.ownerDocument.activeElement === element,
@@ -412,7 +457,7 @@ export function createChromiumHarness(
// a control the browser calls unavailable what it does when clicked
// anyway.
try {
- await locator.click({
+ await pointerLocator.click({
force: options?.ignoreAvailability === true,
// Bounded, and short. A control a pointer cannot reach — one covered
// by something else, or clipped to nothing — otherwise sits here
@@ -431,7 +476,7 @@ export function createChromiumHarness(
}
},
abortedPress: async () => {
- const box = await locator.boundingBox();
+ const box = await pointerLocator.boundingBox();
if (box == null) {
throw new Error('the subject has no box to press on');
}
@@ -439,7 +484,7 @@ export function createChromiumHarness(
// releasing it elsewhere does. Without this, a control a pointer cannot
// reach reports a serene pass for pointer cancellation — the exact
// vacuous green the evidence-layer rules exist to prevent.
- const reachable = await locator.evaluate(element => {
+ const reachable = await pointerLocator.evaluate(element => {
const rect = element.getBoundingClientRect();
const at = element.ownerDocument.elementFromPoint(
rect.x + rect.width / 2,
diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.ts
index b1cff5d90f..b29b227669 100644
--- a/internal/a11y-spec/src/index.ts
+++ b/internal/a11y-spec/src/index.ts
@@ -52,6 +52,7 @@ export {
export {
MissingBindingCapability,
runBinding,
+ unmatchedKnownFailures,
type BindingResult,
type ExpectationResult,
type KnownFailure,
@@ -71,6 +72,8 @@ export {
export {createJsdomHarness, type JsdomHarnessOptions} from './harness/jsdom';
+export {CHECKBOX_PATTERN, type CheckboxStateFacts} from './patterns/checkbox';
+
export {SWITCH_PATTERN, type SwitchStateFacts} from './patterns/switch';
export {saysInOrder, spokenWords} from './spoken';
diff --git a/internal/a11y-spec/src/patterns/checkbox.chromium.spec.ts b/internal/a11y-spec/src/patterns/checkbox.chromium.spec.ts
new file mode 100644
index 0000000000..225a5fa082
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/checkbox.chromium.spec.ts
@@ -0,0 +1,139 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file checkbox.chromium.spec.ts
+ * @input Uses @playwright/test, ./checkbox (the contract), ./checkbox.fixtures,
+ * ../harness/chromium, ../run
+ * @output The contract's own proof in a real engine: every expectation passes
+ * against a conforming fixture and fails against each fixture that removes
+ * its outcome.
+ * @position Self-test, the Chromium half of ./checkbox.jsdom.test.ts. Both halves
+ * read the same fixtures, so the same positive and negative proof runs at
+ * every layer that can see it.
+ *
+ * The fixtures are hand-written HTML with no Astryx in them, because what is
+ * under test here is the CONTRACT — whether an expectation can actually fail.
+ * A component binding proves the different claim that the component delivers
+ * the outcome.
+ *
+ * SYNC: Fixtures and mutations live in ./checkbox.fixtures.ts, shared with the
+ * jsdom half.
+ */
+
+import {expect, test, type CDPSession, type Page} from '@playwright/test';
+import {describeExpectation, requiredLayers} from '../contract';
+import {
+ CHROMIUM_OBSERVES,
+ createChromiumHarness,
+ holdMotionStill,
+} from '../harness/chromium';
+import {runBinding, type ExpectationResult} from '../run';
+import {CHECKBOX_PATTERN} from './checkbox';
+import {
+ CONFORMING_FIXTURES,
+ SUBJECT_SELECTOR,
+ CHECKBOX_MUTATIONS,
+ expectedMutationFailure,
+ fixture,
+ type CheckboxFixture,
+} from './checkbox.fixtures';
+
+/**
+ * A tab stop after the checkbox, so "focus can leave it" has somewhere to go.
+ * Without it the browser moves focus to its own chrome and the fixture could
+ * not tell an escape from a trap.
+ */
+function fixturePage(html: string): string {
+ return `<!doctype html><html lang="en"><body>${html}<button type="button" id="after">after</button></body></html>`;
+}
+
+async function results(
+ page: Page,
+ cdp: CDPSession,
+ target: CheckboxFixture,
+ only?: readonly string[],
+): Promise<readonly ExpectationResult[]> {
+ const run = await runBinding({
+ contract: CHECKBOX_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ only,
+ mount: async () => {
+ await page.setContent(fixturePage(target.html));
+ await holdMotionStill(page);
+ return createChromiumHarness({
+ page,
+ subject: page.locator(SUBJECT_SELECTOR),
+ cdp,
+ });
+ },
+ });
+ return run.results;
+}
+
+test.describe('checkbox contract — conforming fixtures', () => {
+ for (const id of CONFORMING_FIXTURES) {
+ test(`${id}: every applicable expectation passes`, async ({page}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const observed = await results(page, cdp, fixture(id));
+ const notPassing = observed.filter(
+ result =>
+ result.status !== 'pass' && result.status !== 'not-applicable',
+ );
+ expect(
+ notPassing.map(
+ result => `${result.expectation}: ${result.detail ?? ''}`,
+ ),
+ ).toEqual([]);
+ });
+ }
+});
+
+test('every expectation passes against at least one conforming fixture', async ({
+ page,
+}) => {
+ test.setTimeout(2 * 60 * 1000);
+ const cdp = await page.context().newCDPSession(page);
+ const withoutPass: string[] = [];
+ for (const expectation of CHECKBOX_PATTERN.expectations) {
+ let passed = false;
+ for (const id of CONFORMING_FIXTURES) {
+ const [result] = await results(page, cdp, fixture(id), [expectation.id]);
+ if (result?.status === 'pass') {
+ passed = true;
+ break;
+ }
+ }
+ if (!passed) {
+ withoutPass.push(expectation.id);
+ }
+ }
+ expect(withoutPass).toEqual([]);
+});
+
+test.describe('checkbox contract — deliberately violating fixtures', () => {
+ for (const expectation of CHECKBOX_PATTERN.expectations) {
+ if (
+ !requiredLayers(expectation).every(layer =>
+ CHROMIUM_OBSERVES.includes(layer),
+ )
+ ) {
+ continue;
+ }
+ for (const fixtureId of CHECKBOX_MUTATIONS[expectation.id] ?? []) {
+ test(`${describeExpectation(expectation)} — fails against ${fixtureId}`, async ({
+ page,
+ }) => {
+ const cdp = await page.context().newCDPSession(page);
+ const [result] = await results(page, cdp, fixture(fixtureId), [
+ expectation.id,
+ ]);
+ expect(result?.status, result?.detail ?? 'no result').toBe('fail');
+ expect(result?.detail ?? '').toBe(
+ expectedMutationFailure(expectation.id, fixtureId),
+ );
+ });
+ }
+ }
+});
diff --git a/internal/a11y-spec/src/patterns/checkbox.fixtures.ts b/internal/a11y-spec/src/patterns/checkbox.fixtures.ts
new file mode 100644
index 0000000000..081bad62e5
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/checkbox.fixtures.ts
@@ -0,0 +1,587 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file checkbox.fixtures.ts
+ * @input Uses ./checkbox (CheckboxStateFacts)
+ * @output CHECKBOX_FIXTURES — hand-written checkboxes, one conforming per state and
+ * one deliberately violating per expectation — and CHECKBOX_MUTATIONS, which
+ * says which fixture each expectation must fail against.
+ * @position The contract's own proof (AST-020 FR11). Used by the jsdom self-test
+ * and by the Chromium self-test, so the same positive and negative fixtures
+ * run at both layers.
+ *
+ * These are plain HTML on purpose. They prove the CONTRACT — that each
+ * expectation passes when the outcome is present and fails when it is removed —
+ * so they must not depend on any Astryx component. A component binding proves
+ * something different: that the component delivers the outcome.
+ *
+ * Each fixture marks its control with `data-a11y-subject`. A binding designates
+ * its subject rather than the contract hunting for one by role, so removing the
+ * role flips exactly the role expectation instead of making every expectation
+ * fail at once (which would prove nothing about any of them).
+ *
+ * SYNC: A new expectation in ./checkbox.ts needs a row in CHECKBOX_MUTATIONS, and
+ * the self-tests fail until it has one.
+ */
+
+import type {CheckboxStateFacts} from './checkbox';
+
+/** The attribute a fixture marks its control with. */
+const SUBJECT_ATTRIBUTE = 'data-a11y-subject';
+
+/** How a lane finds the control a fixture designates. */
+export const SUBJECT_SELECTOR = `[${SUBJECT_ATTRIBUTE}]`;
+
+export interface CheckboxFixture {
+ readonly id: string;
+ /** What this fixture is, in one line, for the test name. */
+ readonly summary: string;
+ /** What the fixture declares itself to be. */
+ readonly facts: CheckboxStateFacts;
+ readonly html: string;
+}
+
+const CONFORMING_FACTS: CheckboxStateFacts = {
+ role: 'checkbox',
+ checked: false,
+ operable: true,
+ focusable: true,
+ disabled: false,
+ description: null,
+ readOnly: false,
+ required: false,
+ invalid: false,
+};
+
+function facts(
+ overrides: Partial<CheckboxStateFacts> = {},
+): CheckboxStateFacts {
+ return {...CONFORMING_FACTS, ...overrides};
+}
+
+/** A native checkbox promoted to a checkbox — the APG's own HTML-checkbox example. */
+function nativeCheckbox(attributes = ''): string {
+ return (
+ '<label for="fx">Notifications</label>' +
+ `<input id="fx" ${SUBJECT_ATTRIBUTE} type="checkbox" role="checkbox"${attributes ? ` ${attributes}` : ''}>`
+ );
+}
+
+/** A div-based checkbox, so a fixture can withhold behaviour a native input has. */
+function divCheckbox(attributes: string, body = 'Notifications'): string {
+ return `<div ${SUBJECT_ATTRIBUTE} role="checkbox" ${attributes}>${body}</div>`;
+}
+
+const TOGGLE_ON_CLICK = `onclick="this.setAttribute('aria-checked', this.getAttribute('aria-checked') === 'true' ? 'false' : 'true')"`;
+const TOGGLE_ON_SPACE = `onkeydown="if (event.key === ' ') { event.preventDefault(); this.setAttribute('aria-checked', this.getAttribute('aria-checked') === 'true' ? 'false' : 'true'); }"`;
+/** Changes on the way down, where a press can no longer be taken back. */
+const TOGGLE_ON_POINTER_DOWN = `onpointerdown="this.setAttribute('aria-checked', this.getAttribute('aria-checked') === 'true' ? 'false' : 'true')"`;
+
+export const CHECKBOX_FIXTURES: readonly CheckboxFixture[] = [
+ // ---- conforming, one per representative state ---------------------------
+ {
+ id: 'conforming-menuitem',
+ summary:
+ 'a menu checkbox item whose composite owns keyboard navigation and focus',
+ facts: facts({
+ role: 'menuitemcheckbox',
+ focusable: false,
+ }),
+ html: `<div ${SUBJECT_ATTRIBUTE} role="menuitemcheckbox" tabindex="-1" aria-checked="false" ${TOGGLE_ON_CLICK}>Notifications</div>`,
+ },
+ {
+ id: 'conforming-off',
+ summary: 'a labelled native checkbox, unchecked',
+ facts: facts(),
+ html: nativeCheckbox(),
+ },
+ {
+ id: 'conforming-on',
+ summary: 'the same checkbox, on',
+ facts: facts({checked: true}),
+ html: nativeCheckbox('checked'),
+ },
+ {
+ id: 'conforming-mixed',
+ summary:
+ 'a tri-state checkbox, partially checked, that resolves to checked and then unchecked',
+ facts: facts({checked: 'mixed'}),
+ html: divCheckbox(
+ `tabindex="0" aria-checked="mixed" onclick="const state = this.getAttribute('aria-checked'); this.setAttribute('aria-checked', state === 'mixed' ? 'true' : state === 'true' ? 'false' : 'true')" onkeydown="if (event.key === ' ') { event.preventDefault(); this.click(); }"`,
+ ),
+ },
+ {
+ id: 'conforming-described',
+ summary: 'a checkbox with supporting text attached as its description',
+ facts: facts({description: 'Sends a notification for every mention.'}),
+ html:
+ '<p id="hint">Sends a notification for every mention.</p>' +
+ nativeCheckbox('aria-describedby="hint"'),
+ },
+ {
+ id: 'conforming-label-hidden',
+ summary:
+ 'a checkbox named for assistive technology with nothing rendered visibly',
+ facts: facts(),
+ html: `<input ${SUBJECT_ATTRIBUTE} type="checkbox" role="checkbox" aria-label="Notifications">`,
+ },
+ {
+ id: 'conforming-label-sr-only',
+ summary:
+ 'a checkbox whose label is present but clipped away by the sr-only recipe',
+ facts: facts(),
+ html:
+ '<label for="fx" style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap">Notifications</label>' +
+ `<input id="fx" ${SUBJECT_ATTRIBUTE} type="checkbox" role="checkbox" aria-label="Notifications">`,
+ },
+ {
+ id: 'conforming-label-decoratively-clipped',
+ summary:
+ 'a readable label that happens to carry a decorative clip-path — visible, and it must not read as hidden',
+ facts: facts(),
+ html:
+ '<label for="fx" style="clip-path:circle(60%)">Notifications</label>' +
+ `<input id="fx" ${SUBJECT_ATTRIBUTE} type="checkbox" role="checkbox">`,
+ },
+ {
+ id: 'conforming-label-pointer-transparent',
+ summary:
+ 'a readable label that ignores pointer input so its containing row can receive the click',
+ facts: facts(),
+ html:
+ '<label for="fx" style="pointer-events:none">Notifications</label>' +
+ `<input id="fx" ${SUBJECT_ATTRIBUTE} type="checkbox" role="checkbox">`,
+ },
+ {
+ id: 'conforming-label-pointer-transparent-and-clipped',
+ summary:
+ 'a fully clipped label that also ignores pointer input, so it remains invisible',
+ facts: facts(),
+ html:
+ '<label for="fx" style="pointer-events:none;clip-path:inset(100%)">Notifications</label>' +
+ `<input id="fx" ${SUBJECT_ATTRIBUTE} type="checkbox" role="checkbox" aria-label="Notification setting">`,
+ },
+ {
+ id: 'conforming-label-hidden-by-ancestor',
+ summary:
+ 'a label inside a hidden wrapper: nothing is readable, and the name comes from aria-label',
+ facts: facts(),
+ html:
+ '<div style="visibility:hidden"><label for="fx">Notifications</label></div>' +
+ `<input id="fx" ${SUBJECT_ATTRIBUTE} type="checkbox" role="checkbox" aria-label="Notifications">`,
+ },
+ {
+ id: 'conforming-disabled',
+ summary: 'a natively disabled checkbox',
+ facts: facts({disabled: true, operable: false, focusable: false}),
+ html: nativeCheckbox('disabled'),
+ },
+ {
+ id: 'conforming-focusable-disabled',
+ summary:
+ 'an unavailable checkbox that stays in the tab sequence and refuses both pointer and keyboard changes',
+ facts: facts({disabled: true, operable: false, focusable: true}),
+ html: nativeCheckbox(
+ `aria-disabled="true" onclick="event.preventDefault()" onkeydown="if (event.key === ' ') { event.preventDefault(); }"`,
+ ),
+ },
+ {
+ id: 'conforming-pending',
+ summary:
+ 'a checkbox that refuses its own change without being disabled — the case where "cannot be changed" and "reported disabled" come apart',
+ facts: facts({operable: false}),
+ html: nativeCheckbox(
+ `onclick="event.preventDefault()" onkeydown="if (event.key === ' ') { event.preventDefault(); }"`,
+ ),
+ },
+ {
+ id: 'conforming-readonly',
+ summary: 'a read-only checkbox that stays focusable and does not change',
+ facts: facts({readOnly: true, operable: false}),
+ html: nativeCheckbox(
+ `aria-readonly="true" onclick="event.preventDefault()" onkeydown="if (event.key === ' ') { event.preventDefault(); }"`,
+ ),
+ },
+ {
+ id: 'conforming-required',
+ summary: 'a required checkbox',
+ facts: facts({required: true, invalid: true}),
+ html: nativeCheckbox('required'),
+ },
+ {
+ id: 'conforming-invalid',
+ summary: 'a checkbox reported as being in error',
+ facts: facts({invalid: true}),
+ html: nativeCheckbox('aria-invalid="true"'),
+ },
+
+ // ---- one deliberate violation per expectation ---------------------------
+ {
+ id: 'violating-unnamed',
+ summary: 'a checkbox with no label at all',
+ facts: facts(),
+ html: `<input ${SUBJECT_ATTRIBUTE} type="checkbox" role="checkbox">`,
+ },
+ {
+ id: 'violating-name-mismatch',
+ summary: 'a checkbox whose aria-label replaces the visible label',
+ facts: facts(),
+ html: nativeCheckbox('aria-label="Toggle"'),
+ },
+ {
+ id: 'violating-down-event-toggle',
+ summary:
+ 'a checkbox that changes on the way down, so a slip cannot be taken back',
+ facts: facts(),
+ html: divCheckbox(
+ `tabindex="0" aria-checked="false" ${TOGGLE_ON_POINTER_DOWN} ${TOGGLE_ON_SPACE}`,
+ ),
+ },
+ {
+ id: 'violating-focus-moves-on-change',
+ summary:
+ 'a checkbox that throws focus somewhere else the moment it is changed',
+ facts: facts(),
+ html: nativeCheckbox(`onchange="document.getElementById('after').focus()"`),
+ },
+ {
+ id: 'violating-checkbox-role',
+ summary: 'a switch that exposes the wrong widget role',
+ facts: facts(),
+ html:
+ '<label for="fx">Notifications</label>' +
+ `<input id="fx" ${SUBJECT_ATTRIBUTE} type="checkbox" role="switch">`,
+ },
+ {
+ id: 'violating-generic-element',
+ summary: 'a plain element with neither the role nor any state',
+ facts: facts({operable: false, focusable: false}),
+ html: `<div ${SUBJECT_ATTRIBUTE} tabindex="0">Notifications</div>`,
+ },
+ {
+ id: 'violating-state-mismatch',
+ summary: 'a checkbox rendered on while reporting itself off',
+ facts: facts({checked: true, operable: false, focusable: false}),
+ html: divCheckbox('tabindex="0" aria-checked="false"'),
+ },
+ {
+ id: 'violating-mixed-state-mismatch',
+ summary: 'a partially checked checkbox reported as unchecked',
+ facts: facts({checked: 'mixed', operable: false, focusable: false}),
+ html: divCheckbox('tabindex="0" aria-checked="false"'),
+ },
+ {
+ id: 'violating-dangling-description',
+ summary: 'a checkbox described by an id that resolves to nothing',
+ facts: facts({description: 'Sends a notification for every mention.'}),
+ html: nativeCheckbox('aria-describedby="hint"'),
+ },
+ {
+ id: 'violating-empty-description',
+ summary: 'a checkbox described by an element that renders no text',
+ facts: facts({description: 'Sends a notification for every mention.'}),
+ html: '<p id="hint"></p>' + nativeCheckbox('aria-describedby="hint"'),
+ },
+ {
+ id: 'violating-wrong-description',
+ summary: 'a checkbox pointing at unrelated nonempty text',
+ facts: facts({description: 'Sends a notification for every mention.'}),
+ html:
+ '<p id="hint">This text describes a different control.</p>' +
+ nativeCheckbox('aria-describedby="hint"'),
+ },
+ {
+ id: 'violating-inert',
+ summary: 'a checkbox that never changes state',
+ // Same markup as violating-state-mismatch, different declaration: there,
+ // the binding says the checkbox renders ON and the markup says off, which is
+ // an exposure failure. Here it says off and means off, so the failure is
+ // that pressing it does nothing. One inert control, two separate outcomes.
+ facts: facts(),
+ html: divCheckbox('tabindex="0" aria-checked="false"'),
+ },
+ {
+ id: 'violating-wrong-start-first-noop',
+ summary:
+ 'a checkbox rendered checked despite an unchecked declaration, whose first activation does nothing and second activation unchecks it',
+ facts: facts(),
+ html: divCheckbox(
+ `tabindex="0" aria-checked="true" onclick="const count = Number(this.dataset.activations || '0') + 1; this.dataset.activations = String(count); if (count === 2) { this.setAttribute('aria-checked', 'false'); }" onkeydown="if (event.key === ' ') { event.preventDefault(); this.click(); }"`,
+ ),
+ },
+ {
+ id: 'violating-one-way',
+ summary: 'a checkbox that turns on and cannot be turned back off',
+ facts: facts(),
+ html: divCheckbox(
+ `tabindex="0" aria-checked="false" onclick="this.setAttribute('aria-checked', 'true')" onkeydown="if (event.key === ' ') { event.preventDefault(); this.setAttribute('aria-checked', 'true'); }"`,
+ ),
+ },
+ {
+ id: 'violating-pointer-only',
+ summary: 'a checkbox that answers a pointer but ignores the keyboard',
+ facts: facts(),
+ html: divCheckbox(`tabindex="0" aria-checked="false" ${TOGGLE_ON_CLICK}`),
+ },
+ {
+ id: 'violating-pointer-only-unfocusable',
+ summary:
+ 'an operable checkbox whose facts try to opt out of direct keyboard focus',
+ facts: facts({focusable: false}),
+ html: divCheckbox(`aria-checked="false" ${TOGGLE_ON_CLICK}`),
+ },
+ {
+ id: 'violating-unreachable',
+ summary: 'a checkbox that is not in the tab sequence',
+ facts: facts(),
+ html: divCheckbox(
+ `aria-checked="false" ${TOGGLE_ON_CLICK} ${TOGGLE_ON_SPACE}`,
+ ),
+ },
+ {
+ id: 'violating-declared-unavailable-unreachable',
+ summary:
+ 'an unavailable checkbox whose binding promises focusability but whose native disabled state removes it from the tab sequence',
+ facts: facts({disabled: true, operable: false, focusable: true}),
+ html: nativeCheckbox('disabled'),
+ },
+ {
+ id: 'violating-keyboard-trap',
+ summary: 'a checkbox that swallows the Tab that would leave it',
+ facts: facts(),
+ html: nativeCheckbox(
+ `onkeydown="if (event.key === 'Tab') { event.preventDefault(); }"`,
+ ),
+ },
+ {
+ id: 'violating-disabled-overexposed',
+ summary: 'an available checkbox falsely exposed as disabled',
+ facts: facts({focusable: false, operable: false}),
+ html: nativeCheckbox('disabled'),
+ },
+ {
+ id: 'violating-disabled-unexposed',
+ summary:
+ 'a checkbox that blocks its own change without saying it is disabled',
+ facts: facts({disabled: true, operable: false}),
+ html: nativeCheckbox(`onclick="event.preventDefault()"`),
+ },
+ {
+ id: 'violating-disabled-operable',
+ summary: 'a checkbox marked disabled that still changes state',
+ facts: facts({disabled: true, operable: false}),
+ html: nativeCheckbox('aria-disabled="true"'),
+ },
+ {
+ id: 'violating-disabled-keyboard-operable',
+ summary:
+ 'a checkbox that refuses pointer activation while its unavailable state still changes with Space',
+ facts: facts({disabled: true, operable: false}),
+ html: divCheckbox(
+ `tabindex="0" aria-checked="false" aria-disabled="true" onclick="event.preventDefault()" ${TOGGLE_ON_SPACE}`,
+ ),
+ },
+ {
+ id: 'violating-required-unexposed',
+ summary: 'a checkbox that must be on but never says so',
+ facts: facts({required: true}),
+ html: nativeCheckbox(),
+ },
+ {
+ id: 'violating-readonly-unexposed',
+ summary: 'a read-only checkbox with no read-only declaration',
+ facts: facts({readOnly: true, operable: false}),
+ html: nativeCheckbox(
+ `onclick="event.preventDefault()" onkeydown="if (event.key === ' ') { event.preventDefault(); }"`,
+ ),
+ },
+ {
+ id: 'violating-readonly-overexposed',
+ summary: 'an editable checkbox falsely declared read-only',
+ facts: facts(),
+ html: nativeCheckbox('aria-readonly="true"'),
+ },
+ {
+ id: 'violating-required-overexposed',
+ summary: 'an optional checkbox falsely declared required',
+ facts: facts({checked: true}),
+ html: nativeCheckbox('checked required'),
+ },
+ {
+ id: 'violating-invalid-overexposed',
+ summary: 'a valid checkbox falsely exposed as invalid',
+ facts: facts(),
+ html: nativeCheckbox('aria-invalid="true"'),
+ },
+ {
+ id: 'violating-invalid-unexposed',
+ summary: 'a checkbox in error that never says so',
+ facts: facts({invalid: true}),
+ html: nativeCheckbox(),
+ },
+];
+
+export function fixture(id: string): CheckboxFixture {
+ const found = CHECKBOX_FIXTURES.find(candidate => candidate.id === id);
+ if (found == null) {
+ throw new Error(`unknown checkbox fixture "${id}"`);
+ }
+ return found;
+}
+
+/** The conforming fixtures every expectation must pass against (AST-020 FR11). */
+export const CONFORMING_FIXTURES: readonly string[] = CHECKBOX_FIXTURES.filter(
+ candidate => candidate.id.startsWith('conforming-'),
+).map(candidate => candidate.id);
+
+/**
+ * For each expectation, the fixtures that remove its outcome. Every expectation
+ * needs at least one, and the self-tests fail when one is missing — that is how
+ * "the contract can actually fail" stops being a claim (AST-020 FR11).
+ */
+export const CHECKBOX_MUTATIONS: Readonly<Record<string, readonly string[]>> = {
+ 'checkbox.description.resolvable': [
+ 'violating-dangling-description',
+ 'violating-wrong-description',
+ ],
+ 'checkbox.role.exposed': [
+ 'violating-checkbox-role',
+ 'violating-generic-element',
+ ],
+ 'checkbox.name.exposed': ['violating-unnamed'],
+ 'checkbox.state.exposed': [
+ 'violating-state-mismatch',
+ 'violating-mixed-state-mismatch',
+ 'violating-generic-element',
+ ],
+ 'checkbox.description.exposed': [
+ 'violating-empty-description',
+ 'violating-wrong-description',
+ ],
+ 'checkbox.disabled.exposed': ['violating-disabled-unexposed'],
+ 'checkbox.disabled.not-exposed': ['violating-disabled-overexposed'],
+ 'checkbox.readonly.declared': ['violating-readonly-unexposed'],
+ 'checkbox.readonly.not-declared': ['violating-readonly-overexposed'],
+ 'checkbox.required.declared': ['violating-required-unexposed'],
+ 'checkbox.required.not-declared': ['violating-required-overexposed'],
+ 'checkbox.invalid.exposed': ['violating-invalid-unexposed'],
+ 'checkbox.invalid.not-exposed': ['violating-invalid-overexposed'],
+ 'checkbox.name.matches-visible-label': ['violating-name-mismatch'],
+ 'checkbox.state.survives-an-aborted-press': ['violating-down-event-toggle'],
+ 'checkbox.state.keeps-focus-on-change': [
+ 'violating-focus-moves-on-change',
+ 'violating-inert',
+ 'violating-pointer-only-unfocusable',
+ ],
+ 'checkbox.state.pointer-round-trip': [
+ 'violating-inert',
+ 'violating-wrong-start-first-noop',
+ 'violating-one-way',
+ ],
+ 'checkbox.state.space-round-trip': [
+ 'violating-pointer-only',
+ 'violating-pointer-only-unfocusable',
+ 'violating-wrong-start-first-noop',
+ 'violating-one-way',
+ ],
+ 'checkbox.focus.reachable-and-escapable': [
+ 'violating-unreachable',
+ 'violating-pointer-only-unfocusable',
+ 'violating-keyboard-trap',
+ ],
+ 'checkbox.focus.declared-inoperable-reachable': [
+ 'violating-declared-unavailable-unreachable',
+ ],
+ 'checkbox.state.inoperable': [
+ 'violating-disabled-operable',
+ 'violating-disabled-keyboard-operable',
+ ],
+};
+
+const MUTATION_FAILURES: Readonly<Record<string, string>> = {
+ 'checkbox.description.resolvable:violating-dangling-description':
+ 'aria-describedby points at "hint", which resolves to nothing',
+ 'checkbox.description.resolvable:violating-wrong-description':
+ 'the binding expects the description "Sends a notification for every mention.", but aria-describedby resolves to "This text describes a different control."',
+ 'checkbox.role.exposed:violating-checkbox-role':
+ 'this binding adopts the checkbox role, but the browser reports "switch"',
+ 'checkbox.role.exposed:violating-generic-element':
+ 'this binding adopts the checkbox role, but the browser reports "generic"',
+ 'checkbox.name.exposed:violating-unnamed':
+ 'the browser computes no accessible name for this checkbox, so the accessibility node does not identify the choice',
+ 'checkbox.state.exposed:violating-state-mismatch':
+ 'this state renders checked but the browser reports it as unchecked',
+ 'checkbox.state.exposed:violating-mixed-state-mismatch':
+ 'this state renders partially checked but the browser reports it as unchecked',
+ 'checkbox.state.exposed:violating-generic-element':
+ 'the browser accessibility node exposes no checked state for this checkbox',
+ 'checkbox.description.exposed:violating-empty-description':
+ 'the binding expects the description "Sends a notification for every mention.", but the browser computes no accessible description',
+ 'checkbox.description.exposed:violating-wrong-description':
+ 'the binding expects the description "Sends a notification for every mention.", but the browser computes "This text describes a different control."',
+ 'checkbox.disabled.exposed:violating-disabled-unexposed':
+ 'the binding declares this state unavailable, but the browser reports the checkbox as available, so the user is invited to change something that will not change',
+ 'checkbox.disabled.not-exposed:violating-disabled-overexposed':
+ 'this state is available, but the browser exposes the checkbox as disabled',
+ 'checkbox.readonly.declared:violating-readonly-unexposed':
+ 'this state is read-only, but the checkbox does not declare aria-readonly="true"',
+ 'checkbox.readonly.not-declared:violating-readonly-overexposed':
+ 'this state is editable, but the checkbox declares aria-readonly="true"',
+ 'checkbox.required.declared:violating-required-unexposed':
+ 'this state is required, but the checkbox declares neither the native required attribute nor aria-required="true", so user agents receive no required-state declaration',
+ 'checkbox.required.not-declared:violating-required-overexposed':
+ 'this state is not required, but the checkbox exposes a required declaration',
+ 'checkbox.invalid.exposed:violating-invalid-unexposed':
+ 'this state is in error, but the browser does not report the checkbox as invalid, so the error is only visible to people who can see the message',
+ 'checkbox.invalid.not-exposed:violating-invalid-overexposed':
+ 'this state is not invalid, but the browser exposes the checkbox as invalid',
+ 'checkbox.name.matches-visible-label:violating-name-mismatch':
+ 'the visible label reads "Notifications" but the browser computes the accessible name as "Toggle", so speaking the visible label does not reach this control',
+ 'checkbox.state.survives-an-aborted-press:violating-down-event-toggle':
+ 'pressing the checkbox and releasing away from it still turned it checked: the change happens on the way down, so a press cannot be taken back',
+ 'checkbox.state.keeps-focus-on-change:violating-focus-moves-on-change':
+ 'changing the checkbox to checked moved focus off it, so the user is somewhere else without having asked to be',
+ 'checkbox.state.keeps-focus-on-change:violating-inert':
+ 'pressing Space left the checkbox unchecked, so nothing changed and this expectation has no change to judge',
+ 'checkbox.state.keeps-focus-on-change:violating-pointer-only-unfocusable':
+ 'the checkbox did not take focus, so this state cannot be changed from the keyboard at all',
+ 'checkbox.state.pointer-round-trip:violating-inert':
+ 'clicking the checkbox left the checkbox unchecked: it cannot be changed to checked',
+ 'checkbox.state.pointer-round-trip:violating-wrong-start-first-noop':
+ 'the binding declares unchecked, but the browser starts checked',
+ 'checkbox.state.pointer-round-trip:violating-one-way':
+ 'clicking the checkbox changed the checkbox to checked, but doing it again left it checked instead of returning it to unchecked: the change only goes one way',
+ 'checkbox.state.space-round-trip:violating-pointer-only':
+ 'pressing Space on the focused checkbox left the checkbox unchecked: it cannot be changed to checked',
+ 'checkbox.state.space-round-trip:violating-pointer-only-unfocusable':
+ 'the checkbox did not take focus, so Space never reaches it',
+ 'checkbox.state.space-round-trip:violating-wrong-start-first-noop':
+ 'the binding declares unchecked, but the browser starts checked',
+ 'checkbox.state.space-round-trip:violating-one-way':
+ 'pressing Space on the focused checkbox changed the checkbox to checked, but doing it again left it checked instead of returning it to unchecked: the change only goes one way',
+ 'checkbox.focus.reachable-and-escapable:violating-unreachable':
+ '10 presses of Tab from the start of the document never reached the checkbox, so a keyboard user cannot get to this setting',
+ 'checkbox.focus.reachable-and-escapable:violating-pointer-only-unfocusable':
+ '10 presses of Tab from the start of the document never reached the checkbox, so a keyboard user cannot get to this setting',
+ 'checkbox.focus.reachable-and-escapable:violating-keyboard-trap':
+ 'Tab did not move focus off the checkbox, so a keyboard user is stuck on it',
+ 'checkbox.focus.declared-inoperable-reachable:violating-declared-unavailable-unreachable':
+ '10 presses of Tab from the start of the document never reached the checkbox, so a keyboard user cannot get to this setting',
+ 'checkbox.state.inoperable:violating-disabled-operable':
+ 'the user is not meant to be able to change this state, but clicking the checkbox turned it checked',
+ 'checkbox.state.inoperable:violating-disabled-keyboard-operable':
+ 'the user is not meant to be able to change this state, but pressing Space on the checkbox turned it checked',
+};
+
+export function expectedMutationFailure(
+ expectation: string,
+ target: string,
+): string {
+ const detail = MUTATION_FAILURES[`${expectation}:${target}`];
+ if (detail == null) {
+ throw new Error(
+ `no expected failure detail for ${expectation} against ${target}`,
+ );
+ }
+ return detail;
+}
diff --git a/internal/a11y-spec/src/patterns/checkbox.jsdom.test.ts b/internal/a11y-spec/src/patterns/checkbox.jsdom.test.ts
new file mode 100644
index 0000000000..e04f8a9750
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/checkbox.jsdom.test.ts
@@ -0,0 +1,170 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file checkbox.jsdom.test.ts
+ * @input Uses ./checkbox (the contract), ./checkbox.fixtures (conforming and
+ * violating fixtures), ../harness/jsdom, ../run
+ * @output The contract's own proof at the DOM layer: every expectation passes
+ * against a conforming fixture, fails against a fixture that removes its
+ * outcome, and reports `unrun` when this harness cannot observe its layer.
+ * @position Self-test. Proves the CONTRACT, not any component — the fixtures are
+ * hand-written HTML with no Astryx in them.
+ *
+ * `docs/specs/AST-020/spec.md` FR11: each expectation must pass against a
+ * minimally conforming fixture and fail when its required outcome is
+ * deliberately removed, and the suite must tell a real violation apart from an
+ * unsupported harness operation.
+ *
+ * SYNC: The Chromium half of this proof is ./checkbox.chromium.spec.ts. Both read
+ * the same fixtures, so a new fixture is covered at whichever layers can see it.
+ */
+
+import {afterEach, describe, expect, it} from 'vitest';
+import {
+ citeSource,
+ describeExpectation,
+ requiredLayers,
+ unansweredDimensions,
+} from '../contract';
+import {JSDOM_OBSERVES, createJsdomHarness} from '../harness/jsdom';
+import {runBinding, type ExpectationResult} from '../run';
+import {CHECKBOX_PATTERN} from './checkbox';
+import {
+ CONFORMING_FIXTURES,
+ SUBJECT_SELECTOR,
+ CHECKBOX_MUTATIONS,
+ expectedMutationFailure,
+ fixture,
+ type CheckboxFixture,
+} from './checkbox.fixtures';
+
+const observableHere = CHECKBOX_PATTERN.expectations.filter(expectation =>
+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),
+);
+
+afterEach(() => {
+ document.body.replaceChildren();
+});
+
+async function resultsFor(target: CheckboxFixture) {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const result = await runBinding({
+ contract: CHECKBOX_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ mount: async () => {
+ container.innerHTML = target.html;
+ const subject = container.querySelector(SUBJECT_SELECTOR);
+ if (subject == null) {
+ throw new Error(`fixture "${target.id}" marks no subject element`);
+ }
+ return createJsdomHarness({subject});
+ },
+ unmount: () => {
+ container.innerHTML = '';
+ },
+ });
+ return result.results;
+}
+
+function resultFor(
+ results: readonly ExpectationResult[],
+ id: string,
+): ExpectationResult {
+ const found = results.find(result => result.expectation === id);
+ if (found == null) {
+ throw new Error(`no result for ${id}`);
+ }
+ return found;
+}
+
+describe('checkbox contract — completeness', () => {
+ it('answers every completeness dimension', () => {
+ expect(unansweredDimensions(CHECKBOX_PATTERN)).toEqual([]);
+ });
+
+ it('gives every expectation at least one deliberately violating fixture', () => {
+ const missing = CHECKBOX_PATTERN.expectations
+ .filter(
+ expectation => (CHECKBOX_MUTATIONS[expectation.id] ?? []).length === 0,
+ )
+ .map(expectation => expectation.id);
+ expect(missing).toEqual([]);
+ });
+
+ it('has an expectation for every violating fixture it records', () => {
+ const ids = new Set(
+ CHECKBOX_PATTERN.expectations.map(expectation => expectation.id),
+ );
+ const orphans = Object.keys(CHECKBOX_MUTATIONS).filter(id => !ids.has(id));
+ expect(orphans).toEqual([]);
+ });
+
+ it('names every fixture it records a mutation against', () => {
+ for (const fixtures of Object.values(CHECKBOX_MUTATIONS)) {
+ for (const id of fixtures) {
+ expect(() => fixture(id)).not.toThrow();
+ }
+ }
+ });
+});
+
+describe('checkbox contract — the jsdom harness reports what it cannot see', () => {
+ it('reports an expectation above the DOM layer as unrun, never as a pass', async () => {
+ const results = await resultsFor(fixture('conforming-off'));
+ const above = results.filter(result => result.status === 'unrun');
+ // There is at least one, or the contract would be provable without a browser.
+ expect(above.length).toBeGreaterThan(0);
+ for (const result of above) {
+ expect(
+ ['unrun', 'not-applicable'],
+ `${result.expectation} in jsdom`,
+ ).toContain(result.status);
+ }
+ });
+});
+
+describe.each(observableHere.map(expectation => [expectation.id] as const))(
+ '%s',
+ id => {
+ const expectation = CHECKBOX_PATTERN.expectations.find(
+ candidate => candidate.id === id,
+ )!;
+
+ it.each(CONFORMING_FIXTURES.map(name => [name] as const))(
+ 'passes against %s (or does not apply to it)',
+ async name => {
+ const target = fixture(name);
+ const result = resultFor(await resultsFor(target), id);
+ expect(
+ ['pass', 'not-applicable'],
+ `${id} against ${name}: ${result.detail ?? ''}`,
+ ).toContain(result.status);
+ },
+ );
+
+ it.each((CHECKBOX_MUTATIONS[id] ?? []).map(name => [name] as const))(
+ 'fails against %s, which removes its outcome',
+ async name => {
+ const target = fixture(name);
+ const result = resultFor(await resultsFor(target), id);
+ expect(result.status, `${id} against ${name}`).toBe('fail');
+ expect(result.detail ?? '').toBe(expectedMutationFailure(id, name));
+ },
+ );
+
+ it('carries its id and its normative source into every failure it reports', async () => {
+ const [violating] = CHECKBOX_MUTATIONS[id] ?? [];
+ const target = fixture(violating ?? CONFORMING_FIXTURES[0]!);
+ const result = resultFor(await resultsFor(target), id);
+ // AST-020 FR4: a failure has to be understandable without opening the
+ // runner, so the id and the citation travel with the result.
+ expect(result.description).toContain(id);
+ expect(result.description).toContain(citeSource(expectation.sources[0]));
+ expect(describeExpectation(expectation)).toBe(result.description);
+ });
+ },
+);
diff --git a/internal/a11y-spec/src/patterns/checkbox.ts b/internal/a11y-spec/src/patterns/checkbox.ts
new file mode 100644
index 0000000000..8ce799cc6e
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/checkbox.ts
@@ -0,0 +1,1025 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file checkbox.ts
+ * @input Uses ../contract (definePattern and the expectation vocabulary)
+ * @output CHECKBOX_PATTERN — the adopted WAI-ARIA APG "checkbox" pattern as a
+ * reusable contract — and CheckboxStateFacts, what a binding declares each of
+ * its states is supposed to be.
+ * @position The third authored pattern, after switch and button.
+ *
+ * Adopted pattern: https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/
+ *
+ * What this contract owns is the part of "is it a checkbox" that is the same for
+ * every component that adopts the pattern: the checkbox-bearing role and name are
+ * exposed, the unchecked, checked, or partially checked state matches what is
+ * rendered, pointer activation changes it and can be taken back, direct checkboxes
+ * respond to Space without trapping focus, and unavailable controls stay inert.
+ * Menu arrow navigation and composite focus stay with the menu contract; callback,
+ * form, composition, and styling behavior stays with each component
+ * (`docs/specs/AST-021/spec.md` FR5).
+ *
+ * SYNC: When an expectation changes, update
+ * - /internal/a11y-spec/README.md
+ * - /packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.test.tsx (the jsdom binding)
+ * - /packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.chromium.spec.ts (Chromium)
+ */
+
+import {
+ definePattern,
+ type ApgRequirement,
+ type AstryxRecord,
+ type PatternContract,
+ type WcagCriterion,
+} from '../contract';
+import type {Harness, Subject} from '../harness';
+import {saysInOrder, spokenWords} from '../spoken';
+
+const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/';
+const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';
+
+const WCAG_1_3_1: WcagCriterion = {
+ standard: 'wcag',
+ id: '1.3.1',
+ name: 'Info and Relationships',
+ level: 'A',
+ url: `${UNDERSTANDING}/info-and-relationships.html`,
+};
+const WCAG_2_1_1: WcagCriterion = {
+ standard: 'wcag',
+ id: '2.1.1',
+ name: 'Keyboard',
+ level: 'A',
+ url: `${UNDERSTANDING}/keyboard.html`,
+};
+const WCAG_2_1_2: WcagCriterion = {
+ standard: 'wcag',
+ id: '2.1.2',
+ name: 'No Keyboard Trap',
+ level: 'A',
+ url: `${UNDERSTANDING}/no-keyboard-trap.html`,
+};
+const WCAG_2_5_2: WcagCriterion = {
+ standard: 'wcag',
+ id: '2.5.2',
+ name: 'Pointer Cancellation',
+ level: 'A',
+ url: `${UNDERSTANDING}/pointer-cancellation.html`,
+};
+const WCAG_3_2_2: WcagCriterion = {
+ standard: 'wcag',
+ id: '3.2.2',
+ name: 'On Input',
+ level: 'A',
+ url: `${UNDERSTANDING}/on-input.html`,
+};
+const WCAG_2_5_3: WcagCriterion = {
+ standard: 'wcag',
+ id: '2.5.3',
+ name: 'Label in Name',
+ level: 'A',
+ url: `${UNDERSTANDING}/label-in-name.html`,
+};
+const WCAG_3_3_2: WcagCriterion = {
+ standard: 'wcag',
+ id: '3.3.2',
+ name: 'Labels or Instructions',
+ level: 'A',
+ url: `${UNDERSTANDING}/labels-or-instructions.html`,
+};
+const WCAG_4_1_2: WcagCriterion = {
+ standard: 'wcag',
+ id: '4.1.2',
+ name: 'Name, Role, Value',
+ level: 'A',
+ url: `${UNDERSTANDING}/name-role-value.html`,
+};
+
+const APG_ROLE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'checkbox',
+ requirement: 'The checkbox has role checkbox.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_MENUITEM_CHECKBOX_ROLE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menu and menubar',
+ requirement:
+ 'Focusable elements, which may have role menuitem, menuitemradio, or menuitemcheckbox, are referred to as items.',
+ url: 'https://www.w3.org/WAI/ARIA/apg/patterns/menubar/#keyboardinteraction',
+};
+const APG_MENUITEM_CHECKBOX_STATE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menu and menubar',
+ requirement:
+ 'When a menuitemcheckbox or menuitemradio is checked, aria-checked is set to true.',
+ url: 'https://www.w3.org/WAI/ARIA/apg/patterns/menubar/#wai-ariaroles,states,andproperties',
+};
+const APG_LABEL: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'checkbox',
+ requirement:
+ 'The checkbox has an accessible label provided by visible text content, aria-labelledby, or aria-label.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_STATE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'checkbox',
+ requirement:
+ 'When checked, the checkbox element has state aria-checked set to true. When not checked, it has state aria-checked set to false. When partially checked, it has state aria-checked set to mixed.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_DESCRIBEDBY: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'checkbox',
+ requirement:
+ 'If the presentation includes additional descriptive static text relevant to a checkbox or to a group of checkboxes, the checkbox or checkbox group has aria-describedby set to the id of the element containing the description.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_SPACE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'checkbox',
+ requirement:
+ 'When the checkbox has focus, pressing the Space key changes the state of the checkbox.',
+ url: `${APG_URL}#keyboardinteraction`,
+};
+const AST_021_PRESERVE_BEHAVIOR: AstryxRecord = {
+ standard: 'astryx',
+ id: 'spec:AST-021',
+ clause: 'FR7',
+ requirement:
+ 'Existing behavior is preserved unless a separate change authorizes it.',
+ url: 'https://github.com/facebook/astryx/blob/9fdb3819f91b3642b46319f21f4d99f95bc14f16/docs/specs/AST-021/spec.md#L85-L89',
+};
+
+/**
+ * How many Tab presses count as "reachable". Ten is generous for one control
+ * on a fixture page and short enough that an unreachable checkbox fails fast
+ * instead of hanging the run.
+ */
+const TAB_BUDGET = 10;
+
+/**
+ * An interaction expectation's claim is a real-browser one — pressing this
+ * changes its state — but the answer is read out of the accessibility tree, so it
+ * cannot run without both.
+ */
+const READS_THE_TREE = ['accessibility-tree'] as const;
+
+/** Applies to every state; the outcome never stops mattering. */
+const ALWAYS = {
+ condition: 'the binding renders the pattern at all',
+ test: () => true,
+};
+
+/**
+ * What a binding declares one of its states is supposed to be. The contract
+ * asks the browser what it actually exposes and compares it against this — so a
+ * binding cannot pass by being consistently wrong, and an expectation knows
+ * which states it applies to (AST-020 FR5, AST-021 FR4).
+ */
+export interface CheckboxStateFacts {
+ /** Which checkbox-bearing role this state adopts. */
+ readonly role: 'checkbox' | 'menuitemcheckbox';
+ /** Whether this state renders unchecked, checked, or partially checked. */
+ readonly checked: boolean | 'mixed';
+ /** Whether the user is meant to be able to change it. */
+ readonly operable: boolean;
+ /** Whether it is meant to be reachable in the page tab sequence. */
+ readonly focusable: boolean;
+ /** Whether it is meant to be exposed as unavailable. */
+ readonly disabled: boolean;
+ /** Supporting text that must be exposed as this state's description. */
+ readonly description: string | null;
+ /** Whether it is meant to be exposed as read-only. */
+ readonly readOnly: boolean;
+ /** Whether it is meant to be exposed as required. */
+ readonly required: boolean;
+ /** Whether it is meant to be exposed as being in error. */
+ readonly invalid: boolean;
+}
+
+function checkedState(checked: 'true' | 'false' | 'mixed' | null): string {
+ switch (checked) {
+ case 'true':
+ return 'checked';
+ case 'false':
+ return 'unchecked';
+ case 'mixed':
+ return 'partially checked';
+ default:
+ return 'without a checked state';
+ }
+}
+
+function sameWords(actual: string, expected: string): boolean {
+ const actualWords = spokenWords(actual);
+ const expectedWords = spokenWords(expected);
+ return (
+ actualWords.length === expectedWords.length &&
+ actualWords.every((word, index) => word === expectedWords[index])
+ );
+}
+
+/**
+ * Half a round trip is not the outcome: a control that turns on and cannot turn
+ * off has failed the person using it just as completely as one that never
+ * turned on (AST-020 FR8).
+ */
+async function roundTrip(
+ start: boolean | 'mixed',
+ activate: () => Promise<void>,
+ read: () => Promise<'true' | 'false' | 'mixed' | null>,
+ how: string,
+): Promise<void> {
+ const from = start === 'mixed' ? 'mixed' : start ? 'true' : 'false';
+ const initial = await read();
+ if (initial !== from) {
+ throw new Error(
+ `the binding declares ${checkedState(from)}, but the browser starts ${checkedState(initial)}`,
+ );
+ }
+ await activate();
+ const after = await read();
+
+ if (start === 'mixed') {
+ if (after !== 'true' && after !== 'false') {
+ throw new Error(
+ `${how} left the checkbox ${checkedState(after)} instead of resolving the partially checked state`,
+ );
+ }
+ await activate();
+ const back = await read();
+ if ((back !== 'true' && back !== 'false') || back === after) {
+ throw new Error(
+ `${how} resolved the partially checked state to ${checkedState(after)}, but doing it again left it ${checkedState(back)}: the change only goes one way`,
+ );
+ }
+ return;
+ }
+
+ const to = start ? 'false' : 'true';
+ if (after !== to) {
+ throw new Error(
+ `${how} left the checkbox ${checkedState(after)}: it cannot be changed to ${checkedState(to)}`,
+ );
+ }
+ await activate();
+ const back = await read();
+ if (back !== from) {
+ throw new Error(
+ `${how} changed the checkbox to ${checkedState(after)}, but doing it again left it ${checkedState(back)} instead of returning it to ${checkedState(from)}: the change only goes one way`,
+ );
+ }
+}
+
+async function assertReachableAndEscapable(
+ harness: Harness,
+ subject: Subject,
+): Promise<void> {
+ await harness.resetFocus();
+ let reached = false;
+ for (let step = 0; step < TAB_BUDGET && !reached; step += 1) {
+ await harness.press('Tab');
+ reached = await subject.isFocused();
+ }
+ if (!reached) {
+ throw new Error(
+ `${TAB_BUDGET} presses of Tab from the start of the document never reached the checkbox, so a keyboard user cannot get to this setting`,
+ );
+ }
+ await harness.press('Tab');
+ if (await subject.isFocused()) {
+ throw new Error(
+ 'Tab did not move focus off the checkbox, so a keyboard user is stuck on it',
+ );
+ }
+}
+
+export const CHECKBOX_PATTERN: PatternContract<CheckboxStateFacts> =
+ definePattern<CheckboxStateFacts>({
+ pattern: 'checkbox',
+ url: 'https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/',
+ scope:
+ 'One checkbox-bearing control that exposes its role, name, checked state, and availability; pointer activation works in both directions, and direct checkboxes also support Space and ordinary tab navigation.',
+
+ expectations: [
+ {
+ id: 'checkbox.role.exposed',
+ outcome:
+ 'The control exposes the checkbox-bearing role its adopted pattern requires, so the user knows this is a selectable value.',
+ sources: [WCAG_4_1_2, APG_ROLE, APG_MENUITEM_CHECKBOX_ROLE],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject, facts}) => {
+ const {role} = await subject.computed();
+ if (role !== facts.role) {
+ throw new Error(
+ role == null
+ ? `the browser exposes no role for this ${facts.role} control, so the accessibility node does not identify which widget pattern it implements`
+ : `this binding adopts the ${facts.role} role, but the browser reports "${role}"`,
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.name.exposed',
+ outcome:
+ 'The checkbox has an accessible name, so the user knows which setting they are turning on or off.',
+ sources: [WCAG_4_1_2, WCAG_3_3_2, APG_LABEL],
+ covers: ['4.1.2-name-role-value', '3.3.2-labels-or-instructions'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const {name} = await subject.computed();
+ if (name.trim() === '') {
+ throw new Error(
+ 'the browser computes no accessible name for this checkbox, so the accessibility node does not identify the choice',
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.name.matches-visible-label',
+ outcome:
+ 'The accessible name contains the visible label, so someone using speech input can say what they can read.',
+ sources: [WCAG_2_5_3, APG_LABEL],
+ covers: ['2.5.3-label-in-name'],
+ // Applies to every state, and reads BOTH sides off the rendered page.
+ // Nothing here consults the binding: a criterion a binding could checkbox
+ // off by declaring something about itself would not be a criterion.
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ alsoNeeds: ['real-browser'],
+ enforcement: 'required',
+ run: async ({subject, notApplicable}) => {
+ const visible = await subject.visibleLabelText();
+ if (visible == null) {
+ // Nothing is presented visually, so there is nothing for a speech
+ // user to say: 2.5.3 applies to "user interface components with
+ // labels that include text or images of text". Reported as such
+ // rather than returning — a silent return would read as a pass, and
+ // this state never exercised the outcome.
+ // `return` so the compiler follows the control flow; the call
+ // itself never returns.
+ return notApplicable(
+ 'this state renders no label where a person can read it, so there are no visible words for a speech-input user to say',
+ );
+ }
+ const {name} = await subject.computed();
+ if (!saysInOrder(spokenWords(name), spokenWords(visible))) {
+ throw new Error(
+ `the visible label reads "${visible}" but the browser computes the accessible name as "${name}", so speaking the visible label does not reach this control`,
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.state.exposed',
+ outcome:
+ 'The browser accessibility node exposes the unchecked, checked, or partially checked state that the binding renders.',
+ sources: [WCAG_4_1_2, APG_STATE, APG_MENUITEM_CHECKBOX_STATE],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject, facts}) => {
+ const {checked} = await subject.computed();
+ if (checked == null) {
+ throw new Error(
+ 'the browser accessibility node exposes no checked state for this checkbox',
+ );
+ }
+ const expected =
+ facts.checked === 'mixed'
+ ? 'mixed'
+ : facts.checked
+ ? 'true'
+ : 'false';
+ if (checked !== expected) {
+ throw new Error(
+ `this state renders ${checkedState(expected)} but the browser reports it as ${checkedState(checked)}`,
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.description.resolvable',
+ outcome:
+ 'Every piece of supporting text the checkbox points at exists, so none of the explanation is silently dropped.',
+ sources: [WCAG_1_3_1, APG_DESCRIBEDBY],
+ covers: ['1.3.1-info-and-relationships'],
+ appliesWhen: {
+ condition: 'the binding renders supporting text for this state',
+ test: facts => facts.description != null,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject, facts}) => {
+ const expected = facts.description;
+ if (expected == null) {
+ throw new Error(
+ 'description expectation ran without expected text',
+ );
+ }
+ const attribute = await subject.attribute('aria-describedby');
+ const ids = (attribute ?? '').split(/\s+/).filter(Boolean);
+ if (ids.length === 0) {
+ throw new Error(
+ 'the binding renders supporting text for this state, but the checkbox has no aria-describedby, so the text is never attached to the control',
+ );
+ }
+ const targets = await subject.idReferences('aria-describedby');
+ const dangling = ids.filter((_, index) => targets[index] == null);
+ if (dangling.length > 0) {
+ throw new Error(
+ `aria-describedby points at ${dangling.map(id => `"${id}"`).join(', ')}, which ${dangling.length === 1 ? 'resolves' : 'resolve'} to nothing`,
+ );
+ }
+ const attached = targets
+ .filter((text): text is string => text != null)
+ .join(' ');
+ if (!sameWords(attached, expected)) {
+ throw new Error(
+ `the binding expects the description "${expected}", but aria-describedby resolves to "${attached}"`,
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.description.exposed',
+ outcome:
+ 'The browser computes the intended supporting text as the control’s distinct accessible description, not just as nearby markup.',
+ sources: [WCAG_4_1_2, APG_DESCRIBEDBY],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'the binding renders supporting text for this state',
+ test: facts => facts.description != null,
+ },
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject, facts}) => {
+ const expected = facts.description;
+ if (expected == null) {
+ throw new Error(
+ 'description expectation ran without expected text',
+ );
+ }
+ const {description} = await subject.computed();
+ if (!sameWords(description, expected)) {
+ throw new Error(
+ description.trim() === ''
+ ? `the binding expects the description "${expected}", but the browser computes no accessible description`
+ : `the binding expects the description "${expected}", but the browser computes "${description}"`,
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.disabled.exposed',
+ outcome:
+ 'A checkbox the binding marks unavailable is reported as unavailable, instead of looking available and doing nothing.',
+ sources: [WCAG_4_1_2],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'the binding declares this state unavailable',
+ test: facts => facts.disabled,
+ },
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const {disabled} = await subject.computed();
+ if (!disabled) {
+ throw new Error(
+ 'the binding declares this state unavailable, but the browser reports the checkbox as available, so the user is invited to change something that will not change',
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.disabled.not-exposed',
+ outcome:
+ 'An available checkbox does not expose a false disabled state.',
+ sources: [WCAG_4_1_2],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'this state is available',
+ test: facts => !facts.disabled,
+ },
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const {disabled} = await subject.computed();
+ if (disabled) {
+ throw new Error(
+ 'this state is available, but the browser exposes the checkbox as disabled',
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.readonly.declared',
+ outcome:
+ 'A read-only checkbox declares that its value cannot be changed.',
+ sources: [WCAG_4_1_2],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'this state is read-only',
+ test: facts => facts.readOnly,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ if ((await subject.attribute('aria-readonly')) !== 'true') {
+ throw new Error(
+ 'this state is read-only, but the checkbox does not declare aria-readonly="true"',
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.readonly.not-declared',
+ outcome:
+ 'An editable checkbox does not expose a false read-only state.',
+ sources: [WCAG_4_1_2],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'this state is not read-only',
+ test: facts => !facts.readOnly,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ if ((await subject.attribute('aria-readonly')) === 'true') {
+ throw new Error(
+ 'this state is editable, but the checkbox declares aria-readonly="true"',
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.required.declared',
+ outcome:
+ 'A checkbox that has to be checked declares that requirement in markup for user agents and assistive technology to consume.',
+ sources: [WCAG_4_1_2],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'this state is required',
+ test: facts => facts.required,
+ },
+ // The accessibility-tree layer would be the stronger place for this, but
+ // Chromium's protocol does not emit a `required` property for a checkbox
+ // (it reports the resulting constraint-validation `invalid` instead), so
+ // the honest layer for the claim is the declaration itself.
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const native = await subject.attribute('required');
+ const aria = await subject.attribute('aria-required');
+ if (native == null && aria !== 'true') {
+ throw new Error(
+ 'this state is required, but the checkbox declares neither the native required attribute nor aria-required="true", so user agents receive no required-state declaration',
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.required.not-declared',
+ outcome:
+ 'A checkbox that is not required does not expose a false required state.',
+ sources: [WCAG_4_1_2],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'this state is not required',
+ test: facts => !facts.required,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const native = await subject.attribute('required');
+ const aria = await subject.attribute('aria-required');
+ if (native != null || aria === 'true') {
+ throw new Error(
+ 'this state is not required, but the checkbox exposes a required declaration',
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.invalid.exposed',
+ outcome:
+ 'A checkbox in error is reported as being in error, so the user can find what needs fixing.',
+ sources: [WCAG_4_1_2],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'this state is in error',
+ test: facts => facts.invalid,
+ },
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const {invalid} = await subject.computed();
+ if (!invalid) {
+ throw new Error(
+ 'this state is in error, but the browser does not report the checkbox as invalid, so the error is only visible to people who can see the message',
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.invalid.not-exposed',
+ outcome:
+ 'A checkbox that is not invalid does not expose a false invalid state.',
+ sources: [WCAG_4_1_2],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'this state is not invalid',
+ test: facts => !facts.invalid,
+ },
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const {invalid} = await subject.computed();
+ if (invalid) {
+ throw new Error(
+ 'this state is not invalid, but the browser exposes the checkbox as invalid',
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.state.pointer-round-trip',
+ outcome:
+ 'A pointer changes the checkbox and can change it again, while the exposed state follows each transition.',
+ sources: [APG_STATE, WCAG_4_1_2],
+ wcagOutcome:
+ 'The checked state exposed under 4.1.2 stays synchronized with the state the user changes.',
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the user is meant to be able to change this state',
+ test: facts => facts.operable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: READS_THE_TREE,
+ enforcement: 'advisory',
+ advisoryBecause:
+ 'APG specifies keyboard state change but does not independently require pointer activation, and no current Astryx checkbox record adopts it as a gate.',
+ run: async ({harness, subject, facts}) => {
+ await roundTrip(
+ facts.checked,
+ () => harness.click(subject),
+ async () => (await subject.computed()).checked,
+ 'clicking the checkbox',
+ );
+ },
+ },
+ {
+ id: 'checkbox.state.space-round-trip',
+ outcome:
+ 'With focus on the checkbox, Space changes its state and can change it again — the keyboard reaches the same function the pointer does.',
+ sources: [WCAG_2_1_1, APG_SPACE],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition:
+ 'the user is meant to be able to change this direct checkbox',
+ test: facts => facts.operable && facts.role === 'checkbox',
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: READS_THE_TREE,
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'the checkbox did not take focus, so Space never reaches it',
+ );
+ }
+ await roundTrip(
+ facts.checked,
+ () => harness.press('Space'),
+ async () => (await subject.computed()).checked,
+ 'pressing Space on the focused checkbox',
+ );
+ },
+ },
+ {
+ id: 'checkbox.state.survives-an-aborted-press',
+ outcome:
+ 'A press the user slides off and releases elsewhere leaves the checkbox alone, so a misplaced touch can be taken back.',
+ sources: [WCAG_2_5_2],
+ covers: ['2.5.2-pointer-cancellation'],
+ appliesWhen: {
+ condition: 'the user is meant to be able to change this state',
+ test: facts => facts.operable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: READS_THE_TREE,
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const before = (await subject.computed()).checked;
+ await harness.abortedPress(subject);
+ const after = (await subject.computed()).checked;
+ if (after !== before) {
+ throw new Error(
+ `pressing the checkbox and releasing away from it still turned it ${checkedState(after)}: the change happens on the way down, so a press cannot be taken back`,
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.state.keeps-focus-on-change',
+ outcome:
+ 'Turning the checkbox on leaves focus on the checkbox, so a keyboard user is not thrown somewhere else mid-task.',
+ sources: [WCAG_3_2_2],
+ // Partly: see the 3.2.2 entry in `exemptions` for the half of the
+ // criterion a component-level run cannot see.
+ covers: ['3.2.2-on-input'],
+ appliesWhen: {
+ condition:
+ 'the user is meant to be able to change this direct checkbox',
+ test: facts => facts.operable && facts.role === 'checkbox',
+ },
+ evidenceLayer: 'real-browser',
+ // The claim is about a CHANGE, so the state has to be read before and
+ // after: "focus stayed put" is worth nothing if nothing happened.
+ alsoNeeds: READS_THE_TREE,
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'the checkbox did not take focus, so this state cannot be changed from the keyboard at all',
+ );
+ }
+ const before = (await subject.computed()).checked;
+ await harness.press('Space');
+ const after = (await subject.computed()).checked;
+ if (after === before) {
+ throw new Error(
+ `pressing Space left the checkbox ${checkedState(after)}, so nothing changed and this expectation has no change to judge`,
+ );
+ }
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ `changing the checkbox to ${checkedState(after)} moved focus off it, so the user is somewhere else without having asked to be`,
+ );
+ }
+ },
+ },
+ {
+ id: 'checkbox.focus.reachable-and-escapable',
+ outcome:
+ 'Tab reaches an operable checkbox, and Tab again leaves it, so a keyboard user can get to the setting and carry on past it.',
+ sources: [WCAG_2_1_1, WCAG_2_1_2],
+ covers: ['2.1.1-keyboard', '2.1.2-no-keyboard-trap'],
+ appliesWhen: {
+ condition: 'this direct checkbox is operable',
+ test: facts => facts.role === 'checkbox' && facts.operable,
+ },
+ evidenceLayer: 'real-browser',
+ // No `alsoNeeds`: this one reads only where focus is, which is a real
+ // browser's own answer.
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ await assertReachableAndEscapable(harness, subject);
+ },
+ },
+ {
+ id: 'checkbox.focus.declared-inoperable-reachable',
+ outcome:
+ 'When a binding promises that an inoperable checkbox remains reachable, Tab reaches it and Tab again leaves it.',
+ sources: [AST_021_PRESERVE_BEHAVIOR],
+ covers: ['2.1.1-keyboard', '2.1.2-no-keyboard-trap'],
+ appliesWhen: {
+ condition:
+ 'this direct checkbox is inoperable but its binding promises to keep it in the tab sequence',
+ test: facts =>
+ facts.role === 'checkbox' && !facts.operable && facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ enforcement: 'advisory',
+ advisoryBecause:
+ 'AST-021 requires a migration to preserve and record existing behavior, but no current component or system record makes focusability of every inoperable checkbox a universal conformance requirement.',
+ run: async ({harness, subject}) => {
+ await assertReachableAndEscapable(harness, subject);
+ },
+ },
+ {
+ id: 'checkbox.state.inoperable',
+ outcome:
+ 'A checkbox the user is not meant to be able to change does not change when it is clicked or when Space is pressed on it.',
+ sources: [APG_STATE, WCAG_4_1_2],
+ wcagOutcome:
+ 'The checked state exposed under 4.1.2 does not claim a change the unavailable control did not accept.',
+ covers: ['4.1.2-name-role-value'],
+ // Not keyed on `disabled`: a checkbox can also be temporarily
+ // unchangeable while it waits on the change it already started, and a
+ // second press that slips through queues a change nobody asked for.
+ appliesWhen: {
+ condition: 'the user is not meant to be able to change this state',
+ test: facts => !facts.operable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: READS_THE_TREE,
+ enforcement: 'advisory',
+ advisoryBecause:
+ 'The standards require accurate exposed state, but no current Astryx checkbox record independently adopts inertness for every unavailable or pending state.',
+ run: async ({harness, subject, facts}) => {
+ const before = (await subject.computed()).checked;
+ await harness.click(subject, {ignoreAvailability: true});
+ const afterClick = (await subject.computed()).checked;
+ if (afterClick !== before) {
+ throw new Error(
+ `the user is not meant to be able to change this state, but clicking the checkbox turned it ${checkedState(afterClick)}`,
+ );
+ }
+ // A checkbox kept focusable while it cannot be changed — the usual way
+ // to keep a reason or a pending state discoverable — still has to
+ // refuse the keyboard.
+ if (!facts.focusable || facts.role !== 'checkbox') {
+ return;
+ }
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ // Reachability is a separate binding promise. The dedicated
+ // declared-unavailable focus expectation records that mismatch;
+ // inertness has still been proved for every input path the user can
+ // actually reach in this rendered state.
+ return;
+ }
+ await harness.press('Space');
+ const afterSpace = (await subject.computed()).checked;
+ if (afterSpace !== before) {
+ throw new Error(
+ `the user is not meant to be able to change this state, but pressing Space on the checkbox turned it ${checkedState(afterSpace)}`,
+ );
+ }
+ },
+ },
+ ],
+
+ // Every completeness dimension this pattern does not own, and who does.
+ // A dimension answered neither here nor by an expectation's `covers` list is
+ // reported by `unansweredDimensions` and asserted empty by this pattern's
+ // suite (AST-020 FR5).
+ exemptions: {
+ 'apg-interaction': {
+ owner: 'the checkbox-group composition and its binding component',
+ verifiedBy:
+ 'group-level DOM and accessibility-tree tests for the group role, group name, and any group-level aria-describedby relationship',
+ reason:
+ 'This contract owns one checkbox-bearing control. APG also covers naming and describing a checkbox group, which can only be verified where the group is composed around its members.',
+ coversRemainderOnly: true,
+ },
+ '1.1.1-non-text-content': {
+ owner: 'the binding component',
+ verifiedBy:
+ "the binding components' own suites for decorative indicators and busy content, plus the repository axe audit, `pnpm a11y:audit`",
+ reason:
+ 'The pattern owns one control node. Which decorative graphics a binding paints around that node, and whether each is hidden, is a per-component composition fact this contract never sees.',
+ },
+ '1.3.2-meaningful-sequence': {
+ owner: 'the composing page',
+ verifiedBy: "the component's DOM-order tests and page-level review",
+ reason:
+ 'A checkbox is a single control; the order it is read in relative to other content is decided by whatever composes it.',
+ },
+ '1.4.1-use-of-color': {
+ owner: 'the binding component and the theme',
+ verifiedBy:
+ "the component's forced-colors suite and the repository visual gate",
+ reason:
+ 'Not part-encoded, and deliberately so. WCAG is explicit that exposure to assistive technology contributes nothing here: "even if information that is conveyed by color differences is appropriately conveyed to assistive technologies, it does not necessarily pass this criterion". 1.4.1 is entirely about what a sighted person who cannot distinguish two colours can see, which is a pixel fact no layer this contract observes can read.',
+ },
+ '1.4.3-contrast-minimum': {
+ owner: 'the binding component and the theme',
+ verifiedBy:
+ 'the repository axe audit, `pnpm a11y:audit`, over the component stories, plus the visual gate',
+ reason:
+ 'Contrast is measured from resolved rendered colours over a real backdrop, which is the axe and visual layer rather than the accessibility tree.',
+ },
+ '1.4.11-non-text-contrast': {
+ owner: 'the binding component and the theme',
+ verifiedBy:
+ 'the repository axe audit, `pnpm a11y:audit`, plus the visual gate',
+ reason:
+ 'Checkbox indicators, selectable-card rings, menu focus treatment, and focus indicators are painted surfaces; their contrast is a rendered-colour measurement this contract cannot make.',
+ },
+ '2.4.2-page-titled': {
+ owner: 'the page',
+ verifiedBy:
+ 'page-level review and the application that hosts the control',
+ reason:
+ 'A component rendered in isolation owns no document title and cannot supply one.',
+ },
+ '2.4.3-focus-order': {
+ owner: 'the composing page',
+ verifiedBy:
+ 'page-level review; this contract proves only that the checkbox is one reachable stop that focus can also leave',
+ reason:
+ 'Order is a property of the sequence a page builds, not of a single focus stop.',
+ },
+ '2.4.4-link-purpose': {
+ owner: 'caller content',
+ verifiedBy: 'review of any link a caller places near the control',
+ reason: 'The adopted checkbox pattern has no link part.',
+ },
+ '2.4.6-headings-and-labels': {
+ owner: 'caller content and component review',
+ verifiedBy:
+ 'review of the label text against the setting it controls; this contract proves that a name exists and matches the visible label, not that the wording describes the purpose well',
+ reason:
+ 'Whether a label is descriptive is a judgement about wording that no runtime layer can make.',
+ },
+ '2.4.7-focus-visible': {
+ owner:
+ 'the interaction-modality architecture record and the binding component',
+ verifiedBy:
+ "the repository visual gate and the component's own focus-ring styling",
+ reason:
+ 'A focus indicator is a painted result. Each adopter owns its visible focus treatment on its actual interactive surface, verified by component-level focus styling tests and the visual gate.',
+ },
+ '2.4.11-focus-not-obscured': {
+ owner: 'the composing page',
+ verifiedBy:
+ 'page-level and overlay review, plus the repository modal-close visibility guard',
+ reason:
+ 'Whether something covers a focused control depends on what else the page renders over it.',
+ },
+ '2.5.8-target-size': {
+ owner: 'the binding component and the composing page',
+ verifiedBy:
+ 'real-browser geometry measurement of the target and its neighbouring-target spacing in representative compositions, plus manual review of applicable WCAG exceptions',
+ reason:
+ 'The exception that decides most real checkboxes depends on the clearance between a target and its neighbours, which a binding rendered on its own cannot see. The repository axe audit does not enable the experimental target-size rule, so it is not evidence for this dimension.',
+ },
+ '3.1.1-language-of-page': {
+ owner: 'the page',
+ verifiedBy:
+ 'page-level review and the application that hosts the control',
+ reason:
+ 'A component rendered in isolation owns no document language and cannot supply one.',
+ },
+ '3.2.4-consistent-identification': {
+ owner: 'the composing application and caller content',
+ verifiedBy:
+ 'cross-page review that equivalent checkbox functions use consistent names and identification in their application context',
+ reason:
+ 'This contract gives each adopter the same role and state rules, but one isolated binding cannot compare equivalent functions across pages or application workflows.',
+ },
+ '3.2.2-on-input': {
+ owner: 'the caller, for its own onChange',
+ verifiedBy:
+ 'integration and page-level review of what a caller does in response to the change',
+ reason:
+ "A change of context is a change of user agent, viewport, focus, or content that changes the page's meaning. The checkbox owns exactly one of those: whether activating it moves focus. If a caller's onChange navigates, reloads, or rewrites the page around the control, that is the caller's context change to warn about before the user reaches the checkbox, and no run of one component can observe it.",
+ coversRemainderOnly: true,
+ },
+ '3.3.2-labels-or-instructions': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ 'component tests and content review for persistent visible labels and any instructions required to complete the choice',
+ reason:
+ 'This contract proves that the checkbox has an accessible name and accurately declares requiredness. Whether the visible label stays present and whether the person needs additional instructions are presentation and content outcomes owned by the binding and caller.',
+ coversRemainderOnly: true,
+ },
+ '3.3.1-error-identification': {
+ owner: 'the binding component',
+ verifiedBy: "the component's own status-message tests",
+ reason:
+ 'Not part-encoded, and deliberately so. 3.3.1 is satisfied in TEXT — "the error must be indicated in text" — and WCAG says the programmatic half "is not required for this success criterion, but may be covered by other criteria such as 4.1.2". checkbox.invalid.exposed is that 4.1.2 outcome, so it contributes nothing here. The text itself is composed around the checkbox rather than being part of the control.',
+ },
+ '4.1.3-status-messages': {
+ owner:
+ 'the binding component, and the assistive-technology verification record for the announcement itself',
+ verifiedBy:
+ "the component's own live-region regression test, plus real-AT evidence under `docs/specs/AST-009/spec.md` whenever a change claims what is announced",
+ reason:
+ 'A status message is composed around the checkbox rather than being part of the control, and whether it is announced is a real-AT claim no automated layer here can settle.',
+ },
+ 'forced-colors': {
+ owner: 'the binding component and the theme',
+ verifiedBy:
+ "the component's forced-colors suite over the compiled CSS, plus manual review under Windows High Contrast",
+ reason:
+ 'Forced-colors output is a paint result; this contract observes semantics and behaviour, not paint.',
+ },
+ 'reduced-motion': {
+ owner: 'the binding component and the theme',
+ verifiedBy:
+ "review of each binding's transition declarations and the repository's visual/manual reduced-motion checks",
+ reason:
+ 'Motion is a rendered result over time, and no layer this contract observes can watch it.',
+ },
+ 'at-facing-strings': {
+ owner: 'the binding component',
+ verifiedBy:
+ 'the repository i18n catalog check and review of the strings a component renders for assistive technology',
+ reason:
+ 'Translation is a source-level concern: the rendered result this contract observes looks the same whichever language the string is in, so a lint-layer check is the only one that can see an untranslated string.',
+ },
+ },
+ });
diff --git a/internal/a11y-spec/src/report.ts b/internal/a11y-spec/src/report.ts
index 83c1d64cdc..73c54cd3dd 100644
--- a/internal/a11y-spec/src/report.ts
+++ b/internal/a11y-spec/src/report.ts
@@ -145,8 +145,10 @@ export function neverExercised(
*
* A `required` expectation that fails is a regression. An unexpected pass is a
* stale debt record, and AST-021 FR9 requires removing it rather than counting
- * it. An `advisory` failure reports and does not gate (AST-020 FR9), and an
- * `unrun` layer gates nothing — it is a coverage fact, reported as one.
+ * it. An ordinary `advisory` failure reports without gating, including when it
+ * differs from recorded advisory debt: AST-020 FR9 says advisory expectations
+ * report only. An `unrun` layer gates nothing — it is a coverage fact, reported
+ * as one.
*/
export function blockingResults(
bindings: readonly BindingResult[],
@@ -189,9 +191,16 @@ export function formatReport(report: Report): string {
result.status === 'known-failure' && result.knownFailure != null
? ` (${result.knownFailure.issue})`
: '';
+ const failureLike =
+ result.status === 'fail' ||
+ result.status === 'known-failure' ||
+ result.status === 'unexpected-pass';
lines.push(
- ` ${result.status.padEnd(15)} ${result.expectation} · ${result.evidenceLayer} · ${result.enforcement}${suffix}`,
+ ` ${result.status.padEnd(15)} ${failureLike ? result.description : result.expectation} · ${result.evidenceLayer} · ${result.enforcement}${suffix}`,
);
+ if (failureLike && result.detail != null) {
+ lines.push(` ${result.detail.split('\n').join('\n ')}`);
+ }
}
lines.push('');
}
diff --git a/internal/a11y-spec/src/run.test.ts b/internal/a11y-spec/src/run.test.ts
index dcc00e42f4..69fc064a96 100644
--- a/internal/a11y-spec/src/run.test.ts
+++ b/internal/a11y-spec/src/run.test.ts
@@ -23,7 +23,7 @@ import {
neverExercised,
summarize,
} from './report';
-import {runBinding, type KnownFailure} from './run';
+import {runBinding, unmatchedKnownFailures, type KnownFailure} from './run';
interface Facts {
readonly applicable: boolean;
@@ -93,7 +93,8 @@ function knownFailure(overrides: Partial<KnownFailure> = {}): KnownFailure {
binding: 'Stub',
state: 'default',
evidenceLayer: 'dom',
- failureIncludes: 'the stub outcome is missing',
+ failureEquals: 'the stub outcome is missing entirely',
+ standardsReference: 'WCAG 2.2 4.1.2 Name, Role, Value (Level A)',
userImpact: 'The stub does nothing for the user.',
issue: 'https://github.com/facebook/astryx/issues/1',
reason: 'Recorded by the migration; the fix is its own change.',
@@ -270,12 +271,16 @@ describe('runBinding', () => {
expect(blockingResults([result])).toHaveLength(1);
});
- it('fails in a state the record does not name', async () => {
- const result = await run(contractThat(missing), {
- state: 'another-state',
- knownFailures: [knownFailure()],
- });
+ it('reports an advisory failure in a state the record does not name', async () => {
+ const result = await run(
+ contractThat(missing, {enforcement: 'advisory'}),
+ {
+ state: 'another-state',
+ knownFailures: [knownFailure()],
+ },
+ );
expect(result.results[0]?.status).toBe('fail');
+ expect(blockingResults([result])).toEqual([]);
});
it('fails at an evidence layer the record does not name', async () => {
@@ -285,6 +290,52 @@ describe('runBinding', () => {
expect(result.results[0]?.status).toBe('fail');
});
+ it('fails when only a substring of the recorded failure matches', async () => {
+ const result = await run(contractThat(missing), {
+ knownFailures: [
+ knownFailure({failureEquals: 'the stub outcome is missing'}),
+ ],
+ });
+ expect(result.results[0]?.status).toBe('fail');
+ expect(blockingResults([result])).toHaveLength(1);
+ });
+
+ it('reports a different advisory failure when a known record was consulted', async () => {
+ const result = await run(
+ contractThat(
+ () => {
+ throw new Error('the stub outcome broke differently');
+ },
+ {enforcement: 'advisory'},
+ ),
+ {knownFailures: [knownFailure()]},
+ );
+ expect(result.results[0]?.status).toBe('fail');
+ expect(result.results[0]?.knownFailure).toBeDefined();
+ expect(blockingResults([result])).toEqual([]);
+ });
+
+ it('accepts a record matched by exactly one executed result', async () => {
+ const record = knownFailure();
+ const result = await run(contractThat(missing), {
+ knownFailures: [record],
+ });
+ expect(unmatchedKnownFailures([record], [result])).toEqual([]);
+ });
+
+ it('reports a record orphaned by a missing state or expectation', async () => {
+ const orphan = knownFailure({state: 'deleted-state'});
+ const result = await run(
+ contractThat(() => {}),
+ {
+ knownFailures: [orphan],
+ },
+ );
+ expect(unmatchedKnownFailures([orphan], [result])).toEqual([
+ expect.stringContaining('matched 0 results'),
+ ]);
+ });
+
it('reports an unexpected pass when the recorded failure stops happening', async () => {
const result = await run(
contractThat(() => {}),
@@ -293,7 +344,12 @@ describe('runBinding', () => {
},
);
expect(result.results[0]?.status).toBe('unexpected-pass');
- expect(result.results[0]?.detail).toContain('remove the known-failure');
+ expect(result.results[0]?.detail).toContain(
+ 'remove this stale known-failure',
+ );
+ expect(result.results[0]?.detail).toContain(
+ 'close the issue only when no remaining records refer to it',
+ );
expect(blockingResults([result])).toHaveLength(1);
});
});
@@ -315,6 +371,16 @@ describe('runBinding', () => {
});
describe('the report keeps its facts apart', () => {
+ it('prints the source and failure detail for a report-only advisory result', async () => {
+ const result = await run(contractThat(missing, {enforcement: 'advisory'}));
+ const text = formatReport(
+ summarize(contractThat(missing, {enforcement: 'advisory'}), [result]),
+ );
+ expect(text).toContain('WCAG 2.2 4.1.2 Name, Role, Value (A)');
+ expect(text).toContain('the stub outcome is missing entirely');
+ expect(blockingResults([result])).toEqual([]);
+ });
+
it('counts each status separately and quotes no score', async () => {
const contract = contractThat(missing);
const failing = await run(contract);
diff --git a/internal/a11y-spec/src/run.ts b/internal/a11y-spec/src/run.ts
index e99b104e66..69b8357b1e 100644
--- a/internal/a11y-spec/src/run.ts
+++ b/internal/a11y-spec/src/run.ts
@@ -4,7 +4,8 @@
* @file run.ts
* @input Uses ./contract (expectations), ./harness (the runtime seam)
* @output `runBinding` — runs one pattern contract against one component
- * binding state — plus the known-failure vocabulary it obeys.
+ * binding state — plus the known-failure vocabulary and exact-record
+ * reconciliation helpers it obeys.
* @position The engine between a pattern and a component. Everything a report
* later says about a binding is decided here.
*
@@ -61,11 +62,10 @@ export interface KnownFailure {
readonly binding: string;
readonly state: string;
readonly evidenceLayer: EvidenceLayer;
- /**
- * A distinctive fragment of the failure this record covers. A failure whose
- * message does not contain it is a different failure, and still fails.
- */
- readonly failureIncludes: string;
+ /** The exact failure this record covers. Any text change is a different failure. */
+ readonly failureEquals: string;
+ /** Exact standards source for the failed user outcome. */
+ readonly standardsReference: string;
/** What the person using the component actually experiences. */
readonly userImpact: string;
/** Public issue tracking the fix. */
@@ -89,7 +89,7 @@ export interface ExpectationResult {
* unrun because the tree it reads the result from is out of reach.
*/
readonly missingLayers?: readonly EvidenceLayer[];
- /** Present when a known-failure record was consulted. */
+ /** Present when an exact known-failure record was consulted. */
readonly knownFailure?: KnownFailure;
}
@@ -165,6 +165,22 @@ function findKnownFailure<Facts>(
);
}
+export function unmatchedKnownFailures(
+ knownFailures: readonly KnownFailure[],
+ bindings: readonly BindingResult[],
+): readonly string[] {
+ return knownFailures.flatMap(record => {
+ const matches = bindings.flatMap(binding =>
+ binding.results.filter(result => result.knownFailure === record),
+ ).length;
+ return matches === 1
+ ? []
+ : [
+ `${record.binding} [${record.state}] ${record.expectation} at ${record.evidenceLayer} matched ${matches} results; every known-failure record must match exactly one executed result`,
+ ];
+ });
+}
+
export async function runBinding<Facts>(
options: RunBindingOptions<Facts>,
): Promise<BindingResult> {
@@ -275,13 +291,13 @@ export async function runBinding<Facts>(
...base,
status: 'unexpected-pass',
knownFailure: record,
- detail: `the recorded failure no longer happens; remove the known-failure record and let ${record.issue} close`,
+ detail: `the recorded failure no longer happens; remove this stale known-failure record and update ${record.issue}; close the issue only when no remaining records refer to it`,
},
);
continue;
}
- if (record != null && failure.includes(record.failureIncludes)) {
+ if (record != null && failure === record.failureEquals) {
results.push({
...base,
status: 'known-failure',
@@ -297,7 +313,7 @@ export async function runBinding<Facts>(
detail:
record == null
? failure
- : `${failure}\n\nA known failure is recorded for this expectation, binding, and state, but it covers a different failure (${JSON.stringify(record.failureIncludes)}). A known failure never widens to cover a new one.`,
+ : `${failure}\n\nA known failure is recorded for this expectation, binding, and state, but it covers a different failure (${JSON.stringify(record.failureEquals)}). A known failure never widens to cover a new one.`,
knownFailure: record,
});
}
diff --git a/packages/core/src/Button/__tests__/Button.a11y.chromium.spec.ts b/packages/core/src/Button/__tests__/Button.a11y.chromium.spec.ts
index ecffa105f8..4af3b05751 100644
--- a/packages/core/src/Button/__tests__/Button.a11y.chromium.spec.ts
+++ b/packages/core/src/Button/__tests__/Button.a11y.chromium.spec.ts
@@ -28,6 +28,7 @@ import {
formatFailures,
formatReport,
neverExercised,
+ unmatchedKnownFailures,
runBinding,
spokenWords,
summarize,
@@ -316,6 +317,7 @@ test('every expectation is exercised by at least one bound state', async ({
// looks. This is the only place that can notice: the contract never sees the
// states, so whether a condition matches a real one is a binding-side fact.
expect(neverExercised(results)).toEqual([]);
+ expect(unmatchedKnownFailures(BUTTON_KNOWN_FAILURES, results)).toEqual([]);
});
for (const state of BUTTON_BINDING_STATES) {
diff --git a/packages/core/src/Button/__tests__/Button.a11y.known-failures.ts b/packages/core/src/Button/__tests__/Button.a11y.known-failures.ts
index d24fffa6c5..97cfbc1a53 100644
--- a/packages/core/src/Button/__tests__/Button.a11y.known-failures.ts
+++ b/packages/core/src/Button/__tests__/Button.a11y.known-failures.ts
@@ -8,12 +8,12 @@
* binding, one state, and one public issue.
* @position Recorded debt, not permission. `docs/specs/AST-021/spec.md` FR8–FR10
* govern this: FR8 requires every record to name the expectation, binding,
- * state, user impact, evidence layer, issue, and reason; FR9 is the exact
- * gate — the expectation still RUNS and reports `known-failure`, never
- * `pass`, and "a different error, another state, a new expectation, or a
- * wider failure MUST fail". When the component is fixed the record stops
- * matching and the run reports `unexpected-pass`, which gates, so a fix
- * cannot land while leaving a stale record behind.
+ * state, user impact, standards reference, evidence layer, issue, and reason;
+ * FR9 is the exact gate — the expectation still RUNS and reports
+ * `known-failure`, never `pass`, and "a different error, another state, a new
+ * expectation, or a wider failure MUST fail". When the component is fixed the
+ * record stops matching and the run reports `unexpected-pass`, which gates, so
+ * a fix cannot land while leaving a stale record behind.
*
* A record is never a way to make a run green. It is a way to say, in public and
* in one place, precisely what is broken and where the fix is being tracked.
@@ -35,7 +35,10 @@ export const BUTTON_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [
binding: 'Button',
state: 'button-loading',
evidenceLayer: 'real-browser',
- failureIncludes: 'never reached the button',
+ failureEquals:
+ '10 presses of Tab from the start of the document never reached the button, so a keyboard user cannot get to this action',
+ standardsReference:
+ 'WCAG 2.2 2.1.1 Keyboard and 2.1.2 No Keyboard Trap (Level A)',
userImpact:
'A keyboard user who activates Save and waits is dropped to the top of the document the moment the action starts, and the button leaves the tab sequence entirely — so they cannot get back to it, to see that it is busy or to interrupt it. The next Tab restarts from the beginning of the page.',
issue: BUSY_FOCUS_ISSUE,
@@ -47,7 +50,10 @@ export const BUTTON_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [
binding: 'IconButton',
state: 'icon-button-loading',
evidenceLayer: 'real-browser',
- failureIncludes: 'never reached the button',
+ failureEquals:
+ '10 presses of Tab from the start of the document never reached the button, so a keyboard user cannot get to this action',
+ standardsReference:
+ 'WCAG 2.2 2.1.1 Keyboard and 2.1.2 No Keyboard Trap (Level A)',
userImpact:
'The same drop from an icon button, where it is worse: an icon button is usually one of several in a row, so the user loses their place among them.',
issue: BUSY_FOCUS_ISSUE,
@@ -60,7 +66,10 @@ export const BUTTON_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [
binding: 'Button',
state: 'button-loading',
evidenceLayer: 'real-browser',
- failureIncludes: 'declared focusable so its reason stays reachable',
+ failureEquals:
+ 'this state is declared focusable so its reason stays reachable, but it cannot take focus — so a keyboard user can neither read why it is unavailable nor reach it to confirm it refuses to act',
+ standardsReference:
+ 'Current Astryx family:buttons FR3 and WAI-ARIA APG Button unavailable-state requirement; supports WCAG 2.2 4.1.2 Name, Role, Value (Level A)',
userImpact:
'The third face of the same defect: because the busy button cannot take focus, there is no way to confirm from the keyboard that it declines a second press — the user can neither reach it nor see why it is unavailable.',
issue: BUSY_FOCUS_ISSUE,
@@ -72,7 +81,10 @@ export const BUTTON_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [
binding: 'IconButton',
state: 'icon-button-loading',
evidenceLayer: 'real-browser',
- failureIncludes: 'declared focusable so its reason stays reachable',
+ failureEquals:
+ 'this state is declared focusable so its reason stays reachable, but it cannot take focus — so a keyboard user can neither read why it is unavailable nor reach it to confirm it refuses to act',
+ standardsReference:
+ 'Current Astryx family:buttons FR3 and WAI-ARIA APG Button unavailable-state requirement; supports WCAG 2.2 4.1.2 Name, Role, Value (Level A)',
userImpact: 'The same, from an icon button.',
issue: BUSY_FOCUS_ISSUE,
reason: 'Inherited from Button, as above.',
@@ -84,7 +96,9 @@ export const BUTTON_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [
binding: 'ClickableCard',
state: 'clickable-card',
evidenceLayer: 'real-browser',
- failureIncludes: 'a pointer press cannot land on this control',
+ failureEquals:
+ 'a pointer press cannot land on this control: something else is on top of it at its own centre, so there is no press here to abort',
+ standardsReference: 'WCAG 2.2 2.5.2 Pointer Cancellation (Level A)',
userImpact:
'The same defect seen from the other side: pointer cancellation cannot be demonstrated on a control no pointer press can land on. Recorded rather than reported green — a serene pass here would claim an outcome nobody observed.',
issue: CARD_POINTER_ISSUE,
@@ -96,7 +110,10 @@ export const BUTTON_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [
binding: 'ClickableCard',
state: 'clickable-card',
evidenceLayer: 'real-browser',
- failureIncludes: 'a pointer could not reach this control',
+ failureEquals:
+ 'a pointer could not reach this control within 2000ms: the browser never found it visible, stable, and able to receive a pointer event. Something is covering it, or it is clipped to nothing.',
+ standardsReference:
+ 'Current Astryx buttons family FR2 and WAI-ARIA APG Button operability requirement; supports WCAG 2.2 4.1.2 Name, Role, Value (Level A)',
userImpact:
"Anyone whose tooling acts on the accessible object rather than on pixels — a speech-input user saying the card's name, or assistive technology dispatching a click at the element it is told is the button — aims at a 1×1 control the card's own content paints over. A sighted mouse user is unaffected: they click the card surface, which handles it.",
issue: CARD_POINTER_ISSUE,
diff --git a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
index 96759a3e15..2e5860aff4 100644
--- a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
+++ b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
@@ -3,8 +3,11 @@
/**
* @file CheckboxInput.test.tsx
* @input Uses vitest, @testing-library/react, CheckboxInput component
- * @output Unit tests for CheckboxInput component behavior
- * @position Testing; validates CheckboxInput.tsx implementation
+ * @output Unit tests for CheckboxInput-specific API, callback, form,
+ * composition, and styling behavior. Shared checkbox semantics live in
+ * __tests__/Checkbox.a11y.test.tsx and its Chromium twin.
+ * @position Component-owned regression tests; validates CheckboxInput.tsx without
+ * duplicating outcomes owned by the reusable checkbox contract.
*
* SYNC: When CheckboxInput.tsx changes, update tests to match new behavior
*/
@@ -75,27 +78,6 @@ beforeEach(() => {
});
describe('CheckboxInput', () => {
- it('renders with label', () => {
- render(
- <CheckboxInput label="Accept terms" value={false} onChange={() => {}} />,
- );
- expect(screen.getByLabelText('Accept terms')).toBeInTheDocument();
- });
-
- it('renders as unchecked by default', () => {
- render(
- <CheckboxInput label="Accept terms" value={false} onChange={() => {}} />,
- );
- expect(screen.getByRole('checkbox')).not.toBeChecked();
- });
-
- it('renders as checked when value prop is true', () => {
- render(
- <CheckboxInput label="Accept terms" value={true} onChange={() => {}} />,
- );
- expect(screen.getByRole('checkbox')).toBeChecked();
- });
-
it('calls onChange with new checked state when clicked', async () => {
const user = userEvent.setup();
const handleChange = vi.fn();
@@ -157,20 +139,6 @@ describe('CheckboxInput', () => {
expect(screen.getByText('Receive weekly updates')).toBeInTheDocument();
});
- it('associates description with checkbox via aria-describedby', () => {
- render(
- <CheckboxInput
- label="Subscribe"
- description="Receive weekly updates"
- value={false}
- onChange={() => {}}
- />,
- );
- const checkbox = screen.getByRole('checkbox');
- const description = screen.getByText('Receive weekly updates');
- expect(checkbox).toHaveAttribute('aria-describedby', description.id);
- });
-
it('toggles when clicking on the description', async () => {
const user = userEvent.setup();
const handleChange = vi.fn();
@@ -186,36 +154,6 @@ describe('CheckboxInput', () => {
expect(handleChange).toHaveBeenCalledWith(true, expect.any(Object));
});
- it('does not fold the description into the checkbox accessible name', () => {
- // The description stays a sibling of the <label>, so it must NOT become
- // part of the checkbox's accessible name (which is computed from the
- // associated label). It belongs in the accessible DESCRIPTION only
- // (via aria-describedby) — otherwise screen readers announce it twice.
- render(
- <CheckboxInput
- label="Email notifications"
- description="We'll send weekly digests"
- value={false}
- onChange={() => {}}
- />,
- );
- const checkbox = screen.getByRole('checkbox');
- expect(checkbox).toHaveAccessibleName('Email notifications');
- expect(checkbox).toHaveAccessibleDescription("We'll send weekly digests");
- });
-
- it('is disabled when isDisabled prop is true', () => {
- render(
- <CheckboxInput
- label="Accept terms"
- value={false}
- onChange={() => {}}
- isDisabled
- />,
- );
- expect(screen.getByRole('checkbox')).toBeDisabled();
- });
-
it('does not call onChange when isDisabled', async () => {
const user = userEvent.setup();
const handleChange = vi.fn();
@@ -383,7 +321,7 @@ describe('CheckboxInput', () => {
expect(container.querySelector('.astryx-icon')).toBeInTheDocument();
});
- it('renders status message and sets aria-invalid for error', () => {
+ it('renders the status message for an error', () => {
render(
<CheckboxInput
label="Accept terms"
@@ -393,10 +331,6 @@ describe('CheckboxInput', () => {
/>,
);
expect(screen.getByText('Required field')).toBeInTheDocument();
- expect(screen.getByRole('checkbox')).toHaveAttribute(
- 'aria-invalid',
- 'true',
- );
});
// Regression: the status is conditionally mounted, so it must be announced
diff --git a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.chromium.spec.ts b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..b00e2a4fd8
--- /dev/null
+++ b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.chromium.spec.ts
@@ -0,0 +1,361 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Checkbox.a11y.chromium.spec.ts
+ * @input Uses the shared checkbox contract, Chromium harness, checked-in
+ * CheckboxA11y stories, state inventory, and exact known failures
+ * @output Real-browser and accessibility-tree evidence for every current
+ * checkbox-bearing Astryx component part.
+ * @position Browser lane required by AST-013; it makes no real-AT claim.
+ */
+
+import {
+ expect,
+ test,
+ type CDPSession,
+ type Locator,
+ type Page,
+} from '@playwright/test';
+import {
+ CHECKBOX_PATTERN,
+ blockingResults,
+ formatFailures,
+ formatReport,
+ neverExercised,
+ unmatchedKnownFailures,
+ runBinding,
+ spokenWords,
+ summarize,
+ type BindingResult,
+} from '@astryxdesign/a11y-spec';
+import {
+ createChromiumHarness,
+ holdMotionStill,
+} from '@astryxdesign/a11y-spec/chromium';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+import {CHECKBOX_KNOWN_FAILURES} from './Checkbox.a11y.known-failures';
+import {
+ CHECKBOX_BINDING_STATES,
+ type CheckboxBindingRow,
+ type CheckboxBindingState,
+} from './Checkbox.a11y.states';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+function storyUrl(storyId: string): string {
+ return `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story`;
+}
+
+function subjectFor(page: Page, state: CheckboxBindingRow): Locator {
+ return page
+ .locator('#storybook-root')
+ .getByRole(state.facts.role, {includeHidden: true})
+ .first();
+}
+
+async function mountState(
+ page: Page,
+ state: CheckboxBindingRow,
+): Promise<void> {
+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});
+ await holdMotionStill(page);
+ const root = page.locator('#storybook-root');
+ if ((state as CheckboxBindingState).opensMenu === true) {
+ await root.getByRole('button', {name: 'View options'}).click();
+ }
+ await subjectFor(page, state).waitFor({state: 'attached'});
+}
+
+function visibleLabelFor(
+ page: Page,
+ state: CheckboxBindingRow,
+): Locator | undefined {
+ const selector = (state as CheckboxBindingState).visibleLabelSelector;
+ return selector == null ? undefined : page.locator(selector).first();
+}
+
+function pointerTargetFor(
+ page: Page,
+ state: CheckboxBindingRow,
+): Locator | undefined {
+ const selector = (state as CheckboxBindingState).pointerTargetSelector;
+ return selector == null ? undefined : page.locator(selector).first();
+}
+
+async function runState(
+ page: Page,
+ cdp: CDPSession,
+ state: CheckboxBindingRow,
+): Promise<BindingResult> {
+ return runBinding({
+ contract: CHECKBOX_PATTERN,
+ binding: state.binding,
+ state: state.id,
+ facts: state.facts,
+ knownFailures: CHECKBOX_KNOWN_FAILURES,
+ mount: async () => {
+ await mountState(page, state);
+ return createChromiumHarness({
+ page,
+ subject: subjectFor(page, state),
+ pointerTarget: pointerTargetFor(page, state),
+ cdp,
+ visibleLabel: visibleLabelFor(page, state),
+ });
+ },
+ });
+}
+
+const FIELD_MARKERS = ['required', 'optional'];
+
+function sameWords(rendered: string, claimed: string): boolean {
+ const words = [...spokenWords(rendered)];
+ const last = words[words.length - 1];
+ if (last != null && FIELD_MARKERS.includes(last)) {
+ words.pop();
+ }
+ const expected = spokenWords(claimed);
+ return (
+ words.length === expected.length &&
+ words.every((word, index) => word === expected[index])
+ );
+}
+
+test('the state inventory describes each visible label', async ({page}) => {
+ test.setTimeout(3 * 60 * 1000);
+ const cdp = await page.context().newCDPSession(page);
+ const wrong: string[] = [];
+ for (const state of CHECKBOX_BINDING_STATES) {
+ await mountState(page, state);
+ const harness = createChromiumHarness({
+ page,
+ subject: subjectFor(page, state),
+ cdp,
+ visibleLabel: visibleLabelFor(page, state),
+ });
+ const rendered = await (await harness.subject()).visibleLabelText();
+ const matches =
+ state.visibleLabel == null
+ ? rendered == null
+ : rendered != null && sameWords(rendered, state.visibleLabel);
+ if (!matches) {
+ wrong.push(
+ `${state.id}: inventory says ${JSON.stringify(state.visibleLabel)}, page renders ${JSON.stringify(rendered)}`,
+ );
+ }
+ }
+ expect(wrong).toEqual([]);
+});
+
+test('every applicability fact matches what the page exposes', async ({
+ page,
+}) => {
+ test.setTimeout(4 * 60 * 1000);
+ const cdp = await page.context().newCDPSession(page);
+ const wrong: string[] = [];
+ for (const state of CHECKBOX_BINDING_STATES) {
+ await mountState(page, state);
+ const locator = subjectFor(page, state);
+ const harness = createChromiumHarness({
+ page,
+ subject: locator,
+ pointerTarget: pointerTargetFor(page, state),
+ cdp,
+ });
+ const contractSubject = await harness.subject();
+ const computed = await contractSubject.computed();
+ await harness.click(contractSubject, {ignoreAvailability: true});
+ const afterPointer = (await contractSubject.computed()).checked;
+ const operable = afterPointer !== computed.checked;
+ await page.evaluate(() => {
+ (document.activeElement as HTMLElement | null)?.blur();
+ });
+ let reachedByTab = false;
+ for (let step = 0; step < 10 && !reachedByTab; step += 1) {
+ await page.keyboard.press('Tab');
+ reachedByTab = await locator.evaluate(
+ element => element.ownerDocument.activeElement === element,
+ );
+ }
+ const expectedChecked =
+ state.facts.checked === 'mixed'
+ ? 'mixed'
+ : state.facts.checked
+ ? 'true'
+ : 'false';
+ const required =
+ (await locator.getAttribute('required')) != null ||
+ (await locator.getAttribute('aria-required')) === 'true';
+ const readOnly = (await locator.getAttribute('aria-readonly')) === 'true';
+ const observed = {
+ role: computed.role,
+ checked: computed.checked,
+ disabled: computed.disabled,
+ description:
+ computed.description.trim() === '' ? null : computed.description,
+ focusable: reachedByTab,
+ required,
+ readOnly,
+ invalid: computed.invalid,
+ operable,
+ } as const;
+ const expected = {
+ role: state.facts.role,
+ checked: expectedChecked,
+ disabled: state.facts.disabled,
+ description: state.facts.description,
+ focusable: state.facts.focusable,
+ required: state.facts.required,
+ readOnly: state.facts.readOnly,
+ invalid: state.facts.invalid,
+ operable: state.facts.operable,
+ } as const;
+ const excused = (state as CheckboxBindingState).declaredNotDelivered ?? [];
+ for (const fact of Object.keys(expected) as (keyof typeof expected)[]) {
+ if (fact === 'focusable' && state.facts.role === 'menuitemcheckbox') {
+ // A menu composite owns its roving focus. This contract deliberately
+ // makes no claim about whether the item is reachable by page Tab order.
+ continue;
+ }
+ const matches = expected[fact] === observed[fact];
+ const excuse = excused.find(entry => entry.fact === fact);
+ // Operability and focusability have their own real-browser expectations,
+ // including advisory ones. Let those results carry their declared
+ // enforcement instead of turning this inventory cross-check into a hidden
+ // required gate. The remaining facts feed required semantic expectations,
+ // so an unexplained mismatch there still means the binding inventory lies.
+ const reportsThroughExpectation =
+ fact === 'operable' || fact === 'focusable';
+ if (!matches && excuse == null && !reportsThroughExpectation) {
+ wrong.push(
+ `${state.id}: declares ${fact}=${String(expected[fact])}, page exposes ${String(observed[fact])}`,
+ );
+ }
+ if (matches && excuse != null) {
+ wrong.push(
+ `${state.id}: lists ${fact} as declared-but-not-delivered, yet the page delivers it`,
+ );
+ }
+ if (
+ excuse != null &&
+ !CHECKBOX_KNOWN_FAILURES.some(
+ record =>
+ record.expectation === excuse.owned && record.state === state.id,
+ )
+ ) {
+ wrong.push(
+ `${state.id}: excuses ${fact} against "${excuse.owned}", but no exact known-failure record owns it`,
+ );
+ }
+ }
+ }
+ expect(wrong).toEqual([]);
+});
+
+test('every expectation is exercised by at least one bound state', async ({
+ page,
+}) => {
+ test.setTimeout(5 * 60 * 1000);
+ const cdp = await page.context().newCDPSession(page);
+ const results: BindingResult[] = [];
+ for (const state of CHECKBOX_BINDING_STATES) {
+ let mounted = false;
+ results.push(
+ await runBinding({
+ contract: CHECKBOX_PATTERN,
+ binding: state.binding,
+ state: state.id,
+ facts: state.facts,
+ knownFailures: CHECKBOX_KNOWN_FAILURES,
+ mount: async () => {
+ if (!mounted) {
+ await mountState(page, state);
+ mounted = true;
+ }
+ return createChromiumHarness({
+ page,
+ subject: subjectFor(page, state),
+ cdp,
+ visibleLabel: visibleLabelFor(page, state),
+ });
+ },
+ }),
+ );
+ }
+ expect(neverExercised(results)).toEqual([]);
+ expect(unmatchedKnownFailures(CHECKBOX_KNOWN_FAILURES, results)).toEqual([]);
+});
+
+test('CheckboxInput keeps supporting text out of its accessible name', async ({
+ page,
+}) => {
+ const state = CHECKBOX_BINDING_STATES.find(
+ candidate => candidate.id === 'input-described',
+ );
+ if (state == null) {
+ throw new Error('missing input-described binding state');
+ }
+ const cdp = await page.context().newCDPSession(page);
+ await mountState(page, state);
+ const subject = await createChromiumHarness({
+ page,
+ subject: subjectFor(page, state),
+ cdp,
+ }).subject();
+ const computed = await subject.computed();
+ expect(computed.name).toBe('Share usage data');
+ expect(computed.description).toBe('Help improve the product');
+});
+
+test('the disabled SelectableCard records only its documented focusability mismatch', async ({
+ page,
+}) => {
+ const state = CHECKBOX_BINDING_STATES.find(
+ candidate => candidate.id === 'card-disabled',
+ );
+ if (state == null) {
+ throw new Error('missing card-disabled binding state');
+ }
+ const cdp = await page.context().newCDPSession(page);
+ const result = await runState(page, cdp, state);
+ expect(
+ result.results.find(
+ candidate =>
+ candidate.expectation ===
+ 'checkbox.focus.declared-inoperable-reachable',
+ )?.status,
+ ).toBe('known-failure');
+ expect(
+ result.results.find(
+ candidate => candidate.expectation === 'checkbox.state.inoperable',
+ )?.status,
+ ).toBe('pass');
+});
+
+for (const state of CHECKBOX_BINDING_STATES) {
+ test(`${state.binding} [${state.id}] — ${state.summary}`, async ({page}) => {
+ test.setTimeout(2 * 60 * 1000);
+ const cdp = await page.context().newCDPSession(page);
+ const result = await runState(page, cdp, state);
+ const report = summarize(CHECKBOX_PATTERN, [result]);
+ // eslint-disable-next-line no-console -- the report is this run's artifact
+ console.log(formatReport(report));
+ expect(formatFailures(blockingResults([result]))).toBe('');
+ expect(report.unrunLayers).toEqual([]);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+}
diff --git a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.known-failures.ts b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.known-failures.ts
new file mode 100644
index 0000000000..020a357a01
--- /dev/null
+++ b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.known-failures.ts
@@ -0,0 +1,123 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Checkbox.a11y.known-failures.ts
+ * @input Uses KnownFailure from @astryxdesign/a11y-spec
+ * @output CHECKBOX_KNOWN_FAILURES — exact, runnable existing gaps discovered by
+ * the Checkbox pattern migration.
+ * @position Recorded public debt under AST-021 FR8–FR10, never passing coverage.
+ */
+
+import type {KnownFailure} from '@astryxdesign/a11y-spec';
+
+const CHECKBOX_LIST_DESCRIPTION_ISSUE =
+ 'https://github.com/facebook/astryx/issues/6154';
+const RICH_LABEL_NAME_ISSUE = 'https://github.com/facebook/astryx/issues/6161';
+const LIST_HANDLERLESS_READONLY_ISSUE =
+ 'https://github.com/facebook/astryx/issues/6163';
+const INPUT_HANDLERLESS_READONLY_ISSUE =
+ 'https://github.com/facebook/astryx/issues/6165';
+const MENU_HANDLERLESS_UNAVAILABLE_ISSUE =
+ 'https://github.com/facebook/astryx/issues/6166';
+
+export const CHECKBOX_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [
+ {
+ expectation: 'checkbox.description.resolvable',
+ binding: 'CheckboxListItem',
+ state: 'list-item-described',
+ evidenceLayer: 'dom',
+ failureEquals:
+ 'the binding renders supporting text for this state, but the checkbox has no aria-describedby, so the text is never attached to the control',
+ standardsReference: 'WCAG 2.2 1.3.1 Info and Relationships (Level A)',
+ userImpact:
+ 'The browser accessibility node exposes no separate description for the visible supporting text, so downstream accessibility consumers cannot distinguish it as the choice explanation.',
+ issue: CHECKBOX_LIST_DESCRIPTION_ISSUE,
+ reason:
+ 'CheckboxListItem renders its description in the ListItem row but does not pass or reference that content from the nested CheckboxInput. The migration records the gap without changing component behavior.',
+ },
+ {
+ expectation: 'checkbox.description.exposed',
+ binding: 'CheckboxListItem',
+ state: 'list-item-described',
+ evidenceLayer: 'accessibility-tree',
+ failureEquals:
+ 'the binding expects the description "Receive notifications by email", but the browser computes no accessible description',
+ standardsReference: 'WCAG 2.2 4.1.2 Name, Role, Value (Level A)',
+ userImpact:
+ 'The browser computes no distinct description for the visible explanation; this records browser exposure only, not what any assistive technology announces.',
+ issue: CHECKBOX_LIST_DESCRIPTION_ISSUE,
+ reason:
+ 'This is the accessibility-tree face of the missing relationship recorded above. It is separate because each known failure names exactly one expectation and layer.',
+ },
+ {
+ expectation: 'checkbox.name.matches-visible-label',
+ binding: 'CheckboxListItem',
+ state: 'list-item-rich-label-missing-name',
+ evidenceLayer: 'accessibility-tree',
+ failureEquals:
+ 'the visible label reads "Pro plan" but the browser computes the accessible name as "Checkbox", so speaking the visible label does not reach this control',
+ standardsReference: 'WCAG 2.2 2.5.3 Label in Name (Level A)',
+ userImpact:
+ 'The browser exposes every rich-label item without an aria-label under the generic name "Checkbox", so speech input cannot address the item by the visible words.',
+ issue: RICH_LABEL_NAME_ISSUE,
+ reason:
+ 'The public API permits a ReactNode label without an equivalent plain-text name. The migration records that supported branch without changing the component API.',
+ },
+ {
+ expectation: 'checkbox.readonly.declared',
+ binding: 'CheckboxInput',
+ state: 'input-handlerless-read-only',
+ evidenceLayer: 'dom',
+ failureEquals:
+ 'this state is read-only, but the checkbox does not declare aria-readonly="true"',
+ standardsReference: 'WCAG 2.2 4.1.2 Name, Role, Value (Level A)',
+ userImpact:
+ 'The browser exposes a controlled handlerless checkbox without a read-only declaration, so accessibility consumers cannot distinguish its static value from an editable setting.',
+ issue: INPUT_HANDLERLESS_READONLY_ISSUE,
+ reason:
+ 'CheckboxInput makes both onChange and changeAction optional. With neither handler, the controlled value cannot persist a user change, but the component does not declare the resulting read-only state.',
+ },
+ {
+ expectation: 'checkbox.readonly.declared',
+ binding: 'CheckboxListItem',
+ state: 'list-item-handlerless-read-only',
+ evidenceLayer: 'dom',
+ failureEquals:
+ 'this state is read-only, but the checkbox does not declare aria-readonly="true"',
+ standardsReference: 'WCAG 2.2 4.1.2 Name, Role, Value (Level A)',
+ userImpact:
+ 'The browser exposes a handlerless inert checkbox without a read-only declaration, so accessibility consumers cannot distinguish it from an editable control.',
+ issue: LIST_HANDLERLESS_READONLY_ISSUE,
+ reason:
+ 'The public standalone API permits an item with isChecked and no onCheck. The row is inert, but CheckboxInput does not receive isReadOnly.',
+ },
+ {
+ expectation: 'checkbox.disabled.exposed',
+ binding: 'DropdownMenuCheckboxItem',
+ state: 'menu-item-handlerless-inert',
+ evidenceLayer: 'accessibility-tree',
+ failureEquals:
+ 'the binding declares this state unavailable, but the browser reports the checkbox as available, so the user is invited to change something that will not change',
+ standardsReference: 'WCAG 2.2 4.1.2 Name, Role, Value (Level A)',
+ userImpact:
+ 'The menu item looks available to accessibility consumers, but activation cannot change its controlled value because it has no handler.',
+ issue: MENU_HANDLERLESS_UNAVAILABLE_ISSUE,
+ reason:
+ 'DropdownMenuCheckboxItem makes onChange optional. Without it, the controlled value cannot persist a user change, but the role-bearing item remains exposed as available.',
+ },
+ {
+ expectation: 'checkbox.focus.declared-inoperable-reachable',
+ binding: 'SelectableCard',
+ state: 'card-disabled',
+ evidenceLayer: 'real-browser',
+ failureEquals:
+ '10 presses of Tab from the start of the document never reached the checkbox, so a keyboard user cannot get to this setting',
+ standardsReference:
+ 'Astryx spec:AST-021 FR7 (preserve existing documented behavior); SelectableCard isDisabled public prop contract',
+ userImpact:
+ 'A keyboard user cannot tab to the disabled card to discover that the option exists and is unavailable, despite the public prop contract promising continued focusability.',
+ issue: 'https://github.com/facebook/astryx/issues/6156',
+ reason:
+ 'SelectableCard documents a focusable aria-disabled state, but the implementation applies native disabled to its checkbox and removes it from the tab sequence. This advisory migration check records that public-contract mismatch without presenting disabled focusability as a WCAG requirement.',
+ },
+];
diff --git a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.renders.tsx b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.renders.tsx
new file mode 100644
index 0000000000..28ccb18a46
--- /dev/null
+++ b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.renders.tsx
@@ -0,0 +1,310 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file Checkbox.a11y.renders.tsx
+ * @input Uses every current checkbox-bearing Astryx component and the state-id
+ * union from Checkbox.a11y.states.ts
+ * @output CHECKBOX_STATE_RENDERS — one consumer-realistic rendering per inventory
+ * row, shared by jsdom and checked-in Storybook stories.
+ * @position Binding fixture layer. Component-specific callbacks and form behavior
+ * remain in their local suites.
+ */
+
+import {useState, type ReactElement, type ReactNode} from 'react';
+import {CheckboxInput} from '../CheckboxInput';
+import {CheckboxList, CheckboxListItem} from '../../CheckboxList';
+import {DropdownMenu, DropdownMenuCheckboxItem} from '../../DropdownMenu';
+import {FormLayout} from '../../FormLayout';
+import {List} from '../../List';
+import {SelectableCard} from '../../SelectableCard';
+import type {CheckboxStateId} from './Checkbox.a11y.states';
+
+function VisibleLabel({children}: {children: ReactNode}) {
+ return <span data-a11y-visible-label>{children}</span>;
+}
+
+function ControlledInput({
+ initial,
+ hasChangeHandler = true,
+ ...props
+}: {
+ initial: boolean | 'indeterminate';
+ hasChangeHandler?: boolean;
+ label: string;
+ description?: string;
+ isLabelHidden?: boolean;
+ isDisabled?: boolean;
+ disabledMessage?: string;
+ isLoading?: boolean;
+ isReadOnly?: boolean;
+ isRequired?: boolean;
+ status?: {type: 'error' | 'warning' | 'success'; message: string};
+}) {
+ const [value, setValue] = useState<boolean | 'indeterminate'>(initial);
+ return (
+ <CheckboxInput
+ {...props}
+ value={value}
+ onChange={hasChangeHandler ? setValue : undefined}
+ />
+ );
+}
+
+function InheritedRequiredInput() {
+ return (
+ <FormLayout defaultOptionality="required">
+ <ControlledInput initial={false} label="Marketing consent" />
+ </FormLayout>
+ );
+}
+
+function StandaloneListItem({
+ initial,
+ label,
+ description,
+ isDisabled,
+ isLoading,
+ plainLabel = false,
+ omitAriaLabel = false,
+}: {
+ initial: boolean | 'indeterminate';
+ label: string;
+ description?: ReactNode;
+ isDisabled?: boolean;
+ isLoading?: boolean;
+ plainLabel?: boolean;
+ omitAriaLabel?: boolean;
+}) {
+ const [checked, setChecked] = useState<boolean | 'indeterminate'>(initial);
+ return (
+ <List>
+ <CheckboxListItem
+ data-a11y-visible-label={plainLabel || undefined}
+ label={plainLabel ? label : <VisibleLabel>{label}</VisibleLabel>}
+ aria-label={plainLabel || omitAriaLabel ? undefined : label}
+ description={description}
+ isChecked={checked}
+ onCheck={setChecked}
+ isDisabled={isDisabled}
+ isLoading={isLoading}
+ />
+ </List>
+ );
+}
+
+function CollectionListItem({initial}: {initial: boolean}) {
+ const [value, setValue] = useState<string[]>(initial ? ['email'] : []);
+ return (
+ <CheckboxList
+ label="Notification methods"
+ value={value}
+ onChange={setValue}>
+ <CheckboxListItem
+ label={<VisibleLabel>Email</VisibleLabel>}
+ aria-label="Email"
+ value="email"
+ />
+ </CheckboxList>
+ );
+}
+
+function ReadOnlyCollectionListItem() {
+ return (
+ <CheckboxList label="Notification methods" value={['email']} isReadOnly>
+ <CheckboxListItem data-a11y-visible-label label="Email" value="email" />
+ </CheckboxList>
+ );
+}
+
+function HandlerlessListItem() {
+ return (
+ <List>
+ <CheckboxListItem
+ data-a11y-visible-label
+ label="Completed task"
+ isChecked
+ />
+ </List>
+ );
+}
+
+function GroupDisabledListItem() {
+ return (
+ <CheckboxList
+ label="Notification methods"
+ value={['email']}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="Managed by your administrator">
+ <CheckboxListItem
+ label={<VisibleLabel>Email</VisibleLabel>}
+ aria-label="Email"
+ value="email"
+ />
+ </CheckboxList>
+ );
+}
+
+function MenuCheckbox({
+ initial,
+ isDisabled = false,
+ description,
+ hasChangeHandler = true,
+}: {
+ initial: boolean;
+ isDisabled?: boolean;
+ description?: ReactNode;
+ hasChangeHandler?: boolean;
+}) {
+ const [value, setValue] = useState(initial);
+ return (
+ <DropdownMenu button={{label: 'View options'}}>
+ <DropdownMenuCheckboxItem
+ label="Show archived"
+ description={description}
+ value={value}
+ onChange={hasChangeHandler ? setValue : undefined}
+ isDisabled={isDisabled}
+ />
+ </DropdownMenu>
+ );
+}
+
+function ControlledCard({
+ initial,
+ isDisabled = false,
+}: {
+ initial: boolean;
+ isDisabled?: boolean;
+}) {
+ const [selected, setSelected] = useState(initial);
+ return (
+ <SelectableCard
+ data-a11y-pointer-target
+ label="Analytics"
+ isSelected={selected}
+ onChange={setSelected}
+ isDisabled={isDisabled}>
+ <VisibleLabel>Analytics</VisibleLabel>
+ </SelectableCard>
+ );
+}
+
+export type CheckboxStateRender = () => ReactElement;
+
+export const CHECKBOX_STATE_RENDERS: Record<
+ CheckboxStateId,
+ CheckboxStateRender
+> = {
+ 'input-unchecked': () => (
+ <ControlledInput initial={false} label="Email notifications" />
+ ),
+ 'input-checked': () => (
+ <ControlledInput initial={true} label="Email notifications" />
+ ),
+ 'input-mixed': () => (
+ <ControlledInput initial="indeterminate" label="Select all notifications" />
+ ),
+ 'input-described': () => (
+ <ControlledInput
+ initial={false}
+ label="Share usage data"
+ description="Help improve the product"
+ />
+ ),
+ 'input-hidden-label': () => (
+ <ControlledInput initial={false} label="Select row" isLabelHidden />
+ ),
+ 'input-disabled': () => (
+ <ControlledInput initial={false} label="Managed setting" isDisabled />
+ ),
+ 'input-disabled-with-message': () => (
+ <ControlledInput
+ initial={false}
+ label="Managed setting"
+ isDisabled
+ disabledMessage="Managed by your administrator"
+ />
+ ),
+ 'input-loading': () => (
+ <ControlledInput initial={false} label="Email notifications" isLoading />
+ ),
+ 'input-read-only': () => (
+ <ControlledInput initial={true} label="Policy acknowledged" isReadOnly />
+ ),
+ 'input-handlerless-read-only': () => (
+ <ControlledInput
+ initial={true}
+ label="Policy acknowledged"
+ hasChangeHandler={false}
+ />
+ ),
+ 'input-required': () => (
+ <ControlledInput initial={false} label="Accept terms" isRequired />
+ ),
+ 'input-inherited-required-valid': () => <InheritedRequiredInput />,
+ 'input-invalid': () => (
+ <ControlledInput
+ initial={false}
+ label="Accept terms"
+ status={{type: 'error', message: 'You must accept the terms'}}
+ />
+ ),
+ 'input-warning': () => (
+ <ControlledInput
+ initial={false}
+ label="Enable sharing"
+ status={{type: 'warning', message: 'This setting affects all workspaces'}}
+ />
+ ),
+ 'input-success': () => (
+ <ControlledInput
+ initial={true}
+ label="Email notifications"
+ status={{type: 'success', message: 'Preference saved'}}
+ />
+ ),
+
+ 'list-item-unchecked': () => (
+ <StandaloneListItem initial={false} label="Email" plainLabel />
+ ),
+ 'list-item-checked': () => <CollectionListItem initial />,
+ 'list-item-mixed': () => (
+ <StandaloneListItem initial="indeterminate" label="Select all" />
+ ),
+ 'list-item-described': () => (
+ <StandaloneListItem
+ initial={false}
+ label="Email"
+ description="Receive notifications by email"
+ />
+ ),
+ 'list-item-rich-label-missing-name': () => (
+ <StandaloneListItem initial={false} label="Pro plan" omitAriaLabel />
+ ),
+ 'list-item-disabled': () => (
+ <StandaloneListItem initial={false} label="SMS" isDisabled />
+ ),
+ 'list-item-loading': () => (
+ <StandaloneListItem initial={false} label="Push notifications" isLoading />
+ ),
+ 'list-item-read-only': () => <ReadOnlyCollectionListItem />,
+ 'list-item-handlerless-read-only': () => <HandlerlessListItem />,
+ 'list-item-group-disabled-with-message': () => <GroupDisabledListItem />,
+
+ 'menu-item-unchecked': () => <MenuCheckbox initial={false} />,
+ 'menu-item-checked': () => <MenuCheckbox initial />,
+ 'menu-item-described': () => (
+ <MenuCheckbox initial={false} description="Include unpublished items" />
+ ),
+ 'menu-item-handlerless-inert': () => (
+ <MenuCheckbox initial={false} hasChangeHandler={false} />
+ ),
+ 'menu-item-disabled': () => <MenuCheckbox initial={false} isDisabled />,
+
+ 'card-unchecked': () => <ControlledCard initial={false} />,
+ 'card-checked': () => <ControlledCard initial />,
+ 'card-disabled': () => <ControlledCard initial={false} isDisabled />,
+};
diff --git a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.states.ts b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.states.ts
new file mode 100644
index 0000000000..8be921414e
--- /dev/null
+++ b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.states.ts
@@ -0,0 +1,414 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Checkbox.a11y.states.ts
+ * @input Uses CheckboxStateFacts from @astryxdesign/a11y-spec
+ * @output CHECKBOX_BINDING_STATES — the AST-021 inventory for every current
+ * checkbox-bearing Astryx part and every state that changes the shared pattern
+ * outcome — plus CHECKBOX_CALLEE_EXCLUSIONS for composed/decorative callsites
+ * that reuse an already-bound part without exposing another checkbox control.
+ * @position Data-only binding inventory. JSX lives in Checkbox.a11y.renders.tsx
+ * so Playwright can import this file without loading component source.
+ */
+
+import type {CheckboxStateFacts} from '@astryxdesign/a11y-spec';
+
+export type CheckboxBinding =
+ | 'CheckboxInput'
+ | 'CheckboxListItem'
+ | 'DropdownMenuCheckboxItem'
+ | 'SelectableCard';
+
+export type CheckboxBindingRow = (typeof CHECKBOX_BINDING_STATES)[number];
+export type CheckboxStateId = (typeof CHECKBOX_BINDING_STATES)[number]['id'];
+
+export interface CheckboxBindingState {
+ readonly id: string;
+ readonly binding: CheckboxBinding;
+ readonly summary: string;
+ readonly facts: CheckboxStateFacts;
+ readonly visibleLabel: string | null;
+ readonly visibleLabelSelector?: string;
+ readonly pointerTargetSelector?: string;
+ readonly storyId: string;
+ readonly opensMenu?: boolean;
+ readonly declaredNotDelivered?: ReadonlyArray<{
+ readonly fact:
+ 'description' | 'disabled' | 'focusable' | 'invalid' | 'readOnly';
+ readonly owned: string;
+ }>;
+}
+
+const DEFAULT_FACTS: CheckboxStateFacts = {
+ role: 'checkbox',
+ checked: false,
+ operable: true,
+ focusable: true,
+ disabled: false,
+ description: null,
+ readOnly: false,
+ required: false,
+ invalid: false,
+};
+
+function facts(
+ overrides: Partial<CheckboxStateFacts> = {},
+): CheckboxStateFacts {
+ return {...DEFAULT_FACTS, ...overrides};
+}
+
+const menuFacts = (
+ overrides: Partial<CheckboxStateFacts> = {},
+): CheckboxStateFacts =>
+ facts({
+ role: 'menuitemcheckbox',
+ focusable: false,
+ ...overrides,
+ });
+
+export const CHECKBOX_CALLEE_EXCLUSIONS = [
+ {
+ owner: 'Table selection',
+ part: 'CheckboxInput',
+ reason:
+ 'Table select-all and row selection compose the already-bound CheckboxInput part; Table owns selection labels and group context, while the shared input states cover hidden labels and mixed state.',
+ },
+ {
+ owner: 'MultiSelector option decoration',
+ part: 'CheckboxInput',
+ reason:
+ 'MultiSelector renders its CheckboxInput inside an inert, aria-hidden marker; role="option" remains the only exposed selectable control and the decorative checkbox is outside this pattern inventory.',
+ },
+] as const;
+
+export const CHECKBOX_BINDING_STATES = [
+ {
+ id: 'input-unchecked',
+ binding: 'CheckboxInput',
+ summary: 'the default unchecked checkbox with a visible label',
+ facts: facts(),
+ visibleLabel: 'Email notifications',
+ storyId: 'a11y-checkbox-pattern--input-unchecked',
+ },
+ {
+ id: 'input-checked',
+ binding: 'CheckboxInput',
+ summary: 'the same checkbox checked',
+ facts: facts({checked: true}),
+ visibleLabel: 'Email notifications',
+ storyId: 'a11y-checkbox-pattern--input-checked',
+ },
+ {
+ id: 'input-mixed',
+ binding: 'CheckboxInput',
+ summary: 'a tri-state select-all checkbox in its partially checked state',
+ facts: facts({checked: 'mixed'}),
+ visibleLabel: 'Select all notifications',
+ storyId: 'a11y-checkbox-pattern--input-mixed',
+ },
+ {
+ id: 'input-described',
+ binding: 'CheckboxInput',
+ summary: 'a checkbox with supporting text attached',
+ facts: facts({description: 'Help improve the product'}),
+ visibleLabel: 'Share usage data',
+ storyId: 'a11y-checkbox-pattern--input-described',
+ },
+ {
+ id: 'input-hidden-label',
+ binding: 'CheckboxInput',
+ summary: 'a checkbox named by a visually hidden associated label',
+ facts: facts(),
+ visibleLabel: null,
+ storyId: 'a11y-checkbox-pattern--input-hidden-label',
+ },
+ {
+ id: 'input-disabled',
+ binding: 'CheckboxInput',
+ summary: 'a natively disabled checkbox outside the tab sequence',
+ facts: facts({operable: false, focusable: false, disabled: true}),
+ visibleLabel: 'Managed setting',
+ storyId: 'a11y-checkbox-pattern--input-disabled',
+ },
+ {
+ id: 'input-disabled-with-message',
+ binding: 'CheckboxInput',
+ summary:
+ 'an unavailable checkbox kept focusable so its attached reason remains reachable',
+ facts: facts({
+ operable: false,
+ disabled: true,
+ description: 'Managed by your administrator',
+ }),
+ visibleLabel: 'Managed setting',
+ storyId: 'a11y-checkbox-pattern--input-disabled-with-message',
+ },
+ {
+ id: 'input-loading',
+ binding: 'CheckboxInput',
+ summary: 'a busy checkbox that stays focusable but refuses another change',
+ // Loading is inventoried because it changes operability. The public
+ // isLoading -> aria-busy mapping remains in CheckboxInput.test.tsx under
+ // AST-021 FR5: APG Checkbox adopts no busy state, and no current Astryx
+ // record makes it a reusable checkbox-pattern requirement.
+ facts: facts({operable: false}),
+ visibleLabel: 'Email notifications',
+ storyId: 'a11y-checkbox-pattern--input-loading',
+ },
+ {
+ id: 'input-read-only',
+ binding: 'CheckboxInput',
+ summary: 'a read-only checkbox that stays focusable and cannot change',
+ facts: facts({checked: true, operable: false, readOnly: true}),
+ visibleLabel: 'Policy acknowledged',
+ storyId: 'a11y-checkbox-pattern--input-read-only',
+ },
+ {
+ id: 'input-handlerless-read-only',
+ binding: 'CheckboxInput',
+ summary:
+ 'a handlerless controlled checkbox that is inert but does not declare read-only semantics',
+ facts: facts({checked: true, operable: false, readOnly: true}),
+ visibleLabel: 'Policy acknowledged',
+ storyId: 'a11y-checkbox-pattern--input-handlerless-read-only',
+ declaredNotDelivered: [
+ {fact: 'readOnly', owned: 'checkbox.readonly.declared'},
+ ],
+ },
+ {
+ id: 'input-required',
+ binding: 'CheckboxInput',
+ summary: 'a checkbox declared required',
+ facts: facts({required: true, invalid: true}),
+ visibleLabel: 'Accept terms',
+ storyId: 'a11y-checkbox-pattern--input-required',
+ },
+ {
+ id: 'input-inherited-required-valid',
+ binding: 'CheckboxInput',
+ summary:
+ 'an unchecked checkbox inheriting required semantics without native validation',
+ facts: facts({required: true}),
+ visibleLabel: 'Marketing consent',
+ storyId: 'a11y-checkbox-pattern--input-inherited-required-valid',
+ },
+ {
+ id: 'input-invalid',
+ binding: 'CheckboxInput',
+ summary: 'a checkbox whose current value is in error',
+ facts: facts({
+ invalid: true,
+ description: 'You must accept the terms',
+ }),
+ visibleLabel: 'Accept terms',
+ storyId: 'a11y-checkbox-pattern--input-invalid',
+ },
+ {
+ id: 'input-warning',
+ binding: 'CheckboxInput',
+ summary: 'a valid checkbox with warning supporting text',
+ facts: facts({description: 'This setting affects all workspaces'}),
+ visibleLabel: 'Enable sharing',
+ storyId: 'a11y-checkbox-pattern--input-warning',
+ },
+ {
+ id: 'input-success',
+ binding: 'CheckboxInput',
+ summary: 'a valid checkbox with success supporting text',
+ facts: facts({checked: true, description: 'Preference saved'}),
+ visibleLabel: 'Email notifications',
+ storyId: 'a11y-checkbox-pattern--input-success',
+ },
+
+ {
+ id: 'list-item-unchecked',
+ binding: 'CheckboxListItem',
+ summary: 'a standalone checkbox list item',
+ facts: facts(),
+ visibleLabel: 'Email',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ storyId: 'a11y-checkbox-pattern--list-item-unchecked',
+ },
+ {
+ id: 'list-item-checked',
+ binding: 'CheckboxListItem',
+ summary: 'a checked item in a controlled CheckboxList collection',
+ facts: facts({checked: true}),
+ visibleLabel: 'Email',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ storyId: 'a11y-checkbox-pattern--list-item-checked',
+ },
+ {
+ id: 'list-item-mixed',
+ binding: 'CheckboxListItem',
+ summary: 'a standalone partially checked list item',
+ facts: facts({checked: 'mixed'}),
+ visibleLabel: 'Select all',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ storyId: 'a11y-checkbox-pattern--list-item-mixed',
+ },
+ {
+ id: 'list-item-described',
+ binding: 'CheckboxListItem',
+ summary: 'a list item with visible supporting text for the choice',
+ facts: facts({description: 'Receive notifications by email'}),
+ visibleLabel: 'Email',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ storyId: 'a11y-checkbox-pattern--list-item-described',
+ declaredNotDelivered: [
+ {fact: 'description', owned: 'checkbox.description.resolvable'},
+ ],
+ },
+ {
+ id: 'list-item-rich-label-missing-name',
+ binding: 'CheckboxListItem',
+ summary:
+ 'a rich-label list item with no equivalent plain-text accessible name',
+ facts: facts(),
+ visibleLabel: 'Pro plan',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ storyId: 'a11y-checkbox-pattern--list-item-rich-label-missing-name',
+ },
+ {
+ id: 'list-item-disabled',
+ binding: 'CheckboxListItem',
+ summary: 'an individually disabled list item',
+ facts: facts({operable: false, focusable: false, disabled: true}),
+ visibleLabel: 'SMS',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ storyId: 'a11y-checkbox-pattern--list-item-disabled',
+ },
+ {
+ id: 'list-item-loading',
+ binding: 'CheckboxListItem',
+ summary: 'a busy list item that stays focusable but refuses another change',
+ // The list row's aria-busy and spinner composition remain component-owned;
+ // this pattern row covers the shared checkbox's changed operability.
+ facts: facts({operable: false}),
+ visibleLabel: 'Push notifications',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ storyId: 'a11y-checkbox-pattern--list-item-loading',
+ },
+ {
+ id: 'list-item-read-only',
+ binding: 'CheckboxListItem',
+ summary: 'a read-only list item that stays focusable and cannot change',
+ facts: facts({checked: true, operable: false, readOnly: true}),
+ visibleLabel: 'Email',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ storyId: 'a11y-checkbox-pattern--list-item-read-only',
+ },
+ {
+ id: 'list-item-handlerless-read-only',
+ binding: 'CheckboxListItem',
+ summary:
+ 'a standalone handlerless item that is inert but does not declare read-only semantics',
+ facts: facts({checked: true, operable: false, readOnly: true}),
+ visibleLabel: 'Completed task',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ storyId: 'a11y-checkbox-pattern--list-item-handlerless-read-only',
+ declaredNotDelivered: [
+ {fact: 'readOnly', owned: 'checkbox.readonly.declared'},
+ ],
+ },
+ {
+ id: 'list-item-group-disabled-with-message',
+ binding: 'CheckboxListItem',
+ summary:
+ 'an item in an unavailable group, kept focusable so the group reason is discoverable',
+ facts: facts({checked: true, operable: false, disabled: true}),
+ visibleLabel: 'Email',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ storyId: 'a11y-checkbox-pattern--list-item-group-disabled-with-message',
+ },
+
+ {
+ id: 'menu-item-unchecked',
+ binding: 'DropdownMenuCheckboxItem',
+ summary:
+ 'an unchecked menu checkbox item; the menu contract owns composite focus and keys',
+ facts: menuFacts(),
+ visibleLabel: 'Show archived',
+ storyId: 'a11y-checkbox-pattern--menu-item-unchecked',
+ opensMenu: true,
+ },
+ {
+ id: 'menu-item-checked',
+ binding: 'DropdownMenuCheckboxItem',
+ summary: 'a checked menu checkbox item',
+ facts: menuFacts({checked: true}),
+ visibleLabel: 'Show archived',
+ storyId: 'a11y-checkbox-pattern--menu-item-checked',
+ opensMenu: true,
+ },
+ {
+ id: 'menu-item-described',
+ binding: 'DropdownMenuCheckboxItem',
+ summary:
+ 'a menu checkbox item whose secondary row text participates in its visible name',
+ facts: menuFacts(),
+ visibleLabel: 'Show archived Include unpublished items',
+ storyId: 'a11y-checkbox-pattern--menu-item-described',
+ opensMenu: true,
+ },
+ {
+ id: 'menu-item-handlerless-inert',
+ binding: 'DropdownMenuCheckboxItem',
+ summary:
+ 'a handlerless menu checkbox that does nothing but is not exposed as unavailable',
+ facts: menuFacts({operable: false, disabled: true}),
+ visibleLabel: 'Show archived',
+ storyId: 'a11y-checkbox-pattern--menu-item-handlerless-inert',
+ opensMenu: true,
+ declaredNotDelivered: [
+ {fact: 'disabled', owned: 'checkbox.disabled.exposed'},
+ ],
+ },
+ {
+ id: 'menu-item-disabled',
+ binding: 'DropdownMenuCheckboxItem',
+ summary: 'an unavailable menu checkbox item',
+ facts: menuFacts({operable: false, disabled: true}),
+ visibleLabel: 'Show archived',
+ storyId: 'a11y-checkbox-pattern--menu-item-disabled',
+ opensMenu: true,
+ },
+
+ {
+ id: 'card-unchecked',
+ binding: 'SelectableCard',
+ summary: 'an independently selectable card, unchecked',
+ facts: facts(),
+ visibleLabel: 'Analytics',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ pointerTargetSelector: '[data-a11y-pointer-target]',
+ storyId: 'a11y-checkbox-pattern--card-unchecked',
+ },
+ {
+ id: 'card-checked',
+ binding: 'SelectableCard',
+ summary: 'the same selectable card checked',
+ facts: facts({checked: true}),
+ visibleLabel: 'Analytics',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ pointerTargetSelector: '[data-a11y-pointer-target]',
+ storyId: 'a11y-checkbox-pattern--card-checked',
+ },
+ {
+ id: 'card-disabled',
+ binding: 'SelectableCard',
+ summary:
+ 'an unavailable selectable card whose public prop contract promises continued keyboard reachability',
+ facts: facts({operable: false, disabled: true}),
+ visibleLabel: 'Analytics',
+ visibleLabelSelector: '[data-a11y-visible-label]',
+ pointerTargetSelector: '[data-a11y-pointer-target]',
+ storyId: 'a11y-checkbox-pattern--card-disabled',
+ declaredNotDelivered: [
+ {
+ fact: 'focusable',
+ owned: 'checkbox.focus.declared-inoperable-reachable',
+ },
+ ],
+ },
+] as const satisfies ReadonlyArray<CheckboxBindingState>;
diff --git a/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.test.tsx b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.test.tsx
new file mode 100644
index 0000000000..28e31dc4f4
--- /dev/null
+++ b/packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.test.tsx
@@ -0,0 +1,115 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file Checkbox.a11y.test.tsx
+ * @input Uses the shared checkbox contract, the jsdom harness, and the complete
+ * binding inventory and render map.
+ * @output DOM-layer binding evidence for CheckboxInput, CheckboxListItem,
+ * DropdownMenuCheckboxItem, and SelectableCard.
+ * @position Fast migration lane. Browser-owned outcomes remain explicitly unrun.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {cleanup, render, screen} from '@testing-library/react';
+import {
+ CHECKBOX_PATTERN,
+ blockingResults,
+ createJsdomHarness,
+ formatFailures,
+ runBinding,
+ summarize,
+ type BindingResult,
+} from '@astryxdesign/a11y-spec';
+import {CHECKBOX_KNOWN_FAILURES} from './Checkbox.a11y.known-failures';
+import {CHECKBOX_STATE_RENDERS} from './Checkbox.a11y.renders';
+import {
+ CHECKBOX_BINDING_STATES,
+ CHECKBOX_CALLEE_EXCLUSIONS,
+ type CheckboxBindingRow,
+} from './Checkbox.a11y.states';
+
+function subjectFor(state: CheckboxBindingRow): Element {
+ return screen.getByRole(state.facts.role, {hidden: true});
+}
+
+async function runState(state: CheckboxBindingRow): Promise<BindingResult> {
+ return runBinding({
+ contract: CHECKBOX_PATTERN,
+ binding: state.binding,
+ state: state.id,
+ facts: state.facts,
+ knownFailures: CHECKBOX_KNOWN_FAILURES,
+ mount: async () => {
+ render(CHECKBOX_STATE_RENDERS[state.id]());
+ return createJsdomHarness({subject: subjectFor(state)});
+ },
+ unmount: cleanup,
+ });
+}
+
+describe('the shared checkbox pattern, jsdom lane', () => {
+ it.each(
+ CHECKBOX_BINDING_STATES.map(
+ state =>
+ [`${state.binding} [${state.id}]`, state.summary, state] as const,
+ ),
+ )('%s — %s', async (_id, _summary, state) => {
+ const result = await runState(state);
+ expect(formatFailures(blockingResults([result]))).toBe('');
+ });
+
+ it('runs the DOM layer here and reports higher layers as unrun', async () => {
+ const results: BindingResult[] = [];
+ for (const state of CHECKBOX_BINDING_STATES) {
+ results.push(await runState(state));
+ }
+ const report = summarize(CHECKBOX_PATTERN, results);
+ expect(report.counts.pass).toBeGreaterThan(0);
+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+});
+
+describe('the checkbox binding inventory', () => {
+ it('names a distinct checked-in story for every state', () => {
+ const ids = CHECKBOX_BINDING_STATES.map(state => state.storyId);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it('binds every checkbox-bearing public part with its own semantics', () => {
+ const bound = new Set(CHECKBOX_BINDING_STATES.map(state => state.binding));
+ expect([...bound].sort()).toEqual([
+ 'CheckboxInput',
+ 'CheckboxListItem',
+ 'DropdownMenuCheckboxItem',
+ 'SelectableCard',
+ ]);
+ });
+
+ it('records composed and decorative CheckboxInput callsites explicitly', () => {
+ expect(CHECKBOX_CALLEE_EXCLUSIONS).toEqual([
+ expect.objectContaining({
+ owner: 'Table selection',
+ part: 'CheckboxInput',
+ }),
+ expect.objectContaining({
+ owner: 'MultiSelector option decoration',
+ part: 'CheckboxInput',
+ }),
+ ]);
+ expect(
+ CHECKBOX_CALLEE_EXCLUSIONS.every(
+ exclusion => exclusion.reason.length > 0,
+ ),
+ ).toBe(true);
+ });
+
+ it('renders exactly one role-bearing subject for every state', () => {
+ for (const state of CHECKBOX_BINDING_STATES) {
+ render(CHECKBOX_STATE_RENDERS[state.id]());
+ expect(subjectFor(state), state.id).toBeTruthy();
+ cleanup();
+ }
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx
index 95a0a621b6..3c051b28c2 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx
@@ -4,6 +4,8 @@
* @file DropdownMenuSelectable.test.tsx
* @input vitest, @testing-library/react, DropdownMenu + selectable items
* @output Unit tests for DropdownMenuCheckboxItem / RadioGroup / RadioItem (#3829)
+ * @position Component-local callback and composition coverage; shared checkbox
+ * role, name, state, and interaction outcomes live in the reusable contract.
*/
import {describe, it, expect, vi, beforeEach} from 'vitest';
@@ -41,22 +43,6 @@ beforeEach(() => {
});
describe('DropdownMenuCheckboxItem', () => {
- it('renders role menuitemcheckbox and reflects checked state', async () => {
- const user = userEvent.setup();
- render(
- <DropdownMenu button={{label: 'View'}}>
- <DropdownMenuCheckboxItem label="Show archived" value={true} />
- </DropdownMenu>,
- );
- await user.click(screen.getByRole('button', {name: /View/}));
- expect(
- screen.getByRole('menuitemcheckbox', {
- name: /Show archived/,
- hidden: true,
- }),
- ).toHaveAttribute('aria-checked', 'true');
- });
-
it('calls onChange with the toggled value on click', async () => {
const user = userEvent.setup();
const onChangeSpy = vi.fn();
diff --git a/packages/core/src/SelectableCard/SelectableCard.test.tsx b/packages/core/src/SelectableCard/SelectableCard.test.tsx
index 2a0274a78c..603fa2ab34 100644
--- a/packages/core/src/SelectableCard/SelectableCard.test.tsx
+++ b/packages/core/src/SelectableCard/SelectableCard.test.tsx
@@ -1,5 +1,13 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file SelectableCard.test.tsx
+ * @input Uses vitest, Testing Library, and SelectableCard
+ * @output Component-specific callback, keyboard extension, and styling tests;
+ * shared checkbox semantics live under CheckboxInput/__tests__.
+ * @position Local behavior coverage that remains after AST-021 migration.
+ */
+
import {describe, it, expect, vi} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
import {SelectableCard} from './SelectableCard';
@@ -14,36 +22,6 @@ describe('SelectableCard', () => {
expect(screen.getByText('Card content')).toBeInTheDocument();
});
- it('renders a hidden checkbox', () => {
- render(
- <SelectableCard label="Test" isSelected={false} onChange={() => {}}>
- Content
- </SelectableCard>,
- );
- const checkbox = screen.getByRole('checkbox', {name: 'Test'});
- expect(checkbox).toBeInTheDocument();
- });
-
- it('checkbox reflects isSelected=true as checked', () => {
- render(
- <SelectableCard label="Plan A" isSelected={true} onChange={() => {}}>
- Content
- </SelectableCard>,
- );
- const checkbox = screen.getByRole('checkbox', {name: 'Plan A'});
- expect(checkbox).toBeChecked();
- });
-
- it('checkbox reflects isSelected=false as unchecked', () => {
- render(
- <SelectableCard label="Plan B" isSelected={false} onChange={() => {}}>
- Content
- </SelectableCard>,
- );
- const checkbox = screen.getByRole('checkbox', {name: 'Plan B'});
- expect(checkbox).not.toBeChecked();
- });
-
it('calls onChange with true when card surface is clicked (unselected)', () => {
const handleChange = vi.fn();
render(
@@ -78,21 +56,6 @@ describe('SelectableCard', () => {
expect(handleChange).toHaveBeenCalledWith(true);
});
- it('disabled checkbox is disabled', () => {
- const handleChange = vi.fn();
- render(
- <SelectableCard
- label="Disabled"
- isSelected={false}
- onChange={handleChange}
- isDisabled>
- Content
- </SelectableCard>,
- );
- const checkbox = screen.getByRole('checkbox', {name: 'Disabled'});
- expect(checkbox).toBeDisabled();
- });
-
it('does not call onChange when disabled card is clicked', () => {
const handleChange = vi.fn();
render(
diff --git a/packages/core/src/Switch/__tests__/Switch.a11y.chromium.spec.ts b/packages/core/src/Switch/__tests__/Switch.a11y.chromium.spec.ts
index 53f99051f5..d4d0d9818a 100644
--- a/packages/core/src/Switch/__tests__/Switch.a11y.chromium.spec.ts
+++ b/packages/core/src/Switch/__tests__/Switch.a11y.chromium.spec.ts
@@ -29,6 +29,7 @@ import {
runBinding,
spokenWords,
summarize,
+ unmatchedKnownFailures,
type BindingResult,
} from '@astryxdesign/a11y-spec';
import {
@@ -181,6 +182,7 @@ test('every expectation is exercised by at least one bound state', async ({
// looks. This is the only place that can notice: the contract never sees the
// states, so whether a condition matches a real one is a binding-side fact.
expect(neverExercised(results)).toEqual([]);
+ expect(unmatchedKnownFailures(SWITCH_KNOWN_FAILURES, results)).toEqual([]);
});
for (const state of SWITCH_BINDING_STATES) {