Skip to content

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

TypeScript

test(a11y): Accordion contract and CollapsibleGroup binding (#7468)

Cindy Zhangd5b123da05d8
diff --git a/.github/scripts/pr-scope-touches.test.mjs b/.github/scripts/pr-scope-touches.test.mjs
index 17b7861db4..12570d2680 100644
--- a/.github/scripts/pr-scope-touches.test.mjs
+++ b/.github/scripts/pr-scope-touches.test.mjs
@@ -179,7 +179,9 @@ describe('pr-scope-touches', () => {
workflow.match(
/git show "\$BASE_SHA:\.github\/scripts\/pr-scope-touches\.sh" > "\$helper"/g,
) ?? [];
- expect(uses.length).toBe(4);
+ // Every consumer loads the helper from the base; new contract steps add
+ // consumers, so the count is a floor, not an exact tally.
+ expect(uses.length).toBeGreaterThanOrEqual(4);
expect(fromBase.length).toBe(uses.length);
expect(workflow).not.toMatch(/bash \.github\/scripts\/pr-scope-touches/);
});
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 99bca65033..9427ef519f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1580,6 +1580,54 @@ jobs:
retention-days: 30
if-no-files-found: warn
+ # The accordion contract's header role and name, the page Tab step between
+ # headers, the absence of arrow-key focus movement, and the single-expansion
+ # sibling collapse are accessibility-tree and real-browser facts that jsdom
+ # cannot observe. Run the contract's own fixture proof and the
+ # CollapsibleGroup binding whenever Collapsible source, the binding's
+ # stories, or the contract changes. Its own --output directory; the JSON
+ # report is the head-bound record, uploaded next.
+ - name: Run Accordion accessibility contract
+ id: accordion-contract
+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}
+ env:
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ PLAYWRIGHT_JSON_OUTPUT_FILE: accordion-contract/report.json
+ run: |
+ should_run=false
+ # Collapsible and the contract are matched by file name.
+ # The helper comes from the base, since an older PR head lacks it.
+ # Exit 1 means out of scope; 0 in scope; 2 unknown, so run.
+ scope=2
+ helper="$(mktemp)"
+ if git fetch --quiet --no-tags --depth=1 origin "$BASE_SHA" \
+ && git show "$BASE_SHA:.github/scripts/pr-scope-touches.sh" > "$helper"; then
+ scope=0
+ bash "$helper" "$BASE_SHA" \
+ '^(internal/a11y-spec/src/patterns/accordion|packages/core/src/Collapsible/|apps/storybook/stories/CollapsibleGroupA11y)' || scope=$?
+ fi
+ if [ "$scope" != 1 ]; then
+ should_run=true
+ fi
+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"
+ if [ "$should_run" != true ]; then
+ echo "CollapsibleGroup and the accordion contract are not in PR scope; skipping accordion evidence."
+ exit 0
+ fi
+ pnpm exec playwright test \
+ internal/a11y-spec/src/patterns/accordion.chromium.spec.ts \
+ packages/core/src/Collapsible/__tests__/CollapsibleGroupAccordion.a11y.chromium.spec.ts \
+ --project chromium \
+ --reporter list,json \
+ --output accordion-contract-output
+
+ - name: Upload Accordion accessibility contract evidence
+ if: ${{ !cancelled() && steps.accordion-contract.outputs.should_run == 'true' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: accordion-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: accordion-contract/
+
# The link contract's role, name, Tab, Enter, and pointer-release outcomes
# are accessibility-tree and real-browser facts that jsdom cannot observe.
# Run the contract's own fixture proof and the Link binding whenever Link
diff --git a/apps/storybook/stories/CollapsibleGroupA11y.stories.tsx b/apps/storybook/stories/CollapsibleGroupA11y.stories.tsx
new file mode 100644
index 0000000000..da1edceee0
--- /dev/null
+++ b/apps/storybook/stories/CollapsibleGroupA11y.stories.tsx
@@ -0,0 +1,39 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CollapsibleGroupA11y.stories.tsx
+ * @input The CollapsibleGroup accordion binding states, rendered through the binding's own renderer so the jsdom and Chromium lanes see the same tree
+ * @output One checked-in story per state for the Chromium accessibility lane; excluded from the visual matrix
+ * @position Browser fixtures for component:CollapsibleGroup AR4 (ACCORDION_PATTERN)
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {renderAccordionState} from '../../../packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.renders';
+import {COLLAPSIBLE_GROUP_ACCORDION_STATES} from '../../../packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.states';
+
+const meta = {
+ title: 'A11y/CollapsibleGroup Accordion',
+ tags: ['no-visual'],
+ parameters: {layout: 'padded'},
+} satisfies Meta;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+function storyFor(
+ id: (typeof COLLAPSIBLE_GROUP_ACCORDION_STATES)[number]['id'],
+): Story {
+ const state = COLLAPSIBLE_GROUP_ACCORDION_STATES.find(
+ candidate => candidate.id === id,
+ );
+ if (state == null) {
+ throw new Error(`no CollapsibleGroup accordion state "${id}"`);
+ }
+ return {render: () => renderAccordionState(state)};
+}
+
+export const SingleCollapsedMiddle = storyFor('single-collapsed-middle');
+export const SingleExpandedFirst = storyFor('single-expanded-first');
+export const MultipleCollapsedLast = storyFor('multiple-collapsed-last');
+export const SingleDisabledCollapsed = storyFor('single-disabled-collapsed');
+export const SingleDisabledExpanded = storyFor('single-disabled-expanded');
diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.md
index 44bcc85611..4df230dce4 100644
--- a/internal/a11y-spec/README.md
+++ b/internal/a11y-spec/README.md
@@ -51,6 +51,7 @@ src/
├── listbox.* listbox, group, and option semantics
├── spinbutton.* numeric role, value, bounds, state, and arrow stepping
├── disclosure.* standalone disclosure state/content semantics
+ ├── accordion.* a group's header role and name, panel state, single-expansion collapse, page Tab order
├── breadcrumb.* landmark, list-trail, current-page, and separator semantics
├── landmark.* one component-owned landmark region's role, name, and content boundary
└── link.* one available link's role, name, current state, focus, and activation
@@ -58,23 +59,24 @@ src/
## The patterns
-| Pattern | Adopted from | Bound by |
-| ---------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
-| `radio-group` | [APG radio group](https://www.w3.org/WAI/ARIA/apg/patterns/radio/) | RadioList, SegmentedControl; role/state portions of DropdownMenu radio items |
-| `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 |
-| `tabs` | [APG Tabs](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/) | Explicit `role="tablist"` TabList, Tab, and caller-authored tabpanels |
-| `listbox` | [WAI-ARIA 1.2 Listbox](https://www.w3.org/TR/wai-aria-1.2/#listbox) and WCAG 2.2 semantics | Selector and MultiSelector popup listbox, group, and option parts |
-| `spinbutton` | WCAG 2.2 semantics and [APG Spinbutton](https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/) | NumberInput |
-| `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 |
-| `landmark` | WCAG 2.2 semantics; [APG Landmark Regions](https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/) as context | LayoutHeader, LayoutContent, LayoutFooter, and LayoutPanel caller-declared landmarks |
-| `link` | WCAG 2.2 semantics; [APG Link](https://www.w3.org/WAI/ARIA/apg/patterns/link/) role and Enter mechanics | Link, including LinkProvider and `as` router components |
+| Pattern | Adopted from | Bound by |
+| ---------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `radio-group` | [APG radio group](https://www.w3.org/WAI/ARIA/apg/patterns/radio/) | RadioList, SegmentedControl; role/state portions of DropdownMenu radio items |
+| `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 |
+| `tabs` | [APG Tabs](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/) | Explicit `role="tablist"` TabList, Tab, and caller-authored tabpanels |
+| `listbox` | [WAI-ARIA 1.2 Listbox](https://www.w3.org/TR/wai-aria-1.2/#listbox) and WCAG 2.2 semantics | Selector and MultiSelector popup listbox, group, and option parts |
+| `spinbutton` | WCAG 2.2 semantics and [APG Spinbutton](https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/) | NumberInput |
+| `disclosure` | [APG Disclosure](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/) | Standalone Collapsible triggers and their controlled content |
+| `accordion` | [APG Accordion](https://www.w3.org/WAI/ARIA/apg/patterns/accordion/) required parts | CollapsibleGroup headers: button role and name, expanded state, controlled panel, Enter/Space, single-expansion sibling collapse, page Tab order, no arrow-key movement (single-expansion collapse, grouped Tab order, no arrow movement are advisory until `component:CollapsibleGroup` AR4 is current) |
+| `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 |
+| `landmark` | WCAG 2.2 semantics; [APG Landmark Regions](https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/) as context | LayoutHeader, LayoutContent, LayoutFooter, and LayoutPanel caller-declared landmarks |
+| `link` | WCAG 2.2 semantics; [APG Link](https://www.w3.org/WAI/ARIA/apg/patterns/link/) role and Enter mechanics | Link, including LinkProvider and `as` router components |
The toggle-button contract owns the persistent-action extension of button
semantics: the pressed state must be exposed, reversible by pointer, Enter, and
diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.ts
index 825067e960..11f2610ba1 100644
--- a/internal/a11y-spec/src/index.ts
+++ b/internal/a11y-spec/src/index.ts
@@ -139,6 +139,10 @@ export {
type LandmarkStateFacts,
} from './patterns/landmark';
+export {
+ ACCORDION_PATTERN,
+ type AccordionStateFacts,
+} from './patterns/accordion';
export {
LINK_PATTERN,
type LinkCurrentToken,
diff --git a/internal/a11y-spec/src/patterns/accordion.chromium.spec.ts b/internal/a11y-spec/src/patterns/accordion.chromium.spec.ts
new file mode 100644
index 0000000000..526506f6d8
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/accordion.chromium.spec.ts
@@ -0,0 +1,103 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file accordion.chromium.spec.ts
+ * @input ACCORDION_PATTERN and its fixtures in real Chromium
+ * @output Proof that every expectation passes conforming fixtures and fails its mutation at the layers only a browser observes
+ * @position Contract self-test, Chromium lane
+ */
+
+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 {ACCORDION_PATTERN} from './accordion';
+import {
+ ACCORDION_MUTATIONS,
+ CONFORMING_FIXTURES,
+ NEXT_HEADER_SELECTOR,
+ OPEN_SIBLING_SELECTOR,
+ PANEL_SELECTOR,
+ SUBJECT_SELECTOR,
+ fixture,
+ type AccordionFixture,
+} from './accordion.fixtures';
+
+function fixturePage(html: string): string {
+ return `<!doctype html><html lang="en"><body>${html}<button type="button" id="after">After accordion</button></body></html>`;
+}
+
+async function results(
+ page: Page,
+ cdp: CDPSession,
+ target: AccordionFixture,
+ only?: readonly string[],
+): Promise<readonly ExpectationResult[]> {
+ const run = await checkAccessibilitySpec({
+ spec: ACCORDION_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),
+ related: {
+ panel: page.locator(PANEL_SELECTOR),
+ 'next-header': page.locator(NEXT_HEADER_SELECTOR),
+ 'open-sibling': page.locator(OPEN_SIBLING_SELECTOR),
+ },
+ });
+ },
+ });
+ return run.results;
+}
+
+test.describe('accordion 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('accordion contract — deliberately violating fixtures', () => {
+ for (const expectation of ACCORDION_PATTERN.expectations) {
+ if (
+ !requiredLayers(expectation).every(layer =>
+ CHROMIUM_OBSERVES.includes(layer),
+ )
+ ) {
+ continue;
+ }
+ for (const fixtureId of ACCORDION_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/accordion.fixtures.ts b/internal/a11y-spec/src/patterns/accordion.fixtures.ts
new file mode 100644
index 0000000000..9069c53060
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/accordion.fixtures.ts
@@ -0,0 +1,314 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file accordion.fixtures.ts
+ * @input Plain HTML accordions with three headers, conforming and deliberately violating
+ * @output ACCORDION_FIXTURES, the subject and relation selectors, and the expectation → violating-fixture map
+ * @position Contract self-test data for accordion.jsdom.test.ts and accordion.chromium.spec.ts
+ */
+
+import type {AccordionStateFacts} from './accordion';
+
+const SUBJECT_ATTRIBUTE = 'data-a11y-subject';
+export const SUBJECT_SELECTOR = `[${SUBJECT_ATTRIBUTE}]`;
+export const PANEL_SELECTOR = '#panel-2';
+export const NEXT_HEADER_SELECTOR = '#header-3';
+export const OPEN_SIBLING_SELECTOR = '#header-1';
+
+export interface AccordionFixture {
+ readonly id: string;
+ readonly summary: string;
+ readonly facts: AccordionStateFacts;
+ readonly html: string;
+}
+
+/**
+ * The subject is always the second header. Header 1 starts expanded, header 2
+ * collapsed, header 3 collapsed; `single` fixtures collapse the other open
+ * header when one expands.
+ */
+const TOGGLE_MULTIPLE = `const open = this.getAttribute('aria-expanded') !== 'true'; this.setAttribute('aria-expanded', String(open)); document.getElementById(this.getAttribute('aria-controls')).hidden = !open;`;
+const TOGGLE_SINGLE = `const open = this.getAttribute('aria-expanded') !== 'true'; if (open) { for (const other of document.querySelectorAll('[data-accordion-header]')) { if (other !== this) { other.setAttribute('aria-expanded', 'false'); document.getElementById(other.getAttribute('aria-controls')).hidden = true; } } } this.setAttribute('aria-expanded', String(open)); document.getElementById(this.getAttribute('aria-controls')).hidden = !open;`;
+const TOGGLE_SINGLE_NO_COLLAPSE = TOGGLE_MULTIPLE;
+const STATE_ONLY = `this.setAttribute('aria-expanded', String(this.getAttribute('aria-expanded') !== 'true'));`;
+const ARROW_MOVES = `if (event.key === 'ArrowDown') { event.preventDefault(); document.getElementById('header-3').focus(); } if (event.key === 'ArrowUp') { event.preventDefault(); document.getElementById('header-1').focus(); }`;
+
+function header(
+ index: 1 | 2 | 3,
+ {
+ expanded,
+ tag = 'button',
+ controls = `panel-${index}`,
+ onclick,
+ onkeydown = '',
+ disabled = false,
+ subject = false,
+ tabindex = '',
+ }: {
+ expanded: boolean;
+ tag?: string;
+ controls?: string | null;
+ onclick: string;
+ onkeydown?: string;
+ disabled?: boolean;
+ subject?: boolean;
+ tabindex?: string;
+ },
+): string {
+ const typeAttr = tag === 'button' ? ' type="button"' : '';
+ return `<${tag}${typeAttr} id="header-${index}" data-accordion-header${subject ? ` ${SUBJECT_ATTRIBUTE}` : ''} aria-expanded="${expanded}"${controls == null ? '' : ` aria-controls="${controls}"`}${disabled ? ' aria-disabled="true"' : ''}${tabindex === '' ? '' : ` tabindex="${tabindex}"`}${onclick === '' ? '' : ` onclick="${onclick}"`}${onkeydown === '' ? '' : ` onkeydown="${onkeydown}"`}>Section ${index}</${tag}>`;
+}
+
+function panel(index: 1 | 2 | 3, hidden: boolean): string {
+ return `<div id="panel-${index}"${hidden ? ' hidden' : ''}>Body ${index}</div>`;
+}
+
+function accordion({
+ single = true,
+ subjectExpanded = false,
+ subjectTag = 'button',
+ subjectControls = `panel-2`,
+ subjectOnclick,
+ subjectOnkeydown = '',
+ subjectDisabled = false,
+ subjectPanelHidden,
+ subjectTabindex = '',
+ siblingToggle,
+}: {
+ single?: boolean;
+ subjectExpanded?: boolean;
+ subjectTag?: string;
+ subjectControls?: string | null;
+ subjectOnclick?: string;
+ subjectOnkeydown?: string;
+ subjectDisabled?: boolean;
+ subjectPanelHidden?: boolean;
+ subjectTabindex?: string;
+ siblingToggle?: string;
+} = {}): string {
+ const toggle = single ? TOGGLE_SINGLE : TOGGLE_MULTIPLE;
+ return [
+ header(1, {expanded: true, onclick: siblingToggle ?? toggle}),
+ panel(1, false),
+ header(2, {
+ expanded: subjectExpanded,
+ tag: subjectTag,
+ controls: subjectControls,
+ onclick: subjectOnclick ?? toggle,
+ onkeydown: subjectOnkeydown,
+ disabled: subjectDisabled,
+ subject: true,
+ tabindex: subjectTabindex,
+ }),
+ panel(2, subjectPanelHidden ?? !subjectExpanded),
+ header(3, {expanded: false, onclick: toggle}),
+ panel(3, true),
+ ].join('');
+}
+
+const facts = (
+ overrides: Partial<AccordionStateFacts> = {},
+): AccordionStateFacts => ({
+ expanded: false,
+ operable: true,
+ focusable: true,
+ single: true,
+ hasNextHeader: true,
+ hasOpenSibling: true,
+ ...overrides,
+});
+
+export const ACCORDION_FIXTURES: readonly AccordionFixture[] = [
+ {
+ id: 'conforming-single-collapsed',
+ summary:
+ 'a collapsed header in a single-expansion group whose sibling is open',
+ facts: facts(),
+ html: accordion(),
+ },
+ {
+ id: 'conforming-single-expanded',
+ summary: 'an expanded header in a single-expansion group',
+ facts: facts({expanded: true, hasOpenSibling: false}),
+ html: accordion({subjectExpanded: true, siblingToggle: TOGGLE_SINGLE})
+ .replace(
+ 'id="header-1" data-accordion-header aria-expanded="true"',
+ 'id="header-1" data-accordion-header aria-expanded="false"',
+ )
+ .replace('<div id="panel-1">', '<div id="panel-1" hidden>'),
+ },
+ {
+ id: 'conforming-multiple-collapsed',
+ summary: 'a collapsed header in a group that allows several open panels',
+ facts: facts({single: false}),
+ html: accordion({single: false}),
+ },
+ {
+ id: 'conforming-fixed-open',
+ summary:
+ 'an expanded header that cannot be collapsed and says so with aria-disabled',
+ facts: facts({
+ expanded: true,
+ operable: false,
+ focusable: true,
+ hasOpenSibling: false,
+ }),
+ html: accordion({
+ subjectExpanded: true,
+ subjectOnclick: '',
+ subjectDisabled: true,
+ }),
+ },
+ {
+ id: 'violating-header-not-button',
+ summary: 'a header rendered as a div with no role',
+ facts: facts(),
+ html: accordion({subjectTag: 'div', subjectTabindex: '0'}),
+ },
+ {
+ id: 'violating-expanded-missing',
+ summary: 'a header with no aria-expanded',
+ facts: facts(),
+ html: accordion().replace(
+ `${SUBJECT_ATTRIBUTE} aria-expanded="false"`,
+ SUBJECT_ATTRIBUTE,
+ ),
+ },
+ {
+ id: 'violating-controls-missing',
+ summary: 'a header that does not name its panel',
+ facts: facts(),
+ html: accordion({subjectControls: null}),
+ },
+ {
+ id: 'violating-controls-unrelated',
+ summary: 'a header whose aria-controls points at another panel',
+ facts: facts(),
+ html: accordion({subjectControls: 'panel-3'}),
+ },
+ {
+ id: 'violating-fixed-not-disabled',
+ summary:
+ 'an expanded header that cannot be collapsed but carries no aria-disabled',
+ facts: facts({
+ expanded: true,
+ operable: false,
+ focusable: true,
+ hasOpenSibling: false,
+ }),
+ html: accordion({subjectExpanded: true, subjectOnclick: ''}),
+ },
+ {
+ id: 'violating-collapsed-panel-visible',
+ summary: 'a collapsed header whose panel stays visible',
+ facts: facts(),
+ html: accordion({subjectPanelHidden: false}),
+ },
+ {
+ id: 'violating-enter-unavailable',
+ summary: 'a header that blocks Enter',
+ facts: facts(),
+ html: accordion({
+ subjectOnkeydown: "if (event.key === 'Enter') event.preventDefault();",
+ }),
+ },
+ {
+ id: 'violating-space-unavailable',
+ summary: 'a header that blocks Space',
+ facts: facts(),
+ html: accordion({
+ subjectOnkeydown: "if (event.key === ' ') event.preventDefault();",
+ }),
+ },
+ {
+ id: 'violating-state-only',
+ summary: 'a header that changes aria-expanded without showing its panel',
+ facts: facts(),
+ html: accordion({subjectOnclick: STATE_ONLY}),
+ },
+ {
+ id: 'violating-down-event-activation',
+ summary:
+ 'a header that toggles on pointer-down before the user can cancel the press',
+ facts: facts(),
+ html: accordion({subjectOnclick: ''}).replace(
+ `${SUBJECT_ATTRIBUTE} aria-expanded="false"`,
+ `${SUBJECT_ATTRIBUTE} aria-expanded="false" onpointerdown="${TOGGLE_SINGLE}"`,
+ ),
+ },
+ {
+ id: 'violating-focus-moved',
+ summary: 'a header that moves focus into its panel when toggled',
+ facts: facts(),
+ html: accordion({
+ subjectOnclick: `${TOGGLE_SINGLE} document.getElementById('panel-2').focus();`,
+ }).replace(
+ '<div id="panel-2" hidden>',
+ '<div id="panel-2" hidden tabindex="-1">',
+ ),
+ },
+ {
+ id: 'violating-single-keeps-sibling',
+ summary:
+ 'a single-expansion group that leaves the open sibling expanded when another header opens',
+ facts: facts(),
+ html: accordion({subjectOnclick: TOGGLE_SINGLE_NO_COLLAPSE}),
+ },
+ {
+ id: 'violating-next-header-out-of-tab-order',
+ summary: 'the following header is removed from the Tab sequence',
+ facts: facts(),
+ html: accordion().replace(
+ 'id="header-3" data-accordion-header',
+ 'id="header-3" data-accordion-header tabindex="-1"',
+ ),
+ },
+ {
+ id: 'violating-arrows-move-focus',
+ summary:
+ 'arrow keys move focus between headers as if the group were one widget',
+ facts: facts(),
+ html: accordion({subjectOnkeydown: ARROW_MOVES}),
+ },
+];
+
+export function fixture(id: string): AccordionFixture {
+ const found = ACCORDION_FIXTURES.find(candidate => candidate.id === id);
+ if (found == null) {
+ throw new Error(`unknown accordion fixture "${id}"`);
+ }
+ return found;
+}
+
+export const CONFORMING_FIXTURES: readonly string[] = ACCORDION_FIXTURES.filter(
+ candidate => candidate.id.startsWith('conforming-'),
+).map(candidate => candidate.id);
+
+export const ACCORDION_MUTATIONS: Readonly<Record<string, readonly string[]>> =
+ {
+ 'accordion.header.role-and-name': ['violating-header-not-button'],
+ 'accordion.header.expanded-state': ['violating-expanded-missing'],
+ 'accordion.header.controls-panel': [
+ 'violating-controls-missing',
+ 'violating-controls-unrelated',
+ ],
+ 'accordion.header.disabled-when-fixed': ['violating-fixed-not-disabled'],
+ 'accordion.panel.matches-state': ['violating-collapsed-panel-visible'],
+ 'accordion.header.enter-round-trip': [
+ 'violating-enter-unavailable',
+ 'violating-state-only',
+ ],
+ 'accordion.header.space-round-trip': [
+ 'violating-space-unavailable',
+ 'violating-state-only',
+ ],
+ 'accordion.header.survives-an-aborted-press': [
+ 'violating-down-event-activation',
+ ],
+ 'accordion.focus.stays-on-header': ['violating-focus-moved'],
+ 'accordion.group.single-collapses-sibling': [
+ 'violating-single-keeps-sibling',
+ ],
+ 'accordion.group.tab-order': ['violating-next-header-out-of-tab-order'],
+ 'accordion.group.arrows-do-not-move-focus': ['violating-arrows-move-focus'],
+ };
diff --git a/internal/a11y-spec/src/patterns/accordion.jsdom.test.ts b/internal/a11y-spec/src/patterns/accordion.jsdom.test.ts
new file mode 100644
index 0000000000..c6d2d7eb28
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/accordion.jsdom.test.ts
@@ -0,0 +1,174 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file accordion.jsdom.test.ts
+ * @input ACCORDION_PATTERN and its conforming and violating fixtures
+ * @output Proof that the contract is complete, that every DOM-layer expectation passes conforming fixtures and fails its mutation, and that jsdom reports browser layers as unrun
+ * @position Contract self-test, jsdom lane
+ */
+
+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 {ACCORDION_PATTERN} from './accordion';
+import {
+ ACCORDION_MUTATIONS,
+ CONFORMING_FIXTURES,
+ NEXT_HEADER_SELECTOR,
+ OPEN_SIBLING_SELECTOR,
+ PANEL_SELECTOR,
+ SUBJECT_SELECTOR,
+ fixture,
+ type AccordionFixture,
+} from './accordion.fixtures';
+
+const observableHere = ACCORDION_PATTERN.expectations.filter(expectation =>
+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),
+);
+
+afterEach(() => document.body.replaceChildren());
+
+async function resultsFor(target: AccordionFixture) {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const result = await checkAccessibilitySpec({
+ spec: ACCORDION_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ mount: async () => {
+ container.innerHTML = target.html;
+ const subject = container.querySelector(SUBJECT_SELECTOR);
+ const panel = container.querySelector(PANEL_SELECTOR);
+ const nextHeader = container.querySelector(NEXT_HEADER_SELECTOR);
+ const openSibling = container.querySelector(OPEN_SIBLING_SELECTOR);
+ if (
+ subject == null ||
+ panel == null ||
+ nextHeader == null ||
+ openSibling == null
+ ) {
+ throw new Error(
+ `fixture "${target.id}" is missing its subject or a relation`,
+ );
+ }
+ return createJsdomHarness({
+ subject,
+ related: {
+ panel,
+ 'next-header': nextHeader,
+ 'open-sibling': openSibling,
+ },
+ });
+ },
+ 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('accordion contract — completeness', () => {
+ it('answers every completeness dimension', () => {
+ expect(unansweredDimensions(ACCORDION_PATTERN)).toEqual([]);
+ });
+
+ it('gives every expectation at least one deliberately violating fixture', () => {
+ const missing = ACCORDION_PATTERN.expectations
+ .filter(
+ expectation => (ACCORDION_MUTATIONS[expectation.id] ?? []).length === 0,
+ )
+ .map(expectation => expectation.id);
+ expect(missing).toEqual([]);
+ });
+
+ it('has an expectation for every mutation it records', () => {
+ const ids = new Set(
+ ACCORDION_PATTERN.expectations.map(expectation => expectation.id),
+ );
+ expect(Object.keys(ACCORDION_MUTATIONS).filter(id => !ids.has(id))).toEqual(
+ [],
+ );
+ });
+
+ it('names every fixture it records a mutation against', () => {
+ for (const fixtures of Object.values(ACCORDION_MUTATIONS)) {
+ for (const id of fixtures) {
+ expect(() => fixture(id)).not.toThrow();
+ }
+ }
+ });
+});
+
+describe('accordion contract — the jsdom harness stays within its evidence boundary', () => {
+ it('runs DOM expectations and reports browser expectations as unrun', async () => {
+ const results = await resultsFor(fixture('conforming-single-collapsed'));
+ expect(results.some(result => result.status === 'pass')).toBe(true);
+ const above = results.filter(result => result.status === 'unrun');
+ expect(above.length).toBeGreaterThan(0);
+ for (const result of above) {
+ expect(
+ (result.missingLayers ?? []).some(
+ layer => layer === 'real-browser' || layer === 'accessibility-tree',
+ ),
+ ).toBe(true);
+ }
+ });
+});
+
+describe.each(observableHere.map(expectation => [expectation.id] as const))(
+ '%s',
+ id => {
+ const expectation = ACCORDION_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 result = resultFor(await resultsFor(fixture(name)), id);
+ expect(
+ ['pass', 'not-applicable'],
+ `${id} against ${name}: ${result.detail ?? ''}`,
+ ).toContain(result.status);
+ },
+ );
+
+ it.each((ACCORDION_MUTATIONS[id] ?? []).map(name => [name] as const))(
+ 'fails against %s, which removes its outcome',
+ 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 primary source into every result description', async () => {
+ const target = fixture(
+ ACCORDION_MUTATIONS[id]?.[0] ?? CONFORMING_FIXTURES[0]!,
+ );
+ const result = resultFor(await resultsFor(target), 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/accordion.ts b/internal/a11y-spec/src/patterns/accordion.ts
new file mode 100644
index 0000000000..d24a4438e3
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/accordion.ts
@@ -0,0 +1,688 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file accordion.ts
+ * @input WCAG 2.2 A/AA success criteria and the APG Accordion pattern's header, state, relationship, and keyboard requirements
+ * @output ACCORDION_PATTERN — the reusable contract a group of disclosures binds to when it adopts Accordion's required parts
+ * @position Pattern contract; bound by CollapsibleGroup under its record's AR4 (`spec:AST-020/FR15`)
+ */
+
+import {
+ definePattern,
+ type ApgRequirement,
+ type PatternContract,
+ type WcagCriterion,
+} from '../contract';
+import type {Subject} from '../harness';
+
+const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/accordion/';
+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_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_4_1_2: WcagCriterion = {
+ standard: 'wcag',
+ id: '4.1.2',
+ name: 'Name, Role, Value',
+ level: 'A',
+ url: `${UNDERSTANDING}/name-role-value.html`,
+};
+
+const APG_HEADER_BUTTON: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'accordion',
+ requirement:
+ 'The title of each accordion header is contained in an element with role button.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_EXPANDED: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'accordion',
+ requirement:
+ 'If the accordion panel associated with an accordion header is visible, the header button element has aria-expanded set to true. If the panel is not visible, aria-expanded is set to false.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_CONTROLS: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'accordion',
+ requirement:
+ 'The accordion header button element has aria-controls set to the ID of the element containing the accordion panel content.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_DISABLED: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'accordion',
+ requirement:
+ 'If the accordion panel associated with an accordion header is visible, and if the accordion does not permit the panel to be collapsed, the header button element has aria-disabled set to true.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_ENTER_SPACE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'accordion',
+ requirement:
+ 'Enter or Space: When focus is on the accordion header for a collapsed panel, expands the associated panel. If the implementation allows only one panel to be expanded, and if another panel is expanded, collapses that panel. When focus is on the accordion header for an expanded panel, collapses the panel if the implementation supports collapsing.',
+ url: `${APG_URL}#keyboardinteraction`,
+};
+const APG_TAB: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'accordion',
+ requirement:
+ 'Tab: Moves focus to the next focusable element; all focusable elements in the accordion are included in the page Tab sequence.',
+ url: `${APG_URL}#keyboardinteraction`,
+};
+
+/**
+ * What a binding knows about one accordion header and the group around it.
+ * The subject is always a header; `panel` is the content it controls,
+ * `next-header` the header that follows it in the page Tab order (when one
+ * exists), and `open-sibling` the other header that is expanded in a
+ * single-expansion group (when one exists).
+ */
+export interface AccordionStateFacts {
+ /** Whether this header's panel is meant to be visible in this state. */
+ readonly expanded: boolean;
+ /** Whether the user is meant to be able to toggle this header. */
+ readonly operable: boolean;
+ /** Whether this header is meant to accept keyboard focus. */
+ readonly focusable: boolean;
+ /** Whether the group allows only one panel to be expanded at a time. */
+ readonly single: boolean;
+ /** Whether the binding supplies a `next-header` relation after this header. */
+ readonly hasNextHeader: boolean;
+ /** Whether the binding supplies an expanded `open-sibling` relation. */
+ readonly hasOpenSibling: boolean;
+}
+
+const ALWAYS = {
+ condition: 'the binding designates an accordion header',
+ test: () => true,
+};
+
+function stateWord(expanded: boolean): 'expanded' | 'collapsed' {
+ return expanded ? 'expanded' : 'collapsed';
+}
+
+async function authoredExpanded(subject: Subject): Promise<boolean | null> {
+ const value = await subject.attribute('aria-expanded');
+ return value === 'true' ? true : value === 'false' ? false : null;
+}
+
+async function assertStateAndPanel(
+ subject: Subject,
+ panel: Subject,
+ expected: boolean,
+ after: string,
+): Promise<void> {
+ const state = await authoredExpanded(subject);
+ if (state !== expected) {
+ throw new Error(
+ `${after} left aria-expanded ${state == null ? 'absent or invalid' : state} instead of ${expected}`,
+ );
+ }
+ const visible = await panel.isVisible();
+ if (visible !== expected) {
+ throw new Error(
+ `${after} left the header ${stateWord(expected)} while its panel was ${visible ? 'visible' : 'hidden'}`,
+ );
+ }
+}
+
+async function roundTrip(
+ subject: Subject,
+ panel: Subject,
+ start: boolean,
+ activate: () => Promise<void>,
+ how: string,
+): Promise<void> {
+ await assertStateAndPanel(subject, panel, start, 'the starting state');
+ await activate();
+ await assertStateAndPanel(subject, panel, !start, how);
+ await activate();
+ await assertStateAndPanel(subject, panel, start, `${how} a second time`);
+}
+
+async function focusOrFail(subject: Subject, forWhat: string): Promise<void> {
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ `the accordion header did not take focus, so ${forWhat} never reaches it`,
+ );
+ }
+}
+
+export const ACCORDION_PATTERN: PatternContract<AccordionStateFacts> =
+ definePattern<AccordionStateFacts>({
+ pattern: 'accordion',
+ url: APG_URL,
+ scope:
+ "An accordion header's button role and name, expanded state, controlled panel, Enter and Space toggling, single-expansion sibling collapse, page Tab order, and the absence of arrow-key focus movement.",
+ expectations: [
+ {
+ id: 'accordion.header.role-and-name',
+ outcome:
+ 'The browser exposes the header as a named button, so a user hears what section they can open.',
+ sources: [WCAG_4_1_2, APG_HEADER_BUTTON],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const {role, name} = await subject.computed();
+ if (role !== 'button') {
+ throw new Error(
+ `the browser exposes this header as ${role == null ? 'no role' : `"${role}"`}, not as a button`,
+ );
+ }
+ if (!name || name.trim() === '') {
+ throw new Error(
+ 'the browser computes no accessible name for this header',
+ );
+ }
+ },
+ },
+ {
+ id: 'accordion.header.expanded-state',
+ outcome:
+ 'The header reports whether its panel is expanded or collapsed.',
+ sources: [WCAG_4_1_2, APG_EXPANDED],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject, facts}) => {
+ const expanded = await subject.attribute('aria-expanded');
+ if (expanded !== String(facts.expanded)) {
+ throw new Error(
+ `the header is ${stateWord(facts.expanded)} but aria-expanded is ${expanded ?? 'absent'}`,
+ );
+ }
+ },
+ },
+ {
+ id: 'accordion.header.controls-panel',
+ outcome:
+ 'The header names the panel it controls, so the relationship is programmatic.',
+ sources: [WCAG_1_3_1, APG_CONTROLS],
+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const panel = await harness.related('panel');
+ if (!(await harness.references(subject, 'aria-controls', panel))) {
+ throw new Error('aria-controls does not identify the panel');
+ }
+ if (
+ (await subject.idReferences('aria-controls')).some(
+ target => target === null,
+ )
+ ) {
+ throw new Error('aria-controls includes a missing panel target');
+ }
+ },
+ },
+ {
+ id: 'accordion.header.disabled-when-fixed',
+ outcome:
+ 'A header whose expanded panel cannot be collapsed says so, instead of looking like a control that ignores the user.',
+ sources: [WCAG_4_1_2, APG_DISABLED],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the header is expanded and cannot be toggled',
+ test: facts => facts.expanded && !facts.operable,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ if ((await subject.attribute('aria-disabled')) !== 'true') {
+ throw new Error(
+ 'the expanded header cannot be collapsed but does not carry aria-disabled="true"',
+ );
+ }
+ },
+ },
+ {
+ id: 'accordion.panel.matches-state',
+ outcome:
+ 'An expanded panel is visible and a collapsed panel is hidden, so the exposed state describes what the user receives.',
+ sources: [WCAG_4_1_2, APG_EXPANDED],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await assertStateAndPanel(
+ subject,
+ await harness.related('panel'),
+ facts.expanded,
+ 'the rendered state',
+ );
+ },
+ },
+ {
+ id: 'accordion.header.enter-round-trip',
+ outcome:
+ 'With focus on the header, Enter expands the panel and collapses it again.',
+ sources: [WCAG_2_1_1, APG_ENTER_SPACE],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the header can be toggled and can receive focus',
+ test: facts => facts.operable && facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await focusOrFail(subject, 'Enter');
+ await roundTrip(
+ subject,
+ await harness.related('panel'),
+ facts.expanded,
+ () => harness.press('Enter'),
+ 'pressing Enter on the focused header',
+ );
+ },
+ },
+ {
+ id: 'accordion.header.space-round-trip',
+ outcome:
+ 'With focus on the header, Space expands the panel and collapses it again.',
+ sources: [WCAG_2_1_1, APG_ENTER_SPACE],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the header can be toggled and can receive focus',
+ test: facts => facts.operable && facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await focusOrFail(subject, 'Space');
+ await roundTrip(
+ subject,
+ await harness.related('panel'),
+ facts.expanded,
+ () => harness.press('Space'),
+ 'pressing Space on the focused header',
+ );
+ },
+ },
+ {
+ id: 'accordion.header.survives-an-aborted-press',
+ outcome:
+ 'A press released away from the header leaves it unchanged, so an unintended press can be cancelled.',
+ sources: [WCAG_2_5_2],
+ covers: ['2.5.2-pointer-cancellation'],
+ appliesWhen: {
+ condition: 'the header can be toggled',
+ test: facts => facts.operable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ const panel = await harness.related('panel');
+ await assertStateAndPanel(
+ subject,
+ panel,
+ facts.expanded,
+ 'the starting state',
+ );
+ await harness.abortedPress(subject);
+ await assertStateAndPanel(
+ subject,
+ panel,
+ facts.expanded,
+ 'releasing the press away from the header',
+ );
+ },
+ },
+ {
+ id: 'accordion.focus.stays-on-header',
+ outcome:
+ 'Toggling a header leaves focus on it, so the user stays at the control they changed.',
+ sources: [WCAG_3_2_2],
+ covers: ['3.2.2-on-input'],
+ appliesWhen: {
+ condition: 'the header can be toggled and can receive focus',
+ test: facts => facts.operable && facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await focusOrFail(subject, 'the focus result of toggling');
+ const panel = await harness.related('panel');
+ await harness.press('Space');
+ await assertStateAndPanel(
+ subject,
+ panel,
+ !facts.expanded,
+ 'pressing Space on the focused header',
+ );
+ if (!(await subject.isFocused())) {
+ throw new Error('toggling the header moved focus away from it');
+ }
+ },
+ },
+ {
+ id: 'accordion.group.single-collapses-sibling',
+ outcome:
+ 'In a single-expansion group, expanding a header collapses the sibling that was open, so one panel is open at a time.',
+ sources: [APG_ENTER_SPACE],
+ wcagOutcome:
+ 'Supports WCAG 2.2 4.1.2 for the grouped behaviour; the APG and component:CollapsibleGroup AR4 define it, so this row is advisory until that record is current (AST-020 FR9).',
+ covers: ['apg-interaction'],
+ appliesWhen: {
+ condition:
+ 'the group allows one expanded panel, this header is collapsed and operable, and another header is expanded',
+ test: facts =>
+ facts.single &&
+ !facts.expanded &&
+ facts.operable &&
+ facts.focusable &&
+ facts.hasOpenSibling,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'advisory',
+ advisoryBecause:
+ "Single-expansion sibling collapse is the group's own promise (component:CollapsibleGroup AR4), not an APG-required part; this becomes required once that record is current (AST-020 FR9).",
+ run: async ({harness, subject}) => {
+ const sibling = await harness.related('open-sibling');
+ if ((await authoredExpanded(sibling)) !== true) {
+ throw new Error('the open sibling is not expanded to begin with');
+ }
+ await focusOrFail(subject, 'Space');
+ await harness.press('Space');
+ if ((await authoredExpanded(subject)) !== true) {
+ throw new Error('pressing Space did not expand the header');
+ }
+ if ((await authoredExpanded(sibling)) !== false) {
+ throw new Error(
+ 'expanding this header left the open sibling expanded in a single-expansion group',
+ );
+ }
+ },
+ },
+ {
+ id: 'accordion.group.tab-order',
+ outcome:
+ 'Tab moves from this header to the next header, so every header sits in the page Tab sequence.',
+ sources: [APG_TAB],
+ wcagOutcome:
+ 'Supports WCAG 2.2 2.1.1 for the grouped behaviour; the APG and component:CollapsibleGroup AR4 define it, so this row is advisory until that record is current (AST-020 FR9).',
+ covers: ['2.4.3-focus-order', 'apg-interaction'],
+ appliesWhen: {
+ condition:
+ 'this header can receive focus and another header follows it',
+ test: facts => facts.focusable && facts.hasNextHeader,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'advisory',
+ advisoryBecause:
+ "The header-to-header Tab step is the group's own promise (component:CollapsibleGroup AR4); this becomes required once that record is current (AST-020 FR9).",
+ run: async ({harness, subject}) => {
+ const next = await harness.related('next-header');
+ await focusOrFail(subject, 'Tab');
+ await harness.press('Tab');
+ if (!(await next.isFocused())) {
+ throw new Error(
+ 'Tab from the header did not reach the next header in the page sequence',
+ );
+ }
+ },
+ },
+ {
+ id: 'accordion.group.arrows-do-not-move-focus',
+ outcome:
+ 'ArrowDown and ArrowUp leave focus on the header, because this group is a set of independent disclosures, not one composite control.',
+ sources: [APG_TAB],
+ wcagOutcome:
+ 'Supports WCAG 2.2 2.1.1 for the grouped behaviour; the APG and component:CollapsibleGroup AR4 define it, so this row is advisory until that record is current (AST-020 FR9).',
+ covers: ['2.4.3-focus-order', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'this header can receive focus',
+ test: facts => facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'advisory',
+ advisoryBecause:
+ "Not adopting arrow-key movement is the group's own decision (component:CollapsibleGroup AR4 and DEC-1); this becomes required once that record is current (AST-020 FR9).",
+ run: async ({harness, subject}) => {
+ await focusOrFail(subject, 'ArrowDown');
+ await harness.press('ArrowDown');
+ if (!(await subject.isFocused())) {
+ throw new Error('ArrowDown moved focus away from the header');
+ }
+ await harness.press('ArrowUp');
+ if (!(await subject.isFocused())) {
+ throw new Error('ArrowUp moved focus away from the header');
+ }
+ },
+ },
+ ],
+ exemptions: {
+ '1.1.1-non-text-content': {
+ owner: 'the binding component',
+ verifiedBy:
+ "the component's decorative-icon tests and the repository axe audit, `pnpm a11y:audit`",
+ reason:
+ 'The accordion contract owns trigger state and controlled-content behavior. Decorative graphics such as a chevron are binding-specific composition.',
+ },
+ '1.3.1-info-and-relationships': {
+ owner: 'the binding component and composing page',
+ verifiedBy:
+ "the binding's component tests and page-level relationship review",
+ reason:
+ 'This contract encodes the required header-to-panel relationship (aria-controls). Other structure and relationships inside or around a panel belong to the binding and its composition.',
+ coversRemainderOnly: true,
+ },
+ '1.3.2-meaningful-sequence': {
+ owner: 'the binding component and composing page',
+ verifiedBy:
+ "the component's DOM-order tests and page-level reading-order review",
+ reason:
+ 'The page decides where the trigger and revealed section sit relative to surrounding content.',
+ },
+ '1.3.5-identify-input-purpose': {
+ owner: 'the composing form and caller content',
+ verifiedBy:
+ 'form integration review for any user-information input inside the disclosed content',
+ reason:
+ 'An accordion trigger does not itself collect information about the user.',
+ },
+ '1.4.1-use-of-color': {
+ owner: 'the binding component and theme',
+ verifiedBy: 'the repository visual gate and forced-colors review',
+ reason:
+ 'Color and any non-color accordion cue are rendered presentation facts, not trigger-state semantics.',
+ },
+ '1.4.3-contrast-minimum': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ 'the repository axe audit over component stories plus the visual gate',
+ reason:
+ 'Text contrast depends on resolved colors and backdrop in the rendered binding.',
+ },
+ '1.4.11-non-text-contrast': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ 'the repository axe audit plus rendered review of the trigger boundary, state cue, and focus indicator',
+ reason:
+ 'Control and accordion-cue contrast are paint outcomes owned by the binding and theme.',
+ },
+ '2.1.1-keyboard': {
+ owner: 'the button pattern and composing page',
+ verifiedBy:
+ 'BUTTON_PATTERN focus-navigation expectations plus page-level keyboard-order review',
+ reason:
+ 'This contract encodes the accordion-specific Enter and Space transitions, the header-to-header Tab step, and the absence of arrow-key movement. Generic reachability and other page keyboard paths remain with the button and composition owners.',
+ coversRemainderOnly: true,
+ },
+ '2.1.2-no-keyboard-trap': {
+ owner: 'the button pattern and composing page',
+ verifiedBy:
+ 'BUTTON_PATTERN for adopters, plus binding-local focus reach/escape tests and page-level keyboard review',
+ reason:
+ 'An accordion adds no focus trap; Tab entry and exit are generic button and composition behavior.',
+ },
+ '2.4.2-page-titled': {
+ owner: 'the page',
+ verifiedBy: 'page-level review',
+ reason: 'An accordion rendered in isolation owns no document title.',
+ },
+ '2.4.3-focus-order': {
+ owner: 'the composing page',
+ verifiedBy:
+ 'page-level focus-order review; this contract proves the header-to-header Tab step and that arrow keys do not move focus',
+ reason:
+ 'Sequential order between the headers, the revealed panels, and surrounding controls depends on composition.',
+ coversRemainderOnly: true,
+ },
+ '2.4.4-link-purpose': {
+ owner: 'the link pattern and caller content',
+ verifiedBy: 'review of links inside or around the disclosed content',
+ reason: 'The adopted accordion trigger is a button, not a link.',
+ },
+ '2.4.6-headings-and-labels': {
+ owner: 'the button pattern and caller content',
+ verifiedBy:
+ 'BUTTON_PATTERN naming checks plus content review of the trigger label',
+ reason:
+ 'Whether the trigger label describes its purpose is a caller-content judgement; generic button naming is already owned by BUTTON_PATTERN.',
+ },
+ '2.4.7-focus-visible': {
+ owner:
+ 'the interaction-modality architecture record, binding component, and theme',
+ verifiedBy:
+ "the component's focus-ring styling and the repository visual gate",
+ reason: 'A focus indicator is a paint outcome.',
+ },
+ '2.4.11-focus-not-obscured': {
+ owner: 'the composing page and overlay system',
+ verifiedBy: 'page-level and overlay visibility review',
+ reason:
+ 'Whether another surface covers the focused trigger or revealed content depends on composition.',
+ },
+ '2.5.3-label-in-name': {
+ owner: 'the button pattern and caller content',
+ verifiedBy:
+ 'BUTTON_PATTERN for adopters, plus binding-local visible-label and accessible-name checks',
+ reason:
+ 'The accordion adds state to a button without changing who owns the button label and name.',
+ },
+ '2.5.8-target-size': {
+ owner: 'the binding component and composing page',
+ verifiedBy:
+ "the repository axe audit's target-size rule over the trigger and neighbouring targets",
+ reason:
+ 'Target size and spacing exceptions depend on the binding geometry and neighbouring controls.',
+ },
+ '3.1.1-language-of-page': {
+ owner: 'the page',
+ verifiedBy: 'page-level language review',
+ reason: 'An accordion rendered in isolation owns no document language.',
+ },
+ '3.2.2-on-input': {
+ owner: 'the caller and composing page',
+ verifiedBy:
+ 'integration review of any navigation, viewport, or meaning change a caller causes while toggling',
+ reason:
+ 'This contract proves the trigger keeps focus while its own section toggles. Any additional context change is caller behavior.',
+ coversRemainderOnly: true,
+ },
+ '3.2.4-consistent-identification': {
+ owner: 'the design system and caller content',
+ verifiedBy:
+ 'this shared contract across bindings plus content review of repeated accordion labels',
+ reason:
+ 'Consistency is a property of the full set of repeated functions, not one isolated accordion.',
+ },
+ '3.3.1-error-identification': {
+ owner: 'the binding component and composing form',
+ verifiedBy: 'form-level error-state and text review',
+ reason: 'The accordion pattern defines no validation error state.',
+ },
+ '3.3.2-labels-or-instructions': {
+ owner: 'the composing form and caller content',
+ verifiedBy: 'form-level review of labels and instructions',
+ reason:
+ 'The accordion trigger does not collect user input that needs form instructions.',
+ },
+ '4.1.2-name-role-value': {
+ owner: 'the button pattern and binding component',
+ verifiedBy:
+ 'BUTTON_PATTERN for adopters, plus binding-local role, name, and unavailable-state tests',
+ reason:
+ 'This contract encodes the header role and name, the expanded state, the fixed-panel disabled state, and their transitions. Other button semantics remain with BUTTON_PATTERN.',
+ coversRemainderOnly: true,
+ },
+ '4.1.3-status-messages': {
+ owner:
+ 'the caller and the assistive-technology verification record, spec:AST-009',
+ verifiedBy:
+ 'the status-message pattern and real-AT evidence under AST-009 when a change claims spoken or braille output',
+ reason:
+ 'Showing or hiding ordinary content is not itself a status-message contract, and this pattern makes no announcement claim.',
+ },
+ 'apg-interaction': {
+ owner: 'the button pattern',
+ verifiedBy:
+ 'BUTTON_PATTERN for adopters, plus binding-local role, name, reachability, and activation tests',
+ reason:
+ "This contract encodes accordion state, relationship, and Enter/Space visibility transitions. The trigger's generic button semantics stay with BUTTON_PATTERN.",
+ coversRemainderOnly: true,
+ },
+ 'forced-colors': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ "the component's forced-colors tests plus rendered Windows High Contrast review",
+ reason:
+ 'Forced-colors output is a paint result owned by the binding and theme.',
+ },
+ 'reduced-motion': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ "the component's reduced-motion source tests and rendered motion review",
+ reason:
+ 'Reveal motion is binding-specific paint over time and is not part of accordion semantics.',
+ },
+ 'at-facing-strings': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ 'the repository i18n catalog check and source review of authored labels and descriptions',
+ reason:
+ 'The accordion contract introduces no string; trigger and content text come from the binding or caller.',
+ },
+ },
+ });
diff --git a/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.renders.tsx b/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.renders.tsx
new file mode 100644
index 0000000000..6b035ceab1
--- /dev/null
+++ b/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.renders.tsx
@@ -0,0 +1,45 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CollapsibleGroup.a11y.renders.tsx
+ * @input One CollapsibleGroup accordion state from CollapsibleGroup.a11y.states.ts
+ * @output The React tree every lane renders for that state (the jsdom test directly, the story through Storybook)
+ * @position Shared fixture for the CollapsibleGroup accordion binding
+ */
+
+import type {ReactElement} from 'react';
+import {Collapsible, CollapsibleGroup} from '../index';
+import {
+ COLLAPSIBLE_GROUP_ITEMS,
+ type CollapsibleGroupAccordionState,
+} from './CollapsibleGroup.a11y.states';
+
+export function renderAccordionState(
+ state: Pick<
+ CollapsibleGroupAccordionState,
+ 'type' | 'defaultValue' | 'disabled'
+ >,
+): ReactElement {
+ return (
+ <div>
+ <CollapsibleGroup
+ type={state.type}
+ defaultValue={
+ state.type === 'single'
+ ? state.defaultValue[0]
+ : [...state.defaultValue]
+ }>
+ {COLLAPSIBLE_GROUP_ITEMS.map(item => (
+ <Collapsible
+ key={item.value}
+ value={item.value}
+ trigger={item.label}
+ isDisabled={state.disabled?.includes(item.value)}>
+ {item.label} content
+ </Collapsible>
+ ))}
+ </CollapsibleGroup>
+ <button type="button">After the group</button>
+ </div>
+ );
+}
diff --git a/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.states.ts b/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.states.ts
new file mode 100644
index 0000000000..f28006f5de
--- /dev/null
+++ b/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.states.ts
@@ -0,0 +1,139 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CollapsibleGroup.a11y.states.ts
+ * @input CollapsibleGroup's representative accordion states and the facts the ACCORDION_PATTERN contract reads
+ * @output COLLAPSIBLE_GROUP_ACCORDION_STATES and the explicit ownership exclusions for this binding
+ * @position Binding inventory shared by the jsdom test and the Chromium spec (component:CollapsibleGroup AR4)
+ */
+
+import type {AccordionStateFacts} from '@astryxdesign/a11y-spec';
+
+export interface CollapsibleGroupAccordionState {
+ readonly id: string;
+ readonly summary: string;
+ readonly storyId: string;
+ /** The subject header's visible label. */
+ readonly label: string;
+ /** The header that follows the subject in the page Tab order, when one exists. */
+ readonly nextLabel?: string;
+ /** The other header that starts expanded in a single-expansion group, when one exists. */
+ readonly openSiblingLabel?: string;
+ readonly facts: AccordionStateFacts;
+ readonly type: 'single' | 'multiple';
+ /** Values open at mount. */
+ readonly defaultValue: ReadonlyArray<string>;
+ /** Items that are disabled at mount. */
+ readonly disabled?: ReadonlyArray<string>;
+}
+
+const ITEMS = [
+ {value: 'profile', label: 'Profile settings'},
+ {value: 'privacy', label: 'Privacy settings'},
+ {value: 'notifications', label: 'Notification settings'},
+] as const;
+
+export const COLLAPSIBLE_GROUP_ITEMS = ITEMS;
+
+function facts(
+ overrides: Partial<AccordionStateFacts> = {},
+): AccordionStateFacts {
+ return {
+ expanded: false,
+ operable: true,
+ focusable: true,
+ single: true,
+ hasNextHeader: true,
+ hasOpenSibling: true,
+ ...overrides,
+ };
+}
+
+const story = (id: string) => `a11y-collapsiblegroup-accordion--${id}`;
+
+export const COLLAPSIBLE_GROUP_ACCORDION_STATES = [
+ {
+ id: 'single-collapsed-middle',
+ summary:
+ 'the collapsed middle header of a single-expansion group whose first header is open',
+ storyId: story('single-collapsed-middle'),
+ label: 'Privacy settings',
+ nextLabel: 'Notification settings',
+ openSiblingLabel: 'Profile settings',
+ facts: facts(),
+ type: 'single',
+ defaultValue: ['profile'],
+ },
+ {
+ id: 'single-expanded-first',
+ summary: 'the expanded first header of a single-expansion group',
+ storyId: story('single-expanded-first'),
+ label: 'Profile settings',
+ nextLabel: 'Privacy settings',
+ facts: facts({expanded: true, hasOpenSibling: false}),
+ type: 'single',
+ defaultValue: ['profile'],
+ },
+ {
+ id: 'multiple-collapsed-last',
+ summary:
+ 'the collapsed last header of a group that allows several open panels',
+ storyId: story('multiple-collapsed-last'),
+ label: 'Notification settings',
+ facts: facts({
+ single: false,
+ hasNextHeader: false,
+ hasOpenSibling: false,
+ }),
+ type: 'multiple',
+ defaultValue: ['profile', 'privacy'],
+ },
+ {
+ id: 'single-disabled-collapsed',
+ summary:
+ 'a disabled collapsed header that stays named and exposed but leaves the Tab order and cannot be toggled',
+ storyId: story('single-disabled-collapsed'),
+ label: 'Privacy settings',
+ facts: facts({
+ operable: false,
+ focusable: false,
+ hasNextHeader: false,
+ hasOpenSibling: false,
+ }),
+ type: 'single',
+ defaultValue: ['profile'],
+ disabled: ['privacy'],
+ },
+ {
+ id: 'single-disabled-expanded',
+ summary:
+ 'a disabled header whose panel stays open: it says aria-disabled, leaves the Tab order, and cannot be collapsed',
+ storyId: story('single-disabled-expanded'),
+ label: 'Profile settings',
+ facts: facts({
+ expanded: true,
+ operable: false,
+ focusable: false,
+ hasNextHeader: false,
+ hasOpenSibling: false,
+ }),
+ type: 'single',
+ defaultValue: ['profile'],
+ disabled: ['profile'],
+ },
+] as const satisfies ReadonlyArray<CollapsibleGroupAccordionState>;
+
+export const COLLAPSIBLE_GROUP_ACCORDION_EXCLUSIONS = [
+ {
+ id: 'collapsible-disclosure-semantics',
+ owner: 'DISCLOSURE_PATTERN and Collapsible.a11y.test.tsx',
+ reason:
+ 'Each header is a Collapsible trigger. Its standalone disclosure state, pointer round trip, and aborted-press behavior are already bound to the disclosure contract; this binding proves the Accordion parts across the group — header role and name, aria-controls, aria-disabled on a fixed panel, Enter and Space — and, advisory until the record is current, what the group adds: single-expansion sibling collapse, the page Tab step between headers, and the absence of arrow-key focus movement.',
+ },
+ {
+ id: 'heading-wrapper-and-region-panels',
+ owner: 'component:CollapsibleGroup AR4 and the composing page',
+ reason:
+ 'The record adopts the Accordion pattern without a heading element around each header and without the optional region role on panels; the caller places the group in its own heading structure. Neither is asserted here because neither is a component promise.',
+ },
+] as const;
diff --git a/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.test.tsx b/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.test.tsx
new file mode 100644
index 0000000000..beb7cce024
--- /dev/null
+++ b/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.test.tsx
@@ -0,0 +1,135 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file CollapsibleGroup.a11y.test.tsx
+ * @input ACCORDION_PATTERN bound to CollapsibleGroup's representative states
+ * @output jsdom-lane proof of the DOM expectations and an honest "unrun" report for the browser layers
+ * @position Binding test for component:CollapsibleGroup AR4 (the Chromium spec covers the rest)
+ */
+
+import {cleanup, render, screen} from '@testing-library/react';
+import {describe, expect, it} from 'vitest';
+import {
+ ACCORDION_PATTERN,
+ checkAccessibilitySpec,
+ createJsdomHarness,
+ expectAccessibilitySpec,
+ summarize,
+ type BindingResult,
+} from '@astryxdesign/a11y-spec';
+import {renderAccordionState} from './CollapsibleGroup.a11y.renders';
+import {
+ COLLAPSIBLE_GROUP_ACCORDION_EXCLUSIONS,
+ COLLAPSIBLE_GROUP_ACCORDION_STATES,
+ type CollapsibleGroupAccordionState,
+} from './CollapsibleGroup.a11y.states';
+
+function header(label: string): HTMLElement {
+ return screen.getByRole('button', {name: label});
+}
+
+function panelFor(subject: HTMLElement, id: string): HTMLElement {
+ const controls = subject.getAttribute('aria-controls');
+ const panel = controls == null ? null : document.getElementById(controls);
+ if (panel == null) {
+ throw new Error(`CollapsibleGroup state "${id}" has no controlled panel`);
+ }
+ return panel;
+}
+
+function relatedFor(
+ state: CollapsibleGroupAccordionState,
+): Readonly<Record<string, Element>> {
+ const subject = header(state.label);
+ const related: Record<string, Element> = {
+ panel: panelFor(subject, state.id),
+ };
+ if (state.nextLabel != null) {
+ related['next-header'] = header(state.nextLabel);
+ }
+ if (state.openSiblingLabel != null) {
+ related['open-sibling'] = header(state.openSiblingLabel);
+ }
+ return related;
+}
+
+async function checkState(
+ state: CollapsibleGroupAccordionState,
+): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: ACCORDION_PATTERN,
+ binding: 'CollapsibleGroup.header',
+ state: state.id,
+ facts: state.facts,
+ mount: async () => {
+ render(renderAccordionState(state));
+ return createJsdomHarness({
+ subject: header(state.label),
+ related: relatedFor(state),
+ });
+ },
+ unmount: cleanup,
+ });
+}
+
+describe('CollapsibleGroup.header — accordion pattern, jsdom lane', () => {
+ it.each(
+ COLLAPSIBLE_GROUP_ACCORDION_STATES.map(
+ state => [state.id, state.summary, state] as const,
+ ),
+ )('%s — %s', async (_id, _summary, state) => {
+ await expectAccessibilitySpec({
+ spec: ACCORDION_PATTERN,
+ binding: 'CollapsibleGroup.header',
+ state: state.id,
+ facts: state.facts,
+ render: () => {
+ render(renderAccordionState(state));
+ },
+ subject: () => header(state.label),
+ related: () => relatedFor(state),
+ cleanup,
+ });
+ });
+
+ it('runs the DOM layer and reports the browser-owned outcomes as unrun', async () => {
+ const results: BindingResult[] = [];
+ for (const state of COLLAPSIBLE_GROUP_ACCORDION_STATES) {
+ results.push(await checkState(state));
+ }
+ const report = summarize(ACCORDION_PATTERN, results);
+ expect(report.counts.pass).toBeGreaterThan(0);
+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+});
+
+describe('CollapsibleGroup accordion binding inventory', () => {
+ it('gives every representative state a distinct checked-in story', () => {
+ const stories = COLLAPSIBLE_GROUP_ACCORDION_STATES.map(
+ state => state.storyId,
+ );
+ expect(new Set(stories).size).toBe(stories.length);
+ });
+
+ it('keeps disclosure and page ownership explicit', () => {
+ expect(COLLAPSIBLE_GROUP_ACCORDION_EXCLUSIONS.map(row => row.id)).toEqual([
+ 'collapsible-disclosure-semantics',
+ 'heading-wrapper-and-region-panels',
+ ]);
+ for (const exclusion of COLLAPSIBLE_GROUP_ACCORDION_EXCLUSIONS) {
+ expect(exclusion.owner.length, exclusion.id).toBeGreaterThan(20);
+ expect(exclusion.reason.length, exclusion.id).toBeGreaterThan(80);
+ }
+ });
+
+ it('renders exactly one subject header and its relations for every state', () => {
+ for (const state of COLLAPSIBLE_GROUP_ACCORDION_STATES) {
+ render(renderAccordionState(state));
+ expect(header(state.label), state.id).toBeTruthy();
+ expect(Object.keys(relatedFor(state)), state.id).toContain('panel');
+ cleanup();
+ }
+ });
+});
diff --git a/packages/core/src/Collapsible/__tests__/CollapsibleGroupAccordion.a11y.chromium.spec.ts b/packages/core/src/Collapsible/__tests__/CollapsibleGroupAccordion.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..b8bc331992
--- /dev/null
+++ b/packages/core/src/Collapsible/__tests__/CollapsibleGroupAccordion.a11y.chromium.spec.ts
@@ -0,0 +1,128 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CollapsibleGroupAccordion.a11y.chromium.spec.ts
+ * @input Built CollapsibleGroup accordion stories and ACCORDION_PATTERN in real Chromium
+ * @output Browser evidence for every accordion expectation across the binding's states
+ * @position Chromium lane of the CollapsibleGroup accordion binding (component:CollapsibleGroup AR4)
+ */
+
+import {
+ expect,
+ test,
+ type CDPSession,
+ type Locator,
+ type Page,
+} from '@playwright/test';
+import {
+ ACCORDION_PATTERN,
+ blockingResults,
+ checkAccessibilitySpec,
+ formatFailures,
+ neverExercised,
+ 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 {
+ COLLAPSIBLE_GROUP_ACCORDION_STATES,
+ type CollapsibleGroupAccordionState,
+} from './CollapsibleGroup.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 header(page: Page, label: string): Locator {
+ return page
+ .locator('#storybook-root')
+ .getByRole('button', {name: label, includeHidden: true});
+}
+
+async function mountState(
+ page: Page,
+ state: CollapsibleGroupAccordionState,
+): Promise<{subject: Locator; related: Record<string, Locator>}> {
+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});
+ await holdMotionStill(page);
+ const subject = header(page, state.label);
+ await subject.waitFor({state: 'attached'});
+ const id = await subject.getAttribute('aria-controls');
+ if (id == null) {
+ throw new Error(
+ `CollapsibleGroup state "${state.id}" has no aria-controls`,
+ );
+ }
+ const related: Record<string, Locator> = {
+ panel: page.locator(`#storybook-root [id="${id}"]`),
+ };
+ if (state.nextLabel != null) {
+ related['next-header'] = header(page, state.nextLabel);
+ }
+ if (state.openSiblingLabel != null) {
+ related['open-sibling'] = header(page, state.openSiblingLabel);
+ }
+ return {subject, related};
+}
+
+async function runState(
+ page: Page,
+ cdp: CDPSession,
+ state: CollapsibleGroupAccordionState,
+): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: ACCORDION_PATTERN,
+ binding: 'CollapsibleGroup.header',
+ state: state.id,
+ facts: state.facts,
+ mount: async () => {
+ const {subject, related} = await mountState(page, state);
+ return createChromiumHarness({page, cdp, subject, related});
+ },
+ });
+}
+
+test('every accordion expectation is exercised by a CollapsibleGroup state', async ({
+ page,
+}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const results: BindingResult[] = [];
+ for (const state of COLLAPSIBLE_GROUP_ACCORDION_STATES) {
+ results.push(await runState(page, cdp, state));
+ }
+ expect(neverExercised(results)).toEqual([]);
+});
+
+for (const state of COLLAPSIBLE_GROUP_ACCORDION_STATES) {
+ test(`CollapsibleGroup.header [${state.id}] — ${state.summary}`, async ({
+ page,
+ }) => {
+ const cdp = await page.context().newCDPSession(page);
+ const result = await runState(page, cdp, state);
+ const report = summarize(ACCORDION_PATTERN, [result]);
+ // Only required rows block (AST-020 FR9); advisory rows report.
+ expect(formatFailures(blockingResults([result]))).toBe('');
+ expect(report.unrunLayers).toEqual([]);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+}