An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): add status-message accessibility contract (#6208)
Cindy Zhang9c83d436ca2b
diff --git a/apps/storybook/stories/AppShell.stories.tsx b/apps/storybook/stories/AppShell.stories.tsxindex 7e19d57712..5bfa79e8e8 100644--- a/apps/storybook/stories/AppShell.stories.tsx+++ b/apps/storybook/stories/AppShell.stories.tsx@@ -98,9 +98,7 @@ function AppTopNav({endContent}: {endContent?: React.ReactNode}) {heading={<TopNavHeadingheading="Acme App"- logo={- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />- }+ logo={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}/>}startContent={@@ -181,9 +179,7 @@ function SideNavWithHeader() {<SideNavheader={<SideNavHeading- icon={- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />- }+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}heading="Acme App"headingHref="#"/>diff --git a/apps/storybook/stories/StatusMessageA11y.stories.tsx b/apps/storybook/stories/StatusMessageA11y.stories.tsxnew file mode 100644index 0000000000..682bbf201a--- /dev/null+++ b/apps/storybook/stories/StatusMessageA11y.stories.tsx@@ -0,0 +1,92 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file StatusMessageA11y.stories.tsx+ * @input Uses the Core and Lab status-message binding inventories and render maps+ * @output One checked-in reproduction story for every status-message contract state+ * @position Stable browser fixtures required by AST-009 FR30 and AST-021+ */++import type {Meta, StoryObj} from '@storybook/react';+import {CORE_STATUS_MESSAGE_STATE_RENDERS} from '../../../packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.renders';+import {CORE_STATUS_MESSAGE_BINDING_STATES} from '../../../packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states';+import {CHAT_TYPING_STATUS_STATE_RENDERS} from '../../../packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.renders';+import {CHAT_TYPING_STATUS_BINDING_STATES} from '../../../packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.states';++function coreStory(id: string): StoryObj {+ const state = CORE_STATUS_MESSAGE_BINDING_STATES.find(+ candidate => candidate.id === id,+ );+ if (state == null) {+ throw new Error(+ `no Core binding state "${id}" — see StatusMessage.a11y.states.ts`,+ );+ }+ return {+ name: `${state.binding} — ${state.id}`,+ render: () => CORE_STATUS_MESSAGE_STATE_RENDERS[state.id](),+ };+}++function labStory(id: string): StoryObj {+ const state = CHAT_TYPING_STATUS_BINDING_STATES.find(+ candidate => candidate.id === id,+ );+ if (state == null) {+ throw new Error(+ `no Lab binding state "${id}" — see ChatTypingIndicator.a11y.states.ts`,+ );+ }+ return {+ name: `${state.binding} — ${state.id}`,+ render: () => CHAT_TYPING_STATUS_STATE_RENDERS[state.id](),+ };+}++const meta: Meta = {+ title: 'a11y/Status message pattern',+ tags: ['no-visual'],+ parameters: {+ docs: {+ description: {+ component:+ 'Binding states for the shared status-message accessibility contract. The controls drive real empty, update, replacement, clear, repeat, and progress transitions.',+ },+ },+ },+};++export default meta;++export const ToastInfoAnnouncement = coreStory('toast-info-announcement');+export const ToastErrorAnnouncement = coreStory('toast-error-announcement');+export const ToastInfoCardMounted = coreStory('toast-info-card-mounted');+export const ToastErrorCardMounted = coreStory('toast-error-card-mounted');+export const FieldStatusErrorAttached = coreStory(+ 'field-status-error-attached',+);+export const FieldStatusWarningDetached = coreStory(+ 'field-status-warning-detached',+);+export const FieldStatusSuccessDetached = coreStory(+ 'field-status-success-detached',+);+export const SpinnerDefaultLabelMounted = coreStory(+ 'spinner-default-label-mounted',+);+export const SpinnerVisibleLabelMounted = coreStory(+ 'spinner-visible-label-mounted',+);+export const ChatSystemStatusMounted = coreStory('chat-system-status-mounted');+export const ProgressLoadingToComplete = coreStory(+ 'progress-loading-to-complete',+);+export const ProgressCustomRange = coreStory('progress-custom-range');+export const ProgressMarkFocusedUpdate = coreStory(+ 'progress-mark-focused-update',+);++export const ChatTypingEmptyToMessage = labStory(+ 'chat-typing-empty-to-message',+);+export const ChatTypingNameMounted = labStory('chat-typing-name-mounted');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex 56b5d3974b..3e86282e70 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -45,19 +45,21 @@ src/├── switch.* the switch pattern, same four files├── 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+ ├── modal-dialog.* the native modal-dialog pattern, same four files+ └── status-message.* live-region and progress status mechanics```## The patterns-| Pattern | Adopted from | Bound by |-| -------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |-| `radio-group` | [APG radio group](https://www.w3.org/WAI/ARIA/apg/patterns/radio/) | RadioList, SegmentedControl; role/state portions of DropdownMenu radio items |-| `checkbox` | [APG checkbox](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/) | CheckboxInput, CheckboxListItem, DropdownMenuCheckboxItem, SelectableCard |-| `switch` | [APG switch](https://www.w3.org/WAI/ARIA/apg/patterns/switch/) | Switch |-| `button` | [APG button](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | Button, IconButton, ClickableCard, SideNavCollapseButton, ChatSendButton |-| `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 |+| Pattern | Adopted from | Bound by |+| ---------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |+| `radio-group` | [APG radio group](https://www.w3.org/WAI/ARIA/apg/patterns/radio/) | RadioList, SegmentedControl; role/state portions of DropdownMenu radio items |+| `checkbox` | [APG checkbox](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/) | CheckboxInput, CheckboxListItem, DropdownMenuCheckboxItem, SelectableCard |+| `switch` | [APG switch](https://www.w3.org/WAI/ARIA/apg/patterns/switch/) | Switch |+| `button` | [APG button](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | Button, IconButton, ClickableCard, SideNavCollapseButton, ChatSendButton |+| `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 |The `radio-group` contract owns direct-group Tab entry/exit, Space, and adopteddirectional selection, including zero-selection entry. DropdownMenu radio roles@@ -66,6 +68,14 @@ with Menu. Home and End remain component-local because the current APG radiopattern does not require them and no current Astryx record adopts them as sharedbehavior.+The `status-message` contract is WCAG-derived rather than an APG widget+pattern. Required expectations cover browser-exposed status/alert roles and+channels, complete exposed text or names across every public update, preserved+focus, and progressbar role/name/range/value transitions. ARIA22's+container-before-update technique and the roles' overridable implicit atomic+defaults remain advisory reliability evidence. Repetition, timing, order, and+omission remain real assistive-technology outcomes.+The `text-input` contract is native rather than APG-derived. It covers therole-bearing `<input>` or `<textarea>` only; composed clear and tooltip buttonskeep their button contract. Password fields bind to persistent naming, state,@@ -199,6 +209,11 @@ Lower-level contract fixtures, Chromium bindings, report generation, and mutatioproof use `checkAccessibilitySpec`, which returns the complete factual result withoutasserting it.+Some stateful patterns ask the binding to perform named public transitions. The+binding drives each transition through its public API; the contract then+re-observes the current semantic subject. Transition names describe user-visible+state changes rather than component-private implementation steps.+## Known failuresA known failure names one expectation, one binding, one state, one evidence@@ -222,6 +237,8 @@ refers to it (AST-021 FR8–FR10).# jsdom lane — part of `pnpm test`pnpm vitest run --project node internal/a11y-specpnpm vitest run --project ui packages/core/src/Switch+pnpm vitest run --project ui packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.test.tsx+pnpm vitest run --project ui packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.test.tsx# Chromium lane — needs a browser and a built Storybookpnpm storybook:builddiff --git a/internal/a11y-spec/src/check.test.ts b/internal/a11y-spec/src/check.test.tsindex c549c7bf2e..965314f728 100644--- a/internal/a11y-spec/src/check.test.ts+++ b/internal/a11y-spec/src/check.test.ts@@ -120,6 +120,7 @@ async function run(observes?: readonly EvidenceLayer[];state?: string;initialFocusEntry?: () => Promise<{readonly subjectWasModal: boolean}>;+ transition?: (name: string) => Promise<void> | void;} = {},) {return checkAccessibilitySpec({@@ -130,6 +131,7 @@ async function run(mount: async () => harness(options.observes ?? ['unit', 'dom']),knownFailures: options.knownFailures,initialFocusEntry: options.initialFocusEntry,+ transition: options.transition,});}@@ -235,6 +237,24 @@ describe('checkAccessibilitySpec', () => {expect(result.results[0]?.status).toBe('pass');});+ it('treats a missing public transition driver as a binding fault', async () => {+ const spec = contractThat(async ({transition}) => transition('show'));++ await expect(run(spec)).rejects.toThrow(+ 'requests the "show" transition, but this binding supplies no transition driver',+ );+ });++ it('passes named public transitions to the binding driver', async () => {+ const transition = vi.fn(async () => {});+ const spec = contractThat(async context => context.transition('replace'));++ const result = await run(spec, {transition});+ expect(transition).toHaveBeenCalledOnce();+ expect(transition).toHaveBeenCalledWith('replace');+ expect(result.results[0]?.status).toBe('pass');+ });+describe('an expectation that discovers mid-run that it does not apply', () => {it('reports not-applicable with its reason, never a pass', async () => {const contract = contractThat(() => {});diff --git a/internal/a11y-spec/src/check.ts b/internal/a11y-spec/src/check.tsindex 3d25602075..bddb82a16e 100644--- a/internal/a11y-spec/src/check.ts+++ b/internal/a11y-spec/src/check.ts@@ -134,6 +134,8 @@ export interface CheckAccessibilitySpecOptions<Facts> {* binding must begin recording before the subject can receive focus.*/readonly initialFocusEntry?: () => Promise<InitialFocusEntryObservation>;+ /** Perform one named public state transition required by the pattern. */+ readonly transition?: (name: string) => Promise<void> | void;/*** Run only these expectation ids. Used by the contract's own mutation proof,* which asks one expectation at a time whether it notices its outcome being@@ -266,6 +268,14 @@ export async function checkAccessibilitySpec<Facts>(}return options.initialFocusEntry();},+ transition: async name => {+ if (options.transition == null) {+ throw new MissingBindingCapability(+ `${expectation.id} requests the "${name}" transition, but this binding supplies no transition driver`,+ );+ }+ await options.transition(name);+ },});} catch (error) {if (diff --git a/internal/a11y-spec/src/contract.ts b/internal/a11y-spec/src/contract.tsindex dc28bb84f0..b81436b86c 100644--- a/internal/a11y-spec/src/contract.ts+++ b/internal/a11y-spec/src/contract.ts@@ -182,6 +182,8 @@ export interface ExpectationContext<Facts> {* a missing observation into a contract result.*/readonly initialFocusEntry: () => Promise<InitialFocusEntryObservation>;+ /** Ask the binding to perform one named public state transition. */+ readonly transition: (name: string) => Promise<void>;}export interface Expectation<Facts> {diff --git a/internal/a11y-spec/src/harness.ts b/internal/a11y-spec/src/harness.tsindex 9bafbd646c..0241e365ab 100644--- a/internal/a11y-spec/src/harness.ts+++ b/internal/a11y-spec/src/harness.ts@@ -48,8 +48,19 @@ export interface ComputedNode {readonly name: string;/** Computed accessible description. */readonly description: string;+ /** Text descendants the engine keeps in this node's accessibility subtree. */+ readonly accessibleText: string;+ /** Computed live-region channel, or null when this node is not live. */+ readonly live: 'off' | 'polite' | 'assertive' | null;+ /** Whether the accessibility tree exposes the live region as atomic. */+ readonly atomic: boolean | null;/** Computed text value, or null when the node exposes no value. */readonly value: string | null;+ /** Numeric range value when the accessibility node exposes one. */+ readonly rangeValue: number | null;+ readonly rangeMin: number | null;+ readonly rangeMax: number | null;+ readonly valueText: string | null;/** Whether the engine exposes the subject as modal. */readonly modal: boolean | null;/** Whether the engine exposes the textbox as multi-line. */@@ -80,6 +91,12 @@ export interface Subject {labelText(): Promise<string | null>;/** DOM/runtime layer: the live value of a native text control, if this is one. */textValue(): Promise<string | null>;+ /** DOM layer: the subject's authored text content, whitespace-normalized. */+ textContent(): Promise<string>;+ /** DOM layer: whether a current semantic subject resolves after an update. */+ currentExists(): Promise<boolean>;+ /** DOM layer: whether the originally designated subject is still connected. */+ isConnected(): Promise<boolean>;/** Accessibility-tree layer: what the engine computes for this node. */computed(): Promise<ComputedNode>;/**diff --git a/internal/a11y-spec/src/harness/chromium.ts b/internal/a11y-spec/src/harness/chromium.tsindex b2a6e0066b..c926393502 100644--- a/internal/a11y-spec/src/harness/chromium.ts+++ b/internal/a11y-spec/src/harness/chromium.ts@@ -97,6 +97,8 @@ interface AxProperty {}interface AxNode {+ readonly nodeId?: string;+ readonly childIds?: readonly string[];readonly ignored?: boolean;readonly role?: AxValue;readonly name?: AxValue;@@ -115,6 +117,24 @@ function property(node: AxNode, name: string): unknown {?.value;}+function accessibleText(nodes: readonly AxNode[], root: AxNode): string {+ const byId = new Map(+ nodes.flatMap(node =>+ node.nodeId == null ? [] : [[node.nodeId, node] as const],+ ),+ );+ const visit = (node: AxNode): string => {+ if (node.ignored !== true && text(node.role) === 'StaticText') {+ return text(node.name);+ }+ return (node.childIds ?? [])+ .map(id => byId.get(id))+ .flatMap(child => (child == null ? [] : [visit(child)]))+ .join(' ');+ };+ return visit(root).replace(/\s+/g, ' ').trim();+}+function flag(node: AxNode, name: string): boolean {const value = property(node, name);// The protocol is not consistent about booleans across property names, so@@ -173,7 +193,7 @@ async function computedNode(const {nodes} = (await cdp.send('Accessibility.getPartialAXTree', {nodeId,- fetchRelatives: false,+ fetchRelatives: true,})) as unknown as {nodes: readonly AxNode[]};const node = nodes[0];@@ -183,7 +203,14 @@ async function computedNode(role: null,name: '',description: '',+ accessibleText: '',+ live: null,+ atomic: null,value: null,+ rangeValue: null,+ rangeMin: null,+ rangeMax: null,+ valueText: null,modal: null,multiline: null,readOnly: null,@@ -195,6 +222,24 @@ async function computedNode(}const role = text(node.role);+ let textNodes = nodes;+ let textRoot = node;+ if (+ (role === 'status' || role === 'alert') &&+ node.backendDOMNodeId != null+ ) {+ const full = (await cdp.send(+ 'Accessibility.getFullAXTree',+ )) as unknown as {nodes: readonly AxNode[]};+ const fullRoot = full.nodes.find(+ candidate => candidate.backendDOMNodeId === node.backendDOMNodeId,+ );+ if (fullRoot != null) {+ textNodes = full.nodes;+ textRoot = fullRoot;+ }+ }+ const live = property(node, 'live');const checked = property(node, 'checked');const invalid = property(node, 'invalid');const exposedValue = node.value?.value;@@ -203,12 +248,31 @@ async function computedNode(role: role === '' ? null : role,name: text(node.name),description: text(node.description),+ accessibleText: accessibleText(textNodes, textRoot),+ live:+ live === 'off' || live === 'polite' || live === 'assertive'+ ? live+ : null,+ atomic: optionalFlag(node, 'atomic'),value:typeof exposedValue === 'string'? exposedValue: role === 'textbox'? '': null,+ rangeValue: typeof exposedValue === 'number' ? exposedValue : null,+ rangeMin:+ typeof property(node, 'valuemin') === 'number'+ ? (property(node, 'valuemin') as number)+ : null,+ rangeMax:+ typeof property(node, 'valuemax') === 'number'+ ? (property(node, 'valuemax') as number)+ : null,+ valueText:+ typeof property(node, 'valuetext') === 'string'+ ? (property(node, 'valuetext') as string)+ : null,modal: optionalFlag(node, 'modal'),multiline: optionalFlag(node, 'multiline'),readOnly: optionalFlag(node, 'readonly'),@@ -271,6 +335,11 @@ export function createChromiumHarness(): Harness {const {page, subject: locator, pointerTarget, cdp, visibleLabel} = options;const pointerLocator = pointerTarget ?? locator;+ let initialElement: ReturnType<Locator['elementHandle']> | undefined;+ const capturedElement = () => {+ initialElement ??= locator.elementHandle();+ return initialElement;+ };const pointerTargets = new WeakMap<Subject, Locator>();const subject: Subject = {@@ -425,6 +494,15 @@ export function createChromiumHarness(}return null;}),+ textContent: () =>+ locator.evaluate(node =>+ (node.textContent ?? '').replace(/\s+/g, ' ').trim(),+ ),+ currentExists: async () => (await locator.count()) > 0,+ isConnected: async () => {+ const element = await capturedElement();+ return element != null && element.evaluate(node => node.isConnected);+ },computed: () => computedNode(cdp, locator),visibleLabelText: async () => {if (visibleLabel === null) {@@ -724,6 +802,12 @@ export function createChromiumHarness(}return null;}),+ textContent: () =>+ related.evaluate(node =>+ (node.textContent ?? '').replace(/\s+/g, ' ').trim(),+ ),+ currentExists: async () => (await related.count()) > 0,+ isConnected: () => related.evaluate(node => node.isConnected),computed: () => computedNode(cdp, related),visibleLabelText: async () => {const value = (await related.innerText()).trim();diff --git a/internal/a11y-spec/src/harness/jsdom.ts b/internal/a11y-spec/src/harness/jsdom.tsindex 9b33afee5a..1b01b30672 100644--- a/internal/a11y-spec/src/harness/jsdom.ts+++ b/internal/a11y-spec/src/harness/jsdom.ts@@ -105,6 +105,10 @@ function createSubject(element: Element): Subject {}return null;},+ textContent: async () =>+ (element.textContent ?? '').replace(/\s+/g, ' ').trim(),+ currentExists: async () => element.isConnected,+ isConnected: async () => element.isConnected,computed: async () =>unobservable('accessibility-tree', 'a computed accessibility node'),visibleLabelText: async () =>diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.tsindex bcb647b353..a28d4b7011 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -100,6 +100,11 @@ export {type ModalDialogStateFacts,} from './patterns/modal-dialog';+export {+ STATUS_MESSAGE_PATTERN,+ type StatusMessageStateFacts,+} from './patterns/status-message';+export {saysInOrder, spokenWords} from './spoken';export {BUTTON_PATTERN, type ButtonStateFacts} from './patterns/button';diff --git a/internal/a11y-spec/src/patterns/status-message.chromium.spec.ts b/internal/a11y-spec/src/patterns/status-message.chromium.spec.tsnew file mode 100644index 0000000000..4fc138222f--- /dev/null+++ b/internal/a11y-spec/src/patterns/status-message.chromium.spec.ts@@ -0,0 +1,198 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file status-message.chromium.spec.ts+ * @input Uses plain-HTML status fixtures and the Chromium accessibility tree+ * @output Positive and negative proof for every browser-owned status-message outcome+ * @position Real-browser self-test of the contract, not a component binding+ */++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} from '../harness/chromium';+import {STATUS_MESSAGE_PATTERN} from './status-message';+import {+ STATUS_MESSAGE_CONFORMING_FIXTURES,+ STATUS_MESSAGE_MUTATIONS,+ STATUS_MESSAGE_SUBJECT_SELECTOR,+ statusMessageFixture,+ type StatusMessageFixture,+} from './status-message.fixtures';++async function applyTransition(+ page: Page,+ target: StatusMessageFixture,+ name: string,+): Promise<void> {+ const transition =+ target.transitions?.[name as keyof typeof target.transitions];+ if (transition == null) {+ throw new Error(`fixture "${target.id}" supplies no "${name}" transition`);+ }+ const subject = page.locator(STATUS_MESSAGE_SUBJECT_SELECTOR);+ if (transition.removeSubject === true) {+ await subject.evaluate(node => node.remove());+ return;+ }+ if (transition.replaceSubject === true) {+ await subject.evaluate((node, next) => {+ const replacement = node.cloneNode(false) as Element;+ if (next.attribute != null) {+ if (next.value == null) {+ replacement.removeAttribute(next.attribute);+ } else {+ replacement.setAttribute(next.attribute, next.value);+ }+ } else if (next.value !== undefined) {+ replacement.textContent = next.value;+ }+ node.replaceWith(replacement);+ }, transition);+ return;+ }+ if (transition.pulse === true) {+ await subject.evaluate((node, attribute) => {+ if (attribute == null) {+ node.textContent = '';+ } else {+ node.setAttribute(attribute, '');+ }+ }, transition.attribute ?? null);+ await page.evaluate(+ () =>+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),+ );+ }+ if (transition.hiddenValue !== undefined) {+ await subject.evaluate((node, value) => {+ const hidden = node.ownerDocument.createElement('span');+ hidden.setAttribute('aria-hidden', 'true');+ hidden.textContent = value;+ node.replaceChildren(hidden);+ }, transition.hiddenValue);+ }+ if (transition.attributes != null) {+ await subject.evaluate((node, attributes) => {+ for (const [name, value] of Object.entries(attributes)) {+ if (value == null) {+ node.removeAttribute(name);+ } else {+ node.setAttribute(name, value);+ }+ }+ }, transition.attributes);+ }+ if (transition.value !== undefined) {+ await subject.evaluate((node, next) => {+ if (next.attribute == null) {+ node.textContent = next.value ?? '';+ } else if (next.value == null) {+ node.removeAttribute(next.attribute);+ } else {+ node.setAttribute(next.attribute, next.value);+ }+ }, transition);+ }+ if (transition.focusSelector != null) {+ await page.locator(transition.focusSelector).focus();+ }+}++async function resultsFor(+ page: Page,+ cdp: CDPSession,+ target: StatusMessageFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ return (+ await checkAccessibilitySpec({+ spec: STATUS_MESSAGE_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ only,+ mount: async () => {+ await page.setContent(target.html);+ return createChromiumHarness({+ page,+ cdp,+ subject: page.locator(STATUS_MESSAGE_SUBJECT_SELECTOR),+ related: {+ 'focus-anchor': page.locator('[data-a11y-relation="focus-anchor"]'),+ },+ });+ },+ transition: name => applyTransition(page, target, name),+ })+ ).results;+}++test.describe('status-message contract — conforming fixtures', () => {+ for (const fixtureId of STATUS_MESSAGE_CONFORMING_FIXTURES) {+ test(`${fixtureId}: every applicable expectation passes`, async ({+ page,+ }) => {+ const cdp = await page.context().newCDPSession(page);+ const results = await resultsFor(+ page,+ cdp,+ statusMessageFixture(fixtureId),+ );+ expect(+ results+ .filter(+ result =>+ result.status !== 'pass' && result.status !== 'not-applicable',+ )+ .map(result => `${result.expectation}: ${result.detail ?? ''}`),+ ).toEqual([]);+ });+ }++ test('a replacement node can satisfy every required semantic outcome', async ({+ page,+ }) => {+ const cdp = await page.context().newCDPSession(page);+ const fixture = statusMessageFixture('violating-replaced-region');+ const requiredIds = STATUS_MESSAGE_PATTERN.expectations+ .filter(expectation => expectation.enforcement === 'required')+ .map(expectation => expectation.id);+ const required = await resultsFor(page, cdp, fixture, requiredIds);+ expect(+ required+ .filter(+ result =>+ result.status !== 'pass' && result.status !== 'not-applicable',+ )+ .map(result => `${result.expectation}: ${result.detail ?? ''}`),+ ).toEqual([]);+ });+});++test.describe('status-message contract — deliberately violating fixtures', () => {+ for (const expectation of STATUS_MESSAGE_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const mutation of STATUS_MESSAGE_MUTATIONS[expectation.id] ?? []) {+ test(`${describeExpectation(expectation)} — fails against ${mutation.fixture}`, async ({+ page,+ }) => {+ const cdp = await page.context().newCDPSession(page);+ const [result] = await resultsFor(+ page,+ cdp,+ statusMessageFixture(mutation.fixture),+ [expectation.id],+ );+ expect(result?.status, result?.detail ?? 'no result').toBe('fail');+ expect(result?.detail).toContain(mutation.failureIncludes);+ });+ }+ }+});diff --git a/internal/a11y-spec/src/patterns/status-message.fixtures.ts b/internal/a11y-spec/src/patterns/status-message.fixtures.tsnew file mode 100644index 0000000000..b0c485d371--- /dev/null+++ b/internal/a11y-spec/src/patterns/status-message.fixtures.ts@@ -0,0 +1,548 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file status-message.fixtures.ts+ * @input Uses the status-message binding facts+ * @output Plain-HTML conforming and deliberately violating fixtures, transition data, and mutation map+ * @position Contract self-test fixtures; no Astryx component is used here+ */++import type {StatusMessageStateFacts} from './status-message';++export const STATUS_MESSAGE_SUBJECT_SELECTOR = '[data-a11y-subject]';++export type StatusMessageTransition =+ 'show' | 'replace' | 'clear' | 'repeat' | 'progress' | 'complete';++export interface StatusMessageFixtureTransition {+ readonly value?: string | null;+ readonly attribute?: 'aria-label' | 'aria-valuenow';+ readonly attributes?: Readonly<Record<string, string | null>>;+ readonly hiddenValue?: string;+ readonly replaceSubject?: boolean;+ readonly removeSubject?: boolean;+ readonly pulse?: boolean;+ readonly focusSelector?: string;+}++export interface StatusMessageFixture {+ readonly id: string;+ readonly facts: StatusMessageStateFacts;+ readonly html: string;+ readonly transitions?: Readonly<+ Partial<Record<StatusMessageTransition, StatusMessageFixtureTransition>>+ >;+}++const POLITE_FACTS: StatusMessageStateFacts = {+ kind: 'live-region',+ role: 'status',+ politeness: 'polite',+ messageSource: 'text',+ initialMessage: '',+ message: 'Changes saved',+ replacement: 'Profile updated',+ semanticTransitions: ['show', 'replace', 'repeat', 'clear'],+};++const MOUNTED_POLITE_FACTS: StatusMessageStateFacts = {+ ...POLITE_FACTS,+ initialMessage: 'Changes saved',+ semanticTransitions: ['replace'],+};++const ASSERTIVE_FACTS: StatusMessageStateFacts = {+ ...POLITE_FACTS,+ role: 'alert',+ politeness: 'assertive',+ message: 'Upload failed',+ replacement: 'Connection failed',+};++const NAMED_FACTS: StatusMessageStateFacts = {+ ...POLITE_FACTS,+ role: 'status',+ messageSource: 'accessible-name',+ semanticTransitions: ['show', 'replace'],+};++const PROGRESS_FACTS: StatusMessageStateFacts = {+ kind: 'progressbar',+ politeness: null,+ name: 'Upload progress',+ initialValue: null,+ initialMin: 0,+ initialMax: 100,+ progressValue: 40,+ completionValue: 100,+ minValue: 0,+ maxValue: 100,+};++const REVERSED_INITIAL_PROGRESS_FACTS: StatusMessageStateFacts = {+ ...PROGRESS_FACTS,+ initialMin: 5,+ initialMax: 0,+};++const OUT_OF_INITIAL_RANGE_PROGRESS_FACTS: StatusMessageStateFacts = {+ ...PROGRESS_FACTS,+ initialValue: 10,+ initialMin: 0,+ initialMax: 5,+};++const REVERSED_PROGRESS_FACTS: StatusMessageStateFacts = {+ ...PROGRESS_FACTS,+ minValue: 100,+ maxValue: 0,+};++const OUT_OF_RANGE_PROGRESS_FACTS: StatusMessageStateFacts = {+ ...PROGRESS_FACTS,+ progressValue: 120,+};++const POLITE_TRANSITIONS = {+ show: {value: 'Changes saved'},+ replace: {value: 'Profile updated'},+ clear: {value: ''},+ repeat: {value: 'Changes saved', pulse: true},+} as const;++export const STATUS_MESSAGE_FIXTURES: readonly StatusMessageFixture[] = [+ {+ id: 'conforming-polite-channel',+ facts: POLITE_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Save</button><div data-a11y-subject role="status" aria-live="polite" aria-atomic="true"></div>',+ transitions: POLITE_TRANSITIONS,+ },+ {+ id: 'conforming-removable-status',+ facts: POLITE_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Save</button><div data-a11y-subject role="status" aria-live="polite" aria-atomic="true"></div>',+ transitions: {+ show: {value: 'Changes saved'},+ replace: {value: 'Profile updated'},+ repeat: {value: 'Changes saved', pulse: true},+ clear: {removeSubject: true},+ },+ },+ {+ id: 'conforming-assertive-channel',+ facts: ASSERTIVE_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Upload</button><div data-a11y-subject role="alert" aria-live="assertive" aria-atomic="true"></div>',+ transitions: {+ show: {value: 'Upload failed'},+ replace: {value: 'Connection failed'},+ clear: {value: ''},+ repeat: {value: 'Upload failed', pulse: true},+ },+ },+ {+ id: 'conforming-named-channel',+ facts: NAMED_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Load</button><div data-a11y-subject role="status" aria-label=""></div>',+ transitions: {+ show: {attribute: 'aria-label', value: 'Changes saved'},+ replace: {attribute: 'aria-label', value: 'Profile updated'},+ },+ },+ {+ id: 'conforming-progress',+ facts: PROGRESS_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Start upload</button><div data-a11y-subject role="progressbar" aria-label="Upload progress"></div>',+ transitions: {+ progress: {attribute: 'aria-valuenow', value: '40'},+ complete: {attribute: 'aria-valuenow', value: '100'},+ },+ },+ {+ id: 'violating-unexposed-channel',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject></div>',+ },+ {+ id: 'violating-wrong-channel',+ facts: ASSERTIVE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ },+ {+ id: 'violating-loses-channel',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ transitions: {+ show: {value: 'Changes saved', attributes: {'aria-live': 'assertive'}},+ },+ },+ {+ id: 'violating-wrong-role',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="log" aria-live="polite" aria-atomic="true"></div>',+ },+ {+ id: 'violating-loses-role',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ transitions: {+ show: {+ value: 'Changes saved',+ attributes: {role: 'log', 'aria-live': 'polite', 'aria-atomic': 'true'},+ },+ },+ },+ {+ id: 'violating-replaced-on-show',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ transitions: {show: {value: 'Changes saved', replaceSubject: true}},+ },+ {+ id: 'violating-replaced-on-first-update',+ facts: MOUNTED_POLITE_FACTS,+ html: '<div data-a11y-subject role="status">Changes saved</div>',+ transitions: {+ replace: {value: 'Profile updated', replaceSubject: true},+ },+ },+ {+ id: 'violating-missing-message',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ transitions: {show: {}},+ },+ {+ id: 'violating-hidden-message',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ transitions: {show: {hiddenValue: 'Changes saved'}},+ },+ {+ id: 'violating-non-atomic',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status" aria-atomic="false"></div>',+ },+ {+ id: 'violating-loses-atomicity',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ transitions: {+ show: {value: 'Changes saved', attributes: {'aria-atomic': 'false'}},+ },+ },+ {+ id: 'violating-replaced-region',+ facts: POLITE_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Save</button><div data-a11y-subject role="status"></div>',+ transitions: {+ show: {value: 'Changes saved'},+ replace: {value: 'Profile updated', replaceSubject: true},+ clear: {value: ''},+ repeat: {value: 'Changes saved', pulse: true},+ },+ },+ {+ id: 'violating-wrong-replacement',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ transitions: {+ show: {value: 'Changes saved'},+ replace: {value: 'Changes saved'},+ },+ },+ {+ id: 'violating-hidden-replacement',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ transitions: {+ show: {value: 'Changes saved'},+ replace: {hiddenValue: 'Profile updated'},+ },+ },+ {+ id: 'violating-hidden-repeat',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ transitions: {+ show: {value: 'Changes saved'},+ replace: {value: 'Profile updated'},+ repeat: {hiddenValue: 'Changes saved'},+ },+ },+ {+ id: 'violating-stale-clear',+ facts: POLITE_FACTS,+ html: '<div data-a11y-subject role="status"></div>',+ transitions: {+ show: {value: 'Changes saved'},+ replace: {value: 'Profile updated'},+ repeat: {value: 'Changes saved', pulse: true},+ clear: {},+ },+ },+ {+ id: 'violating-named-never-updates',+ facts: NAMED_FACTS,+ html: '<div data-a11y-subject role="status" aria-label=""></div>',+ transitions: {show: {}},+ },+ {+ id: 'violating-moves-focus',+ facts: POLITE_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Save</button><div data-a11y-subject role="status" tabindex="-1"></div>',+ transitions: {+ show: {+ value: 'Changes saved',+ focusSelector: STATUS_MESSAGE_SUBJECT_SELECTOR,+ },+ },+ },+ {+ id: 'violating-progress-role',+ facts: PROGRESS_FACTS,+ html: '<div data-a11y-subject aria-label="Upload progress"></div>',+ },+ {+ id: 'violating-progress-loses-role',+ facts: PROGRESS_FACTS,+ html: '<div data-a11y-subject role="progressbar" aria-label="Upload progress"></div>',+ transitions: {+ progress: {+ attribute: 'aria-valuenow',+ value: '40',+ attributes: {role: 'group'},+ },+ complete: {attribute: 'aria-valuenow', value: '100'},+ },+ },+ {+ id: 'violating-progress-name',+ facts: PROGRESS_FACTS,+ html: '<div data-a11y-subject role="progressbar"></div>',+ },+ {+ id: 'violating-progress-loses-name',+ facts: PROGRESS_FACTS,+ html: '<div data-a11y-subject role="progressbar" aria-label="Upload progress"></div>',+ transitions: {+ progress: {+ attribute: 'aria-valuenow',+ value: '40',+ attributes: {'aria-label': null},+ },+ complete: {attribute: 'aria-valuenow', value: '100'},+ },+ },+ {+ id: 'violating-progress-initial-value',+ facts: PROGRESS_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Start upload</button><div data-a11y-subject role="progressbar" aria-label="Upload progress" aria-valuenow="5"></div>',+ transitions: {+ progress: {attribute: 'aria-valuenow', value: '40'},+ complete: {attribute: 'aria-valuenow', value: '100'},+ },+ },+ {+ id: 'violating-reversed-initial-progress-range',+ facts: REVERSED_INITIAL_PROGRESS_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Start upload</button><div data-a11y-subject role="progressbar" aria-label="Upload progress"></div>',+ },+ {+ id: 'violating-out-of-initial-range-value',+ facts: OUT_OF_INITIAL_RANGE_PROGRESS_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Start upload</button><div data-a11y-subject role="progressbar" aria-label="Upload progress" aria-valuemin="0" aria-valuemax="5" aria-valuenow="10"></div>',+ },+ {+ id: 'violating-reversed-progress-range',+ facts: REVERSED_PROGRESS_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Start upload</button><div data-a11y-subject role="progressbar" aria-label="Upload progress"></div>',+ },+ {+ id: 'violating-out-of-range-progress-value',+ facts: OUT_OF_RANGE_PROGRESS_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Start upload</button><div data-a11y-subject role="progressbar" aria-label="Upload progress"></div>',+ },+ {+ id: 'violating-frozen-progress',+ facts: PROGRESS_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Start upload</button><div data-a11y-subject role="progressbar" aria-label="Upload progress"></div>',+ transitions: {progress: {}, complete: {}},+ },+ {+ id: 'violating-incomplete-progress',+ facts: PROGRESS_FACTS,+ html: '<button data-a11y-relation="focus-anchor">Start upload</button><div data-a11y-subject role="progressbar" aria-label="Upload progress"></div>',+ transitions: {+ progress: {attribute: 'aria-valuenow', value: '40'},+ complete: {attribute: 'aria-valuenow', value: '40'},+ },+ },+];++export const STATUS_MESSAGE_CONFORMING_FIXTURES = [+ 'conforming-polite-channel',+ 'conforming-removable-status',+ 'conforming-assertive-channel',+ 'conforming-named-channel',+ 'conforming-progress',+] as const;++export interface StatusMessageMutation {+ readonly fixture: string;+ /** Semantic detail that proves the intended branch, not a harness failure, failed. */+ readonly failureIncludes: string;+}++export const STATUS_MESSAGE_MUTATIONS: Readonly<+ Record<string, readonly StatusMessageMutation[]>+> = {+ 'status-message.role.exposed': [+ {+ fixture: 'violating-wrong-role',+ failureIncludes: 'not as the declared "status" role',+ },+ {+ fixture: 'violating-loses-role',+ failureIncludes: 'after the "show" transition',+ },+ ],+ 'status-message.channel.exposed': [+ {+ fixture: 'violating-unexposed-channel',+ failureIncludes: 'exposes no live channel at the pre-update boundary',+ },+ {+ fixture: 'violating-wrong-channel',+ failureIncludes: 'not the intended assertive channel',+ },+ {+ fixture: 'violating-loses-channel',+ failureIncludes:+ 'after the "show" transition, not the intended polite channel',+ },+ ],+ 'status-message.region.precedes-update': [+ {+ fixture: 'violating-replaced-on-show',+ failureIncludes:+ 'role=status container was replaced by the "show" update',+ },+ {+ fixture: 'violating-replaced-on-first-update',+ failureIncludes:+ 'role=status container was replaced by the "replace" update',+ },+ ],+ 'status-message.message.text-exposed': [+ {+ fixture: 'violating-missing-message',+ failureIncludes: 'not the complete authored message',+ },+ {+ fixture: 'violating-hidden-message',+ failureIncludes: 'accessibility tree exposes ""',+ },+ {+ fixture: 'violating-wrong-replacement',+ failureIncludes:+ 'after the "replace" transition, not the complete authored message "Profile updated"',+ },+ {+ fixture: 'violating-hidden-replacement',+ failureIncludes:+ 'accessibility tree exposes "" after the "replace" transition',+ },+ {+ fixture: 'violating-hidden-repeat',+ failureIncludes:+ 'accessibility tree exposes "" after the "repeat" transition',+ },+ {+ fixture: 'violating-stale-clear',+ failureIncludes:+ 'after the "clear" transition, not the complete authored message ""',+ },+ ],+ 'status-message.message.name-exposed': [+ {+ fixture: 'violating-named-never-updates',+ failureIncludes: 'not "Changes saved"',+ },+ ],+ 'status-message.region.atomic': [+ {+ fixture: 'violating-non-atomic',+ failureIncludes:+ 'not expose this status region as atomic at the pre-update boundary',+ },+ {+ fixture: 'violating-loses-atomicity',+ failureIncludes:+ 'not expose this status region as atomic after the "show" transition',+ },+ ],+ 'status-message.focus.unchanged': [+ {+ fixture: 'violating-moves-focus',+ failureIncludes: 'status transition moved focus away',+ },+ ],+ 'status-message.progress.role-exposed': [+ {+ fixture: 'violating-progress-role',+ failureIncludes: 'not as a progress bar',+ },+ {+ fixture: 'violating-progress-loses-role',+ failureIncludes: 'after the "progress" transition, not as a progress bar',+ },+ ],+ 'status-message.progress.name-exposed': [+ {+ fixture: 'violating-progress-name',+ failureIncludes: 'browser computes no accessible name',+ },+ {+ fixture: 'violating-progress-loses-name',+ failureIncludes: 'after the "progress" transition',+ },+ ],+ 'status-message.progress.values-exposed': [+ {+ fixture: 'violating-reversed-initial-progress-range',+ failureIncludes: 'reversed initial progress range 5..0',+ },+ {+ fixture: 'violating-out-of-initial-range-value',+ failureIncludes: 'initial progress value 10 outside 0..5',+ },+ {+ fixture: 'violating-reversed-progress-range',+ failureIncludes: 'binding declares a reversed progress range 100..0',+ },+ {+ fixture: 'violating-out-of-range-progress-value',+ failureIncludes: 'progress value 120 outside 0..100',+ },+ {+ fixture: 'violating-progress-initial-value',+ failureIncludes: 'initial progress as value=5',+ },+ {+ fixture: 'violating-frozen-progress',+ failureIncludes: 'browser exposes progress as value=',+ },+ {+ fixture: 'violating-incomplete-progress',+ failureIncludes: 'browser exposes completion as value=',+ },+ ],+};++export function statusMessageFixture(id: string): StatusMessageFixture {+ const found = STATUS_MESSAGE_FIXTURES.find(candidate => candidate.id === id);+ if (found == null) {+ throw new Error(`unknown status-message fixture "${id}"`);+ }+ return found;+}diff --git a/internal/a11y-spec/src/patterns/status-message.jsdom.test.ts b/internal/a11y-spec/src/patterns/status-message.jsdom.test.tsnew file mode 100644index 0000000000..8c948c1308--- /dev/null+++ b/internal/a11y-spec/src/patterns/status-message.jsdom.test.ts@@ -0,0 +1,200 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file status-message.jsdom.test.ts+ * @input Uses plain-HTML status fixtures and the jsdom harness+ * @output Positive and negative proof for every DOM-owned status-message outcome+ * @position Fast self-test of the contract, not a component binding+ */++import {afterEach, describe, expect, it} from 'vitest';+import {checkAccessibilitySpec, type ExpectationResult} from '../check';+import {+ describeExpectation,+ requiredLayers,+ unansweredDimensions,+} from '../contract';+import {JSDOM_OBSERVES, createJsdomHarness} from '../harness/jsdom';+import {STATUS_MESSAGE_PATTERN} from './status-message';+import {+ STATUS_MESSAGE_CONFORMING_FIXTURES,+ STATUS_MESSAGE_MUTATIONS,+ STATUS_MESSAGE_SUBJECT_SELECTOR,+ statusMessageFixture,+ type StatusMessageFixture,+} from './status-message.fixtures';++const observableHere = STATUS_MESSAGE_PATTERN.expectations.filter(expectation =>+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),+);++afterEach(() => {+ document.body.replaceChildren();+});++async function resultFor(+ target: StatusMessageFixture,+ expectation: string,+): Promise<ExpectationResult> {+ const container = document.createElement('div');+ document.body.append(container);+ let subjectElement: Element | null = null;+ const result = await checkAccessibilitySpec({+ spec: STATUS_MESSAGE_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ only: [expectation],+ mount: async () => {+ container.innerHTML = target.html;+ const subject = container.querySelector(STATUS_MESSAGE_SUBJECT_SELECTOR);+ if (subject == null) {+ throw new Error(`fixture "${target.id}" marks no subject element`);+ }+ subjectElement = subject;+ return createJsdomHarness({subject});+ },+ transition: async name => {+ const transition =+ target.transitions?.[name as keyof typeof target.transitions];+ if (subjectElement == null || transition == null) {+ throw new Error(+ `fixture "${target.id}" supplies no "${name}" transition`,+ );+ }+ if (transition.removeSubject === true) {+ subjectElement.remove();+ return;+ }+ if (transition.replaceSubject === true) {+ const replacement = subjectElement.cloneNode(false) as Element;+ if (transition.attribute != null) {+ if (transition.value == null) {+ replacement.removeAttribute(transition.attribute);+ } else {+ replacement.setAttribute(transition.attribute, transition.value);+ }+ } else if (transition.value !== undefined) {+ replacement.textContent = transition.value;+ }+ subjectElement.replaceWith(replacement);+ return;+ }+ if (transition.pulse === true) {+ if (transition.attribute == null) {+ subjectElement.textContent = '';+ } else {+ subjectElement.setAttribute(transition.attribute, '');+ }+ await Promise.resolve();+ }+ if (transition.hiddenValue !== undefined) {+ const hidden = subjectElement.ownerDocument.createElement('span');+ hidden.setAttribute('aria-hidden', 'true');+ hidden.textContent = transition.hiddenValue;+ subjectElement.replaceChildren(hidden);+ }+ if (transition.attributes != null) {+ for (const [name, value] of Object.entries(transition.attributes)) {+ if (value == null) {+ subjectElement.removeAttribute(name);+ } else {+ subjectElement.setAttribute(name, value);+ }+ }+ }+ if (transition.value !== undefined) {+ if (transition.attribute == null) {+ subjectElement.textContent = transition.value;+ } else if (transition.value == null) {+ subjectElement.removeAttribute(transition.attribute);+ } else {+ subjectElement.setAttribute(transition.attribute, transition.value);+ }+ await Promise.resolve();+ }+ },+ unmount: () => {+ container.innerHTML = '';+ },+ });+ const found = result.results.find(+ candidate => candidate.expectation === expectation,+ );+ if (found == null) {+ throw new Error(`no result for ${expectation}`);+ }+ return found;+}++describe('status-message contract — completeness', () => {+ it('answers every checklist dimension', () => {+ expect(unansweredDimensions(STATUS_MESSAGE_PATTERN)).toEqual([]);+ });++ it('gives every expectation at least one deliberately violating fixture', () => {+ expect(+ STATUS_MESSAGE_PATTERN.expectations+ .filter(+ expectation =>+ (STATUS_MESSAGE_MUTATIONS[expectation.id] ?? []).length === 0,+ )+ .map(expectation => expectation.id),+ ).toEqual([]);+ });++ it('has no orphaned mutation ids or fixture ids', () => {+ const expectationIds = new Set(+ STATUS_MESSAGE_PATTERN.expectations.map(expectation => expectation.id),+ );+ expect(+ Object.keys(STATUS_MESSAGE_MUTATIONS).filter(+ id => !expectationIds.has(id),+ ),+ ).toEqual([]);+ for (const mutations of Object.values(STATUS_MESSAGE_MUTATIONS)) {+ for (const mutation of mutations) {+ expect(() => statusMessageFixture(mutation.fixture)).not.toThrow();+ }+ }+ });+});++describe.each(observableHere.map(expectation => [expectation] as const))(+ '%s',+ expectation => {+ it.each(STATUS_MESSAGE_CONFORMING_FIXTURES.map(id => [id] as const))(+ 'passes against %s (or does not apply)',+ async id => {+ const result = await resultFor(+ statusMessageFixture(id),+ expectation.id,+ );+ expect(+ ['pass', 'not-applicable'],+ `${describeExpectation(expectation)}: ${result.detail ?? ''}`,+ ).toContain(result.status);+ },+ );++ it.each(+ (STATUS_MESSAGE_MUTATIONS[expectation.id] ?? []).map(+ mutation => [mutation.fixture, mutation.failureIncludes] as const,+ ),+ )(+ 'fails against %s with the intended semantic detail',+ async (id, failureIncludes) => {+ const result = await resultFor(+ statusMessageFixture(id),+ expectation.id,+ );+ expect(+ result.status,+ `${describeExpectation(expectation)}: ${result.detail ?? ''}`,+ ).toBe('fail');+ expect(result.detail).toContain(failureIncludes);+ },+ );+ },+);diff --git a/internal/a11y-spec/src/patterns/status-message.ts b/internal/a11y-spec/src/patterns/status-message.tsnew file mode 100644index 0000000000..5f3bf3bb4f--- /dev/null+++ b/internal/a11y-spec/src/patterns/status-message.ts@@ -0,0 +1,808 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file status-message.ts+ * @input Uses the shared accessibility contract vocabulary+ * @output STATUS_MESSAGE_PATTERN and the facts a binding declares for one status surface+ * @position Reusable WCAG 2.2 status-message contract+ */++import {+ definePattern,+ type PatternContract,+ type WcagCriterion,+ type WebStandardRequirement,+} from '../contract';++const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';+const ARIA = 'https://www.w3.org/TR/wai-aria-1.2';++const WCAG_4_1_2: WcagCriterion = {+ standard: 'wcag',+ id: '4.1.2',+ name: 'Name, Role, Value',+ level: 'A',+ url: `${UNDERSTANDING}/name-role-value.html`,+};++const WCAG_4_1_3: WcagCriterion = {+ standard: 'wcag',+ id: '4.1.3',+ name: 'Status Messages',+ level: 'AA',+ url: `${UNDERSTANDING}/status-messages.html`,+};++const ARIA_STATUS: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2 status role',+ requirement:+ 'A status is a type of live region whose content is advisory information for the user but is not important enough to justify an alert.',+ url: `${ARIA}/#status`,+};++const ARIA_ALERT: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2 alert role',+ requirement:+ 'Alerts are assertive live regions, which means they cause immediate notification for assistive technology users.',+ url: `${ARIA}/#alert`,+};++const ARIA_STATUS_ATOMIC: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2 status role',+ requirement: 'The implicit value of aria-atomic for status is true.',+ url: `${ARIA}/#status`,+};++const ARIA_ALERT_ATOMIC: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2 alert role',+ requirement: 'The implicit value of aria-atomic for alert is true.',+ url: `${ARIA}/#alert`,+};++const WCAG_ARIA22: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WCAG 2.2 Technique ARIA22',+ requirement:+ 'The status container must be present in the DOM when the status message is displayed; the message is then added to or updated inside that container.',+ url: 'https://www.w3.org/WAI/WCAG22/Techniques/aria/ARIA22',+};++const ARIA_PROGRESSBAR: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2 progressbar role',+ requirement:+ 'A progressbar is an element that displays the progress status for tasks that take a long time.',+ url: `${ARIA}/#progressbar`,+};++const ARIA_VALUE_MIN: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2 aria-valuemin property',+ requirement:+ 'Authors MUST ensure the value of aria-valuemin is less than or equal to the value of aria-valuemax.',+ url: `${ARIA}/#aria-valuemin`,+};++const ARIA_VALUE_NOW: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2 aria-valuenow property',+ requirement:+ 'Authors MUST ensure aria-valuenow is greater than or equal to aria-valuemin and less than or equal to aria-valuemax.',+ url: `${ARIA}/#aria-valuenow`,+};++export type StatusMessageTransitionName =+ 'show' | 'replace' | 'clear' | 'repeat' | 'progress' | 'complete';++export type StatusMessageStateFacts =+ | {+ readonly kind: 'live-region';+ readonly role: 'status' | 'alert' | null;+ readonly politeness: 'polite' | 'assertive';+ readonly messageSource: 'text' | 'accessible-name';+ /** Message exposed before the binding performs any transition. */+ readonly initialMessage: string;+ readonly message: string;+ readonly replacement: string;+ /** Public message transitions to observe; clear may remove the semantic subject. */+ readonly semanticTransitions: readonly StatusMessageTransitionName[];+ }+ | {+ readonly kind: 'progressbar';+ readonly politeness: null;+ readonly name: string;+ readonly initialValue: number | null;+ readonly initialMin: number;+ readonly initialMax: number;+ readonly progressValue: number;+ readonly completionValue: number;+ readonly minValue: number;+ readonly maxValue: number;+ };++const LIVE_REGION = {+ condition: 'this binding uses a live region to expose the status message',+ test: (facts: StatusMessageStateFacts) => facts.kind === 'live-region',+};++const ROLE_LIVE_REGION = {+ condition: 'this binding uses a status or alert role for its live region',+ test: (facts: StatusMessageStateFacts) =>+ facts.kind === 'live-region' && facts.role != null,+};++const LIVE_TEXT_REGION = {+ condition:+ 'this binding exposes status text inside a live region that it updates',+ test: (facts: StatusMessageStateFacts) =>+ facts.kind === 'live-region' && facts.messageSource === 'text',+};++const PROGRESSBAR = {+ condition: 'this binding exposes the status as a progress bar',+ test: (facts: StatusMessageStateFacts) => facts.kind === 'progressbar',+};++function normalizeText(value: string): string {+ return value.replace(/\s+/g, ' ').trim();+}++function messageAfterTransition(+ facts: Extract<StatusMessageStateFacts, {kind: 'live-region'}>,+ transition: StatusMessageTransitionName,+): string {+ switch (transition) {+ case 'show':+ case 'repeat':+ return facts.message;+ case 'replace':+ return facts.replacement;+ case 'clear':+ return '';+ case 'progress':+ case 'complete':+ throw new Error(+ `live-region facts cannot use the ${JSON.stringify(transition)} transition`,+ );+ }+}++export const STATUS_MESSAGE_PATTERN: PatternContract<StatusMessageStateFacts> =+ definePattern<StatusMessageStateFacts>({+ pattern: 'status-message',+ url: `${UNDERSTANDING}/status-messages.html`,+ scope:+ 'One status update that is programmatically exposed without moving focus; announcement output remains real-AT evidence.',+ expectations: [+ {+ id: 'status-message.role.exposed',+ outcome:+ 'The browser exposes the live region through the status or alert role selected by the binding.',+ sources: [WCAG_4_1_3, WCAG_4_1_2, ARIA_STATUS, ARIA_ALERT],+ covers: ['4.1.3-status-messages', '4.1.2-name-role-value'],+ appliesWhen: ROLE_LIVE_REGION,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts, transition}) => {+ if (facts.kind !== 'live-region' || facts.role == null) {+ return;+ }+ const assertRole = async (phase: string): Promise<void> => {+ const {role} = await subject.computed();+ if (role !== facts.role) {+ throw new Error(+ `the browser exposes this ${facts.politeness} status as ${JSON.stringify(role)} ${phase}, not as the declared ${JSON.stringify(facts.role)} role`,+ );+ }+ };+ await assertRole('at the pre-update boundary');+ for (const name of facts.semanticTransitions) {+ await transition(name);+ if (name === 'clear' && !(await subject.currentExists())) {+ continue;+ }+ await assertRole(`after the ${JSON.stringify(name)} transition`);+ }+ },+ },+ {+ id: 'status-message.channel.exposed',+ outcome:+ 'The browser exposes the status through the intended polite or assertive live channel before and after its public updates.',+ sources: [WCAG_4_1_3, ARIA_STATUS, ARIA_ALERT],+ covers: ['4.1.3-status-messages'],+ appliesWhen: LIVE_REGION,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts, transition}) => {+ if (facts.kind !== 'live-region') {+ return;+ }+ const assertChannel = async (phase: string): Promise<void> => {+ const {live} = await subject.computed();+ if (live !== facts.politeness) {+ throw new Error(+ live == null+ ? `the browser exposes no live channel ${phase} for this ${facts.politeness} status message, so assistive technology has no programmatic status update to present without moving focus`+ : `the browser exposes this status message through the ${live} channel ${phase}, not the intended ${facts.politeness} channel`,+ );+ }+ };+ await assertChannel('at the pre-update boundary');+ for (const name of facts.semanticTransitions) {+ await transition(name);+ if (name === 'clear' && !(await subject.currentExists())) {+ continue;+ }+ await assertChannel(`after the ${JSON.stringify(name)} transition`);+ }+ },+ },+ {+ id: 'status-message.region.precedes-update',+ outcome:+ 'The binding follows the ARIA22 reliability technique: the role=status container exists before a tested message update occurs in that same node.',+ sources: [WCAG_ARIA22, WCAG_4_1_3, ARIA_STATUS],+ wcagOutcome:+ 'Status information can be programmatically determined without moving focus.',+ covers: ['4.1.3-status-messages'],+ appliesWhen: {+ condition:+ 'this binding exposes text through the status role; alerts and accessible-name-only states use different semantics',+ test: facts =>+ facts.kind === 'live-region' &&+ facts.role === 'status' &&+ facts.messageSource === 'text',+ },+ evidenceLayer: 'dom',+ enforcement: 'advisory',+ advisoryBecause:+ 'ARIA22 is a sufficient WCAG technique, not the only conforming implementation; real assistive-technology evidence owns whether another lifecycle is reliably announced.',+ run: async ({subject, facts, transition}) => {+ if (+ facts.kind !== 'live-region' ||+ facts.role !== 'status' ||+ facts.messageSource !== 'text'+ ) {+ return;+ }+ const firstUpdate = facts.semanticTransitions[0];+ if (firstUpdate == null) {+ throw new Error(+ 'the binding declares no message transition for the ARIA22 lifecycle check',+ );+ }+ await subject.isConnected();+ await transition(firstUpdate);+ if (!(await subject.isConnected())) {+ throw new Error(+ `the role=status container was replaced by the ${JSON.stringify(firstUpdate)} update instead of predating and receiving that message`,+ );+ }+ },+ },+ {+ id: 'status-message.message.text-exposed',+ outcome:+ 'The complete status text remains in the browser accessibility subtree before and after the binding’s public update.',+ sources: [WCAG_4_1_3, ARIA_STATUS, ARIA_ALERT],+ covers: ['4.1.3-status-messages'],+ appliesWhen: LIVE_TEXT_REGION,+ evidenceLayer: 'accessibility-tree',+ alsoNeeds: ['dom'],+ enforcement: 'required',+ run: async ({subject, facts, transition}) => {+ if (facts.kind !== 'live-region' || facts.messageSource !== 'text') {+ return;+ }+ const assertMessage = async (+ expected: string,+ phase: string,+ ): Promise<void> => {+ const authored = normalizeText(await subject.textContent());+ if (authored !== normalizeText(expected)) {+ throw new Error(+ `the live region contains ${JSON.stringify(authored)} ${phase}, not the complete authored message ${JSON.stringify(normalizeText(expected))}`,+ );+ }+ const exposed = normalizeText(+ (await subject.computed()).accessibleText,+ );+ if (exposed !== normalizeText(expected)) {+ throw new Error(+ `the accessibility tree exposes ${JSON.stringify(exposed)} ${phase}, not the complete status text ${JSON.stringify(normalizeText(expected))}`,+ );+ }+ };+ await assertMessage(+ facts.initialMessage,+ 'at the pre-update boundary',+ );+ for (const name of facts.semanticTransitions) {+ await transition(name);+ if (name === 'clear' && !(await subject.currentExists())) {+ continue;+ }+ await assertMessage(+ messageAfterTransition(facts, name),+ `after the ${JSON.stringify(name)} transition`,+ );+ }+ },+ },+ {+ id: 'status-message.message.name-exposed',+ outcome:+ 'The browser exposes the complete status as the live region’s accessible name when that is the chosen message channel.',+ sources: [WCAG_4_1_3, WCAG_4_1_2],+ covers: ['4.1.3-status-messages', '4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'this binding exposes the status as the live region accessible name',+ test: facts =>+ facts.kind === 'live-region' &&+ facts.messageSource === 'accessible-name',+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts, transition}) => {+ if (+ facts.kind !== 'live-region' ||+ facts.messageSource !== 'accessible-name'+ ) {+ return;+ }+ const assertName = async (+ expected: string,+ phase: string,+ ): Promise<void> => {+ const name = (await subject.computed()).name.trim();+ if (name !== expected.trim()) {+ throw new Error(+ `the browser computes the live region name as ${JSON.stringify(name)} ${phase}, not ${JSON.stringify(expected.trim())}`,+ );+ }+ };+ await assertName(facts.initialMessage, 'at the pre-update boundary');+ for (const name of facts.semanticTransitions) {+ await transition(name);+ if (name === 'clear' && !(await subject.currentExists())) {+ continue;+ }+ await assertName(+ messageAfterTransition(facts, name),+ `after the ${JSON.stringify(name)} transition`,+ );+ }+ },+ },+ {+ id: 'status-message.region.atomic',+ outcome:+ 'The browser exposes the status or alert role’s implicit whole-region atomicity before and after public updates.',+ sources: [ARIA_STATUS_ATOMIC, ARIA_ALERT_ATOMIC, WCAG_4_1_3],+ wcagOutcome:+ 'Status information can be programmatically determined without moving focus.',+ covers: ['4.1.3-status-messages'],+ appliesWhen: ROLE_LIVE_REGION,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'advisory',+ advisoryBecause:+ 'WAI-ARIA defines an overridable implicit default; only real assistive-technology evidence can establish whole-message presentation.',+ run: async ({subject, facts, transition}) => {+ if (facts.kind !== 'live-region' || facts.role == null) {+ return;+ }+ const assertAtomic = async (phase: string): Promise<void> => {+ const {atomic} = await subject.computed();+ if (atomic !== true) {+ throw new Error(+ `the browser does not expose this ${facts.role} region as atomic ${phase}, so a partial text mutation can omit the context needed to understand the status`,+ );+ }+ };+ await assertAtomic('at the pre-update boundary');+ for (const name of facts.semanticTransitions) {+ await transition(name);+ if (name === 'clear' && !(await subject.currentExists())) {+ continue;+ }+ await assertAtomic(`after the ${JSON.stringify(name)} transition`);+ }+ },+ },+ {+ id: 'status-message.focus.unchanged',+ outcome:+ 'The status update leaves focus on the user’s current control instead of moving focus to the message.',+ sources: [WCAG_4_1_3],+ covers: [+ '4.1.3-status-messages',+ '2.4.3-focus-order',+ '3.2.2-on-input',+ ],+ appliesWhen: {+ condition:+ 'the binding produces a status update without a context change',+ test: () => true,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, facts, transition}) => {+ const anchor = await harness.related('focus-anchor');+ await anchor.focus();+ if (!(await anchor.isFocused())) {+ throw new Error(+ 'the binding focus anchor could not receive focus before the status transition, so this scenario does not prove the no-focus-change requirement',+ );+ }+ const transitions: readonly StatusMessageTransitionName[] =+ facts.kind === 'live-region'+ ? facts.semanticTransitions+ : ['progress', 'complete'];+ for (const name of transitions) {+ await transition(name);+ if (!(await anchor.isFocused())) {+ throw new Error(+ `the ${JSON.stringify(name)} status transition moved focus away from the user’s current control instead of remaining passive`,+ );+ }+ }+ },+ },+ {+ id: 'status-message.progress.role-exposed',+ outcome:+ 'The browser exposes ongoing progress as a progress bar rather than as an unidentified visual change.',+ sources: [WCAG_4_1_3, WCAG_4_1_2, ARIA_PROGRESSBAR],+ covers: ['4.1.3-status-messages', '4.1.2-name-role-value'],+ appliesWhen: PROGRESSBAR,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts, transition}) => {+ if (facts.kind !== 'progressbar') {+ return;+ }+ const assertRole = async (phase: string): Promise<void> => {+ const {role} = await subject.computed();+ if (role !== 'progressbar') {+ throw new Error(+ role == null+ ? `the browser exposes no role for this progress status ${phase}, so assistive technology cannot identify the changing value as progress`+ : `the browser exposes this progress status as ${JSON.stringify(role)} ${phase}, not as a progress bar`,+ );+ }+ };+ await assertRole('at the pre-update boundary');+ await transition('progress');+ await assertRole('after the "progress" transition');+ await transition('complete');+ await assertRole('after the "complete" transition');+ },+ },+ {+ id: 'status-message.progress.name-exposed',+ outcome:+ 'The progress status names the operation whose progress is changing.',+ sources: [WCAG_4_1_2, ARIA_PROGRESSBAR],+ covers: ['4.1.2-name-role-value', '2.4.6-headings-and-labels'],+ appliesWhen: PROGRESSBAR,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts, transition}) => {+ if (facts.kind !== 'progressbar') {+ return;+ }+ const assertName = async (phase: string): Promise<void> => {+ const {name} = await subject.computed();+ if (name.trim() === '') {+ throw new Error(+ `the browser computes no accessible name for this progress bar ${phase}, so the changing value does not say which operation it belongs to`,+ );+ }+ if (name.trim() !== facts.name.trim()) {+ throw new Error(+ `the browser computes the progress name as ${JSON.stringify(name.trim())} ${phase}, not the binding’s declared operation ${JSON.stringify(facts.name.trim())}`,+ );+ }+ };+ await assertName('at the pre-update boundary');+ await transition('progress');+ await assertName('after the "progress" transition');+ await transition('complete');+ await assertName('after the "complete" transition');+ },+ },+ {+ id: 'status-message.progress.values-exposed',+ outcome:+ 'The progress bar exposes a valid declared range and its starting, in-progress, and completion values.',+ sources: [+ WCAG_4_1_2,+ ARIA_VALUE_MIN,+ ARIA_VALUE_NOW,+ ARIA_PROGRESSBAR,+ WCAG_4_1_3,+ ],+ wcagOutcome:+ 'Progress status and its current value can be programmatically determined without moving focus.',+ covers: ['4.1.3-status-messages', '4.1.2-name-role-value'],+ appliesWhen: PROGRESSBAR,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts, transition}) => {+ if (facts.kind !== 'progressbar') {+ return;+ }+ if (facts.initialMin > facts.initialMax) {+ throw new Error(+ `the binding declares a reversed initial progress range ${facts.initialMin}..${facts.initialMax}`,+ );+ }+ if (+ facts.initialValue != null &&+ (facts.initialValue < facts.initialMin ||+ facts.initialValue > facts.initialMax)+ ) {+ throw new Error(+ `the binding declares initial progress value ${facts.initialValue} outside ${facts.initialMin}..${facts.initialMax}`,+ );+ }+ if (facts.minValue > facts.maxValue) {+ throw new Error(+ `the binding declares a reversed progress range ${facts.minValue}..${facts.maxValue}`,+ );+ }+ for (const [phase, value] of [+ ['progress', facts.progressValue],+ ['completion', facts.completionValue],+ ] as const) {+ if (value < facts.minValue || value > facts.maxValue) {+ throw new Error(+ `the binding declares ${phase} progress value ${value} outside ${facts.minValue}..${facts.maxValue}`,+ );+ }+ }+ const initial = await subject.computed();+ if (+ initial.rangeValue !== facts.initialValue ||+ initial.rangeMin !== facts.initialMin ||+ initial.rangeMax !== facts.initialMax+ ) {+ throw new Error(+ `the browser exposes initial progress as value=${String(initial.rangeValue)}, min=${String(initial.rangeMin)}, max=${String(initial.rangeMax)} instead of value=${String(facts.initialValue)}, min=${String(facts.initialMin)}, max=${String(facts.initialMax)}`,+ );+ }+ await transition('progress');+ const progressing = await subject.computed();+ if (+ progressing.rangeValue !== facts.progressValue ||+ progressing.rangeMin !== facts.minValue ||+ progressing.rangeMax !== facts.maxValue+ ) {+ throw new Error(+ `the browser exposes progress as value=${String(progressing.rangeValue)}, min=${String(progressing.rangeMin)}, max=${String(progressing.rangeMax)} instead of ${facts.progressValue} in ${facts.minValue}..${facts.maxValue}`,+ );+ }+ await transition('complete');+ const completed = await subject.computed();+ if (+ completed.rangeValue !== facts.completionValue ||+ completed.rangeMin !== facts.minValue ||+ completed.rangeMax !== facts.maxValue+ ) {+ throw new Error(+ `the browser exposes completion as value=${String(completed.rangeValue)}, min=${String(completed.rangeMin)}, max=${String(completed.rangeMax)} instead of ${facts.completionValue} in ${facts.minValue}..${facts.maxValue}`,+ );+ }+ },+ },+ ],+ exemptions: {+ '1.1.1-non-text-content': {+ owner: 'the binding component and caller content',+ verifiedBy:+ "the component's own decorative-icon and text-alternative tests plus the repository axe audit",+ reason:+ 'This contract observes the status surface. A component or caller decides whether an icon carries information and supplies its alternative or hides it as redundant.',+ },+ '1.3.1-info-and-relationships': {+ owner: 'the binding component and composing feature',+ verifiedBy:+ "the component's relationship tests and integration review of any control or result the message describes",+ reason:+ 'A live channel exposes the update, but the relationship between that update and nearby controls or results belongs to the composition that creates them.',+ },+ '1.3.2-meaningful-sequence': {+ owner: 'the composing page',+ verifiedBy: 'page-level DOM-order and reading-order review',+ reason:+ 'The order of a status surface among surrounding content is decided by the page, not by one message in isolation.',+ },+ '1.3.5-identify-input-purpose': {+ owner: 'the composing form',+ verifiedBy:+ 'form review for user-information inputs and their autocomplete purposes',+ reason:+ 'A status message reports an outcome and does not collect user information.',+ },+ '1.4.1-use-of-color': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the component's non-color-cue tests and the repository visual review",+ reason:+ 'Color and any redundant visible icon are painted binding details that this semantic contract cannot observe.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'the binding component and theme',+ verifiedBy:+ 'the repository axe audit over component stories plus rendered visual review',+ reason:+ 'Text contrast depends on resolved foreground, backdrop, theme, and state pixels.',+ },+ '1.4.11-non-text-contrast': {+ owner: 'the binding component and theme',+ verifiedBy:+ 'the repository axe audit plus rendered visual review of meaningful indicators and progress graphics',+ reason:+ 'The contrast of an icon, progress fill, track, or boundary is a rendered-pixel result outside this semantic contract.',+ },+ '2.1.1-keyboard': {+ owner: 'the binding component and composing page',+ verifiedBy:+ "the component's own tests for any controls placed beside or inside the status",+ reason:+ 'The status surface is passive. Any dismiss, retry, or related action keeps its own button or link contract.',+ },+ '2.1.2-no-keyboard-trap': {+ owner: 'the binding component and composing page',+ verifiedBy:+ 'keyboard review of any interactive content composed with the status',+ reason:+ 'The status surface neither accepts nor traps focus; interactive descendants remain separate component contracts.',+ },+ '2.4.2-page-titled': {+ owner: 'the page',+ verifiedBy: 'page-level review',+ reason:+ 'A component status update cannot provide or evaluate the document title.',+ },+ '2.4.3-focus-order': {+ owner: 'the composing page',+ verifiedBy:+ 'page-level focus-order review; this contract proves only that producing the status leaves the current focus unchanged',+ reason:+ 'The order of every focusable element around the status is a page property.',+ coversRemainderOnly: true,+ },+ '2.4.4-link-purpose': {+ owner: 'caller content and the link pattern',+ verifiedBy:+ 'review of any link composed into or beside a visible status message',+ reason:+ 'A status surface is not a link, and any linked recovery or follow-up action keeps its own contract.',+ },+ '2.4.6-headings-and-labels': {+ owner: 'caller content and the binding component',+ verifiedBy:+ 'content review of the status wording; this contract proves only that a progress status has a name',+ reason:+ 'Whether the supplied wording describes the operation or outcome well is a content judgement.',+ coversRemainderOnly: true,+ },+ '2.4.7-focus-visible': {+ owner: 'the currently focused control and its component',+ verifiedBy:+ 'the focused component contract and rendered focus-indicator review',+ reason:+ 'The status must not take focus. The control that keeps focus owns its visible indicator.',+ },+ '2.4.11-focus-not-obscured': {+ owner: 'the composing page and overlay system',+ verifiedBy: 'page-level and overlay visual review',+ reason:+ 'Whether a newly rendered status covers the focused control depends on page layout and layering.',+ },+ '2.5.2-pointer-cancellation': {+ owner: 'any interactive control composed with the status',+ verifiedBy: "that control's pointer interaction contract",+ reason:+ 'The status surface is passive and performs no single-pointer action.',+ },+ '2.5.3-label-in-name': {+ owner: 'interactive controls composed with the status',+ verifiedBy: "each control's visible-label and accessible-name contract",+ reason:+ 'A passive status message is not a speech-input target. A related action remains a separate button or link.',+ },+ '2.5.8-target-size': {+ owner: 'interactive controls composed with the status and the page',+ verifiedBy:+ 'the repository target-size audit over rendered controls and their neighbours',+ reason:+ 'The status surface has no pointer target; related actions keep their own geometry.',+ },+ '3.1.1-language-of-page': {+ owner: 'the page',+ verifiedBy: 'page-level language review',+ reason:+ 'A component status update cannot set or verify the document language.',+ },+ '3.2.2-on-input': {+ owner: 'the caller that causes the status update',+ verifiedBy:+ 'integration review of any navigation, viewport, or meaning change caused by the caller',+ reason:+ 'This contract proves that the status itself does not move focus. Any other context change comes from the action that produced it.',+ coversRemainderOnly: true,+ },+ '3.2.4-consistent-identification': {+ owner: 'the design system',+ verifiedBy:+ 'this shared contract and review of every component binding to it',+ reason:+ 'Consistency is a property of the complete set of status-message adopters, not one binding state.',+ },+ '3.3.1-error-identification': {+ owner: 'the field component and caller content',+ verifiedBy:+ "the field's error-state and textual-identification tests plus form review",+ reason:+ 'This contract can expose an error message through an assertive channel, but the field owner decides which input is in error and whether the text identifies it.',+ },+ '3.3.2-labels-or-instructions': {+ owner: 'the composing form and caller content',+ verifiedBy: 'form-level review of labels and instructions',+ reason:+ 'A status message reports an outcome; it does not provide the persistent label or instructions for an input.',+ },+ '4.1.2-name-role-value': {+ owner: 'the binding component',+ verifiedBy:+ "the component's own semantic contract for states outside the progress status represented here",+ reason:+ 'This pattern encodes the progressbar role, name, and value updates. Other component state and value semantics remain with each adopted component pattern.',+ coversRemainderOnly: true,+ },+ '4.1.3-status-messages': {+ owner: 'the assistive-technology verification record, spec:AST-009',+ verifiedBy:+ 'the named real-AT/browser matrix and durable receipts required by AST-009 when a change claims spoken or braille output, order, timing, repetition, or omission',+ reason:+ 'This contract proves DOM lifecycle, browser exposure, and focus preservation only. It does not claim what assistive technology announces.',+ coversRemainderOnly: true,+ },+ 'apg-interaction': {+ owner: 'no adopted APG widget pattern for status messages',+ verifiedBy:+ 'WCAG 2.2 Status Messages and WAI-ARIA status, alert, and progressbar semantics cited by this contract',+ reason:+ 'No current Astryx record adopts an APG widget interaction model for this passive status-message pattern, so the contract does not import one.',+ },+ 'forced-colors': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the component's forced-colors tests plus rendered Windows High Contrast review",+ reason:+ 'Forced-color paint is outside the DOM and accessibility-tree observations in this contract.',+ },+ 'reduced-motion': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the component's reduced-motion source tests and rendered motion review",+ reason:+ 'Spinner, typing, progress, and toast animation are visual timing behavior, not status-message semantics.',+ },+ 'at-facing-strings': {+ owner: 'the binding component and caller content',+ verifiedBy:+ 'the repository i18n catalog check plus source review of generated and caller-supplied status strings',+ reason:+ 'The shared contract receives rendered messages and cannot tell whether their source was translated. Each component owns generated strings; callers own supplied content.',+ },+ },+ });diff --git a/packages/core/src/Chat/ChatSystemMessage.test.tsx b/packages/core/src/Chat/ChatSystemMessage.test.tsxindex a9665e2a6a..d48f0ca001 100644--- a/packages/core/src/Chat/ChatSystemMessage.test.tsx+++ b/packages/core/src/Chat/ChatSystemMessage.test.tsx@@ -10,12 +10,6 @@ describe('ChatSystemMessage', () => {expect(screen.getByText('Conversation started')).toBeTruthy();});- it('has role="status"', () => {- render(<ChatSystemMessage data-testid="sys">Notice</ChatSystemMessage>);- const el = screen.getByTestId('sys');- expect(el.getAttribute('role')).toBe('status');- });-it('renders default variant without divider lines', () => {const {container} = render(<ChatSystemMessage>Hello</ChatSystemMessage>);// Divider lines have aria-hidden, so check there are none@@ -57,7 +51,7 @@ describe('ChatSystemMessage', () => {expect(screen.getByTestId('my-sys')).toBeTruthy();});- it('forwards rest props (data-*, id) while keeping its own role', () => {+ it('forwards rest props (data-*, id)', () => {render(<ChatSystemMessage data-testid="sys" data-custom="x" id="sys-1">Hello@@ -66,7 +60,6 @@ describe('ChatSystemMessage', () => {const el = screen.getByTestId('sys');expect(el).toHaveAttribute('data-custom', 'x');expect(el).toHaveAttribute('id', 'sys-1');- expect(el.getAttribute('role')).toBe('status');});it('forwards rest props in the divider variant', () => {@@ -77,6 +70,6 @@ describe('ChatSystemMessage', () => {);const el = screen.getByTestId('sys');expect(el).toHaveAttribute('data-custom', 'x');- expect(el.getAttribute('role')).toBe('status');+ expect(el).toHaveAttribute('role', 'status');});});diff --git a/packages/core/src/FieldStatus/FieldStatus.spec.md b/packages/core/src/FieldStatus/FieldStatus.spec.mdindex 1677623e71..4a73e5c7e0 100644--- a/packages/core/src/FieldStatus/FieldStatus.spec.md+++ b/packages/core/src/FieldStatus/FieldStatus.spec.md@@ -13,6 +13,8 @@ review_triggers: [public-api, behavior, theming, accessibility]verified_by:[packages/core/src/FieldStatus/FieldStatus.test.tsx,+ packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.test.tsx,+ packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.chromium.spec.ts,scripts/check-knowledge.mjs,]modules: []@@ -20,7 +22,7 @@ families: []design_specs: []architecture: [architecture:component-theming-surface]contributing: []-system_specs: []+system_specs: [spec:AST-009, spec:AST-020, spec:AST-021]---# FieldStatus component contract@@ -116,23 +118,28 @@ intentional decision.### Performance and resources-- **PR1 — Announcement work.** A message change schedules only the persistent- live-region announcement; FieldStatus owns no global event listeners,- observers, or measurements.+- **PR1 — Channel-update work.** A message change schedules only the persistent+ live-region update; FieldStatus owns no global event listeners, observers, or+ measurements.## Accessibility contract-- **AR1 — Announcement channel.** Errors MUST announce through the persistent- assertive region; warnings and successes MUST announce through the persistent- polite region, including on first mount and when message or type changes.+- **AR1 — Programmatic announcement channel.** Errors MUST update the persistent+ assertive region; warnings and successes MUST update the persistent polite+ region, including on first mount and when message or type changes, without+ moving focus.+- **AR5 — Assistive-technology output.** Claims about whether, when, or how the+ message is spoken or presented in braille MUST be verified through the real-AT+ evidence process in `spec:AST-009`; DOM and accessibility-tree checks prove+ only programmatic exposure and routing.- **AR2 — Visible description.** The rendered message box MUST remain availableto assistive technology for `aria-describedby` association and MUST NOT becomeits own newly mounted live region.- **AR3 — Non-color cue.** Detached status MUST include a leading status glyph sostatus is not conveyed only by color or position.- **AR4 — Redundant glyph.** The detached glyph MUST remain hidden from assistive- technology because the visible message already conveys and announces the- status.+ technology because the visible message already conveys the status in text;+ announcement output remains owned by AR5.## Design relationships@@ -140,7 +147,7 @@ intentional decision.| ---------------- | ---------------------------------------------------------- | ----------------------------------------------- | -------------- | ------------------ || Message box | Carries the visible validation treatment. | Current behavior and approved component intent. | Supporting | FR1, FR3 || Detached icon | Adds a non-color status cue only in detached presentation. | Current behavior and approved component intent. | Supporting | FR2, FR4, AR3 |-| Message text | Communicates the validation result in words. | Current behavior and approved component intent. | Prominent | FR1, AR1, AR2 |+| Message text | Communicates the validation result in words. | Current behavior and approved component intent. | Prominent | FR1, AR1, AR2, AR5 |Current behavior renders the detached icon before message text. The intendedpublic theming ownership is the exact map below; it does not add a target or@@ -167,13 +174,16 @@ change either presentation.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | --------------------------------------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------- | --------------------------------- |-| FR1, FR2, AR3, AR4 | `FieldStatus.test.tsx` rendering and detached-icon suites | Attached and detached; all status types | Removing or reordering presentation parts fails DOM and accessibility assertions. | `audit:FieldStatus/anatomy` |-| FR3, FR4 | `FieldStatus.test.tsx` theme target suites | Attached/detached; error/warning/success | Removing a target or status reflection fails class/data-attribute assertions. | `audit:FieldStatus/theming` |-| FR5, FR6 | `FieldStatus.test.tsx` forwarding and update suites | Initial render and rerender | Breaking the released root or update behavior fails compatibility assertions. | `audit:FieldStatus/behavior` |-| AR1, AR2 | `FieldStatus.test.tsx` announcement suites | Mount, message update, type update, empty message | Reintroducing a local live region or misrouting severity fails announcement assertions. | `audit:FieldStatus/accessibility` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy and current targets | Missing, extra, duplicated, prefixed, or stale mappings fail repository validation. | `audit:FieldStatus/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |+| FR1, FR2, AR3, AR4 | `FieldStatus.test.tsx` rendering and detached-icon suites | Attached and detached; all status types | Removing or reordering presentation parts fails DOM and accessibility assertions. | `audit:FieldStatus/anatomy` |+| FR3, FR4 | `FieldStatus.test.tsx` theme target suites | Attached/detached; error/warning/success | Removing a target or status reflection fails class/data-attribute assertions. | `audit:FieldStatus/theming` |+| FR5, FR6 | `FieldStatus.test.tsx` forwarding and update suites | Initial render and rerender | Breaking the released root or update behavior fails compatibility assertions. | `audit:FieldStatus/behavior` |+| AR1 | `StatusMessage.a11y.test.tsx` and `StatusMessage.a11y.chromium.spec.ts` | Error, warning, and success; post-mount message replacement | Removing the persistent channel, changing its role/urgency, or dropping a post-mount update fails the shared status-message contract. | `audit:FieldStatus/accessibility` |+| AR1 | `FieldStatus.test.tsx` channel-routing suite | First non-empty mount; same-instance message and type changes | Breaking FieldStatus's first-use hook call or severity rerouting fails component-specific assertions. | `audit:FieldStatus/accessibility` |+| AR5 | Pending/unverified real-AT evidence governed by `spec:AST-009` | First mount; message replacement; type/urgency change | Spoken and braille output remain unverified until a durable named AT/browser receipt exists. | `audit:FieldStatus/accessibility` |+| AR2 | `FieldStatus.test.tsx` | Attached/detached visible message and empty message | The visible description becomes a second live region or is hidden from assistive technology. | `audit:FieldStatus/accessibility` |+| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy and current targets | Missing, extra, duplicated, prefixed, or stale mappings fail repository validation. | `audit:FieldStatus/theming` |## Decision logdiff --git a/packages/core/src/FieldStatus/FieldStatus.test.tsx b/packages/core/src/FieldStatus/FieldStatus.test.tsxindex a7994fa908..e8b3650581 100644--- a/packages/core/src/FieldStatus/FieldStatus.test.tsx+++ b/packages/core/src/FieldStatus/FieldStatus.test.tsx@@ -53,7 +53,8 @@ describe('FieldStatus', () => {expect(el).not.toHaveAttribute('aria-live');});- // Errors are urgent — they interrupt via the assertive channel.+ // These remain local because they exercise FieldStatus's first-use hook+ // routing. The shared binding starts from an already established channel.it('announces error messages assertively, including on first mount', async () => {render(<FieldStatus type="error" message="This field is required" />);await waitFor(() => {@@ -62,7 +63,7 @@ describe('FieldStatus', () => {expect(politeRegion()).toHaveTextContent('');});- it('announces warning messages politely', async () => {+ it('announces warning messages politely on first mount', async () => {render(<FieldStatus type="warning" message="Check this value" />);await waitFor(() => {expect(politeRegion()).toHaveTextContent('Check this value');@@ -70,14 +71,14 @@ describe('FieldStatus', () => {expect(assertiveRegion()).toHaveTextContent('');});- it('announces success messages politely', async () => {+ it('announces success messages politely on first mount', async () => {render(<FieldStatus type="success" message="Looks good" />);await waitFor(() => {expect(politeRegion()).toHaveTextContent('Looks good');});});- it('announces message changes', async () => {+ it('announces message changes through the component hook', async () => {const {rerender} = render(<FieldStatus type="error" message="First" />);await waitFor(() => {expect(assertiveRegion()).toHaveTextContent('First');@@ -88,7 +89,8 @@ describe('FieldStatus', () => {});});- // Severity changes re-route the announcement to the matching channel.+ // The generic contract checks each fixed urgency. This local test protects+ // the component-specific same-instance type reroute.it('re-routes to the polite channel when type changes from error', async () => {const {rerender} = render(<FieldStatus type="error" message="msg" />);await waitFor(() => {diff --git a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.chromium.spec.ts b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.chromium.spec.tsnew file mode 100644index 0000000000..9bf9068c09--- /dev/null+++ b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.chromium.spec.ts@@ -0,0 +1,198 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file StatusMessage.a11y.chromium.spec.ts+ * @input Uses the shared status-message contract, checked-in stories, Core state inventory, and exact known failures+ * @output Real-browser and accessibility-tree evidence for every current Core status-message binding+ * @position Browser migration lane; it makes no claim about assistive-technology speech or timing+ */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ STATUS_MESSAGE_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 {CORE_STATUS_MESSAGE_KNOWN_FAILURES} from './StatusMessage.a11y.known-failures';+import {+ CORE_STATUS_MESSAGE_BINDING_STATES,+ type CoreStatusMessageBindingState,+} from './StatusMessage.a11y.states';++function transitionTestId(name: string): string {+ return `status-transition-${name}`;+}++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`;+}++const BOUND_SUBJECT_ATTRIBUTE = 'data-a11y-binding-subject';++function subjectFor(page: Page): Locator {+ return page.locator(`[${BOUND_SUBJECT_ATTRIBUTE}]`);+}++async function bindSubject(+ page: Page,+ state: CoreStatusMessageBindingState,+): Promise<void> {+ const facts = state.facts;+ const role = facts.kind === 'progressbar' ? 'progressbar' : facts.role;+ if (role == null) {+ throw new Error(+ `${state.id}: this component binding declares no public role`,+ );+ }+ const candidates = page.getByRole(role, {includeHidden: true});+ let target: Locator;+ if (facts.kind === 'progressbar') {+ target = page.getByRole(role, {includeHidden: true, name: facts.name});+ } else if (facts.messageSource === 'accessible-name') {+ target = page.getByRole(role, {+ includeHidden: true,+ name: facts.initialMessage,+ });+ } else {+ const texts = await candidates.evaluateAll(elements =>+ elements.map(element =>+ (element.textContent ?? '').replace(/\s+/g, ' ').trim(),+ ),+ );+ const indexes = texts.flatMap((text, index) =>+ text === facts.initialMessage ? [index] : [],+ );+ if (indexes.length !== 1) {+ throw new Error(+ `${state.id}: expected one ${role} subject in initial state, found ${indexes.length}`,+ );+ }+ target = candidates.nth(indexes[0]);+ }+ await expect(target).toHaveCount(1);+ await target.evaluate((element, attribute) => {+ element.setAttribute(attribute, '');+ }, BOUND_SUBJECT_ATTRIBUTE);+}++async function mountState(+ page: Page,+ state: CoreStatusMessageBindingState,+): Promise<void> {+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});+ await holdMotionStill(page);+ await page.locator('[data-a11y-ready="true"]').waitFor({state: 'attached'});+ await bindSubject(page, state);+ await subjectFor(page).waitFor({state: 'attached'});+ await expect(subjectFor(page)).toHaveCount(1);+ if ('focusSelector' in state) {+ await expect(page.locator(state.focusSelector)).toHaveAttribute(+ 'aria-describedby',+ /\S+/,+ );+ }+}++async function transition(page: Page, name: string): Promise<void> {+ await page+ .getByTestId(transitionTestId(name))+ .evaluate(element => (element as HTMLElement).click());+ await page.evaluate(+ async () =>+ new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ ),+ );+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: CoreStatusMessageBindingState,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: STATUS_MESSAGE_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: CORE_STATUS_MESSAGE_KNOWN_FAILURES,+ mount: async () => {+ await mountState(page, state);+ return createChromiumHarness({+ page,+ cdp,+ subject: subjectFor(page),+ related: {+ 'focus-anchor': page.locator(+ 'focusSelector' in state+ ? state.focusSelector+ : '[data-a11y-relation="focus-anchor"]',+ ),+ },+ });+ },+ transition: async name => transition(page, name),+ });+}++test('every expectation is exercised by at least one Core binding state', async ({+ page,+}) => {+ test.setTimeout(4 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of CORE_STATUS_MESSAGE_BINDING_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(neverExercised(results)).toEqual([]);+ expect(+ unmatchedKnownFailures(CORE_STATUS_MESSAGE_KNOWN_FAILURES, results),+ ).toEqual([]);+});++for (const state of CORE_STATUS_MESSAGE_BINDING_STATES) {+ test(`${state.binding} [${state.id}] — ${state.summary}`, async ({page}) => {+ test.setTimeout(2 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(STATUS_MESSAGE_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/FieldStatus/__tests__/StatusMessage.a11y.known-failures.ts b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.known-failures.tsnew file mode 100644index 0000000000..b7f465b5ab--- /dev/null+++ b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.known-failures.ts@@ -0,0 +1,13 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file StatusMessage.a11y.known-failures.ts+ * @input Uses the exact known-failure vocabulary from the shared runner+ * @output Public-safe Core status-message debt records (currently none)+ * @position Migration debt only; operational ownership is maintained outside this public repository+ */++import type {KnownFailure} from '@astryxdesign/a11y-spec';++export const CORE_STATUS_MESSAGE_KNOWN_FAILURES: ReadonlyArray<KnownFailure> =+ [];diff --git a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.renders.tsx b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.renders.tsxnew file mode 100644index 0000000000..9e0a05aa6c--- /dev/null+++ b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.renders.tsx@@ -0,0 +1,305 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file StatusMessage.a11y.renders.tsx+ * @input Uses current Core status-message components and the binding state ids+ * @output One public-interface rendering for every Core status-message binding state+ * @position Shared jsdom and checked-in Storybook fixture layer+ */++import {useEffect, useState, type ReactElement, type ReactNode} from 'react';+import {ChatSystemMessage} from '../../Chat/ChatSystemMessage';+import {ProgressBar} from '../../ProgressBar/ProgressBar';+import {Spinner} from '../../Spinner/Spinner';+import {Toast} from '../../Toast/Toast';+import {ToastViewport} from '../../Toast/ToastViewport';+import {useToast} from '../../Toast/useToast';+import {useAnnounce, type AnnouncePoliteness} from '../../hooks/useAnnounce';+import {FieldStatus} from '../FieldStatus';+import type {CoreStatusMessageStateId} from './StatusMessage.a11y.states';++const transitionTestId = (name: string) => `status-transition-${name}`;++function TransitionButton({+ name,+ onClick,+}: {+ name: string;+ onClick: () => void;+}) {+ return (+ <button+ data-testid={transitionTestId(name)}+ type="button"+ onClick={onClick}>+ {name}+ </button>+ );+}++function Frame({+ children,+ isReady = true,+}: {+ children: ReactNode;+ isReady?: boolean;+}) {+ return (+ <div>+ <span data-a11y-ready={String(isReady)} hidden />+ <button data-a11y-relation="focus-anchor" type="button">+ Keep focus+ </button>+ {children}+ </div>+ );+}++/**+ * Establishes the same singleton channel the component will update, then clears+ * the seed before the test starts. This lets a browser binding inspect the+ * pre-existing empty node; the contract's plain-HTML fixtures separately prove+ * the first-use insertion order.+ */+function PrimeLiveRegion({politeness}: {politeness: AnnouncePoliteness}) {+ const announce = useAnnounce();+ const [isReady, setIsReady] = useState(false);+ useEffect(() => {+ let secondFrame = 0;+ announce('Preparing status channel', politeness);+ const firstFrame = requestAnimationFrame(() => {+ secondFrame = requestAnimationFrame(() => {+ announce('', politeness);+ setIsReady(true);+ });+ });+ return () => {+ cancelAnimationFrame(firstFrame);+ cancelAnimationFrame(secondFrame);+ };+ }, [announce, politeness]);+ return <span data-a11y-ready={String(isReady)} hidden />;+}++function ToastAnnouncementButtons({type}: {type: 'info' | 'error'}) {+ const toast = useToast();+ const message = type === 'error' ? 'Upload failed' : 'Changes saved';+ const replacement =+ type === 'error' ? 'Connection failed' : 'Profile updated';+ const show = (body: string) =>+ toast({+ body,+ type,+ uniqueID: `status-contract-${type}`,+ isAutoHide: false,+ });+ return (+ <>+ <TransitionButton name="show" onClick={() => show(message)} />+ <TransitionButton name="replace" onClick={() => show(replacement)} />+ <TransitionButton name="repeat" onClick={() => show(message)} />+ </>+ );+}++function ToastAnnouncementHarness({type}: {type: 'info' | 'error'}) {+ const politeness = type === 'error' ? 'assertive' : 'polite';+ return (+ <ToastViewport isTopLayer={false}>+ <PrimeLiveRegion politeness={politeness} />+ <button data-a11y-relation="focus-anchor" type="button">+ Keep focus+ </button>+ <ToastAnnouncementButtons type={type} />+ </ToastViewport>+ );+}++function ToastCardHarness({type}: {type: 'info' | 'error'}) {+ const message = type === 'error' ? 'Upload failed' : 'Changes saved';+ const replacement =+ type === 'error' ? 'Connection failed' : 'Profile updated';+ const [body, setBody] = useState(message);+ return (+ <Frame>+ <TransitionButton name="show" onClick={() => setBody(message)} />+ <TransitionButton name="replace" onClick={() => setBody(replacement)} />+ <Toast+ type={type}+ body={body}+ isAutoHide={false}+ autoHideDuration={5000}+ onDismiss={() => {}}+ />+ </Frame>+ );+}++function FieldStatusHarness({+ type,+ variant,+ message,+ replacement,+}: {+ type: 'error' | 'warning' | 'success';+ variant: 'attached' | 'detached';+ message: string;+ replacement: string;+}) {+ const politeness = type === 'error' ? 'assertive' : 'polite';+ const [current, setCurrent] = useState('');+ const [version, setVersion] = useState(0);+ return (+ <>+ <PrimeLiveRegion politeness={politeness} />+ <button data-a11y-relation="focus-anchor" type="button">+ Keep focus+ </button>+ <TransitionButton name="show" onClick={() => setCurrent(message)} />+ <TransitionButton+ name="replace"+ onClick={() => setCurrent(replacement)}+ />+ <TransitionButton+ name="repeat"+ onClick={() => {+ setCurrent(message);+ setVersion(value => value + 1);+ }}+ />+ <FieldStatus+ key={version}+ type={type}+ variant={variant}+ message={current}+ />+ </>+ );+}++function SpinnerHarness({visibleLabel}: {visibleLabel: boolean}) {+ const initial = visibleLabel ? 'Fetching data' : undefined;+ const replacement = visibleLabel ? 'Saving data' : 'Saving';+ const [label, setLabel] = useState<string | undefined>(initial);+ return (+ <Frame>+ <TransitionButton name="show" onClick={() => setLabel(initial)} />+ <TransitionButton name="replace" onClick={() => setLabel(replacement)} />+ {visibleLabel ? (+ <Spinner label={label ?? 'Fetching data'} />+ ) : label == null ? (+ <Spinner />+ ) : (+ <Spinner aria-label={label} />+ )}+ </Frame>+ );+}++function ChatSystemMessageHarness() {+ const initial = 'Conversation started';+ const [message, setMessage] = useState(initial);+ return (+ <Frame>+ <TransitionButton name="show" onClick={() => setMessage(initial)} />+ <TransitionButton+ name="replace"+ onClick={() => setMessage('A file was shared')}+ />+ <TransitionButton name="clear" onClick={() => setMessage('')} />+ <ChatSystemMessage>{message}</ChatSystemMessage>+ </Frame>+ );+}++function ProgressHarness({+ initial,+ progressValue = 40,+ completionValue = 100,+ max = 100,+ withMark = false,+}: {+ initial?: 'loading' | number;+ progressValue?: number;+ completionValue?: number;+ max?: number;+ withMark?: boolean;+}) {+ const [progress, setProgress] = useState<'loading' | number>(+ initial ?? (withMark ? 20 : 'loading'),+ );+ return (+ <Frame>+ <TransitionButton+ name="progress"+ onClick={() => setProgress(progressValue)}+ />+ <TransitionButton+ name="complete"+ onClick={() => setProgress(completionValue)}+ />+ <ProgressBar+ label="Upload progress"+ isIndeterminate={progress === 'loading'}+ value={typeof progress === 'number' ? progress : 0}+ max={max}+ marks={withMark ? [{value: 75, label: 'Target'}] : undefined}+ />+ </Frame>+ );+}++export type CoreStatusMessageStateRender = () => ReactElement;++export const CORE_STATUS_MESSAGE_STATE_RENDERS: Record<+ CoreStatusMessageStateId,+ CoreStatusMessageStateRender+> = {+ 'toast-info-announcement': () => <ToastAnnouncementHarness type="info" />,+ 'toast-error-announcement': () => <ToastAnnouncementHarness type="error" />,+ 'toast-info-card-mounted': () => <ToastCardHarness type="info" />,+ 'toast-error-card-mounted': () => <ToastCardHarness type="error" />,+ 'field-status-error-attached': () => (+ <FieldStatusHarness+ type="error"+ variant="attached"+ message="This field is required"+ replacement="Enter a valid email address"+ />+ ),+ 'field-status-warning-detached': () => (+ <FieldStatusHarness+ type="warning"+ variant="detached"+ message="Check this value"+ replacement="This value may be visible to others"+ />+ ),+ 'field-status-success-detached': () => (+ <FieldStatusHarness+ type="success"+ variant="detached"+ message="Looks good"+ replacement="Changes saved"+ />+ ),+ 'spinner-default-label-mounted': () => (+ <SpinnerHarness visibleLabel={false} />+ ),+ 'spinner-visible-label-mounted': () => <SpinnerHarness visibleLabel />,+ 'chat-system-status-mounted': () => <ChatSystemMessageHarness />,+ 'progress-loading-to-complete': () => <ProgressHarness />,+ 'progress-custom-range': () => (+ <ProgressHarness+ initial={1}+ progressValue={3}+ completionValue={5}+ max={5}+ />+ ),+ 'progress-mark-focused-update': () => <ProgressHarness withMark />,+};++export {transitionTestId};diff --git a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.ts b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.tsnew file mode 100644index 0000000000..3ddec3b5de--- /dev/null+++ b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.ts@@ -0,0 +1,317 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file StatusMessage.a11y.states.ts+ * @input Uses StatusMessageStateFacts from the shared accessibility contract+ * @output The AST-021 inventory for current Core status-message parts and states, plus explicit exclusions+ * @position Data-only binding inventory shared by jsdom, Storybook, and Chromium+ */++import type {StatusMessageStateFacts} from '@astryxdesign/a11y-spec';++export type CoreStatusMessageBinding =+ | 'Toast announcement channel'+ | 'Toast card'+ | 'FieldStatus announcement channel'+ | 'Spinner'+ | 'ChatSystemMessage'+ | 'ProgressBar';++export interface CoreStatusMessageBindingDefinition {+ readonly id: string;+ readonly binding: CoreStatusMessageBinding;+ readonly summary: string;+ readonly facts: StatusMessageStateFacts;+ readonly focusSelector?: string;+ readonly storyId: string;+}++function liveFacts({+ role,+ politeness,+ message,+ replacement,+ initialMessage = '',+ messageSource = 'text',+ semanticTransitions,+}: {+ role: 'status' | 'alert' | null;+ politeness: 'polite' | 'assertive';+ message: string;+ replacement: string;+ initialMessage?: string;+ messageSource?: 'text' | 'accessible-name';+ semanticTransitions: ReadonlyArray<'show' | 'replace' | 'clear' | 'repeat'>;+}): StatusMessageStateFacts {+ return {+ kind: 'live-region',+ role,+ politeness,+ messageSource,+ initialMessage,+ message,+ replacement,+ semanticTransitions,+ };+}++export const CORE_STATUS_MESSAGE_BINDING_STATES = [+ {+ id: 'toast-info-announcement',+ binding: 'Toast announcement channel',+ summary:+ 'an info toast dispatch updates and can repeat through the persistent polite channel',+ facts: liveFacts({+ role: 'status',+ politeness: 'polite',+ message: 'Changes saved',+ replacement: 'Profile updated',+ semanticTransitions: ['show', 'replace', 'repeat'],+ }),+ storyId: 'a11y-status-message-pattern--toast-info-announcement',+ },+ {+ id: 'toast-error-announcement',+ binding: 'Toast announcement channel',+ summary:+ 'an error toast dispatch updates and can repeat through the persistent assertive channel',+ facts: liveFacts({+ role: 'alert',+ politeness: 'assertive',+ message: 'Upload failed',+ replacement: 'Connection failed',+ semanticTransitions: ['show', 'replace', 'repeat'],+ }),+ storyId: 'a11y-status-message-pattern--toast-error-announcement',+ },+ {+ id: 'toast-info-card-mounted',+ binding: 'Toast card',+ summary:+ 'the visible info card is mounted with its polite live-region content',+ facts: liveFacts({+ role: 'status',+ politeness: 'polite',+ initialMessage: 'Changes saved',+ message: 'Changes saved',+ replacement: 'Profile updated',+ semanticTransitions: ['replace'],+ }),+ storyId: 'a11y-status-message-pattern--toast-info-card-mounted',+ },+ {+ id: 'toast-error-card-mounted',+ binding: 'Toast card',+ summary:+ 'the visible error card is mounted with its assertive live-region content',+ facts: liveFacts({+ role: 'alert',+ politeness: 'assertive',+ initialMessage: 'Upload failed',+ message: 'Upload failed',+ replacement: 'Connection failed',+ semanticTransitions: ['replace'],+ }),+ storyId: 'a11y-status-message-pattern--toast-error-card-mounted',+ },+ {+ id: 'field-status-error-attached',+ binding: 'FieldStatus announcement channel',+ summary:+ 'an attached error enters and updates through the persistent assertive channel',+ facts: liveFacts({+ role: 'alert',+ politeness: 'assertive',+ message: 'This field is required',+ replacement: 'Enter a valid email address',+ semanticTransitions: ['show', 'replace', 'repeat'],+ }),+ storyId: 'a11y-status-message-pattern--field-status-error-attached',+ },+ {+ id: 'field-status-warning-detached',+ binding: 'FieldStatus announcement channel',+ summary:+ 'a detached warning enters and updates through the persistent polite channel',+ facts: liveFacts({+ role: 'status',+ politeness: 'polite',+ message: 'Check this value',+ replacement: 'This value may be visible to others',+ semanticTransitions: ['show', 'replace', 'repeat'],+ }),+ storyId: 'a11y-status-message-pattern--field-status-warning-detached',+ },+ {+ id: 'field-status-success-detached',+ binding: 'FieldStatus announcement channel',+ summary:+ 'a detached success enters and updates through the persistent polite channel',+ facts: liveFacts({+ role: 'status',+ politeness: 'polite',+ message: 'Looks good',+ replacement: 'Changes saved',+ semanticTransitions: ['show', 'replace', 'repeat'],+ }),+ storyId: 'a11y-status-message-pattern--field-status-success-detached',+ },+ {+ id: 'spinner-default-label-mounted',+ binding: 'Spinner',+ summary:+ 'a loading spinner is mounted with its default accessible status name',+ facts: liveFacts({+ role: 'status',+ politeness: 'polite',+ initialMessage: 'Loading',+ messageSource: 'accessible-name',+ message: 'Loading',+ replacement: 'Saving',+ semanticTransitions: ['replace'],+ }),+ storyId: 'a11y-status-message-pattern--spinner-default-label-mounted',+ },+ {+ id: 'spinner-visible-label-mounted',+ binding: 'Spinner',+ summary:+ 'a loading spinner is mounted with a visible label that names its status role',+ facts: liveFacts({+ role: 'status',+ politeness: 'polite',+ initialMessage: 'Fetching data',+ messageSource: 'accessible-name',+ message: 'Fetching data',+ replacement: 'Saving data',+ semanticTransitions: ['replace'],+ }),+ storyId: 'a11y-status-message-pattern--spinner-visible-label-mounted',+ },+ {+ id: 'chat-system-status-mounted',+ binding: 'ChatSystemMessage',+ summary: 'a chat status notice is mounted with its live-region content',+ facts: liveFacts({+ role: 'status',+ politeness: 'polite',+ initialMessage: 'Conversation started',+ message: 'Conversation started',+ replacement: 'A file was shared',+ semanticTransitions: ['replace', 'clear'],+ }),+ storyId: 'a11y-status-message-pattern--chat-system-status-mounted',+ },+ {+ id: 'progress-loading-to-complete',+ binding: 'ProgressBar',+ summary:+ 'an indeterminate operation becomes 40 percent complete and then finishes',+ facts: {+ kind: 'progressbar',+ politeness: null,+ name: 'Upload progress',+ initialValue: null,+ initialMin: 0,+ initialMax: 100,+ progressValue: 40,+ completionValue: 100,+ minValue: 0,+ maxValue: 100,+ },+ storyId: 'a11y-status-message-pattern--progress-loading-to-complete',+ },+ {+ id: 'progress-custom-range',+ binding: 'ProgressBar',+ summary: 'a five-step operation exposes and updates its non-default range',+ facts: {+ kind: 'progressbar',+ politeness: null,+ name: 'Upload progress',+ initialValue: 1,+ initialMin: 0,+ initialMax: 5,+ progressValue: 3,+ completionValue: 5,+ minValue: 0,+ maxValue: 5,+ },+ storyId: 'a11y-status-message-pattern--progress-custom-range',+ },+ {+ id: 'progress-mark-focused-update',+ binding: 'ProgressBar',+ summary:+ 'a determinate value update preserves focus on a labeled target mark',+ facts: {+ kind: 'progressbar',+ politeness: null,+ name: 'Upload progress',+ initialValue: 20,+ initialMin: 0,+ initialMax: 100,+ progressValue: 40,+ completionValue: 100,+ minValue: 0,+ maxValue: 100,+ },+ focusSelector: '[role="progressbar"] [tabindex="0"]',+ storyId: 'a11y-status-message-pattern--progress-mark-focused-update',+ },+] as const satisfies ReadonlyArray<CoreStatusMessageBindingDefinition>;++export type CoreStatusMessageBindingState =+ (typeof CORE_STATUS_MESSAGE_BINDING_STATES)[number];+export type CoreStatusMessageStateId = CoreStatusMessageBindingState['id'];++export const CORE_STATUS_MESSAGE_EXCLUSIONS = [+ {+ owner: 'FieldStatus visible message box',+ part: 'visible validation text',+ reason:+ 'component:FieldStatus AR2 keeps the visible box role-free as the input description target; its separate persistent announcement channel is bound above.',+ },+ {+ owner: 'Spinner compositions',+ part: 'aria-hidden decorative spinner',+ reason:+ 'A composing control that marks Spinner aria-hidden owns the surrounding busy semantics; the decorative ring is not another status message.',+ },+ {+ owner: 'ChatSystemMessage divider',+ part: 'date or section separator',+ reason:+ 'A divider does not report success, results, waiting, progress, or an error. Its current forced status role is tracked as a separate ownership mismatch rather than adopted here.',+ },+ {+ owner: 'ChatMessageList and streaming logs',+ part: 'role=log transcript updates',+ reason:+ 'Sequential log announcements and stream batching are a distinct log pattern, not one atomic status message.',+ },+ {+ owner: 'ChatComposer and ChatToolCalls',+ part: 'composer errors and tool-run states',+ reason:+ 'These adjacent surfaces have their own state ownership and were not named by this bounded first status-message migration.',+ },+ {+ owner: 'Switch',+ part: 'busy announcement',+ reason:+ 'The current switch pattern has no busy announcement expectation, and overlapping work is changing this path; it is not silently absorbed into this migration.',+ },+ {+ owner: 'ProgressBar marks and Tooltip',+ part: 'focusable target-mark triggers and labels',+ reason:+ 'The marked progress state above proves that value updates preserve mark focus. ProgressBar and Tooltip local tests own trigger labeling and interaction; ARIA ownership of focusable descendants is tracked separately.',+ },+ {+ owner: 'ProgressBar component and theme',+ part: 'visual fill, track, animation, and status cadence',+ reason:+ 'The binding covers browser-exposed role, name, values, and focus preservation. Paint stays in visual evidence; spoken cadence and timing stay under AST-009.',+ },+] as const;diff --git a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.test.tsx b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.test.tsxnew file mode 100644index 0000000000..44c3c59056--- /dev/null+++ b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.test.tsx@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file StatusMessage.a11y.test.tsx+ * @input Uses the shared status-message contract and current Core binding render map+ * @output Component-facing jsdom evidence through expectAccessibilitySpec+ * @position Fast migration lane; browser-owned outcomes remain explicitly unrun+ */++import {afterEach, describe, expect, it} from 'vitest';+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react';+import {+ STATUS_MESSAGE_PATTERN,+ expectAccessibilitySpec,+} from '@astryxdesign/a11y-spec';+import {__resetLiveRegionsForTest} from '../../hooks/useAnnounce';+import {CORE_STATUS_MESSAGE_KNOWN_FAILURES} from './StatusMessage.a11y.known-failures';+import {+ CORE_STATUS_MESSAGE_STATE_RENDERS,+ transitionTestId,+} from './StatusMessage.a11y.renders';+import {+ CORE_STATUS_MESSAGE_BINDING_STATES,+ CORE_STATUS_MESSAGE_EXCLUSIONS,+ type CoreStatusMessageBindingState,+} from './StatusMessage.a11y.states';++async function twoFrames(): Promise<void> {+ await new Promise<void>(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+}++async function renderState(+ state: CoreStatusMessageBindingState,+): Promise<void> {+ render(CORE_STATUS_MESSAGE_STATE_RENDERS[state.id]());+ await waitFor(() =>+ expect(document.querySelector('[data-a11y-ready="true"]')).not.toBeNull(),+ );+}++function subjectFor(state: CoreStatusMessageBindingState): Element {+ const facts = state.facts;+ const role = facts.kind === 'progressbar' ? 'progressbar' : facts.role;+ if (role == null) {+ throw new Error(+ `${state.id}: this component binding declares no public role`,+ );+ }+ const matches =+ facts.kind === 'progressbar'+ ? screen.getAllByRole(role, {hidden: true, name: facts.name})+ : facts.messageSource === 'accessible-name'+ ? screen.getAllByRole(role, {+ hidden: true,+ name: facts.initialMessage,+ })+ : screen+ .getAllByRole(role, {hidden: true})+ .filter(+ element =>+ (element.textContent ?? '').replace(/\s+/g, ' ').trim() ===+ facts.initialMessage,+ );+ if (matches.length !== 1) {+ throw new Error(+ `${state.id}: expected one ${role} subject in initial state, found ${matches.length}`,+ );+ }+ return matches[0];+}++async function transition(name: string): Promise<void> {+ fireEvent.click(screen.getByTestId(transitionTestId(name)));+ await act(twoFrames);+}++function reset(): void {+ cleanup();+ __resetLiveRegionsForTest();+}++afterEach(reset);++describe('Core status-message bindings — jsdom lane', () => {+ it.each(+ CORE_STATUS_MESSAGE_BINDING_STATES.map(+ state =>+ [`${state.binding} [${state.id}]`, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectAccessibilitySpec({+ spec: STATUS_MESSAGE_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: CORE_STATUS_MESSAGE_KNOWN_FAILURES,+ render: async () => renderState(state),+ subject: () => subjectFor(state),+ transition,+ cleanup: reset,+ });+ });+});++describe('Core status-message binding inventory', () => {+ it('names a distinct checked-in story for every bound state', () => {+ const stories = CORE_STATUS_MESSAGE_BINDING_STATES.map(+ state => state.storyId,+ );+ expect(new Set(stories).size).toBe(stories.length);+ });++ it('binds every named Core status-message owner', () => {+ expect(+ [+ ...new Set(+ CORE_STATUS_MESSAGE_BINDING_STATES.map(state => state.binding),+ ),+ ].sort(),+ ).toEqual([+ 'ChatSystemMessage',+ 'FieldStatus announcement channel',+ 'ProgressBar',+ 'Spinner',+ 'Toast announcement channel',+ 'Toast card',+ ]);+ });++ it('records every adjacent non-status or separately owned surface explicitly', () => {+ expect(CORE_STATUS_MESSAGE_EXCLUSIONS.map(entry => entry.part)).toEqual([+ 'visible validation text',+ 'aria-hidden decorative spinner',+ 'date or section separator',+ 'role=log transcript updates',+ 'composer errors and tool-run states',+ 'busy announcement',+ 'focusable target-mark triggers and labels',+ 'visual fill, track, animation, and status cadence',+ ]);+ expect(+ CORE_STATUS_MESSAGE_EXCLUSIONS.every(entry => entry.reason.length > 0),+ ).toBe(true);+ });+});diff --git a/packages/core/src/ProgressBar/ProgressBar.test.tsx b/packages/core/src/ProgressBar/ProgressBar.test.tsxindex b2f5ec4f95..944ceb851a 100644--- a/packages/core/src/ProgressBar/ProgressBar.test.tsx+++ b/packages/core/src/ProgressBar/ProgressBar.test.tsx@@ -14,23 +14,6 @@ beforeAll(async () => {});describe('ProgressBar', () => {- it('renders with default props', () => {- render(<ProgressBar value={50} label="Progress" />);- const progressbar = screen.getByRole('progressbar');- expect(progressbar).toBeInTheDocument();- expect(progressbar).toHaveAttribute('aria-valuenow', '50');- expect(progressbar).toHaveAttribute('aria-valuemin', '0');- expect(progressbar).toHaveAttribute('aria-valuemax', '100');- });-- it('uses role="progressbar" (not "meter") for determinate progress', () => {- // A determinate ProgressBar conveys task completion, so it must be a- // progressbar (announced on update), not a meter (a static gauge).- render(<ProgressBar value={50} label="Progress" />);- expect(screen.getByRole('progressbar')).toBeInTheDocument();- expect(screen.queryByRole('meter')).not.toBeInTheDocument();- });-it('renders visible label by default', () => {render(<ProgressBar value={50} label="Storage used" />);expect(screen.getByText('Storage used')).toBeInTheDocument();@@ -70,13 +53,6 @@ describe('ProgressBar', () => {expect(progressbar).toHaveAttribute('aria-valuetext', '50%');});- it('respects custom max', () => {- render(<ProgressBar value={3} max={10} label="Steps" />);- const progressbar = screen.getByRole('progressbar');- expect(progressbar).toHaveAttribute('aria-valuenow', '3');- expect(progressbar).toHaveAttribute('aria-valuemax', '10');- });-it('clamps value to [0, max]', () => {const {rerender} = render(<ProgressBar value={150} max={100} label="Over" />,@@ -197,13 +173,7 @@ describe('ProgressBar', () => {// Indeterminate mode testsdescribe('indeterminate mode', () => {- it('renders with role="progressbar" when isIndeterminate', () => {- render(<ProgressBar isIndeterminate label="Loading" />);- const progressbar = screen.getByRole('progressbar');- expect(progressbar).toBeInTheDocument();- });-- it('does not set aria-valuenow/min/max when indeterminate', () => {+ it('omits authored value attributes while the value is indeterminate', () => {render(<ProgressBar isIndeterminate label="Loading" />);const progressbar = screen.getByRole('progressbar');expect(progressbar).not.toHaveAttribute('aria-valuenow');diff --git a/packages/core/src/Spinner/Spinner.test.tsx b/packages/core/src/Spinner/Spinner.test.tsxindex e088a54e7e..e8da0d6662 100644--- a/packages/core/src/Spinner/Spinner.test.tsx+++ b/packages/core/src/Spinner/Spinner.test.tsx@@ -72,24 +72,6 @@ describe('Spinner', () => {expect(spinner).toHaveAttribute('data-shade', 'inherit');});- it('has role="status"', () => {- render(<Spinner data-testid="spinner" />);- expect(screen.getByRole('status')).toBeInTheDocument();- });-- it('has aria-label="Loading" by default', () => {- render(<Spinner data-testid="spinner" />);- expect(screen.getByTestId('spinner')).toHaveAttribute(- 'aria-label',- 'Loading',- );- });-- it('names the status element from the visible string label', () => {- render(<Spinner label="Fetching data" data-testid="spinner" />);- expect(screen.getByRole('status')).toHaveAccessibleName('Fetching data');- });-it('does not duplicate a visible string label as aria-label', () => {render(<Spinner label="Fetching data" data-testid="spinner" />);const status = screen.getByRole('status');diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsxindex 0045d751cc..4e1a4cfbe7 100644--- a/packages/core/src/Toast/ToastViewport.test.tsx+++ b/packages/core/src/Toast/ToastViewport.test.tsx@@ -34,7 +34,7 @@ import React from 'react';import {readFileSync} from 'node:fs';import {type AnnounceFn, __resetLiveRegionsForTest} from '../hooks/useAnnounce';import {Button} from '../Button';-import {Toast, type ToastProps} from './Toast';+import type {ToastProps} from './Toast';import {ToastViewport} from './ToastViewport';import {useToast} from './useToast';import type {ToastOptions} from './types';@@ -1720,44 +1720,6 @@ describe('Toast swipe dismissal', () => {});});-describe('Toast live-region fallback semantics', () => {- it('keeps standalone info Toast content in a polite status region', () => {- render(- <Toast- type="info"- body="Saved"- isAutoHide={false}- autoHideDuration={5000}- onDismiss={() => {}}- />,- );-- const visualToast = screen.getByText('Saved').closest('[data-type]');- expect(visualToast).toHaveAttribute('role', 'status');- expect(visualToast).toHaveAttribute('aria-live', 'polite');- expect(visualToast).toHaveAttribute('aria-atomic', 'true');- });-- it('keeps standalone error Toast content in an assertive alert region', () => {- render(- <Toast- type="error"- body="Upload failed"- isAutoHide={false}- autoHideDuration={5000}- onDismiss={() => {}}- />,- );-- const visualToast = screen- .getByText('Upload failed')- .closest('[data-type]');- expect(visualToast).toHaveAttribute('role', 'alert');- expect(visualToast).toHaveAttribute('aria-live', 'assertive');- expect(visualToast).toHaveAttribute('aria-atomic', 'true');- });-});-describe('ToastViewport region ARIA', () => {it('does not expose an empty notifications landmark', () => {renderViewport(<ShowToastButton />);diff --git a/packages/lab/package.json b/packages/lab/package.jsonindex d44fbed8ec..b2ba061dc7 100644--- a/packages/lab/package.json+++ b/packages/lab/package.json@@ -69,6 +69,7 @@"d3-shape": "^3.2.0"},"devDependencies": {+ "@astryxdesign/a11y-spec": "workspace:*","@astryxdesign/cli": "workspace:*","@types/d3-array": "^3.2.2","@types/d3-scale": "^4.0.9",diff --git a/packages/lab/src/Chat/ChatTypingIndicator.test.tsx b/packages/lab/src/Chat/ChatTypingIndicator.test.tsxindex 518b730ff8..2256cd0081 100644--- a/packages/lab/src/Chat/ChatTypingIndicator.test.tsx+++ b/packages/lab/src/Chat/ChatTypingIndicator.test.tsx@@ -32,13 +32,6 @@ describe('ChatTypingIndicator', () => {expect(screen.getByTestId('typing').textContent).toBe('');});- it('is a polite live region', () => {- render(<ChatTypingIndicator names={['Ana']} data-testid="typing" />);- const root = screen.getByTestId('typing');- expect(root.getAttribute('role')).toBe('status');- expect(root.getAttribute('aria-live')).toBe('polite');- });-it('applies the stable class name', () => {render(<ChatTypingIndicator names={['Ana']} data-testid="typing" />);expect(screen.getByTestId('typing').className).toContain(diff --git a/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.chromium.spec.ts b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.chromium.spec.tsnew file mode 100644index 0000000000..418cd70ca7--- /dev/null+++ b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.chromium.spec.ts@@ -0,0 +1,166 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Real-browser and accessibility-tree binding for ChatTypingIndicator. */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ STATUS_MESSAGE_PATTERN,+ blockingResults,+ checkAccessibilitySpec,+ formatFailures,+ formatReport,+ 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 {CHAT_TYPING_STATUS_KNOWN_FAILURES} from './ChatTypingIndicator.a11y.known-failures';+import {+ CHAT_TYPING_STATUS_BINDING_STATES,+ type ChatTypingStatusBindingState,+} from './ChatTypingIndicator.a11y.states';++function transitionTestId(name: string): string {+ return `status-transition-${name}`;+}++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++const BOUND_SUBJECT_ATTRIBUTE = 'data-a11y-binding-subject';++function subjectFor(page: Page): Locator {+ return page.locator(`[${BOUND_SUBJECT_ATTRIBUTE}]`);+}++async function bindSubject(+ page: Page,+ state: ChatTypingStatusBindingState,+): Promise<void> {+ const facts = state.facts;+ if (facts.kind !== 'live-region' || facts.role == null) {+ throw new Error(+ `${state.id}: this component binding declares no public role`,+ );+ }+ const candidates = page.getByRole(facts.role, {includeHidden: true});+ const texts = await candidates.evaluateAll(elements =>+ elements.map(element =>+ (element.textContent ?? '').replace(/\s+/g, ' ').trim(),+ ),+ );+ const indexes = texts.flatMap((text, index) =>+ text === facts.initialMessage ? [index] : [],+ );+ if (indexes.length !== 1) {+ throw new Error(+ `${state.id}: expected one ${facts.role} subject in initial state, found ${indexes.length}`,+ );+ }+ const target = candidates.nth(indexes[0]);+ await target.evaluate((element, attribute) => {+ element.setAttribute(attribute, '');+ }, BOUND_SUBJECT_ATTRIBUTE);+}++async function mountState(+ page: Page,+ state: ChatTypingStatusBindingState,+): Promise<void> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${state.storyId}&viewMode=story`,+ {waitUntil: 'load'},+ );+ await holdMotionStill(page);+ await page.locator('[data-a11y-ready="true"]').waitFor({state: 'attached'});+ await bindSubject(page, state);+ await subjectFor(page).waitFor({state: 'attached'});+ await expect(subjectFor(page)).toHaveCount(1);+}++async function transition(page: Page, name: string): Promise<void> {+ await page+ .getByTestId(transitionTestId(name))+ .evaluate(element => (element as HTMLElement).click());+ await page.evaluate(+ async () =>+ new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ ),+ );+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: ChatTypingStatusBindingState,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: STATUS_MESSAGE_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: CHAT_TYPING_STATUS_KNOWN_FAILURES,+ mount: async () => {+ await mountState(page, state);+ return createChromiumHarness({+ page,+ cdp,+ subject: subjectFor(page),+ related: {+ 'focus-anchor': page.locator('[data-a11y-relation="focus-anchor"]'),+ },+ });+ },+ transition: async name => transition(page, name),+ });+}++test('the exact known failure matches one executed ChatTypingIndicator result', async ({+ page,+}) => {+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of CHAT_TYPING_STATUS_BINDING_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(+ unmatchedKnownFailures(CHAT_TYPING_STATUS_KNOWN_FAILURES, results),+ ).toEqual([]);+});++for (const state of CHAT_TYPING_STATUS_BINDING_STATES) {+ test(`${state.binding} [${state.id}] — ${state.summary}`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(STATUS_MESSAGE_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/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.known-failures.ts b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.known-failures.tsnew file mode 100644index 0000000000..661a099a2a--- /dev/null+++ b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.known-failures.ts@@ -0,0 +1,8 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Public-safe ChatTypingIndicator status-message debt records (currently none). */++import type {KnownFailure} from '@astryxdesign/a11y-spec';++export const CHAT_TYPING_STATUS_KNOWN_FAILURES: ReadonlyArray<KnownFailure> =+ [];diff --git a/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.renders.tsx b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.renders.tsxnew file mode 100644index 0000000000..9aff973d8c--- /dev/null+++ b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.renders.tsx@@ -0,0 +1,60 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/** Shared jsdom and Storybook renderings for ChatTypingIndicator status states. */++import {useState, type ReactElement} from 'react';+import {ChatTypingIndicator} from '../ChatTypingIndicator';+import type {ChatTypingStatusStateId} from './ChatTypingIndicator.a11y.states';++const transitionTestId = (name: string) => `status-transition-${name}`;++function TransitionButton({+ name,+ onClick,+}: {+ name: string;+ onClick: () => void;+}) {+ return (+ <button+ data-testid={transitionTestId(name)}+ type="button"+ onClick={onClick}>+ {name}+ </button>+ );+}++function TypingHarness({startsNamed}: {startsNamed: boolean}) {+ const initial = startsNamed ? ['Ana'] : [];+ const [names, setNames] = useState<string[]>(initial);+ return (+ <div>+ <span data-a11y-ready="true" hidden />+ <button data-a11y-relation="focus-anchor" type="button">+ Keep focus+ </button>+ <TransitionButton name="show" onClick={() => setNames(['Ana'])} />+ <TransitionButton+ name="replace"+ onClick={() => setNames(['Ana', 'Ben'])}+ />+ <TransitionButton name="clear" onClick={() => setNames([])} />+ <ChatTypingIndicator names={names} />+ </div>+ );+}++export type ChatTypingStatusStateRender = () => ReactElement;++export const CHAT_TYPING_STATUS_STATE_RENDERS: Record<+ ChatTypingStatusStateId,+ ChatTypingStatusStateRender+> = {+ 'chat-typing-empty-to-message': () => <TypingHarness startsNamed={false} />,+ 'chat-typing-name-mounted': () => <TypingHarness startsNamed />,+};++export {transitionTestId};diff --git a/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.states.ts b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.states.tsnew file mode 100644index 0000000000..541822feff--- /dev/null+++ b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.states.ts@@ -0,0 +1,78 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ChatTypingIndicator.a11y.states.ts+ * @input Uses StatusMessageStateFacts from the shared accessibility contract+ * @output The AST-021 inventory for ChatTypingIndicator status states and exclusions+ * @position Data-only binding inventory shared by jsdom, Storybook, and Chromium+ */++import type {StatusMessageStateFacts} from '@astryxdesign/a11y-spec';++export type ChatTypingStatusStateId =+ 'chat-typing-empty-to-message' | 'chat-typing-name-mounted';++export interface ChatTypingStatusBindingDefinition {+ readonly id: ChatTypingStatusStateId;+ readonly binding: 'ChatTypingIndicator';+ readonly summary: string;+ readonly facts: StatusMessageStateFacts;+ readonly storyId: string;+}++const LIFECYCLE_FACTS: StatusMessageStateFacts = {+ kind: 'live-region',+ role: 'status',+ politeness: 'polite',+ messageSource: 'text',+ initialMessage: '',+ message: 'Ana is typing…',+ replacement: 'Ana and Ben are typing…',+ semanticTransitions: ['show', 'replace', 'clear'],+};++export const CHAT_TYPING_STATUS_BINDING_STATES: ReadonlyArray<ChatTypingStatusBindingDefinition> =+ [+ {+ id: 'chat-typing-empty-to-message',+ binding: 'ChatTypingIndicator',+ summary:+ 'the mounted empty indicator receives one name, replaces it with two, then clears',+ facts: LIFECYCLE_FACTS,+ storyId: 'a11y-status-message-pattern--chat-typing-empty-to-message',+ },+ {+ id: 'chat-typing-name-mounted',+ binding: 'ChatTypingIndicator',+ summary: 'the documented named indicator is mounted with its status text',+ facts: {+ ...LIFECYCLE_FACTS,+ initialMessage: 'Ana is typing…',+ semanticTransitions: ['replace'],+ },+ storyId: 'a11y-status-message-pattern--chat-typing-name-mounted',+ },+ ];++export type ChatTypingStatusBindingState = ChatTypingStatusBindingDefinition;++export const CHAT_TYPING_STATUS_EXCLUSIONS = [+ {+ owner: 'ChatTypingIndicator',+ part: 'omitted names',+ reason:+ 'Omitted names and an empty names array render the same empty persistent status state, so one binding row covers both inputs.',+ },+ {+ owner: 'ChatTypingIndicator and theme',+ part: 'typing-dot animation and reduced motion',+ reason:+ 'The dots are decorative and aria-hidden; their paint and reduced-motion behavior stay in component and visual evidence.',+ },+ {+ owner: 'ChatMessageList',+ part: 'transcript log announcements',+ reason:+ 'The parent role=log owns sequential message updates and stream batching, which are distinct from this one atomic typing status.',+ },+] as const;diff --git a/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.test.tsx b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.test.tsxnew file mode 100644index 0000000000..61d66cbb81--- /dev/null+++ b/packages/lab/src/Chat/__tests__/ChatTypingIndicator.a11y.test.tsx@@ -0,0 +1,78 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/** Component-facing jsdom binding for ChatTypingIndicator's status-message states. */++import {describe, expect, it} from 'vitest';+import {act, cleanup, fireEvent, render, screen} from '@testing-library/react';+import {+ STATUS_MESSAGE_PATTERN,+ expectAccessibilitySpec,+} from '@astryxdesign/a11y-spec';+import {CHAT_TYPING_STATUS_KNOWN_FAILURES} from './ChatTypingIndicator.a11y.known-failures';+import {+ CHAT_TYPING_STATUS_STATE_RENDERS,+ transitionTestId,+} from './ChatTypingIndicator.a11y.renders';+import {+ CHAT_TYPING_STATUS_BINDING_STATES,+ CHAT_TYPING_STATUS_EXCLUSIONS,+ type ChatTypingStatusBindingState,+} from './ChatTypingIndicator.a11y.states';++async function transition(name: string): Promise<void> {+ fireEvent.click(screen.getByTestId(transitionTestId(name)));+ await act(async () => Promise.resolve());+}++function subjectFor(state: ChatTypingStatusBindingState): Element {+ const facts = state.facts;+ if (facts.kind !== 'live-region' || facts.role == null) {+ throw new Error(+ `${state.id}: this component binding declares no public role`,+ );+ }+ const matches = screen+ .getAllByRole(facts.role, {hidden: true})+ .filter(+ element =>+ (element.textContent ?? '').replace(/\s+/g, ' ').trim() ===+ facts.initialMessage,+ );+ if (matches.length !== 1) {+ throw new Error(+ `${state.id}: expected one ${facts.role} subject in initial state, found ${matches.length}`,+ );+ }+ return matches[0];+}++describe('ChatTypingIndicator status-message binding — jsdom lane', () => {+ it.each(+ CHAT_TYPING_STATUS_BINDING_STATES.map(+ state => [state.id, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectAccessibilitySpec({+ spec: STATUS_MESSAGE_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: CHAT_TYPING_STATUS_KNOWN_FAILURES,+ render: () => {+ render(CHAT_TYPING_STATUS_STATE_RENDERS[state.id]());+ },+ subject: () => subjectFor(state),+ transition,+ cleanup,+ });+ });++ it('records equivalent and separately owned states explicitly', () => {+ expect(CHAT_TYPING_STATUS_EXCLUSIONS.map(entry => entry.part)).toEqual([+ 'omitted names',+ 'typing-dot animation and reduced motion',+ 'transcript log announcements',+ ]);+ });+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9d39b36e45..3069088623 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -761,6 +761,9 @@ importers:specifier: '>=19.0.0'version: 19.2.7([email protected])devDependencies:+ '@astryxdesign/a11y-spec':+ specifier: workspace:*+ version: link:../../internal/a11y-spec'@astryxdesign/cli':specifier: workspace:*version: link:../cli