An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): add Toolbar contract and bind Toolbar (#7731)
Cindy Zhang29fc5f906505
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ef0185f0dd..938e571178 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1680,6 +1680,56 @@ jobs:retention-days: 30if-no-files-found: warn+ # The toolbar contract's role and name, the controls inside it, the single+ # Tab stop, and the arrow (wrap, RTL, vertical) and Home/End movement are+ # accessibility-tree and real-browser facts that jsdom cannot observe. Run+ # the contract's own fixture proof and the Toolbar binding whenever+ # Toolbar 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 Toolbar accessibility contract+ id: toolbar-contract+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}+ env:+ BASE_SHA: ${{ github.event.pull_request.base.sha }}+ PLAYWRIGHT_JSON_OUTPUT_FILE: toolbar-contract/report.json+ run: |+ should_run=false+ # Toolbar 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/toolbar\.|packages/core/src/Toolbar/|apps/storybook/stories/ToolbarA11y)' || scope=$?+ fi+ if [ "$scope" != 1 ]; then+ should_run=true+ fi+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"+ if [ "$should_run" != true ]; then+ echo "Toolbar and the toolbar contract are not in PR scope; skipping toolbar evidence."+ exit 0+ fi+ pnpm exec playwright test \+ internal/a11y-spec/src/patterns/toolbar.chromium.spec.ts \+ packages/core/src/Toolbar/__tests__/Toolbar.a11y.chromium.spec.ts \+ --project chromium \+ --reporter list,json \+ --output toolbar-contract-output++ - name: Upload Toolbar accessibility contract evidence+ if: ${{ !cancelled() && steps.toolbar-contract.outputs.should_run == 'true' }}+ uses: actions/upload-artifact@v7+ with:+ name: toolbar-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: toolbar-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/ToolbarA11y.stories.tsx b/apps/storybook/stories/ToolbarA11y.stories.tsxnew file mode 100644index 0000000000..9dde96ae83--- /dev/null+++ b/apps/storybook/stories/ToolbarA11y.stories.tsx@@ -0,0 +1,34 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ToolbarA11y.stories.tsx+ * @input The Toolbar 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 Toolbar binding (TOOLBAR_PATTERN)+ */++import type {Meta, StoryObj} from '@storybook/react';+import {renderToolbarState} from '../../../packages/core/src/Toolbar/__tests__/Toolbar.a11y.renders';+import {TOOLBAR_BINDING_STATES} from '../../../packages/core/src/Toolbar/__tests__/Toolbar.a11y.states';++const meta = {+ title: 'A11y/Toolbar',+ tags: ['no-visual'],+ parameters: {layout: 'padded'},+} satisfies Meta;++export default meta;+type Story = StoryObj<typeof meta>;++function storyFor(id: (typeof TOOLBAR_BINDING_STATES)[number]['id']): Story {+ const state = TOOLBAR_BINDING_STATES.find(candidate => candidate.id === id);+ if (state == null) {+ throw new Error(`no Toolbar binding state "${id}"`);+ }+ return {render: () => renderToolbarState(state)};+}++export const Horizontal = storyFor('horizontal');+export const HorizontalRtl = storyFor('horizontal-rtl');+export const Vertical = storyFor('vertical');+export const FirstControlDisabled = storyFor('first-control-disabled');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex c2c28fabbb..b5033f499a 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -53,6 +53,7 @@ src/├── disclosure.* standalone disclosure state/content semantics├── menu-button.* a control's button role and name, aria-haspopup, expanded state, controls, and keyboard opens├── menu.* a displayed menu's role and name, item roles/names/checked/disabled state, and arrow/Home/End/Enter/Escape/Tab keys (typeahead advisory)+ ├── 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├── 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@@ -84,6 +85,7 @@ src/| `disclosure` | [APG Disclosure](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/) | Standalone Collapsible triggers and their controlled content || `menu-button` | [APG Menu Button](https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/) required parts; the optional ArrowDown/ArrowUp opens Astryx ships are advisory | Anchored DropdownMenu and MoreMenu triggers: button role and name, `aria-haspopup="menu"`, `aria-expanded`, `aria-controls`, Enter/Space open on the first enabled item (advisory: ArrowDown on the first, ArrowUp on the last) || `menu` | [APG Menu and Menubar](https://www.w3.org/WAI/ARIA/apg/patterns/menubar/) menu; arrows (with wrap) and Home/End per AST-020 FR15; typeahead advisory | DropdownMenu pointer menu: named `menu`, item roles/names, `aria-checked`, `aria-disabled`, arrows with wrap, Home/End, Enter and Escape back to the trigger, Tab out (advisory: typeahead) |+| `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 || `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 e11e994a4b..e4af7b60b4 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -172,3 +172,4 @@ export {type LinkCurrentToken,type LinkStateFacts,} from './patterns/link';+export {TOOLBAR_PATTERN, type ToolbarStateFacts} from './patterns/toolbar';diff --git a/internal/a11y-spec/src/patterns/toolbar.chromium.spec.ts b/internal/a11y-spec/src/patterns/toolbar.chromium.spec.tsnew file mode 100644index 0000000000..c72e9808ce--- /dev/null+++ b/internal/a11y-spec/src/patterns/toolbar.chromium.spec.ts@@ -0,0 +1,101 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file toolbar.chromium.spec.ts+ * @input TOOLBAR_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 {TOOLBAR_PATTERN} from './toolbar';+import {+ TOOLBAR_MUTATIONS,+ CONFORMING_FIXTURES,+ SUBJECT_SELECTOR,+ fixture,+ type ToolbarFixture,+} from './toolbar.fixtures';++function fixturePage(html: string): string {+ return `<!doctype html><html lang="en"><body>${html}</body></html>`;+}++async function results(+ page: Page,+ cdp: CDPSession,+ target: ToolbarFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ const run = await checkAccessibilitySpec({+ spec: TOOLBAR_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('toolbar 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('toolbar contract — deliberately violating fixtures', () => {+ for (const expectation of TOOLBAR_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of TOOLBAR_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/toolbar.fixtures.ts b/internal/a11y-spec/src/patterns/toolbar.fixtures.tsnew file mode 100644index 0000000000..343a2b8ade--- /dev/null+++ b/internal/a11y-spec/src/patterns/toolbar.fixtures.ts@@ -0,0 +1,344 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file toolbar.fixtures.ts+ * @input Plain HTML toolbars between two page buttons, conforming and deliberately violating+ * @output TOOLBAR_FIXTURES, their subject and relation selectors, and the expectation → violating-fixture map+ * @position Contract self-test data for toolbar.jsdom.test.ts and toolbar.chromium.spec.ts+ */++import type {ToolbarStateFacts} from './toolbar';++export const SUBJECT_SELECTOR = '#toolbar';++/**+ * How the fixture toolbar behaves. One script reads these from the toolbar's+ * data attributes, so a violating fixture changes exactly one behavior.+ */+interface Behavior {+ /** Controls the next arrow advances by. */+ readonly nextStep?: 1 | 2;+ /** Whether the previous arrow moves at all. */+ readonly previous?: boolean;+ readonly wrap?: boolean;+ readonly homeEnd?: boolean;+ /**+ * Which arrows move: the toolbar's own axis and direction, the horizontal+ * pair whatever the orientation, or Right as next whatever the direction.+ */+ readonly keys?: 'axis' | 'horizontal-only' | 'ignore-direction';+ /**+ * Tab stops: one roving stop on the first enabled control, every control+ * tabbable, or the one stop left on the first control even when disabled.+ */+ readonly stops?: 'roving' | 'every-control' | 'first-even-if-disabled';+}++/**+ * The smallest toolbar behavior: a roving tab stop over enabled controls, the+ * next/previous arrows on the toolbar's axis (mirrored under RTL), optional+ * wrap and Home/End. jsdom does not run it; the jsdom lane reads DOM+ * attributes only.+ */+const SCRIPT = `<script>(() => {+ const bar = document.getElementById('toolbar');+ const d = bar.dataset;+ const all = () => [...bar.querySelectorAll('[data-control]')];+ const enabled = () => all().filter(c => c.getAttribute('aria-disabled') !== 'true');+ const stamp = target => all().forEach(c => { c.tabIndex = c === target ? 0 : -1; });+ if (d.stops === 'every-control') all().forEach(c => { c.tabIndex = 0; });+ else stamp(d.stops === 'first-even-if-disabled' ? all()[0] : enabled()[0]);+ bar.addEventListener('focusin', event => {+ if (d.stops === 'roving' && enabled().includes(event.target)) stamp(event.target);+ });+ bar.addEventListener('keydown', event => {+ const list = enabled();+ const n = list.length;+ const i = list.indexOf(document.activeElement);+ if (i < 0) return;+ const vertical = bar.getAttribute('data-axis') === 'vertical';+ const rtl = getComputedStyle(bar).direction === 'rtl';+ let nextKey = 'ArrowRight';+ let previousKey = 'ArrowLeft';+ if (d.keys === 'axis' && vertical) { nextKey = 'ArrowDown'; previousKey = 'ArrowUp'; }+ else if (d.keys === 'axis' && rtl) { nextKey = 'ArrowLeft'; previousKey = 'ArrowRight'; }+ const go = k => { event.preventDefault(); list[k].focus(); };+ if (event.key === nextKey) {+ const k = i + Number(d.nextStep);+ return go(k < n ? k : d.wrap === 'true' ? 0 : n - 1);+ }+ if (event.key === previousKey) {+ if (d.previous !== 'true') return;+ return go(i > 0 ? i - 1 : d.wrap === 'true' ? n - 1 : 0);+ }+ if (event.key === 'Home' && d.homeEnd === 'true') return go(0);+ if (event.key === 'End' && d.homeEnd === 'true') return go(n - 1);+ });+})();</script>`;++interface Control {+ readonly id: string;+ readonly label: string;+ readonly disabled?: boolean;+}++const FORMATTING: readonly Control[] = [+ {id: 'bold', label: 'Bold'},+ {id: 'italic', label: 'Italic'},+ {id: 'underline', label: 'Underline'},+ {id: 'settings', label: 'Settings'},+];++const WITH_DISABLED_FIRST: readonly Control[] = [+ {id: 'undo', label: 'Undo', disabled: true},+ {id: 'bold', label: 'Bold'},+ {id: 'italic', label: 'Italic'},+ {id: 'settings', label: 'Settings'},+];++function controlHtml(control: Control): string {+ return `<button type="button" id="${control.id}" data-control${control.disabled ? ' aria-disabled="true"' : ''}>${control.label}</button>`;+}++function toolbarHtml({+ controls = FORMATTING,+ behavior = {},+ role = 'toolbar',+ label = 'Text formatting',+ orientation = 'horizontal',+ orientationAttribute = orientation === 'vertical' ? 'vertical' : null,+ dir = 'ltr',+ outside = null,+}: {+ controls?: readonly Control[];+ behavior?: Behavior;+ role?: string;+ label?: string | null;+ orientation?: ToolbarStateFacts['orientation'];+ /** The aria-orientation the toolbar carries; null for none. */+ orientationAttribute?: string | null;+ dir?: ToolbarStateFacts['direction'];+ /** A control rendered after the toolbar instead of inside it. */+ outside?: Control | null;+}): string {+ const b: Required<Behavior> = {+ nextStep: 1,+ previous: true,+ wrap: true,+ homeEnd: true,+ keys: 'axis',+ stops: 'roving',+ ...behavior,+ };+ const data = `data-axis="${orientation}" data-next-step="${b.nextStep}" data-previous="${b.previous}" data-wrap="${b.wrap}" data-home-end="${b.homeEnd}" data-keys="${b.keys}" data-stops="${b.stops}"`;+ const attributes = [+ `id="toolbar"`,+ `role="${role}"`,+ label == null ? null : `aria-label="${label}"`,+ orientationAttribute == null+ ? null+ : `aria-orientation="${orientationAttribute}"`,+ data,+ ]+ .filter(attribute => attribute != null)+ .join(' ');+ const flow = orientation === 'vertical' ? 'column' : 'row';+ return `<div dir="${dir}"><button type="button" id="before">Before toolbar</button><div ${attributes} style="display:flex;flex-direction:${flow}">${controls.map(controlHtml).join('')}</div>${outside == null ? '' : controlHtml(outside)}<button type="button" id="after">After toolbar</button></div>${SCRIPT}`;+}++export interface ToolbarFixture {+ readonly id: string;+ readonly summary: string;+ readonly facts: ToolbarStateFacts;+ /** Relation name → selector inside the fixture. */+ readonly relations: Readonly<Record<string, string>>;+ readonly html: string;+}++const RELATIONS = {+ before: '#before',+ after: '#after',+ 'first-control': '#bold',+ 'second-control': '#italic',+ 'last-control': '#settings',+} as const;++const facts = (+ overrides: Partial<ToolbarStateFacts> = {},+): ToolbarStateFacts => ({+ orientation: 'horizontal',+ direction: 'ltr',+ wraps: true,+ homeEnd: true,+ ...overrides,+});++function toolbar(+ id: string,+ summary: string,+ {+ facts: stateFacts = facts(),+ relations = RELATIONS,+ ...options+ }: Parameters<typeof toolbarHtml>[0] & {+ facts?: ToolbarStateFacts;+ relations?: Readonly<Record<string, string>>;+ } = {},+): ToolbarFixture {+ return {+ id,+ summary,+ facts: stateFacts,+ relations,+ html: toolbarHtml({+ orientation: stateFacts.orientation,+ dir: stateFacts.direction,+ ...options,+ }),+ };+}++const RTL = facts({direction: 'rtl'});+const VERTICAL = facts({orientation: 'vertical'});++export const TOOLBAR_FIXTURES: readonly ToolbarFixture[] = [+ toolbar(+ 'conforming-horizontal',+ 'a named horizontal toolbar of four controls with one roving Tab stop, wrapping arrows and Home/End',+ ),+ toolbar(+ 'conforming-rtl',+ 'the same toolbar under right-to-left, where ArrowLeft moves to the next control',+ {facts: RTL},+ ),+ toolbar(+ 'conforming-vertical',+ 'a vertical toolbar carrying aria-orientation="vertical", moved through with Down and Up',+ {facts: VERTICAL},+ ),+ toolbar(+ 'conforming-first-disabled',+ 'a toolbar whose first control is disabled, so Tab enters on the second',+ {controls: WITH_DISABLED_FIRST},+ ),+ toolbar(+ 'conforming-no-wrap-no-home-end',+ 'a toolbar whose arrows stop at either end and which ships no Home and End, and claims neither',+ {+ behavior: {wrap: false, homeEnd: false},+ facts: facts({wraps: false, homeEnd: false}),+ },+ ),+ toolbar(+ 'conforming-explicit-horizontal',+ 'a horizontal toolbar that states aria-orientation="horizontal"',+ {orientationAttribute: 'horizontal'},+ ),+ toolbar('violating-unnamed', 'a toolbar with no accessible name', {+ label: null,+ }),+ toolbar(+ 'violating-group-role',+ 'the controls grouped as a plain group instead of a toolbar',+ {role: 'group'},+ ),+ toolbar(+ 'violating-vertical-without-orientation',+ 'a vertical toolbar that does not carry aria-orientation',+ {facts: VERTICAL, orientationAttribute: null},+ ),+ toolbar(+ 'violating-horizontal-claims-vertical',+ 'a horizontal toolbar that claims aria-orientation="vertical"',+ {orientationAttribute: 'vertical'},+ ),+ toolbar(+ 'violating-control-outside',+ 'the last control rendered after the toolbar instead of inside it',+ {+ controls: FORMATTING.slice(0, 3),+ outside: {id: 'settings', label: 'Settings'},+ },+ ),+ toolbar(+ 'violating-every-control-tabbable',+ 'every control is its own Tab stop, so Tab walks through the toolbar',+ {behavior: {stops: 'every-control'}},+ ),+ toolbar(+ 'violating-enters-on-disabled',+ 'the Tab stop sits on the disabled first control',+ {+ controls: WITH_DISABLED_FIRST,+ behavior: {stops: 'first-even-if-disabled'},+ },+ ),+ toolbar(+ 'violating-next-skips',+ 'the next arrow jumps two controls instead of one',+ {behavior: {nextStep: 2}},+ ),+ toolbar(+ 'violating-rtl-not-mirrored',+ 'a right-to-left toolbar whose ArrowRight still moves to the next control',+ {facts: RTL, behavior: {keys: 'ignore-direction'}},+ ),+ toolbar(+ 'violating-vertical-uses-horizontal-arrows',+ 'a vertical toolbar moved only by Left and Right',+ {facts: VERTICAL, behavior: {keys: 'horizontal-only'}},+ ),+ toolbar('violating-previous-ignored', 'the previous arrow does nothing', {+ behavior: {previous: false},+ }),+ toolbar(+ 'violating-claims-wrap',+ 'a toolbar that claims wrapping but stops at either end',+ {behavior: {wrap: false}},+ ),+ toolbar(+ 'violating-home-end-ignored',+ 'a toolbar that claims Home and End but ignores them',+ {behavior: {homeEnd: false}},+ ),+];++export function fixture(id: string): ToolbarFixture {+ const found = TOOLBAR_FIXTURES.find(candidate => candidate.id === id);+ if (found == null) {+ throw new Error(`unknown toolbar fixture "${id}"`);+ }+ return found;+}++export const CONFORMING_FIXTURES: readonly string[] = TOOLBAR_FIXTURES.filter(+ candidate => candidate.id.startsWith('conforming-'),+).map(candidate => candidate.id);++export const TOOLBAR_MUTATIONS: Readonly<Record<string, readonly string[]>> = {+ 'toolbar.container.role-and-name': [+ 'violating-unnamed',+ 'violating-group-role',+ ],+ 'toolbar.container.orientation': [+ 'violating-vertical-without-orientation',+ 'violating-horizontal-claims-vertical',+ ],+ 'toolbar.controls.inside-toolbar': ['violating-control-outside'],+ 'toolbar.focus.single-tab-stop': [+ 'violating-every-control-tabbable',+ 'violating-enters-on-disabled',+ ],+ 'toolbar.keys.next-arrow': [+ 'violating-next-skips',+ 'violating-rtl-not-mirrored',+ 'violating-vertical-uses-horizontal-arrows',+ ],+ 'toolbar.keys.previous-arrow': [+ 'violating-previous-ignored',+ 'violating-rtl-not-mirrored',+ 'violating-vertical-uses-horizontal-arrows',+ ],+ 'toolbar.keys.arrows-wrap': ['violating-claims-wrap'],+ 'toolbar.keys.home-and-end': ['violating-home-end-ignored'],+};diff --git a/internal/a11y-spec/src/patterns/toolbar.jsdom.test.ts b/internal/a11y-spec/src/patterns/toolbar.jsdom.test.tsnew file mode 100644index 0000000000..0a1fd014b8--- /dev/null+++ b/internal/a11y-spec/src/patterns/toolbar.jsdom.test.ts@@ -0,0 +1,162 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file toolbar.jsdom.test.ts+ * @input TOOLBAR_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 {TOOLBAR_PATTERN} from './toolbar';+import {+ TOOLBAR_MUTATIONS,+ CONFORMING_FIXTURES,+ SUBJECT_SELECTOR,+ fixture,+ type ToolbarFixture,+} from './toolbar.fixtures';++const observableHere = TOOLBAR_PATTERN.expectations.filter(expectation =>+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),+);++afterEach(() => document.body.replaceChildren());++async function resultsFor(target: ToolbarFixture) {+ const container = document.createElement('div');+ document.body.append(container);+ const result = await checkAccessibilitySpec({+ spec: TOOLBAR_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 toolbar`);+ }+ 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('toolbar contract — completeness', () => {+ it('answers every completeness dimension', () => {+ expect(unansweredDimensions(TOOLBAR_PATTERN)).toEqual([]);+ });++ it('gives every expectation at least one deliberately violating fixture', () => {+ const missing = TOOLBAR_PATTERN.expectations+ .filter(+ expectation => (TOOLBAR_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(+ TOOLBAR_PATTERN.expectations.map(expectation => expectation.id),+ );+ expect(Object.keys(TOOLBAR_MUTATIONS).filter(id => !ids.has(id))).toEqual(+ [],+ );+ });++ it('names every fixture it records a mutation against', () => {+ for (const fixtures of Object.values(TOOLBAR_MUTATIONS)) {+ for (const id of fixtures) {+ expect(() => fixture(id)).not.toThrow();+ }+ }+ });+});++describe('toolbar 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-horizontal'));+ 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 = TOOLBAR_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((TOOLBAR_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(+ TOOLBAR_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/toolbar.ts b/internal/a11y-spec/src/patterns/toolbar.tsnew file mode 100644index 0000000000..4d80de6ea7--- /dev/null+++ b/internal/a11y-spec/src/patterns/toolbar.ts@@ -0,0 +1,627 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file toolbar.ts+ * @input WCAG 2.2 A/AA success criteria, the APG Toolbar pattern's role, label, orientation, and keyboard requirements, and design:bidirectionality DR6 for the mirrored arrows+ * @output TOOLBAR_PATTERN — the reusable contract a toolbar binds to: its role and name, its orientation, its controls inside it, one Tab stop entering on the first enabled control, and the arrow (with wrap) and Home/End movement between controls+ * @position Pattern contract; bound by Toolbar (`spec:AST-020/FR15`: a roving-tabindex toolbar is one composite control, so it adopts the arrow and Home/End movement it ships)+ */++import {+ definePattern,+ type ApgRequirement,+ type AstryxRecord,+ type PatternContract,+ type WcagCriterion,+} from '../contract';+import type {Key, Subject} from '../harness';++const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/';+const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';++const WCAG_1_3_1: WcagCriterion = {+ standard: 'wcag',+ id: '1.3.1',+ name: 'Info and Relationships',+ level: 'A',+ url: `${UNDERSTANDING}/info-and-relationships.html`,+};+const WCAG_2_1_1: WcagCriterion = {+ standard: 'wcag',+ id: '2.1.1',+ name: 'Keyboard',+ level: 'A',+ url: `${UNDERSTANDING}/keyboard.html`,+};+const WCAG_2_1_2: WcagCriterion = {+ standard: 'wcag',+ id: '2.1.2',+ name: 'No Keyboard Trap',+ level: 'A',+ url: `${UNDERSTANDING}/no-keyboard-trap.html`,+};+const WCAG_2_4_3: WcagCriterion = {+ standard: 'wcag',+ id: '2.4.3',+ name: 'Focus Order',+ level: 'A',+ url: `${UNDERSTANDING}/focus-order.html`,+};+const WCAG_4_1_2: WcagCriterion = {+ standard: 'wcag',+ id: '4.1.2',+ name: 'Name, Role, Value',+ level: 'A',+ url: `${UNDERSTANDING}/name-role-value.html`,+};++const ROLES = `${APG_URL}#wai-ariaroles,states,andproperties`;+const KEYS = `${APG_URL}#keyboardinteraction`;++const APG_ROLE: ApgRequirement = {+ standard: 'apg',+ pattern: 'toolbar',+ requirement:+ 'The element that serves as the toolbar container has role toolbar.',+ url: ROLES,+};+const APG_LABEL: ApgRequirement = {+ standard: 'apg',+ pattern: 'toolbar',+ requirement:+ 'If the toolbar has a visible label, it is referenced by aria-labelledby on the toolbar element. Otherwise, the toolbar element has a label provided by aria-label.',+ url: ROLES,+};+const APG_GROUPING: ApgRequirement = {+ standard: 'apg',+ pattern: 'toolbar',+ requirement:+ 'A toolbar is a container for grouping a set of controls, such as buttons, menubuttons, or checkboxes.',+ url: APG_URL,+};+const APG_ORIENTATION: ApgRequirement = {+ standard: 'apg',+ pattern: 'toolbar',+ requirement:+ 'If the controls are arranged vertically, the toolbar element has aria-orientation set to vertical. The default orientation is horizontal.',+ url: ROLES,+};+const APG_TAB: ApgRequirement = {+ standard: 'apg',+ pattern: 'toolbar',+ requirement:+ 'Tab and Shift + Tab: Move focus into and out of the toolbar. When focus moves into a toolbar: If focus is moving into the toolbar for the first time, focus is set on the first control that is not disabled.',+ url: KEYS,+};+const APG_ARROWS: ApgRequirement = {+ standard: 'apg',+ pattern: 'toolbar',+ requirement:+ 'For a horizontal toolbar (the default): Left Arrow: Moves focus to the previous control. Right Arrow: Moves focus to the next control. If the items in a toolbar are arranged vertically: Down Arrow performs as Right Arrow is described above. Up Arrow performs as Left Arrow is described above.',+ url: KEYS,+};+const APG_WRAP: ApgRequirement = {+ standard: 'apg',+ pattern: 'toolbar',+ requirement:+ 'Left Arrow: Optionally, focus movement may wrap from the first element to the last element. Right Arrow: Optionally, focus movement may wrap from the last element to the first element.',+ url: KEYS,+};+const APG_HOME_END: ApgRequirement = {+ standard: 'apg',+ pattern: 'toolbar',+ requirement:+ 'Home (Optional): Moves focus to first element. End (Optional): Moves focus to last element.',+ url: KEYS,+};++/**+ * The current Astryx adoption rule. A roving-tabindex toolbar already plays+ * the toolbar role and is one composite control, so it takes the pattern's+ * required parts and the arrow and Home/End movement it ships between its+ * controls.+ */+const AST_020_FR15: AstryxRecord = {+ standard: 'astryx',+ id: 'spec:AST-020',+ clause: 'FR15',+ url: 'https://github.com/facebook/astryx/blob/878fad9d7ac23cd3f4c5def64595abd770bb01a3/docs/specs/AST-020/spec.md#L83-L92',+ requirement:+ "Where a component part already plays an APG pattern's role, Astryx adopts that pattern's required parts for it: the role, the accessible name, the state and relationship properties, and activation by Tab plus Enter or Space. The pattern's optional keyboard extras — arrow-key movement between parts, Home and End — are adopted only where the component already acts as one composite control.",+};++/**+ * The current Astryx bidirectionality rule: horizontal keyboard movement+ * follows the RTL visual state, so under right-to-left the arrow pointing the+ * way the controls read (ArrowLeft) is "next". The APG names only Right as+ * next, so the mirrored arm rests on this record.+ */+const DESIGN_BIDI_DR6: AstryxRecord = {+ standard: 'astryx',+ id: 'design:bidirectionality',+ clause: 'DR6',+ url: 'https://github.com/facebook/astryx/blob/22c592a7a5a911945c0c53204e4daa09a349843d/docs/design/bidirectionality.md#L79-L81',+ requirement:+ 'Horizontal keyboard movement, drag/resize math, carousel or scroll progression, range navigation, and side placement MUST produce the action indicated by the RTL visual state.',+};++/**+ * What a binding knows about one toolbar. The subject is the element with role+ * toolbar. Relations: `before` and `after` (focusable controls outside the+ * toolbar on either side of it in the page Tab order), and `first-control`,+ * `second-control` and `last-control` (the first, second and last enabled+ * controls, in the order the arrow keys visit them).+ */+export interface ToolbarStateFacts {+ /** The axis the controls are arranged on, and so which arrows move between them. */+ readonly orientation: 'horizontal' | 'vertical';+ /** The toolbar's resolved writing direction; a horizontal toolbar's arrows follow it. */+ readonly direction: 'ltr' | 'rtl';+ /** Whether the forward arrow on the last control wraps to the first, and the backward arrow on the first to the last. */+ readonly wraps: boolean;+ /** Whether Home and End move to the first and last controls. */+ readonly homeEnd: boolean;+}++const ALWAYS = {+ condition: 'the binding designates a toolbar',+ test: () => true,+};++const CONTROL_RELATIONS = [+ 'first-control',+ 'second-control',+ 'last-control',+] as const;++/**+ * The arrows that move to the next and previous control. A vertical toolbar+ * uses Down and Up; a horizontal one uses the arrow that points the way its+ * controls read, so under right-to-left ArrowLeft is next.+ */+function arrowKeys(facts: ToolbarStateFacts): {+ readonly next: Key;+ readonly previous: Key;+} {+ if (facts.orientation === 'vertical') {+ return {next: 'ArrowDown', previous: 'ArrowUp'};+ }+ return facts.direction === 'rtl'+ ? {next: 'ArrowLeft', previous: 'ArrowRight'}+ : {next: 'ArrowRight', previous: 'ArrowLeft'};+}++async function focusOrFail(control: Subject, name: string): Promise<void> {+ await control.focus();+ if (!(await control.isFocused())) {+ throw new Error(`the ${name} did not take focus`);+ }+}++async function expectFocused(+ control: Subject,+ name: string,+ after: string,+): Promise<void> {+ if (!(await control.isFocused())) {+ throw new Error(`${after} did not move focus to the ${name}`);+ }+}++export const TOOLBAR_PATTERN: PatternContract<ToolbarStateFacts> =+ definePattern<ToolbarStateFacts>({+ pattern: 'toolbar',+ url: APG_URL,+ scope:+ "A toolbar's role and name, its orientation, its controls exposed inside it, one Tab stop that enters on the first enabled control, and the next/previous arrows (mirrored under right-to-left, Down/Up when vertical), their wrap, and Home/End where the binding ships them.",+ expectations: [+ {+ id: 'toolbar.container.role-and-name',+ outcome:+ 'The browser exposes the group as a named toolbar, so a user knows they have reached a set of related controls and which set it is.',+ sources: [WCAG_4_1_2, APG_ROLE, APG_LABEL],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {role, name} = await subject.computed();+ if (role !== 'toolbar') {+ throw new Error(+ `the browser exposes this group as ${role == null ? 'no role' : `"${role}"`}, not as a toolbar`,+ );+ }+ if (name.trim() === '') {+ throw new Error(+ 'the browser computes no accessible name for the toolbar',+ );+ }+ },+ },+ {+ id: 'toolbar.container.orientation',+ outcome:+ 'A vertical toolbar says it is vertical and a horizontal one does not, so a screen-reader user knows which arrows move between its controls.',+ sources: [WCAG_4_1_2, APG_ORIENTATION, AST_020_FR15],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const value = await subject.attribute('aria-orientation');+ if (facts.orientation === 'vertical' && value !== 'vertical') {+ throw new Error(+ `the vertical toolbar's aria-orientation is ${value ?? 'absent'}, not vertical`,+ );+ }+ if (+ facts.orientation === 'horizontal' &&+ value != null &&+ value !== 'horizontal'+ ) {+ throw new Error(+ `the horizontal toolbar's aria-orientation is ${value}, not horizontal or absent`,+ );+ }+ },+ },+ {+ id: 'toolbar.controls.inside-toolbar',+ outcome:+ 'Every control is exposed inside the toolbar, so a user hears it as one of the toolbar’s set rather than a loose control beside it.',+ sources: [WCAG_1_3_1, APG_GROUPING],+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({harness, subject}) => {+ for (const relation of CONTROL_RELATIONS) {+ const control = await harness.related(relation);+ if (!(await harness.containsSemantically(subject, control))) {+ throw new Error(+ `the ${relation} is not exposed inside the toolbar`,+ );+ }+ }+ },+ },+ {+ id: 'toolbar.focus.single-tab-stop',+ outcome:+ 'The whole toolbar is one Tab stop: Tab from before it lands on its first enabled control, and Tab again leaves the toolbar.',+ sources: [WCAG_2_4_3, WCAG_2_1_2, APG_TAB, AST_020_FR15],+ covers: [+ '2.1.1-keyboard',+ '2.1.2-no-keyboard-trap',+ '2.4.3-focus-order',+ 'apg-interaction',+ ],+ appliesWhen: ALWAYS,+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, subject}) => {+ const before = await harness.related('before');+ const after = await harness.related('after');+ await focusOrFail(before, 'control before the toolbar');+ await harness.press('Tab');+ await expectFocused(+ await harness.related('first-control'),+ 'first enabled control',+ 'Tab from before the toolbar',+ );+ await harness.press('Tab');+ if (await subject.containsFocus()) {+ throw new Error(+ 'Tab from the first control left focus inside the toolbar; a toolbar is one Tab stop',+ );+ }+ await expectFocused(+ after,+ 'control after the toolbar',+ 'Tab from the toolbar',+ );+ },+ },+ {+ id: 'toolbar.keys.next-arrow',+ outcome:+ 'The next arrow (Right, Left under right-to-left, Down when vertical) moves focus from one control to the next enabled control.',+ sources: [WCAG_2_1_1, APG_ARROWS, AST_020_FR15, DESIGN_BIDI_DR6],+ covers: ['2.1.1-keyboard', '2.4.3-focus-order', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, facts}) => {+ const {next} = arrowKeys(facts);+ await focusOrFail(+ await harness.related('first-control'),+ 'first control',+ );+ await harness.press(next);+ await expectFocused(+ await harness.related('second-control'),+ 'second control',+ `${next} on the first control`,+ );+ },+ },+ {+ id: 'toolbar.keys.previous-arrow',+ outcome:+ 'The previous arrow (Left, Right under right-to-left, Up when vertical) moves focus from one control to the previous enabled control.',+ sources: [WCAG_2_1_1, APG_ARROWS, AST_020_FR15, DESIGN_BIDI_DR6],+ covers: ['2.1.1-keyboard', '2.4.3-focus-order', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, facts}) => {+ const {previous} = arrowKeys(facts);+ await focusOrFail(+ await harness.related('second-control'),+ 'second control',+ );+ await harness.press(previous);+ await expectFocused(+ await harness.related('first-control'),+ 'first control',+ `${previous} on the second control`,+ );+ },+ },+ {+ id: 'toolbar.keys.arrows-wrap',+ outcome:+ 'The next arrow on the last control moves to the first, and the previous arrow on the first moves to the last.',+ sources: [WCAG_2_1_1, APG_WRAP, AST_020_FR15, DESIGN_BIDI_DR6],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition: 'the binding ships arrow-key wrapping',+ test: facts => facts.wraps,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, facts}) => {+ const {next, previous} = arrowKeys(facts);+ const first = await harness.related('first-control');+ const last = await harness.related('last-control');+ await focusOrFail(last, 'last control');+ await harness.press(next);+ await expectFocused(+ first,+ 'first control',+ `${next} on the last control`,+ );+ await harness.press(previous);+ await expectFocused(+ last,+ 'last control',+ `${previous} on the first control`,+ );+ },+ },+ {+ id: 'toolbar.keys.home-and-end',+ outcome:+ 'Home moves focus to the first enabled control and End to the last.',+ sources: [WCAG_2_1_1, APG_HOME_END, AST_020_FR15],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition: 'the binding ships Home and End',+ test: facts => facts.homeEnd,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness}) => {+ const first = await harness.related('first-control');+ const last = await harness.related('last-control');+ await focusOrFail(+ await harness.related('second-control'),+ 'second control',+ );+ await harness.press('End');+ await expectFocused(last, 'last control', 'End');+ await harness.press('Home');+ await expectFocused(first, 'first control', 'Home');+ },+ },+ ],+ exemptions: {+ '1.1.1-non-text-content': {+ owner: 'the controls placed in the toolbar and caller content',+ verifiedBy:+ "each control's own pattern contract (button, toggle-button, menu-button) and the repository axe audit, `pnpm a11y:audit`",+ reason:+ 'A toolbar paints no graphic of its own; icon-only controls name themselves through their own pattern.',+ },+ '1.3.1-info-and-relationships': {+ owner: 'the binding component and caller content',+ verifiedBy:+ "the binding's slot-layout tests (Toolbar.test.tsx) and content review of any visible toolbar heading",+ reason:+ 'This contract encodes that the controls are exposed inside the toolbar. Whether a visible heading labels it, and how slots group controls visually, are binding and caller structure.',+ coversRemainderOnly: true,+ },+ '1.3.2-meaningful-sequence': {+ owner: 'the binding component',+ verifiedBy:+ "the binding's DOM-order tests; this contract's arrow rows prove the keyboard order the binding declares",+ reason:+ 'The reading order of the controls is the order the caller places them in the slots.',+ },+ '1.3.5-identify-input-purpose': {+ owner: 'the controls placed in the toolbar and the composing form',+ verifiedBy:+ 'the text-input contract and form integration review of any user-information input in a toolbar',+ reason: 'A toolbar collects no information about the user.',+ },+ '1.4.1-use-of-color': {+ owner: 'the controls placed in the toolbar and the theme',+ verifiedBy: 'the repository visual gate and forced-colors review',+ reason:+ 'Pressed, selected and focused controls are painted by the controls, not by the toolbar container.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'the controls placed in the toolbar and the theme',+ verifiedBy:+ 'the repository axe audit over component stories plus the visual gate',+ reason:+ 'Text contrast depends on the resolved colors of the rendered controls.',+ },+ '1.4.11-non-text-contrast': {+ owner: 'the controls placed in the toolbar, Section, and the theme',+ verifiedBy:+ 'the repository axe audit plus rendered review of focus indicators and dividers',+ reason:+ 'Focus rings, control boundaries and the Section divider are paint outcomes owned by the controls, Section and the theme.',+ },+ '2.1.1-keyboard': {+ owner: 'the binding component and the controls placed in it',+ verifiedBy:+ "the binding's caret-guard, nested-popover and onKeyDown-composition tests (Toolbar.test.tsx) and each control's own pattern contract for activation",+ reason:+ 'This contract encodes the Tab stop, the next and previous arrows, their wrap, and Home/End. Activating a control is that control’s own pattern; leaving caret keys to a text field and leaving keys inside an open popover to that popover are binding behaviour the APG leaves to the author.',+ coversRemainderOnly: true,+ },+ '2.1.2-no-keyboard-trap': {+ owner: 'the composing page',+ verifiedBy: 'page-level keyboard review',+ reason:+ 'This contract proves Tab leaves the toolbar. Where focus goes beyond it is the composition.',+ coversRemainderOnly: true,+ },+ '2.4.2-page-titled': {+ owner: 'the page',+ verifiedBy: 'page-level review',+ reason: 'A toolbar rendered in isolation owns no document title.',+ },+ '2.4.3-focus-order': {+ owner: 'the binding component and the composing page',+ verifiedBy:+ "the binding's tab-stop-repair tests (Toolbar.test.tsx: outside dismissal of a MoreMenu keeps the tab stop) plus page-level focus-order review",+ reason:+ 'This contract proves entry on the first enabled control and arrow order inside the toolbar. Returning to the control that last had focus is optional in the APG, so it stays binding behaviour; the toolbar among surrounding controls is the composition.',+ coversRemainderOnly: true,+ },+ '2.4.4-link-purpose': {+ owner: 'the link pattern and caller content',+ verifiedBy: 'LINK_PATTERN and content review of link text',+ reason:+ 'A link in a toolbar is a link the caller labels; the toolbar only groups it.',+ },+ '2.4.6-headings-and-labels': {+ owner: 'caller content',+ verifiedBy: 'content review of toolbar labels',+ reason:+ 'Whether a label describes the set of controls is a caller-content judgement; this contract checks that a name exists.',+ },+ '2.4.7-focus-visible': {+ owner:+ 'the interaction-modality architecture record, the controls placed in the toolbar, and the theme',+ verifiedBy:+ "each control's focus-ring styling and the repository visual gate",+ reason: 'The focus ring belongs to the focused control.',+ },+ '2.4.11-focus-not-obscured': {+ owner: 'the composing page and overlay system',+ verifiedBy: 'page-level review of sticky headers and overlays',+ reason:+ 'Whether a sticky surface hides the focused control depends on the page geometry around the toolbar.',+ },+ '2.5.2-pointer-cancellation': {+ owner: 'the controls placed in the toolbar',+ verifiedBy:+ "each control's own pattern contract (button, toggle-button, menu-button)",+ reason: 'A toolbar has no pointer action of its own.',+ },+ '2.5.3-label-in-name': {+ owner: 'the controls placed in the toolbar and caller content',+ verifiedBy:+ "each control's own pattern contract and content review of visible labels",+ reason:+ 'The toolbar label is not rendered as visible text by the binding; each control names itself from its own visible label.',+ },+ '2.5.8-target-size': {+ owner: 'the controls placed in the toolbar and the theme',+ verifiedBy:+ "the repository axe audit's target-size rule and the size cascade tests (Toolbar.test.tsx)",+ reason: 'Control size and spacing are binding and control geometry.',+ },+ '3.1.1-language-of-page': {+ owner: 'the page',+ verifiedBy: 'page-level language review',+ reason: 'A toolbar rendered in isolation owns no document language.',+ },+ '3.2.2-on-input': {+ owner: 'the controls placed in the toolbar and the caller',+ verifiedBy: 'integration review of what each control does when changed',+ reason:+ 'Moving focus between controls changes no setting; what a control does when changed is that control 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 toolbar labels',+ reason:+ 'Consistency is a property of the set of repeated toolbars, not one toolbar.',+ },+ '3.3.1-error-identification': {+ owner: 'the composing form',+ verifiedBy: 'form-level error-state review',+ reason: 'The toolbar pattern defines no validation error state.',+ },+ '3.3.2-labels-or-instructions': {+ owner: 'the controls placed in the toolbar and caller content',+ verifiedBy: 'form-level review of labels and instructions',+ reason:+ 'A toolbar collects no input of its own that needs form instructions.',+ },+ '4.1.2-name-role-value': {+ owner: 'the controls placed in the toolbar',+ verifiedBy:+ "each control's own pattern contract (button, toggle-button, menu-button, checkbox)",+ reason:+ 'This contract encodes the toolbar role, name and orientation. Each control’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:+ 'Moving through a toolbar is not a status message, and this pattern makes no announcement claim.',+ },+ 'apg-interaction': {+ owner: 'the binding component and the controls placed in it',+ verifiedBy:+ "the binding's nested-popover and caret-guard tests (Toolbar.test.tsx) and each control's own pattern contract",+ reason:+ 'This contract encodes the toolbar container and movement between its controls. Returning to the last-focused control and focusable disabled controls are optional in the APG; the shortcut key into a toolbar is a recommendation for the application; multi-row toolbars have no Astryx adopter.',+ coversRemainderOnly: true,+ },+ 'forced-colors': {+ owner: 'the controls placed in the toolbar, Section, and the theme',+ verifiedBy:+ "each control's forced-colors tests plus rendered Windows High Contrast review",+ reason: 'Forced-colors output is a paint result.',+ },+ 'reduced-motion': {+ owner: 'the controls placed in the toolbar and the theme',+ verifiedBy:+ "each control's reduced-motion source tests and rendered motion review",+ reason: 'A toolbar container has no entry or exit motion.',+ },+ 'at-facing-strings': {+ owner: 'the binding component and caller content',+ verifiedBy:+ 'the repository i18n catalog check and source review of authored labels',+ reason:+ 'The toolbar contract introduces no string; the toolbar label comes from the caller.',+ },+ },+ });diff --git a/packages/core/src/Toolbar/Toolbar.test.tsx b/packages/core/src/Toolbar/Toolbar.test.tsxindex 77bbc20140..ed6a6b7388 100644--- a/packages/core/src/Toolbar/Toolbar.test.tsx+++ b/packages/core/src/Toolbar/Toolbar.test.tsx@@ -140,14 +140,6 @@ describe('Toolbar', () => {);});- it('sets aria-orientation to vertical', () => {- render(<Toolbar label="Actions" orientation="vertical" />);- expect(screen.getByRole('toolbar')).toHaveAttribute(- 'aria-orientation',- 'vertical',- );- });-it('reflects the size', () => {render(<Toolbar label="Actions" size="sm" />);const toolbar = screen.getByRole('toolbar');diff --git a/packages/core/src/Toolbar/__tests__/Toolbar.a11y.chromium.spec.ts b/packages/core/src/Toolbar/__tests__/Toolbar.a11y.chromium.spec.tsnew file mode 100644index 0000000000..7ec9251b2d--- /dev/null+++ b/packages/core/src/Toolbar/__tests__/Toolbar.a11y.chromium.spec.ts@@ -0,0 +1,163 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Toolbar.a11y.chromium.spec.ts+ * @input Built toolbar stories and TOOLBAR_PATTERN in real Chromium+ * @output Browser evidence for every toolbar expectation across Toolbar's representative states, and a paint check that each state's controls sit on the axis and in the direction it declares+ * @position Chromium lane of the Toolbar binding+ */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ TOOLBAR_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 {+ TOOLBAR_BINDING_STATES,+ type ToolbarBindingState,+} from './Toolbar.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: ToolbarBindingState,+): Promise<{subject: Locator; related: Record<string, Locator>}> {+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});+ await holdMotionStill(page);+ const root = page.locator('#storybook-root');+ const subject = root.getByRole('toolbar', {name: state.label, exact: true});+ await expect(subject).toBeVisible();+ const related: Record<string, Locator> = {+ before: root.getByRole('button', {+ name: 'Before the toolbar',+ exact: true,+ }),+ after: root.getByRole('button', {name: 'After the toolbar', exact: true}),+ };+ for (const [relation, name] of Object.entries(state.controls)) {+ related[relation] = subject.getByRole('button', {name, exact: true});+ }+ return {subject, related};+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: ToolbarBindingState,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: TOOLBAR_PATTERN,+ binding: 'Toolbar',+ state: state.id,+ facts: state.facts,+ mount: async () => {+ const {subject, related} = await mountState(page, state);+ return createChromiumHarness({page, cdp, subject, related});+ },+ });+}++test('every toolbar expectation is exercised by a Toolbar state', async ({+ page,+}) => {+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of TOOLBAR_BINDING_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(neverExercised(results)).toEqual([]);+});++/**+ * The contract reads `orientation` and `direction` as facts the binding+ * declares. This checks the painted page agrees: the second control sits+ * below the first in a vertical state, and after it in reading order — to+ * its right, or its left under right-to-left — in a horizontal one.+ */+for (const state of TOOLBAR_BINDING_STATES) {+ test(`Toolbar [${state.id}] paints its controls on the declared axis and direction`, async ({+ page,+ }) => {+ const {related} = await mountState(page, state);+ const first = await related['first-control'].boundingBox();+ const second = await related['second-control'].boundingBox();+ if (first == null || second == null) {+ throw new Error(`state "${state.id}" has an unpainted control`);+ }+ const firstMiddle = {+ x: first.x + first.width / 2,+ y: first.y + first.height / 2,+ };+ const secondMiddle = {+ x: second.x + second.width / 2,+ y: second.y + second.height / 2,+ };+ if (state.facts.orientation === 'vertical') {+ expect(second.y, 'second control below the first').toBeGreaterThanOrEqual(+ first.y + first.height,+ );+ } else {+ expect(+ Math.abs(secondMiddle.y - firstMiddle.y),+ 'controls share a row',+ ).toBeLessThan(first.height / 2);+ if (state.facts.direction === 'rtl') {+ expect(secondMiddle.x, 'second control left of the first').toBeLessThan(+ firstMiddle.x,+ );+ } else {+ expect(+ secondMiddle.x,+ 'second control right of the first',+ ).toBeGreaterThan(firstMiddle.x);+ }+ }+ });+}++for (const state of TOOLBAR_BINDING_STATES) {+ test(`Toolbar [${state.id}] — ${state.summary}`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(TOOLBAR_PATTERN, [result]);+ // Required rows block (AST-020 FR9).+ expect(formatFailures(blockingResults([result]))).toBe('');+ expect(report.unrunLayers).toEqual([]);+ expect(report.counts.unexpectedPass).toBe(0);+ });+}diff --git a/packages/core/src/Toolbar/__tests__/Toolbar.a11y.renders.tsx b/packages/core/src/Toolbar/__tests__/Toolbar.a11y.renders.tsxnew file mode 100644index 0000000000..8c823ee9a6--- /dev/null+++ b/packages/core/src/Toolbar/__tests__/Toolbar.a11y.renders.tsx@@ -0,0 +1,63 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file Toolbar.a11y.renders.tsx+ * @input One toolbar binding state from Toolbar.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 Toolbar, the Toolbar, and a page button after it+ * @position Shared fixture for the Toolbar binding+ */++import type {ReactElement} from 'react';+import {Button} from '../../Button/Button';+import {VStack} from '../../VStack/VStack';+import {Toolbar} from '../Toolbar';+import type {ToolbarBindingState, ToolbarControl} from './Toolbar.a11y.states';++/**+ * One slot's controls. A slot lays its children out in a row, so a vertical+ * toolbar's caller stacks them, as a product toolbar would, to arrange the+ * controls on the axis the state declares.+ */+function controls(+ list: ReadonlyArray<ToolbarControl>,+ orientation: ToolbarBindingState['facts']['orientation'],+): ReactElement | undefined {+ if (list.length === 0) {+ return undefined;+ }+ const buttons = list.map(control => (+ <Button+ key={control.label}+ label={control.label}+ variant="ghost"+ isDisabled={control.isDisabled}+ />+ ));+ return orientation === 'vertical' ? (+ <VStack gap={1}>{buttons}</VStack>+ ) : (+ <>{buttons}</>+ );+}++export function renderToolbarState(+ state: Pick<+ ToolbarBindingState,+ 'label' | 'startControls' | 'endControls' | 'facts'+ >,+): ReactElement {+ return (+ <div dir={state.facts.direction} style={{padding: 24, maxWidth: 640}}>+ <button type="button">Before the toolbar</button>+ <Toolbar+ label={state.label}+ orientation={state.facts.orientation}+ startContent={controls(state.startControls, state.facts.orientation)}+ endContent={controls(state.endControls, state.facts.orientation)}+ />+ <button type="button">After the toolbar</button>+ </div>+ );+}diff --git a/packages/core/src/Toolbar/__tests__/Toolbar.a11y.states.ts b/packages/core/src/Toolbar/__tests__/Toolbar.a11y.states.tsnew file mode 100644index 0000000000..bf981a899f--- /dev/null+++ b/packages/core/src/Toolbar/__tests__/Toolbar.a11y.states.ts@@ -0,0 +1,142 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Toolbar.a11y.states.ts+ * @input Toolbar's representative states and the facts TOOLBAR_PATTERN reads+ * @output TOOLBAR_BINDING_STATES and the explicit ownership exclusions for this binding+ * @position Binding inventory shared by the jsdom test and the Chromium spec (Toolbar under spec:AST-020 FR15)+ */++import type {ToolbarStateFacts} from '@astryxdesign/a11y-spec';++export interface ToolbarControl {+ readonly label: string;+ readonly isDisabled?: boolean;+}++export interface ToolbarBindingState {+ readonly id: string;+ readonly summary: string;+ readonly storyId: string;+ /** The Toolbar `label`, which names the toolbar. */+ readonly label: string;+ /** Controls in the start slot, in order. */+ readonly startControls: ReadonlyArray<ToolbarControl>;+ /** Controls in the end slot, in order. */+ readonly endControls: ReadonlyArray<ToolbarControl>;+ /** Relation name → accessible name of the control it designates. */+ readonly controls: Readonly<+ Record<'first-control' | 'second-control' | 'last-control', string>+ >;+ readonly facts: ToolbarStateFacts;+}++const story = (id: string) => `a11y-toolbar--${id}`;++const FORMATTING = [+ {label: 'Bold'},+ {label: 'Italic'},+ {label: 'Underline'},+] as const;++const FORMATTING_CONTROLS = {+ 'first-control': 'Bold',+ 'second-control': 'Italic',+ 'last-control': 'Settings',+} as const;++const HORIZONTAL_LTR: ToolbarStateFacts = {+ orientation: 'horizontal',+ direction: 'ltr',+ wraps: true,+ homeEnd: true,+};++export const TOOLBAR_BINDING_STATES = [+ {+ id: 'horizontal',+ summary:+ 'a named horizontal Toolbar with three formatting buttons in the start slot and Settings in the end slot',+ storyId: story('horizontal'),+ label: 'Text formatting',+ startControls: FORMATTING,+ endControls: [{label: 'Settings'}],+ controls: FORMATTING_CONTROLS,+ facts: HORIZONTAL_LTR,+ },+ {+ id: 'horizontal-rtl',+ summary:+ 'the same Toolbar inside a right-to-left container, where ArrowLeft moves to the next control',+ storyId: story('horizontal-rtl'),+ label: 'Text formatting',+ startControls: FORMATTING,+ endControls: [{label: 'Settings'}],+ controls: FORMATTING_CONTROLS,+ facts: {...HORIZONTAL_LTR, direction: 'rtl'},+ },+ {+ id: 'vertical',+ summary:+ 'a vertical Toolbar of drawing tools, moved through with ArrowDown and ArrowUp',+ storyId: story('vertical'),+ label: 'Drawing tools',+ startControls: [{label: 'Select'}, {label: 'Pen'}, {label: 'Eraser'}],+ endControls: [],+ controls: {+ 'first-control': 'Select',+ 'second-control': 'Pen',+ 'last-control': 'Eraser',+ },+ facts: {...HORIZONTAL_LTR, orientation: 'vertical'},+ },+ {+ id: 'first-control-disabled',+ summary:+ 'a Toolbar whose first button is disabled, so Tab enters on the first enabled button and the arrows skip the disabled one',+ storyId: story('first-control-disabled'),+ label: 'Edit actions',+ startControls: [+ {label: 'Undo', isDisabled: true},+ {label: 'Cut'},+ {label: 'Copy'},+ ],+ endControls: [{label: 'Paste'}],+ controls: {+ 'first-control': 'Cut',+ 'second-control': 'Copy',+ 'last-control': 'Paste',+ },+ facts: HORIZONTAL_LTR,+ },+] as const satisfies ReadonlyArray<ToolbarBindingState>;++export const TOOLBAR_EXCLUSIONS = [+ {+ id: 'control-semantics',+ owner:+ 'the button, toggle-button and menu-button patterns and their bindings',+ reason:+ 'Each control placed in a Toolbar exposes its own role, name, state and activation through its own pattern; this binding renders plain Buttons only so the toolbar container and the movement between controls are what is checked.',+ },+ {+ id: 'caret-guard-and-nested-popovers',+ owner:+ 'Toolbar.test.tsx (caret-guard, nested popover and onKeyDown composition suites)',+ reason:+ 'Leaving caret keys to a text field mid-line, leaving keys inside an open MoreMenu to that menu, and composing a caller onKeyDown are binding behaviour the APG leaves to the author, so no state here places a text field or popover in the toolbar.',+ },+ {+ id: 'three-lane-layout',+ owner:+ 'Toolbar.test.tsx (centerContent and three-slot layout tests) and the repository visual gate',+ reason:+ 'Center content switches the row to a three-column grid, but the controls stay in DOM order inside the same toolbar element and the same roving tab stop walks them, so the role, name, Tab stop and arrow order this contract reads do not change; the grid itself is layout paint.',+ },+ {+ id: 'outer-chrome',+ owner: 'component:Section and the repository visual gate',+ reason:+ 'Variant, dividers, block padding and edge compensation are Section and layout paint around the toolbar row; they change no role, name, Tab stop or arrow movement, so every state uses the default transparent chrome.',+ },+] as const;diff --git a/packages/core/src/Toolbar/__tests__/Toolbar.a11y.test.tsx b/packages/core/src/Toolbar/__tests__/Toolbar.a11y.test.tsxnew file mode 100644index 0000000000..adc7171700--- /dev/null+++ b/packages/core/src/Toolbar/__tests__/Toolbar.a11y.test.tsx@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file Toolbar.a11y.test.tsx+ * @input TOOLBAR_PATTERN bound to Toolbar's representative states+ * @output jsdom-lane proof of the DOM expectations and an honest "unrun" report for the browser layers+ * @position Binding test for Toolbar (the Chromium spec covers the rest)+ */++import {cleanup, render, screen} from '@testing-library/react';+import {describe, expect, it} from 'vitest';+import {+ TOOLBAR_PATTERN,+ checkAccessibilitySpec,+ createJsdomHarness,+ expectAccessibilitySpec,+ summarize,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {renderToolbarState} from './Toolbar.a11y.renders';+import {+ TOOLBAR_BINDING_STATES,+ TOOLBAR_EXCLUSIONS,+ type ToolbarBindingState,+} from './Toolbar.a11y.states';++function toolbarFor(state: ToolbarBindingState): HTMLElement {+ return screen.getByRole('toolbar', {name: state.label});+}++function relatedFor(+ state: ToolbarBindingState,+): Readonly<Record<string, Element>> {+ const related: Record<string, Element> = {+ before: screen.getByRole('button', {name: 'Before the toolbar'}),+ after: screen.getByRole('button', {name: 'After the toolbar'}),+ };+ for (const [relation, name] of Object.entries(state.controls)) {+ related[relation] = screen.getByRole('button', {name});+ }+ return related;+}++async function checkState(state: ToolbarBindingState): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: TOOLBAR_PATTERN,+ binding: 'Toolbar',+ state: state.id,+ facts: state.facts,+ mount: async () => {+ render(renderToolbarState(state));+ return createJsdomHarness({+ subject: toolbarFor(state),+ related: relatedFor(state),+ });+ },+ unmount: cleanup,+ });+}++describe('Toolbar — toolbar pattern, jsdom lane', () => {+ it.each(+ TOOLBAR_BINDING_STATES.map(+ state => [state.id, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectAccessibilitySpec({+ spec: TOOLBAR_PATTERN,+ binding: 'Toolbar',+ state: state.id,+ facts: state.facts,+ render: () => {+ render(renderToolbarState(state));+ },+ subject: () => toolbarFor(state),+ related: () => relatedFor(state),+ cleanup,+ });+ });++ it('runs the DOM layer and reports the browser-owned outcomes as unrun', async () => {+ const results: BindingResult[] = [];+ for (const state of TOOLBAR_BINDING_STATES) {+ results.push(await checkState(state));+ }+ const report = summarize(TOOLBAR_PATTERN, results);+ expect(report.counts.pass).toBeGreaterThan(0);+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);+ expect(report.counts.unexpectedPass).toBe(0);+ });+});++describe('toolbar binding inventory', () => {+ it('gives every representative state a distinct checked-in story', () => {+ const stories = TOOLBAR_BINDING_STATES.map(state => state.storyId);+ expect(new Set(stories).size).toBe(stories.length);+ });++ it('keeps control semantics, editing and popover keys, the three-lane layout, and outer chrome explicit', () => {+ expect(TOOLBAR_EXCLUSIONS.map(row => row.id)).toEqual([+ 'control-semantics',+ 'caret-guard-and-nested-popovers',+ 'three-lane-layout',+ 'outer-chrome',+ ]);+ for (const exclusion of TOOLBAR_EXCLUSIONS) {+ expect(exclusion.owner.length, exclusion.id).toBeGreaterThan(20);+ expect(exclusion.reason.length, exclusion.id).toBeGreaterThan(80);+ }+ });++ it('renders the toolbar and every control relation it names for every state', () => {+ for (const state of TOOLBAR_BINDING_STATES) {+ render(renderToolbarState(state));+ const toolbar = toolbarFor(state);+ for (const name of Object.values(state.controls)) {+ expect(+ toolbar.contains(screen.getByRole('button', {name})),+ `${state.id}: ${name}`,+ ).toBe(true);+ }+ cleanup();+ }+ });+});