An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): Slider contract and binding (#7483)
Cindy Zhangc239413c7747
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9427ef519f..bec74c69c0 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1628,6 +1628,54 @@ jobs:name: accordion-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}path: accordion-contract/+ # The slider contract's thumb role and name, and its arrow, Page, Home and+ # End results, are accessibility-tree and real-browser facts that jsdom+ # cannot observe. Run the contract's own fixture proof and the Slider+ # binding whenever Slider, the harness, the binding's stories, or the+ # contract changes. Its own --output directory; the JSON report is the+ # head-bound record, uploaded next.+ - name: Run Slider accessibility contract+ id: slider-contract+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}+ env:+ BASE_SHA: ${{ github.event.pull_request.base.sha }}+ PLAYWRIGHT_JSON_OUTPUT_FILE: slider-contract/report.json+ run: |+ should_run=false+ # The helper comes from the base, since an older PR head lacks it.+ # Exit 1 means out of scope; 0 in scope; 2 unknown, so run.+ scope=2+ helper="$(mktemp)"+ if git fetch --quiet --no-tags --depth=1 origin "$BASE_SHA" \+ && git show "$BASE_SHA:.github/scripts/pr-scope-touches.sh" > "$helper"; then+ scope=0+ bash "$helper" "$BASE_SHA" \+ '^(internal/a11y-spec/src/patterns/slider|internal/a11y-spec/src/harness|packages/core/src/Slider/|apps/storybook/stories/SliderA11y)' || scope=$?+ fi+ if [ "$scope" != 1 ]; then+ should_run=true+ fi+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"+ if [ "$should_run" != true ]; then+ echo "Slider and the slider contract are not in PR scope; skipping slider evidence."+ exit 0+ fi+ pnpm exec playwright test \+ internal/a11y-spec/src/patterns/slider.chromium.spec.ts \+ packages/core/src/Slider/__tests__/Slider.a11y.chromium.spec.ts \+ --project chromium \+ --reporter list,json \+ --output slider-contract-output++ - name: Upload Slider accessibility contract evidence+ if: ${{ !cancelled() && steps.slider-contract.outputs.should_run == 'true' }}+ uses: actions/upload-artifact@v7+ with:+ name: slider-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: slider-contract/+ retention-days: 30+ if-no-files-found: warn+# The link contract's role, name, Tab, Enter, and pointer-release outcomes# are accessibility-tree and real-browser facts that jsdom cannot observe.# Run the contract's own fixture proof and the Link binding whenever Linkdiff --git a/apps/storybook/stories/SliderA11y.stories.tsx b/apps/storybook/stories/SliderA11y.stories.tsxnew file mode 100644index 0000000000..332538cc49--- /dev/null+++ b/apps/storybook/stories/SliderA11y.stories.tsx@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SliderA11y.stories.tsx+ * @input The Slider binding states, rendered through the binding's own renderer so the jsdom and Chromium lanes see the same tree+ * @output One checked-in story per state for the Chromium accessibility lane; excluded from the visual matrix+ * @position Browser fixtures for component:Slider AR1 (SLIDER_PATTERN)+ */++import type {Meta, StoryObj} from '@storybook/react';+import {renderSliderState} from '../../../packages/core/src/Slider/__tests__/Slider.a11y.renders';+import {SLIDER_BINDING_STATES} from '../../../packages/core/src/Slider/__tests__/Slider.a11y.states';++const meta = {+ title: 'A11y/Slider',+ tags: ['no-visual'],+ parameters: {layout: 'padded'},+} satisfies Meta;++export default meta;+type Story = StoryObj<typeof meta>;++function storyFor(id: (typeof SLIDER_BINDING_STATES)[number]['id']): Story {+ const state = SLIDER_BINDING_STATES.find(candidate => candidate.id === id);+ if (state == null) {+ throw new Error(`no Slider binding state "${id}"`);+ }+ return {render: () => renderSliderState(state)};+}++export const Horizontal = storyFor('horizontal');+export const Vertical = storyFor('vertical');+export const HorizontalRtl = storyFor('horizontal-rtl');+export const Formatted = storyFor('formatted');+export const DisabledWithMessage = storyFor('disabled-with-message');+export const StepThree = storyFor('step-three');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex 4df230dce4..e4b796a644 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -51,6 +51,7 @@ src/├── listbox.* listbox, group, and option semantics├── spinbutton.* numeric role, value, bounds, state, and arrow stepping├── disclosure.* standalone disclosure state/content semantics+ ├── slider.* a thumb's role, name, values, text, orientation, and arrow/Page/Home/End keys (RTL-mirrored arrows)├── accordion.* a group's header role and name, panel state, single-expansion collapse, page Tab order├── breadcrumb.* landmark, list-trail, current-page, and separator semantics├── landmark.* one component-owned landmark region's role, name, and content boundary@@ -76,6 +77,7 @@ src/| `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 || `landmark` | WCAG 2.2 semantics; [APG Landmark Regions](https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/) as context | LayoutHeader, LayoutContent, LayoutFooter, and LayoutPanel caller-declared landmarks |+| `slider` | [APG Slider](https://www.w3.org/WAI/ARIA/apg/patterns/slider/) role, values, name, orientation and keys | Slider thumbs: role, name, now/min/max, value text, orientation, arrows (RTL-mirrored), Page, Home/End, disabled keeps value || `link` | WCAG 2.2 semantics; [APG Link](https://www.w3.org/WAI/ARIA/apg/patterns/link/) role and Enter mechanics | Link, including LinkProvider and `as` router components |The toggle-button contract owns the persistent-action extension of buttondiff --git a/internal/a11y-spec/src/harness.ts b/internal/a11y-spec/src/harness.tsindex e022d61d7c..4ee8cb56ec 100644--- a/internal/a11y-spec/src/harness.ts+++ b/internal/a11y-spec/src/harness.ts@@ -142,7 +142,11 @@ export type Key =| 'ArrowLeft'| 'ArrowRight'| 'ArrowUp'- | 'ArrowDown';+ | 'ArrowDown'+ | 'Home'+ | 'End'+ | 'PageUp'+ | 'PageDown';/*** A mounted binding, observed at whatever layers this runtime can honestly see.diff --git a/internal/a11y-spec/src/harness/chromium.ts b/internal/a11y-spec/src/harness/chromium.tsindex 11f996ff7d..ef934c17e0 100644--- a/internal/a11y-spec/src/harness/chromium.ts+++ b/internal/a11y-spec/src/harness/chromium.ts@@ -85,6 +85,10 @@ const KEYS: Record<Key, string> = {ArrowRight: 'ArrowRight',ArrowUp: 'ArrowUp',ArrowDown: 'ArrowDown',+ Home: 'Home',+ End: 'End',+ PageUp: 'PageUp',+ PageDown: 'PageDown',};interface AxValue {diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.tsindex 11f2610ba1..fcef90e569 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -139,6 +139,7 @@ export {type LandmarkStateFacts,} from './patterns/landmark';+export {SLIDER_PATTERN, type SliderStateFacts} from './patterns/slider';export {ACCORDION_PATTERN,type AccordionStateFacts,diff --git a/internal/a11y-spec/src/patterns/slider.chromium.spec.ts b/internal/a11y-spec/src/patterns/slider.chromium.spec.tsnew file mode 100644index 0000000000..9b77a57488--- /dev/null+++ b/internal/a11y-spec/src/patterns/slider.chromium.spec.ts@@ -0,0 +1,96 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file slider.chromium.spec.ts+ * @input SLIDER_PATTERN and its fixtures in real Chromium (the fixture script implements the APG keyboard model)+ * @output Proof that every expectation passes conforming fixtures and fails its mutation at the layers only a browser observes+ * @position Contract self-test, Chromium lane+ */++import {expect, test, type CDPSession, type Page} from '@playwright/test';+import {describeExpectation, requiredLayers} from '../contract';+import {checkAccessibilitySpec, type ExpectationResult} from '../check';+import {+ CHROMIUM_OBSERVES,+ createChromiumHarness,+ holdMotionStill,+} from '../harness/chromium';+import {SLIDER_PATTERN} from './slider';+import {+ SLIDER_MUTATIONS,+ CONFORMING_FIXTURES,+ SUBJECT_SELECTOR,+ fixture,+ type SliderFixture,+} from './slider.fixtures';++function fixturePage(html: string): string {+ return `<!doctype html><html lang="en"><body>${html}</body></html>`;+}++async function results(+ page: Page,+ cdp: CDPSession,+ target: SliderFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ const run = await checkAccessibilitySpec({+ spec: SLIDER_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: {},+ });+ },+ });+ return run.results;+}++test.describe('slider 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('slider contract — deliberately violating fixtures', () => {+ for (const expectation of SLIDER_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of SLIDER_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/slider.fixtures.ts b/internal/a11y-spec/src/patterns/slider.fixtures.tsnew file mode 100644index 0000000000..3e9edce7bd--- /dev/null+++ b/internal/a11y-spec/src/patterns/slider.fixtures.ts@@ -0,0 +1,259 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file slider.fixtures.ts+ * @input Plain HTML slider thumbs (one script implements the APG keyboard model; the DOM lane never runs it), conforming and deliberately violating+ * @output SLIDER_FIXTURES, the subject selector, and the expectation → violating-fixture map+ * @position Contract self-test data for slider.jsdom.test.ts and slider.chromium.spec.ts+ */++import type {SliderStateFacts} from './slider';++const SUBJECT_ATTRIBUTE = 'data-a11y-subject';+export const SUBJECT_SELECTOR = `[${SUBJECT_ATTRIBUTE}]`;++export interface SliderFixture {+ readonly id: string;+ readonly summary: string;+ readonly facts: SliderStateFacts;+ readonly html: string;+}++const SCRIPT = `<script>+(() => {+ const thumb = document.querySelector('[${SUBJECT_ATTRIBUTE}]');+ const num = name => Number(thumb.getAttribute(name));+ const rtl = thumb.closest('[dir="rtl"]') != null && !window.__sliderNoRtl;+ // Arrow and Page results snap to the step grid, then clamp; Home and End+ // set the bound itself, which is always an allowed value.+ const set = (raw, snap = true) => {+ const min = num('aria-valuemin'), max = num('aria-valuemax'), step = Number(thumb.dataset.step || 1);+ const snapped = snap ? min + Math.round((raw - min) / step) * step : raw;+ const next = Math.min(max, Math.max(min, Number(snapped.toFixed(10))));+ thumb.setAttribute('aria-valuenow', String(next));+ };+ thumb.addEventListener('keydown', e => {+ if (thumb.getAttribute('aria-disabled') === 'true' && !window.__sliderDisabledMoves) return;+ const now = num('aria-valuenow'), step = Number(thumb.dataset.step || 1);+ let key = e.key;+ if (rtl && (key === 'ArrowLeft' || key === 'ArrowRight')) key = key === 'ArrowLeft' ? 'ArrowRight' : 'ArrowLeft';+ switch (key) {+ case 'ArrowRight': case 'ArrowUp': e.preventDefault(); set(now + step * (window.__sliderUpIsDouble ? 2 : 1)); break;+ case 'ArrowLeft': case 'ArrowDown': e.preventDefault(); set(now - step); break;+ case 'PageUp': e.preventDefault(); if (!window.__sliderNoPage) set(now + step * 10); break;+ case 'PageDown': e.preventDefault(); if (!window.__sliderNoPage) set(now - step * 10); break;+ case 'Home': e.preventDefault(); set(num('aria-valuemin'), false); break;+ case 'End': e.preventDefault(); set(window.__sliderEndShort ? num('aria-valuemax') - step : num('aria-valuemax'), false); break;+ }+ });+})();+</script>`;++function slider({+ min = 0,+ max = 100,+ step = 1,+ value = 40,+ orientation = 'horizontal',+ rtl = false,+ disabled = false,+ valueText = null,+ role = 'slider',+ label = 'Volume',+ omit = [],+ orientationAttr,+}: {+ min?: number;+ max?: number;+ step?: number;+ value?: number;+ orientation?: 'horizontal' | 'vertical';+ rtl?: boolean;+ disabled?: boolean;+ valueText?: string | null;+ role?: string;+ label?: string | null;+ omit?: ReadonlyArray<'aria-valuenow' | 'aria-valuemin' | 'aria-valuemax'>;+ orientationAttr?: string | null;+} = {}): string {+ const attr = (name: string, v: string | number) =>+ omit.includes(name as never) ? '' : ` ${name}="${v}"`;+ const orient =+ orientationAttr === null+ ? ''+ : orientationAttr != null+ ? ` aria-orientation="${orientationAttr}"`+ : orientation === 'vertical'+ ? ' aria-orientation="vertical"'+ : '';+ return `<div${rtl ? ' dir="rtl"' : ''}><div ${SUBJECT_ATTRIBUTE} role="${role}" tabindex="0" data-step="${step}"${attr('aria-valuenow', value)}${attr('aria-valuemin', min)}${attr('aria-valuemax', max)}${orient}${label == null ? '' : ` aria-label="${label}"`}${disabled ? ' aria-disabled="true"' : ''}${valueText == null ? '' : ` aria-valuetext="${valueText}"`} style="width:40px;height:40px;background:#888"></div></div>${SCRIPT}`;+}++const facts = (+ overrides: Partial<SliderStateFacts> = {},+): SliderStateFacts => ({+ min: 0,+ max: 100,+ step: 1,+ value: 40,+ orientation: 'horizontal',+ rtl: false,+ operable: true,+ focusable: true,+ valueText: null,+ largeStep: 10,+ ...overrides,+});++const flag = (name: string, html: string) =>+ html.replace('<script>', `<script>window.${name} = true;</script><script>`);++export const SLIDER_FIXTURES: readonly SliderFixture[] = [+ {+ id: 'conforming-horizontal',+ summary: 'a horizontal thumb at 40 of 0–100 with step 1 and Page keys',+ facts: facts(),+ html: slider(),+ },+ {+ id: 'conforming-vertical',+ summary: 'a vertical thumb',+ facts: facts({orientation: 'vertical'}),+ html: slider({orientation: 'vertical'}),+ },+ {+ id: 'conforming-rtl',+ summary:+ 'a horizontal thumb on a right-to-left track: ArrowLeft raises the value',+ facts: facts({rtl: true}),+ html: slider({rtl: true}),+ },+ {+ id: 'conforming-formatted',+ summary: 'a thumb that speaks a formatted value',+ facts: facts({valueText: '40 percent'}),+ html: slider({valueText: '40 percent'}),+ },+ {+ id: 'conforming-no-page-keys',+ summary: 'a thumb that ships no Page keys (APG-optional)',+ facts: facts({largeStep: null}),+ html: flag('__sliderNoPage', slider()),+ },+ {+ id: 'conforming-disabled-focusable',+ summary:+ 'an unavailable thumb that keeps focus for its message and keeps its value',+ facts: facts({operable: false}),+ html: slider({disabled: true}),+ },+ {+ id: 'conforming-step-three',+ summary: 'a thumb with step 3 whose End reaches the maximum',+ facts: facts({step: 3, value: 48, largeStep: 30}),+ html: slider({step: 3, value: 48}),+ },+ {+ id: 'violating-role',+ summary: 'a thumb exposed as a progressbar',+ facts: facts(),+ html: slider({role: 'progressbar'}),+ },+ {+ id: 'violating-name',+ summary: 'a thumb with no accessible name',+ facts: facts(),+ html: slider({label: null}),+ },+ {+ id: 'violating-no-valuemin',+ summary: 'a thumb with no aria-valuemin',+ facts: facts(),+ html: slider({omit: ['aria-valuemin']}),+ },+ {+ id: 'violating-no-valuemax',+ summary: 'a thumb with no aria-valuemax',+ facts: facts(),+ html: slider({omit: ['aria-valuemax']}),+ },+ {+ id: 'violating-wrong-valuenow',+ summary: 'a thumb whose aria-valuenow disagrees with its value',+ facts: facts(),+ html: slider({value: 41}),+ },+ {+ id: 'violating-valuetext-missing',+ summary: 'a formatted thumb that exposes only the number',+ facts: facts({valueText: '40 percent'}),+ html: slider(),+ },+ {+ id: 'violating-vertical-unmarked',+ summary: 'a vertical thumb with no aria-orientation',+ facts: facts({orientation: 'vertical'}),+ html: slider({orientation: 'vertical', orientationAttr: null}),+ },+ {+ id: 'violating-up-double-step',+ summary: 'a thumb whose Up arrow moves two steps',+ facts: facts(),+ html: flag('__sliderUpIsDouble', slider()),+ },+ {+ id: 'violating-rtl-not-reversed',+ summary:+ 'a right-to-left thumb whose horizontal arrows still follow left-to-right',+ facts: facts({rtl: true}),+ html: flag('__sliderNoRtl', slider({rtl: true})),+ },+ {+ id: 'violating-page-inert',+ summary: 'a thumb that claims Page keys but ignores them',+ facts: facts(),+ html: flag('__sliderNoPage', slider()),+ },+ {+ id: 'violating-end-short',+ summary: 'a thumb whose End stops one step short of the maximum',+ facts: facts(),+ html: flag('__sliderEndShort', slider()),+ },+ {+ id: 'violating-disabled-moves',+ summary: 'an unavailable thumb that still changes on the arrow keys',+ facts: facts({operable: false}),+ html: flag('__sliderDisabledMoves', slider({disabled: true})),+ },+];++export function fixture(id: string): SliderFixture {+ const found = SLIDER_FIXTURES.find(candidate => candidate.id === id);+ if (found == null) {+ throw new Error(`unknown slider fixture "${id}"`);+ }+ return found;+}++export const CONFORMING_FIXTURES: readonly string[] = SLIDER_FIXTURES.filter(+ candidate => candidate.id.startsWith('conforming-'),+).map(candidate => candidate.id);++export const SLIDER_MUTATIONS: Readonly<Record<string, readonly string[]>> = {+ 'slider.thumb.role-and-name': ['violating-role', 'violating-name'],+ 'slider.thumb.value-properties': [+ 'violating-no-valuemin',+ 'violating-no-valuemax',+ 'violating-wrong-valuenow',+ ],+ 'slider.thumb.value-text': ['violating-valuetext-missing'],+ 'slider.thumb.orientation': ['violating-vertical-unmarked'],+ 'slider.keys.arrows-step': [+ 'violating-up-double-step',+ 'violating-rtl-not-reversed',+ ],+ 'slider.keys.page': ['violating-page-inert'],+ 'slider.keys.home-end': ['violating-end-short'],+ 'slider.thumb.unavailable-keeps-value': ['violating-disabled-moves'],+};diff --git a/internal/a11y-spec/src/patterns/slider.jsdom.test.ts b/internal/a11y-spec/src/patterns/slider.jsdom.test.tsnew file mode 100644index 0000000000..5c4758ae9d--- /dev/null+++ b/internal/a11y-spec/src/patterns/slider.jsdom.test.ts@@ -0,0 +1,154 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file slider.jsdom.test.ts+ * @input SLIDER_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 {SLIDER_PATTERN} from './slider';+import {+ SLIDER_MUTATIONS,+ CONFORMING_FIXTURES,+ SUBJECT_SELECTOR,+ fixture,+ type SliderFixture,+} from './slider.fixtures';++const observableHere = SLIDER_PATTERN.expectations.filter(expectation =>+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),+);++afterEach(() => document.body.replaceChildren());++async function resultsFor(target: SliderFixture) {+ const container = document.createElement('div');+ document.body.append(container);+ const result = await checkAccessibilitySpec({+ spec: SLIDER_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ mount: async () => {+ container.innerHTML = target.html;+ const subject = container.querySelector(SUBJECT_SELECTOR);+ if (subject == null) {+ throw new Error(`fixture "${target.id}" is missing its subject`);+ }+ 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('slider contract — completeness', () => {+ it('answers every completeness dimension', () => {+ expect(unansweredDimensions(SLIDER_PATTERN)).toEqual([]);+ });++ it('gives every expectation at least one deliberately violating fixture', () => {+ const missing = SLIDER_PATTERN.expectations+ .filter(+ expectation => (SLIDER_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(+ SLIDER_PATTERN.expectations.map(expectation => expectation.id),+ );+ expect(Object.keys(SLIDER_MUTATIONS).filter(id => !ids.has(id))).toEqual(+ [],+ );+ });++ it('names every fixture it records a mutation against', () => {+ for (const fixtures of Object.values(SLIDER_MUTATIONS)) {+ for (const id of fixtures) {+ expect(() => fixture(id)).not.toThrow();+ }+ }+ });+});++describe('slider 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 = SLIDER_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((SLIDER_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(+ SLIDER_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/slider.ts b/internal/a11y-spec/src/patterns/slider.tsnew file mode 100644index 0000000000..6b5c8fd8b3--- /dev/null+++ b/internal/a11y-spec/src/patterns/slider.ts@@ -0,0 +1,575 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file slider.ts+ * @input WCAG 2.2 A/AA success criteria and the APG Slider pattern's role, value, name, orientation, and keyboard requirements+ * @output SLIDER_PATTERN — the reusable contract a slider thumb binds to when it adopts the pattern (Slider under component:Slider AR1, `spec:AST-020/FR15`)+ * @position Pattern contract; bound by Slider per thumb+ */++import {+ definePattern,+ type ApgRequirement,+ type AstryxRecord,+ type PatternContract,+ type WcagCriterion,+} from '../contract';+import type {Subject} from '../harness';++const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/slider/';+const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';++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 apgReq = (requirement: string, anchor: string): ApgRequirement => ({+ standard: 'apg',+ pattern: 'slider',+ requirement,+ url: `${APG_URL}#${anchor}`,+});+const A = 'wai-ariaroles,states,andproperties';+const K = 'keyboardinteraction';+const APG_ROLE = apgReq(+ 'The element serving as the focusable slider control has role slider.',+ A,+);+const APG_VALUES = apgReq(+ 'The slider element has the aria-valuenow property set to a decimal value representing the current value of the slider. The slider element has the aria-valuemin property set to a decimal value representing the minimum allowed value of the slider. The slider element has the aria-valuemax property set to a decimal value representing the maximum allowed value of the slider.',+ A,+);+const APG_VALUETEXT = apgReq(+ 'If the value of aria-valuenow is not user-friendly, the aria-valuetext property is set to a string that makes the slider value understandable.',+ A,+);+const APG_NAME = apgReq(+ 'If the slider has a visible label, it is referenced by aria-labelledby on the slider element. Otherwise, the slider element has a label provided by aria-label.',+ A,+);+const APG_ORIENTATION = apgReq(+ 'If the slider is vertically oriented, it has aria-orientation set to vertical. The default value of aria-orientation for a slider is horizontal.',+ A,+);+const APG_ARROWS = apgReq(+ 'Right Arrow: Increase the value of the slider by one step. Up Arrow: Increase the value of the slider by one step. Left Arrow: Decrease the value of the slider by one step. Down Arrow: Decrease the value of the slider by one step.',+ K,+);+const APG_HOME_END = apgReq(+ 'Home: Set the slider to the first allowed value in its range. End: Set the slider to the last allowed value in its range.',+ K,+);+const APG_PAGE = apgReq(+ 'Page Up (Optional): Increase the slider value by an amount larger than the step change made by Up Arrow. Page Down (Optional): Decrease the slider value by an amount larger than the step change made by Down Arrow.',+ K,+);+const SLIDER_AR1: AstryxRecord = {+ standard: 'astryx',+ id: 'component:Slider',+ clause: 'AR1',+ url: 'https://github.com/facebook/astryx/blob/250fd9ac197381ec06900279efc31cbb03544ca9/packages/core/src/Slider/Slider.spec.md#L120-L133',+ requirement:+ "On a horizontal track the horizontal arrows follow the track's direction — under RTL ArrowLeft increases and ArrowRight decreases; PageUp and PageDown step by ten steps; Home moves to `min` and End to `max`.",+};+const APG_REVERSED = apgReq(+ 'In some circumstances, reversing the direction of the value change for the keys specified above could create a more intuitive experience.',+ K,+);++/**+ * What a binding knows about one slider thumb (the subject). Values are the+ * numbers the thumb exposes; `largeStep` is the Page key amount when the+ * binding ships Page keys; `valueText` is the formatted text when one is set.+ */+export interface SliderStateFacts {+ readonly min: number;+ readonly max: number;+ readonly step: number;+ readonly value: number;+ readonly orientation: 'horizontal' | 'vertical';+ /** Whether the thumb sits on a right-to-left horizontal track (inline arrows follow the track). */+ readonly rtl: boolean;+ /** Whether the user is meant to be able to change the value. */+ readonly operable: boolean;+ /** Whether the thumb is meant to accept keyboard focus. */+ readonly focusable: boolean;+ /** The formatted value text the thumb exposes, or null when it exposes the number. */+ readonly valueText: string | null;+ /** The Page Up/Down amount, or null when the binding ships no Page keys. */+ readonly largeStep: number | null;+}++const ALWAYS = {+ condition: 'the binding designates a slider thumb',+ test: () => true,+};++async function numericAttribute(+ subject: Subject,+ name: string,+): Promise<number> {+ const raw = await subject.attribute(name);+ const parsed = raw == null ? Number.NaN : Number(raw);+ if (!Number.isFinite(parsed)) {+ throw new Error(`${name} is ${raw ?? 'absent'}, not a number`);+ }+ return parsed;+}++async function valueNow(subject: Subject): Promise<number> {+ return numericAttribute(subject, 'aria-valuenow');+}++function clampToStep(+ target: number,+ facts: Pick<SliderStateFacts, 'min' | 'max' | 'step'>,+): number {+ const steps = Math.round((target - facts.min) / facts.step);+ const snapped = facts.min + steps * facts.step;+ const rounded = Number(snapped.toFixed(10));+ return Math.min(facts.max, Math.max(facts.min, rounded));+}++async function focusOrFail(subject: Subject, forWhat: string): Promise<void> {+ await subject.focus();+ if (!(await subject.isFocused())) {+ throw new Error(+ `the slider thumb did not take focus, so ${forWhat} never reaches it`,+ );+ }+}++async function expectValue(+ subject: Subject,+ expected: number,+ after: string,+): Promise<void> {+ const now = await valueNow(subject);+ if (Math.abs(now - expected) > 1e-9) {+ throw new Error(`${after} left aria-valuenow at ${now}, not ${expected}`);+ }+}++export const SLIDER_PATTERN: PatternContract<SliderStateFacts> =+ definePattern<SliderStateFacts>({+ pattern: 'slider',+ url: APG_URL,+ scope:+ "A slider thumb's role and name, its now/min/max values and optional value text, its orientation, and the arrow, Page, Home and End keys — with the horizontal arrows following the track's direction under right-to-left.",+ expectations: [+ {+ id: 'slider.thumb.role-and-name',+ outcome:+ 'The browser exposes the thumb as a named slider, so a user hears what value they are changing.',+ sources: [WCAG_4_1_2, APG_ROLE, APG_NAME],+ covers: [+ '4.1.2-name-role-value',+ '2.4.6-headings-and-labels',+ 'apg-interaction',+ ],+ appliesWhen: ALWAYS,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {role, name} = await subject.computed();+ if (role !== 'slider') {+ throw new Error(+ `the browser exposes this thumb as ${role == null ? 'no role' : `"${role}"`}, not as a slider`,+ );+ }+ if (!name || name.trim() === '') {+ throw new Error(+ 'the browser computes no accessible name for this thumb',+ );+ }+ },+ },+ {+ id: 'slider.thumb.value-properties',+ outcome:+ 'The thumb states its current value and its bounds, so a user hears where they are in the range.',+ sources: [WCAG_4_1_2, APG_VALUES],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const now = await valueNow(subject);+ const min = await numericAttribute(subject, 'aria-valuemin');+ const max = await numericAttribute(subject, 'aria-valuemax');+ if (now !== facts.value || min !== facts.min || max !== facts.max) {+ throw new Error(+ `the thumb exposes now/min/max ${now}/${min}/${max}, not ${facts.value}/${facts.min}/${facts.max}`,+ );+ }+ if (now < min || now > max) {+ throw new Error(+ 'aria-valuenow lies outside aria-valuemin..aria-valuemax',+ );+ }+ },+ },+ {+ id: 'slider.thumb.value-text',+ outcome:+ 'A formatted value is spoken as that text, not as the raw number.',+ sources: [WCAG_4_1_2, APG_VALUETEXT],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: {+ condition: 'the binding formats the value',+ test: facts => facts.valueText != null,+ },+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const text = await subject.attribute('aria-valuetext');+ if (text !== facts.valueText) {+ throw new Error(+ `aria-valuetext is ${text ?? 'absent'}, not "${facts.valueText}"`,+ );+ }+ },+ },+ {+ id: 'slider.thumb.orientation',+ outcome:+ 'A vertical slider says so, so a user knows which arrows move it along the track.',+ sources: [WCAG_4_1_2, APG_ORIENTATION],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const orientation = await subject.attribute('aria-orientation');+ if (facts.orientation === 'vertical' && orientation !== 'vertical') {+ throw new Error(+ `a vertical thumb has aria-orientation ${orientation ?? 'absent'}`,+ );+ }+ if (+ facts.orientation === 'horizontal' &&+ orientation != null &&+ orientation !== 'horizontal'+ ) {+ throw new Error(+ `a horizontal thumb claims aria-orientation="${orientation}"`,+ );+ }+ },+ },+ {+ id: 'slider.keys.arrows-step',+ outcome:+ "The inline-forward arrow and Up raise the value by one step, the inline-back arrow and Down lower it, and on a right-to-left track the horizontal arrows follow the track's direction.",+ sources: [WCAG_2_1_1, APG_ARROWS, APG_REVERSED, SLIDER_AR1],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition: 'the thumb can be changed and focused',+ test: facts => facts.operable && facts.focusable,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ const up = clampToStep(facts.value + facts.step, facts);+ const down = clampToStep(facts.value - facts.step, facts);+ await focusOrFail(subject, 'the arrow keys');+ if (facts.orientation === 'horizontal') {+ const forward = facts.rtl ? 'ArrowLeft' : 'ArrowRight';+ const back = facts.rtl ? 'ArrowRight' : 'ArrowLeft';+ await harness.press(forward);+ await expectValue(subject, up, `${forward} (inline forward)`);+ await harness.press(back);+ await expectValue(subject, facts.value, `${back} (inline back)`);+ }+ await harness.press('ArrowUp');+ await expectValue(subject, up, 'ArrowUp');+ await harness.press('ArrowDown');+ await expectValue(subject, facts.value, 'ArrowDown');+ await harness.press('ArrowDown');+ await expectValue(subject, down, 'ArrowDown a second time');+ },+ },+ {+ id: 'slider.keys.page',+ outcome:+ 'Page Up and Page Down move the value by a larger amount than one step.',+ sources: [WCAG_2_1_1, APG_PAGE, SLIDER_AR1],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition:+ 'the binding ships Page keys and the thumb can be changed and focused',+ test: facts =>+ facts.largeStep != null && facts.operable && facts.focusable,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ const large = facts.largeStep ?? 0;+ await focusOrFail(subject, 'the Page keys');+ await harness.press('PageUp');+ await expectValue(+ subject,+ clampToStep(facts.value + large, facts),+ 'PageUp',+ );+ await harness.press('PageDown');+ await expectValue(subject, facts.value, 'PageDown');+ },+ },+ {+ id: 'slider.keys.home-end',+ outcome: 'Home sets the minimum and End sets the maximum.',+ sources: [WCAG_2_1_1, APG_HOME_END, SLIDER_AR1],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition: 'the thumb can be changed and focused',+ test: facts => facts.operable && facts.focusable,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ await focusOrFail(subject, 'Home and End');+ await harness.press('Home');+ await expectValue(subject, facts.min, 'Home');+ await harness.press('End');+ await expectValue(subject, facts.max, 'End');+ },+ },+ {+ id: 'slider.thumb.unavailable-keeps-value',+ outcome:+ 'An unavailable thumb that still takes focus keeps its value on every key, so a disabled slider never changes under the keyboard.',+ sources: [WCAG_4_1_2, APG_ARROWS],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: {+ condition: 'the thumb cannot be changed but can receive focus',+ test: facts => !facts.operable && facts.focusable,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ if ((await subject.attribute('aria-disabled')) !== 'true') {+ throw new Error(+ 'an unavailable thumb does not carry aria-disabled="true"',+ );+ }+ await focusOrFail(subject, 'the keys');+ for (const key of ['ArrowRight', 'ArrowUp', 'Home', 'End'] as const) {+ await harness.press(key);+ await expectValue(+ subject,+ facts.value,+ `${key} on an unavailable thumb`,+ );+ }+ },+ },+ ],+ exemptions: {+ '1.1.1-non-text-content': {+ owner: 'the binding component',+ verifiedBy:+ "the component's decorative-icon tests and the repository axe audit, `pnpm a11y:audit`",+ reason:+ "This contract owns the thumb's semantics and keys. Tick marks and any icon the binding paints are binding composition.",+ },+ '1.3.1-info-and-relationships': {+ owner: 'the binding component and caller content',+ verifiedBy:+ "the component's range-group, label and description association tests",+ reason:+ "A range slider's group, its label, and any description or status text are the binding's relationships, proven by its own tests.",+ },+ '1.3.2-meaningful-sequence': {+ owner: 'the binding component and composing page',+ verifiedBy:+ "the component's DOM-order tests and page-level reading-order review",+ reason:+ 'Where the slider, its label and its value sit relative to surrounding content is composition.',+ },+ '1.3.5-identify-input-purpose': {+ owner: 'not applicable',+ verifiedBy: 'none needed',+ reason:+ 'A slider collects a value, not information about the user that autofill could supply.',+ },+ '1.4.1-use-of-color': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the component's filled-range, marks and disabled state tests plus rendered review",+ reason:+ 'Filled range, marks and disabled cues are paint results owned by the binding and theme; this contract proves the programmatic value.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'the binding component and theme',+ verifiedBy: 'the repository axe audit plus rendered contrast review',+ reason:+ 'Label and mark text contrast is a paint outcome owned by the binding and theme.',+ },+ '1.4.11-non-text-contrast': {+ owner: 'the binding component and theme',+ verifiedBy:+ 'the repository axe audit plus rendered review of the thumb, track and focus indicator',+ reason:+ 'Thumb, track and focus indicator contrast are paint outcomes owned by the binding and theme.',+ },+ '2.1.1-keyboard': {+ owner: 'the composing page',+ verifiedBy: 'page-level keyboard review',+ reason:+ "This contract encodes the thumb's arrow, Page, Home and End keys. Reaching the thumb and other page keyboard paths remain with the composition.",+ coversRemainderOnly: true,+ },+ '2.1.2-no-keyboard-trap': {+ owner: 'the binding component and composing page',+ verifiedBy: "the component's Tab tests and page-level keyboard review",+ reason:+ 'A slider thumb adds no focus trap; Tab entry and exit are generic focus behavior.',+ },+ '2.4.2-page-titled': {+ owner: 'the page',+ verifiedBy: 'page-level review',+ reason: 'A slider rendered in isolation owns no document title.',+ },+ '2.4.3-focus-order': {+ owner: 'the composing page',+ verifiedBy: 'page-level focus-order review',+ reason:+ "The thumb's place among surrounding controls, and the order of two range thumbs, depend on composition.",+ },+ '2.4.4-link-purpose': {+ owner: 'not applicable',+ verifiedBy: 'none needed',+ reason: 'A slider renders no link.',+ },+ '2.4.6-headings-and-labels': {+ owner: 'the binding component and caller content',+ verifiedBy: "the component's name tests and caller content review",+ reason:+ 'This contract proves the thumb has a name; whether that label is descriptive is caller content.',+ coversRemainderOnly: true,+ },+ '2.4.7-focus-visible': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the component's focus-outline tests and rendered focus review",+ reason:+ "The focused thumb's indicator is a paint result owned by the binding and theme.",+ },+ '2.4.11-focus-not-obscured': {+ owner: 'the composing page',+ verifiedBy: 'page-level layout review',+ reason:+ 'Whether another surface covers the focused thumb depends on composition.',+ },+ '2.5.2-pointer-cancellation': {+ owner: 'the binding component',+ verifiedBy: "the component's pointer drag and release tests",+ reason:+ "A slider changes value through the drag itself; the pointer model is the binding's and outside this keyboard contract.",+ },+ '2.5.3-label-in-name': {+ owner: 'the binding component',+ verifiedBy: "the component's accessible-name tests",+ reason:+ "Whether the thumb's accessible name contains the visible label is the binding's naming requirement.",+ },+ '2.5.8-target-size': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the repository axe audit's target-size rule over the thumb",+ reason:+ "The thumb's hit area is geometry owned by the binding and theme.",+ },+ '3.1.1-language-of-page': {+ owner: 'the page',+ verifiedBy: 'page-level review',+ reason: 'A slider owns no document language.',+ },+ '3.2.2-on-input': {+ owner: 'the caller and composing page',+ verifiedBy: 'integration review of what a caller does with onChange',+ reason:+ "Changing the value is the slider's own purpose; any context change a caller makes on change is the caller's action.",+ },+ '3.2.4-consistent-identification': {+ owner: 'the composing page',+ verifiedBy:+ 'this shared contract across bindings plus content review of repeated slider labels',+ reason:+ 'Consistency is a property of the full set of repeated functions, not one isolated slider.',+ },+ '3.3.1-error-identification': {+ owner: 'the binding component',+ verifiedBy:+ "the component's status tests (aria-invalid and the status text association)",+ reason:+ "An error status on a slider is the binding's status composition, outside this pattern.",+ },+ '3.3.2-labels-or-instructions': {+ owner: 'the binding component and caller content',+ verifiedBy: "the component's label and description tests",+ reason:+ "This contract proves the thumb is named; help text and its association are the binding's.",+ },+ '4.1.2-name-role-value': {+ owner: 'the binding component',+ verifiedBy: "the component's range-group and status tests",+ reason:+ "This contract encodes the thumb's role, name, values, text, orientation and disabled state. A range slider's group semantics and aria-invalid are the binding's.",+ 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 or braille output',+ reason:+ 'A value change is not a status-message contract, and this pattern makes no announcement claim.',+ },+ 'apg-interaction': {+ owner: "the binding component's record",+ verifiedBy:+ 'component:Slider AR1 and DEC-2, which adopt the pattern per thumb and the reversed inline arrows under RTL',+ reason:+ "This contract encodes the slider role, values, name, orientation and keys. The pointer drag model and a range's two-thumb separation are the binding's.",+ coversRemainderOnly: true,+ },+ 'forced-colors': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the component's forced-colors tests plus rendered Windows High Contrast review",+ reason:+ 'Forced-colors output is a paint result owned by the binding and theme.',+ },+ 'reduced-motion': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the component's reduced-motion source tests and rendered motion review",+ reason:+ 'Thumb and fill motion is binding-specific paint over time and is not part of slider semantics.',+ },+ 'at-facing-strings': {+ owner: 'the binding component and caller content',+ verifiedBy:+ 'the repository i18n catalog check and source review of authored labels',+ reason:+ 'The slider contract introduces no string; the label and value text come from the binding or caller.',+ },+ },+ });diff --git a/packages/core/src/Slider/__tests__/Slider.a11y.chromium.spec.ts b/packages/core/src/Slider/__tests__/Slider.a11y.chromium.spec.tsnew file mode 100644index 0000000000..488a91ce68--- /dev/null+++ b/packages/core/src/Slider/__tests__/Slider.a11y.chromium.spec.ts@@ -0,0 +1,112 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Slider.a11y.chromium.spec.ts+ * @input Built Slider stories and SLIDER_PATTERN in real Chromium+ * @output Browser evidence for every slider expectation across the binding's states, reconciled against the exact known failures+ * @position Chromium lane of the Slider binding (component:Slider AR1)+ */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ SLIDER_PATTERN,+ blockingResults,+ checkAccessibilitySpec,+ formatFailures,+ neverExercised,+ summarize,+ unmatchedKnownFailures,+ 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 {SLIDER_KNOWN_FAILURES} from './Slider.a11y.known-failures';+import {+ SLIDER_BINDING_STATES,+ type SliderBindingState,+} from './Slider.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: SliderBindingState,+): Promise<{subject: Locator; related: Record<string, Locator>}> {+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});+ await holdMotionStill(page);+ const subject = page+ .locator('#storybook-root')+ .getByRole('slider', {name: state.label});+ await subject.waitFor({state: 'attached'});+ return {subject, related: {}};+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: SliderBindingState,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: SLIDER_PATTERN,+ binding: 'Slider',+ state: state.id,+ facts: state.facts,+ knownFailures: SLIDER_KNOWN_FAILURES,+ mount: async () => {+ const {subject, related} = await mountState(page, state);+ return createChromiumHarness({page, cdp, subject, related});+ },+ });+}++test('every slider expectation is exercised by a Slider state', async ({+ page,+}) => {+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of SLIDER_BINDING_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(neverExercised(results)).toEqual([]);+ expect(unmatchedKnownFailures(SLIDER_KNOWN_FAILURES, results)).toEqual([]);+});++for (const state of SLIDER_BINDING_STATES) {+ test(`Slider [${state.id}] — ${state.summary}`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(SLIDER_PATTERN, [result]);+ // Required rows block (AST-020 FR9); advisory rows and exact known+ // failures report.+ expect(formatFailures(blockingResults([result]))).toBe('');+ expect(report.unrunLayers).toEqual([]);+ expect(report.counts.unexpectedPass).toBe(0);+ });+}diff --git a/packages/core/src/Slider/__tests__/Slider.a11y.known-failures.ts b/packages/core/src/Slider/__tests__/Slider.a11y.known-failures.tsnew file mode 100644index 0000000000..5512e87b64--- /dev/null+++ b/packages/core/src/Slider/__tests__/Slider.a11y.known-failures.ts@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Slider.a11y.known-failures.ts+ * @input The exact slider-contract failures the shipped Slider produces today+ * @output SLIDER_KNOWN_FAILURES — records both lanes reconcile against, so a fix shows up as an unexpected pass and any other failure stays a failure+ * @position Known-failure ledger for the Slider binding+ */++import type {KnownFailure} from '@astryxdesign/a11y-spec';++export const SLIDER_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [+ {+ expectation: 'slider.keys.home-end',+ binding: 'Slider',+ state: 'step-three',+ evidenceLayer: 'real-browser',+ failureEquals: 'End left aria-valuenow at 99, not 100',+ standardsReference:+ 'APG Slider keyboard interaction — End sets the slider to the last allowed value in its range; Astryx component:Slider AR1 (End moves to max)',+ userImpact:+ 'With a step that does not divide the range, End stops one step short of the maximum while ArrowRight and PageUp can still reach it.',+ reason:+ 'This test-only binding records the gap named in the Slider record; the endpoint fix is its own change.',+ },+];diff --git a/packages/core/src/Slider/__tests__/Slider.a11y.renders.tsx b/packages/core/src/Slider/__tests__/Slider.a11y.renders.tsxnew file mode 100644index 0000000000..bf5c322072--- /dev/null+++ b/packages/core/src/Slider/__tests__/Slider.a11y.renders.tsx@@ -0,0 +1,42 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file Slider.a11y.renders.tsx+ * @input One Slider binding state+ * @output The React tree every lane renders for that state (the jsdom test directly, the story through Storybook)+ * @position Shared fixture for the Slider binding+ */++import {useState, type ReactElement} from 'react';+import {Slider} from '../Slider';+import type {SliderBindingState} from './Slider.a11y.states';++function BoundSlider({state}: {state: SliderBindingState}) {+ const [value, setValue] = useState(state.facts.value);+ return (+ <Slider+ label={state.label}+ min={state.facts.min}+ max={state.facts.max}+ step={state.facts.step}+ value={value}+ onChange={setValue}+ orientation={state.facts.orientation}+ isDisabled={!state.facts.operable}+ disabledMessage={state.disabledMessage}+ formatValue={+ state.formatValue ? current => `${current} percent` : undefined+ }+ />+ );+}++export function renderSliderState(state: SliderBindingState): ReactElement {+ return (+ <div dir={state.direction ?? 'ltr'} style={{padding: 24, width: 320}}>+ <BoundSlider state={state} />+ </div>+ );+}diff --git a/packages/core/src/Slider/__tests__/Slider.a11y.states.ts b/packages/core/src/Slider/__tests__/Slider.a11y.states.tsnew file mode 100644index 0000000000..797f0c2cb1--- /dev/null+++ b/packages/core/src/Slider/__tests__/Slider.a11y.states.ts@@ -0,0 +1,106 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Slider.a11y.states.ts+ * @input Slider's representative thumb states and the facts SLIDER_PATTERN reads+ * @output SLIDER_BINDING_STATES and the explicit ownership exclusions for this binding+ * @position Binding inventory shared by the jsdom test, the Chromium spec, and the story (component:Slider AR1)+ */++import type {SliderStateFacts} from '@astryxdesign/a11y-spec';++export interface SliderBindingState {+ readonly id: string;+ readonly summary: string;+ readonly storyId: string;+ /** The thumb's accessible name (the visible label). */+ readonly label: string;+ readonly facts: SliderStateFacts;+ /** Props beyond label/min/max/step/value that shape the state. */+ readonly disabledMessage?: string;+ readonly formatValue?: boolean;+ readonly direction?: 'ltr' | 'rtl';+}++function facts(overrides: Partial<SliderStateFacts> = {}): SliderStateFacts {+ return {+ min: 0,+ max: 100,+ step: 1,+ value: 40,+ orientation: 'horizontal',+ rtl: false,+ operable: true,+ focusable: true,+ valueText: null,+ largeStep: 10,+ ...overrides,+ };+}++const story = (id: string) => `a11y-slider--${id}`;++export const SLIDER_BINDING_STATES = [+ {+ id: 'horizontal',+ summary: 'a horizontal single-thumb Slider at 40 of 0–100',+ storyId: story('horizontal'),+ label: 'Volume',+ facts: facts(),+ },+ {+ id: 'vertical',+ summary: 'a vertical single-thumb Slider',+ storyId: story('vertical'),+ label: 'Temperature',+ facts: facts({orientation: 'vertical'}),+ },+ {+ id: 'horizontal-rtl',+ summary:+ 'a horizontal Slider on a right-to-left page: ArrowLeft must raise the value',+ storyId: story('horizontal-rtl'),+ label: 'Volume',+ facts: facts({rtl: true}),+ direction: 'rtl',+ },+ {+ id: 'formatted',+ summary: 'a Slider that speaks a formatted value',+ storyId: story('formatted'),+ label: 'Brightness',+ facts: facts({valueText: '40 percent'}),+ formatValue: true,+ },+ {+ id: 'disabled-with-message',+ summary:+ 'a disabled Slider with a disabled message: the thumb keeps focus and its value',+ storyId: story('disabled-with-message'),+ label: 'Volume',+ facts: facts({operable: false}),+ disabledMessage: 'Volume is locked while sharing your screen',+ },+ {+ id: 'step-three',+ summary: 'a Slider with step 3 on a 0–100 range: End must reach 100',+ storyId: story('step-three'),+ label: 'Zoom',+ facts: facts({step: 3, value: 48, largeStep: 30}),+ },+] as const satisfies ReadonlyArray<SliderBindingState>;++export const SLIDER_EXCLUSIONS = [+ {+ id: 'range-thumb-separation',+ owner: 'component:Slider AR1 and Slider.test.tsx',+ reason:+ "A range Slider renders two thumbs whose aria-valuemin/aria-valuemax narrow to the other thumb minus the minimum separation; that two-thumb coupling and the group semantics around them are the binding's own tests. This binding proves the single-thumb pattern each thumb follows.",+ },+ {+ id: 'pointer-drag-model',+ owner: 'Slider.test.tsx pointer suites and the Chromium pointer evidence',+ reason:+ "Dragging, track clicks (mirrored under RTL), and the value tooltip are pointer behavior outside the keyboard-and-semantics pattern; the component's own suites prove them.",+ },+] as const;diff --git a/packages/core/src/Slider/__tests__/Slider.a11y.test.tsx b/packages/core/src/Slider/__tests__/Slider.a11y.test.tsxnew file mode 100644index 0000000000..26f8bfacfe--- /dev/null+++ b/packages/core/src/Slider/__tests__/Slider.a11y.test.tsx@@ -0,0 +1,105 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file Slider.a11y.test.tsx+ * @input SLIDER_PATTERN bound to Slider's representative states+ * @output jsdom-lane proof of the DOM expectations and an honest "unrun" report for the browser layers+ * @position Binding test for component:Slider AR1 (the Chromium spec covers the rest)+ */++import {cleanup, render, screen} from '@testing-library/react';+import {describe, expect, it} from 'vitest';+import {+ SLIDER_PATTERN,+ checkAccessibilitySpec,+ createJsdomHarness,+ expectAccessibilitySpec,+ summarize,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {SLIDER_KNOWN_FAILURES} from './Slider.a11y.known-failures';+import {renderSliderState} from './Slider.a11y.renders';+import {+ SLIDER_BINDING_STATES,+ SLIDER_EXCLUSIONS,+ type SliderBindingState,+} from './Slider.a11y.states';++function thumb(state: SliderBindingState): HTMLElement {+ return screen.getByRole('slider', {name: state.label});+}++async function checkState(state: SliderBindingState): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: SLIDER_PATTERN,+ binding: 'Slider',+ state: state.id,+ facts: state.facts,+ knownFailures: SLIDER_KNOWN_FAILURES,+ mount: async () => {+ render(renderSliderState(state));+ return createJsdomHarness({subject: thumb(state), related: {}});+ },+ unmount: cleanup,+ });+}++describe('Slider — slider pattern, jsdom lane', () => {+ it.each(+ SLIDER_BINDING_STATES.map(+ state => [state.id, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectAccessibilitySpec({+ spec: SLIDER_PATTERN,+ binding: 'Slider',+ state: state.id,+ facts: state.facts,+ knownFailures: SLIDER_KNOWN_FAILURES,+ render: () => {+ render(renderSliderState(state));+ },+ subject: () => thumb(state),+ related: () => ({}),+ cleanup,+ });+ });++ it('runs the DOM layer and reports the browser-owned outcomes as unrun', async () => {+ const results: BindingResult[] = [];+ for (const state of SLIDER_BINDING_STATES) {+ results.push(await checkState(state));+ }+ const report = summarize(SLIDER_PATTERN, results);+ expect(report.counts.pass).toBeGreaterThan(0);+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);+ expect(report.counts.unexpectedPass).toBe(0);+ });+});++describe('Slider binding inventory', () => {+ it('gives every representative state a distinct checked-in story', () => {+ const stories = SLIDER_BINDING_STATES.map(state => state.storyId);+ expect(new Set(stories).size).toBe(stories.length);+ });++ it('keeps range coupling and pointer ownership explicit', () => {+ expect(SLIDER_EXCLUSIONS.map(exclusion => exclusion.id)).toEqual([+ 'range-thumb-separation',+ 'pointer-drag-model',+ ]);+ for (const exclusion of SLIDER_EXCLUSIONS) {+ expect(exclusion.owner.length, exclusion.id).toBeGreaterThan(20);+ expect(exclusion.reason.length, exclusion.id).toBeGreaterThan(80);+ }+ });++ it('renders exactly one named thumb for every state', () => {+ for (const state of SLIDER_BINDING_STATES) {+ render(renderSliderState(state));+ expect(thumb(state), state.id).toBeTruthy();+ cleanup();+ }+ });+});