Skip to content

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

TypeScript

test(a11y): add toggle-button accessibility contract (#6749)

Cindy Zhang5cd16b69d28a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ee9ed2ef49..87a3e7ecf4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1243,6 +1243,55 @@ jobs:
retention-days: 30
if-no-files-found: ignore
+ # The toggle-button contract's pressed state, keyboard and pointer round
+ # trips, aborted press, focus, and unavailable state are accessibility-tree
+ # and engine facts that jsdom cannot observe. Run the contract's own
+ # fixture proof and the ToggleButton binding whenever the PR scope names
+ # ToggleButton or the contract changes. Its own --output directory; the
+ # JSON report is the head-bound record, uploaded immediately after.
+ - name: Run ToggleButton accessibility contract
+ id: toggle-button-contract
+ if: github.event_name == 'pull_request'
+ env:
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ PLAYWRIGHT_JSON_OUTPUT_FILE: toggle-button-contract/report.json
+ run: |
+ should_run=false
+ COMPONENTS=$(node .github/scripts/a11y-pr-scope.mjs analysis.json)
+ case ",${COMPONENTS}," in
+ *,core/ToggleButton,*) should_run=true ;;
+ esac
+ # The contract belongs to no package, so compare file names with the
+ # base. If the base cannot be fetched, run the evidence.
+ if git fetch --quiet --depth=1 origin "$BASE_SHA"; then
+ if git diff --name-only "$BASE_SHA" HEAD \
+ | grep -qE '^internal/a11y-spec/src/patterns/toggle-button'; then
+ should_run=true
+ fi
+ else
+ should_run=true
+ fi
+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"
+ if [ "$should_run" != true ]; then
+ echo "ToggleButton and its contract are not in PR scope; skipping toggle-button evidence."
+ exit 0
+ fi
+ pnpm exec playwright test \
+ internal/a11y-spec/src/patterns/toggle-button.chromium.spec.ts \
+ packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.ts \
+ --project chromium \
+ --reporter list,json \
+ --output toggle-button-contract-output
+
+ - name: Upload ToggleButton accessibility contract evidence
+ if: ${{ !cancelled() && steps.toggle-button-contract.outputs.should_run == 'true' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: toggle-button-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: toggle-button-contract/
+ retention-days: 30
+ if-no-files-found: warn
+
# The Schedule time grid owns scroll geometry — pinned header and gutter
# alignment under classic scrollbars, inline scroll ownership, keyboard
# reach and its focus ring — none of which exists in jsdom. Every
diff --git a/apps/storybook/stories/ToggleButtonDisabledA11y.stories.tsx b/apps/storybook/stories/ToggleButtonDisabledA11y.stories.tsx
deleted file mode 100644
index 99b4d0cdd4..0000000000
--- a/apps/storybook/stories/ToggleButtonDisabledA11y.stories.tsx
+++ /dev/null
@@ -1,177 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file ToggleButtonDisabledA11y.stories.tsx
- * @input Uses ToggleButton and ToggleButtonGroup from core
- * @output The four disabled/enabled fixtures the ToggleButton disabled-state
- * regression spec drives in a real browser.
- * @position The reproduction path for
- * `packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.ts`
- * (`docs/specs/AST-009/spec.md` FR30: a browser claim is checked against a
- * checked-in story, not a page a test builds and throws away).
- *
- * Each story counts its own activations and publishes the count as
- * `data-a11y-activations`, so a person opening the story reads the same number
- * the spec does. A toggle that refuses a press leaves no trace on itself, so
- * counting the handler is the only honest way to ask whether pressing it did
- * anything.
- *
- * The two disabled fixtures cover the two halves of `docs/families/buttons.md`
- * FR3 that regressed together: a member's own disabled state must survive an
- * enabled group, and a disabled toggle kept focusable by a tooltip must still
- * refuse a pointer press. The two enabled fixtures are the control — they fail
- * if a fix over-disables.
- *
- * SYNC: The spec navigates to these story ids by name. Nothing at compile time
- * catches a renamed export — the Chromium spec does, when it finds no story.
- */
-
-import {useState, type ReactNode} from 'react';
-import type {Meta, StoryObj} from '@storybook/react';
-import {ToggleButton, ToggleButtonGroup} from '@astryxdesign/core/ToggleButton';
-
-/** Render one fixture and count how many times its handler ran. */
-function Counted({
- children,
-}: {
- children: (activate: () => void) => ReactNode;
-}): ReactNode {
- const [count, setCount] = useState(0);
- return (
- <div data-a11y-activations={count}>
- {children(() => {
- setCount(current => current + 1);
- })}
- <p>
- activations: <output>{count}</output>
- </p>
- </div>
- );
-}
-
-const meta: Meta = {
- title: 'a11y/ToggleButton disabled state',
- // These fixtures exist to be DRIVEN by the regression spec, not photographed:
- // a disabled control inside an enabled group is a state no product ships on
- // purpose, so a baseline frame would be a picture nobody reviews. Excluding
- // them costs no coverage — every one is still driven in a real browser.
- tags: ['no-visual'],
- parameters: {
- docs: {
- description: {
- component:
- 'Disabled-state fixtures for ToggleButton and ToggleButtonGroup. Each story counts its own activations, because a toggle that refuses a press leaves no trace of having been pressed.',
- },
- },
- },
-};
-
-export default meta;
-
-/**
- * A member that disables itself, inside a group that does not disable anything.
- * The group must not hand the member its availability back.
- */
-export const GroupEnabledMemberDisabled: StoryObj = {
- name: 'group enabled — member disabled',
- render: function Render() {
- const [value, setValue] = useState<string | null>(null);
- return (
- <Counted>
- {activate => (
- <ToggleButtonGroup
- label="View mode"
- value={value}
- onChange={next => {
- activate();
- setValue(next);
- }}>
- <ToggleButton value="list" label="List" isDisabled />
- <ToggleButton value="grid" label="Grid" />
- </ToggleButtonGroup>
- )}
- </Counted>
- );
- },
-};
-
-/**
- * The other half of the same rule: a group that disables everything still
- * disables a member that says nothing about its own availability.
- */
-export const GroupDisabledMemberSilent: StoryObj = {
- name: 'group disabled — member silent',
- render: function Render() {
- const [value, setValue] = useState<string | null>(null);
- return (
- <Counted>
- {activate => (
- <ToggleButtonGroup
- label="View mode"
- value={value}
- isDisabled
- onChange={next => {
- activate();
- setValue(next);
- }}>
- <ToggleButton value="list" label="List" />
- </ToggleButtonGroup>
- )}
- </Counted>
- );
- },
-};
-
-/**
- * A disabled toggle kept focusable by its tooltip, so the reason it is
- * unavailable stays reachable. Focusable is not operable: a pointer press must
- * still be refused.
- */
-export const DisabledWithTooltip: StoryObj = {
- name: 'disabled — kept focusable by a tooltip',
- render: function Render() {
- const [isPressed, setIsPressed] = useState(false);
- return (
- <Counted>
- {activate => (
- <ToggleButton
- label="Bold"
- tooltip="Formatting is locked for this document"
- isDisabled
- isPressed={isPressed}
- onPressedChange={next => {
- activate();
- setIsPressed(next);
- }}
- />
- )}
- </Counted>
- );
- },
-};
-
-/**
- * The control. An enabled toggle carrying the same tooltip must still toggle —
- * this is the story that fails if a fix disables too much.
- */
-export const EnabledWithTooltip: StoryObj = {
- name: 'enabled — with a tooltip',
- render: function Render() {
- const [isPressed, setIsPressed] = useState(false);
- return (
- <Counted>
- {activate => (
- <ToggleButton
- label="Bold"
- tooltip="Bold the selected text"
- isPressed={isPressed}
- onPressedChange={next => {
- activate();
- setIsPressed(next);
- }}
- />
- )}
- </Counted>
- );
- },
-};
diff --git a/apps/storybook/stories/ToggleButtonPatternA11y.stories.tsx b/apps/storybook/stories/ToggleButtonPatternA11y.stories.tsx
new file mode 100644
index 0000000000..0313f2a0a4
--- /dev/null
+++ b/apps/storybook/stories/ToggleButtonPatternA11y.stories.tsx
@@ -0,0 +1,57 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ToggleButtonPatternA11y.stories.tsx
+ * @input Uses the shared ToggleButton accessibility state inventory and render map
+ * @output One checked-in browser fixture per representative state
+ * @position Stable reproduction path for the Chromium contract binding.
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {TOGGLE_BUTTON_STATE_RENDERS} from '../../../packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.renders';
+import {TOGGLE_BUTTON_BINDING_STATES} from '../../../packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.states';
+
+function storyFor(
+ id: (typeof TOGGLE_BUTTON_BINDING_STATES)[number]['id'],
+): StoryObj {
+ const state = TOGGLE_BUTTON_BINDING_STATES.find(
+ candidate => candidate.id === id,
+ );
+ if (state == null) {
+ throw new Error(`no ToggleButton binding state "${id}"`);
+ }
+ return {name: state.summary, render: TOGGLE_BUTTON_STATE_RENDERS[id]};
+}
+
+const meta: Meta = {
+ title: 'a11y/Toggle Button pattern',
+ tags: ['no-visual'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Representative ToggleButton states for the reusable toggle-button accessibility contract.',
+ },
+ },
+ },
+};
+
+export default meta;
+export const StandaloneUnpressed = storyFor('standalone-unpressed');
+export const StandalonePressed = storyFor('standalone-pressed');
+export const IconOnlyUnpressed = storyFor('icon-only-unpressed');
+export const ComposedLabelPressed = storyFor('composed-label-pressed');
+export const DisabledUnpressed = storyFor('disabled-unpressed');
+export const DisabledWithTooltipPressed = storyFor(
+ 'disabled-with-tooltip-pressed',
+);
+export const SingleGroupUnpressed = storyFor('single-group-unpressed');
+export const SingleGroupPressed = storyFor('single-group-pressed');
+export const SingleGroupMemberDisabled = storyFor(
+ 'single-group-member-disabled',
+);
+export const SingleGroupDisabledMemberSilent = storyFor(
+ 'single-group-disabled-member-silent',
+);
+export const MultipleGroupUnpressed = storyFor('multiple-group-unpressed');
+export const MultipleGroupPressed = storyFor('multiple-group-pressed');
diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.md
index c791da0c6d..6f0bdf123d 100644
--- a/internal/a11y-spec/README.md
+++ b/internal/a11y-spec/README.md
@@ -62,6 +62,7 @@ src/
| `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 |
+| `toggle-button` | Toggle-button semantics in the [APG button pattern](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | ToggleButton, including standalone and grouped states |
| `text-input` | Native HTML controls and [WAI-ARIA textbox](https://www.w3.org/TR/wai-aria-1.2/#textbox) | TextInput, TextArea |
| `modal-dialog` | [APG dialog (modal)](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/) | Dialog |
| `status-message` | [WCAG 2.2 Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html) | Toast, FieldStatus, Spinner, ChatSystemMessage, ChatTypingIndicator, ProgressBar |
@@ -71,6 +72,15 @@ src/
| `disclosure` | [APG Disclosure](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/) | Standalone Collapsible triggers and their controlled content |
| `breadcrumb` | WCAG 2.2 semantics; [APG Breadcrumb](https://www.w3.org/WAI/ARIA/apg/patterns/breadcrumb/) as context | Breadcrumbs landmarks, list trails, current-page state, and separators |
+The toggle-button contract owns the persistent-action extension of button
+semantics: the pressed state must be exposed, reversible by pointer, Enter, and
+Space, stable under an aborted press, and inert when unavailable. It also checks
+that changing state keeps focus and reports APG label stability as advisory
+because current Astryx authority does not make that APG-only detail a gate.
+ToggleButtonGroup naming, selection coordination, Action ordering, pending
+feedback, and rendered appearance keep their existing component, family, and
+visual owners.
+
The `spinbutton` contract owns NumberInput's required role, persistent name,
committed numeric value, optional bounds and formatted value text, disabled and
read-only exposure, and keyboard reachability. ArrowUp and ArrowDown stepping
diff --git a/internal/a11y-spec/src/harness.ts b/internal/a11y-spec/src/harness.ts
index f194e79fb0..e022d61d7c 100644
--- a/internal/a11y-spec/src/harness.ts
+++ b/internal/a11y-spec/src/harness.ts
@@ -69,6 +69,8 @@ export interface ComputedNode {
readonly readOnly: boolean | null;
/** Whether the engine exposes the control as required. */
readonly required: boolean | null;
+ /** Computed pressed state for toggle buttons, or null when none is exposed. */
+ readonly pressed: 'true' | 'false' | 'mixed' | null;
/** Computed checked state, or null when the node exposes none. */
readonly checked: 'true' | 'false' | 'mixed' | null;
/** Computed selected state, or null when the node exposes none. */
diff --git a/internal/a11y-spec/src/harness/chromium.ts b/internal/a11y-spec/src/harness/chromium.ts
index 993234373d..11f996ff7d 100644
--- a/internal/a11y-spec/src/harness/chromium.ts
+++ b/internal/a11y-spec/src/harness/chromium.ts
@@ -215,6 +215,7 @@ async function computedNode(
multiline: null,
readOnly: null,
required: null,
+ pressed: null,
checked: null,
selected: null,
disabled: false,
@@ -241,6 +242,7 @@ async function computedNode(
}
}
const live = property(node, 'live');
+ const pressed = property(node, 'pressed');
const checked = property(node, 'checked');
const selected = optionalFlag(node, 'selected');
const invalid = property(node, 'invalid');
@@ -279,6 +281,14 @@ async function computedNode(
multiline: optionalFlag(node, 'multiline'),
readOnly: optionalFlag(node, 'readonly'),
required: optionalFlag(node, 'required'),
+ pressed:
+ pressed === 'true' || pressed === true
+ ? 'true'
+ : pressed === 'false' || pressed === false
+ ? 'false'
+ : pressed === 'mixed'
+ ? 'mixed'
+ : null,
checked:
checked === 'true' || checked === true
? 'true'
diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.ts
index 38ec3b708f..95611c10da 100644
--- a/internal/a11y-spec/src/index.ts
+++ b/internal/a11y-spec/src/index.ts
@@ -118,6 +118,11 @@ export {
type SpinbuttonStateFacts,
} from './patterns/spinbutton';
+export {
+ TOGGLE_BUTTON_PATTERN,
+ type ToggleButtonStateFacts,
+} from './patterns/toggle-button';
+
export {
DISCLOSURE_PATTERN,
type DisclosureStateFacts,
diff --git a/internal/a11y-spec/src/patterns/toggle-button.chromium.spec.ts b/internal/a11y-spec/src/patterns/toggle-button.chromium.spec.ts
new file mode 100644
index 0000000000..2828022627
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/toggle-button.chromium.spec.ts
@@ -0,0 +1,95 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file toggle-button.chromium.spec.ts
+ * @input Uses Playwright, the toggle-button contract, independent fixtures, and Chromium harness
+ * @output Real-browser positive and deliberate-negative proof for every expectation
+ * @position Contract self-test, independent of Astryx component implementation.
+ */
+
+import {expect, test, type CDPSession, type Page} from '@playwright/test';
+import {describeExpectation, requiredLayers} from '../contract';
+import {checkAccessibilitySpec, type ExpectationResult} from '../check';
+import {
+ CHROMIUM_OBSERVES,
+ createChromiumHarness,
+ holdMotionStill,
+} from '../harness/chromium';
+import {TOGGLE_BUTTON_PATTERN} from './toggle-button';
+import {
+ CONFORMING_FIXTURES,
+ SUBJECT_SELECTOR,
+ TOGGLE_BUTTON_MUTATIONS,
+ fixture,
+ type ToggleButtonFixture,
+} from './toggle-button.fixtures';
+
+function fixturePage(html: string): string {
+ return `<!doctype html><html lang="en"><body>${html}<button type="button" id="after">After toggle</button></body></html>`;
+}
+
+async function results(
+ page: Page,
+ cdp: CDPSession,
+ target: ToggleButtonFixture,
+ only?: readonly string[],
+): Promise<readonly ExpectationResult[]> {
+ const run = await checkAccessibilitySpec({
+ spec: TOGGLE_BUTTON_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ only,
+ mount: async () => {
+ await page.setContent(fixturePage(target.html));
+ await holdMotionStill(page);
+ return createChromiumHarness({
+ page,
+ cdp,
+ subject: page.locator(SUBJECT_SELECTOR),
+ });
+ },
+ });
+ return run.results;
+}
+
+test.describe('toggle-button 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));
+ expect(
+ observed
+ .filter(
+ result =>
+ result.status !== 'pass' && result.status !== 'not-applicable',
+ )
+ .map(result => `${result.expectation}: ${result.detail ?? ''}`),
+ ).toEqual([]);
+ });
+ }
+});
+
+test.describe('toggle-button contract — deliberately violating fixtures', () => {
+ for (const expectation of TOGGLE_BUTTON_PATTERN.expectations) {
+ if (
+ !requiredLayers(expectation).every(layer =>
+ CHROMIUM_OBSERVES.includes(layer),
+ )
+ ) {
+ continue;
+ }
+ for (const fixtureId of TOGGLE_BUTTON_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 ?? '').not.toBe('');
+ });
+ }
+ }
+});
diff --git a/internal/a11y-spec/src/patterns/toggle-button.fixtures.ts b/internal/a11y-spec/src/patterns/toggle-button.fixtures.ts
new file mode 100644
index 0000000000..c6741dd0b6
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/toggle-button.fixtures.ts
@@ -0,0 +1,280 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file toggle-button.fixtures.ts
+ * @input Uses ToggleButtonStateFacts from ./toggle-button
+ * @output Plain-HTML conforming and deliberately violating toggle-button fixtures
+ * @position Contract mutation proof shared by jsdom and Chromium.
+ */
+
+import type {ToggleButtonStateFacts} from './toggle-button';
+
+const SUBJECT_ATTRIBUTE = 'data-a11y-subject';
+export const SUBJECT_SELECTOR = `[${SUBJECT_ATTRIBUTE}]`;
+
+export interface ToggleButtonFixture {
+ readonly id: string;
+ readonly summary: string;
+ readonly facts: ToggleButtonStateFacts;
+ readonly html: string;
+}
+
+const CONFORMING_FACTS: ToggleButtonStateFacts = {
+ pressed: false,
+ operable: true,
+ focusable: true,
+ unavailable: false,
+ described: false,
+};
+
+function facts(
+ overrides: Partial<ToggleButtonStateFacts> = {},
+): ToggleButtonStateFacts {
+ return {...CONFORMING_FACTS, ...overrides};
+}
+
+const TOGGLE = `this.setAttribute('aria-pressed', this.getAttribute('aria-pressed') === 'true' ? 'false' : 'true')`;
+const TOGGLE_UNLESS_DISABLED = `if (this.getAttribute('aria-disabled') !== 'true') { ${TOGGLE}; }`;
+
+function nativeToggle({
+ pressed = false,
+ label = 'Bold',
+ attributes = '',
+ onclick = TOGGLE_UNLESS_DISABLED,
+}: {
+ pressed?: boolean;
+ label?: string;
+ attributes?: string;
+ onclick?: string;
+} = {}): string {
+ return `<button type="button" ${SUBJECT_ATTRIBUTE} aria-pressed="${pressed}"${attributes ? ` ${attributes}` : ''}${onclick ? ` onclick="${onclick}"` : ''}>${label}</button>`;
+}
+
+export const TOGGLE_BUTTON_FIXTURES: readonly ToggleButtonFixture[] = [
+ {
+ id: 'conforming-unpressed',
+ summary: 'a named toggle button that starts unpressed',
+ facts: facts(),
+ html: nativeToggle(),
+ },
+ {
+ id: 'conforming-pressed',
+ summary: 'the same toggle button starting pressed',
+ facts: facts({pressed: true}),
+ html: nativeToggle({pressed: true}),
+ },
+ {
+ id: 'conforming-icon-only',
+ summary:
+ 'a toggle button named for assistive technology with no visible words',
+ facts: facts(),
+ // A drawn icon, not a letter: a visible "B" would be words a person can
+ // read, which the accessible name "Bold" does not contain.
+ html: nativeToggle({
+ label:
+ '<svg aria-hidden="true" width="16" height="16" viewBox="0 0 16 16"><path fill="currentColor" d="M4 2h5a3 3 0 0 1 0 6H4zm0 6h6a3 3 0 0 1 0 6H4z"></path></svg>',
+ attributes: 'aria-label="Bold"',
+ }),
+ },
+ {
+ id: 'conforming-described',
+ summary: 'a toggle button with supporting text attached as its description',
+ facts: facts({described: true}),
+ html:
+ '<p id="hint">Applies bold formatting to the selection.</p>' +
+ nativeToggle({attributes: 'aria-describedby="hint"'}),
+ },
+ {
+ id: 'conforming-disabled',
+ summary: 'a natively disabled toggle button',
+ facts: facts({operable: false, focusable: false, unavailable: true}),
+ html: nativeToggle({attributes: 'disabled', onclick: ''}),
+ },
+ {
+ id: 'conforming-focusable-disabled',
+ summary:
+ 'an aria-disabled toggle button that keeps its explanation reachable',
+ facts: facts({operable: false, unavailable: true, described: true}),
+ html:
+ '<p id="hint">Formatting is locked.</p>' +
+ nativeToggle({
+ attributes: 'aria-disabled="true" aria-describedby="hint"',
+ }),
+ },
+ {
+ id: 'violating-role',
+ summary: 'a persistent control exposed as a switch instead of a button',
+ facts: facts({operable: false, focusable: false}),
+ html: `<div ${SUBJECT_ATTRIBUTE} role="switch" aria-checked="false" aria-pressed="false">Bold</div>`,
+ },
+ {
+ id: 'violating-unnamed',
+ summary: 'a toggle button with no accessible name',
+ facts: facts({operable: false}),
+ html: nativeToggle({label: '', onclick: ''}),
+ },
+ {
+ id: 'violating-name-mismatch',
+ summary: 'a visible label replaced by a different accessible name',
+ facts: facts(),
+ html: nativeToggle({attributes: 'aria-label="Formatting"'}),
+ },
+ {
+ id: 'violating-state-missing',
+ summary: 'a button that omits its persistent pressed state',
+ facts: facts({operable: false}),
+ html: `<button type="button" ${SUBJECT_ATTRIBUTE}>Bold</button>`,
+ },
+ {
+ id: 'violating-state-opposite',
+ summary: 'a rendered pressed state exposed as unpressed',
+ facts: facts({pressed: true, operable: false}),
+ html: nativeToggle({pressed: false, onclick: ''}),
+ },
+ {
+ id: 'violating-dangling-description',
+ summary: 'a description relationship that resolves to nothing',
+ facts: facts({described: true}),
+ html: nativeToggle({attributes: 'aria-describedby="missing"'}),
+ },
+ {
+ id: 'violating-empty-description',
+ summary: 'a description target with no exposed text',
+ facts: facts({described: true}),
+ html:
+ '<p id="hint"></p>' +
+ nativeToggle({attributes: 'aria-describedby="hint"'}),
+ },
+ {
+ id: 'violating-unavailable-unexposed',
+ summary: 'an inoperable toggle button exposed as available',
+ facts: facts({operable: false, unavailable: true}),
+ html: nativeToggle({onclick: ''}),
+ },
+ {
+ id: 'violating-inert',
+ summary: 'a toggle button that never changes state',
+ facts: facts(),
+ html: nativeToggle({onclick: ''}),
+ },
+ {
+ id: 'violating-one-way',
+ summary: 'a toggle button that becomes pressed and cannot be unpressed',
+ facts: facts(),
+ html: nativeToggle({onclick: `this.setAttribute('aria-pressed', 'true')`}),
+ },
+ {
+ id: 'violating-enter-blocked',
+ summary:
+ 'a toggle button that blocks Enter while accepting pointer and Space',
+ facts: facts(),
+ html: nativeToggle({
+ attributes: `onkeydown="if (event.key === 'Enter') event.preventDefault()"`,
+ }),
+ },
+ {
+ id: 'violating-space-blocked',
+ summary:
+ 'a toggle button that blocks Space while accepting pointer and Enter',
+ facts: facts(),
+ html: nativeToggle({
+ attributes: `onkeydown="if (event.key === ' ') event.preventDefault()"`,
+ }),
+ },
+ {
+ id: 'violating-label-changes',
+ summary: 'a toggle button whose label describes the next action',
+ facts: facts(),
+ html: nativeToggle({
+ label: 'Turn on bold',
+ onclick: `const next = this.getAttribute('aria-pressed') !== 'true'; this.setAttribute('aria-pressed', String(next)); this.textContent = next ? 'Turn off bold' : 'Turn on bold'`,
+ }),
+ },
+ {
+ id: 'violating-down-event-toggle',
+ summary: 'a toggle button that changes on pointer-down',
+ facts: facts(),
+ html: nativeToggle({attributes: `onpointerdown="${TOGGLE}"`, onclick: ''}),
+ },
+ {
+ id: 'violating-focus-moves',
+ summary: 'a toggle button that moves focus after changing state',
+ facts: facts(),
+ html: nativeToggle({
+ onclick: `${TOGGLE}; document.getElementById('after').focus()`,
+ }),
+ },
+ {
+ id: 'violating-unreachable',
+ summary: 'a toggle button removed from the tab sequence',
+ facts: facts(),
+ html: nativeToggle({attributes: 'tabindex="-1"'}),
+ },
+ {
+ id: 'violating-keyboard-trap',
+ summary: 'a toggle button that prevents Tab from leaving',
+ facts: facts(),
+ html: nativeToggle({
+ attributes: `onkeydown="if (event.key === 'Tab') event.preventDefault()"`,
+ }),
+ },
+ {
+ id: 'violating-disabled-operable',
+ summary: 'an aria-disabled toggle button that still changes state',
+ facts: facts({operable: false, unavailable: true}),
+ html: nativeToggle({attributes: 'aria-disabled="true"', onclick: TOGGLE}),
+ },
+];
+
+export function fixture(id: string): ToggleButtonFixture {
+ const found = TOGGLE_BUTTON_FIXTURES.find(candidate => candidate.id === id);
+ if (found == null) {
+ throw new Error(`unknown toggle-button fixture "${id}"`);
+ }
+ return found;
+}
+
+export const CONFORMING_FIXTURES: readonly string[] =
+ TOGGLE_BUTTON_FIXTURES.filter(candidate =>
+ candidate.id.startsWith('conforming-'),
+ ).map(candidate => candidate.id);
+
+export const TOGGLE_BUTTON_MUTATIONS: Readonly<
+ Record<string, readonly string[]>
+> = {
+ 'toggle-button.role.exposed': ['violating-role'],
+ 'toggle-button.name.exposed': ['violating-unnamed'],
+ 'toggle-button.name.matches-visible-label': ['violating-name-mismatch'],
+ 'toggle-button.state.exposed': [
+ 'violating-state-missing',
+ 'violating-state-opposite',
+ ],
+ 'toggle-button.description.resolvable': ['violating-dangling-description'],
+ 'toggle-button.description.exposed': ['violating-empty-description'],
+ 'toggle-button.unavailable.exposed': ['violating-unavailable-unexposed'],
+ 'toggle-button.state.pointer-round-trip': [
+ 'violating-inert',
+ 'violating-one-way',
+ ],
+ 'toggle-button.state.enter-round-trip': [
+ 'violating-enter-blocked',
+ 'violating-one-way',
+ ],
+ 'toggle-button.state.space-round-trip': [
+ 'violating-space-blocked',
+ 'violating-one-way',
+ ],
+ 'toggle-button.name.stable-across-change': ['violating-label-changes'],
+ 'toggle-button.state.survives-an-aborted-press': [
+ 'violating-down-event-toggle',
+ ],
+ 'toggle-button.focus.stays-on-change': [
+ 'violating-focus-moves',
+ 'violating-inert',
+ ],
+ 'toggle-button.focus.reachable-and-escapable': [
+ 'violating-unreachable',
+ 'violating-keyboard-trap',
+ ],
+ 'toggle-button.state.inoperable': ['violating-disabled-operable'],
+};
diff --git a/internal/a11y-spec/src/patterns/toggle-button.jsdom.test.ts b/internal/a11y-spec/src/patterns/toggle-button.jsdom.test.ts
new file mode 100644
index 0000000000..e26aa92702
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/toggle-button.jsdom.test.ts
@@ -0,0 +1,148 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file toggle-button.jsdom.test.ts
+ * @input Uses the toggle-button contract, its independent fixtures, and jsdom harness
+ * @output DOM-layer positive/negative proof and honest unrun results for browser layers
+ * @position Contract self-test; no Astryx component is rendered here.
+ */
+
+import {afterEach, describe, expect, it} from 'vitest';
+import {
+ citeSource,
+ describeExpectation,
+ requiredLayers,
+ unansweredDimensions,
+} from '../contract';
+import {checkAccessibilitySpec, type ExpectationResult} from '../check';
+import {JSDOM_OBSERVES, createJsdomHarness} from '../harness/jsdom';
+import {TOGGLE_BUTTON_PATTERN} from './toggle-button';
+import {
+ CONFORMING_FIXTURES,
+ SUBJECT_SELECTOR,
+ TOGGLE_BUTTON_MUTATIONS,
+ fixture,
+ type ToggleButtonFixture,
+} from './toggle-button.fixtures';
+
+const observableHere = TOGGLE_BUTTON_PATTERN.expectations.filter(expectation =>
+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),
+);
+
+afterEach(() => document.body.replaceChildren());
+
+async function resultsFor(target: ToggleButtonFixture) {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const result = await checkAccessibilitySpec({
+ spec: TOGGLE_BUTTON_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('toggle-button contract — completeness', () => {
+ it('answers every completeness dimension', () => {
+ expect(unansweredDimensions(TOGGLE_BUTTON_PATTERN)).toEqual([]);
+ });
+
+ it('gives every expectation at least one deliberately violating fixture', () => {
+ expect(
+ TOGGLE_BUTTON_PATTERN.expectations
+ .filter(
+ expectation =>
+ (TOGGLE_BUTTON_MUTATIONS[expectation.id] ?? []).length === 0,
+ )
+ .map(expectation => expectation.id),
+ ).toEqual([]);
+ });
+
+ it('has no mutation without an expectation', () => {
+ const ids = new Set(
+ TOGGLE_BUTTON_PATTERN.expectations.map(expectation => expectation.id),
+ );
+ expect(
+ Object.keys(TOGGLE_BUTTON_MUTATIONS).filter(id => !ids.has(id)),
+ ).toEqual([]);
+ });
+
+ it('names every fixture it records a mutation against', () => {
+ for (const fixtures of Object.values(TOGGLE_BUTTON_MUTATIONS)) {
+ for (const id of fixtures) {
+ expect(() => fixture(id)).not.toThrow();
+ }
+ }
+ });
+});
+
+describe('toggle-button contract — jsdom evidence boundary', () => {
+ it('reports higher-layer expectations as unrun', async () => {
+ const results = await resultsFor(fixture('conforming-unpressed'));
+ expect(results.some(result => result.status === 'unrun')).toBe(true);
+ });
+});
+
+describe.each(observableHere.map(expectation => [expectation.id] as const))(
+ '%s',
+ id => {
+ const expectation = TOGGLE_BUTTON_PATTERN.expectations.find(
+ candidate => candidate.id === id,
+ )!;
+
+ it.each(CONFORMING_FIXTURES.map(name => [name] as const))(
+ 'passes against %s when applicable',
+ async name => {
+ const result = resultFor(await resultsFor(fixture(name)), id);
+ expect(
+ ['pass', 'not-applicable'],
+ `${id} against ${name}: ${result.detail ?? ''}`,
+ ).toContain(result.status);
+ },
+ );
+
+ it.each((TOGGLE_BUTTON_MUTATIONS[id] ?? []).map(name => [name] as const))(
+ 'fails against %s',
+ async name => {
+ const result = resultFor(await resultsFor(fixture(name)), id);
+ expect(result.status, `${id} against ${name}`).toBe('fail');
+ expect(result.detail ?? '').not.toBe('');
+ },
+ );
+
+ it('carries its id and normative source into failures', async () => {
+ const [violating] = TOGGLE_BUTTON_MUTATIONS[id] ?? [];
+ const result = resultFor(
+ await resultsFor(fixture(violating ?? CONFORMING_FIXTURES[0]!)),
+ id,
+ );
+ 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/toggle-button.ts b/internal/a11y-spec/src/patterns/toggle-button.ts
new file mode 100644
index 0000000000..d097a84a7a
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/toggle-button.ts
@@ -0,0 +1,757 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file toggle-button.ts
+ * @input Uses the shared accessibility-contract vocabulary
+ * @output TOGGLE_BUTTON_PATTERN and ToggleButtonStateFacts
+ * @position The reusable contract for buttons with a persistent pressed state.
+ * Ordinary command buttons remain owned by BUTTON_PATTERN.
+ *
+ * Adopted pattern: https://www.w3.org/WAI/ARIA/apg/patterns/button/
+ *
+ * SYNC: When an expectation changes, update
+ * - /internal/a11y-spec/README.md
+ * - /internal/a11y-spec/src/patterns/toggle-button.fixtures.ts
+ * - /packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.states.ts
+ */
+
+import {
+ definePattern,
+ type ApgRequirement,
+ type AstryxRecord,
+ type PatternContract,
+ type WcagCriterion,
+} from '../contract';
+import type {Subject} from '../harness';
+import {saysInOrder, spokenWords} from '../spoken';
+
+const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/button/';
+const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';
+const FAMILY_BUTTONS =
+ 'https://github.com/facebook/astryx/blob/e86aa19ecb7e8204c8b5b430bb61a971b813d137/docs/families/buttons.md';
+
+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_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_2_2: WcagCriterion = {
+ standard: 'wcag',
+ id: '3.2.2',
+ name: 'On Input',
+ level: 'A',
+ url: `${UNDERSTANDING}/on-input.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 FAMILY_BUTTONS_FR1: AstryxRecord = {
+ standard: 'astryx',
+ id: 'family:buttons',
+ clause: 'FR1',
+ requirement:
+ 'A Button-family control MUST receive a non-empty accessible `label`.',
+ url: `${FAMILY_BUTTONS}#L108-L111`,
+};
+const FAMILY_BUTTONS_FR2: AstryxRecord = {
+ standard: 'astryx',
+ id: 'family:buttons',
+ clause: 'FR2',
+ requirement:
+ 'A momentary or persistent action renders an operable button with keyboard activation, focus-visible feedback, and `type="button"` unless the component\'s documented form mode says otherwise.',
+ url: `${FAMILY_BUTTONS}#L112-L116`,
+};
+const FAMILY_BUTTONS_FR3: AstryxRecord = {
+ standard: 'astryx',
+ id: 'family:buttons',
+ clause: 'FR3',
+ requirement: 'A disabled member MUST NOT invoke its callback or Action.',
+ url: `${FAMILY_BUTTONS}#L117-L120`,
+};
+const FAMILY_BUTTONS_FR6: AstryxRecord = {
+ standard: 'astryx',
+ id: 'family:buttons',
+ clause: 'FR6',
+ requirement:
+ 'A ToggleButton MUST expose its effective state with `aria-pressed` and request the next controlled value on activation.',
+ url: `${FAMILY_BUTTONS}#L135-L138`,
+};
+
+const APG_ROLE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'button',
+ requirement: 'The button has role of button.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_LABEL: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'button',
+ requirement:
+ 'The button has an accessible label. By default, the accessible name is computed from any text content inside the button element. However, it can also be provided with aria-labelledby or aria-label.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_DESCRIPTION: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'button',
+ requirement:
+ "If a description of the button's function is present, the button element has aria-describedby set to the ID of the element containing the description.",
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_UNAVAILABLE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'button',
+ requirement:
+ 'When the action associated with a button is unavailable, the button has aria-disabled set to true.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_PRESSED: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'button',
+ requirement:
+ 'If the button is a toggle button, it has an aria-pressed state. When the button is toggled on, the value of this state is true, and when toggled off, the state is false.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_STABLE_LABEL: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'button',
+ requirement: 'The label on a toggle does not change when its state changes.',
+ url: `${APG_URL}#aboutthispattern`,
+};
+const APG_ENTER: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'button',
+ requirement: 'Enter: Activates the button.',
+ url: `${APG_URL}#keyboardinteraction`,
+};
+const APG_SPACE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'button',
+ requirement: 'Space: Activates the button.',
+ url: `${APG_URL}#keyboardinteraction`,
+};
+
+export interface ToggleButtonStateFacts {
+ readonly pressed: boolean;
+ readonly operable: boolean;
+ readonly focusable: boolean;
+ readonly unavailable: boolean;
+ readonly described: boolean;
+}
+
+const ALWAYS = {
+ condition: 'the binding renders the toggle button',
+ test: () => true,
+};
+const READS_TREE = ['accessibility-tree'] as const;
+const TAB_BUDGET = 10;
+
+function pressedWord(value: 'true' | 'false' | 'mixed' | null): string {
+ return value === 'true'
+ ? 'pressed'
+ : value === 'false'
+ ? 'not pressed'
+ : value === 'mixed'
+ ? 'partly pressed'
+ : 'without a pressed state';
+}
+
+async function roundTrip(
+ subject: Subject,
+ start: boolean,
+ activate: () => Promise<void>,
+ how: string,
+): Promise<void> {
+ const from = start ? 'true' : 'false';
+ const to = start ? 'false' : 'true';
+ const before = (await subject.computed()).pressed;
+ if (before !== from) {
+ throw new Error(
+ `the binding declares ${pressedWord(from)}, but the browser starts ${pressedWord(before)}`,
+ );
+ }
+ await activate();
+ const after = (await subject.computed()).pressed;
+ if (after !== to) {
+ throw new Error(
+ `${how} left the toggle button ${pressedWord(after)}: it did not become ${pressedWord(to)}`,
+ );
+ }
+ await activate();
+ const back = (await subject.computed()).pressed;
+ if (back !== from) {
+ throw new Error(
+ `${how} changed the toggle button to ${pressedWord(after)}, but doing it again left it ${pressedWord(back)} instead of returning it to ${pressedWord(from)}`,
+ );
+ }
+}
+
+export const TOGGLE_BUTTON_PATTERN: PatternContract<ToggleButtonStateFacts> =
+ definePattern<ToggleButtonStateFacts>({
+ pattern: 'toggle-button',
+ url: APG_URL,
+ scope:
+ 'One persistent action control that is reported as a button, exposes its pressed state, keeps one name, and changes in both directions through pointer, Enter, and Space.',
+ expectations: [
+ {
+ id: 'toggle-button.role.exposed',
+ outcome:
+ 'The control is exposed as a button, so the user understands that it performs an action.',
+ sources: [WCAG_4_1_2, FAMILY_BUTTONS_FR2, APG_ROLE],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const {role} = await subject.computed();
+ if (role !== 'button') {
+ throw new Error(
+ role == null
+ ? 'the browser exposes no role for this toggle button'
+ : `the browser reports this control as "${role}", not as a button`,
+ );
+ }
+ },
+ },
+ {
+ id: 'toggle-button.name.exposed',
+ outcome:
+ 'The toggle button has an accessible name, so the user knows which persistent action it controls.',
+ sources: [FAMILY_BUTTONS_FR1, WCAG_4_1_2, APG_LABEL],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ if ((await subject.computed()).name.trim() === '') {
+ throw new Error(
+ 'the browser computes no accessible name for this toggle button',
+ );
+ }
+ },
+ },
+ {
+ id: 'toggle-button.name.matches-visible-label',
+ outcome:
+ 'The accessible name contains the visible label, so a speech-input user can say what they can read.',
+ sources: [WCAG_2_5_3, APG_LABEL],
+ covers: ['2.5.3-label-in-name'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ alsoNeeds: ['real-browser'],
+ enforcement: 'required',
+ run: async ({subject, notApplicable}) => {
+ const visible = await subject.visibleLabelText();
+ if (visible == null) {
+ return notApplicable(
+ 'this state renders no visible words, so WCAG 2.5.3 has no visible label to compare',
+ );
+ }
+ 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}"`,
+ );
+ }
+ },
+ },
+ {
+ id: 'toggle-button.state.exposed',
+ outcome:
+ 'The pressed state is exposed and matches the rendered state, so assistive technology reports the same persistent choice the user sees.',
+ sources: [FAMILY_BUTTONS_FR6, WCAG_4_1_2, APG_PRESSED],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject, facts}) => {
+ const {pressed} = await subject.computed();
+ const expected = facts.pressed ? 'true' : 'false';
+ if (pressed == null) {
+ throw new Error(
+ 'the browser exposes no pressed state for this toggle button',
+ );
+ }
+ if (pressed !== expected) {
+ throw new Error(
+ `this state is ${pressedWord(expected)} but the browser reports it as ${pressedWord(pressed)}`,
+ );
+ }
+ },
+ },
+ {
+ id: 'toggle-button.description.resolvable',
+ outcome:
+ 'Every description target exists, so supporting text is not silently dropped.',
+ sources: [WCAG_1_3_1, APG_DESCRIPTION],
+ covers: ['1.3.1-info-and-relationships'],
+ appliesWhen: {
+ condition: 'the binding renders supporting text',
+ test: facts => facts.described,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const ids = ((await subject.attribute('aria-describedby')) ?? '')
+ .split(/\s+/)
+ .filter(Boolean);
+ if (ids.length === 0) {
+ throw new Error(
+ 'the binding renders supporting text, but the toggle button has no aria-describedby',
+ );
+ }
+ 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 resolves to nothing`,
+ );
+ }
+ },
+ },
+ {
+ id: 'toggle-button.description.exposed',
+ outcome: 'Supporting text is exposed as the toggle button description.',
+ sources: [WCAG_4_1_2, APG_DESCRIPTION],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'the binding renders supporting text',
+ test: facts => facts.described,
+ },
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ if ((await subject.computed()).description.trim() === '') {
+ throw new Error(
+ 'the binding renders supporting text, but the browser computes no accessible description',
+ );
+ }
+ },
+ },
+ {
+ id: 'toggle-button.unavailable.exposed',
+ outcome: 'An unavailable toggle button is reported as unavailable.',
+ sources: [WCAG_4_1_2, APG_UNAVAILABLE],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'the binding declares this state unavailable',
+ test: facts => facts.unavailable,
+ },
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ if (!(await subject.computed()).disabled) {
+ throw new Error(
+ 'this state is unavailable, but the browser reports the toggle button as available',
+ );
+ }
+ },
+ },
+ {
+ id: 'toggle-button.state.pointer-round-trip',
+ outcome:
+ 'A pointer changes the pressed state and changes it back, with the exposed state following both transitions.',
+ sources: [FAMILY_BUTTONS_FR6, APG_PRESSED, WCAG_4_1_2],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the user can change this state',
+ test: facts => facts.operable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: READS_TREE,
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) =>
+ roundTrip(
+ subject,
+ facts.pressed,
+ () => harness.click(subject),
+ 'clicking the toggle button',
+ ),
+ },
+ {
+ id: 'toggle-button.state.enter-round-trip',
+ outcome: 'Enter changes the pressed state and changes it back.',
+ sources: [WCAG_2_1_1, FAMILY_BUTTONS_FR2, APG_ENTER],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the state is operable and focusable',
+ test: facts => facts.operable && facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: READS_TREE,
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'the toggle button did not take focus, so Enter never reaches it',
+ );
+ }
+ await roundTrip(
+ subject,
+ facts.pressed,
+ () => harness.press('Enter'),
+ 'pressing Enter on the focused toggle button',
+ );
+ },
+ },
+ {
+ id: 'toggle-button.state.space-round-trip',
+ outcome: 'Space changes the pressed state and changes it back.',
+ sources: [WCAG_2_1_1, FAMILY_BUTTONS_FR2, APG_SPACE],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the state is operable and focusable',
+ test: facts => facts.operable && facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: READS_TREE,
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'the toggle button did not take focus, so Space never reaches it',
+ );
+ }
+ await roundTrip(
+ subject,
+ facts.pressed,
+ () => harness.press('Space'),
+ 'pressing Space on the focused toggle button',
+ );
+ },
+ },
+ {
+ id: 'toggle-button.name.stable-across-change',
+ outcome:
+ 'The name stays the same after both state changes, so it identifies the action rather than contradicting the pressed state.',
+ sources: [APG_STABLE_LABEL, WCAG_4_1_2],
+ wcagOutcome:
+ 'The accessible name in 4.1.2 continues to identify the same control while its separately exposed state changes.',
+ covers: ['apg-interaction'],
+ appliesWhen: {
+ condition: 'the user can change this state',
+ test: facts => facts.operable,
+ },
+ evidenceLayer: 'accessibility-tree',
+ alsoNeeds: ['real-browser'],
+ enforcement: 'advisory',
+ advisoryBecause:
+ 'The label-stability detail is APG guidance that no current Astryx record adopts as a required shared outcome.',
+ run: async ({harness, subject}) => {
+ const before = (await subject.computed()).name;
+ await harness.click(subject);
+ const changed = (await subject.computed()).name;
+ if (changed.trim().toLowerCase() !== before.trim().toLowerCase()) {
+ throw new Error(
+ `changing the pressed state renamed the toggle button from "${before}" to "${changed}"`,
+ );
+ }
+ await harness.click(subject);
+ const back = (await subject.computed()).name;
+ if (back.trim().toLowerCase() !== before.trim().toLowerCase()) {
+ throw new Error(
+ `changing the pressed state back renamed the toggle button from "${before}" to "${back}"`,
+ );
+ }
+ },
+ },
+ {
+ id: 'toggle-button.state.survives-an-aborted-press',
+ outcome:
+ 'A press released away from the control leaves the pressed state unchanged.',
+ sources: [WCAG_2_5_2],
+ covers: ['2.5.2-pointer-cancellation'],
+ appliesWhen: {
+ condition: 'the user can change this state',
+ test: facts => facts.operable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: READS_TREE,
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const before = (await subject.computed()).pressed;
+ await harness.abortedPress(subject);
+ const after = (await subject.computed()).pressed;
+ if (after !== before) {
+ throw new Error(
+ `pressing and releasing away still changed the toggle button to ${pressedWord(after)}`,
+ );
+ }
+ },
+ },
+ {
+ id: 'toggle-button.focus.stays-on-change',
+ outcome:
+ 'Changing the pressed state leaves focus on the toggle button.',
+ sources: [WCAG_3_2_2],
+ // Partly: see the 3.2.2 exemption for context changes caused by the
+ // caller rather than by the ToggleButton itself.
+ covers: ['3.2.2-on-input'],
+ appliesWhen: {
+ condition: 'the state is operable and focusable',
+ test: facts => facts.operable && facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: READS_TREE,
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'the toggle button did not take focus, so its state cannot be changed from the keyboard',
+ );
+ }
+ const before = (await subject.computed()).pressed;
+ await harness.press('Space');
+ if ((await subject.computed()).pressed === before) {
+ throw new Error(
+ 'pressing Space did not change the pressed state, so there is no change whose focus outcome can be checked',
+ );
+ }
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'changing the pressed state moved focus off the toggle button',
+ );
+ }
+ },
+ },
+ {
+ id: 'toggle-button.focus.reachable-and-escapable',
+ outcome: 'Tab reaches the toggle button and then leaves it.',
+ sources: [WCAG_2_1_1, WCAG_2_1_2],
+ covers: ['2.1.1-keyboard', '2.1.2-no-keyboard-trap'],
+ appliesWhen: {
+ condition: 'the state belongs in the tab sequence',
+ test: facts => facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ 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 never reached the toggle button`,
+ );
+ }
+ await harness.press('Tab');
+ if (await subject.isFocused()) {
+ throw new Error('Tab did not move focus off the toggle button');
+ }
+ },
+ },
+ {
+ id: 'toggle-button.state.inoperable',
+ outcome:
+ 'A toggle button that cannot be operated keeps its pressed state under pointer, Enter, and Space.',
+ sources: [FAMILY_BUTTONS_FR3, FAMILY_BUTTONS_FR6, WCAG_4_1_2],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: {
+ condition: 'the user cannot change this state',
+ test: facts => !facts.operable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: READS_TREE,
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ const before = (await subject.computed()).pressed;
+ await harness.click(subject, {ignoreAvailability: true});
+ if ((await subject.computed()).pressed !== before) {
+ throw new Error(
+ 'clicking an inoperable toggle button changed its pressed state',
+ );
+ }
+ if (!facts.focusable) {
+ return;
+ }
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'this state is declared focusable but cannot take focus',
+ );
+ }
+ for (const key of ['Enter', 'Space'] as const) {
+ await harness.press(key);
+ if ((await subject.computed()).pressed !== before) {
+ throw new Error(
+ `pressing ${key} changed an inoperable toggle button`,
+ );
+ }
+ }
+ },
+ },
+ ],
+ exemptions: {
+ '1.1.1-non-text-content': {
+ owner: 'the binding component',
+ verifiedBy: 'component icon tests and the repository axe audit',
+ reason:
+ 'Decorative or informative graphics inside the control are component composition, not pressed-button semantics.',
+ },
+ '1.3.2-meaningful-sequence': {
+ owner: 'the composing page',
+ verifiedBy: 'page-level DOM-order review',
+ reason:
+ 'A single control cannot determine its order among surrounding content.',
+ },
+ '1.3.5-identify-input-purpose': {
+ owner: 'the composing form',
+ verifiedBy: 'form integration review',
+ reason:
+ 'A toggle button performs an action and does not collect user information.',
+ },
+ '1.4.1-use-of-color': {
+ owner: 'the binding component and theme',
+ verifiedBy: 'forced-colors tests and the visual gate',
+ reason:
+ 'Whether pressed state is conveyed without color alone is a rendered-pixel claim.',
+ },
+ '1.4.3-contrast-minimum': {
+ owner: 'the binding component and theme',
+ verifiedBy: 'axe and visual gates',
+ reason: 'Resolved text contrast is a rendered-pixel measurement.',
+ },
+ '1.4.11-non-text-contrast': {
+ owner: 'the binding component and theme',
+ verifiedBy: 'axe, forced-colors, and visual gates',
+ reason:
+ 'Control, state, icon, and focus-indicator contrast are rendered-pixel measurements.',
+ },
+ '2.4.2-page-titled': {
+ owner: 'the page',
+ verifiedBy: 'page-level review',
+ reason: 'A component does not own the document title.',
+ },
+ '2.4.3-focus-order': {
+ owner: 'the composing page',
+ verifiedBy: 'page-level focus-order review',
+ reason:
+ 'This contract proves reachability and escape, not the meaning of the surrounding sequence.',
+ },
+ '2.4.4-link-purpose': {
+ owner: 'the link pattern and caller content',
+ verifiedBy: 'link-pattern and page review',
+ reason:
+ 'ToggleButton remains an action and never adopts link semantics.',
+ },
+ '2.4.6-headings-and-labels': {
+ owner: 'caller content',
+ verifiedBy:
+ 'content review of whether the supplied label describes the action',
+ reason:
+ 'The contract proves that a name exists, not that the chosen wording is descriptive.',
+ },
+ '2.4.7-focus-visible': {
+ owner: 'interaction-modality and the binding component',
+ verifiedBy: 'the repository visual gate',
+ reason: 'A visible focus indicator is a paint result.',
+ },
+ '2.4.11-focus-not-obscured': {
+ owner: 'the composing page',
+ verifiedBy: 'page and overlay review',
+ reason: 'Obscuration depends on surrounding authored content.',
+ },
+ '2.5.8-target-size': {
+ owner: 'the binding component and composing page',
+ verifiedBy: 'the repository axe target-size rule and visual review',
+ reason:
+ 'Target-size exceptions depend on rendered geometry and neighbouring targets.',
+ },
+ '3.1.1-language-of-page': {
+ owner: 'the page',
+ verifiedBy: 'page-level review',
+ reason: 'A component does not own the document language.',
+ },
+ '3.2.2-on-input': {
+ owner: 'the caller, for its response to onPressedChange',
+ verifiedBy:
+ 'integration and page-level review of any navigation, reload, or surrounding content change triggered by the caller',
+ reason:
+ 'This contract proves that changing pressed state keeps focus on the ToggleButton. It cannot observe whether caller code changes the wider page context in response to onPressedChange.',
+ coversRemainderOnly: true,
+ },
+ '3.2.4-consistent-identification': {
+ owner: 'the design system and caller content',
+ verifiedBy: 'shared pattern adoption and page-level content review',
+ reason:
+ 'Consistency is a property of repeated controls across a product.',
+ },
+ '3.3.1-error-identification': {
+ owner: 'the composing workflow',
+ verifiedBy: 'workflow validation and status-message tests',
+ reason:
+ 'A toggle button exposes pressed state, not a validation error contract.',
+ },
+ '3.3.2-labels-or-instructions': {
+ owner: 'caller content',
+ verifiedBy: 'content review',
+ reason:
+ 'Instructions for a workflow are not owned by one toggle button.',
+ },
+ '4.1.3-status-messages': {
+ owner: 'the binding component and caller',
+ verifiedBy:
+ 'status-message tests and AST-009 when announcement is claimed',
+ reason:
+ 'A pressed state is exposed on the control; separate status announcements are composed around it.',
+ },
+ 'forced-colors': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ 'ToggleButton forced-colors tests and manual Windows High Contrast review',
+ reason: 'Forced-colors output is a paint result.',
+ },
+ 'reduced-motion': {
+ owner: 'the binding component and theme',
+ verifiedBy: 'motion guards and the visual gate',
+ reason: 'Motion is a rendered result over time.',
+ },
+ 'at-facing-strings': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ 'localization review and AST-009 when announcement is claimed',
+ reason:
+ 'The contract compares names and labels but does not own translation or spoken output.',
+ },
+ },
+ });
diff --git a/packages/core/src/ToggleButton/ToggleButton.test.tsx b/packages/core/src/ToggleButton/ToggleButton.test.tsx
index 8c701eb7b2..5e4d1135ea 100644
--- a/packages/core/src/ToggleButton/ToggleButton.test.tsx
+++ b/packages/core/src/ToggleButton/ToggleButton.test.tsx
@@ -111,24 +111,6 @@ describe('ToggleButton', () => {
expect(screen.getByTestId('icon')).toBeInTheDocument();
});
- it('sets aria-pressed=false when not pressed', () => {
- render(
- <ToggleButton
- label="Bold"
- isPressed={false}
- onPressedChange={() => {}}
- />,
- );
- expect(screen.getByRole('button')).toHaveAttribute('aria-pressed', 'false');
- });
-
- it('sets aria-pressed=true when pressed', () => {
- render(
- <ToggleButton label="Bold" isPressed={true} onPressedChange={() => {}} />,
- );
- expect(screen.getByRole('button')).toHaveAttribute('aria-pressed', 'true');
- });
-
it('calls onPressedChange with true when clicking unpressed button', async () => {
const user = userEvent.setup();
const handleChange = vi.fn();
diff --git a/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.ts b/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.ts
index 8e7d8cfeac..9c6e7451e8 100644
--- a/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.ts
+++ b/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.ts
@@ -2,41 +2,39 @@
/**
* @file ToggleButton.a11y.chromium.spec.ts
- * @input Uses @playwright/test, the a11y-spec static Storybook server, and the
- * checked-in ToggleButtonDisabledA11y stories
- * @output Real-browser evidence for `docs/families/buttons.md` FR3 — disabled
- * means non-operable — across the two ways a ToggleButton becomes disabled,
- * plus the enabled control that catches a fix which disables too much.
- * @position The half of FR3 that jsdom cannot honestly reach. A disabled toggle
- * kept focusable by a tooltip carries `aria-disabled` instead of the native
- * `disabled` attribute, so whether a real mouse press is refused is an engine
- * fact — jsdom's synthetic click does not settle it
- * (`docs/specs/AST-013/spec.md`: a browser claim is made in a browser).
+ * @input Uses the reusable toggle-button contract and checked-in Storybook states
+ * @output Accessibility-tree and real-browser evidence for ToggleButton
+ * @position Component binding; jsdom covers only the DOM layer.
*
- * Each state drives a checked-in story rather than a page this file builds, so
- * the reproduction path for any failure is a URL a person can open
- * (`docs/specs/AST-009/spec.md` FR30). Each story counts its own activations,
- * which is what `activationsOn` reads — a toggle that refuses a press leaves no
- * trace on itself.
- *
- * Presses go through `page.mouse` at the control's own centre rather than
- * `locator.click()`. Playwright's actionability wait would refuse to press a
- * natively disabled control at all, which would prove nothing about what the
- * engine does with a press that really lands.
- *
- * SYNC: Fixtures live in
- * /apps/storybook/stories/ToggleButtonDisabledA11y.stories.tsx.
+ * SYNC: States and story IDs live in ToggleButton.a11y.states.ts and
+ * apps/storybook/stories/ToggleButtonPatternA11y.stories.tsx.
*/
-import {expect, test, type Page} from '@playwright/test';
-import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+import {expect, test, type CDPSession, type Page} from '@playwright/test';
+import {
+ TOGGLE_BUTTON_PATTERN,
+ blockingResults,
+ checkAccessibilitySpec,
+ formatFailures,
+ formatReport,
+ neverExercised,
+ 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';
-
-const STORY_BASE = 'a11y-togglebutton-disabled-state';
+import {
+ TOGGLE_BUTTON_BINDING_STATES,
+ type ToggleButtonBindingRow,
+} from './ToggleButton.a11y.states';
let storybook: StaticServer;
@@ -50,10 +48,12 @@ test.afterAll(async () => {
await storybook?.close();
});
-/** Load a story and wait for the control the assertions press. */
-async function mountStory(page: Page, storyId: string): Promise<void> {
+async function mountState(
+ page: Page,
+ state: ToggleButtonBindingRow,
+): Promise<void> {
await page.goto(
- `${storybook.origin}/iframe.html?id=${STORY_BASE}--${storyId}&viewMode=story`,
+ `${storybook.origin}/iframe.html?id=${state.storyId}&viewMode=story`,
{waitUntil: 'load'},
);
await holdMotionStill(page);
@@ -64,146 +64,106 @@ async function mountStory(page: Page, storyId: string): Promise<void> {
.waitFor({state: 'attached'});
}
-/**
- * How many times this story's own handler has run.
- *
- * The story publishes the count as an attribute, so this reads a fact the story
- * renders rather than instrumenting the page from the test — a person opening
- * the story sees the same number the spec does.
- */
-async function activationsOn(page: Page): Promise<number> {
- const raw = await page
- .locator('[data-a11y-activations]')
- .first()
- .getAttribute('data-a11y-activations');
- return Number(raw ?? '0');
+async function runState(
+ page: Page,
+ cdp: CDPSession,
+ state: ToggleButtonBindingRow,
+): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: TOGGLE_BUTTON_PATTERN,
+ binding: 'ToggleButton',
+ state: state.id,
+ facts: state.facts,
+ mount: async () => {
+ await mountState(page, state);
+ return createChromiumHarness({
+ page,
+ cdp,
+ subject: page.locator('#storybook-root').getByRole('button').first(),
+ });
+ },
+ });
}
-/**
- * A real mouse press at the control's own centre, landing whether or not
- * Playwright would consider the control actionable. This is the press the
- * expectations are about: a user aiming at a control that looks unavailable.
- */
-async function pressWithMouse(page: Page, name: string): Promise<void> {
- const control = page
- .locator('#storybook-root')
- .getByRole('button', {name, includeHidden: true})
- .first();
- const box = await control.boundingBox();
- if (box == null) {
- throw new Error(
- `"${name}" has no layout box, so no mouse press could land on it`,
- );
- }
- await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
-}
-
-/**
- * Whether the engine reports this control as unavailable, by either of the two
- * spellings FR3 permits: the native attribute, or focusable `aria-disabled`.
- */
-async function isUnavailable(page: Page, name: string): Promise<boolean> {
- return page
- .locator('#storybook-root')
- .getByRole('button', {name, includeHidden: true})
- .first()
- .evaluate(
- element =>
- (element as HTMLButtonElement).disabled ||
- element.getAttribute('aria-disabled') === 'true',
- );
+function namesTheSameLabel(rendered: string, claimed: string): boolean {
+ const words = spokenWords(rendered);
+ const expected = spokenWords(claimed);
+ return (
+ words.length === expected.length &&
+ words.every((word, index) => word === expected[index])
+ );
}
-test('a member that disables itself stays disabled inside an enabled group', async ({
- page,
-}) => {
- await mountStory(page, 'group-enabled-member-disabled');
-
- expect(
- await isUnavailable(page, 'List'),
- 'the member sets isDisabled, so it must be exposed as unavailable even though the group disables nothing',
- ).toBe(true);
-
- await pressWithMouse(page, 'List');
- expect(
- await activationsOn(page),
- 'a disabled member must not invoke the group selection callback (family:buttons FR3)',
- ).toBe(0);
-});
-
-test('an enabled member of the same group still toggles', async ({page}) => {
- await mountStory(page, 'group-enabled-member-disabled');
-
- expect(await isUnavailable(page, 'Grid')).toBe(false);
-
- await pressWithMouse(page, 'Grid');
- expect(
- await activationsOn(page),
- 'the sibling says nothing about its own availability and the group disables nothing, so it must still select',
- ).toBe(1);
-});
-
-test('a group disabled state still disables a member that says nothing', async ({
+test('the state inventory matches rendered labels and applicability facts', async ({
page,
}) => {
- await mountStory(page, 'group-disabled-member-silent');
-
- expect(await isUnavailable(page, 'List')).toBe(true);
-
- await pressWithMouse(page, 'List');
- expect(
- await activationsOn(page),
- 'a group disabled state overrides member availability (family:buttons FR3)',
- ).toBe(0);
+ test.setTimeout(3 * 60 * 1000);
+ const cdp = await page.context().newCDPSession(page);
+ const wrong: string[] = [];
+ for (const state of TOGGLE_BUTTON_BINDING_STATES) {
+ await mountState(page, state);
+ const locator = page.locator('#storybook-root').getByRole('button').first();
+ const harness = createChromiumHarness({page, cdp, subject: locator});
+ const subject = await harness.subject();
+ const computed = await subject.computed();
+ const rendered = await subject.visibleLabelText();
+ const labelMatches =
+ state.visibleLabel == null
+ ? rendered == null
+ : rendered != null && namesTheSameLabel(rendered, state.visibleLabel);
+ if (!labelMatches) {
+ wrong.push(
+ `${state.id}: inventory label ${JSON.stringify(state.visibleLabel)}, rendered ${JSON.stringify(rendered)}`,
+ );
+ }
+
+ 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 observed = {
+ unavailable: computed.disabled,
+ focusable: reachedByTab,
+ described: computed.description.trim() !== '',
+ };
+ for (const fact of ['unavailable', 'focusable', 'described'] as const) {
+ if (observed[fact] !== state.facts[fact]) {
+ wrong.push(
+ `${state.id}: declares ${fact}=${state.facts[fact]}, browser exposes ${observed[fact]}`,
+ );
+ }
+ }
+ }
+ expect(wrong).toEqual([]);
});
-test('a disabled toggle kept focusable by its tooltip refuses a mouse press', async ({
+test('every expectation is exercised by at least one ToggleButton state', async ({
page,
}) => {
- await mountStory(page, 'disabled-with-tooltip');
-
- const control = page.locator('#storybook-root').getByRole('button').first();
-
- // The tooltip is why this control is focusable rather than natively disabled,
- // so the press has to be made the way a user reaches it: hover first, let the
- // tip come up, then press. Pressing cold would skip the hover state the
- // tooltip's own pointer listeners run in.
- await control.hover();
- await expect(page.getByRole('tooltip')).toBeVisible();
-
- expect(
- await control.evaluate(element => element.getAttribute('aria-disabled')),
- 'a tooltip keeps the reason reachable by making the control focusable rather than natively disabled',
- ).toBe('true');
- expect(await control.getAttribute('aria-pressed')).toBe('false');
-
- await pressWithMouse(page, 'Bold');
-
- expect(
- await activationsOn(page),
- 'focusable is not operable: a disabled toggle must not invoke onPressedChange from a mouse press (family:buttons FR3)',
- ).toBe(0);
- expect(
- await control.getAttribute('aria-pressed'),
- 'the pressed state must not flip',
- ).toBe('false');
+ test.setTimeout(5 * 60 * 1000);
+ const cdp = await page.context().newCDPSession(page);
+ const results: BindingResult[] = [];
+ for (const state of TOGGLE_BUTTON_BINDING_STATES) {
+ results.push(await runState(page, cdp, state));
+ }
+ expect(neverExercised(results)).toEqual([]);
});
-test('an enabled toggle with the same tooltip still toggles on a mouse press', async ({
- page,
-}) => {
- await mountStory(page, 'enabled-with-tooltip');
-
- const control = page.locator('#storybook-root').getByRole('button').first();
- await control.hover();
- await expect(page.getByRole('tooltip')).toBeVisible();
- expect(await control.getAttribute('aria-pressed')).toBe('false');
-
- await pressWithMouse(page, 'Bold');
-
- expect(
- await activationsOn(page),
- 'the enabled path must be untouched by the disabled-state fix',
- ).toBe(1);
- expect(await control.getAttribute('aria-pressed')).toBe('true');
-});
+for (const state of TOGGLE_BUTTON_BINDING_STATES) {
+ test(`ToggleButton [${state.id}] — ${state.summary}`, async ({page}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const result = await runState(page, cdp, state);
+ const report = summarize(TOGGLE_BUTTON_PATTERN, [result]);
+ // eslint-disable-next-line no-console -- the report is this run's evidence
+ 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/ToggleButton/__tests__/ToggleButton.a11y.renders.tsx b/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.renders.tsx
new file mode 100644
index 0000000000..1611b455c6
--- /dev/null
+++ b/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.renders.tsx
@@ -0,0 +1,133 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file ToggleButton.a11y.renders.tsx
+ * @input Uses ToggleButton, ToggleButtonGroup, and the checked state inventory
+ * @output Exhaustive render functions shared by jsdom tests and Storybook stories
+ * @position Keeps both evidence lanes on the same public component states.
+ */
+
+import {useState, type ReactElement} from 'react';
+import {BoldIcon} from '@heroicons/react/24/outline';
+import {ToggleButton} from '../ToggleButton';
+import {ToggleButtonGroup} from '../ToggleButtonGroup';
+import {
+ TOGGLE_BUTTON_BINDING_STATES,
+ type ToggleButtonBindingRow,
+ type ToggleButtonBindingState,
+ type ToggleButtonStateId,
+} from './ToggleButton.a11y.states';
+
+function StatefulToggle({
+ state,
+}: {
+ state: ToggleButtonBindingRow;
+}): ReactElement {
+ const [pressed, setPressed] = useState(state.facts.pressed);
+ const tooltip = (state as ToggleButtonBindingState).tooltip;
+ const common = {
+ isPressed: pressed,
+ onPressedChange: setPressed,
+ isDisabled: state.facts.unavailable,
+ tooltip,
+ };
+ if (state.renderKind === 'icon-only') {
+ // A drawn icon, as product callers pass: a text glyph such as "B" would be
+ // a visible label the accessible name "Bold" does not contain.
+ return (
+ <ToggleButton {...common} label="Bold" isIconOnly icon={<BoldIcon />} />
+ );
+ }
+ if (state.renderKind === 'composed-label') {
+ return (
+ <ToggleButton {...common} label="Bold formatting">
+ Bold formatting
+ </ToggleButton>
+ );
+ }
+ return <ToggleButton {...common} label="Bold" />;
+}
+
+function SingleGroup({state}: {state: ToggleButtonBindingRow}): ReactElement {
+ const bindingState = state as ToggleButtonBindingState;
+ const [value, setValue] = useState<string | null>(
+ state.facts.pressed ? 'list' : null,
+ );
+ return (
+ <ToggleButtonGroup
+ label="View"
+ value={value}
+ isDisabled={bindingState.groupDisabled}
+ onChange={setValue}>
+ <ToggleButton
+ value="list"
+ label="List"
+ isDisabled={bindingState.memberDisabled}
+ />
+ </ToggleButtonGroup>
+ );
+}
+
+function MultipleGroup({pressed}: {pressed: boolean}): ReactElement {
+ const [value, setValue] = useState<string[]>(pressed ? ['bold'] : []);
+ return (
+ <ToggleButtonGroup
+ type="multiple"
+ label="Formatting"
+ value={value}
+ onChange={setValue}>
+ <ToggleButton value="bold" label="Bold" />
+ </ToggleButtonGroup>
+ );
+}
+
+function renderState(state: ToggleButtonBindingRow): ReactElement {
+ switch (state.renderKind) {
+ case 'standalone':
+ case 'icon-only':
+ case 'composed-label':
+ return <StatefulToggle state={state} />;
+ case 'single-group':
+ return <SingleGroup state={state} />;
+ case 'multiple-group':
+ return <MultipleGroup pressed={state.facts.pressed} />;
+ }
+}
+
+export const TOGGLE_BUTTON_STATE_RENDERS: Readonly<
+ Record<ToggleButtonStateId, () => ReactElement>
+> = {
+ 'standalone-unpressed': () => renderStateById('standalone-unpressed'),
+ 'standalone-pressed': () => renderStateById('standalone-pressed'),
+ 'icon-only-unpressed': () => renderStateById('icon-only-unpressed'),
+ 'composed-label-pressed': () => renderStateById('composed-label-pressed'),
+ 'disabled-unpressed': () => renderStateById('disabled-unpressed'),
+ 'disabled-with-tooltip-pressed': () =>
+ renderStateById('disabled-with-tooltip-pressed'),
+ 'single-group-unpressed': () => renderStateById('single-group-unpressed'),
+ 'single-group-pressed': () => renderStateById('single-group-pressed'),
+ 'single-group-member-disabled': () =>
+ renderStateById('single-group-member-disabled'),
+ 'single-group-disabled-member-silent': () =>
+ renderStateById('single-group-disabled-member-silent'),
+ 'multiple-group-unpressed': () => renderStateById('multiple-group-unpressed'),
+ 'multiple-group-pressed': () => renderStateById('multiple-group-pressed'),
+};
+
+function renderStateById(id: ToggleButtonStateId): ReactElement {
+ // The inventory owns each state; this lookup keeps the render map exhaustive
+ // without copying its facts into a second file.
+ return renderState(requireState(id));
+}
+
+function requireState(id: ToggleButtonStateId): ToggleButtonBindingRow {
+ const state = TOGGLE_BUTTON_BINDING_STATES.find(
+ candidate => candidate.id === id,
+ );
+ if (state == null) {
+ throw new Error(`unknown ToggleButton state "${id}"`);
+ }
+ return state;
+}
diff --git a/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.states.ts b/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.states.ts
new file mode 100644
index 0000000000..13173ec0d6
--- /dev/null
+++ b/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.states.ts
@@ -0,0 +1,167 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ToggleButton.a11y.states.ts
+ * @input Uses ToggleButtonStateFacts from @astryxdesign/a11y-spec
+ * @output The finite ToggleButton state inventory shared by jsdom and Chromium
+ * @position Records every state that can change the toggle-button contract.
+ */
+
+import type {ToggleButtonStateFacts} from '@astryxdesign/a11y-spec';
+
+export interface ToggleButtonBindingState {
+ readonly id: string;
+ readonly summary: string;
+ readonly storyId: string;
+ readonly visibleLabel: string | null;
+ readonly renderKind:
+ | 'standalone'
+ | 'icon-only'
+ | 'composed-label'
+ | 'single-group'
+ | 'multiple-group';
+ readonly facts: ToggleButtonStateFacts;
+ readonly tooltip?: string;
+ readonly groupDisabled?: boolean;
+ readonly memberDisabled?: boolean;
+}
+
+const facts = (
+ pressed: boolean,
+ overrides: Partial<ToggleButtonStateFacts> = {},
+): ToggleButtonStateFacts => ({
+ pressed,
+ operable: true,
+ focusable: true,
+ unavailable: false,
+ described: false,
+ ...overrides,
+});
+
+export const TOGGLE_BUTTON_BINDING_STATES = [
+ {
+ id: 'standalone-unpressed',
+ summary: 'a standalone text toggle that starts unpressed',
+ storyId: 'a11y-toggle-button-pattern--standalone-unpressed',
+ visibleLabel: 'Bold',
+ renderKind: 'standalone',
+ facts: facts(false),
+ },
+ {
+ id: 'standalone-pressed',
+ summary: 'a standalone text toggle that starts pressed',
+ storyId: 'a11y-toggle-button-pattern--standalone-pressed',
+ visibleLabel: 'Bold',
+ renderKind: 'standalone',
+ facts: facts(true),
+ },
+ {
+ id: 'icon-only-unpressed',
+ summary: 'an icon-only toggle named by its label',
+ storyId: 'a11y-toggle-button-pattern--icon-only-unpressed',
+ visibleLabel: null,
+ renderKind: 'icon-only',
+ facts: facts(false),
+ },
+ {
+ id: 'composed-label-pressed',
+ summary: 'a pressed toggle whose custom visible content matches its name',
+ storyId: 'a11y-toggle-button-pattern--composed-label-pressed',
+ visibleLabel: 'Bold formatting',
+ renderKind: 'composed-label',
+ facts: facts(true),
+ },
+ {
+ id: 'disabled-unpressed',
+ summary: 'a natively disabled standalone toggle',
+ storyId: 'a11y-toggle-button-pattern--disabled-unpressed',
+ visibleLabel: 'Bold',
+ renderKind: 'standalone',
+ facts: facts(false, {operable: false, focusable: false, unavailable: true}),
+ },
+ {
+ id: 'disabled-with-tooltip-pressed',
+ summary:
+ 'an aria-disabled pressed toggle kept focusable by its explanation',
+ storyId: 'a11y-toggle-button-pattern--disabled-with-tooltip-pressed',
+ visibleLabel: 'Bold',
+ renderKind: 'standalone',
+ tooltip: 'Formatting is locked for this document',
+ facts: facts(true, {operable: false, unavailable: true, described: true}),
+ },
+ {
+ id: 'single-group-unpressed',
+ summary: 'an unselected member of a single-selection ToggleButtonGroup',
+ storyId: 'a11y-toggle-button-pattern--single-group-unpressed',
+ visibleLabel: 'List',
+ renderKind: 'single-group',
+ facts: facts(false),
+ },
+ {
+ id: 'single-group-pressed',
+ summary: 'the selected member of a single-selection ToggleButtonGroup',
+ storyId: 'a11y-toggle-button-pattern--single-group-pressed',
+ visibleLabel: 'List',
+ renderKind: 'single-group',
+ facts: facts(true),
+ },
+ {
+ id: 'single-group-member-disabled',
+ summary: 'a disabled member inside an enabled ToggleButtonGroup',
+ storyId: 'a11y-toggle-button-pattern--single-group-member-disabled',
+ visibleLabel: 'List',
+ renderKind: 'single-group',
+ memberDisabled: true,
+ facts: facts(false, {operable: false, focusable: false, unavailable: true}),
+ },
+ {
+ id: 'single-group-disabled-member-silent',
+ summary: 'an otherwise enabled member inside a disabled ToggleButtonGroup',
+ storyId: 'a11y-toggle-button-pattern--single-group-disabled-member-silent',
+ visibleLabel: 'List',
+ renderKind: 'single-group',
+ groupDisabled: true,
+ facts: facts(false, {operable: false, focusable: false, unavailable: true}),
+ },
+ {
+ id: 'multiple-group-unpressed',
+ summary: 'an unselected member of a multiple-selection ToggleButtonGroup',
+ storyId: 'a11y-toggle-button-pattern--multiple-group-unpressed',
+ visibleLabel: 'Bold',
+ renderKind: 'multiple-group',
+ facts: facts(false),
+ },
+ {
+ id: 'multiple-group-pressed',
+ summary: 'a selected member of a multiple-selection ToggleButtonGroup',
+ storyId: 'a11y-toggle-button-pattern--multiple-group-pressed',
+ visibleLabel: 'Bold',
+ renderKind: 'multiple-group',
+ facts: facts(true),
+ },
+] as const satisfies ReadonlyArray<ToggleButtonBindingState>;
+
+export type ToggleButtonBindingRow =
+ (typeof TOGGLE_BUTTON_BINDING_STATES)[number];
+export type ToggleButtonStateId = ToggleButtonBindingRow['id'];
+
+export const TOGGLE_BUTTON_PATTERN_EXCLUSIONS = [
+ {
+ id: 'group-semantics',
+ owner: 'ToggleButton.test.tsx',
+ reason:
+ 'The reusable toggle-button contract owns each pressed button. Group naming, single/multiple selection policy, and sibling coordination remain ToggleButtonGroup behavior.',
+ },
+ {
+ id: 'pending-action-semantics',
+ owner: 'ToggleButton.test.tsx and family:buttons FR4-FR5',
+ reason:
+ 'Optimistic Action state, callback ordering, cancellation, and pending feedback are component and family behavior; they are not generic toggle-button semantics.',
+ },
+ {
+ id: 'rendered-appearance',
+ owner: 'ToggleButton visual, forced-colors, axe, and RTL gates',
+ reason:
+ 'Pressed treatment, contrast, target size, focus paint, icon replacement, dimensions, motion, and direction are rendered evidence outside this semantic contract.',
+ },
+] as const;
diff --git a/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.test.tsx b/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.test.tsx
new file mode 100644
index 0000000000..fe4a4cb60f
--- /dev/null
+++ b/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.test.tsx
@@ -0,0 +1,103 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file ToggleButton.a11y.test.tsx
+ * @input Uses ToggleButton renderings and the reusable toggle-button contract
+ * @output DOM evidence for every ToggleButton binding state
+ * @position Component binding; browser-owned outcomes run in the Chromium lane.
+ */
+
+import {cleanup, render, screen} from '@testing-library/react';
+import {describe, expect, it} from 'vitest';
+import {
+ TOGGLE_BUTTON_PATTERN,
+ checkAccessibilitySpec,
+ createJsdomHarness,
+ expectAccessibilitySpec,
+ summarize,
+ type BindingResult,
+} from '@astryxdesign/a11y-spec';
+import {TOGGLE_BUTTON_STATE_RENDERS} from './ToggleButton.a11y.renders';
+import {
+ TOGGLE_BUTTON_BINDING_STATES,
+ TOGGLE_BUTTON_PATTERN_EXCLUSIONS,
+ type ToggleButtonBindingRow,
+} from './ToggleButton.a11y.states';
+
+function subjectFor(): Element {
+ return screen.getByRole('button', {hidden: true});
+}
+
+async function expectState(state: ToggleButtonBindingRow): Promise<void> {
+ await expectAccessibilitySpec({
+ spec: TOGGLE_BUTTON_PATTERN,
+ binding: 'ToggleButton',
+ state: state.id,
+ facts: state.facts,
+ render: () => {
+ render(TOGGLE_BUTTON_STATE_RENDERS[state.id]());
+ },
+ subject: subjectFor,
+ cleanup,
+ });
+}
+
+async function checkState(
+ state: ToggleButtonBindingRow,
+): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: TOGGLE_BUTTON_PATTERN,
+ binding: 'ToggleButton',
+ state: state.id,
+ facts: state.facts,
+ mount: async () => {
+ render(TOGGLE_BUTTON_STATE_RENDERS[state.id]());
+ return createJsdomHarness({subject: subjectFor()});
+ },
+ unmount: cleanup,
+ });
+}
+
+describe('ToggleButton — toggle-button pattern, jsdom lane', () => {
+ it.each(
+ TOGGLE_BUTTON_BINDING_STATES.map(
+ state => [state.id, state.summary, state] as const,
+ ),
+ )('%s — %s', async (_id, _summary, state) => expectState(state));
+
+ it('runs DOM evidence and reports browser-owned layers as unrun', async () => {
+ const results: BindingResult[] = [];
+ for (const state of TOGGLE_BUTTON_BINDING_STATES) {
+ results.push(await checkState(state));
+ }
+ const report = summarize(TOGGLE_BUTTON_PATTERN, results);
+ expect(report.counts.pass).toBeGreaterThan(0);
+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+});
+
+describe('ToggleButton binding inventory', () => {
+ it('retains disabled ownership through both member and group paths', () => {
+ expect(TOGGLE_BUTTON_BINDING_STATES.map(state => state.id)).toEqual(
+ expect.arrayContaining([
+ 'single-group-member-disabled',
+ 'single-group-disabled-member-silent',
+ ]),
+ );
+ });
+
+ it('gives every representative state a distinct story', () => {
+ const stories = TOGGLE_BUTTON_BINDING_STATES.map(state => state.storyId);
+ expect(new Set(stories).size).toBe(stories.length);
+ });
+
+ it('keeps adjacent owners explicit', () => {
+ expect(TOGGLE_BUTTON_PATTERN_EXCLUSIONS.map(row => row.id)).toEqual([
+ 'group-semantics',
+ 'pending-action-semantics',
+ 'rendered-appearance',
+ ]);
+ });
+});