An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): add Tooltip contract and bind Tooltip (#7799)
Cindy Zhangca4f3b2821a1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex de085467f2..fbea8db502 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1789,6 +1789,56 @@ jobs:--project chromium \--output a11y-harness-output+ # The tooltip contract's computed description, focus and hover showing,+ # Escape and focus-leaving dismissal, and staying while hovered are+ # accessibility-tree and real-browser facts that jsdom cannot observe. Run+ # the contract's own fixture proof and the Tooltip binding whenever+ # Tooltip 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 Tooltip accessibility contract+ id: tooltip-contract+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}+ env:+ BASE_SHA: ${{ github.event.pull_request.base.sha }}+ PLAYWRIGHT_JSON_OUTPUT_FILE: tooltip-contract/report.json+ run: |+ should_run=false+ # Tooltip and the contract are matched by file name.+ # The helper comes from the base, since an older PR head lacks it.+ # Exit 1 means out of scope; 0 in scope; 2 unknown, so run.+ scope=2+ helper="$(mktemp)"+ if git fetch --quiet --no-tags --depth=1 origin "$BASE_SHA" \+ && git show "$BASE_SHA:.github/scripts/pr-scope-touches.sh" > "$helper"; then+ scope=0+ bash "$helper" "$BASE_SHA" \+ '^(internal/a11y-spec/src/patterns/tooltip\.|packages/core/src/Tooltip/|apps/storybook/stories/TooltipA11y)' || scope=$?+ fi+ if [ "$scope" != 1 ]; then+ should_run=true+ fi+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"+ if [ "$should_run" != true ]; then+ echo "Tooltip and the tooltip contract are not in PR scope; skipping tooltip evidence."+ exit 0+ fi+ pnpm exec playwright test \+ internal/a11y-spec/src/patterns/tooltip.chromium.spec.ts \+ packages/core/src/Tooltip/__tests__/Tooltip.a11y.chromium.spec.ts \+ --project chromium \+ --reporter list,json \+ --output tooltip-contract-output++ - name: Upload Tooltip accessibility contract evidence+ if: ${{ !cancelled() && steps.tooltip-contract.outputs.should_run == 'true' }}+ uses: actions/upload-artifact@v7+ with:+ name: tooltip-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: tooltip-contract/+ retention-days: 30+ if-no-files-found: warn+# The accordion contract's header role and name, the page Tab step between# headers, the absence of arrow-key focus movement, and the single-expansion# sibling collapse are accessibility-tree and real-browser facts that jsdomdiff --git a/apps/storybook/stories/TooltipA11y.stories.tsx b/apps/storybook/stories/TooltipA11y.stories.tsxnew file mode 100644index 0000000000..a686023348--- /dev/null+++ b/apps/storybook/stories/TooltipA11y.stories.tsx@@ -0,0 +1,34 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TooltipA11y.stories.tsx+ * @input The Tooltip binding states, rendered through the binding's own renderer so the jsdom and Chromium lanes see the same tree+ * @output One checked-in story per state for the Chromium accessibility lane; excluded from the visual matrix+ * @position Browser fixtures for the Tooltip binding (TOOLTIP_PATTERN)+ */++import type {Meta, StoryObj} from '@storybook/react';+import {renderTooltipState} from '../../../packages/core/src/Tooltip/__tests__/Tooltip.a11y.renders';+import {TOOLTIP_BINDING_STATES} from '../../../packages/core/src/Tooltip/__tests__/Tooltip.a11y.states';++const meta = {+ title: 'A11y/Tooltip',+ tags: ['no-visual'],+ parameters: {layout: 'padded'},+} satisfies Meta;++export default meta;+type Story = StoryObj<typeof meta>;++function storyFor(id: (typeof TOOLTIP_BINDING_STATES)[number]['id']): Story {+ const state = TOOLTIP_BINDING_STATES.find(candidate => candidate.id === id);+ if (state == null) {+ throw new Error(`no Tooltip binding state "${id}"`);+ }+ return {render: () => renderTooltipState(state)};+}++export const WrappedButton = storyFor('wrapped-button');+export const TextTrigger = storyFor('text-trigger');+export const AnchorRefWithHint = storyFor('anchor-ref-with-hint');+export const UseTooltipHook = storyFor('use-tooltip-hook');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex b5033f499a..35a8e6272c 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -54,6 +54,7 @@ src/├── menu-button.* a control's button role and name, aria-haspopup, expanded state, controls, and keyboard opens├── menu.* a displayed menu's role and name, item roles/names/checked/disabled state, and arrow/Home/End/Enter/Escape/Tab keys (typeahead advisory)├── toolbar.* a toolbar's role and name, orientation, controls inside it, one Tab stop, and arrow (with wrap, RTL-mirrored, Down/Up when vertical) and Home/End keys+ ├── tooltip.* a tooltip's role, the trigger described by it, keyboard focus showing it, Escape dismissing it, and hover keeping it (blur, hover-show and pointer-leave advisory)├── window-splitter.* a focusable resize separator's role, name, position/bounds, pane relationship, and arrow/Enter keys (Home/End advisory)├── grid.* a composite grid's role, name, row/cell structure, single Tab stop, selection, and arrow/Home/End/Enter keys├── alert-dialog.* a confirmation surface's alertdialog role, title/message references, modality, initial focus, Escape and click-beside dismissal@@ -86,6 +87,7 @@ src/| `menu-button` | [APG Menu Button](https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/) required parts; the optional ArrowDown/ArrowUp opens Astryx ships are advisory | Anchored DropdownMenu and MoreMenu triggers: button role and name, `aria-haspopup="menu"`, `aria-expanded`, `aria-controls`, Enter/Space open on the first enabled item (advisory: ArrowDown on the first, ArrowUp on the last) || `menu` | [APG Menu and Menubar](https://www.w3.org/WAI/ARIA/apg/patterns/menubar/) menu; arrows (with wrap) and Home/End per AST-020 FR15; typeahead advisory | DropdownMenu pointer menu: named `menu`, item roles/names, `aria-checked`, `aria-disabled`, arrows with wrap, Home/End, Enter and Escape back to the trigger, Tab out (advisory: typeahead) || `toolbar` | [APG Toolbar](https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/); arrows (with wrap) and Home/End per AST-020 FR15 | Toolbar: named `toolbar`, `aria-orientation`, controls inside it, one Tab stop entering on the first enabled control, next/previous arrows (RTL-mirrored, Down/Up when vertical) with wrap, Home/End |+| `tooltip` | [APG Tooltip](https://www.w3.org/WAI/ARIA/apg/patterns/tooltip/) role and relationship per AST-020 FR15; WCAG 1.4.13; three rows advisory | Tooltip, useTooltip: `tooltip` role, `aria-describedby` and computed description, focus shows it (focus stays), Escape dismisses, hover keeps it over trigger and tooltip (advisory: blur hides, hover shows, pointer leaving hides) || `accordion` | [APG Accordion](https://www.w3.org/WAI/ARIA/apg/patterns/accordion/) required parts | CollapsibleGroup headers: button role and name, expanded state, controlled panel, Enter/Space, single-expansion sibling collapse, page Tab order, no arrow-key movement (single-expansion collapse, grouped Tab order, no arrow movement are advisory until `component:CollapsibleGroup` AR4 is current) || `breadcrumb` | WCAG 2.2 semantics; [APG Breadcrumb](https://www.w3.org/WAI/ARIA/apg/patterns/breadcrumb/) as context | Breadcrumbs landmarks, list trails, current-page state, and separators || `combobox` | WCAG 2.2 + [WAI-ARIA 1.2 Combobox](https://www.w3.org/TR/wai-aria-1.2/#combobox); APG as context | Selector trigger identity, state, popup, and active-descendant relationships |diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.tsindex e4af7b60b4..551faf4f42 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -173,3 +173,4 @@ export {type LinkStateFacts,} from './patterns/link';export {TOOLBAR_PATTERN, type ToolbarStateFacts} from './patterns/toolbar';+export {TOOLTIP_PATTERN, type TooltipStateFacts} from './patterns/tooltip';diff --git a/internal/a11y-spec/src/patterns/tooltip.chromium.spec.ts b/internal/a11y-spec/src/patterns/tooltip.chromium.spec.tsnew file mode 100644index 0000000000..a1dc3e725d--- /dev/null+++ b/internal/a11y-spec/src/patterns/tooltip.chromium.spec.ts@@ -0,0 +1,101 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file tooltip.chromium.spec.ts+ * @input TOOLTIP_PATTERN and its fixtures in real Chromium+ * @output Proof that every expectation passes conforming fixtures and fails its mutation at the layers only a browser observes+ * @position Contract self-test, Chromium lane+ */++import {expect, test, type CDPSession, type Page} from '@playwright/test';+import {describeExpectation, requiredLayers} from '../contract';+import {checkAccessibilitySpec, type ExpectationResult} from '../check';+import {+ CHROMIUM_OBSERVES,+ createChromiumHarness,+ holdMotionStill,+} from '../harness/chromium';+import {TOOLTIP_PATTERN} from './tooltip';+import {+ TOOLTIP_MUTATIONS,+ CONFORMING_FIXTURES,+ SUBJECT_SELECTOR,+ fixture,+ type TooltipFixture,+} from './tooltip.fixtures';++function fixturePage(html: string): string {+ return `<!doctype html><html lang="en"><body>${html}</body></html>`;+}++async function results(+ page: Page,+ cdp: CDPSession,+ target: TooltipFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ const run = await checkAccessibilitySpec({+ spec: TOOLTIP_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ only,+ mount: async () => {+ await page.setContent(fixturePage(target.html));+ await holdMotionStill(page);+ return createChromiumHarness({+ page,+ cdp,+ subject: page.locator(SUBJECT_SELECTOR),+ related: Object.fromEntries(+ Object.entries(target.relations).map(([name, selector]) => [+ name,+ page.locator(selector),+ ]),+ ),+ });+ },+ });+ return run.results;+}++test.describe('tooltip contract — conforming fixtures', () => {+ for (const id of CONFORMING_FIXTURES) {+ test(`${id}: every applicable expectation passes`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const observed = await results(page, cdp, fixture(id));+ expect(+ observed+ .filter(+ result =>+ result.status !== 'pass' && result.status !== 'not-applicable',+ )+ .map(result => `${result.expectation}: ${result.detail ?? ''}`),+ ).toEqual([]);+ });+ }+});++test.describe('tooltip contract — deliberately violating fixtures', () => {+ for (const expectation of TOOLTIP_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of TOOLTIP_MUTATIONS[expectation.id] ?? []) {+ test(`${describeExpectation(expectation)} — fails against ${fixtureId}`, async ({+ page,+ }) => {+ const cdp = await page.context().newCDPSession(page);+ const [result] = await results(page, cdp, fixture(fixtureId), [+ expectation.id,+ ]);+ expect(result?.status, result?.detail ?? 'no result').toBe('fail');+ expect(result?.detail ?? '').not.toBe('');+ });+ }+ }+});diff --git a/internal/a11y-spec/src/patterns/tooltip.fixtures.ts b/internal/a11y-spec/src/patterns/tooltip.fixtures.tsnew file mode 100644index 0000000000..abffa2bbb0--- /dev/null+++ b/internal/a11y-spec/src/patterns/tooltip.fixtures.ts@@ -0,0 +1,305 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file tooltip.fixtures.ts+ * @input Plain HTML tooltips on a trigger between two page buttons, conforming and deliberately violating+ * @output TOOLTIP_FIXTURES, their subject and relation selectors, and the expectation → violating-fixture map+ * @position Contract self-test data for tooltip.jsdom.test.ts and tooltip.chromium.spec.ts+ */++import type {TooltipStateFacts} from './tooltip';++export const SUBJECT_SELECTOR = '#trigger';++/** The fixture tooltip's show delay on hover, which every fixture declares. */+const SHOW_DELAY_MS = 200;++/**+ * How the fixture tooltip behaves. One script reads these from the trigger's+ * data attributes, so a violating fixture changes exactly one behavior.+ */+interface Behavior {+ /** What keyboard focus on the trigger does: show the tooltip, nothing, or show it and move focus into it. */+ readonly focus?: 'show' | 'ignore' | 'steal';+ /** When Escape hides the tooltip: always, only while the trigger has focus, or never. */+ readonly escape?: 'always' | 'focused-only' | 'never';+ /** Whether focus leaving the trigger hides the tooltip. */+ readonly blurHides?: boolean;+ /** Whether hovering the trigger shows the tooltip. */+ readonly hoverShows?: boolean;+ /** Leaving the trigger: hide after a short bridge, hide at once, or never hide. */+ readonly leave?: 'bridge' | 'no-bridge' | 'stay';+ /** Hide the tooltip on its own after this many milliseconds, hovered or not. */+ readonly autoHideMs?: number | null;+}++/**+ * The smallest tooltip: focus shows it at once, hover after a delay; leaving+ * hides it after a bridge that entering the tooltip cancels; blur and Escape+ * hide it. jsdom does not run it; the jsdom lane reads DOM attributes only.+ */+const SCRIPT = `<script>(() => {+ const trigger = document.getElementById('trigger');+ const tip = document.getElementById('tip');+ const d = trigger.dataset;+ let showTimer = null;+ let hideTimer = null;+ let autoTimer = null;+ const clear = () => { clearTimeout(showTimer); clearTimeout(hideTimer); };+ const hide = () => { clear(); clearTimeout(autoTimer); tip.hidden = true; };+ const show = () => {+ clear();+ tip.hidden = false;+ if (d.autoHide !== '') {+ clearTimeout(autoTimer);+ autoTimer = setTimeout(hide, Number(d.autoHide));+ }+ };+ trigger.addEventListener('focus', () => {+ if (d.focus === 'ignore') return;+ show();+ if (d.focus === 'steal') tip.focus();+ });+ trigger.addEventListener('blur', () => { if (d.blurHides === 'true' && d.focus !== 'steal') hide(); });+ trigger.addEventListener('mouseenter', () => {+ if (d.hoverShows !== 'true') return;+ clear();+ showTimer = setTimeout(show, ${SHOW_DELAY_MS});+ });+ trigger.addEventListener('mouseleave', () => {+ clearTimeout(showTimer);+ if (d.leave === 'bridge') hideTimer = setTimeout(hide, 100);+ else if (d.leave === 'no-bridge') hide();+ });+ tip.addEventListener('mouseenter', () => clearTimeout(hideTimer));+ tip.addEventListener('mouseleave', () => { if (d.leave !== 'stay') hideTimer = setTimeout(hide, 100); });+ document.addEventListener('keydown', event => {+ if (event.key !== 'Escape' || tip.hidden) return;+ if (d.escape === 'always' || (d.escape === 'focused-only' && document.activeElement === trigger)) hide();+ });+})();</script>`;++interface TriggerOptions {+ readonly behavior?: Behavior;+ /** The popup's role; null for none. */+ readonly role?: string | null;+ /** The trigger's aria-describedby; null for none. */+ readonly describedBy?: string | null;+ /** The trigger's own accessible name and visible text. */+ readonly label?: string;+ /** An aria-label that names an icon-only trigger instead of its text. */+ readonly ariaLabel?: string | null;+ /** A visible hint the trigger is already described by, besides the tooltip. */+ readonly hint?: string | null;+}++const TOOLTIP_TEXT = 'Saves your changes to this draft';++function tooltipHtml({+ behavior = {},+ role = 'tooltip',+ describedBy = 'tip',+ label = 'Save',+ ariaLabel = null,+ hint = null,+}: TriggerOptions): string {+ const b: Required<Behavior> = {+ focus: 'show',+ escape: 'always',+ blurHides: true,+ hoverShows: true,+ leave: 'bridge',+ autoHideMs: null,+ ...behavior,+ };+ const data = `data-focus="${b.focus}" data-escape="${b.escape}" data-blur-hides="${b.blurHides}" data-hover-shows="${b.hoverShows}" data-leave="${b.leave}" data-auto-hide="${b.autoHideMs ?? ''}"`;+ const triggerAttributes = [+ 'type="button"',+ 'id="trigger"',+ ariaLabel == null ? null : `aria-label="${ariaLabel}"`,+ describedBy == null ? null : `aria-describedby="${describedBy}"`,+ data,+ ]+ .filter(attribute => attribute != null)+ .join(' ');+ const tipAttributes = [+ 'id="tip"',+ role == null ? null : `role="${role}"`,+ 'tabindex="-1"',+ 'hidden',+ 'style="position:absolute;inset-block-start:100%;inset-inline-start:0;padding:4px 8px;background:#222;color:#fff;white-space:nowrap"',+ ]+ .filter(attribute => attribute != null)+ .join(' ');+ return `<div style="padding:48px"><button type="button" id="before">Before the trigger</button> <span style="position:relative;display:inline-block"><button ${triggerAttributes}>${label}</button><div ${tipAttributes}>${TOOLTIP_TEXT}</div></span>${hint == null ? '' : ` <span id="hint">${hint}</span>`} <button type="button" id="after">After the trigger</button></div>${SCRIPT}`;+}++export interface TooltipFixture {+ readonly id: string;+ readonly summary: string;+ readonly facts: TooltipStateFacts;+ /** Relation name → selector inside the fixture. */+ readonly relations: Readonly<Record<string, string>>;+ readonly html: string;+}++const RELATIONS = {+ tooltip: '#tip',+ before: '#before',+ after: '#after',+} as const;++const FACTS: TooltipStateFacts = {+ showsOnHover: true,+ showDelayMs: SHOW_DELAY_MS,+};++function tooltip(+ id: string,+ summary: string,+ {+ facts = FACTS,+ ...options+ }: TriggerOptions & {facts?: TooltipStateFacts} = {},+): TooltipFixture {+ return {+ id,+ summary,+ facts,+ relations: RELATIONS,+ html: tooltipHtml(options),+ };+}++export const TOOLTIP_FIXTURES: readonly TooltipFixture[] = [+ tooltip(+ 'conforming-text-trigger',+ 'a button described by its tooltip, shown by focus at once and by hover after a delay, kept while hovered, hidden by Escape, blur and leaving',+ ),+ tooltip(+ 'conforming-icon-trigger',+ 'an icon-only button named by aria-label and described by its tooltip',+ {label: '💾', ariaLabel: 'Save'},+ ),+ tooltip(+ 'conforming-existing-description',+ 'a button already described by a visible hint, whose aria-describedby names the hint and the tooltip',+ {describedBy: 'hint tip', hint: 'Last saved a minute ago'},+ ),+ tooltip(+ 'conforming-focus-only',+ 'a tooltip only keyboard focus shows, which claims no hover; the hover rows do not apply',+ {+ behavior: {hoverShows: false},+ facts: {...FACTS, showsOnHover: false},+ },+ ),+ tooltip(+ 'violating-status-role',+ 'the popup carries role status instead of tooltip',+ {role: 'status'},+ ),+ tooltip('violating-no-role', 'the popup carries no role', {role: null}),+ tooltip(+ 'violating-not-described',+ 'the trigger has no aria-describedby, so nothing ties the tooltip to it',+ {describedBy: null},+ ),+ tooltip(+ 'violating-described-by-other',+ 'the trigger is described only by a neighbouring hint, not by the tooltip',+ {describedBy: 'hint', hint: 'Last saved a minute ago'},+ ),+ tooltip(+ 'violating-focus-ignored',+ 'keyboard focus on the trigger does not show the tooltip',+ {behavior: {focus: 'ignore'}},+ ),+ tooltip(+ 'violating-focus-moves-into-tooltip',+ 'showing the tooltip on focus moves focus into the tooltip',+ {behavior: {focus: 'steal'}},+ ),+ tooltip('violating-escape-ignored', 'Escape does nothing', {+ behavior: {escape: 'never'},+ }),+ tooltip(+ 'violating-escape-needs-focus',+ 'Escape hides the tooltip only while the trigger has focus, so a hovered tooltip cannot be dismissed without moving the pointer',+ {behavior: {escape: 'focused-only'}},+ ),+ tooltip(+ 'violating-blur-keeps',+ 'focus leaving the trigger leaves the tooltip showing',+ {behavior: {blurHides: false}},+ ),+ tooltip(+ 'violating-hover-ignored',+ 'hovering the trigger does not show the tooltip',+ {behavior: {hoverShows: false}},+ ),+ tooltip(+ 'violating-no-hover-bridge',+ 'leaving the trigger hides the tooltip at once, even when the pointer moves onto the tooltip',+ {behavior: {leave: 'no-bridge'}},+ ),+ tooltip(+ 'violating-times-out',+ 'the tooltip hides itself half a second after it appears, though the pointer still rests on the trigger',+ {behavior: {autoHideMs: 500}},+ ),+ tooltip(+ 'violating-focus-only-times-out',+ 'a tooltip only keyboard focus shows, which hides itself half a second later though focus stays on the trigger',+ {+ behavior: {hoverShows: false, autoHideMs: 500},+ facts: {...FACTS, showsOnHover: false},+ },+ ),+ tooltip(+ 'violating-leave-keeps',+ 'the tooltip stays after the pointer leaves the trigger and the tooltip',+ {behavior: {leave: 'stay'}},+ ),+];++export function fixture(id: string): TooltipFixture {+ const found = TOOLTIP_FIXTURES.find(candidate => candidate.id === id);+ if (found == null) {+ throw new Error(`unknown tooltip fixture "${id}"`);+ }+ return found;+}++export const CONFORMING_FIXTURES: readonly string[] = TOOLTIP_FIXTURES.filter(+ candidate => candidate.id.startsWith('conforming-'),+).map(candidate => candidate.id);++export const TOOLTIP_MUTATIONS: Readonly<Record<string, readonly string[]>> = {+ 'tooltip.surface.role': ['violating-status-role', 'violating-no-role'],+ 'tooltip.trigger.described-by-tooltip': [+ 'violating-not-described',+ 'violating-described-by-other',+ ],+ 'tooltip.trigger.description': [+ 'violating-not-described',+ 'violating-described-by-other',+ ],+ 'tooltip.focus.shows-on-keyboard-focus': [+ 'violating-focus-ignored',+ 'violating-focus-moves-into-tooltip',+ 'violating-focus-only-times-out',+ 'violating-times-out',+ ],+ 'tooltip.keys.escape-dismisses': [+ 'violating-escape-ignored',+ 'violating-escape-needs-focus',+ ],+ 'tooltip.focus.leaving-hides': ['violating-blur-keeps'],+ 'tooltip.hover.shows-on-hover': ['violating-hover-ignored'],+ 'tooltip.hover.stays-while-hovered': [+ 'violating-no-hover-bridge',+ 'violating-times-out',+ ],+ 'tooltip.hover.leaving-hides': ['violating-leave-keeps'],+};diff --git a/internal/a11y-spec/src/patterns/tooltip.jsdom.test.ts b/internal/a11y-spec/src/patterns/tooltip.jsdom.test.tsnew file mode 100644index 0000000000..cca9185632--- /dev/null+++ b/internal/a11y-spec/src/patterns/tooltip.jsdom.test.ts@@ -0,0 +1,162 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file tooltip.jsdom.test.ts+ * @input TOOLTIP_PATTERN and its conforming and violating fixtures+ * @output Proof that the contract is complete, that every DOM-layer expectation passes conforming fixtures and fails its mutation, and that jsdom reports browser layers as unrun+ * @position Contract self-test, jsdom lane+ */++import {afterEach, describe, expect, it} from 'vitest';+import {+ citeSource,+ describeExpectation,+ requiredLayers,+ unansweredDimensions,+} from '../contract';+import {checkAccessibilitySpec, type ExpectationResult} from '../check';+import {JSDOM_OBSERVES, createJsdomHarness} from '../harness/jsdom';+import {TOOLTIP_PATTERN} from './tooltip';+import {+ TOOLTIP_MUTATIONS,+ CONFORMING_FIXTURES,+ SUBJECT_SELECTOR,+ fixture,+ type TooltipFixture,+} from './tooltip.fixtures';++const observableHere = TOOLTIP_PATTERN.expectations.filter(expectation =>+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),+);++afterEach(() => document.body.replaceChildren());++async function resultsFor(target: TooltipFixture) {+ const container = document.createElement('div');+ document.body.append(container);+ const result = await checkAccessibilitySpec({+ spec: TOOLTIP_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ mount: async () => {+ container.innerHTML = target.html;+ const subject = container.querySelector(SUBJECT_SELECTOR);+ if (subject == null) {+ throw new Error(`fixture "${target.id}" is missing its trigger`);+ }+ const related: Record<string, Element> = {};+ for (const [name, selector] of Object.entries(target.relations)) {+ const element = container.querySelector(selector);+ if (element == null) {+ throw new Error(`fixture "${target.id}" is missing ${name}`);+ }+ related[name] = element;+ }+ return createJsdomHarness({subject, related});+ },+ unmount: () => {+ container.innerHTML = '';+ },+ });+ return result.results;+}++function resultFor(+ results: readonly ExpectationResult[],+ id: string,+): ExpectationResult {+ const found = results.find(result => result.expectation === id);+ if (found == null) {+ throw new Error(`no result for ${id}`);+ }+ return found;+}++describe('tooltip contract — completeness', () => {+ it('answers every completeness dimension', () => {+ expect(unansweredDimensions(TOOLTIP_PATTERN)).toEqual([]);+ });++ it('gives every expectation at least one deliberately violating fixture', () => {+ const missing = TOOLTIP_PATTERN.expectations+ .filter(+ expectation => (TOOLTIP_MUTATIONS[expectation.id] ?? []).length === 0,+ )+ .map(expectation => expectation.id);+ expect(missing).toEqual([]);+ });++ it('has an expectation for every mutation it records', () => {+ const ids = new Set(+ TOOLTIP_PATTERN.expectations.map(expectation => expectation.id),+ );+ expect(Object.keys(TOOLTIP_MUTATIONS).filter(id => !ids.has(id))).toEqual(+ [],+ );+ });++ it('names every fixture it records a mutation against', () => {+ for (const fixtures of Object.values(TOOLTIP_MUTATIONS)) {+ for (const id of fixtures) {+ expect(() => fixture(id)).not.toThrow();+ }+ }+ });+});++describe('tooltip contract — the jsdom harness stays within its evidence boundary', () => {+ it('runs DOM expectations and reports browser expectations as unrun', async () => {+ const results = await resultsFor(fixture('conforming-text-trigger'));+ expect(results.some(result => result.status === 'pass')).toBe(true);+ const above = results.filter(result => result.status === 'unrun');+ expect(above.length).toBeGreaterThan(0);+ for (const result of above) {+ expect(+ (result.missingLayers ?? []).some(+ layer => layer === 'real-browser' || layer === 'accessibility-tree',+ ),+ ).toBe(true);+ }+ });+});++describe.each(observableHere.map(expectation => [expectation.id] as const))(+ '%s',+ id => {+ const expectation = TOOLTIP_PATTERN.expectations.find(+ candidate => candidate.id === id,+ )!;++ it.each(CONFORMING_FIXTURES.map(name => [name] as const))(+ 'passes against %s (or does not apply to it)',+ async name => {+ const result = resultFor(await resultsFor(fixture(name)), id);+ expect(+ ['pass', 'not-applicable'],+ `${id} against ${name}: ${result.detail ?? ''}`,+ ).toContain(result.status);+ },+ );++ it.each((TOOLTIP_MUTATIONS[id] ?? []).map(name => [name] as const))(+ 'fails against %s, which removes its outcome',+ async name => {+ const result = resultFor(await resultsFor(fixture(name)), id);+ expect(result.status, `${id} against ${name}`).toBe('fail');+ expect(result.detail ?? '').not.toBe('');+ },+ );++ it('carries its id and primary source into every result description', async () => {+ const target = fixture(+ TOOLTIP_MUTATIONS[id]?.[0] ?? CONFORMING_FIXTURES[0]!,+ );+ const result = resultFor(await resultsFor(target), id);+ expect(result.description).toContain(id);+ expect(result.description).toContain(citeSource(expectation.sources[0]));+ expect(describeExpectation(expectation)).toBe(result.description);+ });+ },+);diff --git a/internal/a11y-spec/src/patterns/tooltip.ts b/internal/a11y-spec/src/patterns/tooltip.tsnew file mode 100644index 0000000000..5f5ef93ea4--- /dev/null+++ b/internal/a11y-spec/src/patterns/tooltip.ts@@ -0,0 +1,730 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file tooltip.ts+ * @input WCAG 2.2 A/AA success criteria (1.3.1, 2.1.1, 4.1.2, and 1.4.13 Content on Hover or Focus), the APG Tooltip pattern's role, relationship, focus, and Escape requirements, and spec:AST-020 FR15+ * @output TOOLTIP_PATTERN — the reusable contract a tooltip binds to: its tooltip role, the trigger described by it, keyboard focus showing it while focus stays on the trigger, Escape dismissing it, and hover keeping it while the pointer rests on the trigger or the tooltip; focus leaving hiding it, hover showing it and the pointer leaving hiding it are advisory+ * @position Pattern contract; bound by Tooltip and useTooltip (`spec:AST-020/FR15`: a tooltip plays the tooltip role, so it adopts the pattern's role and relationship; it is not a composite control, so it gains no arrow or Home/End keys)+ */++import {+ definePattern,+ type ApgRequirement,+ type AstryxRecord,+ type PatternContract,+ type WcagCriterion,+} from '../contract';+import type {Harness, Subject} from '../harness';++const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/tooltip/';+const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';++const WCAG_1_3_1: WcagCriterion = {+ standard: 'wcag',+ id: '1.3.1',+ name: 'Info and Relationships',+ level: 'A',+ url: `${UNDERSTANDING}/info-and-relationships.html`,+};+const WCAG_1_4_13: WcagCriterion = {+ standard: 'wcag',+ id: '1.4.13',+ name: 'Content on Hover or Focus',+ level: 'AA',+ url: `${UNDERSTANDING}/content-on-hover-or-focus.html`,+};+const WCAG_2_1_1: WcagCriterion = {+ standard: 'wcag',+ id: '2.1.1',+ name: 'Keyboard',+ level: 'A',+ url: `${UNDERSTANDING}/keyboard.html`,+};+const WCAG_4_1_2: WcagCriterion = {+ standard: 'wcag',+ id: '4.1.2',+ name: 'Name, Role, Value',+ level: 'A',+ url: `${UNDERSTANDING}/name-role-value.html`,+};++const ROLES = `${APG_URL}#wai-ariaroles,states,andproperties`;+const KEYS = `${APG_URL}#keyboardinteraction`;++const APG_ROLE: ApgRequirement = {+ standard: 'apg',+ pattern: 'tooltip',+ requirement:+ 'The element that serves as the tooltip container has role tooltip.',+ url: ROLES,+};+const APG_DESCRIBEDBY: ApgRequirement = {+ standard: 'apg',+ pattern: 'tooltip',+ requirement:+ 'The element that triggers the tooltip references the tooltip element with aria-describedby.',+ url: ROLES,+};+const APG_SHOWS: ApgRequirement = {+ standard: 'apg',+ pattern: 'tooltip',+ requirement:+ 'A tooltip is a popup that displays information related to an element when the element receives keyboard focus or the mouse hovers over it.',+ url: APG_URL,+};+const APG_FOCUS_STAYS: ApgRequirement = {+ standard: 'apg',+ pattern: 'tooltip',+ requirement:+ 'Focus stays on the triggering element while the tooltip is displayed.',+ url: KEYS,+};+const APG_ESCAPE: ApgRequirement = {+ standard: 'apg',+ pattern: 'tooltip',+ requirement: 'Escape: Dismisses the Tooltip.',+ url: KEYS,+};+const APG_BLUR: ApgRequirement = {+ standard: 'apg',+ pattern: 'tooltip',+ requirement:+ 'If the tooltip is invoked when the trigger element receives focus, then it is dismissed when it no longer has focus (onBlur).',+ url: KEYS,+};+const APG_HOVER_STAYS: ApgRequirement = {+ standard: 'apg',+ pattern: 'tooltip',+ requirement:+ 'If the tooltip is invoked when a pointing cursor moves over the trigger element, then it remains open as long as the cursor is over the trigger or the tooltip.',+ url: KEYS,+};+const APG_MOUSE_OUT: ApgRequirement = {+ standard: 'apg',+ pattern: 'tooltip',+ requirement:+ 'It typically appears after a small delay and disappears when Escape is pressed or on mouse out.',+ url: APG_URL,+};++/**+ * The current Astryx adoption rule. A tooltip plays the tooltip role, so it+ * takes the pattern's role and its relationship to the trigger; keyboard focus+ * reaching the hint rests on WCAG 2.1.1. It is not one composite control, so+ * it gains no arrow or Home/End keys. The pattern's blur and hover behaviour is+ * not among the parts the rule names, so those rows stay advisory.+ */+const AST_020_FR15: AstryxRecord = {+ standard: 'astryx',+ id: 'spec:AST-020',+ clause: 'FR15',+ url: 'https://github.com/facebook/astryx/blob/577a62e5901911a24b5a485ac4c0bdf5fca4ef1f/docs/specs/AST-020/spec.md#L83-L92',+ requirement:+ "Where a component part already plays an APG pattern's role, Astryx adopts that pattern's required parts for it: the role, the accessible name, the state and relationship properties, and activation by Tab plus Enter or Space. The pattern's optional keyboard extras — arrow-key movement between parts, Home and End — are adopted only where the component already acts as one composite control.",+};++/**+ * What a binding knows about one tooltip. The subject is the trigger: the+ * element the tooltip describes, which takes focus and hover. Relations:+ * `tooltip` (the element with role tooltip, present in the page whether or+ * not it is showing), `before` and `after` (focusable controls on either side+ * of the trigger in the page Tab order).+ */+export interface TooltipStateFacts {+ /**+ * Whether resting the pointer on the trigger shows the tooltip. WCAG 1.4.13's+ * hoverable and dismissible requirements apply to content hover can show,+ * so the hover rows apply only when it can.+ */+ readonly showsOnHover: boolean;+ /** How long the binding waits after the pointer arrives before it shows the tooltip, in milliseconds. */+ readonly showDelayMs: number;+}++/** How long a tooltip gets to appear or disappear beyond its declared delay. */+const SETTLE_BUDGET_MS = 1000;+/**+ * How long the tooltip must stay while the pointer rests on the trigger or on+ * the tooltip itself. Longer than any hover bridge or hide delay a binding uses+ * to let the pointer cross between them, so a tooltip that times out or+ * vanishes on the crossing fails here.+ */+const PERSIST_MS = 1000;+const POLL_MS = 25;++const ALWAYS = {+ condition: 'the binding designates a tooltip and its trigger',+ test: () => true,+};++const ON_HOVER = {+ condition: 'resting the pointer on the trigger shows the tooltip',+ test: (facts: TooltipStateFacts) => facts.showsOnHover,+};++function pause(ms: number): Promise<void> {+ return new Promise(resolve => setTimeout(resolve, ms));+}++/** Whether `check` becomes true within `withinMs`, polling as the page settles. */+async function becomes(+ check: () => Promise<boolean>,+ withinMs: number,+): Promise<boolean> {+ const deadline = Date.now() + withinMs;+ for (;;) {+ if (await check()) {+ return true;+ }+ if (Date.now() >= deadline) {+ return false;+ }+ await pause(POLL_MS);+ }+}++async function expectHidden(tooltip: Subject, before: string): Promise<void> {+ if (await tooltip.isVisible()) {+ throw new Error(+ `the tooltip was already showing ${before}, so the check cannot tell what made it appear`,+ );+ }+}++async function expectShows(+ tooltip: Subject,+ withinMs: number,+ after: string,+): Promise<void> {+ if (!(await becomes(() => tooltip.isVisible(), withinMs))) {+ throw new Error(`${after} did not show the tooltip within ${withinMs}ms`);+ }+}++async function expectGone(+ tooltip: Subject,+ withinMs: number,+ after: string,+): Promise<void> {+ if (!(await becomes(async () => !(await tooltip.isVisible()), withinMs))) {+ throw new Error(+ `the tooltip was still showing ${withinMs}ms after ${after}`,+ );+ }+}++/** Tab from the control before the trigger, the way a keyboard user arrives. */+async function tabOntoTrigger(+ harness: Harness,+ trigger: Subject,+): Promise<void> {+ const before = await harness.related('before');+ await harness.pointerAway();+ await before.focus();+ if (!(await before.isFocused())) {+ throw new Error('the control before the trigger did not take focus');+ }+ await harness.press('Tab');+ if (!(await trigger.isFocused())) {+ throw new Error(+ 'Tab from the control before the trigger did not move focus to the trigger',+ );+ }+}++export const TOOLTIP_PATTERN: PatternContract<TooltipStateFacts> =+ definePattern<TooltipStateFacts>({+ pattern: 'tooltip',+ url: APG_URL,+ scope:+ "A tooltip's role, its trigger described by it, keyboard focus showing it while focus stays on the trigger, Escape dismissing it whether focus or hover showed it, and hover keeping it while the pointer rests on the trigger or the tooltip; focus leaving hiding it, hover showing it and the pointer leaving hiding it are reported as advisory.",+ expectations: [+ {+ id: 'tooltip.surface.role',+ outcome:+ 'The popup is a tooltip, so assistive technology treats it as a description of its trigger and not as a separate widget to visit.',+ sources: [WCAG_4_1_2, APG_ROLE],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({harness}) => {+ const role = await (+ await harness.related('tooltip')+ ).attribute('role');+ if (role !== 'tooltip') {+ throw new Error(+ `the popup's role is ${role == null ? 'absent' : `"${role}"`}, not tooltip`,+ );+ }+ },+ },+ {+ id: 'tooltip.trigger.described-by-tooltip',+ outcome:+ "The trigger's aria-describedby names the tooltip, so the relationship between the control and its hint is in the markup, not only in where the hint is painted.",+ sources: [WCAG_1_3_1, APG_DESCRIBEDBY],+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({harness, subject}) => {+ const tooltip = await harness.related('tooltip');+ if (+ !(await harness.references(subject, 'aria-describedby', tooltip))+ ) {+ const value = await subject.attribute('aria-describedby');+ throw new Error(+ `the trigger's aria-describedby (${value == null ? 'absent' : `"${value}"`}) does not name the tooltip`,+ );+ }+ },+ },+ {+ id: 'tooltip.trigger.description',+ outcome:+ "The browser computes the tooltip's text into the trigger's accessible description, so a screen-reader user hears the hint on the control without hovering it.",+ sources: [WCAG_4_1_2, APG_DESCRIBEDBY],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'accessibility-tree',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, subject}) => {+ const text = (await (await harness.related('tooltip')).textContent())+ .replace(/\s+/g, ' ')+ .trim();+ if (text === '') {+ throw new Error('the tooltip has no text to describe its trigger');+ }+ const {description} = await subject.computed();+ if (!description.replace(/\s+/g, ' ').includes(text)) {+ throw new Error(+ `the trigger's computed description is "${description}", which does not carry the tooltip's text "${text}"`,+ );+ }+ },+ },+ {+ id: 'tooltip.focus.shows-on-keyboard-focus',+ outcome:+ 'Tabbing onto the trigger shows the tooltip while focus stays on the trigger, and it stays as long as focus does, so a keyboard user gets the same hint a mouse user gets by hovering, has time to read it, and can carry on from the control.',+ sources: [+ WCAG_2_1_1,+ WCAG_1_4_13,+ APG_SHOWS,+ APG_FOCUS_STAYS,+ AST_020_FR15,+ ],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ const tooltip = await harness.related('tooltip');+ await harness.pointerAway();+ await harness.resetFocus();+ await expectHidden(tooltip, 'before the trigger had focus');+ await tabOntoTrigger(harness, subject);+ await expectShows(+ tooltip,+ facts.showDelayMs + SETTLE_BUDGET_MS,+ 'Tab onto the trigger',+ );+ if (!(await subject.isFocused())) {+ throw new Error(+ 'showing the tooltip moved focus off the trigger; focus stays on the trigger while the tooltip is displayed',+ );+ }+ await pause(PERSIST_MS);+ if (!(await tooltip.isVisible())) {+ throw new Error(+ `the tooltip disappeared within ${PERSIST_MS}ms while focus stayed on the trigger`,+ );+ }+ if (!(await subject.isFocused())) {+ throw new Error('focus left the trigger while the tooltip showed');+ }+ },+ },+ {+ id: 'tooltip.keys.escape-dismisses',+ outcome:+ 'Escape hides the tooltip without moving focus or the pointer, whether keyboard focus or (where it can) hover showed it, so a user can clear a hint that covers what they want to read.',+ sources: [WCAG_1_4_13, APG_ESCAPE],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ const tooltip = await harness.related('tooltip');+ const showWithin = facts.showDelayMs + SETTLE_BUDGET_MS;+ await harness.resetFocus();+ await tabOntoTrigger(harness, subject);+ await expectShows(tooltip, showWithin, 'Tab onto the trigger');+ await harness.press('Escape');+ await expectGone(+ tooltip,+ SETTLE_BUDGET_MS,+ 'Escape on the focused trigger',+ );+ if (!(await subject.isFocused())) {+ throw new Error('Escape moved focus off the trigger');+ }+ if (!facts.showsOnHover) {+ return;+ }++ await harness.resetFocus();+ await harness.pointerAway();+ await expectGone(+ tooltip,+ SETTLE_BUDGET_MS,+ 'focus and the pointer left',+ );+ await harness.hover(subject);+ await expectShows(tooltip, showWithin, 'hovering the trigger');+ await harness.press('Escape');+ await expectGone(+ tooltip,+ SETTLE_BUDGET_MS,+ 'Escape with the pointer resting on the trigger',+ );+ },+ },+ {+ id: 'tooltip.focus.leaving-hides',+ outcome:+ 'Tabbing off the trigger hides the tooltip, so a hint for a control the user has left does not linger over the next one.',+ sources: [APG_BLUR],+ wcagOutcome:+ 'Supports WCAG 2.2 2.4.11 Focus Not Obscured by keeping a hint for a control the user has left from lingering over the control they Tab to next; 2.4.11 itself is a placement outcome owned by the layer runtime and the page, so this row reports the shipped behaviour without gating.',+ covers: ['apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'advisory',+ advisoryBecause:+ 'Hiding on blur is the APG Tooltip pattern’s own behaviour, but spec:AST-020 FR15 names only the role, the name, the state and relationship properties and Tab plus Enter or Space as adopted required parts, and the Tooltip component record is draft; it becomes required once a current record names it as adopted (AST-020 FR9).',+ run: async ({harness, subject, facts}) => {+ const tooltip = await harness.related('tooltip');+ await harness.resetFocus();+ await tabOntoTrigger(harness, subject);+ await expectShows(+ tooltip,+ facts.showDelayMs + SETTLE_BUDGET_MS,+ 'Tab onto the trigger',+ );+ await harness.press('Tab');+ if (await subject.isFocused()) {+ throw new Error('Tab from the trigger left focus on it');+ }+ await expectGone(tooltip, SETTLE_BUDGET_MS, 'Tab off the trigger');+ },+ },+ {+ id: 'tooltip.hover.shows-on-hover',+ outcome:+ 'Resting the pointer on the trigger shows the tooltip after its delay, so a mouse user gets the hint without clicking.',+ sources: [APG_SHOWS],+ wcagOutcome:+ 'Supports WCAG 2.2 1.4.13 and 2.1.1 by giving a mouse user the hint keyboard focus already gives; WCAG requires the keyboard path, encoded above, not a hover path, so this row reports the shipped behaviour without gating.',+ covers: ['apg-interaction'],+ appliesWhen: ON_HOVER,+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'advisory',+ advisoryBecause:+ 'Showing on hover is part of the APG Tooltip definition, but spec:AST-020 FR15 names only the role, the name, the state and relationship properties and Tab plus Enter or Space as adopted required parts, and the Tooltip component record is draft; it becomes required once a current record names it as adopted (AST-020 FR9).',+ run: async ({harness, subject, facts}) => {+ const tooltip = await harness.related('tooltip');+ await harness.resetFocus();+ await harness.pointerAway();+ await expectGone(+ tooltip,+ SETTLE_BUDGET_MS,+ 'focus and the pointer left',+ );+ await harness.hover(subject);+ await expectShows(+ tooltip,+ facts.showDelayMs + SETTLE_BUDGET_MS,+ 'hovering the trigger',+ );+ },+ },+ {+ id: 'tooltip.hover.stays-while-hovered',+ outcome:+ 'The tooltip stays while the pointer rests on the trigger, and stays when the pointer moves onto the tooltip itself, so a mouse user can read it, or magnify it, without it timing out or vanishing under the pointer.',+ sources: [WCAG_1_4_13, APG_HOVER_STAYS],+ covers: ['apg-interaction'],+ appliesWhen: ON_HOVER,+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ const tooltip = await harness.related('tooltip');+ await harness.resetFocus();+ await harness.pointerAway();+ await expectGone(+ tooltip,+ SETTLE_BUDGET_MS,+ 'focus and the pointer left',+ );+ await harness.hover(subject);+ await expectShows(+ tooltip,+ facts.showDelayMs + SETTLE_BUDGET_MS,+ 'hovering the trigger',+ );+ await pause(PERSIST_MS);+ if (!(await tooltip.isVisible())) {+ throw new Error(+ `the tooltip disappeared within ${PERSIST_MS}ms while the pointer rested on the trigger`,+ );+ }+ await harness.hover(tooltip);+ await pause(PERSIST_MS);+ if (!(await tooltip.isVisible())) {+ throw new Error(+ 'the tooltip disappeared when the pointer moved from the trigger onto the tooltip',+ );+ }+ },+ },+ {+ id: 'tooltip.hover.leaving-hides',+ outcome:+ 'Moving the pointer off both the trigger and the tooltip hides the tooltip, so a hint does not stay behind over content the user has moved on to.',+ sources: [APG_MOUSE_OUT],+ wcagOutcome:+ 'Supports WCAG 2.2 1.4.13 by keeping hover content tied to the hover that summoned it; 1.4.13 itself requires only that the content can be dismissed (Escape, encoded above), so this row reports the shipped behaviour without gating.',+ covers: ['apg-interaction'],+ appliesWhen: ON_HOVER,+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'advisory',+ advisoryBecause:+ 'The APG describes hiding on mouse out as what a tooltip typically does, not as a required part, and WCAG 1.4.13 requires only that hover content be dismissible, which the Escape row gates; it becomes required once the binding’s component record names it as adopted and that record is current (AST-020 FR9, FR15).',+ run: async ({harness, subject, facts}) => {+ const tooltip = await harness.related('tooltip');+ await harness.resetFocus();+ await harness.pointerAway();+ await expectGone(+ tooltip,+ SETTLE_BUDGET_MS,+ 'focus and the pointer left',+ );+ await harness.hover(subject);+ await expectShows(+ tooltip,+ facts.showDelayMs + SETTLE_BUDGET_MS,+ 'hovering the trigger',+ );+ await harness.pointerAway();+ await expectGone(+ tooltip,+ SETTLE_BUDGET_MS,+ 'the pointer left the trigger and the tooltip',+ );+ },+ },+ ],+ exemptions: {+ '1.1.1-non-text-content': {+ owner: 'the trigger and caller content',+ verifiedBy:+ "the trigger's own pattern contract (button, link) and the repository axe audit, `pnpm a11y:audit`",+ reason:+ 'A tooltip paints no graphic of its own; an icon-only trigger names itself through its own pattern, and the tooltip describes it rather than naming it.',+ },+ '1.3.1-info-and-relationships': {+ owner: 'caller content',+ verifiedBy: 'content review of any structure placed inside a tooltip',+ reason:+ 'This contract encodes the trigger-to-tooltip relationship. Structure inside the tooltip text is caller content; a tooltip is short text, so headings or lists inside it are a content choice.',+ coversRemainderOnly: true,+ },+ '1.3.2-meaningful-sequence': {+ owner: 'the binding component and the layer runtime',+ verifiedBy:+ "the binding's layer placement tests (Tooltip.test.tsx) and the layer runtime's mount-position tests",+ reason:+ 'The tooltip reaches assistive technology through the description relationship, so where it sits in the reading order does not change what the trigger announces.',+ },+ '1.3.5-identify-input-purpose': {+ owner: 'the trigger and the composing form',+ verifiedBy:+ 'the text-input contract and form integration review of any user-information input that carries a tooltip',+ reason: 'A tooltip collects no information about the user.',+ },+ '1.4.1-use-of-color': {+ owner: 'the binding component and the theme',+ verifiedBy: 'the repository visual gate and forced-colors review',+ reason:+ 'A tooltip carries no state of its own that color alone could signal; its text is the content.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'the binding component and the theme',+ verifiedBy:+ 'the repository axe audit over component stories plus the visual gate',+ reason:+ 'Tooltip text contrast depends on the resolved inverted surface and text colors of the theme.',+ },+ '1.4.11-non-text-contrast': {+ owner: 'the binding component and the theme',+ verifiedBy:+ 'the repository visual gate and rendered review of the tooltip surface edge',+ reason:+ 'The tooltip surface boundary is a paint outcome owned by the component styling and the theme.',+ },+ '2.1.1-keyboard': {+ owner: 'the trigger',+ verifiedBy:+ "the trigger's own pattern contract (button, link) for its activation",+ reason:+ 'This contract encodes keyboard focus showing the tooltip and Escape dismissing it. Activating the trigger is the trigger’s own pattern; a tooltip itself takes no focus and has no activation.',+ coversRemainderOnly: true,+ },+ '2.1.2-no-keyboard-trap': {+ owner: 'the composing page',+ verifiedBy:+ 'this contract’s advisory focus-leaving row, which reports that Tab moves off the trigger, plus page-level keyboard review',+ reason:+ 'A tooltip takes no focus, so it cannot hold it; where Tab goes beyond the trigger is the composition.',+ },+ '2.4.2-page-titled': {+ owner: 'the page',+ verifiedBy: 'page-level review',+ reason: 'A tooltip rendered in isolation owns no document title.',+ },+ '2.4.3-focus-order': {+ owner: 'the trigger and the composing page',+ verifiedBy: 'page-level focus-order review',+ reason:+ 'A tooltip adds no stop to the Tab order; this contract proves focus stays on the trigger while it shows. The trigger among surrounding controls is the composition.',+ },+ '2.4.4-link-purpose': {+ owner: 'the link pattern and caller content',+ verifiedBy: 'LINK_PATTERN and content review of link text',+ reason:+ 'A link that carries a tooltip names its purpose through its own text; the tooltip only adds a description.',+ },+ '2.4.6-headings-and-labels': {+ owner: 'caller content',+ verifiedBy: 'content review of tooltip text',+ reason:+ 'Whether a tooltip’s text helps is a caller-content judgement; this contract checks that the text reaches the trigger’s description.',+ },+ '2.4.7-focus-visible': {+ owner:+ 'the interaction-modality architecture record, the trigger, and the theme',+ verifiedBy:+ "the trigger's focus-ring styling and the repository visual gate",+ reason:+ 'The focus ring belongs to the focused trigger; the tooltip never takes focus.',+ },+ '2.4.11-focus-not-obscured': {+ owner:+ 'the binding component, the layer runtime and the composing page',+ verifiedBy:+ "the layer runtime's anchor-placement tests and page-level review of sticky surfaces",+ reason:+ 'The tooltip is placed beside its trigger by the layer runtime, so whether it or another surface hides a focused control is placement and page geometry; this contract’s advisory focus-leaving row reports that it leaves when focus does.',+ },+ '2.5.2-pointer-cancellation': {+ owner: 'the trigger',+ verifiedBy: "the trigger's own pattern contract (button, link)",+ reason:+ 'A tooltip has no pointer activation of its own; pressing the trigger is the trigger’s action.',+ },+ '2.5.3-label-in-name': {+ owner: 'the trigger and caller content',+ verifiedBy:+ "the trigger's own pattern contract and content review of visible labels",+ reason:+ 'A tooltip describes its trigger; it does not supply the name, so the visible label and the name are the trigger’s.',+ },+ '2.5.8-target-size': {+ owner: 'the trigger and the theme',+ verifiedBy: "the repository axe audit's target-size rule",+ reason: 'A tooltip is not a pointer target; the target is the trigger.',+ },+ '3.1.1-language-of-page': {+ owner: 'the page',+ verifiedBy: 'page-level language review',+ reason: 'A tooltip rendered in isolation owns no document language.',+ },+ '3.2.2-on-input': {+ owner: 'the trigger and the caller',+ verifiedBy: 'integration review of what the trigger does when changed',+ reason:+ 'Showing or hiding a tooltip changes no setting; what the trigger does when operated is the trigger and its caller.',+ },+ '3.2.4-consistent-identification': {+ owner: 'the design system and caller content',+ verifiedBy:+ 'this shared contract across bindings plus content review of repeated tooltip text',+ reason:+ 'Consistency is a property of the set of repeated tooltips, not one tooltip.',+ },+ '3.3.1-error-identification': {+ owner: 'the composing form and the field status pattern',+ verifiedBy: 'form-level error-state review',+ reason:+ 'The tooltip pattern defines no validation error state; a field error is announced by the field, not by a hover hint.',+ },+ '3.3.2-labels-or-instructions': {+ owner: 'the trigger and caller content',+ verifiedBy: 'form-level review of labels and instructions',+ reason:+ 'A tooltip may carry an instruction, but whether a field’s instructions are sufficient is the field and its caller.',+ },+ '4.1.2-name-role-value': {+ owner: 'the trigger',+ verifiedBy: "the trigger's own pattern contract (button, link)",+ reason:+ 'This contract encodes the tooltip role and the description it gives the trigger. The trigger’s own role, name and state are its own pattern.',+ coversRemainderOnly: true,+ },+ '4.1.3-status-messages': {+ owner:+ 'the caller and the assistive-technology verification record, spec:AST-009',+ verifiedBy:+ 'the status-message pattern and real-AT evidence under AST-009 when a change claims spoken output',+ reason:+ 'A tooltip is a description read with its trigger, not a status message, and this pattern makes no announcement claim.',+ },+ 'apg-interaction': {+ owner: 'the binding component and caller content',+ verifiedBy:+ "the binding's touch-trigger, controlled-open and press-to-hide tests (Tooltip.test.tsx, useTooltip.test.tsx) and content review",+ reason:+ 'This contract encodes the role, the description relationship, focus showing, Escape and hover staying, and reports focus leaving, hover showing and pointer leaving as advisory. That a tooltip holds no focusable content is caller content — interactive hover content belongs to a non-modal dialog such as HoverCard, not a tooltip; touch, where there is no hover, and press-to-hide are binding behaviour the APG leaves to the author.',+ coversRemainderOnly: true,+ },+ 'forced-colors': {+ owner: 'the binding component and the theme',+ verifiedBy:+ 'rendered Windows High Contrast review of the tooltip surface',+ reason: 'Forced-colors output is a paint result.',+ },+ 'reduced-motion': {+ owner: 'the layer runtime and the theme',+ verifiedBy:+ 'the layer animation reduced-motion source tests and rendered motion review',+ reason:+ 'The tooltip’s entry and exit motion comes from the shared layer animations.',+ },+ 'at-facing-strings': {+ owner: 'caller content',+ verifiedBy:+ 'the repository i18n catalog check and source review of authored tooltip text',+ reason:+ 'The tooltip contract introduces no string; the tooltip text comes from the caller.',+ },+ },+ });diff --git a/packages/core/src/Tooltip/Tooltip.test.tsx b/packages/core/src/Tooltip/Tooltip.test.tsxindex ac584dac85..8eeef43b50 100644--- a/packages/core/src/Tooltip/Tooltip.test.tsx+++ b/packages/core/src/Tooltip/Tooltip.test.tsx@@ -84,17 +84,15 @@ describe('Tooltip', () => {expect(screen.getByRole('button', {name: 'Trigger'})).toBeInTheDocument();});- it('gives the tooltip layer role="tooltip" linked from the trigger', () => {+ it('renders the content prop inside the tooltip layer', () => {render(<Tooltip content="Tooltip text"><button type="button">Trigger</button></Tooltip>,);- const layer = screen.getByRole('tooltip', {hidden: true});- expect(layer).toHaveTextContent('Tooltip text');- // ARIA tooltip pattern: trigger references the layer via aria-describedby.- const trigger = screen.getByRole('button', {name: 'Trigger'});- expect(trigger.getAttribute('aria-describedby')).toBe(layer.id);+ expect(screen.getByRole('tooltip', {hidden: true})).toHaveTextContent(+ 'Tooltip text',+ );});it('calls onOpenChange(true) when shown via hover', async () => {diff --git a/packages/core/src/Tooltip/__tests__/Tooltip.a11y.chromium.spec.ts b/packages/core/src/Tooltip/__tests__/Tooltip.a11y.chromium.spec.tsnew file mode 100644index 0000000000..d15d43baa9--- /dev/null+++ b/packages/core/src/Tooltip/__tests__/Tooltip.a11y.chromium.spec.ts@@ -0,0 +1,129 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tooltip.a11y.chromium.spec.ts+ * @input Built tooltip stories and TOOLTIP_PATTERN in real Chromium+ * @output Browser evidence for every tooltip expectation across Tooltip's and useTooltip's representative states+ * @position Chromium lane of the Tooltip binding+ */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ TOOLTIP_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 {+ TOOLTIP_BINDING_STATES,+ type TooltipBindingState,+} from './Tooltip.a11y.states';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++function storyUrl(storyId: string): string {+ return `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story`;+}++async function mountState(+ page: Page,+ state: TooltipBindingState,+): Promise<{subject: Locator; related: Record<string, Locator>}> {+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});+ await holdMotionStill(page);+ const root = page.locator('#storybook-root');+ const subject =+ state.triggerRole == null+ ? root.getByText(state.triggerText, {exact: true})+ : root.getByRole(state.triggerRole, {+ name: state.triggerText,+ exact: true,+ });+ await expect(subject).toBeVisible();+ return {+ subject,+ related: {+ // The layer may mount the tooltip outside the story root, and it stays+ // in the page while hidden, so it is found page-wide, hidden included.+ tooltip: page.getByRole('tooltip', {includeHidden: true}),+ before: root.getByRole('button', {+ name: 'Before the trigger',+ exact: true,+ }),+ after: root.getByRole('button', {+ name: 'After the trigger',+ exact: true,+ }),+ },+ };+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: TooltipBindingState,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: TOOLTIP_PATTERN,+ binding: 'Tooltip',+ state: state.id,+ facts: state.facts,+ mount: async () => {+ const {subject, related} = await mountState(page, state);+ return createChromiumHarness({page, cdp, subject, related});+ },+ });+}++test('every tooltip expectation is exercised by a Tooltip state', async ({+ page,+}) => {+ test.setTimeout(3 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of TOOLTIP_BINDING_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(neverExercised(results)).toEqual([]);+});++for (const state of TOOLTIP_BINDING_STATES) {+ test(`Tooltip [${state.id}] — ${state.summary}`, async ({page}) => {+ test.setTimeout(2 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(TOOLTIP_PATTERN, [result]);+ // Required rows block (AST-020 FR9); advisory rows report.+ expect(formatFailures(blockingResults([result]))).toBe('');+ expect(report.unrunLayers).toEqual([]);+ expect(report.counts.unexpectedPass).toBe(0);+ });+}diff --git a/packages/core/src/Tooltip/__tests__/Tooltip.a11y.renders.tsx b/packages/core/src/Tooltip/__tests__/Tooltip.a11y.renders.tsxnew file mode 100644index 0000000000..c3553e0cf7--- /dev/null+++ b/packages/core/src/Tooltip/__tests__/Tooltip.a11y.renders.tsx@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file Tooltip.a11y.renders.tsx+ * @input One tooltip binding state from Tooltip.a11y.states.ts+ * @output The React tree every lane renders for that state (the jsdom test directly, the story through Storybook): a page button before the trigger, the trigger and its tooltip, and a page button after it+ * @position Shared fixture for the Tooltip and useTooltip binding+ */++import {useRef, type ReactElement} from 'react';+import {Button} from '../../Button/Button';+import {isRenderable} from '../../utils/isRenderable';+import {Tooltip} from '../Tooltip';+import {useTooltip} from '../useTooltip';+import type {TooltipBindingState} from './Tooltip.a11y.states';++const HINT_ID = 'tooltip-a11y-hint';++type TriggerState = Pick<+ TooltipBindingState,+ 'attachment' | 'triggerText' | 'content' | 'hint'+>;++/** A caller button the tooltip attaches to through `anchorRef`. */+function AnchorRefTrigger({state}: {state: TriggerState}): ReactElement {+ const anchorRef = useRef<HTMLButtonElement>(null);+ return (+ <>+ <button+ ref={anchorRef}+ type="button"+ aria-describedby={state.hint == null ? undefined : HINT_ID}>+ {state.triggerText}+ </button>+ <Tooltip anchorRef={anchorRef} content={state.content} />+ </>+ );+}++/** A caller button wired by hand through `useTooltip`. */+function HookTrigger({state}: {state: TriggerState}): ReactElement {+ const tooltip = useTooltip();+ return (+ <>+ <button+ ref={tooltip.ref}+ type="button"+ aria-describedby={tooltip.describedBy}>+ {state.triggerText}+ </button>+ {tooltip.renderTooltip(state.content)}+ </>+ );+}++function Trigger({state}: {state: TriggerState}): ReactElement {+ switch (state.attachment) {+ case 'wrapped-element':+ return (+ <Tooltip content={state.content}>+ <Button label={state.triggerText} />+ </Tooltip>+ );+ case 'text':+ return <Tooltip content={state.content}>{state.triggerText}</Tooltip>;+ case 'anchor-ref':+ return <AnchorRefTrigger state={state} />;+ case 'hook':+ return <HookTrigger state={state} />;+ }+}++export function renderTooltipState(state: TriggerState): ReactElement {+ return (+ <div style={{padding: 64}}>+ <button type="button">Before the trigger</button>{' '}+ <Trigger state={state} />+ {isRenderable(state.hint) ? (+ <span id={HINT_ID}> {state.hint}</span>+ ) : null}{' '}+ <button type="button">After the trigger</button>+ </div>+ );+}diff --git a/packages/core/src/Tooltip/__tests__/Tooltip.a11y.states.ts b/packages/core/src/Tooltip/__tests__/Tooltip.a11y.states.tsnew file mode 100644index 0000000000..4e95448185--- /dev/null+++ b/packages/core/src/Tooltip/__tests__/Tooltip.a11y.states.ts@@ -0,0 +1,132 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tooltip.a11y.states.ts+ * @input Tooltip's and useTooltip's representative states and the facts TOOLTIP_PATTERN reads+ * @output TOOLTIP_BINDING_STATES and the explicit ownership exclusions for this binding+ * @position Binding inventory shared by the jsdom test and the Chromium spec (Tooltip and useTooltip under spec:AST-020 FR15)+ */++import type {TooltipStateFacts} from '@astryxdesign/a11y-spec';++/**+ * How the caller attaches the tooltip: wrapping an element, wrapping plain+ * text, pointing `anchorRef` at its own element, or calling `useTooltip`.+ */+export type TooltipAttachment =+ 'wrapped-element' | 'text' | 'anchor-ref' | 'hook';++export interface TooltipBindingState {+ readonly id: string;+ readonly summary: string;+ readonly storyId: string;+ readonly attachment: TooltipAttachment;+ /**+ * The trigger's visible text. A `button` trigger is also named by it; a+ * text trigger has no role, so the lanes find it by this text.+ */+ readonly triggerText: string;+ readonly triggerRole: 'button' | null;+ /** The tooltip `content`. */+ readonly content: string;+ /** A visible hint the trigger is already described by, besides the tooltip. */+ readonly hint?: string;+ readonly facts: TooltipStateFacts;+}++const story = (id: string) => `a11y-tooltip--${id}`;++/** Tooltip's and useTooltip's default hover delay. */+const DEFAULT_DELAY: TooltipStateFacts = {showsOnHover: true, showDelayMs: 200};++export const TOOLTIP_BINDING_STATES = [+ {+ id: 'wrapped-button',+ summary:+ 'a Tooltip wrapping a Button, which attaches to the Button and describes it',+ storyId: story('wrapped-button'),+ attachment: 'wrapped-element',+ triggerText: 'Save',+ triggerRole: 'button',+ content: 'Saves your changes to this draft',+ facts: DEFAULT_DELAY,+ },+ {+ id: 'text-trigger',+ summary:+ 'a Tooltip wrapping plain text, which renders its own focusable inline trigger',+ storyId: story('text-trigger'),+ attachment: 'text',+ triggerText: 'Draft',+ triggerRole: null,+ content: 'Only you can see a draft',+ facts: DEFAULT_DELAY,+ },+ {+ id: 'anchor-ref-with-hint',+ summary:+ 'a Tooltip attached through anchorRef to a caller button that is already described by a visible hint, so the trigger is described by both',+ storyId: story('anchor-ref-with-hint'),+ attachment: 'anchor-ref',+ triggerText: 'Publish',+ triggerRole: 'button',+ content: 'Makes this page visible to everyone',+ hint: 'Last published yesterday',+ facts: DEFAULT_DELAY,+ },+ {+ id: 'use-tooltip-hook',+ summary:+ "useTooltip on a caller button, which spreads the hook's ref and describedBy onto it and renders the tooltip",+ storyId: story('use-tooltip-hook'),+ attachment: 'hook',+ triggerText: 'Archive',+ triggerRole: 'button',+ content: 'Moves this page out of the list',+ facts: DEFAULT_DELAY,+ },+] as const satisfies ReadonlyArray<TooltipBindingState>;++export const TOOLTIP_EXCLUSIONS = [+ {+ id: 'focus-trigger',+ owner:+ "the 24 core hosts that pass focusTrigger 'always' — the disabledMessage tooltips on the field and choice controls (TextInput, TextArea, NumberInput, Switch, CheckboxInput, CheckboxList, RadioList, Selector, MultiSelector, SegmentedControl, Slider, Typeahead, Tokenizer, FileInput, and the date and time inputs), the Slider value bubble and ProgressBar marks — each through its own suite (for example TextInput.test.tsx 'shows the reason tooltip on keyboard focus'); and any caller that passes 'never'",+ reason:+ "'always' attaches the focus listeners to a wrapper that is not itself focusable, so focusin bubbling from the control inside it shows the hint; the described element and the focused element differ, which this contract's trigger-centred rows do not model, so each host proves its own keyboard path. 'never' detaches focus showing for a trigger inside a composite widget that moves focus itself, which then owns how a keyboard user reaches the hint; no shipped composition uses it. Every state here uses the default 'auto'.",+ },+ {+ id: 'touch-trigger',+ owner:+ 'useTooltip.test.tsx and Tooltip.test.tsx (touchTrigger suites) through the shared useTouchTrigger hook',+ reason:+ 'On a touch pointer there is no hover, so a tap opens the tooltip or leaves it to the control the tap operates; the APG defines no touch behaviour, and the Chromium lane drives a mouse and a keyboard only.',+ },+ {+ id: 'controlled-and-disabled',+ owner:+ 'Tooltip.test.tsx and useTooltip.test.tsx (isOpen, isDefaultOpen and isEnabled suites)',+ reason:+ 'A controlled tooltip answers Escape by reporting instead of hiding, and a disabled one never shows; both hand visibility to the caller, so the hover and focus outcomes this contract reads belong to the uncontrolled, enabled tooltip every state renders.',+ },+ {+ id: 'interactive-hover-content',+ owner: 'the HoverCard binding and the overlay-dismissal family',+ reason:+ 'Hover content a user can interact with is a non-modal dialog, not a tooltip, so HoverCard and other interactive popovers are reviewed separately; no state here places a focusable control inside a tooltip.',+ },+ {+ id: 'host-compositions',+ owner:+ "the composing components' own contracts (Button for the IconButton label tooltip, the input status binding for useInputStatusIcon, which renders the on-field status tooltip) and their tests",+ reason:+ 'IconButton, useInputStatusIcon and Lab InfoTip render Tooltip or useTooltip for their own purposes; this binding proves the tooltip they render, and what each host adds around it is that host.',+ },+ {+ id: 'placement-and-paint',+ owner:+ 'Tooltip.test.tsx (placement and alignment), the layer runtime anchor tests, and the repository visual gate',+ reason:+ 'Placement, alignment, the inverted surface and the hover underline on a text trigger are layout and paint; they change no role, description, focus or dismissal outcome, so every state uses the default placement.',+ },+] as const;diff --git a/packages/core/src/Tooltip/__tests__/Tooltip.a11y.test.tsx b/packages/core/src/Tooltip/__tests__/Tooltip.a11y.test.tsxnew file mode 100644index 0000000000..8dd104e7d2--- /dev/null+++ b/packages/core/src/Tooltip/__tests__/Tooltip.a11y.test.tsx@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file Tooltip.a11y.test.tsx+ * @input TOOLTIP_PATTERN bound to Tooltip's and useTooltip's representative states+ * @output jsdom-lane proof of the DOM expectations and an honest "unrun" report for the browser layers+ * @position Binding test for Tooltip and useTooltip (the Chromium spec covers the rest)+ */++import {cleanup, render, screen} from '@testing-library/react';+import {describe, expect, it} from 'vitest';+import {+ TOOLTIP_PATTERN,+ checkAccessibilitySpec,+ createJsdomHarness,+ expectAccessibilitySpec,+ summarize,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {renderTooltipState} from './Tooltip.a11y.renders';+import {+ TOOLTIP_BINDING_STATES,+ TOOLTIP_EXCLUSIONS,+ type TooltipBindingState,+} from './Tooltip.a11y.states';++function triggerFor(state: TooltipBindingState): HTMLElement {+ return state.triggerRole == null+ ? screen.getByText(state.triggerText, {exact: true})+ : screen.getByRole(state.triggerRole, {name: state.triggerText});+}++function relatedFor(): Readonly<Record<string, Element>> {+ return {+ // The tooltip stays in the page while hidden; it is found with hidden+ // elements included so the DOM rows can read it before it shows.+ tooltip: screen.getByRole('tooltip', {hidden: true}),+ before: screen.getByRole('button', {name: 'Before the trigger'}),+ after: screen.getByRole('button', {name: 'After the trigger'}),+ };+}++async function checkState(state: TooltipBindingState): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: TOOLTIP_PATTERN,+ binding: 'Tooltip',+ state: state.id,+ facts: state.facts,+ mount: async () => {+ render(renderTooltipState(state));+ return createJsdomHarness({+ subject: triggerFor(state),+ related: relatedFor(),+ });+ },+ unmount: cleanup,+ });+}++describe('Tooltip — tooltip pattern, jsdom lane', () => {+ it.each(+ TOOLTIP_BINDING_STATES.map(+ state => [state.id, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectAccessibilitySpec({+ spec: TOOLTIP_PATTERN,+ binding: 'Tooltip',+ state: state.id,+ facts: state.facts,+ render: () => {+ render(renderTooltipState(state));+ },+ subject: () => triggerFor(state),+ related: () => relatedFor(),+ cleanup,+ });+ });++ it('runs the DOM layer and reports the browser-owned outcomes as unrun', async () => {+ const results: BindingResult[] = [];+ for (const state of TOOLTIP_BINDING_STATES) {+ results.push(await checkState(state));+ }+ const report = summarize(TOOLTIP_PATTERN, results);+ expect(report.counts.pass).toBeGreaterThan(0);+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);+ expect(report.counts.unexpectedPass).toBe(0);+ });+});++describe('tooltip binding inventory', () => {+ it('gives every representative state a distinct checked-in story', () => {+ const stories = TOOLTIP_BINDING_STATES.map(state => state.storyId);+ expect(new Set(stories).size).toBe(stories.length);+ });++ it('keeps focus-trigger opt-outs, touch, controlled visibility, interactive hover content, host compositions and paint explicit', () => {+ expect(TOOLTIP_EXCLUSIONS.map(row => row.id)).toEqual([+ 'focus-trigger',+ 'touch-trigger',+ 'controlled-and-disabled',+ 'interactive-hover-content',+ 'host-compositions',+ 'placement-and-paint',+ ]);+ for (const exclusion of TOOLTIP_EXCLUSIONS) {+ expect(exclusion.owner.length, exclusion.id).toBeGreaterThan(20);+ expect(exclusion.reason.length, exclusion.id).toBeGreaterThan(80);+ }+ });++ it('renders the trigger, one tooltip and both page buttons for every state', () => {+ for (const state of TOOLTIP_BINDING_STATES) {+ render(renderTooltipState(state));+ expect(triggerFor(state), state.id).toBeTruthy();+ expect(+ screen.getAllByRole('tooltip', {hidden: true}),+ state.id,+ ).toHaveLength(1);+ expect(Object.keys(relatedFor())).toEqual(['tooltip', 'before', 'after']);+ cleanup();+ }+ });+});