An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): add reusable Tabs contract (#6250)
Cindy Zhanga0756075486b
diff --git a/apps/storybook/stories/TabsA11y.stories.tsx b/apps/storybook/stories/TabsA11y.stories.tsxnew file mode 100644index 0000000000..c9f78940d3--- /dev/null+++ b/apps/storybook/stories/TabsA11y.stories.tsx@@ -0,0 +1,50 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TabsA11y.stories.tsx+ * @input Uses the shared Tabs binding inventory and render map+ * @output One checked-in reproduction story for every explicit Tabs contract state+ * @position Stable real-browser fixtures required by AST-009 FR30 and AST-021.+ */++import type {Meta, StoryObj} from '@storybook/react';+import {TABS_STATE_RENDERS} from '../../../packages/core/src/TabList/__tests__/Tabs.a11y.renders';+import {TABS_BINDING_STATES} from '../../../packages/core/src/TabList/__tests__/Tabs.a11y.states';++function storyFor(id: string): StoryObj {+ const state = TABS_BINDING_STATES.find(candidate => candidate.id === id);+ if (state == null) {+ throw new Error(`no binding state "${id}" — see Tabs.a11y.states.ts`);+ }+ return {+ name: `${state.binding} — ${state.id}`,+ render: () => TABS_STATE_RENDERS[state.id](),+ };+}++const meta: Meta = {+ title: 'a11y/Tabs pattern',+ tags: ['no-visual'],+ parameters: {+ docs: {+ description: {+ component:+ 'Binding states for the explicit horizontal Tabs accessibility contract.',+ },+ },+ },+};++export default meta;++export const TabListSelectedLtr = storyFor('tab-list-selected-ltr');+export const TabListSelectedRtl = storyFor('tab-list-selected-rtl');+export const TabListDisabledSkip = storyFor('tab-list-disabled-skip');+export const TabSelectedVisibleLabel = storyFor('tab-selected-visible-label');+export const TabUnselectedVisibleLabel = storyFor(+ 'tab-unselected-visible-label',+);+export const TabDisabledUnselected = storyFor('tab-disabled-unselected');+export const TabSelectedHiddenLabel = storyFor('tab-selected-hidden-label');+export const TabpanelActive = storyFor('tabpanel-active');+export const TabpanelInactive = storyFor('tabpanel-inactive');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex 3e86282e70..19054baed6 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -46,7 +46,8 @@ src/├── button.* the button pattern, same four files├── text-input.* the native text-input pattern, same four files├── modal-dialog.* the native modal-dialog pattern, same four files- └── status-message.* live-region and progress status mechanics+ ├── status-message.* live-region and progress status mechanics+ └── tabs.* explicit horizontal ARIA Tabs semantics```## The patterns@@ -60,6 +61,7 @@ src/| `text-input` | Native HTML controls and [WAI-ARIA textbox](https://www.w3.org/TR/wai-aria-1.2/#textbox) | TextInput, TextArea || `modal-dialog` | [APG dialog (modal)](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/) | Dialog || `status-message` | [WCAG 2.2 Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html) | Toast, FieldStatus, Spinner, ChatSystemMessage, ChatTypingIndicator, ProgressBar |+| `tabs` | [APG Tabs](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/) | Explicit `role="tablist"` TabList, Tab, and caller-authored tabpanels |The `radio-group` contract owns direct-group Tab entry/exit, Space, and adopteddirectional selection, including zero-selection entry. DropdownMenu radio rolesdiff --git a/internal/a11y-spec/src/check.test.ts b/internal/a11y-spec/src/check.test.tsindex 965314f728..6e718cf946 100644--- a/internal/a11y-spec/src/check.test.ts+++ b/internal/a11y-spec/src/check.test.ts@@ -45,6 +45,9 @@ function harness(observes: readonly EvidenceLayer[]): Harness {observes,subject: async () => subject,related: async () => subject,+ contains: async () => true,+ containsSemantically: async () => true,+ references: async () => true,click: async () => {},abortedPress: async () => {},typeText: async () => {},diff --git a/internal/a11y-spec/src/expect.ts b/internal/a11y-spec/src/expect.tsindex c4c909983d..88f33b47b4 100644--- a/internal/a11y-spec/src/expect.ts+++ b/internal/a11y-spec/src/expect.ts@@ -28,6 +28,9 @@ export interface ExpectAccessibilitySpecOptions<Facts> extends Omit<readonly render: () => Promise<void> | void;/** Resolve the role-bearing element the specification checks. */readonly subject: () => Promise<Element> | Element;+ readonly related?: () =>+ | Promise<Readonly<Record<string, Element>>>+ | Readonly<Record<string, Element>>;/** Remove the rendered state between expectations. */readonly cleanup?: () => Promise<void> | void;}@@ -39,13 +42,16 @@ export interface ExpectAccessibilitySpecOptions<Facts> extends Omit<export async function expectAccessibilitySpec<Facts>(options: ExpectAccessibilitySpecOptions<Facts>,): Promise<BindingResult> {- const {spec, render, subject, cleanup, ...binding} = options;+ const {spec, render, subject, related, cleanup, ...binding} = options;const result = await checkAccessibilitySpec({...binding,spec,mount: async () => {await render();- return createJsdomHarness({subject: await subject()});+ return createJsdomHarness({+ subject: await subject(),+ related: await related?.(),+ });},unmount: cleanup,});diff --git a/internal/a11y-spec/src/harness.ts b/internal/a11y-spec/src/harness.tsindex 0241e365ab..f194e79fb0 100644--- a/internal/a11y-spec/src/harness.ts+++ b/internal/a11y-spec/src/harness.ts@@ -71,6 +71,8 @@ export interface ComputedNode {readonly required: boolean | null;/** Computed checked state, or null when the node exposes none. */readonly checked: 'true' | 'false' | 'mixed' | null;+ /** Computed selected state, or null when the node exposes none. */+ readonly selected: boolean | null;readonly disabled: boolean;readonly invalid: boolean;}@@ -116,6 +118,8 @@ export interface Subject {* a design system's private structure.*/visibleLabelText(): Promise<string | null>;+ /** Real-browser layer: whether this node is rendered and visible. */+ isVisible(): Promise<boolean>;/** Real-browser layer: whether this node currently holds focus. */isFocused(): Promise<boolean>;/** Real-browser layer: whether focus is on this node or one of its descendants. */@@ -154,6 +158,19 @@ export interface Harness {* contracts never query component-private structure.*/related(name: string): Promise<Subject>;+ /** DOM layer: whether one semantic subject contains another. */+ contains(container: Subject, candidate: Subject): Promise<boolean>;+ /** Accessibility-tree layer: whether one semantic subject owns another. */+ containsSemantically(+ container: Subject,+ candidate: Subject,+ ): Promise<boolean>;+ /** DOM layer: whether an IDREF attribute resolves to the exact target subject. */+ references(+ source: Subject,+ attribute: string,+ target: Subject,+ ): Promise<boolean>;/*** Real-browser layer: click the subject the way a pointer user would,* including the browser's own judgement that the control is there to bediff --git a/internal/a11y-spec/src/harness/chromium.chromium.spec.ts b/internal/a11y-spec/src/harness/chromium.chromium.spec.tsnew file mode 100644index 0000000000..3e96d3b4c6--- /dev/null+++ b/internal/a11y-spec/src/harness/chromium.chromium.spec.ts@@ -0,0 +1,167 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file chromium.chromium.spec.ts+ * @input Uses @playwright/test and the public Chromium harness seam+ * @output Focused accessibility-tree mapping tests for computed node state+ * @position Harness regression coverage; proves browser AX properties are exposed without DOM substitution.+ */++import {expect, test} from '@playwright/test';+import {createChromiumHarness, holdMotionStill} from './chromium';++test('computed node exposes selected state for tabs', async ({page}) => {+ await page.setContent(`+ <div role="tablist" aria-label="Views">+ <button role="tab" aria-selected="true">Overview</button>+ <button role="tab" aria-selected="false">Activity</button>+ </div>+ `);+ const cdp = await page.context().newCDPSession(page);++ const selected = await createChromiumHarness({+ page,+ subject: page.getByRole('tab', {name: 'Overview'}),+ cdp,+ })+ .subject()+ .then(subject => subject.computed());+ const unselected = await createChromiumHarness({+ page,+ subject: page.getByRole('tab', {name: 'Activity'}),+ cdp,+ })+ .subject()+ .then(subject => subject.computed());++ expect(selected.selected).toBe(true);+ expect(unselected.selected).toBe(false);+});++test('contains compares semantic subjects rather than pointer targets', async ({+ page,+}) => {+ await page.setContent(`+ <div id="pointer-wrapper">+ <div id="semantic-subject"></div>+ <div id="semantic-candidate"></div>+ </div>+ `);+ const cdp = await page.context().newCDPSession(page);+ const harness = createChromiumHarness({+ page,+ subject: page.locator('#semantic-subject'),+ pointerTarget: page.locator('#pointer-wrapper'),+ cdp,+ related: {candidate: page.locator('#semantic-candidate')},+ });++ expect(+ await harness.contains(+ await harness.subject(),+ await harness.related('candidate'),+ ),+ ).toBe(false);+});++test('semantic containment follows aria-owns and excludes hidden descendants', async ({+ page,+}) => {+ await page.setContent(`+ <div id="tablist" role="tablist" aria-owns="owned-tab">+ <button id="hidden-tab" role="tab" aria-hidden="true">Hidden</button>+ </div>+ <button id="owned-tab" role="tab">Owned</button>+ `);+ const cdp = await page.context().newCDPSession(page);+ const harness = createChromiumHarness({+ page,+ subject: page.locator('#tablist'),+ cdp,+ related: {+ owned: page.locator('#owned-tab'),+ hidden: page.locator('#hidden-tab'),+ },+ });++ expect(+ await harness.containsSemantically(+ await harness.subject(),+ await harness.related('owned'),+ ),+ ).toBe(true);+ expect(+ await harness.containsSemantically(+ await harness.subject(),+ await harness.related('hidden'),+ ),+ ).toBe(false);+});++test('references compares resolved node identity when ids are duplicated', async ({+ page,+}) => {+ await page.setContent(`+ <button id="source" aria-controls="panel">Tab</button>+ <div id="panel">Wrong duplicate</div>+ <div id="panel" data-expected>Expected panel</div>+ `);+ const cdp = await page.context().newCDPSession(page);+ const harness = createChromiumHarness({+ page,+ subject: page.locator('#source'),+ cdp,+ related: {target: page.locator('[data-expected]')},+ });++ expect(+ await harness.references(+ await harness.subject(),+ 'aria-controls',+ await harness.related('target'),+ ),+ ).toBe(false);+});++test('holding motion still prevents intermediate transition frames', async ({+ page,+}) => {+ await page.setContent(`+ <div id="panel" style="opacity:1; transition:opacity 10s">Panel</div>+ `);+ await holdMotionStill(page);+ const cdp = await page.context().newCDPSession(page);+ const harness = createChromiumHarness({+ page,+ subject: page.locator('#panel'),+ cdp,+ });++ await page.locator('#panel').evaluate(element => {+ element.style.opacity = '0';+ });++ expect(await (await harness.subject()).isVisible()).toBe(false);+});++test('subjects report rendered visibility', async ({page}) => {+ await page.setContent(`+ <div id="visible">Visible</div>+ <div id="hidden" style="display:none">Hidden</div>+ <div id="transparent" style="opacity:0">Transparent</div>+ `);+ const cdp = await page.context().newCDPSession(page);+ const harness = createChromiumHarness({+ page,+ subject: page.locator('#visible'),+ cdp,+ related: {+ hidden: page.locator('#hidden'),+ transparent: page.locator('#transparent'),+ },+ });++ expect(await (await harness.subject()).isVisible()).toBe(true);+ expect(await (await harness.related('hidden')).isVisible()).toBe(false);+ expect(await (await harness.related('transparent')).isVisible()).toBe(false);+});diff --git a/internal/a11y-spec/src/harness/chromium.ts b/internal/a11y-spec/src/harness/chromium.tsindex c926393502..69d4cb12f2 100644--- a/internal/a11y-spec/src/harness/chromium.ts+++ b/internal/a11y-spec/src/harness/chromium.ts@@ -216,6 +216,7 @@ async function computedNode(readOnly: null,required: null,checked: null,+ selected: null,disabled: false,invalid: false,};@@ -241,6 +242,7 @@ async function computedNode(}const live = property(node, 'live');const checked = property(node, 'checked');+ const selected = optionalFlag(node, 'selected');const invalid = property(node, 'invalid');const exposedValue = node.value?.value;@@ -285,6 +287,7 @@ async function computedNode(: checked === 'mixed'? 'mixed': null,+ selected,disabled: flag(node, 'disabled'),invalid: invalid != null && invalid !== 'false' && invalid !== false,};@@ -304,11 +307,30 @@ async function computedNode(* `use: {reducedMotion: 'reduce'}` and Chromium's own* `--force-prefers-reduced-motion` flag both leave* `matchMedia('(prefers-reduced-motion: reduce)')` FALSE in this version —- * measured, not assumed — so either one would read like a safeguard while doing- * nothing. `emulateMedia` takes effect immediately and can be checked.+ * measured, not assumed. `emulateMedia` sets the preference, while the injected+ * override also collapses components that intentionally retain a non-zero+ * reduced-motion duration. Two animation frames apply both changes before an+ * expectation can observe the page.*/export async function holdMotionStill(page: Page): Promise<void> {await page.emulateMedia({reducedMotion: 'reduce'});+ await page.addStyleTag({+ content: `+ *, *::before, *::after {+ animation-delay: 0s !important;+ animation-duration: 0s !important;+ scroll-behavior: auto !important;+ transition-delay: 0s !important;+ transition-duration: 0s !important;+ }+ `,+ });+ await page.evaluate(+ () =>+ new Promise<void>(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ }),+ );}export interface ChromiumHarnessOptions {@@ -330,6 +352,111 @@ export interface ChromiumHarnessOptions {readonly related?: Readonly<Record<string, Locator>>;}+async function renderedVisible(locator: Locator): Promise<boolean> {+ return locator.evaluate(element => {+ if (+ !element.checkVisibility({+ visibilityProperty: true,+ opacityProperty: true,+ contentVisibilityAuto: true,+ })+ ) {+ return false;+ }+ const box = element.getBoundingClientRect();+ return box.width > 0 && box.height > 0;+ });+}++const AX_OWNERSHIP_TARGET_ATTRIBUTE = 'data-a11y-spec-ownership-target';++async function backendNodeId(+ cdp: CDPSession,+ locator: Locator,+): Promise<number | null> {+ const previous = await locator.getAttribute(AX_OWNERSHIP_TARGET_ATTRIBUTE);+ await locator.evaluate(+ (element, attribute) => element.setAttribute(attribute, ''),+ AX_OWNERSHIP_TARGET_ATTRIBUTE,+ );+ try {+ const {root} = (await cdp.send('DOM.getDocument', {+ depth: 0,+ })) as unknown as {+ root: {nodeId: number};+ };+ const {nodeId} = (await cdp.send('DOM.querySelector', {+ nodeId: root.nodeId,+ selector: `[${AX_OWNERSHIP_TARGET_ATTRIBUTE}]`,+ })) as unknown as {nodeId: number};+ if (nodeId === 0) {+ return null;+ }+ const {node} = (await cdp.send('DOM.describeNode', {+ nodeId,+ })) as unknown as {+ node: {backendNodeId?: number};+ };+ return node.backendNodeId ?? null;+ } finally {+ await locator.evaluate(+ (element, [attribute, oldValue]) => {+ if (oldValue == null) {+ element.removeAttribute(attribute);+ } else {+ element.setAttribute(attribute, oldValue);+ }+ },+ [AX_OWNERSHIP_TARGET_ATTRIBUTE, previous] as const,+ );+ }+}++async function containsSemantically(+ cdp: CDPSession,+ container: Locator,+ candidate: Locator,+): Promise<boolean> {+ const containerBackendId = await backendNodeId(cdp, container);+ const candidateBackendId = await backendNodeId(cdp, candidate);+ if (containerBackendId == null || candidateBackendId == null) {+ return false;+ }+ const {nodes} = (await cdp.send(+ 'Accessibility.getFullAXTree',+ )) as unknown as {nodes: readonly AxNode[]};+ const byId = new Map(+ nodes.flatMap(node =>+ node.nodeId == null ? [] : [[node.nodeId, node] as const],+ ),+ );+ const containerNode = nodes.find(+ node =>+ node.backendDOMNodeId === containerBackendId && node.ignored !== true,+ );+ const candidateNode = nodes.find(+ node =>+ node.backendDOMNodeId === candidateBackendId && node.ignored !== true,+ );+ if (containerNode?.nodeId == null || candidateNode?.nodeId == null) {+ return false;+ }+ const pending = [...(containerNode.childIds ?? [])];+ const visited = new Set<string>();+ while (pending.length > 0) {+ const nodeId = pending.pop();+ if (nodeId == null || visited.has(nodeId)) {+ continue;+ }+ if (nodeId === candidateNode.nodeId) {+ return true;+ }+ visited.add(nodeId);+ pending.push(...(byId.get(nodeId)?.childIds ?? []));+ }+ return false;+}+export function createChromiumHarness(options: ChromiumHarnessOptions,): Harness {@@ -341,6 +468,7 @@ export function createChromiumHarness(return initialElement;};const pointerTargets = new WeakMap<Subject, Locator>();+ const semanticTargets = new WeakMap<Subject, Locator>();const subject: Subject = {attribute: name => locator.getAttribute(name),@@ -703,6 +831,7 @@ export function createChromiumHarness(await explicitLabel?.dispose();}},+ isVisible: () => renderedVisible(locator),isFocused: () =>locator.evaluate(element => element.ownerDocument.activeElement === element,@@ -719,6 +848,7 @@ export function createChromiumHarness(focus: () => locator.focus(),};pointerTargets.set(subject, pointerLocator);+ semanticTargets.set(subject, locator);const relatedSubject = (name: string): Subject => {const related = options.related?.[name];@@ -813,6 +943,7 @@ export function createChromiumHarness(const value = (await related.innerText()).trim();return value === '' ? null : value;},+ isVisible: () => renderedVisible(related),isFocused: () =>related.evaluate(element => element.ownerDocument.activeElement === element,@@ -829,6 +960,7 @@ export function createChromiumHarness(focus: () => related.focus(),};pointerTargets.set(result, related);+ semanticTargets.set(result, related);return result;};@@ -837,6 +969,65 @@ export function createChromiumHarness(observes: CHROMIUM_OBSERVES,subject: async () => subject,related: async name => relatedSubject(name),+ contains: async (container, candidate) => {+ const containerLocator = semanticTargets.get(container);+ const candidateLocator = semanticTargets.get(candidate);+ if (containerLocator == null || candidateLocator == null) {+ throw new Error(+ 'the Chromium harness was asked to compare a subject it did not create',+ );+ }+ const candidateHandle = await candidateLocator.elementHandle();+ if (candidateHandle == null) {+ return false;+ }+ try {+ return await containerLocator.evaluate(+ (element, candidateElement) => element.contains(candidateElement),+ candidateHandle,+ );+ } finally {+ await candidateHandle.dispose();+ }+ },+ containsSemantically: async (container, candidate) => {+ const containerLocator = semanticTargets.get(container);+ const candidateLocator = semanticTargets.get(candidate);+ if (containerLocator == null || candidateLocator == null) {+ throw new Error(+ 'the Chromium harness was asked to compare a subject it did not create',+ );+ }+ return containsSemantically(cdp, containerLocator, candidateLocator);+ },+ references: async (source, attribute, target) => {+ const sourceLocator = semanticTargets.get(source);+ const targetLocator = semanticTargets.get(target);+ if (sourceLocator == null || targetLocator == null) {+ throw new Error(+ 'the Chromium harness was asked to compare a subject it did not create',+ );+ }+ const targetHandle = await targetLocator.elementHandle();+ if (targetHandle == null) {+ return false;+ }+ try {+ return await sourceLocator.evaluate(+ (element, [name, targetElement]) =>+ (element.getAttribute(name) ?? '')+ .split(/\s+/)+ .filter(Boolean)+ .some(+ id =>+ element.ownerDocument.getElementById(id) === targetElement,+ ),+ [attribute, targetHandle] as const,+ );+ } finally {+ await targetHandle.dispose();+ }+ },click: async (targetSubject, options) => {const target = pointerTargets.get(targetSubject);if (target == null) {diff --git a/internal/a11y-spec/src/harness/jsdom.ts b/internal/a11y-spec/src/harness/jsdom.tsindex 1b01b30672..36ec989f8c 100644--- a/internal/a11y-spec/src/harness/jsdom.ts+++ b/internal/a11y-spec/src/harness/jsdom.ts@@ -113,6 +113,8 @@ function createSubject(element: Element): Subject {unobservable('accessibility-tree', 'a computed accessibility node'),visibleLabelText: async () =>unobservable('real-browser', 'what a label actually renders as'),+ isVisible: async () =>+ unobservable('real-browser', 'whether a node is rendered and visible'),isFocused: async () => unobservable('real-browser', 'real focus'),containsFocus: async () =>unobservable('real-browser', 'whether focus is inside a subject'),@@ -137,17 +139,56 @@ export interface JsdomHarnessOptions {}export function createJsdomHarness(options: JsdomHarnessOptions): Harness {+ const elements = new WeakMap<Subject, Element>();const subject = createSubject(options.subject);+ elements.set(subject, options.subject);+ const relatedSubjects = new Map<string, Subject>();+ for (const [name, element] of Object.entries(options.related ?? {})) {+ const related = createSubject(element);+ elements.set(related, element);+ relatedSubjects.set(name, related);+ }return {name: HARNESS,observes: JSDOM_OBSERVES,subject: async () => subject,related: async name => {- const element = options.related?.[name];- if (element == null) {+ const related = relatedSubjects.get(name);+ if (related == null) {throw new MissingHarnessRelation(HARNESS, name);}- return createSubject(element);+ return related;+ },+ contains: async (container, candidate) => {+ const containerElement = elements.get(container);+ const candidateElement = elements.get(candidate);+ if (containerElement == null || candidateElement == null) {+ throw new Error(+ 'the jsdom harness was asked to compare a subject it did not create',+ );+ }+ return containerElement.contains(candidateElement);+ },+ containsSemantically: async () =>+ unobservable(+ 'accessibility-tree',+ 'whether one subject semantically owns another',+ ),+ references: async (source, attribute, target) => {+ const sourceElement = elements.get(source);+ const targetElement = elements.get(target);+ if (sourceElement == null || targetElement == null) {+ throw new Error(+ 'the jsdom harness was asked to compare a subject it did not create',+ );+ }+ return (sourceElement.getAttribute(attribute) ?? '')+ .split(/\s+/)+ .filter(Boolean)+ .some(+ id =>+ sourceElement.ownerDocument.getElementById(id) === targetElement,+ );},click: async () =>unobservable('real-browser', 'a real pointer activation'),diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.tsindex a28d4b7011..e6bf50a0c8 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -108,3 +108,5 @@ export {export {saysInOrder, spokenWords} from './spoken';export {BUTTON_PATTERN, type ButtonStateFacts} from './patterns/button';++export {TABS_PATTERN, type TabsStateFacts} from './patterns/tabs';diff --git a/internal/a11y-spec/src/patterns/tabs.chromium.spec.ts b/internal/a11y-spec/src/patterns/tabs.chromium.spec.tsnew file mode 100644index 0000000000..f2448fc3c6--- /dev/null+++ b/internal/a11y-spec/src/patterns/tabs.chromium.spec.ts@@ -0,0 +1,175 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file tabs.chromium.spec.ts+ * @input Uses @playwright/test, the Tabs contract and fixtures, and the Chromium harness+ * @output Real-browser positive and mutation proof for every Tabs expectation+ * @position Contract self-test; proves the reusable contract, not Astryx components.+ */++import {expect, test, type CDPSession, type Page} from '@playwright/test';+import {checkAccessibilitySpec, type ExpectationResult} from '../check';+import {describeExpectation, requiredLayers} from '../contract';+import {+ CHROMIUM_OBSERVES,+ createChromiumHarness,+ holdMotionStill,+} from '../harness/chromium';+import {TABS_PATTERN} from './tabs';+import {+ CONFORMING_TABS_FIXTURES,+ TABS_MUTATIONS,+ TABS_SUBJECT_SELECTOR,+ expectedTabsMutationFailure,+ tabsFixture,+ type TabsFixture,+} from './tabs.fixtures';++function fixturePage(html: string): string {+ return `<!doctype html><html lang="en"><body>${html}</body></html>`;+}++function relatedFor(page: Page, target: TabsFixture) {+ const names = [+ ...target.facts.tabRelations,+ ...target.facts.panelRelations,+ target.facts.controlledPanel,+ target.facts.labellingTab,+ ].filter((name): name is string => name != null);+ return Object.fromEntries(+ names.map(name => [name, page.locator(`[data-a11y-related="${name}"]`)]),+ );+}++async function results(+ page: Page,+ cdp: CDPSession,+ target: TabsFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ const run = await checkAccessibilitySpec({+ spec: TABS_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ only,+ mount: async () => {+ await page.setContent(fixturePage(target.html));+ await holdMotionStill(page);+ return createChromiumHarness({+ page,+ subject: page.locator(TABS_SUBJECT_SELECTOR),+ cdp,+ visibleLabel: target.facts.visibleLabel ? undefined : null,+ related: relatedFor(page, target),+ });+ },+ });+ return run.results;+}++function resultFor(+ observed: readonly ExpectationResult[],+ id: string,+): ExpectationResult {+ const found = observed.find(result => result.expectation === id);+ if (found == null) {+ throw new Error(`no result for ${id}`);+ }+ return found;+}++test.describe('Tabs contract — conforming fixtures', () => {+ for (const id of CONFORMING_TABS_FIXTURES) {+ test(`${id}: every applicable expectation passes`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const observed = await results(page, cdp, tabsFixture(id));+ const notPassing = observed.filter(+ result =>+ result.status !== 'pass' && result.status !== 'not-applicable',+ );+ expect(+ notPassing.map(+ result => `${result.expectation}: ${result.detail ?? ''}`,+ ),+ ).toEqual([]);+ });+ }+});++test('all-unavailable alternatives are not activation or skip candidates', async ({+ page,+}) => {+ const cdp = await page.context().newCDPSession(page);+ const observed = await results(+ page,+ cdp,+ tabsFixture('conforming-tablist-no-available-alternate'),+ );+ for (const id of [+ 'tabs.focus.skips-unavailable',+ 'tabs.selection.manual-arrows-preserve-state',+ 'tabs.selection.enter-round-trip',+ 'tabs.selection.space-round-trip',+ 'tabs.selection.pointer-round-trip',+ ]) {+ expect(resultFor(observed, id).status, id).toBe('not-applicable');+ }+});++test('every expectation passes against at least one conforming fixture', async ({+ page,+}) => {+ test.setTimeout(3 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const withoutPass: string[] = [];+ for (const expectation of TABS_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ let passed = false;+ for (const id of CONFORMING_TABS_FIXTURES) {+ const [result] = await results(page, cdp, tabsFixture(id), [+ expectation.id,+ ]);+ if (result?.status === 'pass') {+ passed = true;+ break;+ }+ }+ if (!passed) {+ withoutPass.push(expectation.id);+ }+ }+ expect(withoutPass).toEqual([]);+});++test.describe('Tabs contract — deliberately violating fixtures', () => {+ for (const [expectationId, fixtures] of Object.entries(TABS_MUTATIONS)) {+ const expectation = TABS_PATTERN.expectations.find(+ candidate => candidate.id === expectationId,+ );++ for (const fixtureId of fixtures) {+ test(`${expectationId} rejects ${fixtureId}`, async ({page}) => {+ const target = tabsFixture(fixtureId);+ const cdp = await page.context().newCDPSession(page);+ const result = resultFor(+ await results(page, cdp, target, [expectationId]),+ expectationId,+ );+ expect(result.status).toBe('fail');+ expect(result.detail).toBe(+ expectedTabsMutationFailure(expectationId, fixtureId),+ );+ if (expectation != null) {+ expect(result.description).toBe(describeExpectation(expectation));+ }+ });+ }+ }+});diff --git a/internal/a11y-spec/src/patterns/tabs.fixtures.ts b/internal/a11y-spec/src/patterns/tabs.fixtures.tsnew file mode 100644index 0000000000..dba28f8197--- /dev/null+++ b/internal/a11y-spec/src/patterns/tabs.fixtures.ts@@ -0,0 +1,808 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file tabs.fixtures.ts+ * @input Uses TabsStateFacts+ * @output Plain-HTML conforming and deliberately violating Tabs fixtures+ * @position Mutation proof for the reusable contract; no Astryx component code.+ */++import type {TabsStateFacts} from './tabs';++const SUBJECT_ATTRIBUTE = 'data-a11y-subject';+export const TABS_SUBJECT_SELECTOR = `[${SUBJECT_ATTRIBUTE}]`;++export interface TabsFixture {+ readonly id: string;+ readonly summary: string;+ readonly facts: TabsStateFacts;+ readonly html: string;+}++function baseFacts(overrides: Partial<TabsStateFacts> = {}): TabsStateFacts {+ return {+ part: 'tablist',+ selected: null,+ active: null,+ disabled: null,+ focusable: null,+ visibleLabel: true,+ controlsPanel: false,+ controlledPanel: null,+ labelledByTab: false,+ labellingTab: null,+ tabRelations: ['first', 'second', 'third'],+ panelRelations: ['panel-first', 'panel-second', 'panel-third'],+ disabledTabs: [],+ selectedTab: 'first',+ direction: 'ltr',+ manualActivation: true,+ tabReachable: true,+ pointerSelection: true,+ pointerCancellation: false,+ ...overrides,+ };+}++function tabFacts(overrides: Partial<TabsStateFacts> = {}): TabsStateFacts {+ return baseFacts({+ part: 'tab',+ selected: true,+ disabled: false,+ focusable: true,+ controlsPanel: true,+ controlledPanel: 'panel-first',+ tabRelations: [],+ panelRelations: [],+ selectedTab: null,+ tabReachable: true,+ pointerSelection: false,+ pointerCancellation: true,+ ...overrides,+ });+}++function panelFacts(overrides: Partial<TabsStateFacts> = {}): TabsStateFacts {+ return baseFacts({+ part: 'tabpanel',+ selected: null,+ active: true,+ disabled: null,+ controlsPanel: false,+ controlledPanel: null,+ labelledByTab: true,+ labellingTab: 'first',+ tabRelations: [],+ panelRelations: [],+ selectedTab: null,+ tabReachable: false,+ pointerSelection: false,+ pointerCancellation: false,+ ...overrides,+ });+}++interface GroupOptions {+ readonly direction?: 'ltr' | 'rtl';+ readonly subject?:+ 'tablist' | 'first-tab' | 'second-tab' | 'first-panel' | 'second-panel';+ readonly tablistRole?: string;+ readonly named?: boolean;+ readonly tabRole?: string;+ readonly firstTabLabel?: string;+ readonly firstTabAriaLabel?: string;+ readonly hideFirstTabLabel?: boolean;+ readonly firstSelected?: boolean;+ readonly secondSelected?: boolean;+ readonly secondDisabled?: boolean;+ readonly thirdDisabled?: boolean;+ readonly secondAriaDisabled?: boolean;+ readonly controls?: 'valid' | 'missing' | 'dangling' | 'wrong';+ readonly panelRole?: string;+ readonly panelLabel?: 'valid' | 'missing' | 'dangling' | 'wrong' | 'empty';+ readonly firstPanelHidden?: boolean;+ readonly firstPanelCssHidden?: boolean;+ readonly firstPanelTransparent?: boolean;+ readonly secondPanelHidden?: boolean;+ readonly secondPanelCssVisible?: boolean;+ readonly duplicatePanelId?: boolean;+ readonly duplicateTabId?: boolean;+ readonly wrongEntry?: boolean;+ readonly trapTab?: boolean;+ readonly arrow?:+ | 'works'+ | 'inert'+ | 'one-way'+ | 'changes-selection'+ | 'does-not-skip'+ | 'physical-ltr'+ | 'no-wrap';+ readonly keyboard?: 'works' | 'inert' | 'one-way';+ readonly pointer?: 'works' | 'inert' | 'one-way' | 'down';+}++function groupHtml(options: GroupOptions = {}): string {+ const {+ direction = 'ltr',+ subject = 'tablist',+ tablistRole = 'tablist',+ named = true,+ tabRole = 'tab',+ firstTabLabel = 'Overview',+ firstTabAriaLabel,+ hideFirstTabLabel = false,+ firstSelected = true,+ secondSelected = false,+ secondDisabled = false,+ thirdDisabled = false,+ secondAriaDisabled = false,+ controls = 'valid',+ panelRole = 'tabpanel',+ panelLabel = 'valid',+ firstPanelHidden = !firstSelected,+ firstPanelCssHidden = false,+ firstPanelTransparent = false,+ secondPanelHidden = !secondSelected,+ secondPanelCssVisible = false,+ duplicatePanelId = false,+ duplicateTabId = false,+ wrongEntry = false,+ trapTab = false,+ arrow = 'works',+ keyboard = 'works',+ pointer = 'works',+ } = options;++ const subjectAttribute = (part: GroupOptions['subject']) =>+ subject === part ? ` ${SUBJECT_ATTRIBUTE}` : '';+ const controlsAttribute =+ controls === 'valid'+ ? ' aria-controls="panel-first"'+ : controls === 'wrong'+ ? ' aria-controls="panel-second"'+ : controls === 'dangling'+ ? ' aria-controls="missing-panel"'+ : '';+ const panelLabelAttribute =+ panelLabel === 'valid' || panelLabel === 'empty'+ ? ' aria-labelledby="tab-first"'+ : panelLabel === 'wrong'+ ? ' aria-labelledby="tab-second"'+ : panelLabel === 'dangling'+ ? ' aria-labelledby="missing-tab"'+ : '';+ const firstLabel =+ panelLabel === 'empty' ? '' : hideFirstTabLabel ? '▣' : firstTabLabel;+ const firstAria =+ firstTabAriaLabel == null ? '' : ` aria-label="${firstTabAriaLabel}"`;++ return `+ ${duplicatePanelId ? '<div id="panel-first">Wrong duplicate panel</div>' : ''}+ ${duplicateTabId ? '<button id="tab-first">Wrong duplicate tab</button>' : ''}+ <button type="button">Before</button>+ <div${subjectAttribute('tablist')} data-a11y-tabs role="${tablistRole}"${named ? ' aria-label="Project views"' : ''} dir="${direction}">+ <button${subjectAttribute('first-tab')} data-a11y-related="first" data-key="first" id="tab-first" role="${tabRole}" aria-selected="${firstSelected}"${controlsAttribute}${firstAria} tabindex="${wrongEntry ? -1 : firstSelected ? 0 : -1}">${firstLabel}</button>+ <button${subjectAttribute('second-tab')} data-a11y-related="second" data-key="second" id="tab-second" role="tab" aria-selected="${secondSelected}" aria-controls="panel-second" tabindex="${wrongEntry ? 0 : secondSelected ? 0 : -1}"${secondDisabled ? ' disabled' : ''}${secondAriaDisabled ? ' aria-disabled="true"' : ''}>Activity</button>+ <button data-a11y-related="third" data-key="third" id="tab-third" role="tab" aria-selected="false" aria-controls="panel-third" tabindex="-1"${thirdDisabled ? ' disabled' : ''}>Members</button>+ </div>+ <div${subjectAttribute('first-panel')} data-a11y-related="panel-first" id="panel-first" role="${panelRole}"${panelLabelAttribute}${firstPanelHidden ? ' hidden' : ''}${firstPanelCssHidden ? ' style="display:none"' : firstPanelTransparent ? ' style="opacity:0"' : ''}>Overview panel</div>+ <div${subjectAttribute('second-panel')} data-a11y-related="panel-second" id="panel-second" role="tabpanel" aria-labelledby="tab-second"${secondPanelHidden ? ' hidden' : ''}${secondPanelCssVisible ? ' style="display:block !important"' : ''}>Activity panel</div>+ <div data-a11y-related="panel-third" id="panel-third" role="tabpanel" aria-labelledby="tab-third" hidden>Members panel</div>+ <button type="button">After</button>+ <script>+ (() => {+ const list = document.querySelector('[data-a11y-tabs]');+ const tabs = Array.from(list.querySelectorAll('[role="tab"], [data-key]'));+ const panels = ['first', 'second', 'third'].map(key => document.getElementById('panel-' + key));+ const select = key => {+ tabs.forEach(tab => {+ const active = tab.dataset.key === key;+ tab.setAttribute('aria-selected', String(active));+ tab.setAttribute('tabindex', active ? '0' : '-1');+ });+ panels.forEach(panel => { panel.hidden = panel.id !== 'panel-' + key; });+ };+ tabs.forEach(tab => {+ ${pointer === 'down' ? "tab.addEventListener('pointerdown', () => select(tab.dataset.key));" : ''}+ tab.addEventListener('click', () => {+ ${pointer === 'inert' ? 'return;' : ''}+ ${pointer === 'one-way' ? "if (tab.dataset.key === 'first') return;" : ''}+ select(tab.dataset.key);+ });+ });+ list.addEventListener('keydown', event => {+ ${trapTab ? "if (event.key === 'Tab') { event.preventDefault(); return; }" : ''}+ const rtl = ${arrow === 'physical-ltr' ? 'false' : "getComputedStyle(list).direction === 'rtl'"};+ const forward = rtl ? 'ArrowLeft' : 'ArrowRight';+ const backward = rtl ? 'ArrowRight' : 'ArrowLeft';+ if (event.key === forward || event.key === backward) {+ ${arrow === 'inert' ? 'return;' : ''}+ ${arrow === 'one-way' ? 'if (event.key === backward) return;' : ''}+ event.preventDefault();+ const current = tabs.indexOf(document.activeElement);+ const step = event.key === forward ? 1 : -1;+ const rawIndex = current + step;+ ${arrow === 'no-wrap' ? 'if (rawIndex < 0 || rawIndex >= tabs.length) return;' : ''}+ let index = (rawIndex + tabs.length) % tabs.length;+ ${arrow === 'does-not-skip' ? '' : 'while (tabs[index].disabled) index = (index + step + tabs.length) % tabs.length;'}+ tabs[index].focus();+ ${arrow === 'changes-selection' ? 'select(tabs[index].dataset.key);' : ''}+ return;+ }+ if (event.key === 'Enter' || event.key === ' ') {+ ${keyboard === 'inert' ? 'event.preventDefault(); return;' : ''}+ ${keyboard === 'one-way' ? "if (document.activeElement.dataset.key === 'first') { event.preventDefault(); return; }" : ''}+ event.preventDefault();+ select(document.activeElement.dataset.key);+ }+ });+ })();+ </script>+ `;+}++export const TABS_FIXTURES: readonly TabsFixture[] = [+ {+ id: 'conforming-tablist-aria-owns',+ summary: 'a tablist that semantically owns an out-of-tree tab',+ facts: baseFacts({+ tabRelations: ['first'],+ panelRelations: [],+ selectedTab: null,+ manualActivation: false,+ tabReachable: false,+ pointerSelection: false,+ }),+ html: `<div ${SUBJECT_ATTRIBUTE} role="tablist" aria-label="Project views" aria-owns="tab-first"></div><button data-a11y-related="first" id="tab-first" role="tab" aria-selected="true">Overview</button>`,+ },+ {+ id: 'conforming-tablist-ltr',+ summary: 'a horizontal LTR manual-activation tablist',+ facts: baseFacts(),+ html: groupHtml(),+ },+ {+ id: 'conforming-tablist-rtl',+ summary: 'a horizontal RTL manual-activation tablist',+ facts: baseFacts({direction: 'rtl'}),+ html: groupHtml({direction: 'rtl'}),+ },+ {+ id: 'conforming-tablist-disabled-skip',+ summary: 'a tablist with an unavailable middle tab',+ facts: baseFacts({disabledTabs: ['second']}),+ html: groupHtml({secondDisabled: true}),+ },+ {+ id: 'conforming-tablist-no-available-alternate',+ summary: 'a tablist whose only available tab is already selected',+ facts: baseFacts({disabledTabs: ['second', 'third']}),+ html: groupHtml({secondDisabled: true, thirdDisabled: true}),+ },+ {+ id: 'conforming-tab-selected',+ summary: 'a selected available tab with a controlled panel',+ facts: tabFacts(),+ html: groupHtml({subject: 'first-tab'}),+ },+ {+ id: 'conforming-tab-unselected',+ summary: 'an unselected available tab with a controlled panel',+ facts: tabFacts({+ selected: false,+ controlledPanel: 'panel-second',+ tabReachable: false,+ }),+ html: groupHtml({subject: 'second-tab'}),+ },+ {+ id: 'conforming-tab-disabled',+ summary: 'an unavailable unselected tab',+ facts: tabFacts({+ selected: false,+ disabled: true,+ focusable: false,+ controlledPanel: 'panel-second',+ tabReachable: false,+ pointerCancellation: false,+ }),+ html: groupHtml({subject: 'second-tab', secondDisabled: true}),+ },+ {+ id: 'conforming-tab-unavailable-inert',+ summary: 'a focusable unavailable tab whose activation is inert',+ facts: tabFacts({+ selected: false,+ disabled: true,+ focusable: true,+ controlledPanel: 'panel-second',+ tabReachable: false,+ pointerCancellation: false,+ }),+ html: groupHtml({+ subject: 'second-tab',+ secondAriaDisabled: true,+ keyboard: 'inert',+ pointer: 'inert',+ }),+ },+ {+ id: 'conforming-tab-hidden-label',+ summary: 'a selected icon-only tab named programmatically',+ facts: tabFacts({visibleLabel: false}),+ html: groupHtml({+ subject: 'first-tab',+ firstTabLabel: 'Overview',+ firstTabAriaLabel: 'Overview',+ hideFirstTabLabel: true,+ }),+ },+ {+ id: 'conforming-panel-active',+ summary: 'the visible panel labelled by the selected tab',+ facts: panelFacts(),+ html: groupHtml({subject: 'first-panel'}),+ },+ {+ id: 'conforming-panel-inactive',+ summary: 'an inactive hidden panel labelled by its tab',+ facts: panelFacts({active: false, labellingTab: 'second'}),+ html: groupHtml({subject: 'second-panel'}),+ },++ {+ id: 'violating-tablist-role',+ summary: 'a Tabs container exposed as a toolbar',+ facts: baseFacts(),+ html: groupHtml({tablistRole: 'toolbar'}),+ },+ {+ id: 'violating-tablist-name',+ summary: 'an unnamed tablist',+ facts: baseFacts(),+ html: groupHtml({named: false}),+ },+ {+ id: 'violating-tab-role',+ summary: 'a tab exposed as a button',+ facts: tabFacts(),+ html: groupHtml({subject: 'first-tab', tabRole: 'button'}),+ },+ {+ id: 'violating-tab-name',+ summary: 'a tab with no accessible name',+ facts: tabFacts(),+ html: groupHtml({subject: 'first-tab', firstTabLabel: ''}),+ },+ {+ id: 'violating-tab-name-mismatch',+ summary: 'a tab whose accessible name replaces its visible label',+ facts: tabFacts(),+ html: groupHtml({+ subject: 'first-tab',+ firstTabLabel: 'Overview',+ firstTabAriaLabel: 'Activity',+ }),+ },+ {+ id: 'violating-tab-selected',+ summary: 'a selected tab exposed as unselected',+ facts: tabFacts(),+ html: groupHtml({subject: 'first-tab', firstSelected: false}),+ },+ {+ id: 'violating-tab-disabled',+ summary: 'an unavailable tab exposed as available',+ facts: tabFacts({+ selected: false,+ disabled: true,+ tabReachable: false,+ pointerCancellation: false,+ }),+ html: groupHtml({subject: 'second-tab'}),+ },+ {+ id: 'violating-unavailable-operable',+ summary: 'a tab exposed as unavailable that still activates',+ facts: tabFacts({+ selected: false,+ disabled: true,+ controlledPanel: 'panel-second',+ tabReachable: false,+ pointerCancellation: false,+ }),+ html: groupHtml({subject: 'second-tab', secondAriaDisabled: true}),+ },+ {+ id: 'violating-controls-missing',+ summary: 'a tab with no panel relationship',+ facts: tabFacts(),+ html: groupHtml({subject: 'first-tab', controls: 'missing'}),+ },+ {+ id: 'violating-controls-dangling',+ summary: 'a tab whose aria-controls target does not exist',+ facts: tabFacts(),+ html: groupHtml({subject: 'first-tab', controls: 'dangling'}),+ },+ {+ id: 'violating-controls-wrong-existing',+ summary: 'a tab whose aria-controls names another tab’s existing panel',+ facts: tabFacts(),+ html: groupHtml({subject: 'first-tab', controls: 'wrong'}),+ },+ {+ id: 'violating-controls-duplicate-id',+ summary: 'aria-controls resolves to a duplicate instead of the bound panel',+ facts: tabFacts(),+ html: groupHtml({subject: 'first-tab', duplicatePanelId: true}),+ },+ {+ id: 'violating-tab-outside-tablist',+ summary: 'a declared tab rendered outside the tablist',+ facts: baseFacts(),+ html: `<button type="button">Before</button><div ${SUBJECT_ATTRIBUTE} role="tablist" aria-label="Project views"><button data-a11y-related="second" id="tab-second" role="tab" aria-selected="false" aria-controls="panel-second" tabindex="-1">Activity</button><button data-a11y-related="third" id="tab-third" role="tab" aria-selected="false" aria-controls="panel-third" tabindex="-1">Members</button></div><button data-a11y-related="first" id="tab-first" role="tab" aria-selected="true" aria-controls="panel-first" tabindex="0">Overview</button><div data-a11y-related="panel-first" id="panel-first" role="tabpanel" aria-labelledby="tab-first">Overview panel</div><div data-a11y-related="panel-second" id="panel-second" role="tabpanel" aria-labelledby="tab-second" hidden>Activity panel</div><div data-a11y-related="panel-third" id="panel-third" role="tabpanel" aria-labelledby="tab-third" hidden>Members panel</div><button type="button">After</button>`,+ },+ {+ id: 'violating-tab-semantically-detached',+ summary: 'a DOM child tab hidden from the accessibility tree',+ facts: baseFacts({+ tabRelations: ['first'],+ panelRelations: [],+ selectedTab: null,+ manualActivation: false,+ tabReachable: false,+ pointerSelection: false,+ }),+ html: `<div ${SUBJECT_ATTRIBUTE} role="tablist" aria-label="Project views"><button data-a11y-related="first" id="tab-first" role="tab" aria-selected="true" aria-hidden="true">Overview</button></div>`,+ },+ {+ id: 'violating-panel-role',+ summary: 'a tabpanel exposed as a region',+ facts: panelFacts(),+ html: groupHtml({subject: 'first-panel', panelRole: 'region'}),+ },+ {+ id: 'violating-panel-labelledby-missing',+ summary: 'a tabpanel with no reverse label relationship',+ facts: panelFacts(),+ html: groupHtml({subject: 'first-panel', panelLabel: 'missing'}),+ },+ {+ id: 'violating-panel-labelledby-dangling',+ summary: 'a tabpanel whose label target does not exist',+ facts: panelFacts(),+ html: groupHtml({subject: 'first-panel', panelLabel: 'dangling'}),+ },+ {+ id: 'violating-panel-labelledby-wrong-existing',+ summary: 'a tabpanel labelled by another tab',+ facts: panelFacts(),+ html: groupHtml({subject: 'first-panel', panelLabel: 'wrong'}),+ },+ {+ id: 'violating-panel-labelledby-duplicate-id',+ summary: 'aria-labelledby resolves to a duplicate instead of the bound tab',+ facts: panelFacts(),+ html: groupHtml({subject: 'first-panel', duplicateTabId: true}),+ },+ {+ id: 'violating-panel-name',+ summary: 'a tabpanel whose referenced tab has no name',+ facts: panelFacts(),+ html: groupHtml({subject: 'first-panel', panelLabel: 'empty'}),+ },+ {+ id: 'violating-panel-active-hidden',+ summary: 'an active tabpanel hidden by rendered CSS',+ facts: panelFacts(),+ html: groupHtml({subject: 'first-panel', firstPanelCssHidden: true}),+ },+ {+ id: 'violating-panel-active-transparent',+ summary: 'an active tabpanel rendered fully transparent',+ facts: panelFacts(),+ html: groupHtml({subject: 'first-panel', firstPanelTransparent: true}),+ },+ {+ id: 'violating-panel-inactive-visible',+ summary: 'an inactive tabpanel that remains visible',+ facts: panelFacts({active: false, labellingTab: 'second'}),+ html: groupHtml({subject: 'second-panel', secondPanelHidden: false}),+ },+ {+ id: 'violating-selection-active-css-hidden',+ summary: 'the selected panel is hidden by CSS during selection',+ facts: baseFacts(),+ html: groupHtml({firstPanelCssHidden: true}),+ },+ {+ id: 'violating-selection-active-transparent',+ summary: 'the selected panel is fully transparent during selection',+ facts: baseFacts(),+ html: groupHtml({firstPanelTransparent: true}),+ },+ {+ id: 'violating-selection-inactive-css-visible',+ summary: 'an unselected panel overrides hidden and remains visible',+ facts: baseFacts(),+ html: groupHtml({secondPanelCssVisible: true}),+ },+ {+ id: 'violating-selection-two',+ summary: 'a tablist exposing two selected tabs',+ facts: baseFacts(),+ html: groupHtml({secondSelected: true}),+ },+ {+ id: 'violating-entry-wrong',+ summary: 'a tablist entered at an unselected tab',+ facts: baseFacts(),+ html: groupHtml({wrongEntry: true}),+ },+ {+ id: 'violating-tab-trap',+ summary: 'a tablist that traps Tab',+ facts: baseFacts(),+ html: groupHtml({trapTab: true}),+ },+ {+ id: 'violating-arrow-inert',+ summary: 'a tablist whose arrows move no focus',+ facts: baseFacts(),+ html: groupHtml({arrow: 'inert'}),+ },+ {+ id: 'violating-arrow-one-way',+ summary: 'a tablist that moves forward but not back',+ facts: baseFacts(),+ html: groupHtml({arrow: 'one-way'}),+ },+ {+ id: 'violating-arrow-no-wrap',+ summary: 'a tablist whose arrows stop at the ends instead of wrapping',+ facts: baseFacts(),+ html: groupHtml({arrow: 'no-wrap'}),+ },+ {+ id: 'violating-rtl-arrow-no-wrap',+ summary: 'an RTL tablist whose arrows stop at the ends instead of wrapping',+ facts: baseFacts({direction: 'rtl'}),+ html: groupHtml({direction: 'rtl', arrow: 'no-wrap'}),+ },+ {+ id: 'violating-rtl-physical-arrows',+ summary: 'an RTL tablist that keeps LTR physical arrow direction',+ facts: baseFacts({direction: 'rtl'}),+ html: groupHtml({direction: 'rtl', arrow: 'physical-ltr'}),+ },+ {+ id: 'violating-arrow-does-not-skip',+ summary: 'a tablist whose arrow stalls on a disabled tab',+ facts: baseFacts({disabledTabs: ['second']}),+ html: groupHtml({secondDisabled: true, arrow: 'does-not-skip'}),+ },+ {+ id: 'violating-arrow-changes-selection',+ summary: 'manual arrow focus also changes selection',+ facts: baseFacts(),+ html: groupHtml({arrow: 'changes-selection'}),+ },+ {+ id: 'violating-keyboard-inert',+ summary: 'a manual tablist whose focused tab ignores Enter',+ facts: baseFacts(),+ html: groupHtml({keyboard: 'inert'}),+ },+ {+ id: 'violating-keyboard-one-way',+ summary: 'activation selects an alternate but cannot restore the original',+ facts: baseFacts(),+ html: groupHtml({keyboard: 'one-way'}),+ },+ {+ id: 'violating-pointer-inert',+ summary: 'an alternate tab ignores pointer activation',+ facts: baseFacts(),+ html: groupHtml({pointer: 'inert'}),+ },+ {+ id: 'violating-pointer-one-way',+ summary: 'a pointer selects an alternate but cannot restore the original',+ facts: baseFacts(),+ html: groupHtml({pointer: 'one-way'}),+ },+ {+ id: 'violating-pointer-down',+ summary: 'a tab selects on pointer down before release',+ facts: tabFacts({selected: false}),+ html: groupHtml({subject: 'second-tab', pointer: 'down'}),+ },+];++export const CONFORMING_TABS_FIXTURES = TABS_FIXTURES.filter(fixture =>+ fixture.id.startsWith('conforming-'),+).map(fixture => fixture.id);++export const TABS_MUTATIONS: Readonly<Record<string, readonly string[]>> = {+ 'tabs.tablist.role-exposed': ['violating-tablist-role'],+ 'tabs.tablist.name-exposed': ['violating-tablist-name'],+ 'tabs.tab.role-exposed': ['violating-tab-role'],+ 'tabs.tab.name-exposed': ['violating-tab-name'],+ 'tabs.tab.name-matches-visible-label': ['violating-tab-name-mismatch'],+ 'tabs.tab.selected-state-exposed': ['violating-tab-selected'],+ 'tabs.tab.availability-exposed': ['violating-tab-disabled'],+ 'tabs.tab.unavailable-pointer-inert': ['violating-unavailable-operable'],+ 'tabs.tab.unavailable-enter-inert': ['violating-unavailable-operable'],+ 'tabs.tab.unavailable-space-inert': ['violating-unavailable-operable'],+ 'tabs.relationship.controls-resolves': [+ 'violating-controls-missing',+ 'violating-controls-dangling',+ 'violating-controls-wrong-existing',+ 'violating-controls-duplicate-id',+ ],+ 'tabs.tablist.contains-tabs': [+ 'violating-tab-outside-tablist',+ 'violating-tab-semantically-detached',+ ],+ 'tabs.tabpanel.role-exposed': ['violating-panel-role'],+ 'tabs.relationship.panel-labelledby-resolves': [+ 'violating-panel-labelledby-missing',+ 'violating-panel-labelledby-dangling',+ 'violating-panel-labelledby-wrong-existing',+ 'violating-panel-labelledby-duplicate-id',+ ],+ 'tabs.tabpanel.name-exposed': ['violating-panel-name'],+ 'tabs.tabpanel.active-state-matches': [+ 'violating-panel-active-hidden',+ 'violating-panel-active-transparent',+ 'violating-panel-inactive-visible',+ ],+ 'tabs.selection.exposed': [+ 'violating-selection-two',+ 'violating-selection-active-css-hidden',+ 'violating-selection-active-transparent',+ 'violating-selection-inactive-css-visible',+ ],+ 'tabs.focus.entry-and-exit': ['violating-entry-wrong', 'violating-tab-trap'],+ 'tabs.focus.arrow-round-trip': [+ 'violating-arrow-inert',+ 'violating-arrow-one-way',+ ],+ 'tabs.focus.wraps-ends': [+ 'violating-arrow-no-wrap',+ 'violating-rtl-arrow-no-wrap',+ ],+ 'tabs.focus.rtl-arrow-round-trip': ['violating-rtl-physical-arrows'],+ 'tabs.focus.skips-unavailable': ['violating-arrow-does-not-skip'],+ 'tabs.selection.manual-arrows-preserve-state': [+ 'violating-arrow-changes-selection',+ ],+ 'tabs.selection.enter-round-trip': [+ 'violating-keyboard-inert',+ 'violating-keyboard-one-way',+ ],+ 'tabs.selection.space-round-trip': [+ 'violating-keyboard-inert',+ 'violating-keyboard-one-way',+ ],+ 'tabs.selection.pointer-round-trip': [+ 'violating-pointer-inert',+ 'violating-pointer-one-way',+ ],+ 'tabs.tab.survives-aborted-press': ['violating-pointer-down'],+};++const EXPECTED_MUTATION_FAILURES: Readonly<Record<string, string>> = {+ 'tabs.tablist.role-exposed:violating-tablist-role':+ 'the browser reports this container as "toolbar", not as a tablist',+ 'tabs.tablist.name-exposed:violating-tablist-name':+ 'the browser computes no accessible name for this tablist',+ 'tabs.tab.role-exposed:violating-tab-role':+ 'the browser reports this item as "button", not as a tab',+ 'tabs.tab.name-exposed:violating-tab-name':+ 'the browser computes no accessible name for this tab',+ 'tabs.tab.name-matches-visible-label:violating-tab-name-mismatch':+ 'the visible label reads "Overview" but the browser computes the accessible name as "Activity"',+ 'tabs.tab.selected-state-exposed:violating-tab-selected':+ 'the binding declares this tab selected, but the browser reports it unselected',+ 'tabs.tab.availability-exposed:violating-tab-disabled':+ 'the binding declares this tab unavailable, but the browser reports it available',+ 'tabs.tab.unavailable-pointer-inert:violating-unavailable-operable':+ 'the tab is reported unavailable, but clicking it selected it',+ 'tabs.tab.unavailable-enter-inert:violating-unavailable-operable':+ 'the tab is reported unavailable, but Enter selected it',+ 'tabs.tab.unavailable-space-inert:violating-unavailable-operable':+ 'the tab is reported unavailable, but Space selected it',+ 'tabs.relationship.controls-resolves:violating-controls-missing':+ 'this tab declares a controlled panel, but it has no aria-controls relationship',+ 'tabs.relationship.controls-resolves:violating-controls-dangling':+ 'aria-controls points at "missing-panel", which resolves to nothing',+ 'tabs.relationship.controls-resolves:violating-controls-wrong-existing':+ 'aria-controls identifies "panel-second" instead of the binding’s associated panel "panel-first"',+ 'tabs.relationship.controls-resolves:violating-controls-duplicate-id':+ 'aria-controls resolves to a different element than the binding’s associated panel "panel-first"',+ 'tabs.tablist.contains-tabs:violating-tab-outside-tablist':+ 'the binding’s "first" tab is not contained by the tablist',+ 'tabs.tablist.contains-tabs:violating-tab-semantically-detached':+ 'the binding’s "first" tab is not contained by the tablist',+ 'tabs.tabpanel.role-exposed:violating-panel-role':+ 'the browser reports this panel as "region", not as a tabpanel',+ 'tabs.relationship.panel-labelledby-resolves:violating-panel-labelledby-missing':+ 'this tabpanel declares a tab label, but it has no aria-labelledby relationship',+ 'tabs.relationship.panel-labelledby-resolves:violating-panel-labelledby-dangling':+ 'aria-labelledby points at "missing-tab", which resolves to nothing',+ 'tabs.relationship.panel-labelledby-resolves:violating-panel-labelledby-wrong-existing':+ 'aria-labelledby identifies "tab-second" instead of the binding’s associated tab "tab-first"',+ 'tabs.relationship.panel-labelledby-resolves:violating-panel-labelledby-duplicate-id':+ 'aria-labelledby resolves to a different element than the binding’s associated tab "tab-first"',+ 'tabs.tabpanel.name-exposed:violating-panel-name':+ 'the browser computes no accessible name for this tabpanel',+ 'tabs.tabpanel.active-state-matches:violating-panel-active-hidden':+ 'the binding declares this tabpanel active, but the browser reports it hidden',+ 'tabs.tabpanel.active-state-matches:violating-panel-active-transparent':+ 'the binding declares this tabpanel active, but the browser reports it hidden',+ 'tabs.tabpanel.active-state-matches:violating-panel-inactive-visible':+ 'the binding declares this tabpanel inactive, but the browser reports it visible',+ 'tabs.selection.exposed:violating-selection-two':+ 'expected exactly "first" selected, but the browser exposes "first", "second"',+ 'tabs.selection.exposed:violating-selection-active-css-hidden':+ 'the "panel-first" panel is hidden while "first" is selected',+ 'tabs.selection.exposed:violating-selection-active-transparent':+ 'the "panel-first" panel is hidden while "first" is selected',+ 'tabs.selection.exposed:violating-selection-inactive-css-visible':+ 'the "panel-second" panel is visible while "second" is unselected',+ 'tabs.focus.entry-and-exit:violating-entry-wrong':+ 'Tab entered the tablist somewhere other than its selected tab "first"',+ 'tabs.focus.entry-and-exit:violating-tab-trap':+ 'Tab did not leave the tablist',+ 'tabs.focus.arrow-round-trip:violating-arrow-inert':+ 'pressing ArrowRight from "first" did not focus the next available tab "second"',+ 'tabs.focus.arrow-round-trip:violating-arrow-one-way':+ 'pressing ArrowRight moved to "second", but pressing ArrowLeft did not restore focus to "first"',+ 'tabs.focus.wraps-ends:violating-arrow-no-wrap':+ 'neither ArrowLeft nor ArrowRight wrapped focus from the first tab "first" to the last tab "third"',+ 'tabs.focus.wraps-ends:violating-rtl-arrow-no-wrap':+ 'neither ArrowLeft nor ArrowRight wrapped focus from the first tab "first" to the last tab "third"',+ 'tabs.focus.rtl-arrow-round-trip:violating-rtl-physical-arrows':+ 'pressing ArrowLeft from "first" did not focus the next available tab "second"',+ 'tabs.focus.skips-unavailable:violating-arrow-does-not-skip':+ 'pressing ArrowRight from "first" did not focus the next available tab "third"',+ 'tabs.selection.manual-arrows-preserve-state:violating-arrow-changes-selection':+ 'expected exactly "first" selected, but the browser exposes "second"',+ 'tabs.selection.enter-round-trip:violating-keyboard-inert':+ 'expected exactly "second" selected, but the browser exposes "first"',+ 'tabs.selection.enter-round-trip:violating-keyboard-one-way':+ 'expected exactly "first" selected, but the browser exposes "second"',+ 'tabs.selection.space-round-trip:violating-keyboard-inert':+ 'expected exactly "second" selected, but the browser exposes "first"',+ 'tabs.selection.space-round-trip:violating-keyboard-one-way':+ 'expected exactly "first" selected, but the browser exposes "second"',+ 'tabs.selection.pointer-round-trip:violating-pointer-inert':+ 'expected exactly "second" selected, but the browser exposes "first"',+ 'tabs.selection.pointer-round-trip:violating-pointer-one-way':+ 'expected exactly "first" selected, but the browser exposes "second"',+ 'tabs.tab.survives-aborted-press:violating-pointer-down':+ 'pressing the tab and releasing away from it still changed the selected state',+};++export function expectedTabsMutationFailure(+ expectation: string,+ fixture: string,+): string {+ const failure = EXPECTED_MUTATION_FAILURES[`${expectation}:${fixture}`];+ if (failure == null) {+ throw new Error(+ `no expected Tabs mutation failure for ${expectation}:${fixture}`,+ );+ }+ return failure;+}++export function tabsFixture(id: string): TabsFixture {+ const fixture = TABS_FIXTURES.find(candidate => candidate.id === id);+ if (fixture == null) {+ throw new Error(`unknown Tabs fixture "${id}"`);+ }+ return fixture;+}diff --git a/internal/a11y-spec/src/patterns/tabs.jsdom.test.ts b/internal/a11y-spec/src/patterns/tabs.jsdom.test.tsnew file mode 100644index 0000000000..0b89887c28--- /dev/null+++ b/internal/a11y-spec/src/patterns/tabs.jsdom.test.ts@@ -0,0 +1,188 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file tabs.jsdom.test.ts+ * @input Uses the Tabs contract, plain fixtures, jsdom harness, and checker+ * @output DOM-layer positive/negative proof and honest unrun results+ * @position Contract self-test; proves the contract rather than Astryx components.+ */++import {afterEach, describe, expect, it} from 'vitest';+import {checkAccessibilitySpec, type ExpectationResult} from '../check';+import {+ citeSource,+ describeExpectation,+ requiredLayers,+ unansweredDimensions,+} from '../contract';+import {createJsdomHarness, JSDOM_OBSERVES} from '../harness/jsdom';+import {TABS_PATTERN} from './tabs';+import {+ CONFORMING_TABS_FIXTURES,+ TABS_MUTATIONS,+ TABS_SUBJECT_SELECTOR,+ tabsFixture,+ type TabsFixture,+} from './tabs.fixtures';++const observableHere = TABS_PATTERN.expectations.filter(expectation =>+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),+);++const EXPECTED_DOM_FAILURES: Readonly<Record<string, string>> = {+ 'tabs.relationship.controls-resolves:violating-controls-missing':+ 'this tab declares a controlled panel, but it has no aria-controls relationship',+ 'tabs.relationship.controls-resolves:violating-controls-dangling':+ 'aria-controls points at "missing-panel", which resolves to nothing',+ 'tabs.relationship.controls-resolves:violating-controls-wrong-existing':+ 'aria-controls identifies "panel-second" instead of the binding’s associated panel "panel-first"',+ 'tabs.relationship.controls-resolves:violating-controls-duplicate-id':+ 'aria-controls resolves to a different element than the binding’s associated panel "panel-first"',+ 'tabs.relationship.panel-labelledby-resolves:violating-panel-labelledby-missing':+ 'this tabpanel declares a tab label, but it has no aria-labelledby relationship',+ 'tabs.relationship.panel-labelledby-resolves:violating-panel-labelledby-dangling':+ 'aria-labelledby points at "missing-tab", which resolves to nothing',+ 'tabs.relationship.panel-labelledby-resolves:violating-panel-labelledby-wrong-existing':+ 'aria-labelledby identifies "tab-second" instead of the binding’s associated tab "tab-first"',+ 'tabs.relationship.panel-labelledby-resolves:violating-panel-labelledby-duplicate-id':+ 'aria-labelledby resolves to a different element than the binding’s associated tab "tab-first"',+};++afterEach(() => {+ document.body.replaceChildren();+});++async function resultsFor(target: TabsFixture) {+ const container = document.createElement('div');+ document.body.append(container);+ const result = await checkAccessibilitySpec({+ spec: TABS_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ mount: async () => {+ container.innerHTML = target.html;+ const subject = container.querySelector(TABS_SUBJECT_SELECTOR);+ if (subject == null) {+ throw new Error(`fixture "${target.id}" marks no subject element`);+ }+ const relationNames = [+ ...target.facts.tabRelations,+ ...target.facts.panelRelations,+ target.facts.controlledPanel,+ target.facts.labellingTab,+ ].filter((name): name is string => name != null);+ const related = Object.fromEntries(+ relationNames.map(name => {+ const element = container.querySelector(+ `[data-a11y-related="${name}"]`,+ );+ if (element == null) {+ throw new Error(+ `fixture "${target.id}" marks no related subject "${name}"`,+ );+ }+ return [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('Tabs contract — completeness', () => {+ it('answers every checklist dimension', () => {+ expect(unansweredDimensions(TABS_PATTERN)).toEqual([]);+ });++ it('gives every expectation a deliberately violating fixture', () => {+ expect(+ TABS_PATTERN.expectations+ .filter(+ expectation => (TABS_MUTATIONS[expectation.id] ?? []).length === 0,+ )+ .map(expectation => expectation.id),+ ).toEqual([]);+ });++ it('has an expectation for every mutation entry', () => {+ const ids = new Set(+ TABS_PATTERN.expectations.map(expectation => expectation.id),+ );+ expect(Object.keys(TABS_MUTATIONS).filter(id => !ids.has(id))).toEqual([]);+ });++ it('names every fixture recorded as a mutation', () => {+ for (const fixtures of Object.values(TABS_MUTATIONS)) {+ for (const id of fixtures) {+ expect(() => tabsFixture(id)).not.toThrow();+ }+ }+ });+});++describe('Tabs contract — jsdom evidence boundary', () => {+ it('runs DOM expectations and reports higher layers as unrun', async () => {+ const results = await resultsFor(tabsFixture('conforming-tab-selected'));+ expect(results.some(result => result.status === 'unrun')).toBe(true);+ expect(results.filter(result => result.status === 'fail')).toEqual([]);+ });+});++describe.each(observableHere.map(expectation => [expectation.id] as const))(+ '%s',+ id => {+ const expectation = TABS_PATTERN.expectations.find(+ candidate => candidate.id === id,+ )!;++ it.each(CONFORMING_TABS_FIXTURES.map(name => [name] as const))(+ 'passes against %s (or does not apply)',+ async name => {+ const result = resultFor(await resultsFor(tabsFixture(name)), id);+ expect(+ ['pass', 'not-applicable'],+ `${id} against ${name}: ${result.detail ?? ''}`,+ ).toContain(result.status);+ },+ );++ it.each((TABS_MUTATIONS[id] ?? []).map(name => [name] as const))(+ 'fails against %s, which removes its outcome',+ async name => {+ const result = resultFor(await resultsFor(tabsFixture(name)), id);+ expect(result.status, `${id} against ${name}`).toBe('fail');+ expect(result.detail ?? '').toBe(+ EXPECTED_DOM_FAILURES[`${id}:${name}`],+ );+ },+ );++ it('carries its id and primary source into failure output', async () => {+ const [fixtureId] = TABS_MUTATIONS[id] ?? [];+ if (fixtureId == null) {+ throw new Error(`no mutation fixture for ${id}`);+ }+ const result = resultFor(await resultsFor(tabsFixture(fixtureId)), id);+ expect(result.description).toContain(id);+ expect(result.description).toContain(citeSource(expectation.sources[0]));+ expect(result.description).toBe(describeExpectation(expectation));+ });+ },+);diff --git a/internal/a11y-spec/src/patterns/tabs.ts b/internal/a11y-spec/src/patterns/tabs.tsnew file mode 100644index 0000000000..b3580c0ad8--- /dev/null+++ b/internal/a11y-spec/src/patterns/tabs.ts@@ -0,0 +1,1285 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file tabs.ts+ * @input Uses the accessibility contract vocabulary+ * @output TABS_PATTERN and TabsStateFacts+ * @position Reusable accessibility contract for explicit horizontal ARIA Tabs compositions.+ *+ * This contract covers only a caller-selected `role="tablist"` composition.+ * Navigation-mode TabList, TabMenu, vertical tabs, automatic activation, and+ * invalid-value policy are separate owners or unresolved decisions.+ */++import {+ definePattern,+ type ApgRequirement,+ type PatternContract,+ type WcagCriterion,+ type WebStandardRequirement,+} from '../contract';+import type {Key} from '../harness';+import {saysInOrder, spokenWords} from '../spoken';++const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';+const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/tabs/';++function wcag(+ id: string,+ name: string,+ level: 'A' | 'AA',+ slug: string,+): WcagCriterion {+ return {+ standard: 'wcag',+ id,+ name,+ level,+ url: `${UNDERSTANDING}/${slug}.html`,+ };+}++const WCAG_1_3_1 = wcag(+ '1.3.1',+ 'Info and Relationships',+ 'A',+ 'info-and-relationships',+);+const WCAG_2_1_1 = wcag('2.1.1', 'Keyboard', 'A', 'keyboard');+const WCAG_2_1_2 = wcag('2.1.2', 'No Keyboard Trap', 'A', 'no-keyboard-trap');+const WCAG_2_4_3 = wcag('2.4.3', 'Focus Order', 'A', 'focus-order');+const WCAG_2_5_2 = wcag(+ '2.5.2',+ 'Pointer Cancellation',+ 'A',+ 'pointer-cancellation',+);+const WCAG_2_5_3 = wcag('2.5.3', 'Label in Name', 'A', 'label-in-name');+const WCAG_2_4_6 = wcag(+ '2.4.6',+ 'Headings and Labels',+ 'AA',+ 'headings-and-labels',+);+const WCAG_4_1_2 = wcag('4.1.2', 'Name, Role, Value', 'A', 'name-role-value');++function apg(requirement: string, fragment: string): ApgRequirement {+ return {+ standard: 'apg',+ pattern: 'tabs',+ requirement,+ url: `${APG_URL}${fragment}`,+ };+}++const APG_TABLIST_ROLE = apg(+ 'An element with role tablist serves as the container for the set of tabs.',+ '#wai-ariaroles,states,andproperties',+);+const APG_TAB_ROLE = apg(+ 'Each element that serves as a tab has role tab and is contained in the element with role tablist.',+ '#wai-ariaroles,states,andproperties',+);+const APG_TABPANEL_ROLE = apg(+ 'Each element that contains the content panel for a tab has role tabpanel.',+ '#wai-ariaroles,states,andproperties',+);+const APG_SELECTED = apg(+ 'The active tab element has aria-selected set to true and all other tab elements have it set to false.',+ '#wai-ariaroles,states,andproperties',+);+const APG_CONTROLS = apg(+ 'Each tab element has aria-controls referring to its associated tabpanel element.',+ '#wai-ariaroles,states,andproperties',+);+const APG_LABELLEDBY = apg(+ 'Each tabpanel has aria-labelledby referring to its associated tab element.',+ '#wai-ariaroles,states,andproperties',+);+const APG_TAB_ENTRY = apg(+ 'When focus moves into the tab list, places focus on the active tab element.',+ '#keyboardinteraction',+);+const APG_ARROWS = apg(+ 'Left Arrow moves focus to the previous tab and Right Arrow moves focus to the next tab, with wrapping at the ends.',+ '#keyboardinteraction',+);+const APG_MANUAL_ACTIVATION = apg(+ 'For a tab list with manual activation, Space or Enter activates the focused tab.',+ '#keyboardinteraction',+);+const APG_PANEL_VISIBILITY = apg(+ 'When a tabbed interface is initialized, one tab panel is displayed and its associated tab is styled to indicate that it is active.',+ '',+);+const ARIA_DISABLED: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2',+ requirement:+ 'The aria-disabled state indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.',+ url: 'https://www.w3.org/TR/wai-aria-1.2/#aria-disabled',+};++export interface TabsStateFacts {+ readonly part: 'tablist' | 'tab' | 'tabpanel';+ readonly selected: boolean | null;+ readonly active: boolean | null;+ readonly disabled: boolean | null;+ readonly focusable: boolean | null;+ readonly visibleLabel: boolean;+ readonly controlsPanel: boolean;+ readonly controlledPanel: string | null;+ readonly labelledByTab: boolean;+ readonly labellingTab: string | null;+ readonly tabRelations: readonly string[];+ readonly panelRelations: readonly string[];+ readonly disabledTabs: readonly string[];+ readonly selectedTab: string | null;+ readonly direction: 'ltr' | 'rtl';+ readonly manualActivation: boolean;+ readonly tabReachable: boolean;+ readonly pointerSelection: boolean;+ readonly pointerCancellation: boolean;+}++function arrowKeys(+ direction: TabsStateFacts['direction'],+): readonly [Key, Key] {+ return direction === 'rtl'+ ? ['ArrowLeft', 'ArrowRight']+ : ['ArrowRight', 'ArrowLeft'];+}++async function selectedRelations(+ harness: Parameters<+ PatternContract<TabsStateFacts>['expectations'][number]['run']+ >[0]['harness'],+ relations: readonly string[],+): Promise<string[]> {+ const selected: string[] = [];+ for (const relation of relations) {+ if (+ (await (await harness.related(relation)).computed()).selected === true+ ) {+ selected.push(relation);+ }+ }+ return selected;+}++async function assertSelection(+ harness: Parameters<+ PatternContract<TabsStateFacts>['expectations'][number]['run']+ >[0]['harness'],+ facts: TabsStateFacts,+ expected: string,+): Promise<void> {+ const selected = await selectedRelations(harness, facts.tabRelations);+ if (selected.length !== 1 || selected[0] !== expected) {+ throw new Error(+ `expected exactly "${expected}" selected, but the browser exposes ${selected.length === 0 ? 'no selected tab' : selected.map(name => `"${name}"`).join(', ')}`,+ );+ }+ for (let index = 0; index < facts.panelRelations.length; index += 1) {+ const panelName = facts.panelRelations[index];+ const tabName = facts.tabRelations[index];+ if (panelName == null || tabName == null) {+ throw new Error(+ 'the binding supplies mismatched tab and panel relations',+ );+ }+ const panel = await harness.related(panelName);+ const visible = await panel.isVisible();+ if (visible !== (tabName === expected)) {+ throw new Error(+ `the "${panelName}" panel is ${visible ? 'visible' : 'hidden'} while "${tabName}" is ${tabName === expected ? 'selected' : 'unselected'}`,+ );+ }+ }+}++async function assertArrowRoundTrip(+ harness: Parameters<+ PatternContract<TabsStateFacts>['expectations'][number]['run']+ >[0]['harness'],+ facts: TabsStateFacts,+ skipUnavailable: boolean,+): Promise<void> {+ const originalName = facts.selectedTab;+ if (originalName == null) {+ throw new Error('arrow expectation ran without an active tab');+ }+ const originalIndex = facts.tabRelations.indexOf(originalName);+ let nextName: string | undefined;+ for (let offset = 1; offset <= facts.tabRelations.length; offset += 1) {+ const candidate =+ facts.tabRelations[(originalIndex + offset) % facts.tabRelations.length];+ if (+ candidate != null &&+ (!skipUnavailable || !facts.disabledTabs.includes(candidate))+ ) {+ nextName = candidate;+ break;+ }+ }+ if (nextName == null) {+ throw new Error('arrow expectation found no available alternate tab');+ }+ const [forward, backward] = arrowKeys(facts.direction);+ const original = await harness.related(originalName);+ const next = await harness.related(nextName);+ await original.focus();+ await harness.press(forward);+ if (!(await next.isFocused())) {+ throw new Error(+ `pressing ${forward} from "${originalName}" did not focus the next available tab "${nextName}"`,+ );+ }+ await harness.press(backward);+ if (!(await original.isFocused())) {+ throw new Error(+ `pressing ${forward} moved to "${nextName}", but pressing ${backward} did not restore focus to "${originalName}"`,+ );+ }+}++async function assertEndWrap(+ harness: Parameters<+ PatternContract<TabsStateFacts>['expectations'][number]['run']+ >[0]['harness'],+ facts: TabsStateFacts,+): Promise<void> {+ const firstName = facts.tabRelations[0];+ const lastName = facts.tabRelations.at(-1);+ if (firstName == null || lastName == null || firstName === lastName) {+ throw new Error('wrap expectation needs distinct first and last tabs');+ }+ const first = await harness.related(firstName);+ const last = await harness.related(lastName);+ const attempts: ReadonlyArray<readonly [Key, Key]> = [+ ['ArrowLeft', 'ArrowRight'],+ ['ArrowRight', 'ArrowLeft'],+ ];+ for (const [outbound, inbound] of attempts) {+ await first.focus();+ await harness.press(outbound);+ if (!(await last.isFocused())) {+ continue;+ }+ await harness.press(inbound);+ if (!(await first.isFocused())) {+ throw new Error(+ `pressing ${outbound} wrapped to "${lastName}", but pressing ${inbound} did not restore focus to "${firstName}"`,+ );+ }+ return;+ }+ throw new Error(+ `neither ArrowLeft nor ArrowRight wrapped focus from the first tab "${firstName}" to the last tab "${lastName}"`,+ );+}++async function assertSelectionKeyRoundTrip(+ harness: Parameters<+ PatternContract<TabsStateFacts>['expectations'][number]['run']+ >[0]['harness'],+ facts: TabsStateFacts,+ key: 'Enter' | 'Space',+): Promise<void> {+ const originalName = facts.selectedTab;+ if (originalName == null) {+ throw new Error(`${key} expectation ran without an active tab`);+ }+ const alternateName = facts.tabRelations.find(+ name => name !== originalName && !facts.disabledTabs.includes(name),+ );+ if (alternateName == null) {+ throw new Error(`${key} expectation found no available alternate tab`);+ }+ await (await harness.related(alternateName)).focus();+ await harness.press(key);+ await assertSelection(harness, facts, alternateName);+ await (await harness.related(originalName)).focus();+ await harness.press(key);+ await assertSelection(harness, facts, originalName);+}++export const TABS_PATTERN: PatternContract<TabsStateFacts> =+ definePattern<TabsStateFacts>({+ pattern: 'tabs',+ url: APG_URL,+ scope:+ 'An explicit horizontal tablist, its tabs, and caller-authored tabpanels expose their roles, selected state, relationships, and manual keyboard interaction.',+ expectations: [+ {+ id: 'tabs.tablist.role-exposed',+ outcome:+ 'The browser exposes the tablist role, so the tabs are presented as one related widget.',+ sources: [WCAG_1_3_1, WCAG_4_1_2, APG_TABLIST_ROLE],+ covers: ['1.3.1-info-and-relationships', '4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding designates the tablist container',+ test: facts => facts.part === 'tablist',+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {role} = await subject.computed();+ if (role !== 'tablist') {+ throw new Error(+ role == null+ ? 'the browser exposes no role for this tablist'+ : `the browser reports this container as "${role}", not as a tablist`,+ );+ }+ },+ },+ {+ id: 'tabs.tablist.name-exposed',+ outcome:+ 'The tablist has an accessible name, so the user knows what set of views it controls.',+ sources: [WCAG_2_4_6, WCAG_4_1_2],+ covers: ['2.4.6-headings-and-labels', '4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding designates the tablist container',+ test: facts => facts.part === 'tablist',+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ if ((await subject.computed()).name.trim() === '') {+ throw new Error(+ 'the browser computes no accessible name for this tablist',+ );+ }+ },+ },+ {+ id: 'tabs.tab.role-exposed',+ outcome:+ 'The browser exposes each tab as a tab, so the user knows it selects a panel rather than navigating away.',+ sources: [WCAG_1_3_1, WCAG_4_1_2, APG_TAB_ROLE],+ covers: ['1.3.1-info-and-relationships', '4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding designates one tab',+ test: facts => facts.part === 'tab',+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {role} = await subject.computed();+ if (role !== 'tab') {+ throw new Error(+ role == null+ ? 'the browser exposes no role for this tab'+ : `the browser reports this item as "${role}", not as a tab`,+ );+ }+ },+ },+ {+ id: 'tabs.tab.name-exposed',+ outcome:+ 'Each tab has an accessible name, so the user can identify the panel before selecting it.',+ sources: [WCAG_2_4_6, WCAG_4_1_2],+ covers: ['2.4.6-headings-and-labels', '4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding designates one tab',+ test: facts => facts.part === 'tab',+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ if ((await subject.computed()).name.trim() === '') {+ throw new Error(+ 'the browser computes no accessible name for this tab',+ );+ }+ },+ },+ {+ id: 'tabs.tab.name-matches-visible-label',+ outcome:+ 'The accessible name contains the visible label, so a speech-input user can say the tab they can read.',+ sources: [WCAG_2_5_3],+ covers: ['2.5.3-label-in-name'],+ appliesWhen: {+ condition: 'the binding designates one tab',+ test: facts => facts.part === 'tab',+ },+ evidenceLayer: 'accessibility-tree',+ alsoNeeds: ['real-browser'],+ enforcement: 'required',+ run: async ({subject, notApplicable}) => {+ const visible = await subject.visibleLabelText();+ if (visible == null) {+ return notApplicable(+ 'this tab renders no label a person can read, so there are no visible words for speech input',+ );+ }+ const {name} = await subject.computed();+ if (!saysInOrder(spokenWords(name), spokenWords(visible))) {+ throw new Error(+ `the visible label reads "${visible}" but the browser computes the accessible name as "${name}"`,+ );+ }+ },+ },+ {+ id: 'tabs.tab.selected-state-exposed',+ outcome:+ 'The browser exposes whether the tab is selected, and that state matches the binding.',+ sources: [WCAG_4_1_2, APG_SELECTED],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding designates one tab with a selected state',+ test: facts => facts.part === 'tab' && facts.selected != null,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const selected = (await subject.computed()).selected;+ if (selected !== facts.selected) {+ throw new Error(+ selected == null+ ? 'the browser exposes no selected state for this tab'+ : `the binding declares this tab ${facts.selected ? 'selected' : 'unselected'}, but the browser reports it ${selected ? 'selected' : 'unselected'}`,+ );+ }+ },+ },+ {+ id: 'tabs.tab.availability-exposed',+ outcome:+ 'The browser exposes whether a tab is available, without presenting an unavailable tab as actionable.',+ sources: [WCAG_4_1_2],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the binding designates one tab with an availability state',+ test: facts => facts.part === 'tab' && facts.disabled != null,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const disabled = (await subject.computed()).disabled;+ if (disabled !== facts.disabled) {+ throw new Error(+ `the binding declares this tab ${facts.disabled ? 'unavailable' : 'available'}, but the browser reports it ${disabled ? 'unavailable' : 'available'}`,+ );+ }+ },+ },+ {+ id: 'tabs.tab.unavailable-pointer-inert',+ outcome:+ 'A tab reported as unavailable does not select its panel when clicked.',+ sources: [WCAG_4_1_2, ARIA_DISABLED],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding designates a tab exposed as unavailable',+ test: facts =>+ facts.part === 'tab' &&+ facts.disabled === true &&+ facts.focusable === true,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['accessibility-tree'],+ enforcement: 'required',+ run: async ({harness, subject}) => {+ const before = (await subject.computed()).selected;+ await harness.click(subject, {ignoreAvailability: true});+ const after = (await subject.computed()).selected;+ if (after !== before) {+ throw new Error(+ 'the tab is reported unavailable, but clicking it selected it',+ );+ }+ },+ },+ {+ id: 'tabs.tab.unavailable-enter-inert',+ outcome:+ 'A focusable tab reported as unavailable does not select its panel from Enter.',+ sources: [WCAG_4_1_2, ARIA_DISABLED],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the binding designates a focusable tab exposed as unavailable',+ test: facts =>+ facts.part === 'tab' &&+ facts.disabled === true &&+ facts.focusable === true,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['accessibility-tree'],+ enforcement: 'required',+ run: async ({harness, subject}) => {+ const before = (await subject.computed()).selected;+ await subject.focus();+ if (!(await subject.isFocused())) {+ throw new Error(+ 'the binding declares this unavailable tab focusable, but the browser could not focus it',+ );+ }+ await harness.press('Enter');+ if ((await subject.computed()).selected !== before) {+ throw new Error(+ 'the tab is reported unavailable, but Enter selected it',+ );+ }+ },+ },+ {+ id: 'tabs.tab.unavailable-space-inert',+ outcome:+ 'A focusable tab reported as unavailable does not select its panel from Space.',+ sources: [WCAG_4_1_2, ARIA_DISABLED],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the binding designates a focusable tab exposed as unavailable',+ test: facts =>+ facts.part === 'tab' &&+ facts.disabled === true &&+ facts.focusable === true,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['accessibility-tree'],+ enforcement: 'required',+ run: async ({harness, subject}) => {+ const before = (await subject.computed()).selected;+ await subject.focus();+ if (!(await subject.isFocused())) {+ throw new Error(+ 'the binding declares this unavailable tab focusable, but the browser could not focus it',+ );+ }+ await harness.press('Space');+ if ((await subject.computed()).selected !== before) {+ throw new Error(+ 'the tab is reported unavailable, but Space selected it',+ );+ }+ },+ },+ {+ id: 'tabs.relationship.controls-resolves',+ outcome:+ 'A tab that declares a controlled panel points to an element that exists, so the relationship is not silently broken.',+ sources: [WCAG_1_3_1, APG_CONTROLS],+ covers: ['1.3.1-info-and-relationships'],+ appliesWhen: {+ condition: 'the binding designates a tab with a controlled panel',+ test: facts => facts.part === 'tab' && facts.controlsPanel,+ },+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ const attribute = await subject.attribute('aria-controls');+ const ids = (attribute ?? '').split(/\s+/).filter(Boolean);+ if (ids.length === 0) {+ throw new Error(+ 'this tab declares a controlled panel, but it has no aria-controls relationship',+ );+ }+ const targets = await subject.idReferences('aria-controls');+ const dangling = ids.filter((_, index) => targets[index] == null);+ if (dangling.length > 0) {+ throw new Error(+ `aria-controls points at ${dangling.map(id => `"${id}"`).join(', ')}, which ${dangling.length === 1 ? 'resolves' : 'resolve'} to nothing`,+ );+ }+ if (facts.controlledPanel == null) {+ throw new Error(+ 'the binding declares a controlled panel but names no panel relation',+ );+ }+ const expectedPanel = await harness.related(facts.controlledPanel);+ const expectedId = await expectedPanel.attribute('id');+ if (expectedId == null) {+ throw new Error(+ 'the binding’s associated panel has no id for aria-controls',+ );+ }+ if (+ !(await harness.references(subject, 'aria-controls', expectedPanel))+ ) {+ throw new Error(+ ids.includes(expectedId)+ ? `aria-controls resolves to a different element than the binding’s associated panel "${expectedId}"`+ : `aria-controls identifies ${ids.map(id => `"${id}"`).join(', ')} instead of the binding’s associated panel "${expectedId}"`,+ );+ }+ },+ },+ {+ id: 'tabs.tablist.contains-tabs',+ outcome:+ 'Every tab in the binding belongs to the tablist, so the widget does not expose an orphan tab as part of the set.',+ sources: [WCAG_1_3_1, APG_TAB_ROLE],+ covers: ['1.3.1-info-and-relationships'],+ appliesWhen: {+ condition: 'the binding designates a tablist and all of its tabs',+ test: facts =>+ facts.part === 'tablist' && facts.tabRelations.length > 0,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ for (const relation of facts.tabRelations) {+ if (+ !(await harness.containsSemantically(+ subject,+ await harness.related(relation),+ ))+ ) {+ throw new Error(+ `the binding’s "${relation}" tab is not contained by the tablist`,+ );+ }+ }+ },+ },+ {+ id: 'tabs.tabpanel.role-exposed',+ outcome:+ 'The browser exposes panel content as a tabpanel, so its relationship to the selected tab is available programmatically.',+ sources: [WCAG_1_3_1, WCAG_4_1_2, APG_TABPANEL_ROLE],+ covers: ['1.3.1-info-and-relationships', '4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding designates a tabpanel',+ test: facts => facts.part === 'tabpanel' && facts.active !== false,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {role} = await subject.computed();+ if (role !== 'tabpanel') {+ throw new Error(+ role == null+ ? 'the browser exposes no role for this tabpanel'+ : `the browser reports this panel as "${role}", not as a tabpanel`,+ );+ }+ },+ },+ {+ id: 'tabs.relationship.panel-labelledby-resolves',+ outcome:+ 'A tabpanel points back to the tab that labels it, so the panel has a stable programmatic identity.',+ sources: [WCAG_1_3_1, WCAG_4_1_2, APG_LABELLEDBY],+ covers: ['1.3.1-info-and-relationships', '4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding designates a tabpanel labelled by its tab',+ test: facts => facts.part === 'tabpanel' && facts.labelledByTab,+ },+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ const attribute = await subject.attribute('aria-labelledby');+ const ids = (attribute ?? '').split(/\s+/).filter(Boolean);+ if (ids.length === 0) {+ throw new Error(+ 'this tabpanel declares a tab label, but it has no aria-labelledby relationship',+ );+ }+ const targets = await subject.idReferences('aria-labelledby');+ const dangling = ids.filter((_, index) => targets[index] == null);+ if (dangling.length > 0) {+ throw new Error(+ `aria-labelledby points at ${dangling.map(id => `"${id}"`).join(', ')}, which ${dangling.length === 1 ? 'resolves' : 'resolve'} to nothing`,+ );+ }+ if (facts.labellingTab == null) {+ throw new Error(+ 'the binding declares a tab label but names no tab relation',+ );+ }+ const expectedTab = await harness.related(facts.labellingTab);+ const expectedId = await expectedTab.attribute('id');+ if (expectedId == null) {+ throw new Error(+ 'the binding’s associated tab has no id for aria-labelledby',+ );+ }+ if (+ !(await harness.references(subject, 'aria-labelledby', expectedTab))+ ) {+ throw new Error(+ ids.includes(expectedId)+ ? `aria-labelledby resolves to a different element than the binding’s associated tab "${expectedId}"`+ : `aria-labelledby identifies ${ids.map(id => `"${id}"`).join(', ')} instead of the binding’s associated tab "${expectedId}"`,+ );+ }+ },+ },+ {+ id: 'tabs.tabpanel.name-exposed',+ outcome:+ 'The browser exposes the tabpanel name derived from its tab, so the user can identify the active view.',+ sources: [WCAG_4_1_2, APG_LABELLEDBY],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the binding designates an active tabpanel labelled by its tab',+ test: facts =>+ facts.part === 'tabpanel' &&+ facts.active !== false &&+ facts.labelledByTab,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ if ((await subject.computed()).name.trim() === '') {+ throw new Error(+ 'the browser computes no accessible name for this tabpanel',+ );+ }+ },+ },+ {+ id: 'tabs.tabpanel.active-state-matches',+ outcome:+ 'The selected tab panel is visible and an unselected tab panel is hidden, so the rendered view matches the exposed selection.',+ sources: [WCAG_1_3_1, APG_PANEL_VISIBILITY],+ covers: ['1.3.1-info-and-relationships'],+ appliesWhen: {+ condition: 'the binding designates an active or inactive tabpanel',+ test: facts => facts.part === 'tabpanel' && facts.active != null,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const visible = await subject.isVisible();+ if (visible !== facts.active) {+ throw new Error(+ `the binding declares this tabpanel ${facts.active ? 'active' : 'inactive'}, but the browser reports it ${visible ? 'visible' : 'hidden'}`,+ );+ }+ },+ },+ {+ id: 'tabs.selection.exposed',+ outcome:+ 'Exactly the binding’s active tab is selected, and the corresponding panel is the one shown.',+ sources: [WCAG_1_3_1, WCAG_4_1_2, APG_SELECTED, APG_PANEL_VISIBILITY],+ covers: ['1.3.1-info-and-relationships', '4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the binding designates a valid tablist with one active tab',+ test: facts => facts.part === 'tablist' && facts.selectedTab != null,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['accessibility-tree', 'dom'],+ enforcement: 'required',+ run: async ({harness, facts}) => {+ if (facts.selectedTab == null) {+ throw new Error('selection expectation ran without an active tab');+ }+ await assertSelection(harness, facts, facts.selectedTab);+ },+ },+ {+ id: 'tabs.focus.entry-and-exit',+ outcome:+ 'Tab enters the tablist at its selected tab and Tab again leaves the widget.',+ sources: [WCAG_2_1_1, WCAG_2_1_2, WCAG_2_4_3, APG_TAB_ENTRY],+ covers: [+ '2.1.1-keyboard',+ '2.1.2-no-keyboard-trap',+ '2.4.3-focus-order',+ ],+ appliesWhen: {+ condition: 'the binding designates a tab-reachable valid tablist',+ test: facts =>+ facts.part === 'tablist' &&+ facts.tabReachable &&+ facts.selectedTab != null,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ await harness.resetFocus();+ for (+ let step = 0;+ step < 10 && !(await subject.containsFocus());+ step += 1+ ) {+ await harness.press('Tab');+ }+ if (!(await subject.containsFocus())) {+ throw new Error('10 presses of Tab never entered the tablist');+ }+ const selected = facts.selectedTab;+ if (+ selected == null ||+ !(await (await harness.related(selected)).isFocused())+ ) {+ throw new Error(+ `Tab entered the tablist somewhere other than its selected tab "${selected}"`,+ );+ }+ await harness.press('Tab');+ if (await subject.containsFocus()) {+ throw new Error('Tab did not leave the tablist');+ }+ },+ },+ {+ id: 'tabs.focus.arrow-round-trip',+ outcome:+ 'Right Arrow moves focus to the next tab and Left Arrow restores the previous tab in the adopted horizontal APG order.',+ sources: [WCAG_2_1_1, APG_ARROWS],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition:+ 'the binding designates an LTR horizontal tablist with no unavailable tabs',+ test: facts =>+ facts.part === 'tablist' &&+ facts.direction === 'ltr' &&+ facts.disabledTabs.length === 0 &&+ facts.tabRelations.length > 1,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, facts}) => {+ await assertArrowRoundTrip(harness, facts, false);+ },+ },+ {+ id: 'tabs.focus.wraps-ends',+ outcome:+ 'Arrow navigation wraps between the first and last tabs without imposing a direction-specific key policy.',+ sources: [WCAG_2_1_1, APG_ARROWS],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition:+ 'the binding designates a horizontal tablist with no unavailable tabs',+ test: facts =>+ facts.part === 'tablist' &&+ facts.disabledTabs.length === 0 &&+ facts.tabRelations.length > 1,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, facts}) => {+ await assertEndWrap(harness, facts);+ },+ },+ {+ id: 'tabs.focus.rtl-arrow-round-trip',+ outcome:+ 'This binding reverses horizontal arrow direction in RTL and returns focus without losing the logical order.',+ sources: [APG_ARROWS],+ wcagOutcome:+ 'Every tab remains keyboard reachable in the direction the component documents for right-to-left content.',+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition:+ 'the binding designates an RTL horizontal tablist with no unavailable tabs',+ test: facts =>+ facts.part === 'tablist' &&+ facts.direction === 'rtl' &&+ facts.disabledTabs.length === 0 &&+ facts.tabRelations.length > 1,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'advisory',+ advisoryBecause:+ 'The APG names previous and next but does not require reversing physical Left and Right in RTL, and no current Astryx Tabs record adopts that policy as a shared gate.',+ run: async ({harness, facts}) => {+ await assertArrowRoundTrip(harness, facts, false);+ },+ },+ {+ id: 'tabs.focus.skips-unavailable',+ outcome:+ 'This binding’s arrow movement skips an unavailable tab and reaches the next available tab.',+ sources: [APG_ARROWS],+ wcagOutcome:+ 'Available tabs remain keyboard reachable when the tab set also contains an unavailable item.',+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition:+ 'the binding designates a horizontal tablist with an unavailable tab and a distinct available destination',+ test: facts =>+ facts.part === 'tablist' &&+ facts.disabledTabs.length > 0 &&+ facts.selectedTab != null &&+ facts.tabRelations.some(+ name =>+ name !== facts.selectedTab &&+ !facts.disabledTabs.includes(name),+ ),+ },+ evidenceLayer: 'real-browser',+ enforcement: 'advisory',+ advisoryBecause:+ 'The APG Tabs pattern does not define disabled-tab navigation, and no current Astryx Tabs record adopts skipping as a shared gate.',+ run: async ({harness, facts}) => {+ await assertArrowRoundTrip(harness, facts, true);+ },+ },+ {+ id: 'tabs.selection.manual-arrows-preserve-state',+ outcome:+ 'In the binding’s manual-activation mode, arrowing away and back moves focus without changing the selected panel.',+ sources: [APG_MANUAL_ACTIVATION],+ wcagOutcome:+ 'Keyboard operation remains predictable and the programmatically exposed selection stays synchronized with the rendered panel.',+ covers: ['apg-interaction', '4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the binding designates a horizontal manual-activation tablist',+ test: facts =>+ facts.part === 'tablist' &&+ facts.manualActivation &&+ facts.selectedTab != null &&+ facts.tabRelations.some(+ name =>+ name !== facts.selectedTab &&+ !facts.disabledTabs.includes(name),+ ),+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['accessibility-tree', 'dom'],+ enforcement: 'advisory',+ advisoryBecause:+ 'The APG allows either manual or automatic activation, and no current Astryx component record chooses one as the shared Tabs gate. This records the binding’s shipped manual behavior without deciding that policy.',+ run: async ({harness, facts}) => {+ const originalName = facts.selectedTab;+ if (originalName == null) {+ throw new Error(+ 'manual-arrow expectation ran without an active tab',+ );+ }+ const originalIndex = facts.tabRelations.indexOf(originalName);+ const nextName = facts.tabRelations.find(+ (name, index) =>+ index !== originalIndex && !facts.disabledTabs.includes(name),+ );+ if (nextName == null) {+ throw new Error(+ 'manual-arrow expectation found no available alternate tab',+ );+ }+ const [forward, backward] = arrowKeys(facts.direction);+ await (await harness.related(originalName)).focus();+ await harness.press(forward);+ await assertSelection(harness, facts, originalName);+ await harness.press(backward);+ await assertSelection(harness, facts, originalName);+ },+ },+ {+ id: 'tabs.selection.enter-round-trip',+ outcome:+ 'In manual mode, Enter activates the focused alternate tab and restores the original tab and panel when pressed there.',+ sources: [WCAG_2_1_1, APG_MANUAL_ACTIVATION],+ covers: ['2.1.1-keyboard', 'apg-interaction', '4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the binding designates an operable manual-activation tablist',+ test: facts =>+ facts.part === 'tablist' &&+ facts.manualActivation &&+ facts.selectedTab != null &&+ facts.tabRelations.some(+ name =>+ name !== facts.selectedTab &&+ !facts.disabledTabs.includes(name),+ ),+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['accessibility-tree', 'dom'],+ enforcement: 'required',+ run: async ({harness, facts}) => {+ await assertSelectionKeyRoundTrip(harness, facts, 'Enter');+ },+ },+ {+ id: 'tabs.selection.space-round-trip',+ outcome:+ 'In manual mode, Space activates the focused alternate tab and restores the original tab and panel when pressed there.',+ sources: [WCAG_2_1_1, APG_MANUAL_ACTIVATION],+ covers: ['2.1.1-keyboard', 'apg-interaction', '4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the binding designates an operable manual-activation tablist',+ test: facts =>+ facts.part === 'tablist' &&+ facts.manualActivation &&+ facts.selectedTab != null &&+ facts.tabRelations.some(+ name =>+ name !== facts.selectedTab &&+ !facts.disabledTabs.includes(name),+ ),+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['accessibility-tree', 'dom'],+ enforcement: 'required',+ run: async ({harness, facts}) => {+ await assertSelectionKeyRoundTrip(harness, facts, 'Space');+ },+ },+ {+ id: 'tabs.selection.pointer-round-trip',+ outcome:+ 'A pointer selects an alternate tab and can restore the original tab and panel.',+ sources: [APG_SELECTED],+ wcagOutcome:+ 'The selected state exposed under WCAG 4.1.2 stays synchronized with the panel changed by pointer input.',+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding designates a pointer-operable valid tablist',+ test: facts =>+ facts.part === 'tablist' &&+ facts.pointerSelection &&+ facts.selectedTab != null &&+ facts.tabRelations.some(+ name =>+ name !== facts.selectedTab &&+ !facts.disabledTabs.includes(name),+ ),+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['accessibility-tree', 'dom'],+ enforcement: 'advisory',+ advisoryBecause:+ 'APG defines the selected-state invariant but does not independently make pointer activation a Tabs keyboard requirement, and no current Astryx Tabs record adopts pointer selection as a shared gate.',+ run: async ({harness, facts}) => {+ const originalName = facts.selectedTab;+ if (originalName == null) {+ throw new Error('pointer expectation ran without an active tab');+ }+ const alternateName = facts.tabRelations.find(+ name => name !== originalName && !facts.disabledTabs.includes(name),+ );+ if (alternateName == null) {+ throw new Error(+ 'pointer expectation found no available alternate tab',+ );+ }+ await harness.click(await harness.related(alternateName));+ await assertSelection(harness, facts, alternateName);+ await harness.click(await harness.related(originalName));+ await assertSelection(harness, facts, originalName);+ },+ },+ {+ id: 'tabs.tab.survives-aborted-press',+ outcome:+ 'A press released away from an available tab leaves its selected state unchanged.',+ sources: [WCAG_2_5_2],+ covers: ['2.5.2-pointer-cancellation'],+ appliesWhen: {+ condition: 'the binding designates an available pointer-operated tab',+ test: facts => facts.part === 'tab' && facts.pointerCancellation,+ },+ evidenceLayer: 'real-browser',+ alsoNeeds: ['accessibility-tree'],+ enforcement: 'required',+ run: async ({harness, subject}) => {+ const before = (await subject.computed()).selected;+ await harness.abortedPress(subject);+ const after = (await subject.computed()).selected;+ if (after !== before) {+ throw new Error(+ 'pressing the tab and releasing away from it still changed the selected state',+ );+ }+ },+ },+ ],+ exemptions: {+ '1.1.1-non-text-content': {+ owner: 'the binding component and caller content',+ verifiedBy: 'component icon tests and the repository axe audit',+ reason:+ 'The contract observes tab and panel semantics; each binding owns decorative or informative graphics inside those parts.',+ },+ '1.3.1-info-and-relationships': {+ owner: 'the binding component and composing page',+ verifiedBy:+ 'component DOM tests for surrounding structure and page-level review beyond the bound tab and panel relations',+ reason:+ 'This contract covers tablist, tab, and tabpanel roles plus their direct authored relationships; surrounding page structure stays with its composition owner.',+ coversRemainderOnly: true,+ },+ '1.3.2-meaningful-sequence': {+ owner: 'the composing page',+ verifiedBy: 'page-level DOM-order review',+ reason:+ 'The reading sequence around the tabbed interface depends on the page that composes it.',+ },+ '1.3.5-identify-input-purpose': {+ owner: 'the composing form and caller content',+ verifiedBy: 'form integration review',+ reason:+ 'Tabs select views and do not collect personal data identified by autocomplete tokens.',+ },+ '1.4.1-use-of-color': {+ owner: 'the binding component and theme',+ verifiedBy: 'the repository visual gate and component review',+ reason:+ 'Whether selection is conveyed by color alone is a rendered-pixel fact.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'the binding component and theme',+ verifiedBy: 'the repository axe audit and visual gate',+ reason: 'Text contrast depends on resolved rendered colors.',+ },+ '1.4.11-non-text-contrast': {+ owner: 'the binding component and theme',+ verifiedBy: 'the repository axe audit and visual gate',+ reason:+ 'Tab indicators, boundaries, and focus indicators require rendered-color measurement.',+ },+ '2.1.1-keyboard': {+ owner: 'the binding component and composing page',+ verifiedBy:+ 'component-local tests for Home, End, and any controls composed around the tablist',+ reason:+ 'This contract covers Tab entry and exit, horizontal arrow movement, and manual Enter/Space activation. Optional shortcuts and adjacent controls remain local.',+ coversRemainderOnly: true,+ },+ '2.1.2-no-keyboard-trap': {+ owner: 'the composing page',+ verifiedBy: 'page-level sequential-focus review',+ reason:+ 'This contract proves Tab leaves the tablist; the larger page focus sequence remains outside it.',+ coversRemainderOnly: true,+ },+ '2.4.2-page-titled': {+ owner: 'the page',+ verifiedBy: 'page-level review',+ reason: 'A tabbed component does not own the document title.',+ },+ '2.4.3-focus-order': {+ owner: 'the composing page',+ verifiedBy: 'page-level review before and after the tabbed interface',+ reason:+ 'This contract proves the entry target and one-stop exit; the surrounding sequence remains page-owned.',+ coversRemainderOnly: true,+ },+ '2.4.4-link-purpose': {+ owner: 'family:navigation-destinations and caller content',+ verifiedBy: 'navigation-mode Tab tests and link-content review',+ reason:+ 'This contract excludes navigation-mode tabs; an ARIA tab selects a panel rather than acting as a link.',+ },+ '2.4.6-headings-and-labels': {+ owner: 'caller content and component review',+ verifiedBy: 'content review of tablist and tab labels',+ reason:+ 'This contract proves names exist; whether their words describe the views is a content judgement.',+ coversRemainderOnly: true,+ },+ '2.4.7-focus-visible': {+ owner:+ 'architecture:interaction-modality, the binding component, and theme',+ verifiedBy: 'component focus-ring tests and the repository visual gate',+ reason: 'A visible focus indicator is a painted result.',+ },+ '2.4.11-focus-not-obscured': {+ owner: 'the composing page or overlay',+ verifiedBy: 'real-browser layout and overlay review',+ reason:+ 'Whether a focused tab is obscured depends on surrounding authored content.',+ },+ '2.5.2-pointer-cancellation': {+ owner: 'the binding component and caller-composed interactive content',+ verifiedBy: 'component pointer suites outside the bound tab target',+ reason:+ 'This contract proves cancellation on the tab itself; enlarged or nested targets stay with their owners.',+ coversRemainderOnly: true,+ },+ '2.5.3-label-in-name': {+ owner: 'the binding component and caller content',+ verifiedBy: 'component label tests and content review',+ reason:+ 'This contract compares a bound tab name with its rendered label; adjacent caller text remains outside that relation.',+ coversRemainderOnly: true,+ },+ '2.5.8-target-size': {+ owner: 'the binding component and composing page',+ verifiedBy:+ 'real-browser geometry measurement with neighbouring-target spacing',+ reason:+ 'Target-size applicability depends on rendered geometry and neighbouring targets.',+ },+ '3.1.1-language-of-page': {+ owner: 'the page',+ verifiedBy: 'page-level review',+ reason:+ 'A component rendered in isolation does not own document language.',+ },+ '3.2.2-on-input': {+ owner: 'the caller',+ verifiedBy:+ 'integration review of any context change caused by the selection callback',+ reason:+ 'The contract keeps selection and panels coherent inside the composition; wider navigation or context changes are caller-owned.',+ },+ '3.2.4-consistent-identification': {+ owner: 'the design system and composing application',+ verifiedBy: 'cross-component and cross-page review',+ reason:+ 'Consistency is a comparison across usages, not a property one isolated binding can establish.',+ },+ '3.3.1-error-identification': {+ owner: 'the composing page',+ verifiedBy: 'page-level validation and status-message tests',+ reason: 'The Tabs pattern defines no validation-error state.',+ },+ '3.3.2-labels-or-instructions': {+ owner: 'caller content',+ verifiedBy: 'content review for any instructions around the views',+ reason:+ 'Tabs are not form inputs that require data-entry instructions; their accessible names are covered separately.',+ },+ '4.1.2-name-role-value': {+ owner: 'the binding component and contracts for composed controls',+ verifiedBy:+ 'component-specific tests for public states not owned by Tabs semantics',+ reason:+ 'This contract covers tablist/tab/tabpanel role, name, selection, availability, and relationships; other component states stay local.',+ coversRemainderOnly: true,+ },+ '4.1.3-status-messages': {+ owner: 'the composing page and AST-009 for any announcement claim',+ verifiedBy:+ 'status-message contracts plus real-AT evidence when the claim is spoken output',+ reason:+ 'Changing panels is not itself a status-message contract, and this pattern makes no announcement claim.',+ },+ 'apg-interaction': {+ owner:+ 'the binding component and a future current Tabs component record',+ verifiedBy:+ 'component-local Home/End tests and owner review for vertical or automatic activation',+ reason:+ 'This contract covers horizontal arrows and manual Enter/Space activation. Home/End remain local; vertical and automatic activation are unresolved and excluded.',+ coversRemainderOnly: true,+ },+ 'forced-colors': {+ owner: 'the binding component and theme',+ verifiedBy: 'component forced-colors suites and manual review',+ reason: 'Forced-colors output is a paint result.',+ },+ 'reduced-motion': {+ owner: 'the binding component and theme',+ verifiedBy: 'component transition tests and the visual gate',+ reason:+ 'Motion is a rendered result and is not intrinsic to Tabs semantics.',+ },+ 'at-facing-strings': {+ owner: 'the binding component',+ verifiedBy: 'the repository i18n catalog check',+ reason:+ 'Translation is a source-level concern that rendered semantics alone cannot distinguish.',+ },+ },+ });diff --git a/packages/core/src/TabList/TabList.test.tsx b/packages/core/src/TabList/TabList.test.tsxindex c266f4958f..d6558e795e 100644--- a/packages/core/src/TabList/TabList.test.tsx+++ b/packages/core/src/TabList/TabList.test.tsx@@ -1316,7 +1316,7 @@ describe('TabList ARIA pattern — role="tablist"', () => {return vi.spyOn(console, 'warn').mockImplementation(() => {});}- it('speaks the tabs pattern: a labelled tablist of tabs with aria-selected', () => {+ it('does not mix navigation semantics into explicit Tabs', () => {render(<TabList value="b" onChange={() => {}} role="tablist" aria-label="Views"><Tab value="a" label="Alpha" panelId="panel-a" />@@ -1324,14 +1324,10 @@ describe('TabList ARIA pattern — role="tablist"', () => {</TabList>,);- const tablist = screen.getByRole('tablist', {name: 'Views'});- const tabs = screen.getAllByRole('tab');- expect(tabs).toHaveLength(2);- expect(tabs.every(tab => tablist.contains(tab))).toBe(true);- expect(tabs[0]).toHaveAttribute('aria-selected', 'false');- expect(tabs[1]).toHaveAttribute('aria-selected', 'true');- expect(tabs[1]).toHaveAttribute('aria-controls', 'panel-b');- expect(tabs[1]).not.toHaveAttribute('aria-current');+ expect(screen.queryByRole('navigation')).toBeNull();+ for (const tab of screen.getAllByRole('tab')) {+ expect(tab).not.toHaveAttribute('aria-current');+ }});it('lets the consumer name the tablist from another element', () => {diff --git a/packages/core/src/TabList/__tests__/Tabs.a11y.chromium.spec.ts b/packages/core/src/TabList/__tests__/Tabs.a11y.chromium.spec.tsnew file mode 100644index 0000000000..384f0b8769--- /dev/null+++ b/packages/core/src/TabList/__tests__/Tabs.a11y.chromium.spec.ts@@ -0,0 +1,191 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tabs.a11y.chromium.spec.ts+ * @input Uses the shared Tabs contract, Chromium harness, checked-in stories, inventory, and exact known failures+ * @output Real-browser and accessibility-tree evidence for explicit TabList Tabs parts+ * @position Browser lane required by AST-013; it makes no real-AT claim.+ */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ TABS_PATTERN,+ blockingResults,+ checkAccessibilitySpec,+ formatFailures,+ formatReport,+ 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 {TABS_KNOWN_FAILURES} from './Tabs.a11y.known-failures';+import {+ TABS_BINDING_STATES,+ type TabsBindingRow,+ type TabsBindingState,+} from './Tabs.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`;+}++function subjectFor(page: Page, state: TabsBindingRow): Locator {+ const root = page.locator('#storybook-root');+ if ('selector' in state.subject) {+ return root.locator(state.subject.selector);+ }+ return root.getByRole(state.subject.role, {+ name: state.subject.name,+ includeHidden: true,+ });+}++function relatedFor(+ page: Page,+ state: TabsBindingRow,+): Readonly<Record<string, Locator>> {+ const metadata = state as TabsBindingState;+ const root = page.locator('#storybook-root');+ return Object.fromEntries(+ Object.entries(metadata.relations ?? {}).map(([name, relation]) => [+ name,+ root.locator(relation.selector),+ ]),+ );+}++async function mountState(page: Page, state: TabsBindingRow): Promise<void> {+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});+ await holdMotionStill(page);+ await subjectFor(page, state).waitFor({state: 'attached'});+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: TabsBindingRow,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: TABS_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: TABS_KNOWN_FAILURES,+ mount: async () => {+ await mountState(page, state);+ return createChromiumHarness({+ page,+ subject: subjectFor(page, state),+ cdp,+ visibleLabel: state.facts.visibleLabel ? undefined : null,+ related: relatedFor(page, state),+ });+ },+ });+}++test('every binding fact matches the rendered semantic state', async ({+ page,+}) => {+ test.setTimeout(3 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const wrong: string[] = [];++ for (const state of TABS_BINDING_STATES) {+ await mountState(page, state);+ const subject = await createChromiumHarness({+ page,+ subject: subjectFor(page, state),+ cdp,+ related: relatedFor(page, state),+ }).subject();+ const computed = await subject.computed();++ const expectedRole =+ state.facts.part === 'tablist'+ ? 'tablist'+ : state.facts.part === 'tab'+ ? 'tab'+ : state.facts.active === false+ ? null+ : 'tabpanel';+ if (computed.role !== expectedRole) {+ wrong.push(+ `${state.id}: declares role=${expectedRole}, browser exposes ${computed.role}`,+ );+ }+ if (+ state.facts.selected != null &&+ computed.selected !== state.facts.selected+ ) {+ wrong.push(+ `${state.id}: declares selected=${state.facts.selected}, browser exposes ${computed.selected}`,+ );+ }+ if (+ state.facts.disabled != null &&+ computed.disabled !== state.facts.disabled+ ) {+ wrong.push(+ `${state.id}: declares disabled=${state.facts.disabled}, browser exposes ${computed.disabled}`,+ );+ }+ }++ expect(wrong).toEqual([]);+});++test('every expectation is exercised by at least one bound state', async ({+ page,+}) => {+ test.setTimeout(5 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of TABS_BINDING_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(neverExercised(results)).toEqual([]);+ expect(unmatchedKnownFailures(TABS_KNOWN_FAILURES, results)).toEqual([]);+});++for (const state of TABS_BINDING_STATES) {+ test(`${state.binding} [${state.id}] — ${state.summary}`, async ({page}) => {+ test.setTimeout(3 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(TABS_PATTERN, [result]);+ // eslint-disable-next-line no-console -- the report is this run's artifact+ console.log(formatReport(report));+ expect(formatFailures(blockingResults([result]))).toBe('');+ expect(report.unrunLayers).toEqual([]);+ expect(report.counts.unexpectedPass).toBe(0);+ });+}diff --git a/packages/core/src/TabList/__tests__/Tabs.a11y.known-failures.ts b/packages/core/src/TabList/__tests__/Tabs.a11y.known-failures.tsnew file mode 100644index 0000000000..e2b73d8a5e--- /dev/null+++ b/packages/core/src/TabList/__tests__/Tabs.a11y.known-failures.ts@@ -0,0 +1,45 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tabs.a11y.known-failures.ts+ * @input Uses KnownFailure from @astryxdesign/a11y-spec+ * @output Exact public-safe Tabs migration failures+ * @position AST-021 debt records; operational ownership remains outside public source.+ */++import type {KnownFailure} from '@astryxdesign/a11y-spec';++const COMMON = {+ binding: 'Tab',+ state: 'tab-disabled-unselected',+ evidenceLayer: 'real-browser',+ standardsReference:+ 'WCAG 2.2 4.1.2 Name, Role, Value; WAI-ARIA 1.2 aria-disabled',+ reason:+ 'This migration records the existing behavior without changing the component interaction contract.',+} as const;++export const TABS_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [+ {+ ...COMMON,+ expectation: 'tabs.tab.unavailable-pointer-inert',+ failureEquals:+ 'the tab is reported unavailable, but clicking it selected it',+ userImpact:+ 'A pointer user can activate a tab that assistive technology reports as unavailable.',+ },+ {+ ...COMMON,+ expectation: 'tabs.tab.unavailable-enter-inert',+ failureEquals: 'the tab is reported unavailable, but Enter selected it',+ userImpact:+ 'A keyboard user can activate a focusable tab with Enter after assistive technology reports it unavailable.',+ },+ {+ ...COMMON,+ expectation: 'tabs.tab.unavailable-space-inert',+ failureEquals: 'the tab is reported unavailable, but Space selected it',+ userImpact:+ 'A keyboard user can activate a focusable tab with Space after assistive technology reports it unavailable.',+ },+];diff --git a/packages/core/src/TabList/__tests__/Tabs.a11y.renders.tsx b/packages/core/src/TabList/__tests__/Tabs.a11y.renders.tsxnew file mode 100644index 0000000000..b3fd5bb421--- /dev/null+++ b/packages/core/src/TabList/__tests__/Tabs.a11y.renders.tsx@@ -0,0 +1,92 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file Tabs.a11y.renders.tsx+ * @input Uses TabList, Tab, React state, and the checked Tabs state inventory+ * @output Consumer-realistic explicit Tabs render functions shared by jsdom and Storybook+ * @position Binding fixture layer; navigation, callbacks, styling, and TabMenu stay local.+ */++import {useState, type ReactElement} from 'react';+import {Tab, TabList} from '../index';+import type {TabsStateId} from './Tabs.a11y.states';++function TabsFixture({+ direction = 'ltr',+ disabledActivity = false,+ hiddenSelectedLabel = false,+}: {+ direction?: 'ltr' | 'rtl';+ disabledActivity?: boolean;+ hiddenSelectedLabel?: boolean;+}) {+ const [value, setValue] = useState('overview');+ const panels = {+ overview: 'Everything at a glance.',+ activity: 'What happened recently.',+ members: 'Who has access.',+ } as const;++ return (+ <div dir={direction}>+ <button type="button">Before tabs</button>+ <TabList+ value={value}+ onChange={setValue}+ role="tablist"+ aria-label="Project views">+ <Tab+ value="overview"+ label="Overview"+ id="tabs-a11y-tab-overview"+ panelId="tabs-a11y-panel-overview"+ isLabelHidden={hiddenSelectedLabel}+ icon={+ hiddenSelectedLabel ? <span aria-hidden="true">▣</span> : undefined+ }+ />+ <Tab+ value="activity"+ label="Activity"+ id="tabs-a11y-tab-activity"+ panelId="tabs-a11y-panel-activity"+ aria-disabled={disabledActivity || undefined}+ />+ <Tab+ value="members"+ label="Members"+ id="tabs-a11y-tab-members"+ panelId="tabs-a11y-panel-members"+ />+ </TabList>+ {Object.entries(panels).map(([key, content]) => (+ <div+ key={key}+ id={`tabs-a11y-panel-${key}`}+ role="tabpanel"+ aria-labelledby={`tabs-a11y-tab-${key}`}+ tabIndex={0}+ hidden={value !== key}>+ {content}+ </div>+ ))}+ <button type="button">After tabs</button>+ </div>+ );+}++export type TabsStateRender = () => ReactElement;++export const TABS_STATE_RENDERS: Record<TabsStateId, TabsStateRender> = {+ 'tab-list-selected-ltr': () => <TabsFixture />,+ 'tab-list-selected-rtl': () => <TabsFixture direction="rtl" />,+ 'tab-list-disabled-skip': () => <TabsFixture disabledActivity />,+ 'tab-selected-visible-label': () => <TabsFixture />,+ 'tab-unselected-visible-label': () => <TabsFixture />,+ 'tab-disabled-unselected': () => <TabsFixture disabledActivity />,+ 'tab-selected-hidden-label': () => <TabsFixture hiddenSelectedLabel />,+ 'tabpanel-active': () => <TabsFixture />,+ 'tabpanel-inactive': () => <TabsFixture />,+};diff --git a/packages/core/src/TabList/__tests__/Tabs.a11y.states.ts b/packages/core/src/TabList/__tests__/Tabs.a11y.states.tsnew file mode 100644index 0000000000..ace7ed5a8a--- /dev/null+++ b/packages/core/src/TabList/__tests__/Tabs.a11y.states.ts@@ -0,0 +1,247 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tabs.a11y.states.ts+ * @input Uses TabsStateFacts from @astryxdesign/a11y-spec+ * @output The AST-021 binding inventory for explicit TabList Tabs parts and states+ * @position Data-only inventory shared by jsdom, Storybook, and Chromium bindings.+ */++import type {TabsStateFacts} from '@astryxdesign/a11y-spec';++export type TabsBinding = 'TabList' | 'Tab' | 'TabsComposition';++export interface TabsRelation {+ readonly selector: string;+}++export interface TabsBindingState {+ readonly id: string;+ readonly binding: TabsBinding;+ readonly summary: string;+ readonly facts: TabsStateFacts;+ readonly subject:+ | {readonly role: 'tablist' | 'tab'; readonly name: string}+ | {readonly selector: string};+ readonly relations?: Readonly<Record<string, TabsRelation>>;+ readonly storyId: string;+}++export type TabsBindingRow = (typeof TABS_BINDING_STATES)[number];+export type TabsStateId = (typeof TABS_BINDING_STATES)[number]['id'];++const RELATIONS = {+ first: {selector: '[role="tab"][data-tab-value="overview"]'},+ second: {selector: '[role="tab"][data-tab-value="activity"]'},+ third: {selector: '[role="tab"][data-tab-value="members"]'},+ panel: {selector: '#tabs-a11y-panel-activity[role="tabpanel"]'},+ tab: {selector: '#tabs-a11y-tab-overview[role="tab"]'},+ 'panel-first': {selector: '#tabs-a11y-panel-overview[role="tabpanel"]'},+ 'panel-second': {selector: '#tabs-a11y-panel-activity[role="tabpanel"]'},+ 'panel-third': {selector: '#tabs-a11y-panel-members[role="tabpanel"]'},+} as const;++function tablistFacts(overrides: Partial<TabsStateFacts> = {}): TabsStateFacts {+ return {+ part: 'tablist',+ selected: null,+ active: null,+ disabled: null,+ focusable: null,+ visibleLabel: true,+ controlsPanel: false,+ controlledPanel: null,+ labelledByTab: false,+ labellingTab: null,+ tabRelations: ['first', 'second', 'third'],+ panelRelations: ['panel-first', 'panel-second', 'panel-third'],+ disabledTabs: [],+ selectedTab: 'first',+ direction: 'ltr',+ manualActivation: true,+ tabReachable: true,+ pointerSelection: true,+ pointerCancellation: false,+ ...overrides,+ };+}++function tabFacts(overrides: Partial<TabsStateFacts> = {}): TabsStateFacts {+ return tablistFacts({+ part: 'tab',+ selected: true,+ disabled: false,+ focusable: true,+ controlsPanel: true,+ controlledPanel: 'panel',+ tabRelations: [],+ panelRelations: [],+ selectedTab: null,+ pointerSelection: false,+ pointerCancellation: true,+ ...overrides,+ });+}++function panelFacts(overrides: Partial<TabsStateFacts> = {}): TabsStateFacts {+ return tablistFacts({+ part: 'tabpanel',+ selected: null,+ active: true,+ disabled: null,+ focusable: null,+ controlsPanel: false,+ controlledPanel: null,+ labelledByTab: true,+ labellingTab: 'tab',+ tabRelations: [],+ panelRelations: [],+ selectedTab: null,+ tabReachable: false,+ pointerSelection: false,+ pointerCancellation: false,+ ...overrides,+ });+}++const story = (id: string) => `a11y-tabs-pattern--${id}`;++export const TABS_BINDING_STATES = [+ {+ id: 'tab-list-selected-ltr',+ binding: 'TabList',+ summary: 'an explicit horizontal LTR tablist with manual activation',+ facts: tablistFacts(),+ subject: {role: 'tablist', name: 'Project views'},+ relations: RELATIONS,+ storyId: story('tab-list-selected-ltr'),+ },+ {+ id: 'tab-list-selected-rtl',+ binding: 'TabList',+ summary: 'an explicit horizontal RTL tablist with logical arrow movement',+ facts: tablistFacts({direction: 'rtl'}),+ subject: {role: 'tablist', name: 'Project views'},+ relations: RELATIONS,+ storyId: story('tab-list-selected-rtl'),+ },+ {+ id: 'tab-list-disabled-skip',+ binding: 'TabList',+ summary: 'a tablist whose unavailable middle tab is skipped by arrows',+ facts: tablistFacts({disabledTabs: ['second']}),+ subject: {role: 'tablist', name: 'Project views'},+ relations: RELATIONS,+ storyId: story('tab-list-disabled-skip'),+ },+ {+ id: 'tab-selected-visible-label',+ binding: 'Tab',+ summary: 'the selected available tab with a visible label',+ facts: tabFacts(),+ subject: {role: 'tab', name: 'Overview'},+ relations: {+ panel: {selector: '#tabs-a11y-panel-overview[role="tabpanel"]'},+ },+ storyId: story('tab-selected-visible-label'),+ },+ {+ id: 'tab-unselected-visible-label',+ binding: 'Tab',+ summary: 'an available unselected tab with a visible label',+ facts: tabFacts({selected: false, tabReachable: false}),+ subject: {role: 'tab', name: 'Activity'},+ relations: {panel: RELATIONS.panel},+ storyId: story('tab-unselected-visible-label'),+ },+ {+ id: 'tab-disabled-unselected',+ binding: 'Tab',+ summary: 'an unavailable unselected tab outside the roving order',+ facts: tabFacts({+ selected: false,+ disabled: true,+ tabReachable: false,+ pointerCancellation: false,+ }),+ subject: {role: 'tab', name: 'Activity'},+ relations: {panel: RELATIONS.panel},+ storyId: story('tab-disabled-unselected'),+ },+ {+ id: 'tab-selected-hidden-label',+ binding: 'Tab',+ summary: 'a selected icon-only tab named programmatically',+ facts: tabFacts({visibleLabel: false}),+ subject: {role: 'tab', name: 'Overview'},+ relations: {+ panel: {selector: '#tabs-a11y-panel-overview[role="tabpanel"]'},+ },+ storyId: story('tab-selected-hidden-label'),+ },+ {+ id: 'tabpanel-active',+ binding: 'TabsComposition',+ summary: 'the visible panel labelled by the selected tab',+ facts: panelFacts(),+ subject: {selector: '#tabs-a11y-panel-overview[role="tabpanel"]'},+ relations: {tab: RELATIONS.tab},+ storyId: story('tabpanel-active'),+ },+ {+ id: 'tabpanel-inactive',+ binding: 'TabsComposition',+ summary: 'an inactive hidden panel labelled by its tab',+ facts: panelFacts({active: false}),+ subject: {selector: '#tabs-a11y-panel-activity[role="tabpanel"]'},+ relations: {+ tab: {selector: '#tabs-a11y-tab-activity[role="tab"]'},+ },+ storyId: story('tabpanel-inactive'),+ },+] as const satisfies ReadonlyArray<TabsBindingState>;++export const TABS_EXCLUSIONS = [+ {+ owner: 'TabList and Tab without role="tablist"',+ classification: 'out-of-scope',+ reason:+ 'The default navigation pattern remains a nav landmark with aria-current and belongs to navigation semantics, not the ARIA Tabs contract.',+ },+ {+ owner: 'TabMenu trigger, popup, and options',+ classification: 'out-of-scope',+ reason:+ 'TabMenu is a menu-button, menu, and radio-menu composition and is invalid as a child of an explicit tablist.',+ },+ {+ owner: 'The table-filter page template’s narrow-view Tabs composition',+ classification: 'out-of-scope',+ reason:+ 'The public template currently points every tab at one shared panel and labels that panel independently. Its page-owned composition mismatch is recorded separately rather than changing a template inside this pattern-migration pull request.',+ },+ {+ owner: 'Home and End shortcuts',+ classification: 'preserved',+ reason:+ 'The component keeps its local coverage; these APG-optional shortcuts are not promoted into the shared contract.',+ },+ {+ owner: 'Vertical Tabs and automatic activation',+ classification: 'needs-human',+ reason:+ 'Neither mode is currently exposed by TabList, and adopting either changes public behavior and interaction policy.',+ },+ {+ owner: 'A public TabPanel primitive or generated relationship ids',+ classification: 'needs-human',+ reason:+ 'The current API leaves panel elements and ids with the caller; introducing a primitive or ownership change is public API design.',+ },+ {+ owner: 'No-selection, multi-selection, or selected-disabled policy',+ classification: 'needs-human',+ reason:+ 'The current controlled API can be given invalid values, but no current record defines the supported recovery policy.',+ },+] as const;diff --git a/packages/core/src/TabList/__tests__/Tabs.a11y.test.tsx b/packages/core/src/TabList/__tests__/Tabs.a11y.test.tsxnew file mode 100644index 0000000000..58b7e8ce6c--- /dev/null+++ b/packages/core/src/TabList/__tests__/Tabs.a11y.test.tsx@@ -0,0 +1,153 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file Tabs.a11y.test.tsx+ * @input Uses the shared Tabs contract and complete explicit-Tabs binding inventory+ * @output DOM-layer binding evidence; browser-owned outcomes remain explicitly unrun+ * @position Fast migration lane for TabList, Tab, and caller-authored panel composition.+ */++import {cleanup, render, screen} from '@testing-library/react';+import {describe, expect, it} from 'vitest';+import {+ TABS_PATTERN,+ checkAccessibilitySpec,+ createJsdomHarness,+ expectAccessibilitySpec,+ summarize,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {TABS_KNOWN_FAILURES} from './Tabs.a11y.known-failures';+import {TABS_STATE_RENDERS} from './Tabs.a11y.renders';+import {+ TABS_BINDING_STATES,+ TABS_EXCLUSIONS,+ type TabsBindingRow,+} from './Tabs.a11y.states';++function subjectFor(state: TabsBindingRow): Element {+ if ('selector' in state.subject) {+ const element = document.querySelector(state.subject.selector);+ if (element == null) {+ throw new Error(`no subject for ${state.id}`);+ }+ return element;+ }+ return screen.getByRole(state.subject.role, {+ name: state.subject.name,+ hidden: true,+ });+}++function relatedFor(state: TabsBindingRow): Readonly<Record<string, Element>> {+ return Object.fromEntries(+ Object.entries(state.relations ?? {}).map(([name, relation]) => {+ const element = document.querySelector(relation.selector);+ if (element == null) {+ throw new Error(`no related subject "${name}" for ${state.id}`);+ }+ return [name, element];+ }),+ );+}++async function expectState(state: TabsBindingRow): Promise<void> {+ await expectAccessibilitySpec({+ spec: TABS_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: TABS_KNOWN_FAILURES,+ render: () => {+ render(TABS_STATE_RENDERS[state.id]());+ },+ subject: () => subjectFor(state),+ related: () => relatedFor(state),+ cleanup,+ });+}++async function checkState(state: TabsBindingRow): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: TABS_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: TABS_KNOWN_FAILURES,+ mount: async () => {+ render(TABS_STATE_RENDERS[state.id]());+ return createJsdomHarness({+ subject: subjectFor(state),+ related: relatedFor(state),+ });+ },+ unmount: cleanup,+ });+}++describe('the shared Tabs pattern, jsdom lane', () => {+ it.each(+ TABS_BINDING_STATES.map(+ state =>+ [`${state.binding} [${state.id}]`, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectState(state);+ });++ it('runs the DOM layer and reports higher layers as unrun', async () => {+ const results: BindingResult[] = [];+ for (const state of TABS_BINDING_STATES) {+ results.push(await checkState(state));+ }+ const report = summarize(TABS_PATTERN, results);+ expect(report.counts.pass).toBeGreaterThan(0);+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);+ expect(report.counts.unexpectedPass).toBe(0);+ });+});++describe('the explicit Tabs binding inventory', () => {+ it('names a distinct checked-in story for every state', () => {+ const ids = TABS_BINDING_STATES.map(state => state.storyId);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('binds TabList, Tab, and caller-authored panel composition', () => {+ expect(+ [...new Set(TABS_BINDING_STATES.map(state => state.binding))].sort(),+ ).toEqual(['Tab', 'TabList', 'TabsComposition']);+ });++ it('records excluded and unsettled surfaces explicitly', () => {+ expect(TABS_EXCLUSIONS.map(row => row.classification)).toEqual([+ 'out-of-scope',+ 'out-of-scope',+ 'out-of-scope',+ 'preserved',+ 'needs-human',+ 'needs-human',+ 'needs-human',+ ]);+ expect(TABS_EXCLUSIONS.every(row => row.reason.length > 0)).toBe(true);+ });++ it('binds only explicit horizontal manual-activation Tabs', () => {+ const wrong = TABS_BINDING_STATES.filter(state => {+ if (state.facts.part !== 'tablist') {+ return false;+ }+ return !state.facts.manualActivation;+ });+ expect(wrong).toEqual([]);+ });++ it('renders exactly one subject for every state', () => {+ for (const state of TABS_BINDING_STATES) {+ render(TABS_STATE_RENDERS[state.id]());+ expect(subjectFor(state), state.id).toBeTruthy();+ cleanup();+ }+ });+});