An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): add Link contract bound to Link and its router seams (#7378)
Cindy Zhang6613d812580b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 63490e8a8f..14934b4bd5 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1565,6 +1565,51 @@ jobs:retention-days: 30if-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 Link+ # 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 Link accessibility contract+ id: link-contract+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}+ env:+ BASE_SHA: ${{ github.event.pull_request.base.sha }}+ PLAYWRIGHT_JSON_OUTPUT_FILE: link-contract/report.json+ run: |+ should_run=false+ # Link and the contract are matched by file name so every Link source+ # file, including LinkProvider, 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/link\.|packages/core/src/Link/|apps/storybook/stories/LinkA11y)'; then+ should_run=true+ fi+ else+ should_run=true+ fi+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"+ if [ "$should_run" != true ]; then+ echo "Link and the link contract are not in PR scope; skipping link evidence."+ exit 0+ fi+ pnpm exec playwright test \+ internal/a11y-spec/src/patterns/link.chromium.spec.ts \+ packages/core/src/Link/__tests__/Link.a11y.chromium.spec.ts \+ --project chromium \+ --reporter list,json \+ --output link-contract-output++ - name: Upload Link accessibility contract evidence+ if: ${{ !cancelled() && steps.link-contract.outputs.should_run == 'true' }}+ uses: actions/upload-artifact@v7+ with:+ name: link-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: link-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/LinkA11y.stories.tsx b/apps/storybook/stories/LinkA11y.stories.tsxnew file mode 100644index 0000000000..85b53350fc--- /dev/null+++ b/apps/storybook/stories/LinkA11y.stories.tsx@@ -0,0 +1,33 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** One checked-in Storybook fixture for every Link binding state. */++import type {Meta, StoryObj} from '@storybook/react';+import {LINK_A11Y_RENDERS} from '../../../packages/core/src/Link/__tests__/Link.a11y.renders';+import {LINK_A11Y_STATES} from '../../../packages/core/src/Link/__tests__/Link.a11y.states';++function storyFor(id: (typeof LINK_A11Y_STATES)[number]['id']): StoryObj {+ const state = LINK_A11Y_STATES.find(candidate => candidate.id === id);+ if (state == null) {+ throw new Error(`no Link binding state "${id}"`);+ }+ return {+ name: `Link — ${state.id}`,+ render: () => LINK_A11Y_RENDERS[state.id](),+ };+}++const meta: Meta = {+ title: 'a11y/Link pattern',+ tags: ['no-visual'],+ parameters: {layout: 'padded'},+};++export default meta;++export const TextNative = storyFor('text-native');+export const IconLabelled = storyFor('icon-labelled');+export const CurrentPage = storyFor('current-page');+export const ExternalNewTab = storyFor('external-new-tab');+export const ProviderRouter = storyFor('provider-router');+export const AsRouter = storyFor('as-router');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex 7ae934f15f..44bcc85611 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -52,7 +52,8 @@ src/├── spinbutton.* numeric role, value, bounds, state, and arrow stepping├── disclosure.* standalone disclosure state/content semantics├── breadcrumb.* landmark, list-trail, current-page, and separator semantics- └── landmark.* one component-owned landmark region's role, name, and content boundary+ ├── landmark.* one component-owned landmark region's role, name, and content boundary+ └── link.* one available link's role, name, current state, focus, and activation```## The patterns@@ -73,6 +74,7 @@ src/| `disclosure` | [APG Disclosure](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/) | Standalone Collapsible triggers and their controlled content || `breadcrumb` | WCAG 2.2 semantics; [APG Breadcrumb](https://www.w3.org/WAI/ARIA/apg/patterns/breadcrumb/) as context | Breadcrumbs landmarks, list trails, current-page state, and separators || `landmark` | WCAG 2.2 semantics; [APG Landmark Regions](https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/) as context | LayoutHeader, LayoutContent, LayoutFooter, and LayoutPanel caller-declared landmarks |+| `link` | WCAG 2.2 semantics; [APG Link](https://www.w3.org/WAI/ARIA/apg/patterns/link/) role and Enter mechanics | Link, including LinkProvider and `as` router components |The toggle-button contract owns the persistent-action extension of buttonsemantics: the pressed state must be exposed, reversible by pointer, Enter, and@@ -116,6 +118,19 @@ Role-less regions, one main landmark per page, top-level placement, and whetherall page content sits in a landmark stay with Layout's own tests, the page, andAppShell; an isolated region never claims page-wide landmark completeness.+The link contract owns one available navigation link: the link role, the+exact name its binding declares, `aria-current` only when the link is the+current item, Tab entry and exit, and exactly one navigation from Enter or from+a pointer press released on the link, with none from a press slid off it. Every+gate is a WCAG 2.2 outcome; the APG Link page supplies the role and Enter+mechanics those outcomes rest on. Its first binding covers Link as a native+anchor, an icon-only labelled link, a caller-marked current page, an external+new-tab link, and router components supplied through LinkProvider and `as`.+Destination safety stays with `family:navigation-destinations`, disabled links+keep their member-owned semantics, and navigation aggregates such as+breadcrumbs, side and top navigation, citations, and clickable cards bind+separately.+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 9538790fea..825067e960 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -138,3 +138,9 @@ export {type LandmarkRole,type LandmarkStateFacts,} from './patterns/landmark';++export {+ LINK_PATTERN,+ type LinkCurrentToken,+ type LinkStateFacts,+} from './patterns/link';diff --git a/internal/a11y-spec/src/patterns/link.chromium.spec.ts b/internal/a11y-spec/src/patterns/link.chromium.spec.tsnew file mode 100644index 0000000000..28ffc41afc--- /dev/null+++ b/internal/a11y-spec/src/patterns/link.chromium.spec.ts@@ -0,0 +1,142 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file link.chromium.spec.ts+ * @input Uses @playwright/test, ./link (the contract), ./link.fixtures,+ * ../harness/chromium, ../check+ * @output Real-browser positive and mutation proof for the Link contract.+ * @position Self-test, the Chromium half of ./link.jsdom.test.ts. Both halves+ * read the same fixtures.+ *+ * A link's activation leaves no trace on the link, so the page counts every+ * navigation it requests through the Navigation API and cancels it. The count+ * is what the contract reads through the `activations()` seam, and the page+ * stays mounted for the next observation.+ */++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 {LINK_PATTERN} from './link';+import {+ CONFORMING_LINK_FIXTURES,+ LINK_MUTATIONS,+ LINK_SUBJECT_SELECTOR,+ linkFixture,+ type LinkFixture,+} from './link.fixtures';++interface NavigationWindow extends Window {+ __a11yLinkNavigations?: number;+}++/** A tab stop after the link, so "focus can leave it" has somewhere to go. */+function fixturePage(html: string): string {+ return `<!doctype html><html lang="en"><body><p>${html}</p><button type="button">after</button></body></html>`;+}++/**+ * Fixtures are served from an HTTP origin rather than `setContent`'s+ * `about:blank`, where fragment links do not navigate the way they do on a+ * real page.+ */+const FIXTURE_URL = 'http://a11y-spec.test/link';++async function mountFixture(page: Page, html: string): Promise<void> {+ await page.route(FIXTURE_URL, route =>+ route.fulfill({contentType: 'text/html', body: fixturePage(html)}),+ );+ await page.goto(FIXTURE_URL);+ await page.unroute(FIXTURE_URL);+}++async function countNavigations(page: Page): Promise<void> {+ await page.evaluate(() => {+ const target = window as NavigationWindow & {+ navigation: EventTarget;+ };+ target.__a11yLinkNavigations = 0;+ target.navigation.addEventListener('navigate', event => {+ target.__a11yLinkNavigations = (target.__a11yLinkNavigations ?? 0) + 1;+ if ((event as Event).cancelable) {+ event.preventDefault();+ }+ });+ });+}++async function results(+ page: Page,+ cdp: CDPSession,+ target: LinkFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ const run = await checkAccessibilitySpec({+ spec: LINK_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ only,+ mount: async () => {+ await mountFixture(page, target.html);+ await holdMotionStill(page);+ await countNavigations(page);+ return createChromiumHarness({+ page,+ cdp,+ subject: page.locator(LINK_SUBJECT_SELECTOR),+ });+ },+ activations: () =>+ page.evaluate(+ () => (window as NavigationWindow).__a11yLinkNavigations ?? 0,+ ),+ });+ return run.results;+}++test.describe('Link contract — conforming fixtures', () => {+ for (const id of CONFORMING_LINK_FIXTURES) {+ test(`${id}: every applicable expectation passes`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const observed = await results(page, cdp, linkFixture(id));+ expect(+ observed+ .filter(+ result =>+ result.status !== 'pass' && result.status !== 'not-applicable',+ )+ .map(result => `${result.expectation}: ${result.detail ?? ''}`),+ ).toEqual([]);+ });+ }+});++test.describe('Link contract — deliberately violating fixtures', () => {+ for (const expectation of LINK_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of LINK_MUTATIONS[expectation.id] ?? []) {+ test(`${describeExpectation(expectation)} — fails against ${fixtureId}`, async ({+ page,+ }) => {+ const cdp = await page.context().newCDPSession(page);+ const [result] = await results(page, cdp, linkFixture(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/link.fixtures.ts b/internal/a11y-spec/src/patterns/link.fixtures.tsnew file mode 100644index 0000000000..53020b5866--- /dev/null+++ b/internal/a11y-spec/src/patterns/link.fixtures.ts@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Plain-HTML positive and mutation fixtures for the Link contract.+ *+ * Every destination is a same-document fragment, so following a link never+ * leaves the fixture page. The Chromium half counts each navigation the page+ * requests through the browser's Navigation API and cancels it, so the count+ * is the observation and the page stays put for the next one.+ */++import type {LinkStateFacts} from './link';++export const LINK_SUBJECT_SELECTOR = '[data-a11y-link]';++export interface LinkFixture {+ readonly id: string;+ readonly summary: string;+ readonly facts: LinkStateFacts;+ readonly html: string;+}++function facts(overrides: Partial<LinkStateFacts> = {}): LinkStateFacts {+ return {name: 'Documentation', current: null, ...overrides};+}++const ICON =+ '<svg aria-hidden="true" width="16" height="16" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3L3 13" stroke="currentColor"/></svg>';++/** A script-free way to request a second, distinct navigation. */+const NAVIGATE = (hash: string) => `location.hash='${hash}'`;++export const LINK_FIXTURES: readonly LinkFixture[] = [+ {+ id: 'conforming-text',+ summary: 'a native link named by its visible text',+ facts: facts(),+ html: '<a data-a11y-link href="#destination">Documentation</a>',+ },+ {+ id: 'conforming-labelled-icon',+ summary: 'an icon-only native link named by aria-label',+ facts: facts({name: 'Close dialog'}),+ html: `<a data-a11y-link href="#destination" aria-label="Close dialog">${ICON}</a>`,+ },+ {+ id: 'conforming-current',+ summary: 'a native link that marks the current page',+ facts: facts({name: 'Overview', current: 'page'}),+ html: '<a data-a11y-link href="#destination" aria-current="page">Overview</a>',+ },+ {+ id: 'violating-role-missing',+ summary: 'a focusable span that navigates on click but is no link',+ facts: facts(),+ html: `<span data-a11y-link tabindex="0" onclick="${NAVIGATE('destination')}">Documentation</span>`,+ },+ {+ id: 'violating-role-button',+ summary: 'a button that navigates, announced as a button',+ facts: facts(),+ html: `<button data-a11y-link type="button" onclick="${NAVIGATE('destination')}">Documentation</button>`,+ },+ {+ id: 'violating-name-missing',+ summary: 'an icon-only link with no accessible name',+ facts: facts({name: 'Close dialog'}),+ html: `<a data-a11y-link href="#destination">${ICON}</a>`,+ },+ {+ id: 'violating-name-wrong',+ summary: 'a link whose aria-label replaces the declared name',+ facts: facts(),+ html: '<a data-a11y-link href="#destination" aria-label="Docs">Documentation</a>',+ },+ {+ id: 'violating-label-not-in-name',+ summary: 'a link whose computed name omits its visible words',+ facts: facts({name: 'Read the guide'}),+ html: '<a data-a11y-link href="#destination" aria-label="Read the guide">Documentation</a>',+ },+ {+ id: 'violating-unfocusable',+ summary: 'a link removed from the tab sequence',+ facts: facts(),+ html: '<a data-a11y-link href="#destination" tabindex="-1">Documentation</a>',+ },+ {+ id: 'violating-enter-inert',+ summary: 'a role="link" element that only listens for clicks',+ facts: facts(),+ html: `<div data-a11y-link role="link" tabindex="0" onclick="${NAVIGATE('destination')}">Documentation</div>`,+ },+ {+ id: 'violating-enter-twice',+ summary: 'a link whose Enter handler navigates on top of native activation',+ facts: facts(),+ html: `<a data-a11y-link href="#destination" onkeydown="if (event.key === 'Enter') { ${NAVIGATE('again')} }">Documentation</a>`,+ },+ {+ id: 'violating-navigates-on-press',+ summary: 'a link that navigates as soon as the pointer goes down',+ facts: facts(),+ html: `<a data-a11y-link href="#destination" onmousedown="${NAVIGATE('pressed')}">Documentation</a>`,+ },+ {+ id: 'violating-pointer-inert',+ summary: 'a link that cancels pointer activation and keeps only a key path',+ facts: facts(),+ html: `<a data-a11y-link href="#destination" onclick="if (event.detail > 0) { event.preventDefault() }">Documentation</a>`,+ },+ {+ id: 'violating-current-missing',+ summary: 'a current-page link that omits aria-current',+ facts: facts({name: 'Overview', current: 'page'}),+ html: '<a data-a11y-link href="#destination">Overview</a>',+ },+ {+ id: 'violating-current-unexpected',+ summary: 'an ordinary link that claims to be the current page',+ facts: facts(),+ html: '<a data-a11y-link href="#destination" aria-current="page">Documentation</a>',+ },+];++export const CONFORMING_LINK_FIXTURES = LINK_FIXTURES.filter(fixture =>+ fixture.id.startsWith('conforming-'),+).map(fixture => fixture.id);++export const LINK_MUTATIONS: Readonly<Record<string, readonly string[]>> = {+ 'link.role.exposed': ['violating-role-missing', 'violating-role-button'],+ 'link.name.exposed': ['violating-name-missing', 'violating-name-wrong'],+ 'link.name.matches-visible-label': ['violating-label-not-in-name'],+ 'link.focus.reachable-and-escapable': ['violating-unfocusable'],+ 'link.navigation.runs-on-enter': [+ 'violating-enter-inert',+ 'violating-enter-twice',+ ],+ 'link.navigation.completes-on-release': [+ 'violating-navigates-on-press',+ 'violating-pointer-inert',+ ],+ 'link.current.exposed': [+ 'violating-current-missing',+ 'violating-current-unexpected',+ ],+};++export function linkFixture(id: string): LinkFixture {+ const fixture = LINK_FIXTURES.find(candidate => candidate.id === id);+ if (fixture == null) {+ throw new Error(`unknown Link fixture "${id}"`);+ }+ return fixture;+}diff --git a/internal/a11y-spec/src/patterns/link.jsdom.test.ts b/internal/a11y-spec/src/patterns/link.jsdom.test.tsnew file mode 100644index 0000000000..8141de724b--- /dev/null+++ b/internal/a11y-spec/src/patterns/link.jsdom.test.ts@@ -0,0 +1,148 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/** Contract self-tests for Link 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 {LINK_PATTERN} from './link';+import {+ CONFORMING_LINK_FIXTURES,+ LINK_MUTATIONS,+ LINK_SUBJECT_SELECTOR,+ linkFixture,+ type LinkFixture,+} from './link.fixtures';++afterEach(() => document.body.replaceChildren());++async function resultsFor(target: LinkFixture) {+ const container = document.createElement('div');+ document.body.append(container);+ const run = await checkAccessibilitySpec({+ spec: LINK_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ mount: async () => {+ container.innerHTML = target.html;+ const subject = container.querySelector(LINK_SUBJECT_SELECTOR);+ if (subject == null) {+ throw new Error(`fixture "${target.id}" is missing its link subject`);+ }+ return createJsdomHarness({subject});+ },+ 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 = LINK_PATTERN.expectations.filter(expectation =>+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),+);++describe('Link contract — completeness', () => {+ it('answers every completeness dimension', () => {+ expect(unansweredDimensions(LINK_PATTERN)).toEqual([]);+ });++ it('gives every expectation at least one deliberately violating fixture', () => {+ expect(+ LINK_PATTERN.expectations+ .filter(+ expectation => (LINK_MUTATIONS[expectation.id] ?? []).length === 0,+ )+ .map(expectation => expectation.id),+ ).toEqual([]);+ });++ it('has an expectation for every mutation it records', () => {+ const ids = new Set(+ LINK_PATTERN.expectations.map(expectation => expectation.id),+ );+ expect(Object.keys(LINK_MUTATIONS).filter(id => !ids.has(id))).toEqual([]);+ });++ it('gates only on WCAG 2.2 outcomes', () => {+ for (const expectation of LINK_PATTERN.expectations) {+ expect(expectation.enforcement, expectation.id).toBe('required');+ expect(expectation.sources[0].standard, expectation.id).toBe('wcag');+ }+ });+});++describe('Link contract — the jsdom harness stays within its evidence boundary', () => {+ it('runs DOM expectations and reports tree and browser expectations as unrun', async () => {+ const results = await resultsFor(linkFixture('conforming-current'));+ 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?.some(layer =>+ ['accessibility-tree', 'real-browser'].includes(layer),+ ),+ result.expectation,+ ).toBe(true);+ }+ });+});++describe.each(observableHere.map(expectation => [expectation.id] as const))(+ '%s',+ id => {+ const expectation = LINK_PATTERN.expectations.find(+ candidate => candidate.id === id,+ )!;++ it.each(CONFORMING_LINK_FIXTURES.map(name => [name] as const))(+ 'passes against %s (or does not apply to it)',+ async name => {+ const result = resultFor(await resultsFor(linkFixture(name)), id);+ expect(+ ['pass', 'not-applicable'],+ `${id} against ${name}: ${result.detail ?? ''}`,+ ).toContain(result.status);+ },+ );++ it.each((LINK_MUTATIONS[id] ?? []).map(name => [name] as const))(+ 'fails against %s, which removes its outcome',+ async name => {+ const result = resultFor(await resultsFor(linkFixture(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 = linkFixture(+ LINK_MUTATIONS[id]?.[0] ?? CONFORMING_LINK_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/link.ts b/internal/a11y-spec/src/patterns/link.tsnew file mode 100644index 0000000000..d0abc9bd8b--- /dev/null+++ b/internal/a11y-spec/src/patterns/link.ts@@ -0,0 +1,464 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file link.ts+ * @input Uses ../contract (definePattern and the expectation vocabulary) and+ * ../spoken+ * @output LINK_PATTERN, LinkCurrentToken, and LinkStateFacts+ * @position Reusable semantic contract for one available navigation link: its+ * role, its name, its current-item state, and how a keyboard and a pointer+ * follow it — whichever element or router component renders it.+ *+ * Every gate is a WCAG 2.2 A or AA outcome. The APG Link pattern is cited as+ * the source of the exact role and Enter mechanics those outcomes rest on; no+ * APG-only detail gates here.+ *+ * Which destinations are safe to follow is not an accessibility outcome and+ * stays with `family:navigation-destinations`; this contract follows only+ * destinations the binding has already accepted. Disabled links are not bound:+ * that family's FR7 leaves disabled semantics with each member.+ *+ * SYNC: When an expectation changes, update+ * - /internal/a11y-spec/README.md+ * - /packages/core/src/Link/__tests__/Link.a11y.test.tsx (the jsdom binding)+ * - /packages/core/src/Link/__tests__/Link.a11y.chromium.spec.ts (Chromium)+ */++import {+ definePattern,+ type ApgRequirement,+ type PatternContract,+ type WcagCriterion,+} from '../contract';+import {saysInOrder, spokenWords} from '../spoken';++const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/link/';+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_1_1 = wcag('2.1.1', 'Keyboard', 'A', 'keyboard');+const WCAG_2_1_2 = wcag('2.1.2', 'No Keyboard Trap', 'A', 'no-keyboard-trap');+const WCAG_2_4_4 = wcag(+ '2.4.4',+ 'Link Purpose (In Context)',+ 'A',+ 'link-purpose-in-context',+);+const WCAG_2_5_2 = wcag(+ '2.5.2',+ 'Pointer Cancellation',+ 'A',+ 'pointer-cancellation',+);+const WCAG_2_5_3 = wcag('2.5.3', 'Label in Name', 'A', 'label-in-name');+const WCAG_4_1_2 = wcag('4.1.2', 'Name, Role, Value', 'A', 'name-role-value');++const APG_ROLE: ApgRequirement = {+ standard: 'apg',+ pattern: 'link',+ requirement:+ 'The element containing the link text or graphic has a role of link.',+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,+};+const APG_ENTER: ApgRequirement = {+ standard: 'apg',+ pattern: 'link',+ requirement: 'Enter: Executes the link and moves focus to the link target.',+ url: `${APG_URL}#keyboardinteraction`,+};++/** The `aria-current` tokens that mark a link as the current item in a set. */+export type LinkCurrentToken =+ 'page' | 'step' | 'location' | 'date' | 'time' | 'true';++export interface LinkStateFacts {+ /** The accessible name the binding declares the link computes. */+ readonly name: string;+ /**+ * The current-item token the binding declares, or null when the link is not+ * the current item of any set it belongs to.+ */+ readonly current: LinkCurrentToken | null;+}++/** Applies to every bound state; every bound state is an available link. */+const ALWAYS = {+ condition: 'the binding renders an available link',+ test: () => true,+};++/**+ * How many Tab presses count as "reachable". Ten is generous for one link on a+ * fixture page and short enough that an unreachable link fails fast.+ */+const TAB_BUDGET = 10;++function normalized(value: string): string {+ return value.replace(/\s+/g, ' ').trim();+}++function describeNavigations(count: number): string {+ return count === 1 ? 'one navigation' : `${count} navigations`;+}++export const LINK_PATTERN: PatternContract<LinkStateFacts> =+ definePattern<LinkStateFacts>({+ pattern: 'link',+ url: APG_URL,+ scope:+ 'One available navigation link: reported as a link with the name its binding declares, marked current only when it is, reachable by Tab, and followed exactly once by Enter or a completed pointer press — whether a native anchor or a router component renders it.',+ expectations: [+ {+ id: 'link.role.exposed',+ outcome:+ 'It is announced as a link, so people know activating it takes them somewhere rather than doing something here.',+ sources: [WCAG_4_1_2, APG_ROLE],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {role} = await subject.computed();+ if (role !== 'link') {+ throw new Error(+ role == null+ ? 'the browser exposes no role for this link, so assistive technology cannot announce it'+ : role === 'button'+ ? 'the browser reports this destination as a button, so it promises an action here while it takes people somewhere else'+ : `the browser reports this destination as "${role}", not as a link`,+ );+ }+ },+ },+ {+ id: 'link.name.exposed',+ outcome:+ 'The link computes exactly the name its binding declares, so people can tell where it goes from the link itself or its context.',+ sources: [WCAG_4_1_2, WCAG_2_4_4],+ covers: ['4.1.2-name-role-value', '2.4.4-link-purpose'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const name = normalized((await subject.computed()).name);+ if (name === '') {+ throw new Error(+ `the browser computes no accessible name, so the link is announced without saying where it goes; the binding declares "${facts.name}"`,+ );+ }+ if (name !== normalized(facts.name)) {+ throw new Error(+ `the link should be named "${facts.name}", but the browser computes "${name}"`,+ );+ }+ },+ },+ {+ id: 'link.name.matches-visible-label',+ outcome:+ 'The accessible name contains the words people can read on the link, so someone using speech input can say what they see.',+ sources: [WCAG_2_5_3],+ covers: ['2.5.3-label-in-name'],+ // Both sides are read off the rendered page, so a binding cannot+ // switch the criterion off by describing itself.+ appliesWhen: ALWAYS,+ evidenceLayer: 'accessibility-tree',+ alsoNeeds: ['real-browser'],+ enforcement: 'required',+ run: async ({subject, notApplicable}) => {+ const visible = await subject.visibleLabelText();+ if (visible == null) {+ return notApplicable(+ 'this state renders no words where a person can read them, so there is no visible label for a speech-input user to say',+ );+ }+ const {name} = await subject.computed();+ if (!saysInOrder(spokenWords(name), spokenWords(visible))) {+ throw new Error(+ `the link reads "${visible}" but the browser computes the accessible name as "${name}", so speaking the visible words does not reach it`,+ );+ }+ },+ },+ {+ id: 'link.focus.reachable-and-escapable',+ outcome:+ 'Tab reaches the link, and Tab again leaves it, so a keyboard user can get to the destination and carry on past it.',+ sources: [WCAG_2_1_1, WCAG_2_1_2],+ covers: ['2.1.1-keyboard', '2.1.2-no-keyboard-trap'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject}) => {+ await harness.resetFocus();+ let reached = false;+ for (let step = 0; step < TAB_BUDGET && !reached; step += 1) {+ await harness.press('Tab');+ reached = await subject.isFocused();+ }+ if (!reached) {+ throw new Error(+ `${TAB_BUDGET} presses of Tab from the start of the document never reached the link, so a keyboard user cannot get to this destination`,+ );+ }+ await harness.press('Tab');+ if (await subject.isFocused()) {+ throw new Error(+ 'Tab did not move focus off the link, so a keyboard user is stuck on it',+ );+ }+ },+ },+ {+ id: 'link.navigation.runs-on-enter',+ outcome:+ 'With focus on the link, Enter follows it exactly once — the keyboard reaches the same destination the pointer does.',+ sources: [WCAG_2_1_1, APG_ENTER],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject, activations}) => {+ await subject.focus();+ if (!(await subject.isFocused())) {+ throw new Error(+ 'the link did not take focus, so Enter never reaches it',+ );+ }+ const before = await activations();+ await harness.press('Enter');+ const followed = (await activations()) - before;+ if (followed === 0) {+ throw new Error(+ 'pressing Enter on the focused link requested no navigation, so its destination is out of reach from the keyboard',+ );+ }+ if (followed > 1) {+ throw new Error(+ `one press of Enter requested ${describeNavigations(followed)}, so the keyboard does not land where the link says it goes`,+ );+ }+ },+ },+ {+ id: 'link.navigation.completes-on-release',+ outcome:+ 'A press slid off the link and released elsewhere goes nowhere, and a press released on the link follows it once, so a misplaced press can be taken back.',+ sources: [WCAG_2_5_2],+ covers: ['2.5.2-pointer-cancellation'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject, activations}) => {+ const before = await activations();+ await harness.abortedPress(subject);+ const aborted = (await activations()) - before;+ if (aborted !== 0) {+ throw new Error(+ `pressing the link and releasing away from it still requested ${describeNavigations(aborted)}: navigation starts on the way down, so a press cannot be taken back`,+ );+ }+ await harness.click(subject);+ const completed = (await activations()) - before;+ if (completed !== 1) {+ throw new Error(+ completed === 0+ ? 'a press released on the link requested no navigation, so the up-event never completes the link'+ : `a press released on the link requested ${describeNavigations(completed)}, not one`,+ );+ }+ },+ },+ {+ id: 'link.current.exposed',+ outcome:+ 'A link marked as the current item says so programmatically, and a link that is not current never claims to be.',+ sources: [WCAG_1_3_1, WCAG_4_1_2],+ covers: ['1.3.1-info-and-relationships'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const authored = await subject.attribute('aria-current');+ const current =+ authored == null || authored === 'false' ? null : authored;+ if (current === facts.current) {+ return;+ }+ if (facts.current == null) {+ throw new Error(+ `the link is not the current item, but it carries aria-current="${authored}", so it tells people they are already there`,+ );+ }+ throw new Error(+ current == null+ ? `the link is the current ${facts.current}, but it carries no aria-current, so only sighted people can tell`+ : `the link is the current ${facts.current}, but it carries aria-current="${authored}"`,+ );+ },+ },+ ],+ exemptions: {+ '1.1.1-non-text-content': {+ owner: 'The binding component and caller content',+ verifiedBy:+ 'Component tests that hide decorative icons, plus the repository axe audit',+ reason:+ 'Whether a glyph inside a link is decorative or informative is a composition fact. This contract proves only that the link’s computed name carries its purpose.',+ },+ '1.3.1-info-and-relationships': {+ owner: 'The composing navigation, list, or prose',+ verifiedBy:+ 'Breadcrumb and navigation-aggregate contracts plus content review',+ reason:+ 'This contract encodes the link’s own current-item state. Lists, landmarks, and grouping around links belong to the components that compose them.',+ coversRemainderOnly: true,+ },+ '1.3.2-meaningful-sequence': {+ owner: 'The composing component and page',+ verifiedBy: 'Component DOM-order tests and reading-order review',+ reason:+ 'Where a link sits in reading order is composition, not link semantics.',+ },+ '1.3.5-identify-input-purpose': {+ owner: 'Form controls',+ verifiedBy: 'Text-input contract bindings',+ reason: 'A link collects no information about the user.',+ },+ '1.4.1-use-of-color': {+ owner: 'The binding and the active theme',+ verifiedBy:+ 'Rendered review of inline-link underline and hover treatment and the repository visual gate',+ reason:+ 'Whether an inline link is distinguishable from surrounding text without color is a paint outcome.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'The binding and the active theme',+ verifiedBy: 'Rendered contrast audit',+ reason: 'Link text contrast depends on resolved colors and backdrop.',+ },+ '1.4.11-non-text-contrast': {+ owner: 'The binding and the active theme',+ verifiedBy: 'Rendered focus-indicator and icon contrast review',+ reason: 'Icon and focus-ring contrast are paint outcomes.',+ },+ '2.4.2-page-titled': {+ owner: 'The page',+ verifiedBy: 'Page-level title review',+ reason: 'A link does not own the document title.',+ },+ '2.4.3-focus-order': {+ owner: 'The composing component and page',+ verifiedBy: 'Real-browser keyboard-order review',+ reason:+ 'Sequential order among several links depends on composition; this contract proves one link joins and leaves the tab sequence.',+ },+ '2.4.4-link-purpose': {+ owner: 'Caller-provided link text and labels',+ verifiedBy: 'Content review of link wording in context',+ reason:+ 'This contract proves the link computes its declared name, not that the caller’s words describe the destination.',+ coversRemainderOnly: true,+ },+ '2.4.6-headings-and-labels': {+ owner: 'Caller-provided link text and labels',+ verifiedBy: 'Content review',+ reason: 'Whether a label describes its purpose is a wording judgement.',+ },+ '2.4.7-focus-visible': {+ owner: 'The binding and the active theme',+ verifiedBy: 'Rendered keyboard-focus review and visual regression',+ reason: 'A visible focus indicator is a paint outcome.',+ },+ '2.4.11-focus-not-obscured': {+ owner: 'The composing page and the overlay system',+ verifiedBy: 'Constrained-viewport and sticky-region browser review',+ reason:+ 'Whether author content hides a focused link depends on layout around it.',+ },+ '2.5.8-target-size': {+ owner: 'The binding and the composing layout',+ verifiedBy:+ 'Rendered target geometry review; inline links in sentences use the inline exception',+ reason: 'Target size is geometry, not link semantics.',+ },+ '3.1.1-language-of-page': {+ owner: 'The page and localization provider',+ verifiedBy: 'Document-language checks',+ reason: 'A link does not own the document language.',+ },+ '3.2.2-on-input': {+ owner: 'Form controls',+ verifiedBy: 'Role-specific interaction tests',+ reason:+ 'A link has no input value; following it is the activation the user asked for.',+ },+ '3.2.4-consistent-identification': {+ owner: 'The design system and caller content',+ verifiedBy: 'Cross-page review of repeated link names',+ reason:+ 'Consistent naming of the same destination is a property of repeated pages.',+ },+ '3.3.1-error-identification': {+ owner: 'The composing form',+ verifiedBy: 'Form-level error review',+ reason: 'A link defines no validation error state.',+ },+ '3.3.2-labels-or-instructions': {+ owner: 'Form controls',+ verifiedBy: 'Form-level label review',+ reason: 'A link is not a form input.',+ },+ '4.1.3-status-messages': {+ owner: 'The destination and the status-message pattern',+ verifiedBy:+ 'Status-message tests and AST-009 when spoken timing is claimed',+ reason: 'Following a link is navigation, not a status message.',+ },+ 'apg-interaction': {+ owner: 'The browser and each binding’s current authority',+ verifiedBy:+ 'Real-browser focus review at the destination; AST-009 for spoken claims',+ reason:+ 'The contract gates the APG role and Enter mechanics through WCAG 2.2 4.1.2 and 2.1.1. Where focus lands after a same-document destination and the optional Shift + F10 context menu belong to the browser, not the link.',+ 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',+ verifiedBy: 'Component motion tests and rendered review',+ reason: 'Link semantics add no motion of their own.',+ },+ '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, including any new-tab suffix the binding declares, without claiming spoken wording, order, or timing.',+ },+ },+ });diff --git a/packages/core/src/Link/__tests__/Link.a11y.chromium.spec.ts b/packages/core/src/Link/__tests__/Link.a11y.chromium.spec.tsnew file mode 100644index 0000000000..e98e950b1e--- /dev/null+++ b/packages/core/src/Link/__tests__/Link.a11y.chromium.spec.ts@@ -0,0 +1,142 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Real-browser and accessibility-tree binding evidence for Link.+ *+ * A link's activation leaves no trace on the link, so the binding counts every+ * navigation the story requests: native navigations through the browser's+ * Navigation API (cancelled, so the story stays mounted), router navigations+ * the story's router component records, and new tabs the page opens.+ */++import {expect, test, type CDPSession, type Page} from '@playwright/test';+import {+ LINK_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 {LINK_A11Y_STATES, type LinkA11yRow} from './Link.a11y.states';++const SUBJECT_SELECTOR = '[data-a11y-link]';+const NEW_TAB_SETTLE_MS = 500;+let storybook: StaticServer;++interface NavigationWindow extends Window {+ __a11yLinkNavigations?: number;+}++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`;+}++async function countNavigations(+ page: Page,+ opensNewTab: boolean,+): Promise<() => Promise<number>> {+ let newTabs = 0;+ page.context().on('page', opened => {+ newTabs += 1;+ void opened.close();+ });+ await page.evaluate(() => {+ const target = window as NavigationWindow & {navigation: EventTarget};+ target.__a11yLinkNavigations = 0;+ target.navigation.addEventListener('navigate', event => {+ target.__a11yLinkNavigations = (target.__a11yLinkNavigations ?? 0) + 1;+ if (event.cancelable) {+ event.preventDefault();+ }+ });+ });+ return async () => {+ // A new tab reaches the test through the browser's target events, after+ // the click or key that opened it has returned. Give it time to arrive so+ // a later reading cannot miss a navigation an earlier one started.+ if (opensNewTab) {+ await page.waitForTimeout(NEW_TAB_SETTLE_MS);+ }+ const inPage = await page.evaluate(+ () => (window as NavigationWindow).__a11yLinkNavigations ?? 0,+ );+ return inPage + newTabs;+ };+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: LinkA11yRow,+): Promise<BindingResult> {+ let navigations: () => Promise<number> = async () => {+ throw new Error('the Link story was not mounted');+ };+ return checkAccessibilitySpec({+ spec: LINK_PATTERN,+ binding: 'Link',+ 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: 'visible'});+ await expect(subject).toHaveCount(1);+ navigations = await countNavigations(+ page,+ state.id === 'external-new-tab',+ );+ return createChromiumHarness({page, cdp, subject});+ },+ activations: async () => navigations(),+ });+}++test('every Link expectation is exercised by at least one Link state', async ({+ page,+}) => {+ // Mounts every state in one test, so it gets every state's time budget.+ test.setTimeout(30_000 * LINK_A11Y_STATES.length);+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of LINK_A11Y_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(neverExercised(results)).toEqual([]);+});++for (const state of LINK_A11Y_STATES) {+ test(`Link [${state.id}] — ${state.summary}`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(LINK_PATTERN, [result]);+ expect(formatFailures(blockingResults([result]))).toBe('');+ expect(+ result.results+ .filter(row => row.status === 'fail')+ .map(row => `${row.expectation}: ${row.detail ?? ''}`),+ ).toEqual([]);+ expect(report.unrunLayers).toEqual([]);+ expect(report.counts.unexpectedPass).toBe(0);+ });+}diff --git a/packages/core/src/Link/__tests__/Link.a11y.renders.tsx b/packages/core/src/Link/__tests__/Link.a11y.renders.tsxnew file mode 100644index 0000000000..30f281ff75--- /dev/null+++ b/packages/core/src/Link/__tests__/Link.a11y.renders.tsx@@ -0,0 +1,97 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/** Stable Link renders shared by jsdom, Storybook, and Chromium. */++import type {ComponentProps, MouseEvent, ReactElement} from 'react';+import {Icon} from '../../Icon';+import {Link} from '../Link';+import {LinkProvider} from '../LinkProvider';+import {LINK_A11Y_DESTINATION, type LinkA11yRow} from './Link.a11y.states';++interface NavigationWindow extends Window {+ __a11yLinkNavigations?: number;+}++/**+ * A minimal client-side router link. It takes over activation the way router+ * links do — cancel the browser navigation, then navigate itself — and counts+ * each navigation on the window, where the browser binding reads it.+ */+function RouterLink({onClick, children, ...props}: ComponentProps<'a'>) {+ const navigate = (event: MouseEvent<HTMLAnchorElement>) => {+ onClick?.(event);+ if (event.defaultPrevented) {+ return;+ }+ event.preventDefault();+ const target = window as NavigationWindow;+ target.__a11yLinkNavigations = (target.__a11yLinkNavigations ?? 0) + 1;+ };+ return (+ // eslint-disable-next-line @astryx/no-hardcoded-anchor -- this stands in for a third-party router's own anchor, which Link receives through LinkProvider and `as`.+ <a {...props} data-a11y-link-router onClick={navigate}>+ {children}+ </a>+ );+}++/** A tab stop after the link, so focus has somewhere to go when it leaves. */+function Frame({children}: {children: ReactElement}) {+ return (+ <div>+ {children}+ <button type="button">After</button>+ </div>+ );+}++export const LINK_A11Y_RENDERS: Readonly<+ Record<LinkA11yRow['id'], () => ReactElement>+> = {+ 'text-native': () => (+ <Frame>+ <Link data-a11y-link href={LINK_A11Y_DESTINATION}>+ Documentation+ </Link>+ </Frame>+ ),+ 'icon-labelled': () => (+ <Frame>+ <Link data-a11y-link href={LINK_A11Y_DESTINATION} label="Close dialog">+ <Icon icon="close" />+ </Link>+ </Frame>+ ),+ 'current-page': () => (+ <Frame>+ <Link aria-current="page" data-a11y-link href={LINK_A11Y_DESTINATION}>+ Overview+ </Link>+ </Frame>+ ),+ 'external-new-tab': () => (+ <Frame>+ <Link data-a11y-link href={LINK_A11Y_DESTINATION} isExternalLink>+ GitHub+ </Link>+ </Frame>+ ),+ 'provider-router': () => (+ <LinkProvider component={RouterLink}>+ <Frame>+ <Link data-a11y-link href="/projects">+ Projects+ </Link>+ </Frame>+ </LinkProvider>+ ),+ 'as-router': () => (+ <Frame>+ <Link as={RouterLink} data-a11y-link href="/settings">+ Settings+ </Link>+ </Frame>+ ),+};diff --git a/packages/core/src/Link/__tests__/Link.a11y.states.ts b/packages/core/src/Link/__tests__/Link.a11y.states.tsnew file mode 100644index 0000000000..a661a91d18--- /dev/null+++ b/packages/core/src/Link/__tests__/Link.a11y.states.ts@@ -0,0 +1,104 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** AST-021 state inventory for the Link binding of the shared Link contract. */++import type {LinkStateFacts} from '@astryxdesign/a11y-spec';++export interface LinkA11yState {+ readonly id:+ | 'text-native'+ | 'icon-labelled'+ | 'current-page'+ | 'external-new-tab'+ | 'provider-router'+ | 'as-router';+ readonly summary: string;+ readonly facts: LinkStateFacts;+ readonly storyId: string;+}++export type LinkA11yRow = (typeof LINK_A11Y_STATES)[number];++const story = (id: string) => `a11y-link-pattern--${id}`;++/**+ * Every destination is a same-document fragment, so following a link keeps the+ * story mounted. The router component records its own navigations; the browser+ * records native ones.+ */+export const LINK_A11Y_DESTINATION = '#link-destination';++export const LINK_A11Y_STATES = [+ {+ id: 'text-native',+ summary: 'a native anchor named by its visible text',+ facts: {name: 'Documentation', current: null},+ storyId: story('text-native'),+ },+ {+ id: 'icon-labelled',+ summary: 'an icon-only link named by its label prop',+ facts: {name: 'Close dialog', current: null},+ storyId: story('icon-labelled'),+ },+ {+ id: 'current-page',+ summary: 'a link the caller marks as the current page',+ facts: {name: 'Overview', current: 'page'},+ storyId: story('current-page'),+ },+ {+ id: 'external-new-tab',+ summary:+ 'an external link whose name carries the new-tab notice and which opens a new tab',+ facts: {name: 'GitHub (opens in new tab)', current: null},+ storyId: story('external-new-tab'),+ },+ {+ id: 'provider-router',+ summary:+ 'a link rendered by a router component supplied through LinkProvider',+ facts: {name: 'Projects', current: null},+ storyId: story('provider-router'),+ },+ {+ id: 'as-router',+ summary: 'a link rendered by a router component supplied through `as`',+ facts: {name: 'Settings', current: null},+ storyId: story('as-router'),+ },+] as const satisfies ReadonlyArray<LinkA11yState>;++export const LINK_A11Y_EXCLUSIONS = [+ {+ owner: 'Link component tests and family:navigation-destinations FR7',+ reason:+ 'A disabled Link renders an href-less anchor that is neither a link nor focusable. That disabled semantics is member-owned, so disabled states are not bound to this available-link contract.',+ },+ {+ owner: 'Link component tests (button rendering)',+ reason:+ 'A Link without href renders a button for an action; the button contract, not this one, owns that role.',+ },+ {+ owner: 'family:navigation-destinations and its verification map',+ reason:+ 'Which destinations are accepted or blocked, and how rejected destinations render, is navigation safety rather than an accessibility outcome.',+ },+ {+ owner:+ 'BreadcrumbItem, SideNavItem, TopNavItem, Citation, and ClickableCard',+ reason:+ 'Links inside navigation aggregates and enlarged surfaces bind separately; this first binding covers the Link component and both custom-router seams.',+ },+ {+ owner: 'Link visual and Tooltip evidence',+ reason:+ 'Underline, hover color, focus ring paint, truncation, and tooltip presentation require rendered and component checks.',+ },+ {+ owner: 'AST-009',+ reason:+ 'This binding claims DOM, accessibility-tree, and real-browser behavior, not spoken wording, virtual-cursor, or assistive-technology activation.',+ },+] as const;diff --git a/packages/core/src/Link/__tests__/Link.a11y.test.tsx b/packages/core/src/Link/__tests__/Link.a11y.test.tsxnew file mode 100644index 0000000000..e59f18596e--- /dev/null+++ b/packages/core/src/Link/__tests__/Link.a11y.test.tsx@@ -0,0 +1,127 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/** Fast DOM binding for Link against the shared Link contract. */++import {cleanup, render} from '@testing-library/react';+import {describe, expect, it} from 'vitest';+import {+ LINK_PATTERN,+ checkAccessibilitySpec,+ createJsdomHarness,+ expectAccessibilitySpec,+ summarize,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {LINK_A11Y_RENDERS} from './Link.a11y.renders';+import {+ LINK_A11Y_EXCLUSIONS,+ LINK_A11Y_STATES,+ type LinkA11yRow,+} from './Link.a11y.states';++const SUBJECT_SELECTOR = '[data-a11y-link]';++function subjectFor(): HTMLElement {+ const subjects = document.querySelectorAll(SUBJECT_SELECTOR);+ if (subjects.length !== 1 || !(subjects[0] instanceof HTMLElement)) {+ throw new Error(+ `binding rendered ${subjects.length} link subjects instead of one`,+ );+ }+ return subjects[0];+}++async function checkState(state: LinkA11yRow): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: LINK_PATTERN,+ binding: 'Link',+ state: state.id,+ facts: state.facts,+ mount: async () => {+ render(LINK_A11Y_RENDERS[state.id]());+ return createJsdomHarness({subject: subjectFor()});+ },+ unmount: cleanup,+ });+}++describe('the shared Link pattern, jsdom lane', () => {+ it.each(+ LINK_A11Y_STATES.map(+ state => [`Link [${state.id}]`, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectAccessibilitySpec({+ spec: LINK_PATTERN,+ binding: 'Link',+ state: state.id,+ facts: state.facts,+ render: () => {+ render(LINK_A11Y_RENDERS[state.id]());+ },+ subject: subjectFor,+ cleanup,+ });+ });++ it('runs DOM expectations and reports tree and browser outcomes as unrun', async () => {+ const results: BindingResult[] = [];+ for (const state of LINK_A11Y_STATES) {+ results.push(await checkState(state));+ }+ const report = summarize(LINK_PATTERN, results);+ expect(report.counts.pass).toBeGreaterThan(0);+ expect([...report.unrunLayers].sort()).toEqual([+ 'accessibility-tree',+ 'real-browser',+ ]);+ expect(report.counts.unexpectedPass).toBe(0);+ });+});++describe('the Link binding inventory', () => {+ it('names a distinct checked-in story for every state', () => {+ const ids = LINK_A11Y_STATES.map(state => state.storyId);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('records every adjacent exclusion with an owner and reason', () => {+ expect(LINK_A11Y_EXCLUSIONS.every(row => row.owner && row.reason)).toBe(+ true,+ );+ });++ it('renders an anchor with a destination for every state', () => {+ for (const state of LINK_A11Y_STATES) {+ render(LINK_A11Y_RENDERS[state.id]());+ const subject = subjectFor();+ expect(subject.tagName, state.id).toBe('A');+ expect(subject.getAttribute('href'), state.id).not.toBeNull();+ cleanup();+ }+ });++ it('renders both custom-router seams through the router component', () => {+ for (const id of ['provider-router', 'as-router'] as const) {+ render(LINK_A11Y_RENDERS[id]());+ expect(subjectFor().hasAttribute('data-a11y-link-router'), id).toBe(true);+ cleanup();+ }+ for (const state of LINK_A11Y_STATES.filter(+ row => row.id !== 'provider-router' && row.id !== 'as-router',+ )) {+ render(LINK_A11Y_RENDERS[state.id]());+ expect(subjectFor().hasAttribute('data-a11y-link-router'), state.id).toBe(+ false,+ );+ cleanup();+ }+ });++ it('opens the external state in a new tab', () => {+ render(LINK_A11Y_RENDERS['external-new-tab']());+ expect(subjectFor().getAttribute('target')).toBe('_blank');+ cleanup();+ });+});