An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): Grid contract and Calendar binding (#7499)
Cindy Zhang50e1a3130f41
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 6042670f19..fcbe49bddf 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1865,6 +1865,54 @@ jobs:retention-days: 30if-no-files-found: warn+ # The grid contract's role and name, and its arrow, Home, End and Enter+ # results, are accessibility-tree and real-browser facts that jsdom cannot+ # observe. Run the contract's own fixture proof and the Calendar binding+ # whenever Calendar, the grid-focus hook, the harness, the binding's+ # stories, or the contract changes. Its own --output directory; the JSON+ # report is the head-bound record, uploaded next.+ - name: Run Grid accessibility contract+ id: grid-contract+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}+ env:+ BASE_SHA: ${{ github.event.pull_request.base.sha }}+ PLAYWRIGHT_JSON_OUTPUT_FILE: grid-contract/report.json+ run: |+ should_run=false+ # 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/grid|internal/a11y-spec/src/harness|packages/core/src/Calendar/|packages/core/src/hooks/useGridFocus|apps/storybook/stories/CalendarGridA11y)' || scope=$?+ fi+ if [ "$scope" != 1 ]; then+ should_run=true+ fi+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"+ if [ "$should_run" != true ]; then+ echo "Calendar and the grid contract are not in PR scope; skipping grid evidence."+ exit 0+ fi+ pnpm exec playwright test \+ internal/a11y-spec/src/patterns/grid.chromium.spec.ts \+ packages/core/src/Calendar/__tests__/Calendar.a11y.chromium.spec.ts \+ --project chromium \+ --reporter list,json \+ --output grid-contract-output++ - name: Upload Grid accessibility contract evidence+ if: ${{ !cancelled() && steps.grid-contract.outputs.should_run == 'true' }}+ uses: actions/upload-artifact@v7+ with:+ name: grid-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: grid-contract/+ retention-days: 30+ if-no-files-found: warn+# The link contract's role, name, Tab, Enter, and pointer-release outcomes# are accessibility-tree and real-browser facts that jsdom cannot observe.# Run the contract's own fixture proof and the Link binding whenever Linkdiff --git a/apps/storybook/stories/CalendarGridA11y.stories.tsx b/apps/storybook/stories/CalendarGridA11y.stories.tsxnew file mode 100644index 0000000000..3a0b6be5c0--- /dev/null+++ b/apps/storybook/stories/CalendarGridA11y.stories.tsx@@ -0,0 +1,34 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CalendarGridA11y.stories.tsx+ * @input The Calendar grid binding states, rendered through the binding's own renderer so the jsdom and Chromium lanes see the same tree+ * @output One checked-in story per state for the Chromium accessibility lane; excluded from the visual matrix+ * @position Browser fixtures for component:Calendar AR1 (GRID_PATTERN)+ */++import type {Meta, StoryObj} from '@storybook/react';+import {renderCalendarState} from '../../../packages/core/src/Calendar/__tests__/Calendar.a11y.renders';+import {CALENDAR_BINDING_STATES} from '../../../packages/core/src/Calendar/__tests__/Calendar.a11y.states';++const meta = {+ title: 'A11y/CalendarGrid',+ tags: ['no-visual'],+ parameters: {layout: 'padded'},+} satisfies Meta;++export default meta;+type Story = StoryObj<typeof meta>;++function storyFor(id: (typeof CALENDAR_BINDING_STATES)[number]['id']): Story {+ const state = CALENDAR_BINDING_STATES.find(candidate => candidate.id === id);+ if (state == null) {+ throw new Error(`no Calendar binding state "${id}"`);+ }+ return {render: () => renderCalendarState(state)};+}++export const SingleSelected = storyFor('single-selected');+export const SingleRtl = storyFor('single-rtl');+export const SingleWeekNumbers = storyFor('single-week-numbers');+export const RangeTwoMonths = storyFor('range-two-months');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex 8ad85d6106..240678d6b9 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -51,6 +51,7 @@ src/├── listbox.* listbox, group, and option semantics├── spinbutton.* numeric role, value, bounds, state, and arrow stepping├── disclosure.* standalone disclosure state/content semantics+ ├── 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├── carousel.* non-rotating collection, slide, off-screen, and focus semantics├── tree-view.* a tree's roles, names, expanded state, one Tab stop, and arrow/Home/End/Enter-or-Space/typeahead movement@@ -84,6 +85,7 @@ src/| `treeview` | [APG Tree View](https://www.w3.org/WAI/ARIA/apg/patterns/treeview/) structure and keyboard model | TreeList rows: tree/treeitem/group, aria-expanded, level/position, one Tab stop, Up/Down, Right/Left (RTL-mirrored), Home/End, Enter or Space, typeahead || `carousel` | [APG Carousel](https://www.w3.org/WAI/ARIA/apg/patterns/carousel/) and WCAG 2.2 semantics | Carousel container, slides, scroll area, and stable navigation-control focus || `alertdialog` | [APG Alert Dialog](https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/) role, references, modality, focus, dismissal | AlertDialog: alertdialog role and name, aria-describedby to the message, modal, Cancel first (advisory), Escape closes, click beside inert (advisory); modal mechanics stay with the modal-dialog contract through Dialog |+| `grid` | [APG Grid](https://www.w3.org/WAI/ARIA/apg/patterns/grid/) role, structure, name, selection and data-grid keys | Calendar month grids: grid role/name, row and gridcell/columnheader structure, one Tab stop, aria-selected/aria-multiselectable, arrows in reading order, Home/End, Enter selects (advisory) || `link` | WCAG 2.2 semantics; [APG Link](https://www.w3.org/WAI/ARIA/apg/patterns/link/) role and Enter mechanics | Link, including LinkProvider and `as` router components |The toggle-button contract owns the persistent-action extension of buttondiff --git a/internal/a11y-spec/src/harness.ts b/internal/a11y-spec/src/harness.tsindex cd0a99d4cd..6a3e54b4c1 100644--- a/internal/a11y-spec/src/harness.ts+++ b/internal/a11y-spec/src/harness.ts@@ -97,6 +97,12 @@ export interface Subject {textValue(): Promise<string | null>;/** DOM layer: the subject's authored text content, whitespace-normalized. */textContent(): Promise<string>;+ /**+ * DOM layer: how many descendants match a CSS selector (`:scope` names the+ * subject). Structure contracts count rows and cells with it; it never+ * reaches into component-private markup beyond ARIA roles and attributes.+ */+ descendantCount(selector: string): Promise<number>;/** DOM layer: whether a current semantic subject resolves after an update. */currentExists(): Promise<boolean>;/** DOM layer: whether the originally designated subject is still connected. */diff --git a/internal/a11y-spec/src/harness/chromium.ts b/internal/a11y-spec/src/harness/chromium.tsindex af7ad3b068..08537c9283 100644--- a/internal/a11y-spec/src/harness/chromium.ts+++ b/internal/a11y-spec/src/harness/chromium.ts@@ -661,6 +661,7 @@ export function createChromiumHarness(locator.evaluate(node =>(node.textContent ?? '').replace(/\s+/g, ' ').trim(),),+ descendantCount: selector => locator.locator(selector).count(),currentExists: async () => (await locator.count()) > 0,isConnected: async () => {const element = await capturedElement();@@ -971,6 +972,7 @@ export function createChromiumHarness(related.evaluate(node =>(node.textContent ?? '').replace(/\s+/g, ' ').trim(),),+ descendantCount: selector => related.locator(selector).count(),currentExists: async () => (await related.count()) > 0,isConnected: () => related.evaluate(node => node.isConnected),computed: () => computedNode(cdp, related),diff --git a/internal/a11y-spec/src/harness/jsdom.ts b/internal/a11y-spec/src/harness/jsdom.tsindex 7da7ed9fd9..4d5c3e66f9 100644--- a/internal/a11y-spec/src/harness/jsdom.ts+++ b/internal/a11y-spec/src/harness/jsdom.ts@@ -107,6 +107,8 @@ function createSubject(element: Element): Subject {},textContent: async () =>(element.textContent ?? '').replace(/\s+/g, ' ').trim(),+ descendantCount: async selector =>+ element.querySelectorAll(selector).length,currentExists: async () => element.isConnected,isConnected: async () => element.isConnected,computed: async () =>diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.tsindex 424a4d7f68..b82539a2c3 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -147,6 +147,7 @@ export {ACCORDION_PATTERN,type AccordionStateFacts,} from './patterns/accordion';+export {GRID_PATTERN, type GridStateFacts} from './patterns/grid';export {ALERT_DIALOG_PATTERN,type AlertDialogStateFacts,diff --git a/internal/a11y-spec/src/patterns/grid.chromium.spec.ts b/internal/a11y-spec/src/patterns/grid.chromium.spec.tsnew file mode 100644index 0000000000..e513a00a2d--- /dev/null+++ b/internal/a11y-spec/src/patterns/grid.chromium.spec.ts@@ -0,0 +1,102 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file grid.chromium.spec.ts+ * @input GRID_PATTERN and its fixtures in real Chromium (the fixture script implements the data-grid keyboard model)+ * @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 {GRID_PATTERN} from './grid';+import {+ GRID_MUTATIONS,+ CONFORMING_FIXTURES,+ RELATION_SELECTORS,+ SUBJECT_SELECTOR,+ fixture,+ type GridFixture,+} from './grid.fixtures';++function fixturePage(html: string): string {+ return `<!doctype html><html lang="en"><body>${html}</body></html>`;+}++async function results(+ page: Page,+ cdp: CDPSession,+ target: GridFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ const run = await checkAccessibilitySpec({+ spec: GRID_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: Object.fromEntries(+ Object.entries(RELATION_SELECTORS).map(([name, selector]) => [+ name,+ page.locator(selector),+ ]),+ ),+ });+ },+ });+ return run.results;+}++test.describe('grid 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('grid contract — deliberately violating fixtures', () => {+ for (const expectation of GRID_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of GRID_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/grid.fixtures.ts b/internal/a11y-spec/src/patterns/grid.fixtures.tsnew file mode 100644index 0000000000..325e180b23--- /dev/null+++ b/internal/a11y-spec/src/patterns/grid.fixtures.ts@@ -0,0 +1,250 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file grid.fixtures.ts+ * @input Plain HTML 3×3 grids (one script implements the data-grid keyboard model with a roving tabindex; the DOM lane never runs it), conforming and deliberately violating+ * @output GRID_FIXTURES, the subject and relation selectors, and the expectation → violating-fixture map+ * @position Contract self-test data for grid.jsdom.test.ts and grid.chromium.spec.ts+ */++import type {GridStateFacts} from './grid';++const SUBJECT_ATTRIBUTE = 'data-a11y-subject';+export const SUBJECT_SELECTOR = `[${SUBJECT_ATTRIBUTE}]`;+/** The start cell is the middle cell (row 2, column 2) so every neighbour exists. */+export const RELATION_SELECTORS = {+ start: '[data-cell="2-2"] > button',+ startCell: '[data-cell="2-2"]',+ next: '[data-cell="2-3"] > button',+ previous: '[data-cell="2-1"] > button',+ below: '[data-cell="3-2"] > button',+ above: '[data-cell="1-2"] > button',+ rowStart: '[data-cell="2-1"] > button',+ rowEnd: '[data-cell="2-3"] > button',+} as const;++export interface GridFixture {+ readonly id: string;+ readonly summary: string;+ readonly facts: GridStateFacts;+ readonly html: string;+}++const SCRIPT = `<script>+(() => {+ const grid = document.querySelector('[${SUBJECT_ATTRIBUTE}]');+ const rtl = grid.closest('[dir="rtl"]') != null && !window.__gridNoRtl;+ const buttons = () => Array.from(grid.querySelectorAll('[data-cell] > button'));+ const at = (r, c) => grid.querySelector('[data-cell="' + r + '-' + c + '"] > button');+ const move = (from, to) => {+ if (!to) return;+ buttons().forEach(b => b.tabIndex = -1);+ to.tabIndex = 0;+ to.focus();+ };+ grid.addEventListener('keydown', e => {+ const b = e.target.closest('[data-cell] > button');+ if (!b) return;+ const [r, c] = b.parentElement.dataset.cell.split('-').map(Number);+ const forward = rtl ? 'ArrowLeft' : 'ArrowRight';+ const back = rtl ? 'ArrowRight' : 'ArrowLeft';+ const step = window.__gridArrowSkips ? 2 : 1;+ let target = null;+ if (e.key === forward) target = at(r, c + step);+ else if (e.key === back) target = at(r, c - step);+ else if (e.key === 'ArrowDown') target = at(r + step, c);+ else if (e.key === 'ArrowUp') target = at(r - step, c);+ else if (e.key === 'Home') target = at(r, window.__gridHomeOff ? 2 : 1);+ else if (e.key === 'End') target = at(r, 3);+ else if (e.key === 'Enter') {+ e.preventDefault();+ if (!window.__gridEnterInert) b.parentElement.setAttribute('aria-selected', 'true');+ return;+ } else return;+ e.preventDefault();+ move(b, target);+ });+})();+</script>`;++function grid({+ role = 'grid',+ label = 'October 2026' as string | null,+ headers = true,+ tabStops = 1,+ multiselectable = false,+ selected = [] as readonly string[],+ cellRole = 'gridcell',+ strayChild = false,+ rtl = false,+}: {+ role?: string;+ label?: string | null;+ headers?: boolean;+ tabStops?: number;+ multiselectable?: boolean;+ selected?: readonly string[];+ cellRole?: string;+ strayChild?: boolean;+ rtl?: boolean;+} = {}): string {+ const header = headers+ ? `<div role="row"><div role="columnheader">A</div><div role="columnheader">B</div><div role="columnheader">C</div></div>`+ : '';+ let stops = 0;+ const rows = [1, 2, 3]+ .map(r => {+ const cells = [1, 2, 3]+ .map(c => {+ const id = `${r}-${c}`;+ const isStop =+ stops < tabStops && (tabStops === 1 ? id === '2-2' : true);+ if (isStop) {+ stops += 1;+ }+ const sel = selected.includes(id) ? ' aria-selected="true"' : '';+ return `<div role="${cellRole}" data-cell="${id}"${sel}><button type="button" tabindex="${isStop ? 0 : -1}">${id}</button></div>`;+ })+ .join('');+ return `<div role="row">${cells}</div>`;+ })+ .join('');+ const stray = strayChild ? '<div>Not a row</div>' : '';+ return `<div${rtl ? ' dir="rtl"' : ''}><div ${SUBJECT_ATTRIBUTE} role="${role}"${label == null ? '' : ` aria-label="${label}"`}${multiselectable ? ' aria-multiselectable="true"' : ''}>${header}${rows}${stray}</div></div>${SCRIPT}`;+}++const ALL_NEIGHBOURS = [+ 'next',+ 'previous',+ 'below',+ 'above',+ 'rowStart',+ 'rowEnd',+] as const;++const facts = (overrides: Partial<GridStateFacts> = {}): GridStateFacts => ({+ hasColumnHeaders: true,+ rtl: false,+ multiselectable: false,+ selectedCount: 0,+ enterSelectsStart: true,+ neighbours: ALL_NEIGHBOURS,+ ...overrides,+});++const flag = (name: string, html: string) =>+ html.replace('<script>', `<script>window.${name} = true;</script><script>`);++export const GRID_FIXTURES: readonly GridFixture[] = [+ {+ id: 'conforming-grid',+ summary:+ 'a named 3×3 grid with a header row, one Tab stop and Enter selecting the focused cell',+ facts: facts(),+ html: grid(),+ },+ {+ id: 'conforming-rtl',+ summary:+ 'the same grid on a right-to-left page: ArrowLeft moves forward in reading order',+ facts: facts({rtl: true}),+ html: grid({rtl: true}),+ },+ {+ id: 'conforming-multiselect',+ summary: 'a multi-selection grid with two selected cells',+ facts: facts({multiselectable: true, selectedCount: 2}),+ html: grid({multiselectable: true, selected: ['1-1', '1-2']}),+ },+ {+ id: 'conforming-no-headers',+ summary: 'a grid whose weekday names live outside it',+ facts: facts({hasColumnHeaders: false}),+ html: grid({headers: false}),+ },+ {+ id: 'violating-role-table',+ summary: 'a grid exposed as a table',+ facts: facts(),+ html: grid({role: 'table'}),+ },+ {+ id: 'violating-no-name',+ summary: 'a grid with no accessible name',+ facts: facts(),+ html: grid({label: null}),+ },+ {+ id: 'violating-cell-role',+ summary: 'cells exposed as plain cells, not gridcells',+ facts: facts(),+ html: grid({cellRole: 'cell'}),+ },+ {+ id: 'violating-stray-child',+ summary: 'a grid with a direct child that is not a row',+ facts: facts(),+ html: grid({strayChild: true}),+ },+ {+ id: 'violating-two-tab-stops',+ summary: 'a grid with two cells in the Tab order',+ facts: facts(),+ html: grid({tabStops: 2}),+ },+ {+ id: 'violating-unmarked-selection',+ summary: 'a grid that claims two selected cells but marks none',+ facts: facts({multiselectable: true, selectedCount: 2}),+ html: grid({multiselectable: true}),+ },+ {+ id: 'violating-arrow-skips',+ summary: 'a grid whose arrows move two cells at a time',+ facts: facts(),+ html: flag('__gridArrowSkips', grid()),+ },+ {+ id: 'violating-rtl-not-reversed',+ summary: 'a right-to-left grid whose arrows still follow left-to-right',+ facts: facts({rtl: true}),+ html: flag('__gridNoRtl', grid({rtl: true})),+ },+ {+ id: 'violating-home-off',+ summary: 'a grid whose Home does not reach the first cell of the row',+ facts: facts(),+ html: flag('__gridHomeOff', grid()),+ },+ {+ id: 'violating-enter-inert',+ summary: 'a grid whose Enter does not select the focused cell',+ facts: facts(),+ html: flag('__gridEnterInert', grid()),+ },+];++export function fixture(id: string): GridFixture {+ const found = GRID_FIXTURES.find(candidate => candidate.id === id);+ if (found == null) {+ throw new Error(`unknown grid fixture "${id}"`);+ }+ return found;+}++export const CONFORMING_FIXTURES: readonly string[] = GRID_FIXTURES.filter(+ candidate => candidate.id.startsWith('conforming-'),+).map(candidate => candidate.id);++export const GRID_MUTATIONS: Readonly<Record<string, readonly string[]>> = {+ 'grid.container.role-and-name': ['violating-role-table', 'violating-no-name'],+ 'grid.structure.rows-and-cells': [+ 'violating-cell-role',+ 'violating-stray-child',+ ],+ 'grid.focus.single-tab-stop': ['violating-two-tab-stops'],+ 'grid.selection.exposed': ['violating-unmarked-selection'],+ 'grid.keys.arrows': ['violating-arrow-skips', 'violating-rtl-not-reversed'],+ 'grid.keys.home-end': ['violating-home-off'],+ 'grid.keys.enter-activates': ['violating-enter-inert'],+};diff --git a/internal/a11y-spec/src/patterns/grid.jsdom.test.ts b/internal/a11y-spec/src/patterns/grid.jsdom.test.tsnew file mode 100644index 0000000000..9bb004caf0--- /dev/null+++ b/internal/a11y-spec/src/patterns/grid.jsdom.test.ts@@ -0,0 +1,160 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file grid.jsdom.test.ts+ * @input GRID_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 {GRID_PATTERN} from './grid';+import {+ GRID_MUTATIONS,+ CONFORMING_FIXTURES,+ RELATION_SELECTORS,+ SUBJECT_SELECTOR,+ fixture,+ type GridFixture,+} from './grid.fixtures';++const observableHere = GRID_PATTERN.expectations.filter(expectation =>+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),+);++afterEach(() => document.body.replaceChildren());++async function resultsFor(target: GridFixture) {+ const container = document.createElement('div');+ document.body.append(container);+ const result = await checkAccessibilitySpec({+ spec: GRID_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 subject`);+ }+ const related: Record<string, Element> = {};+ for (const [name, selector] of Object.entries(RELATION_SELECTORS)) {+ const element = container.querySelector(selector);+ if (element != null) {+ 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('grid contract — completeness', () => {+ it('answers every completeness dimension', () => {+ expect(unansweredDimensions(GRID_PATTERN)).toEqual([]);+ });++ it('gives every expectation at least one deliberately violating fixture', () => {+ const missing = GRID_PATTERN.expectations+ .filter(+ expectation => (GRID_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(+ GRID_PATTERN.expectations.map(expectation => expectation.id),+ );+ expect(Object.keys(GRID_MUTATIONS).filter(id => !ids.has(id))).toEqual([]);+ });++ it('names every fixture it records a mutation against', () => {+ for (const fixtures of Object.values(GRID_MUTATIONS)) {+ for (const id of fixtures) {+ expect(() => fixture(id)).not.toThrow();+ }+ }+ });+});++describe('grid 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-grid'));+ 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 = GRID_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((GRID_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(+ GRID_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/grid.ts b/internal/a11y-spec/src/patterns/grid.tsnew file mode 100644index 0000000000..0ccceb9b6c--- /dev/null+++ b/internal/a11y-spec/src/patterns/grid.ts@@ -0,0 +1,554 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file grid.ts+ * @input WCAG 2.2 A/AA success criteria and the APG Grid pattern's role, structure, name, selection, and data-grid keyboard requirements+ * @output GRID_PATTERN — the reusable contract a composite grid binds to when it adopts the pattern (Calendar's month grid under component:Calendar AR1, `spec:AST-020/FR15`)+ * @position Pattern contract; bound by Calendar (DateInput's month panes to follow)+ */++import type {Subject} from '../harness';+import {+ definePattern,+ type ApgRequirement,+ type AstryxRecord,+ type WebStandardRequirement,+ type PatternContract,+ type WcagCriterion,+} from '../contract';++const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/grid/';+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_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 apgReq = (requirement: string, anchor: string): ApgRequirement => ({+ standard: 'apg',+ pattern: 'grid',+ requirement,+ url: `${APG_URL}#${anchor}`,+});+const A = 'wai-ariaroles,states,andproperties';+const K = 'keyboardinteractionfordatagrids';+const APG_ROLE = apgReq('The grid container has role grid.', A);+const APG_ROWS = apgReq(+ 'Each row container has role row and is either a DOM descendant of or owned by the grid element or an element with role rowgroup. Each cell is either a DOM descendant of or owned by a row element and has role columnheader if it contains header information for the column, rowheader if for the row, or gridcell otherwise.',+ A,+);+const APG_NAME = apgReq(+ 'If there is an element in the user interface that serves as a label for the grid, aria-labelledby is set on the grid element; otherwise, a label is specified for the grid element using aria-label.',+ A,+);+const APG_SELECTION = apgReq(+ 'If the grid supports selection, when a cell or row is selected, the selected element has aria-selected set true.',+ A,+);+const ARIA_MULTISELECTABLE: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2',+ requirement:+ 'aria-multiselectable: Indicates that the user may select more than one item from the current selectable descendants.',+ url: 'https://www.w3.org/TR/wai-aria-1.2/#aria-multiselectable',+};+const APG_FOCUS = apgReq(+ 'Only one of the focusable elements contained by the grid is included in the page tab sequence.',+ 'about-this-pattern',+);+const APG_ARROWS = apgReq(+ 'Right Arrow: Moves focus one cell to the right. Left Arrow: Moves focus one cell to the left. Down Arrow: Moves focus one cell down. Up Arrow: Moves focus one cell up.',+ K,+);+const APG_HOME_END = apgReq(+ 'Home: moves focus to the first cell in the row that contains focus. End: moves focus to the last cell in the row that contains focus.',+ K,+);+const CALENDAR_AR1_ACTIVATE: AstryxRecord = {+ standard: 'astryx',+ id: 'component:Calendar',+ clause: 'AR1',+ url: 'https://github.com/facebook/astryx/blob/66d7146e5aeb8e983b6803c3571a8e871135a35c/packages/core/src/Calendar/Calendar.spec.md#L141-L143',+ requirement: 'Enter or Space picks the focused day.',+};++/**+ * What a binding knows about one grid (the subject). The binding also+ * designates related subjects around one `start` cell's focus target: `next`+ * and `previous` (the cells one column forward and back in reading order),+ * `below` and `above` (one row down and up), and `rowStart` and `rowEnd`+ * (the first and last cells of the start row). Any that do not exist for the+ * chosen start cell are omitted and the matching key is not pressed.+ */+export interface GridStateFacts {+ /** Whether the grid's first row is a header row of `columnheader` cells. */+ readonly hasColumnHeaders: boolean;+ /** Whether the grid is on a right-to-left page (the inline arrows follow reading order). */+ readonly rtl: boolean;+ /** Whether the grid claims `aria-multiselectable`. */+ readonly multiselectable: boolean;+ /** How many cells the binding has selected in this state. */+ readonly selectedCount: number;+ /** Whether Enter on the start cell selects it (the binding's default action). */+ readonly enterSelectsStart: boolean;+ /** Which related neighbours the start cell has in this state. */+ readonly neighbours: ReadonlyArray<+ 'next' | 'previous' | 'below' | 'above' | 'rowStart' | 'rowEnd'+ >;+}++const ALWAYS = {+ condition: 'the binding designates a grid',+ test: () => true,+};++async function expectFocused(subject: Subject, after: string): Promise<void> {+ if (!(await subject.isFocused())) {+ throw new Error(`${after} did not move focus to the expected cell`);+ }+}++export const GRID_PATTERN: PatternContract<GridStateFacts> =+ definePattern<GridStateFacts>({+ pattern: 'grid',+ url: APG_URL,+ scope:+ "A grid's role and name, its row and cell structure, its single Tab stop, its selection semantics, and the arrow, Home, End and activation keys within it.",+ expectations: [+ {+ id: 'grid.container.role-and-name',+ outcome:+ 'The browser exposes the grid as a named grid, so a user hears what the table of cells is.',+ sources: [WCAG_4_1_2, APG_ROLE, APG_NAME],+ covers: [+ '4.1.2-name-role-value',+ '2.4.6-headings-and-labels',+ 'apg-interaction',+ ],+ appliesWhen: ALWAYS,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {role, name} = await subject.computed();+ if (role !== 'grid') {+ throw new Error(+ `the browser exposes this as ${role == null ? 'no role' : `"${role}"`}, not as a grid`,+ );+ }+ if (!name || name.trim() === '') {+ throw new Error(+ 'the browser computes no accessible name for this grid',+ );+ }+ },+ },+ {+ id: 'grid.structure.rows-and-cells',+ outcome:+ 'Every row is a row of gridcells (or column headers), so assistive technology can navigate it as a table.',+ sources: [WCAG_1_3_1, APG_ROWS],+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const rows = await subject.descendantCount('[role="row"]');+ if (rows === 0) {+ throw new Error('the grid contains no role="row"');+ }+ const stray = await subject.descendantCount(+ ':scope > :not([role="row"]):not([role="rowgroup"])',+ );+ if (stray > 0) {+ throw new Error(+ `${stray} direct child(ren) of the grid are neither rows nor row groups`,+ );+ }+ const cells = await subject.descendantCount(+ '[role="row"] > :not([role="gridcell"]):not([role="columnheader"]):not([role="rowheader"])',+ );+ if (cells > 0) {+ throw new Error(+ `${cells} row child(ren) are not gridcell, columnheader or rowheader`,+ );+ }+ const headers = await subject.descendantCount(+ '[role="columnheader"]',+ );+ if (facts.hasColumnHeaders && headers === 0) {+ throw new Error(+ 'the grid claims column headers but has no columnheader cell',+ );+ }+ },+ },+ {+ id: 'grid.focus.single-tab-stop',+ outcome:+ 'Tab lands in the grid once: exactly one cell target is in the Tab order, and the arrows take it from there.',+ sources: [WCAG_2_1_1, WCAG_2_4_3, APG_FOCUS],+ covers: ['2.1.1-keyboard', '2.4.3-focus-order', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject}) => {+ const stops = await subject.descendantCount(+ '[tabindex="0"], button:not([tabindex]):not([disabled]), a[href]:not([tabindex]), input:not([tabindex]):not([disabled])',+ );+ if (stops !== 1) {+ throw new Error(+ `${stops} elements inside the grid are in the Tab order; a grid is one Tab stop`,+ );+ }+ },+ },+ {+ id: 'grid.selection.exposed',+ outcome:+ 'Selected cells say so, and a grid that can hold several selections says that too.',+ sources: [WCAG_4_1_2, APG_SELECTION, ARIA_MULTISELECTABLE],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const multi = await subject.attribute('aria-multiselectable');+ if (facts.multiselectable && multi !== 'true') {+ throw new Error(+ 'a multi-selection grid does not claim aria-multiselectable="true"',+ );+ }+ if (!facts.multiselectable && multi === 'true') {+ throw new Error(+ 'a single-selection grid claims aria-multiselectable="true"',+ );+ }+ const selected = await subject.descendantCount(+ '[aria-selected="true"]',+ );+ if (selected !== facts.selectedCount) {+ throw new Error(+ `${selected} cells are exposed as selected, not ${facts.selectedCount}`,+ );+ }+ },+ },+ {+ id: 'grid.keys.arrows',+ outcome:+ 'The arrows move focus one cell at a time within the grid — forward and back along the row in reading order, down and up the column.',+ sources: [WCAG_2_1_1, APG_ARROWS],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, facts}) => {+ const start = await harness.related('start');+ const forward = facts.rtl ? 'ArrowLeft' : 'ArrowRight';+ const back = facts.rtl ? 'ArrowRight' : 'ArrowLeft';+ await start.focus();+ await expectFocused(start, 'focusing the start cell');+ if (facts.neighbours.includes('next')) {+ await harness.press(forward);+ await expectFocused(+ await harness.related('next'),+ `${forward} (forward)`,+ );+ await harness.press(back);+ await expectFocused(start, `${back} (back)`);+ }+ if (facts.neighbours.includes('previous')) {+ await harness.press(back);+ await expectFocused(+ await harness.related('previous'),+ `${back} (back)`,+ );+ await harness.press(forward);+ await expectFocused(start, `${forward} (forward)`);+ }+ if (facts.neighbours.includes('below')) {+ await harness.press('ArrowDown');+ await expectFocused(await harness.related('below'), 'ArrowDown');+ await harness.press('ArrowUp');+ await expectFocused(start, 'ArrowUp');+ }+ if (facts.neighbours.includes('above')) {+ await harness.press('ArrowUp');+ await expectFocused(await harness.related('above'), 'ArrowUp');+ await harness.press('ArrowDown');+ await expectFocused(start, 'ArrowDown');+ }+ },+ },+ {+ id: 'grid.keys.home-end',+ outcome: 'Home moves to the first cell of the row and End to the last.',+ sources: [WCAG_2_1_1, APG_HOME_END],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition: 'the start row has a first and last cell to reach',+ test: facts =>+ facts.neighbours.includes('rowStart') &&+ facts.neighbours.includes('rowEnd'),+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness}) => {+ const start = await harness.related('start');+ await start.focus();+ await harness.press('Home');+ await expectFocused(await harness.related('rowStart'), 'Home');+ await start.focus();+ await harness.press('End');+ await expectFocused(await harness.related('rowEnd'), 'End');+ },+ },+ {+ id: 'grid.keys.enter-activates',+ outcome:+ "Enter performs the focused cell's default action: here, it selects the cell.",+ sources: [WCAG_2_1_1, CALENDAR_AR1_ACTIVATE],+ wcagOutcome:+ "Supports WCAG 2.2 2.1.1 by keeping the cell's action keyboard-operable; the APG leaves the action to the author and the binding record names it, so this row is advisory until that record is current (AST-020 FR9).",+ covers: ['apg-interaction'],+ appliesWhen: {+ condition: 'Enter on the start cell selects it',+ test: facts => facts.enterSelectsStart,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'advisory',+ advisoryBecause:+ "The cell's default action is author-determined in the APG and defined by the binding's draft record; required once that record is current (AST-020 FR9).",+ run: async ({harness}) => {+ const start = await harness.related('start');+ await start.focus();+ await harness.press('Enter');+ const cell = await harness.related('startCell');+ if ((await cell.attribute('aria-selected')) !== 'true') {+ throw new Error('Enter did not select the focused cell');+ }+ },+ },+ ],+ 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:+ "This contract owns the grid's structure and keys. Icons or images inside cells are the binding's or the caller's composition.",+ },+ '1.3.1-info-and-relationships': {+ owner: 'the binding component',+ verifiedBy:+ "the component's cell-content tests (today marker, descriptions, headers' names)",+ reason:+ "This contract proves the grid/row/cell hierarchy. What each cell says beyond its role (a date name, a today marker) is the binding's.",+ coversRemainderOnly: true,+ },+ '1.3.2-meaningful-sequence': {+ owner: 'the binding component',+ verifiedBy: "the component's DOM-order tests",+ reason:+ 'Row and cell order follow the data; the structure row proves they are nested as a table reads them.',+ },+ '1.3.5-identify-input-purpose': {+ owner: 'not applicable',+ verifiedBy: 'none needed',+ reason:+ 'A grid cell does not collect information about the user that autofill could supply.',+ },+ '1.4.1-use-of-color': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the component's selected, today, range and disabled state tests plus rendered review",+ reason:+ 'Selected, today, in-range and disabled cues are paint results owned by the binding and theme; this contract proves the programmatic selection.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'the binding component and theme',+ verifiedBy: 'the repository axe audit plus rendered contrast review',+ reason:+ 'Cell text contrast is a paint outcome owned by the binding and theme.',+ },+ '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 selection fill',+ reason:+ 'Focus indicator and selection fill contrast are paint outcomes owned by the binding and theme.',+ },+ '2.1.1-keyboard': {+ owner: 'the binding component and composing page',+ verifiedBy:+ "the component's month-navigation and Page-key tests, plus page-level keyboard review",+ reason:+ "This contract encodes the arrows, Home, End and Enter within the grid. Page keys and crossing the grid's edge are author-determined and the binding's; reaching the grid is composition.",+ coversRemainderOnly: true,+ },+ '2.1.2-no-keyboard-trap': {+ owner: 'the binding component and composing page',+ verifiedBy: "the component's Tab tests and page-level keyboard review",+ reason:+ 'A grid adds no focus trap: it is one Tab stop and Tab leaves it; the single-Tab-stop row proves the stop count.',+ },+ '2.4.2-page-titled': {+ owner: 'the page',+ verifiedBy: 'page-level review',+ reason: 'A grid rendered in isolation owns no document title.',+ },+ '2.4.3-focus-order': {+ owner: 'the composing page',+ verifiedBy: 'page-level focus-order review',+ reason:+ "This contract proves the one Tab stop; the grid's place among surrounding controls is composition.",+ coversRemainderOnly: true,+ },+ '2.4.4-link-purpose': {+ owner: 'not applicable',+ verifiedBy: 'none needed',+ reason: 'The bound grids render no link.',+ },+ '2.4.6-headings-and-labels': {+ owner: 'the binding component and caller content',+ verifiedBy: "the component's name tests and caller content review",+ reason:+ 'This contract proves the grid has a name; whether that name and the column headers are descriptive is content.',+ coversRemainderOnly: true,+ },+ '2.4.7-focus-visible': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the component's focus-outline tests and rendered focus review",+ reason:+ "The focused cell's indicator is a paint result owned by the binding and theme.",+ },+ '2.4.11-focus-not-obscured': {+ owner: 'the composing page',+ verifiedBy: 'page-level layout review',+ reason:+ 'Whether another surface covers the focused cell depends on composition.',+ },+ '2.5.2-pointer-cancellation': {+ owner: 'the binding component',+ verifiedBy: "the component's pointer selection tests",+ reason:+ "Picking a cell by pointer is the binding's; this contract covers the keyboard.",+ },+ '2.5.3-label-in-name': {+ owner: 'the binding component',+ verifiedBy: "the component's cell-name tests",+ reason:+ "Whether a cell's accessible name contains its visible text is the binding's naming requirement.",+ },+ '2.5.8-target-size': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the repository axe audit's target-size rule over the cells",+ reason: 'Cell hit areas are geometry owned by the binding and theme.',+ },+ '3.1.1-language-of-page': {+ owner: 'the page',+ verifiedBy: 'page-level review',+ reason: 'A grid owns no document language.',+ },+ '3.2.2-on-input': {+ owner: 'the caller and composing page',+ verifiedBy: 'integration review of what a caller does with onChange',+ reason:+ "Selecting a cell is the grid's own purpose; any further context change a caller makes is the caller's action.",+ },+ '3.2.4-consistent-identification': {+ owner: 'the composing page',+ verifiedBy: 'this shared contract across bindings plus content review',+ reason:+ 'Consistency is a property of the full set of repeated functions, not one isolated grid.',+ },+ '3.3.1-error-identification': {+ owner: 'the binding component',+ verifiedBy:+ "the component's bounds and constraint tests (disabled days)",+ reason:+ "A day outside the bounds is disabled, not an error; the binding's own tests prove the disabled exposure.",+ },+ '3.3.2-labels-or-instructions': {+ owner: 'the binding component and caller content',+ verifiedBy: "the component's label tests",+ reason:+ "This contract proves the grid is named; any instruction text is the binding's or the caller's.",+ },+ '4.1.2-name-role-value': {+ owner: 'the binding component',+ verifiedBy:+ "the component's cell state tests (aria-current, aria-disabled)",+ reason:+ "This contract encodes the grid's role and name, the row/cell roles and the selection state. Per-cell current and disabled states are the binding's.",+ coversRemainderOnly: true,+ },+ '4.1.3-status-messages': {+ owner:+ 'the binding component and the assistive-technology verification record, spec:AST-009',+ verifiedBy:+ "the component's month-change announcement tests and real-AT evidence under AST-009 when a change claims spoken or braille output",+ reason:+ "Moving focus within the grid is not a status message; the month-change announcement is the binding's own live-region claim.",+ },+ 'apg-interaction': {+ owner: "the binding component's record",+ verifiedBy:+ 'component:Calendar AR1 and FR5, which adopt the pattern as one composite control and define edge crossing and Page keys',+ reason:+ "This contract encodes the grid structure, the single Tab stop, the arrows within the grid, Home/End and Enter. Edge crossing into another month, Page keys and selection by pointer are the binding's.",+ 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:+ 'Month transitions are binding-specific paint over time and are not part of grid semantics.',+ },+ 'at-facing-strings': {+ owner: 'the binding component',+ verifiedBy:+ 'the repository i18n catalog check and source review of authored labels',+ reason:+ "The grid contract introduces no string; month names, day names and the grid's name come from the binding's locale.",+ },+ },+ });diff --git a/packages/core/src/Calendar/Calendar.test.tsx b/packages/core/src/Calendar/Calendar.test.tsxindex 7757145186..4bb769a328 100644--- a/packages/core/src/Calendar/Calendar.test.tsx+++ b/packages/core/src/Calendar/Calendar.test.tsx@@ -1651,15 +1651,6 @@ describe('Calendar', () => {});describe('aria-multiselectable', () => {- it('sets aria-multiselectable="true" on the grid in range mode', () => {- render(<Calendar mode="range" focusDate="2026-01-01" />);-- expect(screen.getByRole('grid')).toHaveAttribute(- 'aria-multiselectable',- 'true',- );- });-it('does not set aria-multiselectable in single mode', () => {render(<Calendar focusDate="2026-01-01" />);diff --git a/packages/core/src/Calendar/__tests__/Calendar.a11y.chromium.spec.ts b/packages/core/src/Calendar/__tests__/Calendar.a11y.chromium.spec.tsnew file mode 100644index 0000000000..d85847c19f--- /dev/null+++ b/packages/core/src/Calendar/__tests__/Calendar.a11y.chromium.spec.ts@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Calendar.a11y.chromium.spec.ts+ * @input Built Calendar stories and GRID_PATTERN in real Chromium+ * @output Browser evidence for every grid expectation across the binding's states (role and name, arrows in reading order, Home/End, Enter)+ * @position Chromium lane of the Calendar grid binding (component:Calendar AR1)+ */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ GRID_PATTERN,+ blockingResults,+ checkAccessibilitySpec,+ formatFailures,+ neverExercised,+ unmatchedKnownFailures,+ 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 {+ CALENDAR_BINDING_STATES,+ NEIGHBOURHOOD,+ START_ISO,+ type CalendarBindingState,+} from './Calendar.a11y.states';+import {CALENDAR_KNOWN_FAILURES} from './Calendar.a11y.known-failures';++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: CalendarBindingState,+): Promise<{subject: Locator; related: Record<string, Locator>}> {+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});+ await holdMotionStill(page);+ const root = page.locator('#storybook-root');+ const subject = root.getByRole('grid', {name: state.gridName});+ await subject.waitFor({state: 'attached'});+ const day = (iso: string) => root.locator(`button[data-date="${iso}"]`);+ const start = day(START_ISO);+ return {+ subject,+ related: {+ start,+ startCell: root.locator(+ `[role="gridcell"]:has(> button[data-date="${START_ISO}"])`,+ ),+ ...Object.fromEntries(+ Object.entries(NEIGHBOURHOOD).map(([name, iso]) => [name, day(iso)]),+ ),+ },+ };+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: CalendarBindingState,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: GRID_PATTERN,+ binding: 'Calendar',+ state: state.id,+ facts: state.facts,+ knownFailures: CALENDAR_KNOWN_FAILURES,+ mount: async () => {+ const {subject, related} = await mountState(page, state);+ return createChromiumHarness({page, cdp, subject, related});+ },+ });+}++test('every grid expectation is exercised by a Calendar state', async ({+ page,+}) => {+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of CALENDAR_BINDING_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(neverExercised(results)).toEqual([]);+ expect(unmatchedKnownFailures(CALENDAR_KNOWN_FAILURES, results)).toEqual([]);+});++for (const state of CALENDAR_BINDING_STATES) {+ test(`Calendar [${state.id}] — ${state.summary}`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(GRID_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/Calendar/__tests__/Calendar.a11y.known-failures.ts b/packages/core/src/Calendar/__tests__/Calendar.a11y.known-failures.tsnew file mode 100644index 0000000000..4c3af6df10--- /dev/null+++ b/packages/core/src/Calendar/__tests__/Calendar.a11y.known-failures.ts@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Calendar.a11y.known-failures.ts+ * @input The exact grid-contract failures the shipped Calendar produces today+ * @output CALENDAR_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 Calendar binding+ */++import type {KnownFailure} from '@astryxdesign/a11y-spec';++export const CALENDAR_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [];diff --git a/packages/core/src/Calendar/__tests__/Calendar.a11y.renders.tsx b/packages/core/src/Calendar/__tests__/Calendar.a11y.renders.tsxnew file mode 100644index 0000000000..5e827ca765--- /dev/null+++ b/packages/core/src/Calendar/__tests__/Calendar.a11y.renders.tsx@@ -0,0 +1,57 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file Calendar.a11y.renders.tsx+ * @input One Calendar binding state+ * @output The React tree every lane renders for that state (the jsdom test directly, the story through Storybook)+ * @position Shared fixture for the Calendar grid binding+ */++import {useState, type ReactElement} from 'react';+import {Calendar} from '../Calendar';+import type {DateRange, ISODateString} from '../Calendar';+import {START_ISO, type CalendarBindingState} from './Calendar.a11y.states';++function BoundCalendar({state}: {state: CalendarBindingState}) {+ const [single, setSingle] = useState<ISODateString | null>(+ state.mode === 'single' && typeof state.value === 'string'+ ? state.value+ : null,+ );+ const [range, setRange] = useState<DateRange | null>(+ state.mode === 'range' && typeof state.value === 'object'+ ? state.value+ : null,+ );+ if (state.mode === 'range') {+ return (+ <Calendar+ mode="range"+ value={range}+ onChange={setRange}+ focusDate={START_ISO}+ numberOfMonths={state.numberOfMonths ?? 1}+ />+ );+ }+ return (+ <Calendar+ mode="single"+ value={single}+ onChange={setSingle}+ focusDate={START_ISO}+ numberOfMonths={state.numberOfMonths ?? 1}+ hasWeekNumbers={state.hasWeekNumbers}+ />+ );+}++export function renderCalendarState(state: CalendarBindingState): ReactElement {+ return (+ <div dir={state.rtl ? 'rtl' : 'ltr'} style={{padding: 16}}>+ <BoundCalendar state={state} />+ </div>+ );+}diff --git a/packages/core/src/Calendar/__tests__/Calendar.a11y.states.ts b/packages/core/src/Calendar/__tests__/Calendar.a11y.states.tsnew file mode 100644index 0000000000..82171857ae--- /dev/null+++ b/packages/core/src/Calendar/__tests__/Calendar.a11y.states.ts@@ -0,0 +1,139 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Calendar.a11y.states.ts+ * @input Calendar's representative month-grid states and the facts GRID_PATTERN reads+ * @output CALENDAR_BINDING_STATES, the start-cell neighbourhood for each, and the explicit ownership exclusions for this binding+ * @position Binding inventory shared by the jsdom test, the Chromium spec, and the story (component:Calendar AR1)+ */++import type {GridStateFacts} from '@astryxdesign/a11y-spec';+import type {DateRange, ISODateString} from '../Calendar';++/**+ * Every state starts on a mid-month day with a full neighbourhood inside the+ * same month row: January 14, 2026 is a Wednesday, so its row runs January+ * 11 (Sunday) to January 17 (Saturday), with January 7 above and 21 below.+ */+export const START_ISO: ISODateString = '2026-01-14';+export const NEIGHBOURHOOD = {+ next: '2026-01-15',+ previous: '2026-01-13',+ below: '2026-01-21',+ above: '2026-01-07',+ rowStart: '2026-01-11',+ rowEnd: '2026-01-17',+} as const;++export interface CalendarBindingState {+ readonly id: string;+ readonly summary: string;+ readonly storyId: string;+ /** The grid's accessible name (its month label). */+ readonly gridName: string;+ readonly facts: GridStateFacts;+ readonly mode: 'single' | 'range';+ readonly value?: ISODateString | DateRange;+ readonly numberOfMonths?: 1 | 2;+ /** Render ISO week numbers in a leading column (`hasWeekNumbers`). */+ readonly hasWeekNumbers?: boolean;+ readonly rtl?: boolean;+}++const ALL = [+ 'next',+ 'previous',+ 'below',+ 'above',+ 'rowStart',+ 'rowEnd',+] as const;++function facts(overrides: Partial<GridStateFacts> = {}): GridStateFacts {+ return {+ hasColumnHeaders: true,+ rtl: false,+ multiselectable: false,+ selectedCount: 0,+ enterSelectsStart: true,+ neighbours: ALL,+ ...overrides,+ };+}++const story = (id: string) => `a11y-calendargrid--${id}`;++export const CALENDAR_BINDING_STATES = [+ {+ id: 'single-selected',+ summary:+ 'a single-mode Calendar with January 20 selected; focus starts on January 14',+ storyId: story('single-selected'),+ gridName: 'January 2026',+ mode: 'single',+ value: '2026-01-20',+ facts: facts({selectedCount: 1}),+ },+ {+ id: 'single-rtl',+ summary:+ 'the same Calendar on a right-to-left page: ArrowLeft moves to the next day',+ storyId: story('single-rtl'),+ gridName: 'January 2026',+ mode: 'single',+ value: '2026-01-20',+ rtl: true,+ facts: facts({rtl: true, selectedCount: 1}),+ },+ {+ id: 'single-week-numbers',+ summary:+ 'a single-mode Calendar with week numbers: the header row gains a corner cell before the weekday headers',+ storyId: story('single-week-numbers'),+ gridName: 'January 2026',+ mode: 'single',+ value: '2026-01-20',+ hasWeekNumbers: true,+ facts: facts({selectedCount: 1}),+ },+ {+ id: 'range-two-months',+ summary:+ 'a two-month range Calendar with January 20–22 selected; the first grid is the subject',+ storyId: story('range-two-months'),+ gridName: 'January 2026',+ mode: 'range',+ value: {start: '2026-01-20', end: '2026-01-22'},+ numberOfMonths: 2,+ // Enter on a range Calendar starts a new range rather than selecting the+ // day outright, so the activation row does not apply here.+ facts: facts({+ multiselectable: true,+ selectedCount: 3,+ enterSelectsStart: false,+ }),+ },+] as const satisfies ReadonlyArray<CalendarBindingState>;++export const CALENDAR_EXCLUSIONS = [+ {+ id: 'month-edge-crossing',+ owner: 'component:Calendar FR5 and Calendar.test.tsx (cross-month suites)',+ reason:+ 'An arrow at the edge of a month crosses into the neighbouring month and focuses the real day there; the APG grid pattern stops at the edge, and the record defines the crossing. Every binding state therefore starts mid-month, and the crossing stays with the component tests.',+ },+ {+ id: 'disabled-day-arrows',+ owner:+ 'Calendar.test.tsx (bounds and dateConstraints suites) and component:Calendar AR1',+ reason:+ "An arrow that meets a day disabled by `min`/`max` or a `dateConstraints` rule skips it and continues in the same direction, crossing the month edge when it must — a behaviour the Calendar record defines (AR1) beyond the APG grid's one-cell step, so this contract's arrow row keeps its states free of disabled days. Calendar.test.tsx proves the skip ('ArrowUp skips a disabled cell in the same column to the next enabled row (complex-2)', the weekdays-only and max-bound arrow cases) and owns it.",+ },+ {+ id: 'page-keys-and-pointer',+ owner:+ 'Calendar.test.tsx: the Page-key cases ("moves the focused day by a month with PageDown and PageUp, into the month now shown", "a page into a month with no enabled day changes nothing and keeps focus", "a page onto a day disabled by a constraint moves the month and focuses its first enabled day", "a page whose target lies past max changes nothing and keeps focus", "in a two-month view PageDown from the second month moves both months and a later Next click selects no stale day") and the pointer selection suites',+ reason:+ 'PageUp/PageDown move by a month (author-determined in the APG, defined by component:Calendar AR1) and pointer selection are outside this keyboard-and-structure contract; the component tests own them.',+ },+] as const;diff --git a/packages/core/src/Calendar/__tests__/Calendar.a11y.test.tsx b/packages/core/src/Calendar/__tests__/Calendar.a11y.test.tsxnew file mode 100644index 0000000000..eef8992700--- /dev/null+++ b/packages/core/src/Calendar/__tests__/Calendar.a11y.test.tsx@@ -0,0 +1,137 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file Calendar.a11y.test.tsx+ * @input GRID_PATTERN bound to Calendar's representative month-grid states+ * @output jsdom-lane proof of the DOM expectations (structure, single Tab stop, selection) and an honest "unrun" report for the browser layers+ * @position Binding test for component:Calendar AR1 (the Chromium spec covers the rest)+ */++import {cleanup, render, screen} from '@testing-library/react';+import {describe, expect, it} from 'vitest';+import {+ GRID_PATTERN,+ checkAccessibilitySpec,+ createJsdomHarness,+ expectAccessibilitySpec,+ summarize,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {renderCalendarState} from './Calendar.a11y.renders';+import {+ CALENDAR_BINDING_STATES,+ CALENDAR_EXCLUSIONS,+ NEIGHBOURHOOD,+ START_ISO,+ type CalendarBindingState,+} from './Calendar.a11y.states';+import {CALENDAR_KNOWN_FAILURES} from './Calendar.a11y.known-failures';++function grid(state: CalendarBindingState): HTMLElement {+ return screen.getByRole('grid', {name: state.gridName});+}++function dayButton(iso: string): HTMLElement {+ const button = document.querySelector<HTMLElement>(+ `button[data-date="${iso}"]`,+ );+ if (button == null) {+ throw new Error(`no day button for ${iso}`);+ }+ return button;+}++function related(): Record<string, HTMLElement> {+ const start = dayButton(START_ISO);+ const startCell = start.closest<HTMLElement>('[role="gridcell"]');+ if (startCell == null) {+ throw new Error('the start day is not inside a gridcell');+ }+ return {+ start,+ startCell,+ ...Object.fromEntries(+ Object.entries(NEIGHBOURHOOD).map(([name, iso]) => [+ name,+ dayButton(iso),+ ]),+ ),+ };+}++async function checkState(state: CalendarBindingState): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: GRID_PATTERN,+ binding: 'Calendar',+ state: state.id,+ facts: state.facts,+ knownFailures: CALENDAR_KNOWN_FAILURES,+ mount: async () => {+ render(renderCalendarState(state));+ return createJsdomHarness({subject: grid(state), related: related()});+ },+ unmount: cleanup,+ });+}++describe('Calendar — grid pattern, jsdom lane', () => {+ it.each(+ CALENDAR_BINDING_STATES.map(+ state => [state.id, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectAccessibilitySpec({+ spec: GRID_PATTERN,+ binding: 'Calendar',+ state: state.id,+ facts: state.facts,+ knownFailures: CALENDAR_KNOWN_FAILURES,+ render: () => {+ render(renderCalendarState(state));+ },+ subject: () => grid(state),+ related: () => related(),+ cleanup,+ });+ });++ it('runs the DOM layer and reports the browser-owned outcomes as unrun', async () => {+ const results: BindingResult[] = [];+ for (const state of CALENDAR_BINDING_STATES) {+ results.push(await checkState(state));+ }+ const report = summarize(GRID_PATTERN, results);+ expect(report.counts.pass).toBeGreaterThan(0);+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);+ expect(report.counts.unexpectedPass).toBe(0);+ });+});++describe('Calendar binding inventory', () => {+ it('gives every representative state a distinct checked-in story', () => {+ const stories = CALENDAR_BINDING_STATES.map(state => state.storyId);+ expect(new Set(stories).size).toBe(stories.length);+ });++ it('keeps edge crossing, Page keys and pointer selection explicitly owned elsewhere', () => {+ expect(CALENDAR_EXCLUSIONS.map(exclusion => exclusion.id)).toEqual([+ 'month-edge-crossing',+ 'disabled-day-arrows',+ 'page-keys-and-pointer',+ ]);+ for (const exclusion of CALENDAR_EXCLUSIONS) {+ expect(exclusion.owner.length, exclusion.id).toBeGreaterThan(20);+ expect(exclusion.reason.length, exclusion.id).toBeGreaterThan(80);+ }+ });++ it('renders the named grid and the whole start neighbourhood for every state', () => {+ for (const state of CALENDAR_BINDING_STATES) {+ render(renderCalendarState(state));+ expect(grid(state), state.id).toBeTruthy();+ expect(Object.keys(related()), state.id).toHaveLength(8);+ cleanup();+ }+ });+});