Skip to content

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

TypeScript

test(a11y): add disclosure accessibility contract (#6350)

Cindy Zhang22be8db9bf4d
diff --git a/apps/storybook/stories/CollapsibleA11y.stories.tsx b/apps/storybook/stories/CollapsibleA11y.stories.tsx
new file mode 100644
index 0000000000..2518b70b47
--- /dev/null
+++ b/apps/storybook/stories/CollapsibleA11y.stories.tsx
@@ -0,0 +1,104 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CollapsibleA11y.stories.tsx
+ * @input Uses Collapsible and the shared accessibility binding inventory
+ * @output Stable standalone disclosure states for Chromium contract verification
+ * @position Accessibility contract fixtures only; excluded from visual baselines.
+ */
+
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {Collapsible} from '@astryxdesign/core/Collapsible';
+import type {CollapsibleProps} from '@astryxdesign/core/Collapsible';
+
+const meta = {
+ title: 'A11y/Collapsible Disclosure',
+ tags: ['no-visual'],
+ parameters: {layout: 'padded'},
+} satisfies Meta;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+function Fixture({
+ label,
+ initialOpen,
+ controlled = false,
+ direction = 'ltr',
+ ...props
+}: Omit<
+ CollapsibleProps,
+ 'children' | 'trigger' | 'isOpen' | 'onOpenChange'
+> & {
+ readonly label: string;
+ readonly initialOpen: boolean;
+ readonly controlled?: boolean;
+ readonly direction?: 'ltr' | 'rtl';
+}) {
+ const [open, setOpen] = useState(initialOpen);
+ return (
+ <div dir={direction}>
+ {controlled ? (
+ <Collapsible
+ {...props}
+ trigger={label}
+ isOpen={open}
+ onOpenChange={setOpen}>
+ Disclosure content
+ </Collapsible>
+ ) : (
+ <Collapsible {...props} trigger={label} defaultIsOpen={initialOpen}>
+ Disclosure content
+ </Collapsible>
+ )}
+ <button type="button">After disclosure</button>
+ </div>
+ );
+}
+
+export const UncontrolledOpenEndLtr: Story = {
+ render: () => <Fixture label="Account details" initialOpen />,
+};
+
+export const UncontrolledClosedStartRtl: Story = {
+ render: () => (
+ <Fixture
+ label="Privacy details"
+ initialOpen={false}
+ chevronPosition="start"
+ direction="rtl"
+ />
+ ),
+};
+
+export const ControlledOpenEndLtr: Story = {
+ render: () => <Fixture label="Notification details" initialOpen controlled />,
+};
+
+export const ControlledClosedStartLtr: Story = {
+ render: () => (
+ <Fixture
+ label="Security details"
+ initialOpen={false}
+ controlled
+ chevronPosition="start"
+ />
+ ),
+};
+
+export const DisabledOpenEndLtr: Story = {
+ render: () => <Fixture label="Archived details" initialOpen isDisabled />,
+};
+
+export const DisabledClosedStartRtl: Story = {
+ render: () => (
+ <Fixture
+ label="Restricted details"
+ initialOpen={false}
+ isDisabled
+ chevronPosition="start"
+ direction="rtl"
+ />
+ ),
+};
diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.md
index f03b46a840..acea52c535 100644
--- a/internal/a11y-spec/README.md
+++ b/internal/a11y-spec/README.md
@@ -49,7 +49,8 @@ src/
├── status-message.* live-region and progress status mechanics
├── tabs.* explicit horizontal ARIA Tabs semantics
├── listbox.* listbox, group, and option semantics
- └── spinbutton.* numeric role, value, bounds, state, and arrow stepping
+ ├── spinbutton.* numeric role, value, bounds, state, and arrow stepping
+ └── disclosure.* standalone disclosure state/content semantics
```
## The patterns
@@ -66,6 +67,7 @@ src/
| `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 |
The `spinbutton` contract owns NumberInput's required role, persistent name,
committed numeric value, optional bounds and formatted value text, disabled and
@@ -75,6 +77,13 @@ adopts those mechanics as a shared requirement. Typed draft parsing,
formatting, commit/clamp policy, callbacks, optional buttons, and date/time
segments keep their existing owners.
+The disclosure contract owns only the disclosure-specific state, optional
+trigger-to-content relationship, synchronized visibility, and complete pointer,
+Enter, and Space transitions. Generic role, naming, focus navigation, and
+unavailable-button semantics remain in the existing `button` contract. This first
+migration binds standalone Collapsible states only; CollapsibleGroup coordination
+and Accordion, Table, and SideNav adoption remain outside this contract.
+
The `listbox` contract is a bounded semantic migration, not blanket APG
interaction adoption. Its first bindings cover 21 existing scenarios across
single/multiple selection, disabled options, groups, filtering, custom content,
diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.ts
index c10b28db48..1e89c86c6b 100644
--- a/internal/a11y-spec/src/index.ts
+++ b/internal/a11y-spec/src/index.ts
@@ -117,3 +117,8 @@ export {
SPINBUTTON_PATTERN,
type SpinbuttonStateFacts,
} from './patterns/spinbutton';
+
+export {
+ DISCLOSURE_PATTERN,
+ type DisclosureStateFacts,
+} from './patterns/disclosure';
diff --git a/internal/a11y-spec/src/patterns/disclosure.chromium.spec.ts b/internal/a11y-spec/src/patterns/disclosure.chromium.spec.ts
new file mode 100644
index 0000000000..b6d73b3a92
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/disclosure.chromium.spec.ts
@@ -0,0 +1,97 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file disclosure.chromium.spec.ts
+ * @input Uses Playwright, the disclosure contract, shared fixtures, and Chromium harness
+ * @output Real-browser positive and deliberate-negative proof for every observable expectation
+ * @position Contract self-tests, independent of any 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 {DISCLOSURE_PATTERN} from './disclosure';
+import {
+ CONFORMING_FIXTURES,
+ CONTENT_SELECTOR,
+ DISCLOSURE_MUTATIONS,
+ SUBJECT_SELECTOR,
+ fixture,
+ type DisclosureFixture,
+} from './disclosure.fixtures';
+
+function fixturePage(html: string): string {
+ return `<!doctype html><html lang="en"><body>${html}<button type="button" id="after">After disclosure</button></body></html>`;
+}
+
+async function results(
+ page: Page,
+ cdp: CDPSession,
+ target: DisclosureFixture,
+ only?: readonly string[],
+): Promise<readonly ExpectationResult[]> {
+ const run = await checkAccessibilitySpec({
+ spec: DISCLOSURE_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: {content: page.locator(CONTENT_SELECTOR)},
+ });
+ },
+ });
+ return run.results;
+}
+
+test.describe('disclosure 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('disclosure contract — deliberately violating fixtures', () => {
+ for (const expectation of DISCLOSURE_PATTERN.expectations) {
+ if (
+ !requiredLayers(expectation).every(layer =>
+ CHROMIUM_OBSERVES.includes(layer),
+ )
+ ) {
+ continue;
+ }
+ for (const fixtureId of DISCLOSURE_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/disclosure.fixtures.ts b/internal/a11y-spec/src/patterns/disclosure.fixtures.ts
new file mode 100644
index 0000000000..dfcde482ce
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/disclosure.fixtures.ts
@@ -0,0 +1,214 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file disclosure.fixtures.ts
+ * @input Uses DisclosureStateFacts from ./disclosure
+ * @output Plain-HTML conforming and deliberately violating disclosure fixtures
+ * @position Contract mutation proof shared by jsdom and Chromium.
+ */
+
+import type {DisclosureStateFacts} from './disclosure';
+
+const SUBJECT_ATTRIBUTE = 'data-a11y-subject';
+export const SUBJECT_SELECTOR = `[${SUBJECT_ATTRIBUTE}]`;
+export const CONTENT_SELECTOR = '#content';
+
+export interface DisclosureFixture {
+ readonly id: string;
+ readonly summary: string;
+ readonly facts: DisclosureStateFacts;
+ readonly html: string;
+}
+
+const TOGGLE = `const open = this.getAttribute('aria-expanded') !== 'true'; this.setAttribute('aria-expanded', String(open)); document.getElementById('content').hidden = !open;`;
+const OPEN_ONLY = `this.setAttribute('aria-expanded', 'true'); document.getElementById('content').hidden = false;`;
+const STATE_ONLY = `this.setAttribute('aria-expanded', String(this.getAttribute('aria-expanded') !== 'true'));`;
+
+function disclosure({
+ expanded = false,
+ controls = 'content',
+ onclick = TOGGLE,
+ onkeydown = '',
+ onpointerdown = '',
+ contentHidden = !expanded,
+ contentTabIndex = false,
+}: {
+ expanded?: boolean;
+ controls?: string | null;
+ onclick?: string;
+ onkeydown?: string;
+ onpointerdown?: string;
+ contentHidden?: boolean;
+ contentTabIndex?: boolean;
+} = {}): string {
+ return `<button type="button" ${SUBJECT_ATTRIBUTE} aria-expanded="${expanded}"${controls == null ? '' : ` aria-controls="${controls}"`}${onclick === '' ? '' : ` onclick="${onclick}"`}${onkeydown === '' ? '' : ` onkeydown="${onkeydown}"`}${onpointerdown === '' ? '' : ` onpointerdown="${onpointerdown}"`}>Details</button><div id="content"${contentHidden ? ' hidden' : ''}${contentTabIndex ? ' tabindex="-1"' : ''}>Body</div><div id="other">Other content</div>`;
+}
+
+const facts = (
+ overrides: Partial<DisclosureStateFacts> = {},
+): DisclosureStateFacts => ({
+ expanded: false,
+ controls: true,
+ operable: true,
+ focusable: true,
+ ...overrides,
+});
+
+export const DISCLOSURE_FIXTURES: readonly DisclosureFixture[] = [
+ {
+ id: 'conforming-closed',
+ summary: 'a collapsed disclosure that can be opened and closed again',
+ facts: facts(),
+ html: disclosure(),
+ },
+ {
+ id: 'conforming-open',
+ summary: 'an expanded disclosure that can be closed and opened again',
+ facts: facts({expanded: true}),
+ html: disclosure({expanded: true}),
+ },
+ {
+ id: 'conforming-no-controls',
+ summary:
+ 'a disclosure using the APG-optional form without an aria-controls relationship',
+ facts: facts({controls: false}),
+ html: disclosure({controls: null}),
+ },
+ {
+ id: 'conforming-inoperable-open',
+ summary:
+ 'an expanded disclosure whose unavailable trigger preserves the visible state',
+ facts: facts({expanded: true, operable: false, focusable: false}),
+ html: disclosure({
+ expanded: true,
+ onclick: '',
+ onkeydown: '',
+ }).replace('<button ', '<button aria-disabled="true" tabindex="-1" '),
+ },
+ {
+ id: 'violating-expanded-missing',
+ summary: 'a disclosure trigger with no expanded state',
+ facts: facts({expanded: true}),
+ html: disclosure({expanded: true}).replace(' aria-expanded="true"', ''),
+ },
+ {
+ id: 'violating-expanded-opposite',
+ summary:
+ 'visible content whose trigger reports the opposite expanded state',
+ facts: facts({expanded: true}),
+ html: disclosure({expanded: true}).replace(
+ 'aria-expanded="true"',
+ 'aria-expanded="false"',
+ ),
+ },
+ {
+ id: 'violating-controls-dangling',
+ summary:
+ 'a relationship that names the content and a second target that does not exist',
+ facts: facts(),
+ html: disclosure({controls: 'content missing'}),
+ },
+ {
+ id: 'violating-controls-unrelated',
+ summary: 'a relationship that points only at unrelated content',
+ facts: facts(),
+ html: disclosure({controls: 'other'}),
+ },
+ {
+ id: 'violating-expanded-content-hidden',
+ summary: 'an expanded trigger whose content remains hidden',
+ facts: facts({expanded: true}),
+ html: disclosure({expanded: true, contentHidden: true}),
+ },
+ {
+ id: 'violating-collapsed-content-visible',
+ summary: 'a collapsed trigger whose content remains visible',
+ facts: facts(),
+ html: disclosure({contentHidden: false}),
+ },
+ {
+ id: 'violating-pointer-one-way',
+ summary: 'a pointer can expand the disclosure but cannot collapse it again',
+ facts: facts(),
+ html: disclosure({onclick: OPEN_ONLY}),
+ },
+ {
+ id: 'violating-pointer-state-only',
+ summary: 'a pointer changes aria-expanded without revealing the content',
+ facts: facts(),
+ html: disclosure({onclick: STATE_ONLY}),
+ },
+ {
+ id: 'violating-enter-unavailable',
+ summary:
+ 'a disclosure that blocks Enter while still responding to a pointer',
+ facts: facts(),
+ html: disclosure({
+ onkeydown: "if (event.key === 'Enter') event.preventDefault();",
+ }),
+ },
+ {
+ id: 'violating-space-unavailable',
+ summary:
+ 'a disclosure that blocks Space while still responding to a pointer',
+ facts: facts(),
+ html: disclosure({
+ onkeydown: "if (event.key === ' ') event.preventDefault();",
+ }),
+ },
+ {
+ id: 'violating-down-event-activation',
+ summary:
+ 'a disclosure that toggles on pointer-down before the user can cancel the press',
+ facts: facts(),
+ html: disclosure({onclick: '', onpointerdown: TOGGLE}),
+ },
+ {
+ id: 'violating-focus-moved',
+ summary: 'a disclosure that moves focus into its content when toggled',
+ facts: facts(),
+ html: disclosure({
+ onclick: `${TOGGLE} document.getElementById('content').focus();`,
+ contentTabIndex: true,
+ }),
+ },
+];
+
+export function fixture(id: string): DisclosureFixture {
+ const found = DISCLOSURE_FIXTURES.find(candidate => candidate.id === id);
+ if (found == null) {
+ throw new Error(`unknown disclosure fixture "${id}"`);
+ }
+ return found;
+}
+
+export const CONFORMING_FIXTURES: readonly string[] =
+ DISCLOSURE_FIXTURES.filter(candidate =>
+ candidate.id.startsWith('conforming-'),
+ ).map(candidate => candidate.id);
+
+export const DISCLOSURE_MUTATIONS: Readonly<Record<string, readonly string[]>> =
+ {
+ 'disclosure.state.expanded': [
+ 'violating-expanded-missing',
+ 'violating-expanded-opposite',
+ ],
+ 'disclosure.relationship.controls': [
+ 'violating-controls-dangling',
+ 'violating-controls-unrelated',
+ ],
+ 'disclosure.content.matches-state': [
+ 'violating-expanded-content-hidden',
+ 'violating-collapsed-content-visible',
+ ],
+ 'disclosure.state.pointer-round-trip': [
+ 'violating-pointer-one-way',
+ 'violating-pointer-state-only',
+ ],
+ 'disclosure.state.enter-round-trip': ['violating-enter-unavailable'],
+ 'disclosure.state.space-round-trip': ['violating-space-unavailable'],
+ 'disclosure.state.survives-an-aborted-press': [
+ 'violating-down-event-activation',
+ ],
+ 'disclosure.focus.stays-on-trigger': ['violating-focus-moved'],
+ };
diff --git a/internal/a11y-spec/src/patterns/disclosure.jsdom.test.ts b/internal/a11y-spec/src/patterns/disclosure.jsdom.test.ts
new file mode 100644
index 0000000000..67aeee3bb7
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/disclosure.jsdom.test.ts
@@ -0,0 +1,155 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file disclosure.jsdom.test.ts
+ * @input Uses the disclosure contract, shared fixtures, jsdom harness, and checker
+ * @output Completeness plus positive and negative DOM proof
+ * @position Contract self-tests; browser-only outcomes remain explicitly unrun.
+ */
+
+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 {DISCLOSURE_PATTERN} from './disclosure';
+import {
+ CONFORMING_FIXTURES,
+ CONTENT_SELECTOR,
+ DISCLOSURE_MUTATIONS,
+ SUBJECT_SELECTOR,
+ fixture,
+ type DisclosureFixture,
+} from './disclosure.fixtures';
+
+const observableHere = DISCLOSURE_PATTERN.expectations.filter(expectation =>
+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),
+);
+
+afterEach(() => document.body.replaceChildren());
+
+async function resultsFor(target: DisclosureFixture) {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const result = await checkAccessibilitySpec({
+ spec: DISCLOSURE_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ mount: async () => {
+ container.innerHTML = target.html;
+ const subject = container.querySelector(SUBJECT_SELECTOR);
+ const content = container.querySelector(CONTENT_SELECTOR);
+ if (subject == null || content == null) {
+ throw new Error(
+ `fixture "${target.id}" is missing its subject or content`,
+ );
+ }
+ return createJsdomHarness({subject, related: {content}});
+ },
+ 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('disclosure contract — completeness', () => {
+ it('answers every completeness dimension', () => {
+ expect(unansweredDimensions(DISCLOSURE_PATTERN)).toEqual([]);
+ });
+
+ it('gives every expectation at least one deliberately violating fixture', () => {
+ const missing = DISCLOSURE_PATTERN.expectations
+ .filter(
+ expectation =>
+ (DISCLOSURE_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(
+ DISCLOSURE_PATTERN.expectations.map(expectation => expectation.id),
+ );
+ expect(
+ Object.keys(DISCLOSURE_MUTATIONS).filter(id => !ids.has(id)),
+ ).toEqual([]);
+ });
+
+ it('names every fixture it records a mutation against', () => {
+ for (const fixtures of Object.values(DISCLOSURE_MUTATIONS)) {
+ for (const id of fixtures) {
+ expect(() => fixture(id)).not.toThrow();
+ }
+ }
+ });
+});
+
+describe('disclosure 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-closed'));
+ 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).toContain('real-browser');
+ }
+ });
+});
+
+describe.each(observableHere.map(expectation => [expectation.id] as const))(
+ '%s',
+ id => {
+ const expectation = DISCLOSURE_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((DISCLOSURE_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(
+ DISCLOSURE_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/disclosure.ts b/internal/a11y-spec/src/patterns/disclosure.ts
new file mode 100644
index 0000000000..a72f8be551
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/disclosure.ts
@@ -0,0 +1,570 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file disclosure.ts
+ * @input Uses the shared accessibility-contract vocabulary
+ * @output DISCLOSURE_PATTERN and DisclosureStateFacts
+ * @position Disclosure-specific state, controlled-content, and interaction contract.
+ * Generic button role, naming, focus navigation, and disabled semantics remain
+ * owned by BUTTON_PATTERN; Accordion/group policy is outside this contract.
+ *
+ * Adopted pattern: https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/
+ *
+ * SYNC: When an expectation changes, update
+ * - /internal/a11y-spec/README.md
+ * - /internal/a11y-spec/src/patterns/disclosure.fixtures.ts
+ * - /packages/core/src/Collapsible/__tests__/Collapsible.a11y.states.ts
+ */
+
+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/disclosure/';
+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_STATE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'disclosure',
+ requirement:
+ 'When the content is visible, the element with role button has aria-expanded set to true. When the content area is hidden, it is set to false.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_CONTROLS: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'disclosure',
+ requirement:
+ 'Optionally, the element with role button has a value specified for aria-controls that refers to the element that contains all the content that is shown or hidden.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_ENTER: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'disclosure',
+ requirement:
+ 'Enter: activates the disclosure control and toggles the visibility of the disclosure content.',
+ url: `${APG_URL}#keyboardinteraction`,
+};
+const APG_SPACE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'disclosure',
+ requirement:
+ 'Space: activates the disclosure control and toggles the visibility of the disclosure content.',
+ url: `${APG_URL}#keyboardinteraction`,
+};
+
+export interface DisclosureStateFacts {
+ /** Whether the controlled content is meant to be visible in this state. */
+ readonly expanded: boolean;
+ /** Whether this binding intentionally declares aria-controls. */
+ readonly controls: boolean;
+ /** Whether the user is meant to be able to toggle this state. */
+ readonly operable: boolean;
+ /** Whether this state is meant to accept keyboard focus. */
+ readonly focusable: boolean;
+}
+
+const ALWAYS = {
+ condition: 'the binding renders a disclosure trigger and its content',
+ test: () => true,
+};
+
+async function authoredExpanded(subject: Subject): Promise<boolean | null> {
+ const value = await subject.attribute('aria-expanded');
+ return value === 'true' ? true : value === 'false' ? false : null;
+}
+
+function stateWord(expanded: boolean): 'expanded' | 'collapsed' {
+ return expanded ? 'expanded' : 'collapsed';
+}
+
+async function assertStateAndContent(
+ subject: Subject,
+ content: 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 content.isVisible();
+ if (visible !== expected) {
+ throw new Error(
+ `${after} left the disclosure ${stateWord(expected)} while its content was ${visible ? 'visible' : 'hidden'}`,
+ );
+ }
+}
+
+async function roundTrip(
+ subject: Subject,
+ content: Subject,
+ start: boolean,
+ activate: () => Promise<void>,
+ how: string,
+): Promise<void> {
+ await assertStateAndContent(subject, content, start, 'the starting state');
+ await activate();
+ await assertStateAndContent(subject, content, !start, how);
+ await activate();
+ await assertStateAndContent(subject, content, start, `${how} a second time`);
+}
+
+export const DISCLOSURE_PATTERN: PatternContract<DisclosureStateFacts> =
+ definePattern<DisclosureStateFacts>({
+ pattern: 'disclosure',
+ url: APG_URL,
+ scope:
+ 'One button-controlled content section whose expanded state and visibility stay synchronized through pointer, Enter, and Space activation.',
+ expectations: [
+ {
+ id: 'disclosure.state.expanded',
+ outcome:
+ 'The trigger identifies whether its controlled content is expanded or collapsed.',
+ sources: [WCAG_4_1_2, APG_STATE],
+ 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 disclosure is ${stateWord(facts.expanded)} but aria-expanded is ${expanded ?? 'absent'}`,
+ );
+ }
+ },
+ },
+ {
+ id: 'disclosure.relationship.controls',
+ outcome:
+ 'A declared control relationship identifies the content being disclosed.',
+ sources: [WCAG_1_3_1, APG_CONTROLS],
+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],
+ appliesWhen: {
+ condition:
+ 'the binding intentionally declares a controlled-content relationship',
+ test: facts => facts.controls,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const content = await harness.related('content');
+ if (!(await harness.references(subject, 'aria-controls', content))) {
+ throw new Error(
+ 'aria-controls does not identify the disclosed content',
+ );
+ }
+ if (
+ (await subject.idReferences('aria-controls')).some(
+ target => target === null,
+ )
+ ) {
+ throw new Error('aria-controls includes a missing content target');
+ }
+ },
+ },
+ {
+ id: 'disclosure.content.matches-state',
+ outcome:
+ 'Expanded content is visible and collapsed content is hidden, so the exposed state describes what the user receives.',
+ sources: [WCAG_4_1_2, APG_STATE],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await assertStateAndContent(
+ subject,
+ await harness.related('content'),
+ facts.expanded,
+ 'the rendered state',
+ );
+ },
+ },
+ {
+ id: 'disclosure.state.pointer-round-trip',
+ outcome:
+ 'A pointer reveals the content and hides it again, with the exposed state following both transitions.',
+ sources: [WCAG_4_1_2, APG_STATE],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the disclosure can be operated',
+ test: facts => facts.operable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await roundTrip(
+ subject,
+ await harness.related('content'),
+ facts.expanded,
+ () => harness.click(subject),
+ 'clicking the disclosure',
+ );
+ },
+ },
+ {
+ id: 'disclosure.state.enter-round-trip',
+ outcome:
+ 'With focus on the trigger, Enter reveals the content and hides it again.',
+ sources: [WCAG_2_1_1, APG_ENTER],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition:
+ 'the disclosure can be operated and its trigger can receive focus',
+ test: facts => facts.operable && facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'the disclosure trigger did not take focus, so Enter never reaches it',
+ );
+ }
+ await roundTrip(
+ subject,
+ await harness.related('content'),
+ facts.expanded,
+ () => harness.press('Enter'),
+ 'pressing Enter on the focused disclosure',
+ );
+ },
+ },
+ {
+ id: 'disclosure.state.space-round-trip',
+ outcome:
+ 'With focus on the trigger, Space reveals the content and hides it again.',
+ sources: [WCAG_2_1_1, APG_SPACE],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition:
+ 'the disclosure can be operated and its trigger can receive focus',
+ test: facts => facts.operable && facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'the disclosure trigger did not take focus, so Space never reaches it',
+ );
+ }
+ await roundTrip(
+ subject,
+ await harness.related('content'),
+ facts.expanded,
+ () => harness.press('Space'),
+ 'pressing Space on the focused disclosure',
+ );
+ },
+ },
+ {
+ id: 'disclosure.state.survives-an-aborted-press',
+ outcome:
+ 'A press released away from the trigger leaves the disclosure unchanged, so an unintended press can be cancelled.',
+ sources: [WCAG_2_5_2],
+ covers: ['2.5.2-pointer-cancellation'],
+ appliesWhen: {
+ condition: 'the disclosure can be operated',
+ test: facts => facts.operable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ const content = await harness.related('content');
+ await assertStateAndContent(
+ subject,
+ content,
+ facts.expanded,
+ 'the starting state',
+ );
+ await harness.abortedPress(subject);
+ await assertStateAndContent(
+ subject,
+ content,
+ facts.expanded,
+ 'releasing the press away from the disclosure',
+ );
+ },
+ },
+ {
+ id: 'disclosure.focus.stays-on-trigger',
+ outcome:
+ 'Toggling the disclosure leaves focus on its trigger, so the user stays at the control they changed.',
+ sources: [WCAG_3_2_2],
+ covers: ['3.2.2-on-input'],
+ appliesWhen: {
+ condition:
+ 'the disclosure can be operated and its trigger can receive focus',
+ test: facts => facts.operable && facts.focusable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'the disclosure trigger did not take focus, so the focus result of changing it cannot be observed',
+ );
+ }
+ const content = await harness.related('content');
+ await harness.press('Space');
+ await assertStateAndContent(
+ subject,
+ content,
+ !facts.expanded,
+ 'pressing Space on the focused disclosure',
+ );
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ 'toggling the disclosure moved focus away from its trigger',
+ );
+ }
+ },
+ },
+ ],
+ 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 disclosure 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 optional trigger-to-content relationship. Other structure and relationships inside or around that content 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:
+ 'A disclosure 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 disclosure 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 disclosure-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 disclosure-specific Enter and Space state transitions. 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:
+ 'A disclosure 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: 'A disclosure 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 only that toggling does not move focus',
+ reason:
+ 'Sequential order across the trigger, revealed content, and surrounding controls depends on composition.',
+ },
+ '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 disclosure 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 disclosure 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: 'A disclosure 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 disclosure labels',
+ reason:
+ 'Consistency is a property of the full set of repeated functions, not one isolated disclosure.',
+ },
+ '3.3.1-error-identification': {
+ owner: 'the binding component and composing form',
+ verifiedBy: 'form-level error-state and text review',
+ reason: 'The disclosure 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 disclosure 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 disclosure-expanded state and its transitions. Generic button role, name, and unavailable state 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 disclosure 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 disclosure 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 disclosure contract introduces no string; trigger and content text come from the binding or caller.',
+ },
+ },
+ });
diff --git a/packages/core/src/Collapsible/Collapsible.spec.md b/packages/core/src/Collapsible/Collapsible.spec.md
index 44b626e93a..4698bff1cc 100644
--- a/packages/core/src/Collapsible/Collapsible.spec.md
+++ b/packages/core/src/Collapsible/Collapsible.spec.md
@@ -14,6 +14,8 @@ verified_by:
[
packages/core/src/Collapsible/Collapsible.test.tsx,
packages/core/src/Collapsible/CollapsibleGroup.test.tsx,
+ packages/core/src/Collapsible/__tests__/Collapsible.a11y.test.tsx,
+ packages/core/src/Collapsible/__tests__/Collapsible.a11y.chromium.spec.ts,
]
modules: []
families: []
@@ -21,7 +23,7 @@ design_specs: []
architecture:
[architecture:public-component-api, architecture:react-component-runtime]
contributing: [contributing:api-conventions]
-system_specs: [spec:AST-002/DEC-1]
+system_specs: [spec:AST-002/DEC-1, spec:AST-020, spec:AST-021]
---
# Collapsible component contract
@@ -163,12 +165,12 @@ semantic direction or position states.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------ | ---------------------------------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
-| FR1–FR5 | Collapsible prop/type, DOM-order, glyph/direction, and no-extra-values tests | omitted/end/start; collapsed/expanded; LTR/RTL | default changes, `start` follows the label, collapsed leading cue points outward, or an unsupported cue value is admitted | audit:Collapsible/public-api |
-| FR6 | composed trigger layout and geometry tests | plain text; composed label with trailing content; start/end | label becomes shrink-wrapped/stranded or composed content cannot use remaining row | audit:Collapsible/layout |
-| FR7–FR8, ORD1 | group inheritance, item override, and nested reset tests | group start/end; item override; nested omission | group value is ignored, item cannot override, or position leaks into nested content | audit:Collapsible/behavior |
-| FR9, AR1–AR3, ORD2 | disclosure semantics plus real RTL rendering | collapsed/expanded; start/end; LTR/RTL | position changes state behavior, duplicates accessible output, or leading direction fails to mirror | audit:Collapsible/accessibility |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------ | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
+| FR1–FR5 | Collapsible prop/type, DOM-order, glyph/direction, and no-extra-values tests | omitted/end/start; collapsed/expanded; LTR/RTL | default changes, `start` follows the label, collapsed leading cue points outward, or an unsupported cue value is admitted | audit:Collapsible/public-api |
+| FR6 | composed trigger layout and geometry tests | plain text; composed label with trailing content; start/end | label becomes shrink-wrapped/stranded or composed content cannot use remaining row | audit:Collapsible/layout |
+| FR7–FR8, ORD1 | group inheritance, item override, and nested reset tests | group start/end; item override; nested omission | group value is ignored, item cannot override, or position leaks into nested content | audit:Collapsible/behavior |
+| FR9, AR1–AR3, ORD2 | disclosure semantics via `DISCLOSURE_PATTERN`, plus component-owned chevron and real RTL rendering | collapsed/expanded; controlled/uncontrolled; enabled/disabled; start/end; LTR/RTL | position changes state behavior, the trigger loses its controlled-content relationship, content visibility diverges from state, accessible output duplicates, or leading direction fails to mirror | audit:Collapsible/accessibility |
## Decision log
diff --git a/packages/core/src/Collapsible/Collapsible.test.tsx b/packages/core/src/Collapsible/Collapsible.test.tsx
index 96b47013a8..6394130222 100644
--- a/packages/core/src/Collapsible/Collapsible.test.tsx
+++ b/packages/core/src/Collapsible/Collapsible.test.tsx
@@ -57,13 +57,6 @@ describe('Collapsible', () => {
expect(within(content).getByTestId('child')).toBeInTheDocument();
});
- it('links the trigger to its content via aria-controls', () => {
- render(<Collapsible trigger="T">Body</Collapsible>);
- const button = screen.getByRole('button');
- const content = contentFor(button);
- expect(button.getAttribute('aria-controls')).toBe(content.id);
- });
-
it('renders the stable astryx-collapsible class on the root', () => {
render(
<Collapsible trigger="T" data-testid="root">
@@ -97,77 +90,6 @@ describe('Collapsible', () => {
});
describe('uncontrolled open state', () => {
- it('is open by default (aria-expanded="true")', () => {
- render(<Collapsible trigger="T">Body</Collapsible>);
- expect(screen.getByRole('button')).toHaveAttribute(
- 'aria-expanded',
- 'true',
- );
- });
-
- it('honors defaultIsOpen={false} (starts collapsed)', () => {
- render(
- <Collapsible trigger="T" defaultIsOpen={false}>
- Body
- </Collapsible>,
- );
- expect(screen.getByRole('button')).toHaveAttribute(
- 'aria-expanded',
- 'false',
- );
- });
-
- it('toggles open/closed when the trigger is clicked', async () => {
- const user = userEvent.setup();
- render(<Collapsible trigger="T">Body</Collapsible>);
- const button = screen.getByRole('button');
-
- expect(button).toHaveAttribute('aria-expanded', 'true');
- await user.click(button);
- expect(button).toHaveAttribute('aria-expanded', 'false');
- await user.click(button);
- expect(button).toHaveAttribute('aria-expanded', 'true');
- });
-
- it('opens a default-collapsed instance on click', async () => {
- const user = userEvent.setup();
- render(
- <Collapsible trigger="T" defaultIsOpen={false}>
- Body
- </Collapsible>,
- );
- const button = screen.getByRole('button');
- await user.click(button);
- expect(button).toHaveAttribute('aria-expanded', 'true');
- });
-
- it('toggles via keyboard activation (Enter and Space)', async () => {
- const user = userEvent.setup();
- render(<Collapsible trigger="T">Body</Collapsible>);
- const button = screen.getByRole('button');
-
- button.focus();
- expect(button).toHaveFocus();
-
- await user.keyboard('{Enter}');
- expect(button).toHaveAttribute('aria-expanded', 'false');
- await user.keyboard(' ');
- expect(button).toHaveAttribute('aria-expanded', 'true');
- });
-
- it('hides the content region (display:none) only when collapsed', async () => {
- const user = userEvent.setup();
- render(<Collapsible trigger="T">Body</Collapsible>);
- const button = screen.getByRole('button');
- const content = contentFor(button);
-
- // Open: not display:none.
- expect(content).not.toHaveStyle({display: 'none'});
- await user.click(button);
- // Collapsed: hidden via the contentHidden style.
- expect(content).toHaveStyle({display: 'none'});
- });
-
it('rotates the chevron indicator between open and closed states', async () => {
const user = userEvent.setup();
render(<Collapsible trigger="T">Body</Collapsible>);
diff --git a/packages/core/src/Collapsible/CollapsibleGroup.test.tsx b/packages/core/src/Collapsible/CollapsibleGroup.test.tsx
index f92e5061d4..4cb7765988 100644
--- a/packages/core/src/Collapsible/CollapsibleGroup.test.tsx
+++ b/packages/core/src/Collapsible/CollapsibleGroup.test.tsx
@@ -30,69 +30,6 @@ describe('Collapsible', () => {
expect(screen.getByText('Content')).toBeInTheDocument();
});
- it('starts open by default', () => {
- render(
- <Collapsible trigger="Details">
- <p>Visible content</p>
- </Collapsible>,
- );
-
- const trigger = screen.getByRole('button', {name: /Details/});
- expect(trigger).toHaveAttribute('aria-expanded', 'true');
- expect(screen.getByText('Visible content')).toBeVisible();
- });
-
- it('toggles content on click', async () => {
- const user = userEvent.setup();
- render(
- <Collapsible trigger="Details">
- <p>Collapsible content</p>
- </Collapsible>,
- );
-
- const trigger = screen.getByRole('button', {name: /Details/});
- expect(trigger).toHaveAttribute('aria-expanded', 'true');
- expect(screen.getByText('Collapsible content')).toBeVisible();
-
- // Click to collapse
- await user.click(trigger);
- expect(trigger).toHaveAttribute('aria-expanded', 'false');
- expect(screen.getByText('Collapsible content')).not.toBeVisible();
-
- // Click to expand
- await user.click(trigger);
- expect(trigger).toHaveAttribute('aria-expanded', 'true');
- expect(screen.getByText('Collapsible content')).toBeVisible();
- });
-
- it('starts collapsed when defaultIsOpen is false', () => {
- render(
- <Collapsible trigger="Details" defaultIsOpen={false}>
- <p>Hidden content</p>
- </Collapsible>,
- );
-
- const trigger = screen.getByRole('button', {name: /Details/});
- expect(trigger).toHaveAttribute('aria-expanded', 'false');
- expect(screen.getByText('Hidden content')).not.toBeVisible();
- });
-
- it('links the trigger to its content region via aria-controls', () => {
- render(
- <Collapsible trigger="Details">
- <p>Region content</p>
- </Collapsible>,
- );
-
- const trigger = screen.getByRole('button', {name: /Details/});
- const controlsId = trigger.getAttribute('aria-controls');
- // aria-controls must be present and point at the real content region.
- expect(controlsId).toBeTruthy();
- const region = document.getElementById(controlsId as string);
- expect(region).not.toBeNull();
- expect(region).toContainElement(screen.getByText('Region content'));
- });
-
it('respects controlled isOpen/onOpenChange', async () => {
const onOpenChange = vi.fn();
const user = userEvent.setup();
@@ -169,26 +106,6 @@ describe('Collapsible', () => {
expect(svg).toBeInTheDocument();
expect(svg).toHaveAttribute('aria-hidden');
});
-
- it('activates via keyboard (Enter and Space)', async () => {
- const user = userEvent.setup();
- render(
- <Collapsible trigger="Keyboard">
- <p>Content</p>
- </Collapsible>,
- );
-
- const trigger = screen.getByRole('button', {name: /Keyboard/});
- trigger.focus();
-
- // Enter key
- await user.keyboard('{Enter}');
- expect(trigger).toHaveAttribute('aria-expanded', 'false');
-
- // Space key
- await user.keyboard(' ');
- expect(trigger).toHaveAttribute('aria-expanded', 'true');
- });
});
// =============================================================================
diff --git a/packages/core/src/Collapsible/__tests__/Collapsible.a11y.chromium.spec.ts b/packages/core/src/Collapsible/__tests__/Collapsible.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..a91f2d2881
--- /dev/null
+++ b/packages/core/src/Collapsible/__tests__/Collapsible.a11y.chromium.spec.ts
@@ -0,0 +1,182 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Collapsible.a11y.chromium.spec.ts
+ * @input Uses the disclosure contract, Chromium harness, checked-in stories, and Collapsible state inventory
+ * @output Real-browser proof for every standalone Collapsible disclosure state
+ * @position Browser binding. It makes no speech, braille, or group-policy claim.
+ */
+
+import {
+ expect,
+ test,
+ type CDPSession,
+ type Locator,
+ type Page,
+} from '@playwright/test';
+import {
+ DISCLOSURE_PATTERN,
+ blockingResults,
+ checkAccessibilitySpec,
+ formatFailures,
+ formatReport,
+ 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_DISCLOSURE_STATES,
+ type CollapsibleDisclosureState,
+} from './Collapsible.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`;
+}
+
+async function mountState(
+ page: Page,
+ state: CollapsibleDisclosureState,
+): Promise<{subject: Locator; content: Locator}> {
+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});
+ await holdMotionStill(page);
+ const root = page.locator('#storybook-root');
+ const subject = root.getByRole('button', {name: state.label});
+ await subject.waitFor({state: 'attached'});
+ const id = await subject.getAttribute('aria-controls');
+ if (id == null) {
+ throw new Error(`Collapsible state "${state.id}" has no aria-controls`);
+ }
+ const content = root.locator(`[id="${id}"]`);
+ await content.waitFor({state: 'attached'});
+ return {subject, content};
+}
+
+async function runState(
+ page: Page,
+ cdp: CDPSession,
+ state: CollapsibleDisclosureState,
+): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: DISCLOSURE_PATTERN,
+ binding: 'Collapsible.trigger',
+ state: state.id,
+ facts: state.facts,
+ mount: async () => {
+ const {subject, content} = await mountState(page, state);
+ return createChromiumHarness({
+ page,
+ cdp,
+ subject,
+ related: {content},
+ });
+ },
+ });
+}
+
+test('the state inventory matches rendered disclosure facts', async ({
+ page,
+}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const wrong: string[] = [];
+ for (const state of COLLAPSIBLE_DISCLOSURE_STATES) {
+ const {subject, content} = await mountState(page, state);
+ const expanded = (await subject.getAttribute('aria-expanded')) === 'true';
+ const controls = (await subject.getAttribute('aria-controls')) != null;
+ const visible = await content.isVisible();
+ 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 subject.evaluate(
+ element => element.ownerDocument.activeElement === element,
+ );
+ }
+ const harness = createChromiumHarness({
+ page,
+ cdp,
+ subject,
+ related: {content},
+ });
+ const semanticSubject = await harness.subject();
+ const beforeActivation = await semanticSubject.attribute('aria-expanded');
+ await harness.click(semanticSubject, {ignoreAvailability: true});
+ const afterActivation = await semanticSubject.attribute('aria-expanded');
+ const operable = beforeActivation !== afterActivation;
+ if (expanded !== state.facts.expanded) {
+ wrong.push(
+ `${state.id}: declares expanded=${state.facts.expanded}, page exposes ${expanded}`,
+ );
+ }
+ if (visible !== state.facts.expanded) {
+ wrong.push(
+ `${state.id}: declares expanded=${state.facts.expanded}, content visibility is ${visible}`,
+ );
+ }
+ if (controls !== state.facts.controls) {
+ wrong.push(
+ `${state.id}: declares controls=${state.facts.controls}, page exposes ${controls}`,
+ );
+ }
+ if (reachedByTab !== state.facts.focusable) {
+ wrong.push(
+ `${state.id}: declares focusable=${state.facts.focusable}, Tab reachability is ${reachedByTab}`,
+ );
+ }
+ if (operable !== state.facts.operable) {
+ wrong.push(
+ `${state.id}: declares operable=${state.facts.operable}, forced pointer activation changed state=${operable}`,
+ );
+ }
+ }
+ expect(wrong).toEqual([]);
+});
+
+test('every disclosure expectation is exercised by a Collapsible state', async ({
+ page,
+}) => {
+ test.setTimeout(3 * 60 * 1000);
+ const cdp = await page.context().newCDPSession(page);
+ const results: BindingResult[] = [];
+ for (const state of COLLAPSIBLE_DISCLOSURE_STATES) {
+ results.push(await runState(page, cdp, state));
+ }
+ expect(neverExercised(results)).toEqual([]);
+});
+
+for (const state of COLLAPSIBLE_DISCLOSURE_STATES) {
+ test(`Collapsible.trigger [${state.id}] — ${state.summary}`, async ({
+ page,
+ }) => {
+ const cdp = await page.context().newCDPSession(page);
+ const result = await runState(page, cdp, state);
+ const report = summarize(DISCLOSURE_PATTERN, [result]);
+ // eslint-disable-next-line no-console -- the report is this run's artifact
+ console.log(formatReport(report));
+ expect(formatFailures(blockingResults([result]))).toBe('');
+ expect(report.unrunLayers).toEqual([]);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+}
diff --git a/packages/core/src/Collapsible/__tests__/Collapsible.a11y.states.ts b/packages/core/src/Collapsible/__tests__/Collapsible.a11y.states.ts
new file mode 100644
index 0000000000..29da260083
--- /dev/null
+++ b/packages/core/src/Collapsible/__tests__/Collapsible.a11y.states.ts
@@ -0,0 +1,117 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Collapsible.a11y.states.ts
+ * @input Uses DisclosureStateFacts and CollapsibleProps as type-only contracts
+ * @output COLLAPSIBLE_DISCLOSURE_STATES and explicit non-adoptions
+ * @position Collapsible.trigger binding inventory shared by jsdom and Chromium.
+ */
+
+import type {DisclosureStateFacts} from '@astryxdesign/a11y-spec';
+import type {CollapsibleProps} from '../Collapsible';
+
+export interface CollapsibleDisclosureState {
+ readonly id: string;
+ readonly summary: string;
+ readonly storyId: string;
+ readonly label: string;
+ readonly facts: DisclosureStateFacts;
+ readonly props: Omit<
+ CollapsibleProps,
+ 'children' | 'trigger' | 'onOpenChange' | 'isOpen'
+ >;
+ readonly controlled?: boolean;
+ readonly direction?: 'ltr' | 'rtl';
+}
+
+function facts(
+ overrides: Partial<DisclosureStateFacts> = {},
+): DisclosureStateFacts {
+ return {
+ expanded: true,
+ controls: true,
+ operable: true,
+ focusable: true,
+ ...overrides,
+ };
+}
+
+export const COLLAPSIBLE_DISCLOSURE_STATES = [
+ {
+ id: 'uncontrolled-open-end-ltr',
+ summary:
+ 'the default standalone Collapsible, open with its trailing chevron',
+ storyId: 'a11y-collapsible-disclosure--uncontrolled-open-end-ltr',
+ label: 'Account details',
+ facts: facts(),
+ props: {},
+ },
+ {
+ id: 'uncontrolled-closed-start-rtl',
+ summary:
+ 'a standalone Collapsible initially closed, with its leading chevron under RTL',
+ storyId: 'a11y-collapsible-disclosure--uncontrolled-closed-start-rtl',
+ label: 'Privacy details',
+ facts: facts({expanded: false}),
+ props: {defaultIsOpen: false, chevronPosition: 'start'},
+ direction: 'rtl',
+ },
+ {
+ id: 'controlled-open-end-ltr',
+ summary:
+ 'a controlled standalone Collapsible whose owner starts it open and follows changes',
+ storyId: 'a11y-collapsible-disclosure--controlled-open-end-ltr',
+ label: 'Notification details',
+ facts: facts(),
+ props: {},
+ controlled: true,
+ },
+ {
+ id: 'controlled-closed-start-ltr',
+ summary:
+ 'a controlled standalone Collapsible whose owner starts it closed and follows changes',
+ storyId: 'a11y-collapsible-disclosure--controlled-closed-start-ltr',
+ label: 'Security details',
+ facts: facts({expanded: false}),
+ props: {chevronPosition: 'start'},
+ controlled: true,
+ },
+ {
+ id: 'disabled-open-end-ltr',
+ summary:
+ 'an unavailable standalone Collapsible that preserves its visible content',
+ storyId: 'a11y-collapsible-disclosure--disabled-open-end-ltr',
+ label: 'Archived details',
+ facts: facts({operable: false, focusable: false}),
+ props: {isDisabled: true},
+ },
+ {
+ id: 'disabled-closed-start-rtl',
+ summary:
+ 'an unavailable standalone Collapsible that preserves its hidden content under RTL',
+ storyId: 'a11y-collapsible-disclosure--disabled-closed-start-rtl',
+ label: 'Restricted details',
+ facts: facts({expanded: false, operable: false, focusable: false}),
+ props: {
+ isDisabled: true,
+ defaultIsOpen: false,
+ chevronPosition: 'start',
+ },
+ direction: 'rtl',
+ },
+] as const satisfies ReadonlyArray<CollapsibleDisclosureState>;
+
+export const COLLAPSIBLE_DISCLOSURE_EXCLUSIONS = [
+ {
+ id: 'collapsible-group-coordination',
+ owner: 'CollapsibleGroup.test.tsx and useCollapsible.test.tsx',
+ reason:
+ 'Single/multiple group coordination changes sibling state and callback payloads. This PR binds only the standalone Collapsible trigger; it does not adopt an Accordion or group pattern.',
+ },
+ {
+ id: 'collapsible-button-semantics',
+ owner: 'BUTTON_PATTERN and Collapsible.test.tsx',
+ reason:
+ 'Role, accessible name, generic focus navigation, and unavailable-button semantics are button outcomes. The disclosure contract owns only expanded state, controlled content, and disclosure-specific transitions.',
+ },
+] as const;
diff --git a/packages/core/src/Collapsible/__tests__/Collapsible.a11y.test.tsx b/packages/core/src/Collapsible/__tests__/Collapsible.a11y.test.tsx
new file mode 100644
index 0000000000..dd3c759326
--- /dev/null
+++ b/packages/core/src/Collapsible/__tests__/Collapsible.a11y.test.tsx
@@ -0,0 +1,140 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file Collapsible.a11y.test.tsx
+ * @input Uses Collapsible, its binding inventory, and the disclosure contract
+ * @output DOM evidence for every standalone Collapsible disclosure state
+ * @position Component binding. Group coordination and generic button outcomes remain separate.
+ */
+
+import {useState} from 'react';
+import {cleanup, render, screen} from '@testing-library/react';
+import {describe, expect, it} from 'vitest';
+import {
+ DISCLOSURE_PATTERN,
+ checkAccessibilitySpec,
+ createJsdomHarness,
+ expectAccessibilitySpec,
+ summarize,
+ type BindingResult,
+} from '@astryxdesign/a11y-spec';
+import {Collapsible} from '../Collapsible';
+import {
+ COLLAPSIBLE_DISCLOSURE_EXCLUSIONS,
+ COLLAPSIBLE_DISCLOSURE_STATES,
+ type CollapsibleDisclosureState,
+} from './Collapsible.a11y.states';
+
+function BoundCollapsible({state}: {state: CollapsibleDisclosureState}) {
+ const [open, setOpen] = useState(state.facts.expanded);
+ const component = state.controlled ? (
+ <Collapsible
+ {...state.props}
+ trigger={state.label}
+ isOpen={open}
+ onOpenChange={setOpen}>
+ Disclosure content
+ </Collapsible>
+ ) : (
+ <Collapsible {...state.props} trigger={state.label}>
+ Disclosure content
+ </Collapsible>
+ );
+ return (
+ <div dir={state.direction ?? 'ltr'}>
+ {component}
+ <button type="button">After disclosure</button>
+ </div>
+ );
+}
+
+function subjectFor(state: CollapsibleDisclosureState): HTMLElement {
+ return screen.getByRole('button', {name: state.label});
+}
+
+function contentFor(state: CollapsibleDisclosureState): HTMLElement {
+ const id = subjectFor(state).getAttribute('aria-controls');
+ const content = id == null ? null : document.getElementById(id);
+ if (content == null) {
+ throw new Error(
+ `Collapsible state "${state.id}" has no controlled content`,
+ );
+ }
+ return content;
+}
+
+function renderState(state: CollapsibleDisclosureState): void {
+ render(<BoundCollapsible state={state} />);
+}
+
+async function expectState(state: CollapsibleDisclosureState): Promise<void> {
+ await expectAccessibilitySpec({
+ spec: DISCLOSURE_PATTERN,
+ binding: 'Collapsible.trigger',
+ state: state.id,
+ facts: state.facts,
+ render: () => renderState(state),
+ subject: () => subjectFor(state),
+ related: () => ({content: contentFor(state)}),
+ cleanup,
+ });
+}
+
+async function checkState(
+ state: CollapsibleDisclosureState,
+): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: DISCLOSURE_PATTERN,
+ binding: 'Collapsible.trigger',
+ state: state.id,
+ facts: state.facts,
+ mount: async () => {
+ renderState(state);
+ return createJsdomHarness({
+ subject: subjectFor(state),
+ related: {content: contentFor(state)},
+ });
+ },
+ unmount: cleanup,
+ });
+}
+
+describe('Collapsible.trigger — disclosure pattern, jsdom lane', () => {
+ it.each(
+ COLLAPSIBLE_DISCLOSURE_STATES.map(
+ state => [state.id, state.summary, state] as const,
+ ),
+ )('%s — %s', async (_id, _summary, state) => {
+ await expectState(state);
+ });
+
+ it('runs the DOM layer and reports browser-owned outcomes as unrun', async () => {
+ const results: BindingResult[] = [];
+ for (const state of COLLAPSIBLE_DISCLOSURE_STATES) {
+ results.push(await checkState(state));
+ }
+ const report = summarize(DISCLOSURE_PATTERN, results);
+ expect(report.counts.pass).toBeGreaterThan(0);
+ expect(report.unrunLayers).toEqual(['real-browser']);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+});
+
+describe('Collapsible disclosure binding inventory', () => {
+ it('gives every representative state a distinct checked-in story', () => {
+ const stories = COLLAPSIBLE_DISCLOSURE_STATES.map(state => state.storyId);
+ expect(new Set(stories).size).toBe(stories.length);
+ });
+
+ it('keeps group and generic button ownership explicit', () => {
+ expect(COLLAPSIBLE_DISCLOSURE_EXCLUSIONS.map(row => row.id)).toEqual([
+ 'collapsible-group-coordination',
+ 'collapsible-button-semantics',
+ ]);
+ for (const exclusion of COLLAPSIBLE_DISCLOSURE_EXCLUSIONS) {
+ expect(exclusion.owner.length, exclusion.id).toBeGreaterThan(20);
+ expect(exclusion.reason.length, exclusion.id).toBeGreaterThan(80);
+ }
+ });
+});