An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): add Landmark contract bound to Layout regions (#7102)
Cindy Zhangf4ae1e7ecb97
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ff6cbab25f..4adf63fb3b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1331,6 +1331,50 @@ jobs:retention-days: 30if-no-files-found: warn+ # The landmark contract's role, name, and repeated-label outcomes are+ # accessibility-tree facts that jsdom cannot observe. Run the contract's+ # own fixture proof and the Layout regions binding whenever Layout 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 Landmark accessibility contract+ id: landmark-contract+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}+ env:+ BASE_SHA: ${{ github.event.pull_request.base.sha }}+ PLAYWRIGHT_JSON_OUTPUT_FILE: landmark-contract/report.json+ run: |+ should_run=false+ # Layout and the contract are matched by file name so every Layout+ # region component is covered. If the base cannot be fetched, run.+ if git fetch --quiet --depth=1 origin "$BASE_SHA"; then+ if git diff --name-only "$BASE_SHA" HEAD \+ | grep -qE '^(internal/a11y-spec/src/patterns/landmark|packages/core/src/Layout/|apps/storybook/stories/LayoutLandmarkA11y)'; then+ should_run=true+ fi+ else+ should_run=true+ fi+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"+ if [ "$should_run" != true ]; then+ echo "Layout and the landmark contract are not in PR scope; skipping landmark evidence."+ exit 0+ fi+ pnpm exec playwright test \+ internal/a11y-spec/src/patterns/landmark.chromium.spec.ts \+ packages/core/src/Layout/__tests__/Layout.a11y.chromium.spec.ts \+ --project chromium \+ --reporter list,json \+ --output landmark-contract-output++ - name: Upload Landmark accessibility contract evidence+ if: ${{ !cancelled() && steps.landmark-contract.outputs.should_run == 'true' }}+ uses: actions/upload-artifact@v7+ with:+ name: landmark-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: landmark-contract/+ retention-days: 30+ if-no-files-found: warn+# The Schedule time grid owns scroll geometry — pinned header and gutter# alignment under classic scrollbars, inline scroll ownership, keyboard# reach and its focus ring — none of which exists in jsdom. Everydiff --git a/apps/storybook/stories/LayoutLandmarkA11y.stories.tsx b/apps/storybook/stories/LayoutLandmarkA11y.stories.tsxnew file mode 100644index 0000000000..49cca8e4c4--- /dev/null+++ b/apps/storybook/stories/LayoutLandmarkA11y.stories.tsx@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** One checked-in Storybook fixture for every Layout regions landmark state. */++import type {Meta, StoryObj} from '@storybook/react';+import {LAYOUT_LANDMARK_A11Y_RENDERS} from '../../../packages/core/src/Layout/__tests__/Layout.a11y.renders';+import {LAYOUT_LANDMARK_A11Y_STATES} from '../../../packages/core/src/Layout/__tests__/Layout.a11y.states';++function storyFor(+ id: (typeof LAYOUT_LANDMARK_A11Y_STATES)[number]['id'],+): StoryObj {+ const state = LAYOUT_LANDMARK_A11Y_STATES.find(+ candidate => candidate.id === id,+ );+ if (state == null) {+ throw new Error(`no Layout regions binding state "${id}"`);+ }+ return {+ name: `${state.region} — ${state.id}`,+ render: () => LAYOUT_LANDMARK_A11Y_RENDERS[state.id](),+ };+}++const meta: Meta = {+ title: 'a11y/Landmark pattern',+ tags: ['no-visual'],+ parameters: {layout: 'padded'},+};++export default meta;++export const HeaderBanner = storyFor('header-banner');+export const ContentMain = storyFor('content-main');+export const FooterContentinfo = storyFor('footer-contentinfo');+export const StartEndNavigationRtl = storyFor('start-end-navigation-rtl');+export const NestedPanelRegion = storyFor('nested-panel-region');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex 6f0bdf123d..7ae934f15f 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -51,26 +51,28 @@ src/├── listbox.* listbox, group, and option semantics├── spinbutton.* numeric role, value, bounds, state, and arrow stepping├── disclosure.* standalone disclosure state/content semantics- └── breadcrumb.* landmark, list-trail, current-page, and separator semantics+ ├── breadcrumb.* landmark, list-trail, current-page, and separator semantics+ └── landmark.* one component-owned landmark region's role, name, and content boundary```## The patterns-| Pattern | Adopted from | Bound by |-| ---------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |-| `radio-group` | [APG radio group](https://www.w3.org/WAI/ARIA/apg/patterns/radio/) | RadioList, SegmentedControl; role/state portions of DropdownMenu radio items |-| `checkbox` | [APG checkbox](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/) | CheckboxInput, CheckboxListItem, DropdownMenuCheckboxItem, SelectableCard |-| `switch` | [APG switch](https://www.w3.org/WAI/ARIA/apg/patterns/switch/) | Switch |-| `button` | [APG button](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | Button, IconButton, ClickableCard, SideNavCollapseButton, ChatSendButton |-| `toggle-button` | Toggle-button semantics in the [APG button pattern](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | ToggleButton, including standalone and grouped states |-| `text-input` | Native HTML controls and [WAI-ARIA textbox](https://www.w3.org/TR/wai-aria-1.2/#textbox) | TextInput, TextArea |-| `modal-dialog` | [APG dialog (modal)](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/) | Dialog |-| `status-message` | [WCAG 2.2 Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html) | Toast, FieldStatus, Spinner, ChatSystemMessage, ChatTypingIndicator, ProgressBar |-| `tabs` | [APG Tabs](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/) | Explicit `role="tablist"` TabList, Tab, and caller-authored tabpanels |-| `listbox` | [WAI-ARIA 1.2 Listbox](https://www.w3.org/TR/wai-aria-1.2/#listbox) and WCAG 2.2 semantics | Selector and MultiSelector popup listbox, group, and option parts |-| `spinbutton` | WCAG 2.2 semantics and [APG Spinbutton](https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/) | NumberInput |-| `disclosure` | [APG Disclosure](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/) | Standalone Collapsible triggers and their controlled content |-| `breadcrumb` | WCAG 2.2 semantics; [APG Breadcrumb](https://www.w3.org/WAI/ARIA/apg/patterns/breadcrumb/) as context | Breadcrumbs landmarks, list trails, current-page state, and separators |+| Pattern | Adopted from | Bound by |+| ---------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |+| `radio-group` | [APG radio group](https://www.w3.org/WAI/ARIA/apg/patterns/radio/) | RadioList, SegmentedControl; role/state portions of DropdownMenu radio items |+| `checkbox` | [APG checkbox](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/) | CheckboxInput, CheckboxListItem, DropdownMenuCheckboxItem, SelectableCard |+| `switch` | [APG switch](https://www.w3.org/WAI/ARIA/apg/patterns/switch/) | Switch |+| `button` | [APG button](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | Button, IconButton, ClickableCard, SideNavCollapseButton, ChatSendButton |+| `toggle-button` | Toggle-button semantics in the [APG button pattern](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | ToggleButton, including standalone and grouped states |+| `text-input` | Native HTML controls and [WAI-ARIA textbox](https://www.w3.org/TR/wai-aria-1.2/#textbox) | TextInput, TextArea |+| `modal-dialog` | [APG dialog (modal)](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/) | Dialog |+| `status-message` | [WCAG 2.2 Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html) | Toast, FieldStatus, Spinner, ChatSystemMessage, ChatTypingIndicator, ProgressBar |+| `tabs` | [APG Tabs](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/) | Explicit `role="tablist"` TabList, Tab, and caller-authored tabpanels |+| `listbox` | [WAI-ARIA 1.2 Listbox](https://www.w3.org/TR/wai-aria-1.2/#listbox) and WCAG 2.2 semantics | Selector and MultiSelector popup listbox, group, and option parts |+| `spinbutton` | WCAG 2.2 semantics and [APG Spinbutton](https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/) | NumberInput |+| `disclosure` | [APG Disclosure](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/) | Standalone Collapsible triggers and their controlled content |+| `breadcrumb` | WCAG 2.2 semantics; [APG Breadcrumb](https://www.w3.org/WAI/ARIA/apg/patterns/breadcrumb/) as context | Breadcrumbs landmarks, list trails, current-page state, and separators |+| `landmark` | WCAG 2.2 semantics; [APG Landmark Regions](https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/) as context | LayoutHeader, LayoutContent, LayoutFooter, and LayoutPanel caller-declared landmarks |The toggle-button contract owns the persistent-action extension of buttonsemantics: the pressed state must be exposed, reversible by pointer, Enter, and@@ -104,6 +106,16 @@ no-current-page opt-out. Link, action-button, and sibling-menu semantics staywith their own patterns; the APG Breadcrumb page remains context because nocurrent Astryx record adopts it as an additional required gate.+The landmark contract owns one component-owned landmark region: the role the+binding declares, the label it declares, and the content the region bounds. It+reports the APG unique-label principle for same-role peers as advisory because+no current Astryx record adopts it as a gate. Its first binding covers the four+Layout region components with caller-supplied roles and labels, including+repeated navigation panels under RTL and a region nested in a main landmark.+Role-less regions, one main landmark per page, top-level placement, and whether+all page content sits in a landmark stay with Layout's own tests, the page, and+AppShell; an isolated region never claims page-wide landmark completeness.+The `listbox` contract is a bounded semantic migration, not blanket APGinteraction adoption. Its first bindings cover 21 existing scenarios acrosssingle/multiple selection, disabled options, groups, filtering, custom content,diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.tsindex 95611c10da..9538790fea 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -132,3 +132,9 @@ export {BREADCRUMB_PATTERN,type BreadcrumbStateFacts,} from './patterns/breadcrumb';++export {+ LANDMARK_PATTERN,+ type LandmarkRole,+ type LandmarkStateFacts,+} from './patterns/landmark';diff --git a/internal/a11y-spec/src/patterns/landmark.chromium.spec.ts b/internal/a11y-spec/src/patterns/landmark.chromium.spec.tsnew file mode 100644index 0000000000..507fc089b0--- /dev/null+++ b/internal/a11y-spec/src/patterns/landmark.chromium.spec.ts@@ -0,0 +1,106 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Real-browser positive and mutation proof for the Landmark contract. */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ 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 {LANDMARK_PATTERN} from './landmark';+import {+ CONFORMING_LANDMARK_FIXTURES,+ LANDMARK_CONTENT_SELECTOR,+ LANDMARK_MUTATIONS,+ LANDMARK_PEER_SELECTOR,+ LANDMARK_SUBJECT_SELECTOR,+ landmarkFixture,+ type LandmarkFixture,+} from './landmark.fixtures';++function fixturePage(html: string): string {+ return `<!doctype html><html lang="en"><body>${html}</body></html>`;+}++async function results(+ page: Page,+ cdp: CDPSession,+ target: LandmarkFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ const run = await checkAccessibilitySpec({+ spec: LANDMARK_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ only,+ mount: async () => {+ await page.setContent(fixturePage(target.html));+ await holdMotionStill(page);+ const related: Record<string, Locator> = {+ content: page.locator(LANDMARK_CONTENT_SELECTOR),+ };+ const peers = page.locator(LANDMARK_PEER_SELECTOR);+ for (let index = 0; index < target.facts.sameRolePeers; index += 1) {+ related[`peer-${index}`] = peers.nth(index);+ }+ return createChromiumHarness({+ page,+ cdp,+ subject: page.locator(LANDMARK_SUBJECT_SELECTOR),+ related,+ });+ },+ });+ return run.results;+}++test.describe('Landmark contract — conforming fixtures', () => {+ for (const id of CONFORMING_LANDMARK_FIXTURES) {+ test(`${id}: every applicable expectation passes`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const observed = await results(page, cdp, landmarkFixture(id));+ expect(+ observed+ .filter(+ result =>+ result.status !== 'pass' && result.status !== 'not-applicable',+ )+ .map(result => `${result.expectation}: ${result.detail ?? ''}`),+ ).toEqual([]);+ });+ }+});++test.describe('Landmark contract — deliberately violating fixtures', () => {+ for (const expectation of LANDMARK_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of LANDMARK_MUTATIONS[expectation.id] ?? []) {+ test(`${describeExpectation(expectation)} — fails against ${fixtureId}`, async ({+ page,+ }) => {+ const cdp = await page.context().newCDPSession(page);+ const [result] = await results(page, cdp, landmarkFixture(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/landmark.fixtures.ts b/internal/a11y-spec/src/patterns/landmark.fixtures.tsnew file mode 100644index 0000000000..30b99b13e5--- /dev/null+++ b/internal/a11y-spec/src/patterns/landmark.fixtures.ts@@ -0,0 +1,144 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Plain-HTML positive and mutation fixtures for the Landmark contract. */++import type {LandmarkStateFacts} from './landmark';++export const LANDMARK_SUBJECT_SELECTOR = '[data-a11y-landmark]';+export const LANDMARK_CONTENT_SELECTOR = '[data-a11y-landmark-content]';+export const LANDMARK_PEER_SELECTOR = '[data-a11y-landmark-peer]';++export interface LandmarkFixture {+ readonly id: string;+ readonly summary: string;+ readonly facts: LandmarkStateFacts;+ readonly html: string;+}++function facts(+ overrides: Partial<LandmarkStateFacts> = {},+): LandmarkStateFacts {+ return {+ role: 'navigation',+ label: 'Project sections',+ sameRolePeers: 0,+ ...overrides,+ };+}++function attributes(role: string | null, label: string | null): string {+ return [+ role == null ? '' : `role="${role}"`,+ label == null ? '' : `aria-label="${label}"`,+ ].join(' ');+}++interface Options {+ readonly role?: string | null;+ readonly label?: string | null;+ readonly contentOutside?: boolean;+ readonly peerLabel?: string | null;+}++function html(options: Options = {}): string {+ const role = options.role === undefined ? 'navigation' : options.role;+ const label =+ options.label === undefined ? 'Project sections' : options.label;+ const content = '<p data-a11y-landmark-content>Region content</p>';+ const peer =+ options.peerLabel === undefined+ ? ''+ : `<div data-a11y-landmark-peer ${attributes('navigation', options.peerLabel)}><p>Peer content</p></div>`;+ return `+ <div data-a11y-landmark ${attributes(role, label)}>+ ${options.contentOutside ? '' : content}+ </div>+ ${options.contentOutside ? content : ''}+ ${peer}+ `;+}++export const LANDMARK_FIXTURES: readonly LandmarkFixture[] = [+ {+ id: 'conforming-labelled',+ summary: 'an explicitly labelled navigation landmark around its content',+ facts: facts(),+ html: html(),+ },+ {+ id: 'conforming-unlabelled',+ summary: 'a main landmark whose binding declares no label',+ facts: facts({role: 'main', label: null}),+ html: html({role: 'main', label: null}),+ },+ {+ id: 'conforming-repeated-distinct',+ summary: 'two navigation landmarks with distinct labels',+ facts: facts({sameRolePeers: 1}),+ html: html({peerLabel: 'Page outline'}),+ },+ {+ id: 'violating-role-missing',+ summary: 'a labelled generic container instead of a landmark',+ facts: facts(),+ html: html({role: null}),+ },+ {+ id: 'violating-role-wrong',+ summary: 'a complementary landmark where navigation was declared',+ facts: facts(),+ html: html({role: 'complementary'}),+ },+ {+ id: 'violating-name-missing',+ summary: 'a navigation landmark that drops its declared label',+ facts: facts(),+ html: html({label: null}),+ },+ {+ id: 'violating-name-wrong',+ summary: 'a navigation landmark exposing a different label',+ facts: facts(),+ html: html({label: 'Sections'}),+ },+ {+ id: 'violating-content-outside',+ summary: 'an empty landmark beside the content it should contain',+ facts: facts(),+ html: html({contentOutside: true}),+ },+ {+ id: 'violating-peer-duplicate-name',+ summary: 'two navigation landmarks sharing one label',+ facts: facts({sameRolePeers: 1}),+ html: html({peerLabel: 'Project sections'}),+ },+ {+ id: 'violating-peer-unnamed',+ summary: 'a repeated navigation landmark with no label',+ facts: facts({sameRolePeers: 1}),+ html: html({peerLabel: null}),+ },+];++export const CONFORMING_LANDMARK_FIXTURES = LANDMARK_FIXTURES.filter(fixture =>+ fixture.id.startsWith('conforming-'),+).map(fixture => fixture.id);++export const LANDMARK_MUTATIONS: Readonly<Record<string, readonly string[]>> = {+ 'landmark.role.exposed': ['violating-role-missing', 'violating-role-wrong'],+ 'landmark.name.exposed': ['violating-name-missing', 'violating-name-wrong'],+ 'landmark.content.contained': ['violating-content-outside'],+ 'landmark.peers.distinct-names': [+ 'violating-peer-duplicate-name',+ 'violating-peer-unnamed',+ ],+};++export function landmarkFixture(id: string): LandmarkFixture {+ const fixture = LANDMARK_FIXTURES.find(candidate => candidate.id === id);+ if (fixture == null) {+ throw new Error(`unknown Landmark fixture "${id}"`);+ }+ return fixture;+}diff --git a/internal/a11y-spec/src/patterns/landmark.jsdom.test.ts b/internal/a11y-spec/src/patterns/landmark.jsdom.test.tsnew file mode 100644index 0000000000..ff864e91cf--- /dev/null+++ b/internal/a11y-spec/src/patterns/landmark.jsdom.test.ts@@ -0,0 +1,162 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/** Contract self-tests for Landmark DOM expectations and completeness. */++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 {LANDMARK_PATTERN} from './landmark';+import {+ CONFORMING_LANDMARK_FIXTURES,+ LANDMARK_CONTENT_SELECTOR,+ LANDMARK_MUTATIONS,+ LANDMARK_PEER_SELECTOR,+ LANDMARK_SUBJECT_SELECTOR,+ landmarkFixture,+ type LandmarkFixture,+} from './landmark.fixtures';++afterEach(() => document.body.replaceChildren());++async function resultsFor(target: LandmarkFixture) {+ const container = document.createElement('div');+ document.body.append(container);+ const run = await checkAccessibilitySpec({+ spec: LANDMARK_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ mount: async () => {+ container.innerHTML = target.html;+ const subject = container.querySelector(LANDMARK_SUBJECT_SELECTOR);+ const content = container.querySelector(LANDMARK_CONTENT_SELECTOR);+ if (subject == null || content == null) {+ throw new Error(+ `fixture "${target.id}" is missing its landmark or content`,+ );+ }+ const related: Record<string, Element> = {content};+ container+ .querySelectorAll(LANDMARK_PEER_SELECTOR)+ .forEach((peer, index) => {+ related[`peer-${index}`] = peer;+ });+ return createJsdomHarness({subject, related});+ },+ unmount: () => {+ container.innerHTML = '';+ },+ });+ return run.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;+}++const observableHere = LANDMARK_PATTERN.expectations.filter(expectation =>+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),+);++describe('Landmark contract — completeness', () => {+ it('answers every completeness dimension', () => {+ expect(unansweredDimensions(LANDMARK_PATTERN)).toEqual([]);+ });++ it('gives every expectation at least one deliberately violating fixture', () => {+ expect(+ LANDMARK_PATTERN.expectations+ .filter(+ expectation =>+ (LANDMARK_MUTATIONS[expectation.id] ?? []).length === 0,+ )+ .map(expectation => expectation.id),+ ).toEqual([]);+ });++ it('has an expectation for every mutation it records', () => {+ const ids = new Set(+ LANDMARK_PATTERN.expectations.map(expectation => expectation.id),+ );+ expect(Object.keys(LANDMARK_MUTATIONS).filter(id => !ids.has(id))).toEqual(+ [],+ );+ });++ it('keeps the APG-only repeated-label outcome advisory', () => {+ const peers = LANDMARK_PATTERN.expectations.find(+ expectation => expectation.id === 'landmark.peers.distinct-names',+ );+ expect(peers?.enforcement).toBe('advisory');+ expect(+ LANDMARK_PATTERN.expectations+ .filter(expectation => expectation.id !== peers?.id)+ .every(expectation => expectation.enforcement === 'required'),+ ).toBe(true);+ });+});++describe('Landmark contract — the jsdom harness stays within its evidence boundary', () => {+ it('runs DOM expectations and reports accessibility-tree expectations as unrun', async () => {+ const results = await resultsFor(landmarkFixture('conforming-labelled'));+ expect(results.some(result => result.status === 'pass')).toBe(true);+ const unrun = results.filter(result => result.status === 'unrun');+ expect(unrun.length).toBeGreaterThan(0);+ for (const result of unrun) {+ expect(result.missingLayers).toContain('accessibility-tree');+ }+ });+});++describe.each(observableHere.map(expectation => [expectation.id] as const))(+ '%s',+ id => {+ const expectation = LANDMARK_PATTERN.expectations.find(+ candidate => candidate.id === id,+ )!;++ it.each(CONFORMING_LANDMARK_FIXTURES.map(name => [name] as const))(+ 'passes against %s (or does not apply to it)',+ async name => {+ const result = resultFor(await resultsFor(landmarkFixture(name)), id);+ expect(+ ['pass', 'not-applicable'],+ `${id} against ${name}: ${result.detail ?? ''}`,+ ).toContain(result.status);+ },+ );++ it.each((LANDMARK_MUTATIONS[id] ?? []).map(name => [name] as const))(+ 'fails against %s, which removes its outcome',+ async name => {+ const result = resultFor(await resultsFor(landmarkFixture(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 = landmarkFixture(+ LANDMARK_MUTATIONS[id]?.[0] ?? CONFORMING_LANDMARK_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/landmark.ts b/internal/a11y-spec/src/patterns/landmark.tsnew file mode 100644index 0000000000..ba90497b53--- /dev/null+++ b/internal/a11y-spec/src/patterns/landmark.ts@@ -0,0 +1,385 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file landmark.ts+ * @input Uses the shared accessibility-contract vocabulary+ * @output LANDMARK_PATTERN, LandmarkRole, and LandmarkStateFacts+ * @position Reusable semantic contract for one component-owned landmark region+ * that a binding exposes with a role and, when declared, a label. Page-wide+ * landmark completeness stays with the page.+ *+ * The required slice is derived from WCAG 2.2. The APG Landmark Regions+ * guidance is contextual: its unique-label principle is reported as advisory+ * because no current Astryx record adopts it as a gate.+ */++import {+ definePattern,+ type ApgRequirement,+ type PatternContract,+ type WcagCriterion,+} from '../contract';++const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/';+const APG_PRINCIPLES_URL =+ 'https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/examples/general-principles.html';+const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';++function wcag(+ id: string,+ name: string,+ level: 'A' | 'AA',+ slug: string,+): WcagCriterion {+ return {+ standard: 'wcag',+ id,+ name,+ level,+ url: `${UNDERSTANDING}/${slug}.html`,+ };+}++const WCAG_1_3_1 = wcag(+ '1.3.1',+ 'Info and Relationships',+ 'A',+ 'info-and-relationships',+);+const WCAG_2_4_6 = wcag(+ '2.4.6',+ 'Headings and Labels',+ 'AA',+ 'headings-and-labels',+);++const APG_UNIQUE_LABEL: ApgRequirement = {+ standard: 'apg',+ pattern: 'landmarks',+ requirement:+ 'If a specific landmark role is used more than once on a web page, it should have a unique label.',+ url: APG_PRINCIPLES_URL,+};++/** The WAI-ARIA landmark roles a binding may declare. */+export type LandmarkRole =+ | 'banner'+ | 'complementary'+ | 'contentinfo'+ | 'form'+ | 'main'+ | 'navigation'+ | 'region'+ | 'search';++export interface LandmarkStateFacts {+ /** The landmark role the binding declares for this region. */+ readonly role: LandmarkRole;+ /** The accessible name the binding declares, or null when it declares none. */+ readonly label: string | null;+ /**+ * How many other landmarks with the same role the binding renders in the+ * same bounded composition. Each is supplied as a `peer-<index>` relation.+ */+ readonly sameRolePeers: number;+}++function describeRole(role: string | null): string {+ return role == null ? 'no role' : `"${role}"`;+}++function describeName(name: string): string {+ return name === '' ? 'no name' : `"${name}"`;+}++export const LANDMARK_PATTERN: PatternContract<LandmarkStateFacts> =+ definePattern<LandmarkStateFacts>({+ pattern: 'landmark',+ url: APG_URL,+ scope:+ 'One component-owned landmark region: its exposed role, its declared label, the content it bounds, and how it is told apart from same-role peers in one bounded composition.',+ expectations: [+ {+ id: 'landmark.role.exposed',+ outcome:+ 'The browser exposes the region with the landmark role the binding declares, so people navigating by landmark can find it.',+ sources: [WCAG_1_3_1],+ covers: ['1.3.1-info-and-relationships'],+ appliesWhen: {+ condition: 'the binding declares a landmark role for the region',+ test: () => true,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const {role} = await subject.computed();+ if (role !== facts.role) {+ throw new Error(+ `the browser exposes ${describeRole(role)} instead of the declared "${facts.role}" landmark`,+ );+ }+ },+ },+ {+ id: 'landmark.name.exposed',+ outcome:+ 'When the binding declares a label, the landmark computes exactly that name, so people can tell what the region is for.',+ sources: [WCAG_1_3_1, WCAG_2_4_6],+ covers: ['1.3.1-info-and-relationships', '2.4.6-headings-and-labels'],+ appliesWhen: {+ condition: 'the binding declares a label for the landmark',+ test: facts => facts.label != null,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const {name} = await subject.computed();+ if (name !== facts.label) {+ throw new Error(+ `the landmark should be named "${facts.label}", but the browser computes ${describeName(name)}`,+ );+ }+ },+ },+ {+ id: 'landmark.content.contained',+ outcome:+ 'The content the region presents sits inside the landmark, so moving to the landmark reaches that content.',+ sources: [WCAG_1_3_1],+ covers: ['1.3.1-info-and-relationships'],+ appliesWhen: {+ condition: 'the binding renders content inside the region',+ test: () => true,+ },+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({harness, subject}) => {+ const content = await harness.related('content');+ if (!(await harness.contains(subject, content))) {+ throw new Error(+ 'the region content is outside its landmark element',+ );+ }+ },+ },+ {+ id: 'landmark.peers.distinct-names',+ outcome:+ 'Landmarks that share a role in the same composition each have a different, non-empty name, so people can tell them apart.',+ sources: [APG_UNIQUE_LABEL],+ wcagOutcome:+ 'Supports WCAG 2.2 1.3.1 Info and Relationships by keeping repeated regions of one kind programmatically distinguishable.',+ covers: ['apg-interaction'],+ appliesWhen: {+ condition:+ 'the binding renders another landmark with the same role in the same composition',+ test: facts => facts.sameRolePeers > 0,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'advisory',+ advisoryBecause:+ 'WCAG 2.2 A/AA has no success criterion that directly requires distinct names for repeated same-role landmarks, and no current Astryx record adopts the APG unique-label principle as a gate.',+ run: async ({harness, subject, facts}) => {+ const own = await subject.computed();+ const names = [own.name];+ for (let index = 0; index < facts.sameRolePeers; index += 1) {+ const peer = await (+ await harness.related(`peer-${index}`)+ ).computed();+ if (peer.role !== facts.role) {+ throw new Error(+ `peer ${index + 1} exposes ${describeRole(peer.role)}, not the shared "${facts.role}" role the binding declares`,+ );+ }+ names.push(peer.name);+ }+ const unnamed = names.filter(name => name === '').length;+ if (unnamed > 0) {+ throw new Error(+ `${unnamed} of ${names.length} "${facts.role}" landmarks have no name`,+ );+ }+ const repeated = names.filter(+ (name, index) => names.indexOf(name) !== index,+ );+ if (repeated.length > 0) {+ throw new Error(+ `${names.length} "${facts.role}" landmarks repeat the name ${[+ ...new Set(repeated),+ ]+ .map(name => `"${name}"`)+ .join(', ')}`,+ );+ }+ },+ },+ ],+ exemptions: {+ '1.1.1-non-text-content': {+ owner: 'Caller content placed in the region',+ verifiedBy: 'Content review and the repository axe audit',+ reason:+ 'A landmark adds no non-text content of its own; images and icons inside it belong to their content owners.',+ },+ '1.3.1-info-and-relationships': {+ owner: 'The composing page and caller content',+ verifiedBy: 'Page-level landmark review and the repository axe audit',+ reason:+ 'This contract encodes one region role, its declared name, and its content boundary. Whether all perceivable page content sits in a landmark, whether the page has exactly one main landmark, and whether banner and contentinfo are top level are page outcomes an isolated region cannot satisfy.',+ coversRemainderOnly: true,+ },+ '1.3.2-meaningful-sequence': {+ owner: 'The binding and the composing page',+ verifiedBy: 'Component DOM-order tests and page reading-order review',+ reason:+ 'Region order follows the binding’s slot order and the page’s composition, not the landmark semantics.',+ },+ '1.3.5-identify-input-purpose': {+ owner: 'Form controls inside the region',+ verifiedBy: 'Text-input contract bindings and form review',+ reason: 'A landmark collects no information about the user.',+ },+ '1.4.1-use-of-color': {+ owner: 'The binding and the active theme',+ verifiedBy: 'Rendered review and the repository visual gate',+ reason:+ 'Region boundaries and dividers are paint outcomes outside this semantic contract.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'Caller content and the active theme',+ verifiedBy: 'Rendered contrast audit',+ reason: 'Text contrast depends on resolved colors and backdrop.',+ },+ '1.4.11-non-text-contrast': {+ owner: 'The binding and the active theme',+ verifiedBy: 'Rendered boundary and divider contrast review',+ reason: 'Any region boundary or divider is a paint outcome.',+ },+ '2.1.1-keyboard': {+ owner:+ 'Assistive technology and the pattern owners of interactive content',+ verifiedBy:+ 'Real-AT review under AST-009 and each interactive part’s contract',+ reason:+ 'Landmark navigation keys are provided by assistive technology; the region adds no keyboard interaction of its own.',+ },+ '2.1.2-no-keyboard-trap': {+ owner: 'Interactive content and the composing page',+ verifiedBy: 'Their contracts and page-level keyboard review',+ reason: 'A landmark region cannot trap focus.',+ },+ '2.4.2-page-titled': {+ owner: 'The page',+ verifiedBy: 'Page-level title review',+ reason: 'A region does not own the document title.',+ },+ '2.4.3-focus-order': {+ owner: 'The binding and the composing page',+ verifiedBy: 'Real-browser keyboard-order review',+ reason:+ 'Sequential focus depends on the controls placed in the region and the page’s composition.',+ },+ '2.4.4-link-purpose': {+ owner: 'The link pattern and caller content',+ verifiedBy: 'Link contract bindings plus content review',+ reason: 'A landmark contains links but does not define their purpose.',+ },+ '2.4.6-headings-and-labels': {+ owner: 'Caller-provided landmark labels',+ verifiedBy: 'Content review of each landmark label',+ reason:+ 'This contract proves the landmark computes the declared name, not that the caller’s wording describes the region or avoids repeating the role.',+ coversRemainderOnly: true,+ },+ '2.4.7-focus-visible': {+ owner: 'Interactive content and the active theme',+ verifiedBy: 'Rendered keyboard-focus review',+ reason: 'A landmark is not focusable; focus paint belongs to controls.',+ },+ '2.4.11-focus-not-obscured': {+ owner: 'The binding, the composing page, and the overlay system',+ verifiedBy: 'Constrained-viewport and sticky-region browser review',+ reason:+ 'Whether a sticky or scrolling region hides focused content depends on layout, not landmark semantics.',+ },+ '2.5.2-pointer-cancellation': {+ owner: 'Interactive content pattern owners',+ verifiedBy: 'Their pointer activation tests',+ reason: 'A landmark has no pointer action.',+ },+ '2.5.3-label-in-name': {+ owner: 'Interactive content pattern owners',+ verifiedBy: 'Their visible-label versus computed-name checks',+ reason:+ 'A landmark is not a labelled user-interface component; label-in-name applies to the controls inside it.',+ },+ '2.5.8-target-size': {+ owner: 'Interactive content and the composing page',+ verifiedBy: 'Rendered target geometry review',+ reason: 'A landmark has no pointer target.',+ },+ '3.1.1-language-of-page': {+ owner: 'The page and localization provider',+ verifiedBy: 'Document-language checks',+ reason: 'A region does not own the document language.',+ },+ '3.2.2-on-input': {+ owner: 'Interactive content pattern owners',+ verifiedBy: 'Role-specific interaction tests',+ reason: 'A landmark has no input event.',+ },+ '3.2.4-consistent-identification': {+ owner: 'The design system and caller content',+ verifiedBy: 'Cross-page review of repeated landmark labels',+ reason:+ 'Consistency is a property of repeated pages and regions, not one isolated binding.',+ },+ '3.3.1-error-identification': {+ owner: 'The composing form',+ verifiedBy: 'Form-level error review',+ reason: 'A landmark defines no validation error state.',+ },+ '3.3.2-labels-or-instructions': {+ owner: 'Form controls inside the region',+ verifiedBy: 'Form-level label and instruction review',+ reason: 'A landmark is not a form input.',+ },+ '4.1.2-name-role-value': {+ owner: 'Interactive content pattern owners',+ verifiedBy: 'Their reusable contracts and component tests',+ reason:+ 'A landmark is a structural region rather than a user-interface component; its role and name are encoded here under 1.3.1, and controls inside it keep their own patterns.',+ },+ '4.1.3-status-messages': {+ owner: 'The status-message pattern and caller content',+ verifiedBy:+ 'Status-message tests and AST-009 when spoken timing is claimed',+ reason: 'Rendering a landmark is not a status message.',+ },+ 'apg-interaction': {+ owner: 'Assistive technology and each binding’s current authority',+ verifiedBy:+ 'Real-AT review under AST-009; the advisory unique-label expectation here',+ reason:+ 'APG Landmark Regions defines no widget keyboard interaction. This contract reports its unique-label principle as advisory; its other structural guidance, such as top-level placement and labels that omit the role name, stays with the page and caller content because no current Astryx record adopts it as a gate.',+ coversRemainderOnly: true,+ },+ 'forced-colors': {+ owner: 'The binding and the active theme',+ verifiedBy: 'Rendered forced-colors review',+ reason: 'Semantic exposure does not prove forced-colors paint.',+ },+ 'reduced-motion': {+ owner: 'The binding and its content',+ verifiedBy: 'Component motion tests and rendered review',+ reason: 'Landmark semantics add no motion.',+ },+ 'at-facing-strings': {+ owner: 'The binding’s localization and caller-provided labels',+ verifiedBy:+ 'Catalog checks and localized component tests; AST-009 for speech claims',+ reason:+ 'The contract verifies a deterministic computed name without claiming spoken wording, order, or timing.',+ },+ },+ });diff --git a/packages/core/src/Layout/__tests__/Layout.a11y.chromium.spec.ts b/packages/core/src/Layout/__tests__/Layout.a11y.chromium.spec.tsnew file mode 100644index 0000000000..53a03519d6--- /dev/null+++ b/packages/core/src/Layout/__tests__/Layout.a11y.chromium.spec.ts@@ -0,0 +1,121 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Real-browser and accessibility-tree binding evidence for Layout regions. */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ LANDMARK_PATTERN,+ blockingResults,+ checkAccessibilitySpec,+ formatFailures,+ neverExercised,+ summarize,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {+ createChromiumHarness,+ holdMotionStill,+} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';+import {+ LAYOUT_LANDMARK_A11Y_STATES,+ type LayoutLandmarkA11yRow,+} from './Layout.a11y.states';++const SUBJECT_SELECTOR = '[data-a11y-landmark]';+const CONTENT_SELECTOR = '[data-a11y-landmark-content]';+const PEER_SELECTOR = '[data-a11y-landmark-peer]';+let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => storybook?.close());++function storyUrl(id: string): string {+ return `${storybook.origin}/iframe.html?id=${id}&viewMode=story`;+}++function relatedFor(+ page: Page,+ state: LayoutLandmarkA11yRow,+): Record<string, Locator> {+ const related: Record<string, Locator> = {+ content: page.locator(CONTENT_SELECTOR),+ };+ const peers = page.locator(PEER_SELECTOR);+ for (let index = 0; index < state.facts.sameRolePeers; index += 1) {+ related[`peer-${index}`] = peers.nth(index);+ }+ return related;+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: LayoutLandmarkA11yRow,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: LANDMARK_PATTERN,+ binding: 'Layout regions',+ state: state.id,+ facts: state.facts,+ mount: async () => {+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});+ await holdMotionStill(page);+ const subject = page.locator(SUBJECT_SELECTOR);+ await subject.waitFor({state: 'attached'});+ await expect(subject).toHaveCount(1);+ await expect(page.locator(PEER_SELECTOR)).toHaveCount(+ state.facts.sameRolePeers,+ );+ return createChromiumHarness({+ page,+ cdp,+ subject,+ related: relatedFor(page, state),+ });+ },+ });+}++test('every Landmark expectation is exercised by at least one Layout state', async ({+ page,+}) => {+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of LAYOUT_LANDMARK_A11Y_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(neverExercised(results)).toEqual([]);+});++for (const state of LAYOUT_LANDMARK_A11Y_STATES) {+ test(`Layout regions [${state.id}] — ${state.summary}`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(LANDMARK_PATTERN, [result]);+ expect(formatFailures(blockingResults([result]))).toBe('');+ expect(+ result.results+ .filter(row => row.status === 'fail')+ .map(row => `${row.expectation}: ${row.detail ?? ''}`),+ 'advisory failures are reported, and this binding expects none',+ ).toEqual([]);+ expect(report.unrunLayers).toEqual([]);+ expect(report.counts.unexpectedPass).toBe(0);+ });+}diff --git a/packages/core/src/Layout/__tests__/Layout.a11y.renders.tsx b/packages/core/src/Layout/__tests__/Layout.a11y.renders.tsxnew file mode 100644index 0000000000..a8a18250c9--- /dev/null+++ b/packages/core/src/Layout/__tests__/Layout.a11y.renders.tsx@@ -0,0 +1,110 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/** Stable Layout region renders shared by jsdom, Storybook, and Chromium. */++import type {ReactElement} from 'react';+import {Layout} from '../Layout';+import {LayoutContent} from '../LayoutContent';+import {LayoutFooter} from '../LayoutFooter';+import {LayoutHeader} from '../LayoutHeader';+import {LayoutPanel} from '../LayoutPanel';+import type {LayoutLandmarkA11yRow} from './Layout.a11y.states';++function Body({children = 'Project body'}: {children?: string}) {+ return <LayoutContent>{children}</LayoutContent>;+}++export const LAYOUT_LANDMARK_A11Y_RENDERS: Readonly<+ Record<LayoutLandmarkA11yRow['id'], () => ReactElement>+> = {+ 'header-banner': () => (+ <Layout+ height="auto"+ header={+ <LayoutHeader+ data-a11y-landmark+ hasDivider+ label="Product"+ role="banner">+ <span data-a11y-landmark-content>Product header</span>+ </LayoutHeader>+ }+ content={<Body />}+ />+ ),+ 'content-main': () => (+ <Layout+ height="auto"+ content={+ <LayoutContent data-a11y-landmark label="Project overview" role="main">+ <span data-a11y-landmark-content>Project body</span>+ </LayoutContent>+ }+ />+ ),+ 'footer-contentinfo': () => (+ <Layout+ height="auto"+ content={<Body />}+ footer={+ <LayoutFooter+ data-a11y-landmark+ hasDivider+ label="Legal and support"+ role="contentinfo">+ <span data-a11y-landmark-content>Terms and help</span>+ </LayoutFooter>+ }+ />+ ),+ 'start-end-navigation-rtl': () => (+ <div dir="rtl">+ <Layout+ height="auto"+ start={+ <LayoutPanel+ data-a11y-landmark+ hasDivider+ label="Project sections"+ role="navigation">+ <span data-a11y-landmark-content>Sections</span>+ </LayoutPanel>+ }+ content={<Body />}+ end={+ <LayoutPanel+ data-a11y-landmark-peer+ hasDivider+ label="Page outline"+ role="navigation">+ Outline+ </LayoutPanel>+ }+ />+ </div>+ ),+ 'nested-panel-region': () => (+ <Layout+ height="auto"+ content={+ <LayoutContent label="Project overview" role="main">+ <Layout+ height="auto"+ start={+ <LayoutPanel+ data-a11y-landmark+ hasDivider+ label="Filters"+ role="region">+ <span data-a11y-landmark-content>Status filters</span>+ </LayoutPanel>+ }+ content={<Body>Filtered results</Body>}+ />+ </LayoutContent>+ }+ />+ ),+};diff --git a/packages/core/src/Layout/__tests__/Layout.a11y.states.ts b/packages/core/src/Layout/__tests__/Layout.a11y.states.tsnew file mode 100644index 0000000000..10638521de--- /dev/null+++ b/packages/core/src/Layout/__tests__/Layout.a11y.states.ts@@ -0,0 +1,93 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** AST-021 state inventory for the Layout regions landmark binding. */++import type {LandmarkStateFacts} from '@astryxdesign/a11y-spec';++export interface LayoutLandmarkA11yState {+ readonly id:+ | 'header-banner'+ | 'content-main'+ | 'footer-contentinfo'+ | 'start-end-navigation-rtl'+ | 'nested-panel-region';+ readonly region:+ 'LayoutHeader' | 'LayoutContent' | 'LayoutFooter' | 'LayoutPanel';+ readonly summary: string;+ readonly facts: LandmarkStateFacts;+ readonly storyId: string;+}++export type LayoutLandmarkA11yRow =+ (typeof LAYOUT_LANDMARK_A11Y_STATES)[number];++const story = (id: string) => `a11y-landmark-pattern--${id}`;++export const LAYOUT_LANDMARK_A11Y_STATES = [+ {+ id: 'header-banner',+ region: 'LayoutHeader',+ summary: 'a header region with a caller-supplied banner role and label',+ facts: {role: 'banner', label: 'Product', sameRolePeers: 0},+ storyId: story('header-banner'),+ },+ {+ id: 'content-main',+ region: 'LayoutContent',+ summary: 'a content region with a caller-supplied main role and label',+ facts: {role: 'main', label: 'Project overview', sameRolePeers: 0},+ storyId: story('content-main'),+ },+ {+ id: 'footer-contentinfo',+ region: 'LayoutFooter',+ summary:+ 'a footer region with a caller-supplied contentinfo role and label',+ facts: {role: 'contentinfo', label: 'Legal and support', sameRolePeers: 0},+ storyId: story('footer-contentinfo'),+ },+ {+ id: 'start-end-navigation-rtl',+ region: 'LayoutPanel',+ summary:+ 'start and end panels that both declare navigation, told apart by label under RTL',+ facts: {role: 'navigation', label: 'Project sections', sameRolePeers: 1},+ storyId: story('start-end-navigation-rtl'),+ },+ {+ id: 'nested-panel-region',+ region: 'LayoutPanel',+ summary:+ 'a labelled region panel in a bounded Layout nested inside a main content region',+ facts: {role: 'region', label: 'Filters', sameRolePeers: 0},+ storyId: story('nested-panel-region'),+ },+] as const satisfies ReadonlyArray<LayoutLandmarkA11yState>;++export const LAYOUT_LANDMARK_A11Y_EXCLUSIONS = [+ {+ owner: 'family:layout-regions FR8 and LayoutSlots tests',+ reason:+ 'A region with no caller-supplied role exposes no landmark; that no-inference rule is Layout-specific behavior, not a shared landmark outcome, so unlabelled and role-less states are not bound here.',+ },+ {+ owner: 'LayoutSlots API tests',+ reason:+ 'Each region’s role and label props reaching its element are public-prop assertions under AST-021 FR5 and stay local.',+ },+ {+ owner: 'The composing page and AppShell',+ reason:+ 'One main landmark per page, top-level banner and contentinfo, all content inside landmarks, the skip link, and app-wide navigation are page-shell outcomes an isolated Layout cannot satisfy.',+ },+ {+ owner: 'Layout visual, RTL, and container-padding evidence',+ reason:+ 'Slot geometry, divider ownership, inset distribution, scrolling, content width, and mirrored placement require their existing component and rendered checks.',+ },+ {+ owner: 'AST-009',+ reason:+ 'This binding claims DOM and browser accessibility-tree exposure, not landmark navigation, speech, braille, or virtual-cursor behavior.',+ },+] as const;diff --git a/packages/core/src/Layout/__tests__/Layout.a11y.test.tsx b/packages/core/src/Layout/__tests__/Layout.a11y.test.tsxnew file mode 100644index 0000000000..dd7ad1ebc3--- /dev/null+++ b/packages/core/src/Layout/__tests__/Layout.a11y.test.tsx@@ -0,0 +1,142 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/** Fast DOM binding for Layout regions against the shared Landmark contract. */++import {cleanup, render} from '@testing-library/react';+import {describe, expect, it} from 'vitest';+import {+ LANDMARK_PATTERN,+ checkAccessibilitySpec,+ createJsdomHarness,+ expectAccessibilitySpec,+ summarize,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {LAYOUT_LANDMARK_A11Y_RENDERS} from './Layout.a11y.renders';+import {+ LAYOUT_LANDMARK_A11Y_EXCLUSIONS,+ LAYOUT_LANDMARK_A11Y_STATES,+ type LayoutLandmarkA11yRow,+} from './Layout.a11y.states';++const SUBJECT_SELECTOR = '[data-a11y-landmark]';+const CONTENT_SELECTOR = '[data-a11y-landmark-content]';+const PEER_SELECTOR = '[data-a11y-landmark-peer]';++function subjectFor(): HTMLElement {+ const subjects = document.querySelectorAll(SUBJECT_SELECTOR);+ if (subjects.length !== 1 || !(subjects[0] instanceof HTMLElement)) {+ throw new Error(+ `binding rendered ${subjects.length} landmark subjects instead of one`,+ );+ }+ return subjects[0];+}++function relatedFor(): Record<string, Element> {+ const content = document.querySelector(CONTENT_SELECTOR);+ if (content == null) {+ throw new Error('binding rendered no landmark content');+ }+ const related: Record<string, Element> = {content};+ document.querySelectorAll(PEER_SELECTOR).forEach((peer, index) => {+ related[`peer-${index}`] = peer;+ });+ return related;+}++async function checkState(+ state: LayoutLandmarkA11yRow,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: LANDMARK_PATTERN,+ binding: 'Layout regions',+ state: state.id,+ facts: state.facts,+ mount: async () => {+ render(LAYOUT_LANDMARK_A11Y_RENDERS[state.id]());+ return createJsdomHarness({+ subject: subjectFor(),+ related: relatedFor(),+ });+ },+ unmount: cleanup,+ });+}++describe('the shared Landmark pattern, jsdom lane', () => {+ it.each(+ LAYOUT_LANDMARK_A11Y_STATES.map(+ state => [`Layout regions [${state.id}]`, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectAccessibilitySpec({+ spec: LANDMARK_PATTERN,+ binding: 'Layout regions',+ state: state.id,+ facts: state.facts,+ render: () => {+ render(LAYOUT_LANDMARK_A11Y_RENDERS[state.id]());+ },+ subject: subjectFor,+ related: relatedFor,+ cleanup,+ });+ });++ it('runs DOM expectations and reports accessibility-tree outcomes as unrun', async () => {+ const results: BindingResult[] = [];+ for (const state of LAYOUT_LANDMARK_A11Y_STATES) {+ results.push(await checkState(state));+ }+ const report = summarize(LANDMARK_PATTERN, results);+ expect(report.counts.pass).toBeGreaterThan(0);+ expect(report.unrunLayers).toEqual(['accessibility-tree']);+ expect(report.counts.unexpectedPass).toBe(0);+ });+});++describe('the Layout regions landmark inventory', () => {+ it('names a distinct checked-in story for every state', () => {+ const ids = LAYOUT_LANDMARK_A11Y_STATES.map(state => state.storyId);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('binds only states that declare a landmark role and label', () => {+ for (const state of LAYOUT_LANDMARK_A11Y_STATES) {+ expect(state.facts.label, state.id).not.toBeNull();+ }+ });++ it('binds each Layout region component at least once', () => {+ expect(+ [+ ...new Set(LAYOUT_LANDMARK_A11Y_STATES.map(state => state.region)),+ ].sort(),+ ).toEqual(['LayoutContent', 'LayoutFooter', 'LayoutHeader', 'LayoutPanel']);+ });++ it('records every adjacent exclusion with an owner and reason', () => {+ expect(+ LAYOUT_LANDMARK_A11Y_EXCLUSIONS.every(row => row.owner && row.reason),+ ).toBe(true);+ });++ it('matches the declared role, label, and peer inventory', () => {+ for (const state of LAYOUT_LANDMARK_A11Y_STATES) {+ render(LAYOUT_LANDMARK_A11Y_RENDERS[state.id]());+ const subject = subjectFor();+ expect(subject.getAttribute('role'), state.id).toBe(state.facts.role);+ expect(subject.getAttribute('aria-label'), state.id).toBe(+ state.facts.label,+ );+ const peers = document.querySelectorAll(PEER_SELECTOR);+ expect(peers.length, state.id).toBe(state.facts.sameRolePeers);+ peers.forEach(peer =>+ expect(peer.getAttribute('role'), state.id).toBe(state.facts.role),+ );+ cleanup();+ }+ });+});