Skip to content

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

TypeScript

test(a11y): add Menu contract and bind the DropdownMenu pointer menu (#7636)

Cindy Zhang198a7e3ffcb8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 9b5a09d18c..1ae9b58da5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1630,6 +1630,56 @@ jobs:
retention-days: 30
if-no-files-found: warn
+ # The menu contract's role and name, item roles, and the arrow, Home/End,
+ # typeahead, Enter, Escape and Tab transitions are accessibility-tree and
+ # real-browser facts that jsdom cannot observe. Run the contract's own
+ # fixture proof and the DropdownMenu pointer-menu binding whenever
+ # DropdownMenu 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 Menu accessibility contract
+ id: menu-contract
+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}
+ env:
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ PLAYWRIGHT_JSON_OUTPUT_FILE: menu-contract/report.json
+ run: |
+ should_run=false
+ # DropdownMenu 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/menu\.|packages/core/src/DropdownMenu/|apps/storybook/stories/MenuA11y)' || scope=$?
+ fi
+ if [ "$scope" != 1 ]; then
+ should_run=true
+ fi
+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"
+ if [ "$should_run" != true ]; then
+ echo "DropdownMenu and the menu contract are not in PR scope; skipping menu evidence."
+ exit 0
+ fi
+ pnpm exec playwright test \
+ internal/a11y-spec/src/patterns/menu.chromium.spec.ts \
+ packages/core/src/DropdownMenu/__tests__/Menu.a11y.chromium.spec.ts \
+ --project chromium \
+ --reporter list,json \
+ --output menu-contract-output
+
+ - name: Upload Menu accessibility contract evidence
+ if: ${{ !cancelled() && steps.menu-contract.outputs.should_run == 'true' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: menu-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: menu-contract/
+ 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
diff --git a/apps/storybook/stories/MenuA11y.stories.tsx b/apps/storybook/stories/MenuA11y.stories.tsx
new file mode 100644
index 0000000000..775456f164
--- /dev/null
+++ b/apps/storybook/stories/MenuA11y.stories.tsx
@@ -0,0 +1,35 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MenuA11y.stories.tsx
+ * @input The DropdownMenu menu-surface binding states
+ * @output One checked-in story per state for the Chromium accessibility lane; excluded from the visual matrix
+ * @position Browser fixtures for the DropdownMenu menu surface (MENU_PATTERN)
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {renderMenuState} from '../../../packages/core/src/DropdownMenu/__tests__/Menu.a11y.renders';
+import {MENU_BINDING_STATES} from '../../../packages/core/src/DropdownMenu/__tests__/Menu.a11y.states';
+
+const meta = {
+ title: 'A11y/Menu',
+ tags: ['no-visual'],
+ parameters: {layout: 'padded'},
+} satisfies Meta;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+function storyFor(id: (typeof MENU_BINDING_STATES)[number]['id']): Story {
+ const state = MENU_BINDING_STATES.find(candidate => candidate.id === id);
+ if (state == null) {
+ throw new Error(`no Menu binding state "${id}"`);
+ }
+ return {render: () => renderMenuState(state)};
+}
+
+export const DropdownActions = storyFor('dropdown-actions');
+export const DropdownSelectable = storyFor('dropdown-selectable');
+export const DropdownSelectableCheckboxRow = storyFor(
+ 'dropdown-selectable-checkbox-row',
+);
diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.md
index 676f8471a2..c2c28fabbb 100644
--- a/internal/a11y-spec/README.md
+++ b/internal/a11y-spec/README.md
@@ -52,6 +52,7 @@ src/
├── spinbutton.* numeric role, value, bounds, state, and arrow stepping
├── disclosure.* standalone disclosure state/content semantics
├── menu-button.* a control's button role and name, aria-haspopup, expanded state, controls, and keyboard opens
+ ├── menu.* a displayed menu's role and name, item roles/names/checked/disabled state, and arrow/Home/End/Enter/Escape/Tab keys (typeahead advisory)
├── window-splitter.* a focusable resize separator's role, name, position/bounds, pane relationship, and arrow/Enter keys (Home/End advisory)
├── grid.* a composite grid's role, name, row/cell structure, single Tab stop, selection, and arrow/Home/End/Enter keys
├── alert-dialog.* a confirmation surface's alertdialog role, title/message references, modality, initial focus, Escape and click-beside dismissal
@@ -82,6 +83,7 @@ src/
| `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 |
| `menu-button` | [APG Menu Button](https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/) required parts; the optional ArrowDown/ArrowUp opens Astryx ships are advisory | Anchored DropdownMenu and MoreMenu triggers: button role and name, `aria-haspopup="menu"`, `aria-expanded`, `aria-controls`, Enter/Space open on the first enabled item (advisory: ArrowDown on the first, ArrowUp on the last) |
+| `menu` | [APG Menu and Menubar](https://www.w3.org/WAI/ARIA/apg/patterns/menubar/) menu; arrows (with wrap) and Home/End per AST-020 FR15; typeahead advisory | DropdownMenu pointer menu: named `menu`, item roles/names, `aria-checked`, `aria-disabled`, arrows with wrap, Home/End, Enter and Escape back to the trigger, Tab out (advisory: typeahead) |
| `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 |
| `combobox` | WCAG 2.2 + [WAI-ARIA 1.2 Combobox](https://www.w3.org/TR/wai-aria-1.2/#combobox); APG as context | Selector trigger identity, state, popup, and active-descendant relationships |
diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.ts
index beeafde4e8..e11e994a4b 100644
--- a/internal/a11y-spec/src/index.ts
+++ b/internal/a11y-spec/src/index.ts
@@ -166,6 +166,7 @@ export {
MENU_BUTTON_PATTERN,
type MenuButtonStateFacts,
} from './patterns/menu-button';
+export {MENU_PATTERN, type MenuStateFacts} from './patterns/menu';
export {
LINK_PATTERN,
type LinkCurrentToken,
diff --git a/internal/a11y-spec/src/patterns/menu.chromium.spec.ts b/internal/a11y-spec/src/patterns/menu.chromium.spec.ts
new file mode 100644
index 0000000000..aedb63b198
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/menu.chromium.spec.ts
@@ -0,0 +1,112 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file menu.chromium.spec.ts
+ * @input MENU_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 {MENU_PATTERN} from './menu';
+import {
+ MENU_MUTATIONS,
+ CONFORMING_FIXTURES,
+ SUBJECT_SELECTOR,
+ fixture,
+ type MenuFixture,
+} from './menu.fixtures';
+
+interface ActivationWindow extends Window {
+ __menuActivations?: number;
+}
+
+function fixturePage(html: string): string {
+ return `<!doctype html><html lang="en"><body>${html}<button type="button" id="after">After menu</button></body></html>`;
+}
+
+async function results(
+ page: Page,
+ cdp: CDPSession,
+ target: MenuFixture,
+ only?: readonly string[],
+): Promise<readonly ExpectationResult[]> {
+ const run = await checkAccessibilitySpec({
+ spec: MENU_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ only,
+ mount: async () => {
+ await page.setContent(fixturePage(target.html));
+ await holdMotionStill(page);
+ await page.evaluate(() => {
+ (window as ActivationWindow).__menuActivations = 0;
+ });
+ return createChromiumHarness({
+ page,
+ cdp,
+ subject: page.locator(SUBJECT_SELECTOR),
+ related: Object.fromEntries(
+ Object.entries(target.relations).map(([name, selector]) => [
+ name,
+ page.locator(selector),
+ ]),
+ ),
+ });
+ },
+ // An item's action leaves no trace on the menu, so the fixture script
+ // counts Enter activations on the window and the contract asks for them.
+ activations: () =>
+ page.evaluate(() => (window as ActivationWindow).__menuActivations ?? 0),
+ });
+ return run.results;
+}
+
+test.describe('menu 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('menu contract — deliberately violating fixtures', () => {
+ for (const expectation of MENU_PATTERN.expectations) {
+ if (
+ !requiredLayers(expectation).every(layer =>
+ CHROMIUM_OBSERVES.includes(layer),
+ )
+ ) {
+ continue;
+ }
+ for (const fixtureId of MENU_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/menu.fixtures.ts b/internal/a11y-spec/src/patterns/menu.fixtures.ts
new file mode 100644
index 0000000000..3252c4d923
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/menu.fixtures.ts
@@ -0,0 +1,436 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file menu.fixtures.ts
+ * @input Plain HTML menus opened from a button, conforming and deliberately violating
+ * @output MENU_FIXTURES, their subject and relation selectors, and the expectation → violating-fixture map
+ * @position Contract self-test data for menu.jsdom.test.ts and menu.chromium.spec.ts
+ */
+
+import type {MenuStateFacts} from './menu';
+
+export const SUBJECT_SELECTOR = '#menu';
+export const OPENER_SELECTOR = '#opener';
+
+/**
+ * How the fixture menu behaves. One script reads these from the menu's data
+ * attributes, so a violating fixture changes exactly one behavior.
+ */
+interface Behavior {
+ /** Items ArrowDown advances by. */
+ readonly downStep?: 1 | 2;
+ readonly up?: boolean;
+ readonly wrap?: boolean;
+ readonly homeEnd?: boolean;
+ readonly typeahead?: boolean;
+ /** Enter: close and return focus, stay open, or close and drop focus. */
+ readonly enter?: 'return' | 'stay' | 'drop';
+ /** Whether Enter runs the item's action (counted on `window.__menuActivations`). */
+ readonly activate?: boolean;
+ /** Escape: close and return focus, do nothing, or close and drop focus. */
+ readonly escape?: 'return' | 'ignore' | 'drop';
+ /** Tab: close (focus moves on from the opener) or leave the menu open. */
+ readonly tab?: 'close' | 'keep';
+}
+
+/**
+ * The smallest menu behavior: roving focus over enabled items, optional wrap,
+ * Home/End and typeahead, Enter running the item's action (counted on
+ * `window.__menuActivations`) and closing back to the opener, Escape closing
+ * back to the opener, Tab closing and letting the browser move focus on from
+ * the opener. jsdom does not run it; the jsdom lane reads DOM attributes only.
+ */
+const SCRIPT = `<script>(() => {
+ const menu = document.getElementById('menu');
+ const opener = document.getElementById('opener');
+ const d = menu.dataset;
+ const enabled = () => [...menu.querySelectorAll('[data-item]')].filter(
+ item => item.getAttribute('aria-disabled') !== 'true' && !item.hasAttribute('data-disabled'));
+ const close = returnFocus => {
+ if (!returnFocus && menu.contains(document.activeElement)) document.activeElement.blur();
+ menu.hidden = true;
+ opener.setAttribute('aria-expanded', 'false');
+ if (returnFocus) opener.focus();
+ };
+ menu.addEventListener('keydown', event => {
+ const list = enabled();
+ const n = list.length;
+ const i = list.indexOf(document.activeElement);
+ const go = k => { event.preventDefault(); list[k].focus(); };
+ switch (event.key) {
+ case 'ArrowDown': {
+ const k = i + Number(d.downStep);
+ return go(k < n ? k : d.wrap === 'true' ? 0 : n - 1);
+ }
+ case 'ArrowUp':
+ if (d.up !== 'true') return;
+ return go(i > 0 ? i - 1 : d.wrap === 'true' ? n - 1 : 0);
+ case 'Home':
+ if (d.homeEnd === 'true') go(0);
+ return;
+ case 'End':
+ if (d.homeEnd === 'true') go(n - 1);
+ return;
+ case 'Enter':
+ event.preventDefault();
+ if (d.activate === 'true') window.__menuActivations = (window.__menuActivations || 0) + 1;
+ if (d.enter !== 'stay') close(d.enter === 'return');
+ return;
+ case 'Escape':
+ if (d.escape === 'ignore') return;
+ event.preventDefault();
+ close(d.escape === 'return');
+ return;
+ case 'Tab':
+ if (d.tab === 'close') { opener.focus(); menu.hidden = true; opener.setAttribute('aria-expanded', 'false'); }
+ return;
+ }
+ if (d.typeahead === 'true' && event.key.length === 1) {
+ const c = event.key.toLowerCase();
+ for (let j = 1; j <= n; j++) {
+ const item = list[(i + j + n) % n];
+ if (item.textContent.trim().toLowerCase().startsWith(c)) { go((i + j + n) % n); return; }
+ }
+ }
+ });
+})();</script>`;
+
+interface Item {
+ readonly id: string;
+ readonly label: string;
+ readonly role?: string | null;
+ readonly checked?: boolean | null;
+ /** Disabled and exposed as aria-disabled. */
+ readonly disabled?: boolean;
+ /** Disabled for the keyboard script but not exposed. */
+ readonly hiddenDisabled?: boolean;
+}
+
+function itemHtml(item: Item): string {
+ const role = item.role === undefined ? 'menuitem' : item.role;
+ return `<div id="${item.id}" data-item tabindex="-1"${role == null ? '' : ` role="${role}"`}${item.checked == null ? '' : ` aria-checked="${item.checked}"`}${item.disabled ? ' aria-disabled="true"' : ''}${item.hiddenDisabled ? ' data-disabled' : ''}>${item.label}</div>`;
+}
+
+function menuHtml({
+ items,
+ behavior = {},
+ role = 'menu',
+ label = 'Actions',
+}: {
+ items: readonly (Item | {group: string; items: readonly Item[]})[];
+ behavior?: Behavior;
+ role?: string;
+ label?: string | null;
+}): string {
+ const b: Required<Behavior> = {
+ downStep: 1,
+ up: true,
+ wrap: true,
+ homeEnd: true,
+ typeahead: true,
+ enter: 'return',
+ activate: true,
+ escape: 'return',
+ tab: 'close',
+ ...behavior,
+ };
+ const data = `data-down-step="${b.downStep}" data-up="${b.up}" data-wrap="${b.wrap}" data-home-end="${b.homeEnd}" data-typeahead="${b.typeahead}" data-enter="${b.enter}" data-activate="${b.activate}" data-escape="${b.escape}" data-tab="${b.tab}"`;
+ const body = items
+ .map(entry =>
+ 'group' in entry
+ ? `<div role="group" aria-label="${entry.group}">${entry.items.map(itemHtml).join('')}</div>`
+ : itemHtml(entry),
+ )
+ .join('');
+ const opener = `<button type="button" id="opener" aria-haspopup="menu" aria-expanded="true" aria-controls="menu">Actions</button>`;
+ return `${opener}<div id="menu" role="${role}"${label == null ? '' : ` aria-label="${label}"`} tabindex="-1" ${data}>${body}</div>${SCRIPT}`;
+}
+
+export interface MenuFixture {
+ readonly id: string;
+ readonly summary: string;
+ readonly facts: MenuStateFacts;
+ /** Relation name → selector inside the fixture. */
+ readonly relations: Readonly<Record<string, string>>;
+ readonly html: string;
+}
+
+const ACTIONS: readonly Item[] = [
+ {id: 'rename', label: 'Rename'},
+ {id: 'duplicate', label: 'Duplicate'},
+ {id: 'archive', label: 'Archive', disabled: true},
+ {id: 'delete', label: 'Delete'},
+];
+
+const ACTION_RELATIONS = {
+ opener: OPENER_SELECTOR,
+ 'first-item': '#rename',
+ 'second-item': '#duplicate',
+ 'last-item': '#delete',
+ 'disabled-item': '#archive',
+ 'typeahead-target': '#duplicate',
+} as const;
+
+const actionFacts = (
+ overrides: Partial<MenuStateFacts> = {},
+): MenuStateFacts => ({
+ enterTarget: 'first-item',
+ wraps: true,
+ homeEnd: true,
+ disabledItem: true,
+ checked: {},
+ typeaheadCharacter: 'd',
+ ...overrides,
+});
+
+function actions(
+ id: string,
+ summary: string,
+ {
+ items = ACTIONS,
+ behavior,
+ facts = actionFacts(),
+ role,
+ label,
+ }: {
+ items?: readonly Item[];
+ behavior?: Behavior;
+ facts?: MenuStateFacts;
+ role?: string;
+ label?: string | null;
+ } = {},
+): MenuFixture {
+ return {
+ id,
+ summary,
+ facts,
+ relations: ACTION_RELATIONS,
+ html: menuHtml({items, behavior, role, label}),
+ };
+}
+
+function withItem(id: string, change: Partial<Item>): readonly Item[] {
+ return ACTIONS.map(item => (item.id === id ? {...item, ...change} : item));
+}
+
+const SELECTABLE = menuHtml({
+ label: 'View',
+ items: [
+ {id: 'edit', label: 'Edit'},
+ {
+ id: 'archived',
+ label: 'Show archived',
+ role: 'menuitemcheckbox',
+ checked: true,
+ },
+ {
+ group: 'Sort by',
+ items: [
+ {id: 'newest', label: 'Newest', role: 'menuitemradio', checked: true},
+ {id: 'oldest', label: 'Oldest', role: 'menuitemradio', checked: false},
+ ],
+ },
+ ],
+});
+
+const SELECTABLE_RELATIONS = {
+ opener: OPENER_SELECTOR,
+ 'first-item': '#edit',
+ 'second-item': '#archived',
+ 'last-item': '#oldest',
+ 'checkbox-item': '#archived',
+ 'radio-item': '#newest',
+ 'unchecked-radio-item': '#oldest',
+ 'typeahead-target': '#oldest',
+} as const;
+
+const selectableFacts: MenuStateFacts = {
+ enterTarget: 'first-item',
+ wraps: true,
+ homeEnd: true,
+ disabledItem: false,
+ checked: {
+ 'checkbox-item': true,
+ 'radio-item': true,
+ 'unchecked-radio-item': false,
+ },
+ typeaheadCharacter: 'o',
+};
+
+export const MENU_FIXTURES: readonly MenuFixture[] = [
+ actions(
+ 'conforming-actions',
+ 'a named menu of four actions, one disabled, with wrapping arrows, Home/End and typeahead',
+ ),
+ {
+ id: 'conforming-selectable',
+ summary:
+ 'a menu holding an action, a checked checkbox item and a radio group',
+ facts: selectableFacts,
+ relations: SELECTABLE_RELATIONS,
+ html: SELECTABLE,
+ },
+ actions(
+ 'conforming-no-wrap-with-home-end',
+ 'a menu whose arrows stop at either end and which ships Home and End, as the APG then requires',
+ {
+ behavior: {wrap: false},
+ facts: actionFacts({wraps: false}),
+ },
+ ),
+ actions(
+ 'conforming-no-typeahead',
+ 'a menu that ships no typeahead and does not claim it',
+ {
+ behavior: {typeahead: false},
+ facts: actionFacts({typeaheadCharacter: null}),
+ },
+ ),
+ actions('violating-menu-unnamed', 'a menu with no accessible name', {
+ label: null,
+ }),
+ actions(
+ 'violating-menu-as-list',
+ 'the surface exposed as a list instead of a menu',
+ {role: 'list'},
+ ),
+ actions(
+ 'violating-item-without-role',
+ 'the last item rendered as a plain focusable div',
+ {items: withItem('delete', {role: null})},
+ ),
+ actions('violating-item-unnamed', 'the second item has no text', {
+ items: withItem('duplicate', {label: ''}),
+ facts: actionFacts({typeaheadCharacter: null}),
+ }),
+ {
+ id: 'violating-checkbox-without-checked',
+ summary: 'a checked checkbox item that carries no aria-checked',
+ facts: selectableFacts,
+ relations: SELECTABLE_RELATIONS,
+ html: SELECTABLE.replace(
+ 'role="menuitemcheckbox" aria-checked="true"',
+ 'role="menuitemcheckbox"',
+ ),
+ },
+ {
+ id: 'violating-radio-reports-unchecked',
+ summary: 'the chosen radio item reports unchecked',
+ facts: selectableFacts,
+ relations: SELECTABLE_RELATIONS,
+ html: SELECTABLE.replace(
+ 'role="menuitemradio" aria-checked="true"',
+ 'role="menuitemradio" aria-checked="false"',
+ ),
+ },
+ actions(
+ 'violating-disabled-not-exposed',
+ 'a disabled item the keyboard skips but that does not say it is unavailable',
+ {items: withItem('archive', {disabled: false, hiddenDisabled: true})},
+ ),
+ actions(
+ 'violating-arrow-down-skips',
+ 'ArrowDown jumps two items instead of one',
+ {behavior: {downStep: 2}},
+ ),
+ actions('violating-arrow-up-ignored', 'ArrowUp does nothing', {
+ behavior: {up: false},
+ }),
+ actions(
+ 'violating-claims-wrap',
+ 'a menu that claims wrapping but stops at either end',
+ {behavior: {wrap: false}},
+ ),
+ actions(
+ 'violating-home-end-ignored',
+ 'a menu that claims Home and End but ignores them',
+ {behavior: {homeEnd: false}},
+ ),
+ actions(
+ 'violating-no-wrap-no-home-end',
+ 'a menu that neither wraps nor ships Home and End',
+ {
+ behavior: {wrap: false, homeEnd: false},
+ facts: actionFacts({wraps: false, homeEnd: false}),
+ },
+ ),
+ actions(
+ 'violating-typeahead-ignored',
+ 'a menu that claims typeahead but ignores typed characters',
+ {behavior: {typeahead: false}},
+ ),
+ actions(
+ 'violating-enter-keeps-menu-open',
+ 'Enter on an item leaves the menu displayed',
+ {behavior: {enter: 'stay'}},
+ ),
+ actions(
+ 'violating-enter-closes-without-activating',
+ "Enter closes the menu and returns focus but never runs the item's action",
+ {behavior: {activate: false}},
+ ),
+ actions(
+ 'violating-enter-drops-focus',
+ 'Enter closes the menu and leaves focus on the page body',
+ {behavior: {enter: 'drop'}},
+ ),
+ actions('violating-escape-ignored', 'Escape does nothing', {
+ behavior: {escape: 'ignore'},
+ }),
+ actions(
+ 'violating-escape-drops-focus',
+ 'Escape closes the menu and leaves focus on the page body',
+ {behavior: {escape: 'drop'}},
+ ),
+ actions(
+ 'violating-tab-keeps-menu-open',
+ 'Tab moves focus on but leaves the menu displayed',
+ {behavior: {tab: 'keep'}},
+ ),
+];
+
+export function fixture(id: string): MenuFixture {
+ const found = MENU_FIXTURES.find(candidate => candidate.id === id);
+ if (found == null) {
+ throw new Error(`unknown menu fixture "${id}"`);
+ }
+ return found;
+}
+
+export const CONFORMING_FIXTURES: readonly string[] = MENU_FIXTURES.filter(
+ candidate => candidate.id.startsWith('conforming-'),
+).map(candidate => candidate.id);
+
+export const MENU_MUTATIONS: Readonly<Record<string, readonly string[]>> = {
+ 'menu.container.role-and-name': [
+ 'violating-menu-unnamed',
+ 'violating-menu-as-list',
+ ],
+ 'menu.items.roles-and-names': [
+ 'violating-item-without-role',
+ 'violating-item-unnamed',
+ ],
+ 'menu.items.checked-state': [
+ 'violating-checkbox-without-checked',
+ 'violating-radio-reports-unchecked',
+ ],
+ 'menu.items.disabled-state': ['violating-disabled-not-exposed'],
+ 'menu.keys.arrow-down-moves-to-next-item': ['violating-arrow-down-skips'],
+ 'menu.keys.arrow-up-moves-to-previous-item': ['violating-arrow-up-ignored'],
+ 'menu.keys.arrows-wrap': ['violating-claims-wrap'],
+ 'menu.keys.home-and-end': [
+ 'violating-home-end-ignored',
+ 'violating-no-wrap-no-home-end',
+ ],
+ 'menu.keys.typeahead': ['violating-typeahead-ignored'],
+ 'menu.keys.enter-activates-and-closes': [
+ 'violating-enter-keeps-menu-open',
+ 'violating-enter-closes-without-activating',
+ 'violating-enter-drops-focus',
+ ],
+ 'menu.keys.escape-closes-and-returns-focus': [
+ 'violating-escape-ignored',
+ 'violating-escape-drops-focus',
+ ],
+ 'menu.keys.tab-leaves-and-closes': ['violating-tab-keeps-menu-open'],
+};
diff --git a/internal/a11y-spec/src/patterns/menu.jsdom.test.ts b/internal/a11y-spec/src/patterns/menu.jsdom.test.ts
new file mode 100644
index 0000000000..2697099a3e
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/menu.jsdom.test.ts
@@ -0,0 +1,160 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file menu.jsdom.test.ts
+ * @input MENU_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 {MENU_PATTERN} from './menu';
+import {
+ MENU_MUTATIONS,
+ CONFORMING_FIXTURES,
+ SUBJECT_SELECTOR,
+ fixture,
+ type MenuFixture,
+} from './menu.fixtures';
+
+const observableHere = MENU_PATTERN.expectations.filter(expectation =>
+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),
+);
+
+afterEach(() => document.body.replaceChildren());
+
+async function resultsFor(target: MenuFixture) {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const result = await checkAccessibilitySpec({
+ spec: MENU_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ mount: async () => {
+ container.innerHTML = target.html;
+ const subject = container.querySelector(SUBJECT_SELECTOR);
+ if (subject == null) {
+ throw new Error(`fixture "${target.id}" is missing its menu`);
+ }
+ const related: Record<string, Element> = {};
+ for (const [name, selector] of Object.entries(target.relations)) {
+ const element = container.querySelector(selector);
+ if (element == null) {
+ throw new Error(`fixture "${target.id}" is missing ${name}`);
+ }
+ related[name] = element;
+ }
+ return createJsdomHarness({subject, related});
+ },
+ 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('menu contract — completeness', () => {
+ it('answers every completeness dimension', () => {
+ expect(unansweredDimensions(MENU_PATTERN)).toEqual([]);
+ });
+
+ it('gives every expectation at least one deliberately violating fixture', () => {
+ const missing = MENU_PATTERN.expectations
+ .filter(
+ expectation => (MENU_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(
+ MENU_PATTERN.expectations.map(expectation => expectation.id),
+ );
+ expect(Object.keys(MENU_MUTATIONS).filter(id => !ids.has(id))).toEqual([]);
+ });
+
+ it('names every fixture it records a mutation against', () => {
+ for (const fixtures of Object.values(MENU_MUTATIONS)) {
+ for (const id of fixtures) {
+ expect(() => fixture(id)).not.toThrow();
+ }
+ }
+ });
+});
+
+describe('menu 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-actions'));
+ 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 = MENU_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((MENU_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(
+ MENU_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/menu.ts b/internal/a11y-spec/src/patterns/menu.ts
new file mode 100644
index 0000000000..2c2637a9c6
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/menu.ts
@@ -0,0 +1,748 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file menu.ts
+ * @input WCAG 2.2 A/AA success criteria and the APG Menu and Menubar pattern's menu role, item roles, states, and keyboard requirements
+ * @output MENU_PATTERN — the reusable contract a displayed menu binds to: its role and name, its items' roles, names, checked and disabled states, and the keys that move, activate, and leave it
+ * @position Pattern contract; bound by the DropdownMenu pointer menu (`spec:AST-020/FR15`: a menu is one composite control, so it adopts the arrow and Home/End movement it ships; typeahead stays advisory until a current component record names it)
+ */
+
+import {
+ definePattern,
+ type ApgRequirement,
+ type AstryxRecord,
+ type PatternContract,
+ type WcagCriterion,
+} from '../contract';
+import type {Harness, Subject} from '../harness';
+
+const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/menubar/';
+const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';
+
+const WCAG_1_3_1: WcagCriterion = {
+ standard: 'wcag',
+ id: '1.3.1',
+ name: 'Info and Relationships',
+ level: 'A',
+ url: `${UNDERSTANDING}/info-and-relationships.html`,
+};
+const WCAG_2_1_1: WcagCriterion = {
+ standard: 'wcag',
+ id: '2.1.1',
+ name: 'Keyboard',
+ level: 'A',
+ url: `${UNDERSTANDING}/keyboard.html`,
+};
+const WCAG_2_1_2: WcagCriterion = {
+ standard: 'wcag',
+ id: '2.1.2',
+ name: 'No Keyboard Trap',
+ level: 'A',
+ url: `${UNDERSTANDING}/no-keyboard-trap.html`,
+};
+const WCAG_2_4_3: WcagCriterion = {
+ standard: 'wcag',
+ id: '2.4.3',
+ name: 'Focus Order',
+ level: 'A',
+ url: `${UNDERSTANDING}/focus-order.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 ROLES = `${APG_URL}#wai-ariaroles,states,andproperties`;
+const KEYS = `${APG_URL}#keyboardinteraction`;
+
+const APG_MENU_ROLE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'The element serving as the menu has a role of either menu or menubar.',
+ url: ROLES,
+};
+const APG_MENU_LABEL: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'An element with role menu either has: aria-labelledby set to a value that refers to the menuitem or button that controls its display. A label provided by aria-label.',
+ url: ROLES,
+};
+const APG_ITEM_ROLES: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'The items contained in a menu are child elements of the containing menu or menubar and have any of the following roles: menuitem, menuitemcheckbox, menuitemradio.',
+ url: ROLES,
+};
+const APG_CHECKED: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'When a menuitemcheckbox or menuitemradio is checked, aria-checked is set to true.',
+ url: ROLES,
+};
+const APG_DISABLED: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement: 'When a menu item is disabled, aria-disabled is set to true.',
+ url: ROLES,
+};
+const APG_DOWN: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'Down Arrow: When focus is in a menu, moves focus to the next item, optionally wrapping from the last to the first.',
+ url: KEYS,
+};
+const APG_UP: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'Up Arrow: When focus is in a menu, moves focus to the previous item, optionally wrapping from the first to the last.',
+ url: KEYS,
+};
+const APG_HOME_END: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'Home: If arrow key wrapping is not supported, moves focus to the first item in the current menu or menubar. End: If arrow key wrapping is not supported, moves focus to the last item in the current menu or menubar.',
+ url: KEYS,
+};
+const APG_TYPEAHEAD: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'Any key that corresponds to a printable character (Optional): Move focus to the next item in the current menu whose label begins with that printable character.',
+ url: KEYS,
+};
+const APG_ENTER: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'Enter: When focus is on a menuitem that has a submenu, opens the submenu and places focus on its first item. Otherwise, activates the item and closes the menu.',
+ url: KEYS,
+};
+const APG_ESCAPE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'Escape: Close the menu that contains focus and return focus to the element or context, e.g., menu button or parent menuitem, from which the menu was opened.',
+ url: KEYS,
+};
+const APG_TAB: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'menubar',
+ requirement:
+ 'Tab and Shift + Tab: When focus is on a menuitem in a menu or menubar, move focus out of the menu or menubar, and close all menus and submenus.',
+ url: KEYS,
+};
+
+/**
+ * The current Astryx adoption rule. A menu already plays the menu role and is
+ * one composite control, so it takes the pattern's required parts and the
+ * arrow and Home/End movement it ships between its items. Typeahead is an
+ * extra the rule does not name, so it is advisory until the owning component
+ * record names it (AST-020 FR9).
+ */
+const AST_020_FR15: AstryxRecord = {
+ standard: 'astryx',
+ id: 'spec:AST-020',
+ clause: 'FR15',
+ url: 'https://github.com/facebook/astryx/blob/878fad9d7ac23cd3f4c5def64595abd770bb01a3/docs/specs/AST-020/spec.md#L83-L92',
+ requirement:
+ "Where a component part already plays an APG pattern's role, Astryx adopts that pattern's required parts for it: the role, the accessible name, the state and relationship properties, and activation by Tab plus Enter or Space. The pattern's optional keyboard extras — arrow-key movement between parts, Home and End — are adopted only where the component already acts as one composite control.",
+};
+
+/**
+ * What a binding knows about one displayed menu. The subject is the element
+ * with role menu. Relations: `opener` (the control the menu was opened from),
+ * `first-item`, `second-item` and `last-item` (the first, second and last
+ * enabled items, in the order the arrow keys visit them), `disabled-item`
+ * when `disabledItem`, `typeahead-target` when `typeaheadCharacter`, and one
+ * relation per key of `checked`. The binding also supplies `activations`, the
+ * number of times an item's action has run.
+ */
+export interface MenuStateFacts {
+ /** The item relation Enter is pressed on: `first-item` or another item relation, such as a checkable row. */
+ readonly enterTarget: string;
+ /** Whether ArrowDown on the last item wraps to the first, and ArrowUp on the first to the last. */
+ readonly wraps: boolean;
+ /** Whether Home and End move to the first and last items. */
+ readonly homeEnd: boolean;
+ /** Whether the menu holds a disabled item, named by the `disabled-item` relation. */
+ readonly disabledItem: boolean;
+ /** Checkable items by relation name, and whether each is meant to be checked. */
+ readonly checked: Readonly<Record<string, boolean>>;
+ /**
+ * A printable character that, typed with focus on the menu, moves focus to
+ * the `typeahead-target` item; null when the binding ships no typeahead.
+ */
+ readonly typeaheadCharacter: string | null;
+}
+
+const ITEM_ROLES: ReadonlySet<string> = new Set([
+ 'menuitem',
+ 'menuitemcheckbox',
+ 'menuitemradio',
+]);
+
+const ALWAYS = {
+ condition: 'the binding designates a displayed menu',
+ test: () => true,
+};
+
+function itemRelations(facts: MenuStateFacts): readonly string[] {
+ return [
+ 'first-item',
+ 'second-item',
+ 'last-item',
+ ...(facts.disabledItem ? ['disabled-item'] : []),
+ ...Object.keys(facts.checked),
+ ];
+}
+
+async function focusOrFail(item: Subject, name: string): Promise<void> {
+ await item.focus();
+ if (!(await item.isFocused())) {
+ throw new Error(`the ${name} did not take focus`);
+ }
+}
+
+async function expectFocused(
+ item: Subject,
+ name: string,
+ after: string,
+): Promise<void> {
+ if (!(await item.isFocused())) {
+ throw new Error(`${after} did not move focus to the ${name}`);
+ }
+}
+
+async function expectStillOpen(menu: Subject, after: string): Promise<void> {
+ if (!(await menu.isVisible())) {
+ throw new Error(`${after} closed the menu`);
+ }
+}
+
+/**
+ * Presses one key on a focused item and checks the menu closed and focus went
+ * back to the control that opened it. `activate` also requires the item's
+ * action to have run exactly once.
+ */
+async function closesAndReturnsFocus(
+ harness: Harness,
+ menu: Subject,
+ key: 'Enter' | 'Escape',
+ target: string,
+ activations?: () => Promise<number>,
+): Promise<void> {
+ const opener = await harness.related('opener');
+ await focusOrFail(await harness.related(target), target);
+ const before = activations == null ? 0 : await activations();
+ await harness.press(key);
+ if (activations != null && (await activations()) !== before + 1) {
+ throw new Error(`${key} on the ${target} did not run its action once`);
+ }
+ if (await menu.isVisible()) {
+ throw new Error(`${key} on an item left the menu displayed`);
+ }
+ if (!(await opener.isFocused())) {
+ throw new Error(
+ `${key} closed the menu without returning focus to the control that opened it`,
+ );
+ }
+}
+
+export const MENU_PATTERN: PatternContract<MenuStateFacts> =
+ definePattern<MenuStateFacts>({
+ pattern: 'menu',
+ url: APG_URL,
+ scope:
+ "A displayed menu's role and name; its items' roles, names, checked and disabled states; ArrowDown/ArrowUp movement (and its wrap) and Home/End where the binding ships them, typeahead as advisory; Enter running the item's action and closing; Escape closing; Tab leaving and closing; focus returning to the opener.",
+ expectations: [
+ {
+ id: 'menu.container.role-and-name',
+ outcome:
+ 'The browser exposes the open surface as a named menu, so a user knows they are choosing from a set of commands and which set it is.',
+ sources: [WCAG_4_1_2, APG_MENU_ROLE, APG_MENU_LABEL],
+ 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 !== 'menu') {
+ throw new Error(
+ `the browser exposes this surface as ${role == null ? 'no role' : `"${role}"`}, not as a menu`,
+ );
+ }
+ if (!name || name.trim() === '') {
+ throw new Error(
+ 'the browser computes no accessible name for the menu',
+ );
+ }
+ },
+ },
+ {
+ id: 'menu.items.roles-and-names',
+ outcome:
+ 'Every item is exposed inside the menu as a named menu item, checkbox item or radio item, so a user hears each choice and its kind.',
+ sources: [WCAG_4_1_2, WCAG_1_3_1, APG_ITEM_ROLES],
+ covers: [
+ '4.1.2-name-role-value',
+ '1.3.1-info-and-relationships',
+ 'apg-interaction',
+ ],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ for (const relation of itemRelations(facts)) {
+ const item = await harness.related(relation);
+ const {role, name} = await item.computed();
+ if (role == null || !ITEM_ROLES.has(role)) {
+ throw new Error(
+ `the ${relation} is exposed as ${role == null ? 'no role' : `"${role}"`}, not as a menu item`,
+ );
+ }
+ if (!name || name.trim() === '') {
+ throw new Error(`the ${relation} has no accessible name`);
+ }
+ if (!(await harness.containsSemantically(subject, item))) {
+ throw new Error(`the ${relation} is not exposed inside the menu`);
+ }
+ }
+ },
+ },
+ {
+ id: 'menu.items.checked-state',
+ outcome:
+ 'A checkbox or radio item reports whether it is checked, in both states.',
+ sources: [WCAG_4_1_2, APG_CHECKED, AST_020_FR15],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the menu holds checkable items',
+ test: facts => Object.keys(facts.checked).length > 0,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({harness, facts}) => {
+ for (const [relation, expected] of Object.entries(facts.checked)) {
+ const item = await harness.related(relation);
+ const value = await item.attribute('aria-checked');
+ if (value !== String(expected)) {
+ throw new Error(
+ `the ${relation} is meant to be ${expected ? 'checked' : 'unchecked'} but aria-checked is ${value ?? 'absent'}`,
+ );
+ }
+ }
+ },
+ },
+ {
+ id: 'menu.items.disabled-state',
+ outcome:
+ 'A disabled item says it is unavailable, so a user does not mistake it for a choice they can make.',
+ sources: [WCAG_4_1_2, APG_DISABLED, AST_020_FR15],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the menu holds a disabled item',
+ test: facts => facts.disabledItem,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({harness}) => {
+ const item = await harness.related('disabled-item');
+ const value = await item.attribute('aria-disabled');
+ if (value !== 'true') {
+ throw new Error(
+ `the disabled item's aria-disabled is ${value ?? 'absent'}, not true`,
+ );
+ }
+ },
+ },
+ {
+ id: 'menu.keys.arrow-down-moves-to-next-item',
+ outcome:
+ 'ArrowDown moves focus from one item to the next enabled item and keeps the menu open.',
+ sources: [WCAG_2_1_1, APG_DOWN, AST_020_FR15],
+ covers: ['2.1.1-keyboard', '2.4.3-focus-order', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ await focusOrFail(await harness.related('first-item'), 'first item');
+ await harness.press('ArrowDown');
+ await expectFocused(
+ await harness.related('second-item'),
+ 'second item',
+ 'ArrowDown on the first item',
+ );
+ await expectStillOpen(subject, 'ArrowDown');
+ },
+ },
+ {
+ id: 'menu.keys.arrow-up-moves-to-previous-item',
+ outcome:
+ 'ArrowUp moves focus from one item to the previous enabled item and keeps the menu open.',
+ sources: [WCAG_2_1_1, APG_UP, AST_020_FR15],
+ covers: ['2.1.1-keyboard', '2.4.3-focus-order', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ await focusOrFail(
+ await harness.related('second-item'),
+ 'second item',
+ );
+ await harness.press('ArrowUp');
+ await expectFocused(
+ await harness.related('first-item'),
+ 'first item',
+ 'ArrowUp on the second item',
+ );
+ await expectStillOpen(subject, 'ArrowUp');
+ },
+ },
+ {
+ id: 'menu.keys.arrows-wrap',
+ outcome:
+ 'ArrowDown on the last item moves to the first, and ArrowUp on the first moves to the last.',
+ sources: [WCAG_2_1_1, APG_DOWN, APG_UP, AST_020_FR15],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the binding ships arrow-key wrapping',
+ test: facts => facts.wraps,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness}) => {
+ const first = await harness.related('first-item');
+ const last = await harness.related('last-item');
+ await focusOrFail(last, 'last item');
+ await harness.press('ArrowDown');
+ await expectFocused(
+ first,
+ 'first item',
+ 'ArrowDown on the last item',
+ );
+ await harness.press('ArrowUp');
+ await expectFocused(last, 'last item', 'ArrowUp on the first item');
+ },
+ },
+ {
+ id: 'menu.keys.home-and-end',
+ outcome:
+ 'Home moves focus to the first enabled item and End to the last, keeping the menu open.',
+ sources: [WCAG_2_1_1, APG_HOME_END, AST_020_FR15],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition:
+ 'the binding ships Home and End, or does not wrap (the APG then requires them)',
+ test: facts => facts.homeEnd || !facts.wraps,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const first = await harness.related('first-item');
+ const last = await harness.related('last-item');
+ await focusOrFail(
+ await harness.related('second-item'),
+ 'second item',
+ );
+ await harness.press('End');
+ await expectFocused(last, 'last item', 'End');
+ await harness.press('Home');
+ await expectFocused(first, 'first item', 'Home');
+ await expectStillOpen(subject, 'Home or End');
+ },
+ },
+ {
+ id: 'menu.keys.typeahead',
+ outcome:
+ 'With focus in the menu, typing a character moves focus to the next item whose label starts with it.',
+ sources: [APG_TYPEAHEAD],
+ wcagOutcome:
+ 'Supports WCAG 2.2 2.1.1 by keeping the shipped typeahead keyboard-operable; arrow keys already reach every item, so this row is advisory until the binding record adopts typeahead as current.',
+ covers: ['apg-interaction'],
+ appliesWhen: {
+ condition: 'the binding names a typeahead character and its target',
+ test: facts => facts.typeaheadCharacter != null,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'advisory',
+ advisoryBecause:
+ "Typeahead is optional in the APG and is not one of the composite-control extras AST-020 FR15 names; it becomes required once the binding's component record names it as an adopted exception and that record is current (AST-020 FR9).",
+ run: async ({harness, subject, facts}) => {
+ const character = facts.typeaheadCharacter ?? '';
+ await harness.typeText(subject, character);
+ await expectFocused(
+ await harness.related('typeahead-target'),
+ 'item it names',
+ `typing "${character}"`,
+ );
+ await expectStillOpen(subject, `typing "${character}"`);
+ },
+ },
+ {
+ id: 'menu.keys.enter-activates-and-closes',
+ outcome:
+ 'Enter on an item runs its action once, closes the menu, and returns focus to the control that opened it, so the user is not stranded on the page.',
+ sources: [WCAG_2_1_1, APG_ENTER, WCAG_2_4_3, AST_020_FR15],
+ covers: ['2.1.1-keyboard', '2.4.3-focus-order', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts, activations}) => {
+ await closesAndReturnsFocus(
+ harness,
+ subject,
+ 'Enter',
+ facts.enterTarget,
+ activations,
+ );
+ },
+ },
+ {
+ id: 'menu.keys.escape-closes-and-returns-focus',
+ outcome:
+ 'Escape closes the menu and returns focus to the control that opened it.',
+ sources: [WCAG_2_1_1, APG_ESCAPE, WCAG_2_4_3],
+ covers: ['2.1.1-keyboard', '2.4.3-focus-order', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ await closesAndReturnsFocus(harness, subject, 'Escape', 'first-item');
+ },
+ },
+ {
+ id: 'menu.keys.tab-leaves-and-closes',
+ outcome:
+ 'Tab on an item moves focus out of the menu and closes it, so the keyboard never leaves an open menu behind.',
+ sources: [WCAG_2_1_2, APG_TAB, AST_020_FR15],
+ covers: ['2.1.2-no-keyboard-trap', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ await focusOrFail(await harness.related('first-item'), 'first item');
+ await harness.press('Tab');
+ if (await subject.containsFocus()) {
+ throw new Error('Tab on an item left focus inside the menu');
+ }
+ if (await subject.isVisible()) {
+ throw new Error('Tab moved focus out but left the menu displayed');
+ }
+ },
+ },
+ ],
+ exemptions: {
+ '1.1.1-non-text-content': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ "the component's decorative-icon tests and the repository axe audit, `pnpm a11y:audit`",
+ reason:
+ 'Item icons, check marks and submenu chevrons are binding-specific composition; this contract reads the item names, not their graphics.',
+ },
+ '1.3.1-info-and-relationships': {
+ owner: 'the binding component',
+ verifiedBy:
+ "the binding's group, heading and separator tests (DropdownMenu.test.tsx group suite)",
+ reason:
+ 'This contract encodes that items are menu items inside the menu. Groups, group names, headings and separators inside the menu are binding structure.',
+ coversRemainderOnly: true,
+ },
+ '1.3.2-meaningful-sequence': {
+ owner: 'the binding component',
+ verifiedBy:
+ "the binding's DOM-order tests; this contract's arrow rows prove the keyboard order the binding declares",
+ reason:
+ 'The reading order of the items is the order the binding renders them in.',
+ },
+ '1.3.5-identify-input-purpose': {
+ owner: 'the composing form and caller content',
+ verifiedBy:
+ 'form integration review of any user-information input beside the menu',
+ reason: 'A menu collects no 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:
+ 'How focus, checked and disabled items look is rendered presentation, not menu 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:
+ 'Item text contrast depends on the resolved colors of 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 focus indicator and check marks',
+ reason:
+ 'The focus highlight and check-mark contrast are paint outcomes owned by the binding and theme.',
+ },
+ '2.1.1-keyboard': {
+ owner: 'the binding component',
+ verifiedBy:
+ "the binding's submenu, PageUp/PageDown and Space activation tests (DropdownMenu.test.tsx and DropdownMenuSubMenu.test.tsx keyboard suites)",
+ reason:
+ 'This contract encodes ArrowDown/ArrowUp, Home/End, Enter, Escape and Tab, and reports typeahead as advisory. Submenu opening and closing, PageUp/PageDown, and Space (optional in the APG) remain with the binding until a submenu contract adopts them.',
+ coversRemainderOnly: true,
+ },
+ '2.1.2-no-keyboard-trap': {
+ owner: 'the composing page',
+ verifiedBy: 'page-level keyboard review',
+ reason:
+ 'This contract proves Tab leaves and closes the menu. Where focus goes next is the composition.',
+ coversRemainderOnly: true,
+ },
+ '2.4.2-page-titled': {
+ owner: 'the page',
+ verifiedBy: 'page-level review',
+ reason: 'A menu rendered in isolation owns no document title.',
+ },
+ '2.4.3-focus-order': {
+ owner: 'the menu-button pattern and the composing page',
+ verifiedBy:
+ 'MENU_BUTTON_PATTERN, which proves focus lands on the first or last item when the menu opens, plus page-level focus-order review',
+ reason:
+ 'This contract proves movement inside the menu and the return to the opener. Where focus lands on open is the opening control; the opener among surrounding controls is the composition.',
+ coversRemainderOnly: true,
+ },
+ '2.4.4-link-purpose': {
+ owner: 'the link pattern and caller content',
+ verifiedBy:
+ "the binding's link-row tests (component:DropdownMenu FR10) and content review of row labels",
+ reason:
+ 'A row that navigates is a link the caller labels; this contract reads it as a menu item.',
+ },
+ '2.4.6-headings-and-labels': {
+ owner: 'caller content',
+ verifiedBy: 'content review of menu and item labels',
+ reason:
+ 'Whether a label describes its command is a caller-content judgement; this contract checks that a name exists.',
+ },
+ '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: 'The focused-item highlight is a paint outcome.',
+ },
+ '2.4.11-focus-not-obscured': {
+ owner: 'the binding component and overlay system',
+ verifiedBy:
+ "the binding's scroll-into-view tests and overlay visibility review",
+ reason:
+ 'Whether a focused item stays in view in a scrolling menu depends on the rendered geometry.',
+ },
+ '2.5.2-pointer-cancellation': {
+ owner: 'the binding component',
+ verifiedBy:
+ "the binding's press-model browser spec (DropdownMenu MenuPress.a11y.chromium.spec.ts)",
+ reason:
+ 'How a pointer press on an item is completed or taken back is the binding press model, outside the menu semantics this contract reads.',
+ },
+ '2.5.3-label-in-name': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ "the binding's item-name tests and content review of visible labels",
+ reason:
+ 'An item names itself from its visible label; extra description text is binding composition.',
+ },
+ '2.5.8-target-size': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ "the repository axe audit's target-size rule over the item rows",
+ reason: 'Row height and spacing are binding geometry.',
+ },
+ '3.1.1-language-of-page': {
+ owner: 'the page',
+ verifiedBy: 'page-level language review',
+ reason: 'A menu rendered in isolation owns no document language.',
+ },
+ '3.2.2-on-input': {
+ owner: 'the caller',
+ verifiedBy: 'integration review of what each item does when chosen',
+ reason:
+ 'Choosing an item is an explicit activation, not a change of setting; what the command then does is caller behavior.',
+ },
+ '3.2.4-consistent-identification': {
+ owner: 'the design system and caller content',
+ verifiedBy:
+ 'this shared contract across bindings plus content review of repeated item labels',
+ reason:
+ 'Consistency is a property of the set of repeated commands, not one menu.',
+ },
+ '3.3.1-error-identification': {
+ owner: 'the composing form',
+ verifiedBy: 'form-level error-state review',
+ reason: 'The menu 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: 'A menu collects no input that needs form instructions.',
+ },
+ '4.1.2-name-role-value': {
+ owner: 'the binding component',
+ verifiedBy:
+ "the binding's submenu parent-item tests (aria-haspopup and aria-expanded on a parent item, DropdownMenuSubMenu.test.tsx)",
+ reason:
+ 'This contract encodes the menu and item roles and names and the checked and disabled states. A parent item’s submenu state stays with the binding until a submenu contract adopts it.',
+ 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 output',
+ reason:
+ 'Opening, moving through or closing a menu is not a status message, and this pattern makes no announcement claim.',
+ },
+ 'apg-interaction': {
+ owner: 'the binding component and the menu-button pattern',
+ verifiedBy:
+ "MENU_BUTTON_PATTERN for the opening control, plus the binding's submenu tests (DropdownMenuSubMenu.test.tsx)",
+ reason:
+ 'This contract encodes the menu surface. The control that opens it is the menu-button pattern; submenus (Right/Left Arrow, a parent item’s state) stay with the binding until a submenu contract adopts them; menubar movement has no Astryx adopter; the APG note that disabled items stay focusable is not one of the required parts AST-020 FR15 adopts, so the binding’s own focus order decides it.',
+ 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.',
+ },
+ 'reduced-motion': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ "the component's reduced-motion source tests and rendered motion review",
+ reason: 'Menu entry motion is binding paint over time.',
+ },
+ 'at-facing-strings': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ 'the repository i18n catalog check and source review of authored labels',
+ reason:
+ 'The menu contract introduces no string; the menu and item names come from the binding or caller.',
+ },
+ },
+ });
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 2479823d54..0d7e81ec93 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -1352,18 +1352,6 @@ describe('DropdownMenu items', () => {
);
expect(handleClick).not.toHaveBeenCalled();
});
-
- it('has aria-disabled when disabled', () => {
- render(
- <DropdownMenu
- button={{label: 'Actions'}}
- items={[{label: 'Edit', isDisabled: true}]}
- />,
- );
- expect(
- screen.getByRole('menuitem', {name: 'Edit', hidden: true}),
- ).toHaveAttribute('aria-disabled', 'true');
- });
});
describe('DropdownMenu sections', () => {
diff --git a/packages/core/src/DropdownMenu/__tests__/Menu.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/Menu.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..00228a5870
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/Menu.a11y.chromium.spec.ts
@@ -0,0 +1,145 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Menu.a11y.chromium.spec.ts
+ * @input Built menu stories and MENU_PATTERN in real Chromium
+ * @output Browser evidence for every menu expectation across the DropdownMenu pointer-menu states
+ * @position Chromium lane of the DropdownMenu menu-surface binding
+ */
+
+import {
+ expect,
+ test,
+ type CDPSession,
+ type Locator,
+ type Page,
+} from '@playwright/test';
+import {
+ MENU_PATTERN,
+ blockingResults,
+ checkAccessibilitySpec,
+ formatFailures,
+ neverExercised,
+ summarize,
+ unmatchedKnownFailures,
+ 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 {MENU_KNOWN_FAILURES} from './Menu.a11y.known-failures';
+import {MENU_BINDING_STATES, type MenuBindingState} from './Menu.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`;
+}
+
+/**
+ * Opens the menu the way a keyboard user does — Enter on the focused trigger —
+ * and waits until focus is on the first item, so every expectation starts from
+ * a displayed menu with focus inside it.
+ */
+async function mountState(
+ page: Page,
+ state: MenuBindingState,
+): Promise<{subject: Locator; related: Record<string, Locator>}> {
+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});
+ await holdMotionStill(page);
+ const opener = page
+ .locator('#storybook-root')
+ .getByRole('button', {name: state.label});
+ await opener.focus();
+ await page.keyboard.press('Enter');
+ const id = await opener.getAttribute('aria-controls');
+ if (id == null) {
+ throw new Error(`menu state "${state.id}" has no aria-controls`);
+ }
+ const related: Record<string, Locator> = {opener};
+ for (const [relation, [role, name]] of Object.entries(state.items)) {
+ related[relation] = page.getByRole(
+ role as Parameters<Page['getByRole']>[0],
+ {
+ name,
+ exact: true,
+ includeHidden: true,
+ },
+ );
+ }
+ await expect(related['first-item']).toBeFocused();
+ return {subject: page.locator(`[id="${id}"]`), related};
+}
+
+/**
+ * How many item actions the story's handlers have run. The story renders the
+ * count as an attribute, so this reads a fact the page shows rather than
+ * instrumenting it from the test.
+ */
+async function activationsOn(page: Page): Promise<number> {
+ const raw = await page
+ .locator('[data-a11y-activations]')
+ .first()
+ .getAttribute('data-a11y-activations');
+ return Number(raw ?? '0');
+}
+
+async function runState(
+ page: Page,
+ cdp: CDPSession,
+ state: MenuBindingState,
+): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: MENU_PATTERN,
+ binding: 'DropdownMenu.menu',
+ state: state.id,
+ facts: state.facts,
+ knownFailures: MENU_KNOWN_FAILURES,
+ mount: async () => {
+ const {subject, related} = await mountState(page, state);
+ return createChromiumHarness({page, cdp, subject, related});
+ },
+ activations: async () => activationsOn(page),
+ });
+}
+
+test('every menu expectation is exercised by a DropdownMenu state', async ({
+ page,
+}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const results: BindingResult[] = [];
+ for (const state of MENU_BINDING_STATES) {
+ results.push(await runState(page, cdp, state));
+ }
+ expect(neverExercised(results)).toEqual([]);
+ expect(unmatchedKnownFailures(MENU_KNOWN_FAILURES, results)).toEqual([]);
+});
+
+for (const state of MENU_BINDING_STATES) {
+ test(`DropdownMenu.menu [${state.id}] — ${state.summary}`, async ({page}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const result = await runState(page, cdp, state);
+ const report = summarize(MENU_PATTERN, [result]);
+ // Required rows block (AST-020 FR9); advisory rows and exact known
+ // failures report.
+ expect(formatFailures(blockingResults([result]))).toBe('');
+ expect(report.unrunLayers).toEqual([]);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+}
diff --git a/packages/core/src/DropdownMenu/__tests__/Menu.a11y.known-failures.ts b/packages/core/src/DropdownMenu/__tests__/Menu.a11y.known-failures.ts
new file mode 100644
index 0000000000..e9ce377801
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/Menu.a11y.known-failures.ts
@@ -0,0 +1,26 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Menu.a11y.known-failures.ts
+ * @input The exact menu-contract failures the shipped DropdownMenu produces today
+ * @output MENU_KNOWN_FAILURES — records both lanes reconcile against, so a fix shows up as an unexpected pass and any other failure stays a failure
+ * @position Known-failure ledger for the DropdownMenu menu-surface binding
+ */
+
+import type {KnownFailure} from '@astryxdesign/a11y-spec';
+
+export const MENU_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [
+ {
+ expectation: 'menu.keys.enter-activates-and-closes',
+ binding: 'DropdownMenu.menu',
+ state: 'dropdown-selectable-checkbox-row',
+ evidenceLayer: 'real-browser',
+ failureEquals: 'Enter on an item left the menu displayed',
+ standardsReference:
+ 'APG Menu and Menubar, Enter: "Otherwise, activates the item and closes the menu" (adopted as a required part by spec:AST-020 FR15); WCAG 2.2 2.1.1 Keyboard',
+ userImpact:
+ 'A keyboard user who presses Enter on a checkbox row toggles it but stays in the open menu, where the pattern says Enter chooses and closes; Escape or Tab is needed to get back to the page.',
+ reason:
+ 'DropdownMenuCheckboxItem keeps the menu open by default (hasCloseOnSelect is false), shipped as released behavior under component:DropdownMenu FR16. Whether Enter on a checkbox row closes the menu, or the component record names staying open as an exception, is a behavior decision for the component owner; this test-only binding records it and changes nothing.',
+ },
+];
diff --git a/packages/core/src/DropdownMenu/__tests__/Menu.a11y.renders.tsx b/packages/core/src/DropdownMenu/__tests__/Menu.a11y.renders.tsx
new file mode 100644
index 0000000000..d494fe11a8
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/Menu.a11y.renders.tsx
@@ -0,0 +1,65 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file Menu.a11y.renders.tsx
+ * @input One menu binding state from Menu.a11y.states.ts
+ * @output The React tree every lane renders for that state (the jsdom test directly, the story through Storybook), publishing how many item actions have run as `data-a11y-activations`
+ * @position Shared fixture for the DropdownMenu menu-surface binding
+ */
+
+import {useState, type ReactElement} from 'react';
+import {DropdownMenu} from '../DropdownMenu';
+import {DropdownMenuItem} from '../DropdownMenuItem';
+import {DropdownMenuCheckboxItem} from '../DropdownMenuCheckboxItem';
+import {DropdownMenuRadioGroup} from '../DropdownMenuRadioGroup';
+import {DropdownMenuRadioItem} from '../DropdownMenuRadioItem';
+import {MENU_ACTION_ITEMS, type MenuBindingState} from './Menu.a11y.states';
+
+function MenuState({
+ content,
+ label,
+}: Pick<MenuBindingState, 'content' | 'label'>): ReactElement {
+ // An item's action leaves no trace on the menu, so every handler counts
+ // here and the count is rendered for the browser lane to read.
+ const [activations, setActivations] = useState(0);
+ const activate = () => setActivations(count => count + 1);
+ const menu =
+ content === 'actions' ? (
+ <DropdownMenu
+ button={{label}}
+ items={MENU_ACTION_ITEMS.map(item => ({...item, onClick: activate}))}
+ presentation="popover"
+ />
+ ) : (
+ <DropdownMenu button={{label}} presentation="popover">
+ <DropdownMenuItem label="Edit" onClick={activate} />
+ {/* No hasCloseOnSelect: the row keeps the menu open by default. */}
+ <DropdownMenuCheckboxItem
+ label="Show archived"
+ value={true}
+ onChange={activate}
+ />
+ <DropdownMenuRadioGroup
+ value="newest"
+ onChange={activate}
+ label="Sort by">
+ <DropdownMenuRadioItem value="newest" label="Newest" />
+ <DropdownMenuRadioItem value="oldest" label="Oldest" />
+ </DropdownMenuRadioGroup>
+ </DropdownMenu>
+ );
+ return (
+ <div data-a11y-activations={activations}>
+ {menu}
+ <button type="button">After the menu</button>
+ </div>
+ );
+}
+
+export function renderMenuState(
+ state: Pick<MenuBindingState, 'content' | 'label'>,
+): ReactElement {
+ return <MenuState content={state.content} label={state.label} />;
+}
diff --git a/packages/core/src/DropdownMenu/__tests__/Menu.a11y.states.ts b/packages/core/src/DropdownMenu/__tests__/Menu.a11y.states.ts
new file mode 100644
index 0000000000..a5363e7a9d
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/Menu.a11y.states.ts
@@ -0,0 +1,138 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Menu.a11y.states.ts
+ * @input The DropdownMenu pointer menu's representative open states and the facts MENU_PATTERN reads
+ * @output MENU_BINDING_STATES and the explicit ownership exclusions for this binding
+ * @position Binding inventory shared by the jsdom test and the Chromium spec (component:DropdownMenu menu surface under spec:AST-020 FR15)
+ */
+
+import type {MenuStateFacts} from '@astryxdesign/a11y-spec';
+
+export interface MenuBindingState {
+ readonly id: string;
+ readonly summary: string;
+ readonly storyId: string;
+ /** Which menu content the state renders. */
+ readonly content: 'actions' | 'selectable';
+ /** The trigger's accessible name; the menu is named by it. */
+ readonly label: string;
+ /** Relation name → [role, accessible name] of the item it designates. */
+ readonly items: Readonly<Record<string, readonly [string, string]>>;
+ readonly facts: MenuStateFacts;
+}
+
+export const MENU_ACTION_ITEMS = [
+ {label: 'Rename'},
+ {label: 'Duplicate'},
+ {label: 'Archive', isDisabled: true},
+ {label: 'Delete'},
+] as const;
+
+const story = (id: string) => `a11y-menu--${id}`;
+
+export const MENU_BINDING_STATES = [
+ {
+ id: 'dropdown-actions',
+ summary:
+ 'a DropdownMenu of four actions, one disabled, opened from its Button trigger',
+ storyId: story('dropdown-actions'),
+ content: 'actions',
+ label: 'Actions',
+ items: {
+ 'first-item': ['menuitem', 'Rename'],
+ 'second-item': ['menuitem', 'Duplicate'],
+ 'last-item': ['menuitem', 'Delete'],
+ 'disabled-item': ['menuitem', 'Archive'],
+ 'typeahead-target': ['menuitem', 'Duplicate'],
+ },
+ facts: {
+ enterTarget: 'first-item',
+ wraps: true,
+ homeEnd: true,
+ disabledItem: true,
+ checked: {},
+ typeaheadCharacter: 'd',
+ },
+ },
+ {
+ id: 'dropdown-selectable',
+ summary:
+ 'a DropdownMenu holding an action, a checked checkbox row and a titled radio group',
+ storyId: story('dropdown-selectable'),
+ content: 'selectable',
+ label: 'View',
+ items: {
+ 'first-item': ['menuitem', 'Edit'],
+ 'second-item': ['menuitemcheckbox', 'Show archived'],
+ 'last-item': ['menuitemradio', 'Oldest'],
+ 'checkbox-item': ['menuitemcheckbox', 'Show archived'],
+ 'radio-item': ['menuitemradio', 'Newest'],
+ 'unchecked-radio-item': ['menuitemradio', 'Oldest'],
+ 'typeahead-target': ['menuitemradio', 'Oldest'],
+ },
+ facts: {
+ enterTarget: 'first-item',
+ wraps: true,
+ homeEnd: true,
+ disabledItem: false,
+ checked: {
+ 'checkbox-item': true,
+ 'radio-item': true,
+ 'unchecked-radio-item': false,
+ },
+ typeaheadCharacter: 'o',
+ },
+ },
+ {
+ id: 'dropdown-selectable-checkbox-row',
+ summary:
+ 'the same selectable menu with Enter pressed on its checkbox row, which keeps the menu open (DropdownMenuCheckboxItem hasCloseOnSelect defaults to false)',
+ storyId: story('dropdown-selectable-checkbox-row'),
+ content: 'selectable',
+ label: 'View',
+ items: {
+ 'first-item': ['menuitem', 'Edit'],
+ 'second-item': ['menuitemcheckbox', 'Show archived'],
+ 'last-item': ['menuitemradio', 'Oldest'],
+ 'checkbox-item': ['menuitemcheckbox', 'Show archived'],
+ 'radio-item': ['menuitemradio', 'Newest'],
+ 'unchecked-radio-item': ['menuitemradio', 'Oldest'],
+ 'typeahead-target': ['menuitemradio', 'Oldest'],
+ },
+ facts: {
+ enterTarget: 'checkbox-item',
+ wraps: true,
+ homeEnd: true,
+ disabledItem: false,
+ checked: {
+ 'checkbox-item': true,
+ 'radio-item': true,
+ 'unchecked-radio-item': false,
+ },
+ typeaheadCharacter: 'o',
+ },
+ },
+] as const satisfies ReadonlyArray<MenuBindingState>;
+
+export const MENU_EXCLUSIONS = [
+ {
+ id: 'opening-control',
+ owner: 'the menu-button pattern (MENU_BUTTON_PATTERN, MenuButton.a11y.*)',
+ reason:
+ 'How the trigger exposes itself and where focus lands when it opens the menu are the Menu Button contract. This binding opens the menu from the trigger with Enter only to reach the open state it checks.',
+ },
+ {
+ id: 'submenus',
+ owner:
+ 'DropdownMenuSubMenu.test.tsx and DropdownMenuDrillIn.a11y.chromium.spec.ts',
+ reason:
+ 'Right and Left Arrow opening and closing a flyout, a parent row’s haspopup and expanded state, and the compact-touch drill-in are not yet in a shared contract; the menu pattern exempts them to the binding, so none of these states renders a sub-menu.',
+ },
+ {
+ id: 'bottom-sheet-and-header-footer',
+ owner: 'component:DropdownMenu AR4/AR5 and the modal-dialog pattern',
+ reason:
+ 'On a compact touch display the menu is a bottom sheet, and with a header or footer the popover is a modal dialog in which Tab cycles instead of closing; both are dialogs, so every state here uses the plain pointer popover.',
+ },
+] as const;
diff --git a/packages/core/src/DropdownMenu/__tests__/Menu.a11y.test.tsx b/packages/core/src/DropdownMenu/__tests__/Menu.a11y.test.tsx
new file mode 100644
index 0000000000..db7c674d35
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/Menu.a11y.test.tsx
@@ -0,0 +1,136 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file Menu.a11y.test.tsx
+ * @input MENU_PATTERN bound to the open DropdownMenu pointer menu
+ * @output jsdom-lane proof of the DOM expectations and an honest "unrun" report for the browser layers
+ * @position Binding test for the DropdownMenu menu surface (the Chromium spec covers the rest)
+ */
+
+import {cleanup, render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {describe, expect, it} from 'vitest';
+import {
+ MENU_PATTERN,
+ checkAccessibilitySpec,
+ createJsdomHarness,
+ expectAccessibilitySpec,
+ summarize,
+ type BindingResult,
+} from '@astryxdesign/a11y-spec';
+import {MENU_KNOWN_FAILURES} from './Menu.a11y.known-failures';
+import {renderMenuState} from './Menu.a11y.renders';
+import {
+ MENU_BINDING_STATES,
+ MENU_EXCLUSIONS,
+ type MenuBindingState,
+} from './Menu.a11y.states';
+
+function trigger(state: MenuBindingState): HTMLElement {
+ return screen.getByRole('button', {name: state.label});
+}
+
+function menuFor(state: MenuBindingState): HTMLElement {
+ const id = trigger(state).getAttribute('aria-controls');
+ const menu = id == null ? null : document.getElementById(id);
+ if (menu == null) {
+ throw new Error(`menu state "${state.id}" has no controlled menu`);
+ }
+ return menu;
+}
+
+function relatedFor(
+ state: MenuBindingState,
+): Readonly<Record<string, Element>> {
+ const related: Record<string, Element> = {opener: trigger(state)};
+ for (const [relation, [role, name]] of Object.entries(state.items)) {
+ related[relation] = screen.getByRole(role, {name, hidden: true});
+ }
+ return related;
+}
+
+async function open(state: MenuBindingState): Promise<void> {
+ render(renderMenuState(state));
+ await userEvent.setup().click(trigger(state));
+}
+
+async function checkState(state: MenuBindingState): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: MENU_PATTERN,
+ binding: 'DropdownMenu.menu',
+ state: state.id,
+ facts: state.facts,
+ knownFailures: MENU_KNOWN_FAILURES,
+ mount: async () => {
+ await open(state);
+ return createJsdomHarness({
+ subject: menuFor(state),
+ related: relatedFor(state),
+ });
+ },
+ unmount: cleanup,
+ });
+}
+
+describe('DropdownMenu pointer menu — menu pattern, jsdom lane', () => {
+ it.each(
+ MENU_BINDING_STATES.map(state => [state.id, state.summary, state] as const),
+ )('%s — %s', async (_id, _summary, state) => {
+ await expectAccessibilitySpec({
+ spec: MENU_PATTERN,
+ binding: 'DropdownMenu.menu',
+ state: state.id,
+ facts: state.facts,
+ knownFailures: MENU_KNOWN_FAILURES,
+ render: async () => {
+ await open(state);
+ },
+ subject: () => menuFor(state),
+ 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 MENU_BINDING_STATES) {
+ results.push(await checkState(state));
+ }
+ const report = summarize(MENU_PATTERN, results);
+ expect(report.counts.pass).toBeGreaterThan(0);
+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+});
+
+describe('menu binding inventory', () => {
+ it('gives every representative state a distinct checked-in story', () => {
+ const stories = MENU_BINDING_STATES.map(state => state.storyId);
+ expect(new Set(stories).size).toBe(stories.length);
+ });
+
+ it('keeps the opening control, submenus and dialog presentations explicit', () => {
+ expect(MENU_EXCLUSIONS.map(row => row.id)).toEqual([
+ 'opening-control',
+ 'submenus',
+ 'bottom-sheet-and-header-footer',
+ ]);
+ for (const exclusion of MENU_EXCLUSIONS) {
+ expect(exclusion.owner.length, exclusion.id).toBeGreaterThan(20);
+ expect(exclusion.reason.length, exclusion.id).toBeGreaterThan(80);
+ }
+ });
+
+ it('renders the menu and every item relation it names for every state', async () => {
+ for (const state of MENU_BINDING_STATES) {
+ await open(state);
+ expect(menuFor(state).getAttribute('role'), state.id).toBe('menu');
+ expect(Object.keys(relatedFor(state)), state.id).toEqual([
+ 'opener',
+ ...Object.keys(state.items),
+ ]);
+ cleanup();
+ }
+ });
+});