Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

test(a11y): add modal-dialog contract (#6188)

Cindy Zhang4d2bde2c6629
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index b7a739a0ba..ec499cb6c8 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -136,5 +136,9 @@
{
"component": "lab/ListInput",
"reason": "ListInput is a vertical record editor. Keyboard reordering uses ArrowUp/ArrowDown/Home/End, pointer dragging follows the physical pointer while preserving source direction in the preview, and add/remove motion is block-axis. Its grid and controls follow CSS direction with no component-owned horizontal semantic to mirror."
+ },
+ {
+ "component": "core/Dialog",
+ "reason": "Dialog uses logical inline offsets, logical container spacing, and direction-aware safe-area fallbacks. Its native modal lifecycle, focus entry and return, backdrop, and close glyph are direction-neutral; the directional entry translation follows the invoker's physical viewport position rather than reading direction. Dialog owns no left/right glyph swap, inline reordering, directional scroll or drag action, or horizontal keyboard behavior for the RTL audit to compare."
}
]
diff --git a/apps/storybook/stories/DialogA11y.stories.tsx b/apps/storybook/stories/DialogA11y.stories.tsx
new file mode 100644
index 0000000000..9d7ec88c63
--- /dev/null
+++ b/apps/storybook/stories/DialogA11y.stories.tsx
@@ -0,0 +1,52 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DialogA11y.stories.tsx
+ * @input Uses Dialog's shared modal-dialog state inventory and render map
+ * @output One checked-in browser reproduction story for every bound state
+ * @position Stable real-browser fixtures required by AST-009 FR30 and AST-021.
+ *
+ * SYNC: A new row in Dialog.a11y.states.ts needs a named export here. The
+ * Chromium binding catches a missing or renamed story by its stable storyId.
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {DIALOG_MODAL_BINDING_STATES} from '../../../packages/core/src/Dialog/__tests__/Dialog.a11y.states';
+import {renderDialogModalState} from '../../../packages/core/src/Dialog/__tests__/Dialog.a11y.renders';
+
+function storyFor(id: string): StoryObj {
+ const state = DIALOG_MODAL_BINDING_STATES.find(
+ candidate => candidate.id === id,
+ );
+ if (state == null) {
+ throw new Error(`no Dialog modal binding state "${id}"`);
+ }
+ return {
+ name: state.id,
+ render: () => renderDialogModalState(state),
+ };
+}
+
+const meta: Meta = {
+ title: 'a11y/Dialog modal pattern',
+ tags: ['no-visual'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Stable browser states for Dialog’s shared modal-dialog accessibility contract. They are exercised interactively rather than used as visual baselines.',
+ },
+ },
+ },
+};
+
+export default meta;
+
+export const LabelledDescribedDefaultTitle = storyFor(
+ 'labelled-described-default-title',
+);
+export const ExplicitDescendantFocus = storyFor('explicit-descendant-focus');
+export const ConditionalContentFocusRestoration = storyFor(
+ 'conditional-content-focus-restoration',
+);
+export const NoFocusableContent = storyFor('no-focusable-content');
diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.md
index fabe51df15..c13bf8f4c8 100644
--- a/internal/a11y-spec/README.md
+++ b/internal/a11y-spec/README.md
@@ -43,17 +43,19 @@ src/
├── checkbox.* the checkbox pattern, same four files
├── switch.* the switch pattern, same four files
├── button.* the button pattern, same four files
- └── text-input.* the native text-input pattern, same four files
+ ├── text-input.* the native text-input pattern, same four files
+ └── modal-dialog.* the native modal-dialog pattern, same four files
```
## The patterns
-| Pattern | Adopted from | Bound by |
-| ------------ | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
-| `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 |
+| Pattern | Adopted from | Bound by |
+| -------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
+| `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 |
The `text-input` contract is native rather than APG-derived. It covers the
role-bearing `<input>` or `<textarea>` only; composed clear and tooltip buttons
@@ -73,6 +75,11 @@ button's action leaves no trace on the button at all. A pattern like that reads
binding that does not makes every expectation reading it fail loudly, never
pass quietly.
+Ordering-sensitive focus expectations similarly read `initialFocusEntry()`.
+The binding starts recording before its subject can receive focus and supplies
+whether the subject was already in its native modal state at the first entry;
+a missing observation is a binding fault, not a contract pass or failure.
+
## Evidence layers are the load-bearing idea
An expectation names the layer that characterizes its claim, plus — in
diff --git a/internal/a11y-spec/src/check.test.ts b/internal/a11y-spec/src/check.test.ts
index d3c14253e7..c549c7bf2e 100644
--- a/internal/a11y-spec/src/check.test.ts
+++ b/internal/a11y-spec/src/check.test.ts
@@ -15,7 +15,11 @@
*/
import {describe, expect, it, vi} from 'vitest';
-import {definePattern, type PatternContract} from './contract';
+import {
+ definePattern,
+ type ExpectationContext,
+ type PatternContract,
+} from './contract';
import type {EvidenceLayer, Harness, Subject} from './harness';
import {
blockingResults,
@@ -40,6 +44,7 @@ function harness(observes: readonly EvidenceLayer[]): Harness {
name: 'stub',
observes,
subject: async () => subject,
+ related: async () => subject,
click: async () => {},
abortedPress: async () => {},
typeText: async () => {},
@@ -50,7 +55,7 @@ function harness(observes: readonly EvidenceLayer[]): Harness {
}
function contractThat(
- behaviour: () => void,
+ behaviour: (context: ExpectationContext<Facts>) => void | Promise<void>,
overrides: {
layer?: EvidenceLayer;
alsoNeeds?: readonly EvidenceLayer[];
@@ -87,7 +92,7 @@ function contractThat(
overrides.enforcement === 'advisory'
? 'Nothing adopts the stub outcome.'
: undefined,
- run: async () => behaviour(),
+ run: async context => behaviour(context),
},
],
});
@@ -114,6 +119,7 @@ async function run(
knownFailures?: readonly KnownFailure[];
observes?: readonly EvidenceLayer[];
state?: string;
+ initialFocusEntry?: () => Promise<{readonly subjectWasModal: boolean}>;
} = {},
) {
return checkAccessibilitySpec({
@@ -123,6 +129,7 @@ async function run(
facts: options.facts ?? {applicable: true},
mount: async () => harness(options.observes ?? ['unit', 'dom']),
knownFailures: options.knownFailures,
+ initialFocusEntry: options.initialFocusEntry,
});
}
@@ -198,6 +205,36 @@ describe('checkAccessibilitySpec', () => {
expect(result.results[0]?.status).toBe('pass');
});
+ it('treats a missing first-focus observation as a binding fault', async () => {
+ const spec = contractThat(
+ async ({initialFocusEntry}) => {
+ await initialFocusEntry();
+ },
+ {layer: 'real-browser'},
+ );
+
+ await expect(
+ run(spec, {observes: ['unit', 'dom', 'real-browser']}),
+ ).rejects.toThrow('supplies no focus-entry observation');
+ });
+
+ it('passes the binding-owned first-focus observation to the expectation', async () => {
+ const observed = vi.fn(async () => ({subjectWasModal: true}));
+ const spec = contractThat(
+ async ({initialFocusEntry}) => {
+ expect(await initialFocusEntry()).toEqual({subjectWasModal: true});
+ },
+ {layer: 'real-browser'},
+ );
+
+ const result = await run(spec, {
+ observes: ['unit', 'dom', 'real-browser'],
+ initialFocusEntry: observed,
+ });
+ expect(observed).toHaveBeenCalledOnce();
+ 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.ts
index df6f53165e..3d25602075 100644
--- a/internal/a11y-spec/src/check.ts
+++ b/internal/a11y-spec/src/check.ts
@@ -37,9 +37,14 @@ import {
requiredLayers,
type Enforcement,
type Expectation,
+ type InitialFocusEntryObservation,
type PatternContract,
} from './contract';
-import type {EvidenceLayer, Harness} from './harness';
+import {
+ MissingHarnessRelation,
+ type EvidenceLayer,
+ type Harness,
+} from './harness';
export type ResultStatus =
/** The outcome was observed. */
@@ -124,6 +129,11 @@ export interface CheckAccessibilitySpecOptions<Facts> {
* it where the pattern needs it is a binding fault and fails loudly.
*/
readonly activations?: () => Promise<number>;
+ /**
+ * Browser event evidence for ordering-sensitive focus expectations. The
+ * binding must begin recording before the subject can receive focus.
+ */
+ readonly initialFocusEntry?: () => Promise<InitialFocusEntryObservation>;
/**
* 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
@@ -248,9 +258,20 @@ export async function checkAccessibilitySpec<Facts>(
}
return options.activations();
},
+ initialFocusEntry: async () => {
+ if (options.initialFocusEntry == null) {
+ throw new MissingBindingCapability(
+ `${expectation.id} reads the first focus entry, but this binding supplies no focus-entry observation`,
+ );
+ }
+ return options.initialFocusEntry();
+ },
});
} catch (error) {
- if (error instanceof MissingBindingCapability) {
+ if (
+ error instanceof MissingBindingCapability ||
+ error instanceof MissingHarnessRelation
+ ) {
// Never a contract result: the outcome was not tested at all.
throw error;
}
diff --git a/internal/a11y-spec/src/contract.test.ts b/internal/a11y-spec/src/contract.test.ts
index fc54c41782..bea9c542a0 100644
--- a/internal/a11y-spec/src/contract.test.ts
+++ b/internal/a11y-spec/src/contract.test.ts
@@ -95,6 +95,15 @@ describe('definePattern', () => {
).not.toThrow();
});
+ it('accepts a hyphenated adopted-pattern slug in an expectation id', () => {
+ expect(
+ pattern({
+ pattern: 'modal-dialog',
+ expectations: [expectation({id: 'modal-dialog.name.exposed'})],
+ }),
+ ).not.toThrow();
+ });
+
it('refuses an expectation with no user outcome', () => {
expect(pattern({expectations: [expectation({outcome: ' '})]})).toThrow(
/states no user outcome/,
diff --git a/internal/a11y-spec/src/contract.ts b/internal/a11y-spec/src/contract.ts
index 07bdec9b1c..dc28bb84f0 100644
--- a/internal/a11y-spec/src/contract.ts
+++ b/internal/a11y-spec/src/contract.ts
@@ -141,6 +141,11 @@ export class NotApplicableHere extends Error {
}
}
+/** What the browser observed at the first focus entry into the mounted subject. */
+export interface InitialFocusEntryObservation {
+ readonly subjectWasModal: boolean;
+}
+
/** What an expectation is handed when it runs. */
export interface ExpectationContext<Facts> {
readonly harness: Harness;
@@ -170,6 +175,13 @@ export interface ExpectationContext<Facts> {
* as a harness fault, loudly, rather than quietly passing.
*/
readonly activations: () => Promise<number>;
+ /**
+ * The first focus entry into the mounted subject, captured by the binding from
+ * browser events that occurred before the expectation began sampling state.
+ * A binding that cannot supply it fails as a binding fault rather than turning
+ * a missing observation into a contract result.
+ */
+ readonly initialFocusEntry: () => Promise<InitialFocusEntryObservation>;
}
export interface Expectation<Facts> {
diff --git a/internal/a11y-spec/src/harness.ts b/internal/a11y-spec/src/harness.ts
index 33fd70e0b6..8225aa1134 100644
--- a/internal/a11y-spec/src/harness.ts
+++ b/internal/a11y-spec/src/harness.ts
@@ -50,6 +50,8 @@ export interface ComputedNode {
readonly description: string;
/** Computed text value, or null when the node exposes no value. */
readonly value: string | null;
+ /** Whether the engine exposes the subject as modal. */
+ readonly modal: boolean | null;
/** Whether the engine exposes the textbox as multi-line. */
readonly multiline: boolean | null;
/** Whether the engine exposes the control as read-only. */
@@ -99,6 +101,12 @@ export interface Subject {
visibleLabelText(): Promise<string | null>;
/** Real-browser layer: whether this node currently holds focus. */
isFocused(): Promise<boolean>;
+ /** Real-browser layer: whether focus is on this node or one of its descendants. */
+ containsFocus(): Promise<boolean>;
+ /** Real-browser layer: whether this node is an active modal in the top layer. */
+ isModal(): Promise<boolean>;
+ /** Real-browser layer: whether a pointer can currently reach this node. */
+ canReceivePointer(): Promise<boolean>;
/** Real-browser layer: move focus here the way a user's Tab would leave it. */
focus(): Promise<void>;
}
@@ -116,6 +124,12 @@ export interface Harness {
readonly observes: readonly EvidenceLayer[];
/** The element the binding designates as the pattern's control. */
subject(): Promise<Subject>;
+ /**
+ * Another public-semantic element involved in the outcome, such as the
+ * invoker a modal dialog returns focus to. Bindings name these relations;
+ * contracts never query component-private structure.
+ */
+ related(name: string): Promise<Subject>;
/**
* Real-browser layer: click the subject the way a pointer user would,
* including the browser's own judgement that the control is there to be
@@ -143,6 +157,15 @@ export interface Harness {
resetFocus(): Promise<void>;
}
+export class MissingHarnessRelation extends Error {
+ constructor(harness: string, relation: string) {
+ super(
+ `The ${harness} harness binding supplies no related subject named "${relation}".`,
+ );
+ this.name = 'MissingHarnessRelation';
+ }
+}
+
/**
* Thrown when something asks a harness for an observation it cannot make. The
* runner prevents this by checking `observes` first; the guard exists so a
diff --git a/internal/a11y-spec/src/harness/chromium.ts b/internal/a11y-spec/src/harness/chromium.ts
index 20025437d1..c8f8457a9b 100644
--- a/internal/a11y-spec/src/harness/chromium.ts
+++ b/internal/a11y-spec/src/harness/chromium.ts
@@ -31,6 +31,7 @@
import {errors as playwrightErrors} from '@playwright/test';
import type {CDPSession, Locator, Page} from '@playwright/test';
import {
+ MissingHarnessRelation,
type ComputedNode,
type EvidenceLayer,
type Harness,
@@ -64,6 +65,18 @@ function isTimeout(error: unknown): boolean {
return error instanceof playwrightErrors.TimeoutError;
}
+async function canReceivePointer(locator: Locator): Promise<boolean> {
+ try {
+ await locator.click({trial: true, timeout: POINTER_REACH_BUDGET_MS});
+ return true;
+ } catch (error) {
+ if (isTimeout(error)) {
+ return false;
+ }
+ throw error;
+ }
+}
+
const KEYS: Record<Key, string> = {
Space: ' ',
Enter: 'Enter',
@@ -167,6 +180,7 @@ async function computedNode(
name: '',
description: '',
value: null,
+ modal: null,
multiline: null,
readOnly: null,
required: null,
@@ -191,6 +205,7 @@ async function computedNode(
: role === 'textbox'
? ''
: null,
+ modal: optionalFlag(node, 'modal'),
multiline: optionalFlag(node, 'multiline'),
readOnly: optionalFlag(node, 'readonly'),
required: optionalFlag(node, 'required'),
@@ -239,10 +254,12 @@ export interface ChromiumHarnessOptions {
readonly subject: Locator;
/** The surface that receives pointer input when it differs from the semantic node. */
readonly pointerTarget?: Locator;
- /** A binding-owned visible label when it is not the subject's DOM label. */
- readonly visibleLabel?: Locator;
+ /** A binding-owned visible label when it is not the subject's DOM label. Null means this state deliberately has no visible label. */
+ readonly visibleLabel?: Locator | null;
/** A CDP session on `page`, reused across expectations. */
readonly cdp: CDPSession;
+ /** Public-semantic elements participating in relationship expectations. */
+ readonly related?: Readonly<Record<string, Locator>>;
}
export function createChromiumHarness(
@@ -405,8 +422,11 @@ export function createChromiumHarness(
}),
computed: () => computedNode(cdp, locator),
visibleLabelText: async () => {
+ if (visibleLabel === null) {
+ return null;
+ }
const explicitLabel =
- visibleLabel == null ? null : await visibleLabel.elementHandle();
+ visibleLabel === undefined ? null : await visibleLabel.elementHandle();
try {
return await locator.evaluate((element, explicitLabel) => {
// Whether a person can actually read this text. Two questions, because
@@ -604,13 +624,127 @@ export function createChromiumHarness(
locator.evaluate(
element => element.ownerDocument.activeElement === element,
),
+ containsFocus: () =>
+ locator.evaluate(element => {
+ const active = element.ownerDocument.activeElement;
+ return (
+ active != null && (active === element || element.contains(active))
+ );
+ }),
+ isModal: () => locator.evaluate(element => element.matches(':modal')),
+ canReceivePointer: () => canReceivePointer(locator),
focus: () => locator.focus(),
};
+ const relatedSubject = (name: string): Subject => {
+ const related = options.related?.[name];
+ if (related == null) {
+ throw new MissingHarnessRelation('chromium', name);
+ }
+ return {
+ attribute: attribute => related.getAttribute(attribute),
+ idReferences: attribute =>
+ related.evaluate(
+ (element, relation) =>
+ (element.getAttribute(relation) ?? '')
+ .split(/\s+/)
+ .filter(Boolean)
+ .map(id => {
+ const target = element.ownerDocument.getElementById(id);
+ return target == null
+ ? null
+ : (target.textContent ?? '').trim();
+ }),
+ attribute,
+ ),
+ visibleIdReferences: attribute =>
+ related.evaluate(
+ (element, relation) =>
+ (element.getAttribute(relation) ?? '')
+ .split(/\s+/)
+ .filter(Boolean)
+ .map(id => {
+ const target = element.ownerDocument.getElementById(id);
+ if (target == null || !target.checkVisibility()) {
+ return null;
+ }
+ const text = (target.textContent ?? '')
+ .replace(/\s+/g, ' ')
+ .trim();
+ return text === '' ? null : text;
+ }),
+ attribute,
+ ),
+ labelText: () =>
+ related.evaluate(element => {
+ const labelledBy = element.getAttribute('aria-labelledby');
+ if (labelledBy != null && labelledBy.trim() !== '') {
+ const text = labelledBy
+ .split(/\s+/)
+ .filter(Boolean)
+ .map(
+ id =>
+ element.ownerDocument.getElementById(id)?.textContent ?? '',
+ )
+ .join(' ')
+ .replace(/\s+/g, ' ')
+ .trim();
+ return text === '' ? null : text;
+ }
+ const ariaLabel = element.getAttribute('aria-label')?.trim();
+ if (ariaLabel != null && ariaLabel !== '') {
+ return ariaLabel;
+ }
+ if (
+ element instanceof HTMLInputElement ||
+ element instanceof HTMLTextAreaElement
+ ) {
+ const text = Array.from(element.labels ?? [])
+ .map(label => label.textContent ?? '')
+ .join(' ')
+ .replace(/\s+/g, ' ')
+ .trim();
+ return text === '' ? null : text;
+ }
+ return null;
+ }),
+ textValue: () =>
+ related.evaluate(element => {
+ if (
+ element instanceof HTMLInputElement ||
+ element instanceof HTMLTextAreaElement
+ ) {
+ return element.value;
+ }
+ return null;
+ }),
+ computed: () => computedNode(cdp, related),
+ visibleLabelText: async () => {
+ const value = (await related.innerText()).trim();
+ return value === '' ? null : value;
+ },
+ isFocused: () =>
+ related.evaluate(
+ element => element.ownerDocument.activeElement === element,
+ ),
+ containsFocus: () =>
+ related.evaluate(element => {
+ const active = element.ownerDocument.activeElement;
+ return (
+ active != null && (active === element || element.contains(active))
+ );
+ }),
+ isModal: () => related.evaluate(element => element.matches(':modal')),
+ canReceivePointer: () => canReceivePointer(related),
+ focus: () => related.focus(),
+ };
+ };
+
return {
name: 'chromium',
observes: CHROMIUM_OBSERVES,
subject: async () => subject,
+ related: async name => relatedSubject(name),
click: async (_subject, options) => {
// Without `force`, Playwright first satisfies itself that the control is
// visible, stable, enabled, and actually receives pointer events — so an
diff --git a/internal/a11y-spec/src/harness/jsdom.ts b/internal/a11y-spec/src/harness/jsdom.ts
index aaf2c7d2e1..9b33afee5a 100644
--- a/internal/a11y-spec/src/harness/jsdom.ts
+++ b/internal/a11y-spec/src/harness/jsdom.ts
@@ -20,6 +20,7 @@
*/
import {
+ MissingHarnessRelation,
UnobservableError,
type Harness,
type Subject,
@@ -109,6 +110,12 @@ function createSubject(element: Element): Subject {
visibleLabelText: async () =>
unobservable('real-browser', 'what a label actually renders as'),
isFocused: async () => unobservable('real-browser', 'real focus'),
+ containsFocus: async () =>
+ unobservable('real-browser', 'whether focus is inside a subject'),
+ isModal: async () =>
+ unobservable('real-browser', 'native modal top-layer state'),
+ canReceivePointer: async () =>
+ unobservable('real-browser', 'pointer reachability'),
focus: async () => unobservable('real-browser', 'real focus'),
};
}
@@ -121,6 +128,8 @@ export interface JsdomHarnessOptions {
* the expectation under test instead of making the subject unfindable.
*/
readonly subject: Element;
+ /** Public-semantic elements participating in a relationship expectation. */
+ readonly related?: Readonly<Record<string, Element>>;
}
export function createJsdomHarness(options: JsdomHarnessOptions): Harness {
@@ -129,6 +138,13 @@ export function createJsdomHarness(options: JsdomHarnessOptions): Harness {
name: HARNESS,
observes: JSDOM_OBSERVES,
subject: async () => subject,
+ related: async name => {
+ const element = options.related?.[name];
+ if (element == null) {
+ throw new MissingHarnessRelation(HARNESS, name);
+ }
+ return createSubject(element);
+ },
click: async () =>
unobservable('real-browser', 'a real pointer activation'),
abortedPress: async () =>
diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.ts
index 8bf2b602b7..ff11d9901d 100644
--- a/internal/a11y-spec/src/index.ts
+++ b/internal/a11y-spec/src/index.ts
@@ -27,6 +27,7 @@ export {
type Enforcement,
type Expectation,
type ExpectationContext,
+ type InitialFocusEntryObservation,
type NormativeSource,
type PatternContract,
type WcagCriterion,
@@ -42,6 +43,7 @@ export {
export {
EVIDENCE_LAYERS,
+ MissingHarnessRelation,
UnobservableError,
type ComputedNode,
type EvidenceLayer,
@@ -87,6 +89,11 @@ export {CHECKBOX_PATTERN, type CheckboxStateFacts} from './patterns/checkbox';
export {SWITCH_PATTERN, type SwitchStateFacts} from './patterns/switch';
+export {
+ MODAL_DIALOG_PATTERN,
+ type ModalDialogStateFacts,
+} from './patterns/modal-dialog';
+
export {saysInOrder, spokenWords} from './spoken';
export {BUTTON_PATTERN, type ButtonStateFacts} from './patterns/button';
diff --git a/internal/a11y-spec/src/patterns/modal-dialog.chromium.spec.ts b/internal/a11y-spec/src/patterns/modal-dialog.chromium.spec.ts
new file mode 100644
index 0000000000..aaff6a4664
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/modal-dialog.chromium.spec.ts
@@ -0,0 +1,151 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file modal-dialog.chromium.spec.ts
+ * @input Uses the modal-dialog contract, its plain-HTML fixtures, the Chromium
+ * harness, and checkAccessibilitySpec
+ * @output Positive and negative proof for browser-owned modal-dialog outcomes
+ * @position Real-browser self-test of the contract, not a component binding.
+ */
+
+import {expect, test, type CDPSession, type Page} from '@playwright/test';
+import {
+ MissingBindingCapability,
+ checkAccessibilitySpec,
+ type ExpectationResult,
+} from '../check';
+import {describeExpectation, requiredLayers} from '../contract';
+import {
+ CHROMIUM_OBSERVES,
+ createChromiumHarness,
+ holdMotionStill,
+} from '../harness/chromium';
+import {MODAL_DIALOG_PATTERN} from './modal-dialog';
+import {
+ MODAL_DIALOG_CONFORMING_FIXTURES,
+ MODAL_DIALOG_MUTATIONS,
+ MODAL_DIALOG_SUBJECT_SELECTOR,
+ modalDialogFixture,
+ type ModalDialogFixture,
+} from './modal-dialog.fixtures';
+
+function fixturePage(target: ModalDialogFixture): string {
+ const method = target.presentation === 'nonmodal' ? 'show' : 'showModal';
+ const present = target.focusBeforeModalPresentation
+ ? `subject.show(); const initial = subject.querySelector('[data-a11y-relation~=initial]'); if (initial instanceof HTMLElement) initial.focus(); subject.close(); subject.showModal();`
+ : `subject.${method}();`;
+ return `<!doctype html><html lang="en"><body><button type="button" data-a11y-relation="invoker" onclick="const subject = document.querySelector('${MODAL_DIALOG_SUBJECT_SELECTOR}'); if (subject instanceof HTMLDialogElement && !subject.open) { ${present} }">Open dialog</button>${target.html}<button type="button" data-a11y-relation="background">Background action</button></body></html>`;
+}
+
+async function results(
+ page: Page,
+ cdp: CDPSession,
+ target: ModalDialogFixture,
+ only?: readonly string[],
+): Promise<readonly ExpectationResult[]> {
+ let focusEntryWasModal: boolean | undefined;
+ const run = await checkAccessibilitySpec({
+ spec: MODAL_DIALOG_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ only,
+ mount: async () => {
+ await page.setContent(fixturePage(target));
+ await holdMotionStill(page);
+ const subject = page.locator(MODAL_DIALOG_SUBJECT_SELECTOR);
+ await subject.evaluate(dialog => {
+ dialog.setAttribute('data-a11y-focus-entry-modal', 'unobserved');
+ const recordFirstEntry = (event: FocusEvent) => {
+ if (event.target instanceof Node && dialog.contains(event.target)) {
+ dialog.setAttribute(
+ 'data-a11y-focus-entry-modal',
+ String(dialog.matches(':modal')),
+ );
+ document.removeEventListener('focusin', recordFirstEntry, true);
+ }
+ };
+ document.addEventListener('focusin', recordFirstEntry, true);
+ });
+ await page.locator('[data-a11y-relation="invoker"]').click();
+ const recordedFocusEntry = await subject.getAttribute(
+ 'data-a11y-focus-entry-modal',
+ );
+ focusEntryWasModal =
+ recordedFocusEntry === 'true'
+ ? true
+ : recordedFocusEntry === 'false'
+ ? false
+ : undefined;
+ if (target.moveFocusOutsideAfterOpen === true) {
+ await page.locator('[data-a11y-relation="background"]').focus();
+ }
+ const visibleLabel = page.locator('[data-a11y-visible-label]');
+ return createChromiumHarness({
+ page,
+ subject,
+ visibleLabel: (await visibleLabel.count()) === 0 ? null : visibleLabel,
+ cdp,
+ related: {
+ initial: page.locator('[data-a11y-relation~="initial"]'),
+ close: page.locator('[data-a11y-relation~="close"]'),
+ invoker: page.locator('[data-a11y-relation~="invoker"]'),
+ background: page.locator('[data-a11y-relation~="background"]'),
+ },
+ });
+ },
+ initialFocusEntry: async () => {
+ if (focusEntryWasModal === undefined) {
+ throw new MissingBindingCapability(
+ 'modal-dialog fixture supplies no focus-entry observation',
+ );
+ }
+ return {subjectWasModal: focusEntryWasModal};
+ },
+ });
+ return run.results;
+}
+
+test.describe('modal-dialog contract — conforming fixtures', () => {
+ for (const id of MODAL_DIALOG_CONFORMING_FIXTURES) {
+ test(`${id}: every applicable expectation passes`, async ({page}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const observed = await results(page, cdp, modalDialogFixture(id));
+ const notPassing = observed.filter(
+ result =>
+ result.status !== 'pass' && result.status !== 'not-applicable',
+ );
+ expect(
+ notPassing.map(
+ result => `${result.expectation}: ${result.detail ?? ''}`,
+ ),
+ ).toEqual([]);
+ });
+ }
+});
+
+test.describe('modal-dialog contract — deliberately violating fixtures', () => {
+ for (const expectation of MODAL_DIALOG_PATTERN.expectations) {
+ if (
+ !requiredLayers(expectation).every(layer =>
+ CHROMIUM_OBSERVES.includes(layer),
+ )
+ ) {
+ continue;
+ }
+ for (const fixtureId of MODAL_DIALOG_MUTATIONS[expectation.id] ?? []) {
+ test(`${describeExpectation(expectation)} — fails against ${fixtureId}`, async ({
+ page,
+ }) => {
+ const cdp = await page.context().newCDPSession(page);
+ const [result] = await results(
+ page,
+ cdp,
+ modalDialogFixture(fixtureId),
+ [expectation.id],
+ );
+ expect(result?.status, result?.detail ?? 'no result').toBe('fail');
+ });
+ }
+ }
+});
diff --git a/internal/a11y-spec/src/patterns/modal-dialog.fixtures.ts b/internal/a11y-spec/src/patterns/modal-dialog.fixtures.ts
new file mode 100644
index 0000000000..7607bae049
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/modal-dialog.fixtures.ts
@@ -0,0 +1,189 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file modal-dialog.fixtures.ts
+ * @input Uses ./modal-dialog (ModalDialogStateFacts)
+ * @output Plain-HTML fixtures and mutation mapping for the modal-dialog contract
+ * @position Contract proof only. These fixtures contain no Astryx components.
+ */
+
+import type {ModalDialogStateFacts} from './modal-dialog';
+
+export const MODAL_DIALOG_SUBJECT_SELECTOR = '[data-a11y-subject]';
+
+export interface ModalDialogFixture {
+ readonly id: string;
+ readonly summary: string;
+ readonly facts: ModalDialogStateFacts;
+ readonly html: string;
+ readonly presentation?: 'modal' | 'nonmodal';
+ readonly focusBeforeModalPresentation?: boolean;
+ readonly moveFocusOutsideAfterOpen?: boolean;
+}
+
+const LABELLED_FACTS: ModalDialogStateFacts = {
+ labelledBy: true,
+ hasDescriptionReference: false,
+ hasDeclaredInitialTarget: false,
+ usesNativeFocusFallback: false,
+ exercisesFocusRestoration: false,
+ makesBackgroundInert: false,
+};
+
+const INTERACTIVE_FACTS: ModalDialogStateFacts = {
+ ...LABELLED_FACTS,
+ hasDeclaredInitialTarget: true,
+ exercisesFocusRestoration: true,
+ makesBackgroundInert: true,
+};
+
+export const MODAL_DIALOG_FIXTURES: readonly ModalDialogFixture[] = [
+ {
+ id: 'conforming-labelled',
+ summary: 'a dialog labelled by an existing heading',
+ facts: LABELLED_FACTS,
+ html: '<dialog data-a11y-subject aria-labelledby="title"><h2 id="title" data-a11y-visible-label>Review changes</h2></dialog>',
+ },
+ {
+ id: 'conforming-described',
+ summary: 'a labelled dialog with attached supporting text',
+ facts: {...LABELLED_FACTS, hasDescriptionReference: true},
+ html: '<dialog data-a11y-subject aria-labelledby="title" aria-describedby="details"><h2 id="title" data-a11y-visible-label>Review changes</h2><p id="details">Confirm the changes before saving.</p></dialog>',
+ },
+ {
+ id: 'conforming-interactive',
+ summary:
+ 'a labelled modal with an explicit initial target and two controls',
+ facts: INTERACTIVE_FACTS,
+ html: '<dialog data-a11y-subject aria-labelledby="title"><h2 id="title" data-a11y-visible-label>Review changes</h2><button type="button" data-a11y-relation="initial close" autofocus onclick="this.closest(\'dialog\').close()">Confirm</button><button type="button">Cancel</button></dialog>',
+ },
+ {
+ id: 'conforming-no-focusable-content',
+ summary: 'a named modal with no focusable descendants',
+ facts: {
+ ...LABELLED_FACTS,
+ labelledBy: false,
+ usesNativeFocusFallback: true,
+ exercisesFocusRestoration: false,
+ makesBackgroundInert: true,
+ },
+ html: '<dialog data-a11y-subject aria-label="Read terms"><p>There are no controls in this task.</p></dialog>',
+ },
+ {
+ id: 'violating-native-fallback-outside',
+ summary: 'a non-modal dialog with no descendant focus target',
+ facts: {
+ ...LABELLED_FACTS,
+ labelledBy: false,
+ usesNativeFocusFallback: true,
+ },
+ presentation: 'nonmodal',
+ moveFocusOutsideAfterOpen: true,
+ html: '<dialog data-a11y-subject aria-label="Read terms"><p>There are no controls in this task.</p></dialog>',
+ },
+ {
+ id: 'violating-modal-unexposed',
+ summary: 'a native modal whose accessibility semantics deny modality',
+ facts: LABELLED_FACTS,
+ html: '<dialog data-a11y-subject aria-modal="false" aria-labelledby="title"><h2 id="title" data-a11y-visible-label>Review changes</h2><button type="button">Continue</button></dialog>',
+ },
+ {
+ id: 'violating-focus-before-modal',
+ summary:
+ 'a dialog whose requested content receives focus before native modal presentation',
+ facts: INTERACTIVE_FACTS,
+ focusBeforeModalPresentation: true,
+ html: '<dialog data-a11y-subject aria-labelledby="title"><h2 id="title" data-a11y-visible-label>Review changes</h2><button type="button" data-a11y-relation="initial close" autofocus onclick="this.closest(\'dialog\').close()">Confirm</button></dialog>',
+ },
+ {
+ id: 'violating-initial-target',
+ summary:
+ 'a modal that focuses another control instead of its declared target',
+ facts: INTERACTIVE_FACTS,
+ html: '<dialog data-a11y-subject aria-labelledby="title"><h2 id="title" data-a11y-visible-label>Review changes</h2><button type="button" autofocus>Wrong target</button><button type="button" data-a11y-relation="initial">Confirm</button></dialog>',
+ },
+ {
+ id: 'violating-background-active',
+ summary: 'a non-modal dialog that leaves the background interactive',
+ facts: INTERACTIVE_FACTS,
+ presentation: 'nonmodal',
+ html: '<dialog data-a11y-subject aria-labelledby="title"><h2 id="title" data-a11y-visible-label>Review changes</h2><button type="button" autofocus>Confirm</button><button type="button">Cancel</button></dialog>',
+ },
+ {
+ id: 'violating-focus-not-restored',
+ summary: 'a modal that moves focus away from its invoker after close',
+ facts: INTERACTIVE_FACTS,
+ html: '<dialog data-a11y-subject aria-labelledby="title"><h2 id="title" data-a11y-visible-label>Review changes</h2><button type="button" data-a11y-relation="initial close" autofocus onclick="this.closest(\'dialog\').close(); queueMicrotask(() => document.querySelector(\'[data-a11y-relation~=background]\').focus())">Confirm</button></dialog>',
+ },
+ {
+ id: 'violating-nonmodal-presentation',
+ summary: 'a dialog shown without a native modal boundary',
+ facts: LABELLED_FACTS,
+ presentation: 'nonmodal',
+ html: '<dialog data-a11y-subject aria-labelledby="title"><h2 id="title" data-a11y-visible-label>Review changes</h2><button type="button">Continue</button></dialog>',
+ },
+ {
+ id: 'violating-name-mismatch',
+ summary: 'a dialog whose accessible name replaces its visible title',
+ facts: {...LABELLED_FACTS, labelledBy: false},
+ html: '<dialog data-a11y-subject aria-label="Confirm"><h2 data-a11y-visible-label>Review changes</h2><button type="button">Continue</button></dialog>',
+ },
+ {
+ id: 'violating-unnamed',
+ summary: 'a dialog with no accessible name',
+ facts: {...LABELLED_FACTS, labelledBy: false},
+ html: '<dialog data-a11y-subject><button type="button">Continue</button></dialog>',
+ },
+ {
+ id: 'violating-generic-role',
+ summary: 'a modal-like surface with no dialog role',
+ facts: LABELLED_FACTS,
+ html: '<div data-a11y-subject aria-labelledby="title"><h2 id="title" data-a11y-visible-label>Review changes</h2></div>',
+ },
+ {
+ id: 'violating-dangling-label',
+ summary: 'a dialog labelled by an id that resolves to nothing',
+ facts: LABELLED_FACTS,
+ html: '<dialog data-a11y-subject aria-labelledby="missing"></dialog>',
+ },
+ {
+ id: 'violating-dangling-description',
+ summary: 'a dialog described by an id that resolves to nothing',
+ facts: {...LABELLED_FACTS, hasDescriptionReference: true},
+ html: '<dialog data-a11y-subject aria-labelledby="title" aria-describedby="missing"><h2 id="title" data-a11y-visible-label>Review changes</h2></dialog>',
+ },
+];
+
+export function modalDialogFixture(id: string): ModalDialogFixture {
+ const found = MODAL_DIALOG_FIXTURES.find(candidate => candidate.id === id);
+ if (found == null) {
+ throw new Error(`unknown modal-dialog fixture "${id}"`);
+ }
+ return found;
+}
+
+export const MODAL_DIALOG_CONFORMING_FIXTURES: readonly string[] = [
+ 'conforming-labelled',
+ 'conforming-described',
+ 'conforming-interactive',
+ 'conforming-no-focusable-content',
+];
+
+export const MODAL_DIALOG_MUTATIONS: Readonly<
+ Record<string, readonly string[]>
+> = {
+ 'modal-dialog.modal.in-top-layer': ['violating-nonmodal-presentation'],
+ 'modal-dialog.modal.exposed': ['violating-modal-unexposed'],
+ 'modal-dialog.focus.enters-after-modal': ['violating-focus-before-modal'],
+ 'modal-dialog.focus.initial-target': ['violating-initial-target'],
+ 'modal-dialog.focus.native-fallback': ['violating-native-fallback-outside'],
+ 'modal-dialog.focus.restored': ['violating-focus-not-restored'],
+ 'modal-dialog.background.inert': ['violating-background-active'],
+ 'modal-dialog.role.exposed': ['violating-generic-role'],
+ 'modal-dialog.name.exposed': ['violating-unnamed'],
+ 'modal-dialog.name.matches-visible-label': ['violating-name-mismatch'],
+ 'modal-dialog.name.references-resolve': ['violating-dangling-label'],
+ 'modal-dialog.description.references-resolve': [
+ 'violating-dangling-description',
+ ],
+};
diff --git a/internal/a11y-spec/src/patterns/modal-dialog.jsdom.test.ts b/internal/a11y-spec/src/patterns/modal-dialog.jsdom.test.ts
new file mode 100644
index 0000000000..a04453a1ee
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/modal-dialog.jsdom.test.ts
@@ -0,0 +1,141 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file modal-dialog.jsdom.test.ts
+ * @input Uses the modal-dialog contract, its plain-HTML fixtures, the jsdom
+ * harness, and checkAccessibilitySpec
+ * @output Positive and negative proof for every DOM-observable expectation
+ * @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 {requiredLayers, unansweredDimensions} from '../contract';
+import {JSDOM_OBSERVES, createJsdomHarness} from '../harness/jsdom';
+import {MODAL_DIALOG_PATTERN} from './modal-dialog';
+import {
+ MODAL_DIALOG_CONFORMING_FIXTURES,
+ MODAL_DIALOG_MUTATIONS,
+ MODAL_DIALOG_SUBJECT_SELECTOR,
+ modalDialogFixture,
+ type ModalDialogFixture,
+} from './modal-dialog.fixtures';
+
+const observableHere = MODAL_DIALOG_PATTERN.expectations.filter(expectation =>
+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),
+);
+
+afterEach(() => {
+ document.body.replaceChildren();
+});
+
+async function resultsFor(target: ModalDialogFixture) {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const result = await checkAccessibilitySpec({
+ spec: MODAL_DIALOG_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ mount: async () => {
+ container.innerHTML = target.html;
+ const subject = container.querySelector(MODAL_DIALOG_SUBJECT_SELECTOR);
+ if (subject == null) {
+ throw new Error(`fixture "${target.id}" marks no subject element`);
+ }
+ return createJsdomHarness({subject});
+ },
+ unmount: () => {
+ container.innerHTML = '';
+ },
+ });
+ return result.results;
+}
+
+function resultFor(
+ results: readonly ExpectationResult[],
+ id: string,
+): ExpectationResult {
+ const found = results.find(result => result.expectation === id);
+ if (found == null) {
+ throw new Error(`no result for ${id}`);
+ }
+ return found;
+}
+
+describe('modal-dialog contract — completeness', () => {
+ it('answers every completeness dimension', () => {
+ expect(unansweredDimensions(MODAL_DIALOG_PATTERN)).toEqual([]);
+ });
+
+ it('gives every expectation at least one deliberately violating fixture', () => {
+ expect(
+ MODAL_DIALOG_PATTERN.expectations
+ .filter(
+ expectation =>
+ (MODAL_DIALOG_MUTATIONS[expectation.id] ?? []).length === 0,
+ )
+ .map(expectation => expectation.id),
+ ).toEqual([]);
+ });
+
+ it('has no orphaned mutation ids or fixture ids', () => {
+ const expectationIds = new Set(
+ MODAL_DIALOG_PATTERN.expectations.map(expectation => expectation.id),
+ );
+ expect(
+ Object.keys(MODAL_DIALOG_MUTATIONS).filter(id => !expectationIds.has(id)),
+ ).toEqual([]);
+ for (const fixtures of Object.values(MODAL_DIALOG_MUTATIONS)) {
+ for (const id of fixtures) {
+ expect(() => modalDialogFixture(id)).not.toThrow();
+ }
+ }
+ });
+});
+
+describe('modal-dialog contract — jsdom evidence boundary', () => {
+ it('reports browser-owned outcomes as unrun, never as pass', async () => {
+ const results = await resultsFor(
+ modalDialogFixture('conforming-interactive'),
+ );
+ const browserOwned = results.filter(result =>
+ ['accessibility-tree', 'real-browser'].includes(result.evidenceLayer),
+ );
+ expect(browserOwned.length).toBeGreaterThan(0);
+ for (const result of browserOwned) {
+ expect(['unrun', 'not-applicable']).toContain(result.status);
+ }
+ });
+});
+
+describe.each(observableHere.map(expectation => [expectation.id] as const))(
+ '%s',
+ id => {
+ it.each(MODAL_DIALOG_CONFORMING_FIXTURES.map(name => [name] as const))(
+ 'passes against %s (or does not apply)',
+ async name => {
+ const result = resultFor(
+ await resultsFor(modalDialogFixture(name)),
+ id,
+ );
+ expect(
+ ['pass', 'not-applicable'],
+ `${id}: ${result.detail ?? ''}`,
+ ).toContain(result.status);
+ },
+ );
+
+ it.each((MODAL_DIALOG_MUTATIONS[id] ?? []).map(name => [name] as const))(
+ 'fails against %s, which removes its outcome',
+ async name => {
+ const result = resultFor(
+ await resultsFor(modalDialogFixture(name)),
+ id,
+ );
+ expect(result.status, `${id}: ${result.detail ?? ''}`).toBe('fail');
+ },
+ );
+ },
+);
diff --git a/internal/a11y-spec/src/patterns/modal-dialog.ts b/internal/a11y-spec/src/patterns/modal-dialog.ts
new file mode 100644
index 0000000000..a4c04f2d54
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/modal-dialog.ts
@@ -0,0 +1,606 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file modal-dialog.ts
+ * @input Uses ../contract (definePattern and the expectation vocabulary)
+ * @output MODAL_DIALOG_PATTERN and ModalDialogStateFacts
+ * @position Reusable accessibility contract for native modal dialogs. Component
+ * bindings declare their states; browser-owned focus, top-layer, and inertness
+ * outcomes run only in a real browser.
+ */
+
+import {
+ definePattern,
+ type ApgRequirement,
+ type AstryxRecord,
+ type PatternContract,
+ type WcagCriterion,
+} from '../contract';
+import {saysInOrder, spokenWords} from '../spoken';
+
+const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';
+
+const WCAG_1_3_1: WcagCriterion = {
+ standard: 'wcag',
+ id: '1.3.1',
+ name: 'Info and Relationships',
+ level: 'A',
+ url: `${UNDERSTANDING}/info-and-relationships.html`,
+};
+const WCAG_2_5_3: WcagCriterion = {
+ standard: 'wcag',
+ id: '2.5.3',
+ name: 'Label in Name',
+ level: 'A',
+ url: `${UNDERSTANDING}/label-in-name.html`,
+};
+const WCAG_4_1_2: WcagCriterion = {
+ standard: 'wcag',
+ id: '4.1.2',
+ name: 'Name, Role, Value',
+ level: 'A',
+ url: `${UNDERSTANDING}/name-role-value.html`,
+};
+const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/';
+const APG_ROLE: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'dialog-modal',
+ requirement:
+ 'The element that serves as the dialog container has a role of dialog.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_MODAL: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'dialog-modal',
+ requirement:
+ 'The aria-modal property is set to true on the dialog container.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_NAME: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'dialog-modal',
+ requirement: 'The dialog has either aria-labelledby or aria-label.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+const APG_DESCRIPTION: ApgRequirement = {
+ standard: 'apg',
+ pattern: 'dialog-modal',
+ requirement:
+ 'Optionally, aria-describedby is set on the element with the dialog role to indicate which element or elements in the dialog contain content that describes the primary purpose or message of the dialog.',
+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,
+};
+
+const DIALOG_FR1: AstryxRecord = {
+ standard: 'astryx',
+ id: 'component:Dialog',
+ clause: 'FR1',
+ requirement:
+ 'A native Dialog MUST become visibly modal before Dialog applies its component-owned initial-focus request.',
+ url: 'https://github.com/facebook/astryx/blob/029368bde880cb25a7912523510419285d803a90/packages/core/src/Dialog/Dialog.spec.md',
+};
+const DIALOG_FR2: AstryxRecord = {
+ standard: 'astryx',
+ id: 'component:Dialog',
+ clause: 'FR2',
+ requirement:
+ 'Dialog MUST honor an eligible descendant initial-focus request. A request is eligible only when its rendered target is inside the active Dialog, is neither hidden nor inert, and can receive programmatic focus when selection runs. DialogHeader supplies its title as the default when no non-default eligible request is rendered. Ordering among multiple non-default requests is unspecified (AV3).',
+ url: DIALOG_FR1.url,
+};
+const DIALOG_FR3: AstryxRecord = {
+ standard: 'astryx',
+ id: 'component:Dialog',
+ clause: 'FR3',
+ requirement:
+ 'When no eligible descendant request exists, Dialog MUST preserve the native dialog’s valid initial-focus behavior rather than move focus outside the modal.',
+ url: DIALOG_FR1.url,
+};
+const DIALOG_FR4: AstryxRecord = {
+ standard: 'astryx',
+ id: 'component:Dialog',
+ clause: 'FR4',
+ requirement:
+ 'Closing a native Dialog MUST return focus to the still-connected external element that invoked the modal when that element can receive focus. Descendant mount focus MUST NOT replace that return owner.',
+ url: DIALOG_FR1.url,
+};
+
+const LAYER_NATIVE_MODAL: AstryxRecord = {
+ standard: 'astryx',
+ id: 'architecture:layer-runtime',
+ clause: 'Browser hosts and corrective portals',
+ requirement:
+ 'dialog.showModal() provides a native modal boundary, backdrop, inert outside content, and platform close requests.',
+ url: 'https://github.com/facebook/astryx/blob/029368bde880cb25a7912523510419285d803a90/docs/architecture/layer-runtime.md',
+};
+
+const ALWAYS = {
+ condition: 'the binding renders a modal dialog',
+ test: () => true,
+};
+
+export interface ModalDialogStateFacts {
+ readonly labelledBy: boolean;
+ readonly hasDescriptionReference: boolean;
+ readonly hasDeclaredInitialTarget: boolean;
+ readonly usesNativeFocusFallback: boolean;
+ readonly exercisesFocusRestoration: boolean;
+ readonly makesBackgroundInert: boolean;
+}
+
+export const MODAL_DIALOG_PATTERN: PatternContract<ModalDialogStateFacts> =
+ definePattern<ModalDialogStateFacts>({
+ pattern: 'modal-dialog',
+ url: 'https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/',
+ scope:
+ 'One native modal dialog that enters the browser modal state before focus, exposes its role and name, applies its declared focus entry and return, and makes the background inert.',
+ expectations: [
+ {
+ id: 'modal-dialog.modal.in-top-layer',
+ outcome:
+ 'The active dialog is in the browser’s native modal state, so the background is outside its interaction context.',
+ sources: [DIALOG_FR1, LAYER_NATIVE_MODAL],
+ covers: ['apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'real-browser',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ if (!(await subject.isModal())) {
+ throw new Error(
+ 'the dialog is open but is not a native modal in the browser top layer, so the page behind it remains in the same interaction context',
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.modal.exposed',
+ outcome:
+ 'The browser accessibility tree exposes the dialog as modal, matching the active interaction boundary.',
+ sources: [WCAG_4_1_2, APG_MODAL],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const {modal} = await subject.computed();
+ if (modal !== true) {
+ throw new Error(
+ 'the browser accessibility tree does not expose this active dialog as modal',
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.focus.enters-after-modal',
+ outcome:
+ 'The dialog reaches the browser’s native modal state before focus first enters its requested content.',
+ sources: [DIALOG_FR1],
+ covers: ['2.4.3-focus-order', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the binding declares an eligible initial-focus target',
+ test: facts => facts.hasDeclaredInitialTarget,
+ },
+ evidenceLayer: 'real-browser',
+ enforcement: 'required',
+ run: async ({initialFocusEntry}) => {
+ const entry = await initialFocusEntry();
+ if (!entry.subjectWasModal) {
+ throw new Error(
+ "focus entered the dialog before it reached the browser's native modal state",
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.focus.initial-target',
+ outcome:
+ 'Opening the modal places focus on the binding’s declared initial target inside the visible task.',
+ sources: [DIALOG_FR2],
+ covers: ['2.4.3-focus-order', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the binding declares an eligible initial-focus target',
+ test: facts => facts.hasDeclaredInitialTarget,
+ },
+ evidenceLayer: 'real-browser',
+ enforcement: 'required',
+ run: async ({harness}) => {
+ const initial = await harness.related('initial');
+ if (!(await initial.isFocused())) {
+ throw new Error(
+ 'opening the modal dialog did not focus the binding’s declared initial target',
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.focus.native-fallback',
+ outcome:
+ 'When no descendant requests initial focus, browser-native focus remains inside the visible modal task.',
+ sources: [DIALOG_FR3],
+ covers: ['2.4.3-focus-order'],
+ appliesWhen: {
+ condition:
+ 'the binding has no eligible descendant initial-focus request',
+ test: facts => facts.usesNativeFocusFallback,
+ },
+ evidenceLayer: 'real-browser',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ if (!(await subject.containsFocus())) {
+ throw new Error(
+ 'opening a modal with no eligible descendant focus request left focus outside the visible dialog',
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.focus.restored',
+ outcome:
+ 'Closing the modal returns focus to its still-available invoker, so the person resumes where the task began.',
+ sources: [DIALOG_FR4],
+ covers: ['2.4.3-focus-order'],
+ appliesWhen: {
+ condition:
+ 'the state includes a close action and the invoker remains available',
+ test: facts => facts.exercisesFocusRestoration,
+ },
+ evidenceLayer: 'real-browser',
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const close = await harness.related('close');
+ await close.focus();
+ await harness.press('Enter');
+ if (await subject.isModal()) {
+ throw new Error(
+ 'activating the binding’s close action left the modal dialog open',
+ );
+ }
+ const invoker = await harness.related('invoker');
+ if (!(await invoker.isFocused())) {
+ throw new Error(
+ 'closing the modal dialog did not return focus to its still-available invoker',
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.background.inert',
+ outcome:
+ 'While the modal is active, controls behind it cannot receive focus or pointer interaction.',
+ sources: [DIALOG_FR1, LAYER_NATIVE_MODAL],
+ covers: ['2.4.3-focus-order', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the binding declares a modal background',
+ test: facts => facts.makesBackgroundInert,
+ },
+ evidenceLayer: 'real-browser',
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const background = await harness.related('background');
+ await background.focus();
+ if (await background.isFocused()) {
+ throw new Error(
+ 'a control behind the active modal dialog still received focus',
+ );
+ }
+ if (!(await subject.containsFocus())) {
+ throw new Error(
+ 'trying to focus the background moved focus outside the active modal dialog',
+ );
+ }
+ if (await background.canReceivePointer()) {
+ throw new Error(
+ 'a pointer can still reach a control behind the active modal dialog',
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.role.exposed',
+ outcome:
+ 'The browser accessibility tree exposes the modal task with role dialog.',
+ sources: [WCAG_4_1_2, APG_ROLE],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const {role} = await subject.computed();
+ if (role !== 'dialog') {
+ throw new Error(
+ role == null
+ ? 'the browser exposes no role for this modal task'
+ : `the browser reports this modal task as "${role}", not as a dialog`,
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.name.exposed',
+ outcome:
+ 'The browser accessibility tree exposes a non-empty name for the dialog.',
+ sources: [WCAG_4_1_2, APG_NAME],
+ covers: ['4.1.2-name-role-value'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const {name} = await subject.computed();
+ if (name.trim() === '') {
+ throw new Error(
+ 'the browser computes no accessible name for this dialog',
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.name.matches-visible-label',
+ outcome:
+ 'The accessible name contains the visible dialog title, so speech-input users can say what they read.',
+ sources: [WCAG_2_5_3],
+ covers: ['2.5.3-label-in-name'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ alsoNeeds: ['real-browser'],
+ enforcement: 'required',
+ run: async ({subject, notApplicable}) => {
+ const visible = await subject.visibleLabelText();
+ if (visible == null) {
+ return notApplicable(
+ 'this state renders no visible dialog title, so there are no visible words for a speech-input user to say',
+ );
+ }
+ const {name} = await subject.computed();
+ if (!saysInOrder(spokenWords(name), spokenWords(visible))) {
+ throw new Error(
+ `the visible dialog title reads "${visible}" but the browser computes the accessible name as "${name}"`,
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.name.references-resolve',
+ outcome:
+ 'Every element used to label the dialog exists, so the task name is not silently lost.',
+ sources: [WCAG_1_3_1, APG_NAME],
+ covers: ['1.3.1-info-and-relationships'],
+ appliesWhen: {
+ condition: 'the dialog is named with aria-labelledby',
+ test: facts => facts.labelledBy,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const attribute = await subject.attribute('aria-labelledby');
+ const ids = (attribute ?? '').split(/\s+/).filter(Boolean);
+ if (ids.length === 0) {
+ throw new Error(
+ 'this state is labelled by another element, but the dialog has no aria-labelledby relationship',
+ );
+ }
+ const targets = await subject.idReferences('aria-labelledby');
+ const dangling = ids.filter((_, index) => targets[index] == null);
+ if (dangling.length > 0) {
+ throw new Error(
+ `aria-labelledby points at ${dangling.map(id => `"${id}"`).join(', ')}, which ${dangling.length === 1 ? 'resolves' : 'resolve'} to nothing; the dialog loses that part of its name`,
+ );
+ }
+ },
+ },
+ {
+ id: 'modal-dialog.description.references-resolve',
+ outcome:
+ 'Every id in aria-describedby resolves to an existing element, so the authored relationship is complete.',
+ sources: [WCAG_1_3_1, APG_DESCRIPTION],
+ covers: ['1.3.1-info-and-relationships'],
+ appliesWhen: {
+ condition: 'the binding authors an aria-describedby relationship',
+ test: facts => facts.hasDescriptionReference,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject}) => {
+ const attribute = await subject.attribute('aria-describedby');
+ const ids = (attribute ?? '').split(/\s+/).filter(Boolean);
+ if (ids.length === 0) {
+ throw new Error(
+ 'this state declares an aria-describedby relationship, but the dialog has no aria-describedby attribute',
+ );
+ }
+ const targets = await subject.idReferences('aria-describedby');
+ const dangling = ids.filter((_, index) => targets[index] == null);
+ if (dangling.length > 0) {
+ throw new Error(
+ `aria-describedby points at ${dangling.map(id => `"${id}"`).join(', ')}, which ${dangling.length === 1 ? 'resolves' : 'resolve'} to nothing`,
+ );
+ }
+ },
+ },
+ ],
+ exemptions: {
+ '1.1.1-non-text-content': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ 'component composition tests, the repository axe audit, and content review',
+ reason:
+ 'The modal-dialog pattern owns the dialog surface, not the alternatives for images or icons composed inside it.',
+ },
+ '1.3.1-info-and-relationships': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ 'component DOM tests for structural relationships inside the dialog',
+ reason:
+ 'This contract verifies the dialog name and description relationships; headings, fields, and groups composed inside remain component or caller content.',
+ coversRemainderOnly: true,
+ },
+ '1.3.2-meaningful-sequence': {
+ owner: 'the binding component and caller content',
+ verifiedBy: 'component DOM-order tests and content review',
+ reason:
+ 'Reading order inside a modal task depends on the content the binding composes.',
+ },
+ '1.3.5-identify-input-purpose': {
+ owner:
+ 'caller content and the form controls composed inside the dialog',
+ verifiedBy:
+ 'form-control contracts and integration review of autocomplete purposes',
+ reason:
+ 'The modal-dialog pattern does not choose or encode the purpose of caller-composed input fields.',
+ },
+ '1.4.1-use-of-color': {
+ owner: 'the binding component, theme, and caller content',
+ verifiedBy: 'the repository visual gate and component review',
+ reason:
+ 'Color-dependent meaning is a rendered visual and content fact, not a modal interaction fact.',
+ },
+ '1.4.3-contrast-minimum': {
+ owner: 'the binding component and theme',
+ verifiedBy: 'the repository axe audit and visual gate',
+ reason:
+ 'Text contrast depends on resolved colors and the content rendered inside the modal.',
+ },
+ '1.4.11-non-text-contrast': {
+ owner: 'the binding component and theme',
+ verifiedBy: 'the repository axe audit and visual gate',
+ reason:
+ 'Control, backdrop, and focus-indicator contrast are rendered-color measurements.',
+ },
+ '2.1.1-keyboard': {
+ owner:
+ 'family:overlay-dismissal, the binding component, and caller content',
+ verifiedBy:
+ 'component tests for Escape policy and controls composed inside the dialog, plus integration review of caller-owned commands',
+ reason:
+ 'Current Dialog and overlay authority keep keyboard dismissal policy and composed-control operation outside this reusable modal-focus contract.',
+ },
+ '2.1.2-no-keyboard-trap': {
+ owner: 'the binding component and its current focus contract',
+ verifiedBy:
+ 'current Dialog tests for each supported dismissal path; no Tab-containment claim is verified until the Dialog owner adopts one',
+ reason:
+ 'Current Dialog authority does not adopt APG Tab wrapping as a required outcome, so this contract does not turn that mechanic into policy.',
+ },
+ '2.4.2-page-titled': {
+ owner: 'the page',
+ verifiedBy: 'page-level review',
+ reason:
+ 'A component rendered in isolation does not own the document title.',
+ },
+ '2.4.3-focus-order': {
+ owner: 'the composing page',
+ verifiedBy:
+ 'page-level review of the order before opening and after focus restoration',
+ reason:
+ 'This contract covers focus entry, containment, and return; the surrounding page owns the sequence outside the modal task.',
+ coversRemainderOnly: true,
+ },
+ '2.4.4-link-purpose': {
+ owner: 'caller content',
+ verifiedBy: 'review of links composed inside the dialog',
+ reason: 'The adopted modal-dialog pattern has no required link part.',
+ },
+ '2.4.6-headings-and-labels': {
+ owner: 'caller content',
+ verifiedBy:
+ 'content review of the visible title, field labels, and instructions',
+ reason:
+ 'This contract proves a name exists and includes the visible title; whether the wording describes the task remains a content judgement.',
+ },
+ '2.4.7-focus-visible': {
+ owner: 'the binding component and theme',
+ verifiedBy: 'the repository visual gate and focus-ring review',
+ reason: 'A visible focus indicator is a painted result.',
+ },
+ '2.4.11-focus-not-obscured': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ 'real-browser layout review of scrolling content and composed sticky regions',
+ reason:
+ 'Whether focused content is obscured depends on modal layout and caller-composed content, not the focus lifecycle alone.',
+ },
+ '2.5.2-pointer-cancellation': {
+ owner: 'the binding component',
+ verifiedBy:
+ 'component tests for backdrop and explicit close-button pointer behavior',
+ reason:
+ 'Pointer dismissal channels vary by the component’s declared purpose and are not a universal modal-dialog action.',
+ },
+ '2.5.3-label-in-name': {
+ owner: 'the binding component and caller-composed controls',
+ verifiedBy:
+ 'component-specific label-in-name tests and content review for controls inside the dialog',
+ reason:
+ 'This contract verifies the dialog container’s visible title; buttons, fields, and other controls composed inside retain their own label-in-name obligations.',
+ coversRemainderOnly: true,
+ },
+ '2.5.8-target-size': {
+ owner: 'the binding component and caller content',
+ verifiedBy: 'the repository axe audit and visual gate',
+ reason:
+ 'Target size belongs to the concrete controls composed inside the dialog.',
+ },
+ '3.1.1-language-of-page': {
+ owner: 'the page',
+ verifiedBy: 'page-level review',
+ reason: 'A modal component does not own the document language.',
+ },
+ '3.2.2-on-input': {
+ owner: 'the caller',
+ verifiedBy:
+ 'integration tests for effects the caller performs after onOpenChange',
+ reason:
+ 'The component requests dismissal; navigation or other context changes in response are caller-owned.',
+ },
+ '3.2.4-consistent-identification': {
+ owner: 'the design system',
+ verifiedBy:
+ 'shared contract adoption and component API review across modal-dialog bindings',
+ reason:
+ 'Consistency is a property of all adopters, not one rendered binding.',
+ },
+ '3.3.1-error-identification': {
+ owner: 'caller content and form controls',
+ verifiedBy:
+ 'form-control contracts and composed-dialog integration tests',
+ reason:
+ 'Validation and error text belong to the fields and workflow rendered inside the dialog.',
+ },
+ '3.3.2-labels-or-instructions': {
+ owner: 'caller content and form controls',
+ verifiedBy: 'form-control contracts and content review',
+ reason:
+ 'The modal surface does not author labels or instructions for fields composed inside it.',
+ },
+ '4.1.2-name-role-value': {
+ owner: 'the binding component and composed controls',
+ verifiedBy:
+ 'component-specific tests for states and values not owned by the dialog surface',
+ reason:
+ 'This contract covers the dialog role and name; descendant controls own their own roles, states, and values.',
+ coversRemainderOnly: true,
+ },
+ '4.1.3-status-messages': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ 'component status-message tests plus real-AT evidence under AST-009 when the claim is about announcement',
+ reason:
+ 'A modal opening is a focus transition, not a status-message contract; updates inside it belong to their source.',
+ },
+ 'forced-colors': {
+ owner: 'the binding component and theme',
+ verifiedBy: 'forced-colors review and the repository visual gate',
+ reason: 'Forced-color output is a paint result.',
+ },
+ 'reduced-motion': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ 'component transition tests and the repository visual gate under reduced motion',
+ reason:
+ 'Entry and exit motion are rendered over time, not semantic behavior.',
+ },
+ 'at-facing-strings': {
+ owner: 'the binding component',
+ verifiedBy: 'the repository i18n catalog check',
+ reason:
+ 'Translation is a source-level concern; real announcement claims remain with AST-009.',
+ },
+ },
+ });
diff --git a/packages/core/src/Dialog/Dialog.spec.md b/packages/core/src/Dialog/Dialog.spec.md
index dfcbe98828..ca21369ab7 100644
--- a/packages/core/src/Dialog/Dialog.spec.md
+++ b/packages/core/src/Dialog/Dialog.spec.md
@@ -14,6 +14,8 @@ verified_by:
[
packages/core/src/Dialog/Dialog.test.tsx,
packages/core/src/Dialog/DialogHeader.test.tsx,
+ packages/core/src/Dialog/__tests__/Dialog.a11y.test.tsx,
+ packages/core/src/Dialog/__tests__/Dialog.a11y.chromium.spec.ts,
]
modules: []
families: [family:overlay-dismissal]
@@ -25,7 +27,7 @@ architecture:
architecture:react-component-runtime,
]
contributing: []
-system_specs: []
+system_specs: [spec:AST-013, spec:AST-020, spec:AST-021]
---
# Dialog component contract
@@ -134,12 +136,12 @@ component design and theming owners.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------ | ----------------------------------------------------------------------- | --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------- |
-| FR1–FR3, AR1 | Dialog and DialogHeader focus tests plus native-dialog browser evidence | header default, explicit descendant, no request | focusing before modal visibility or removing descendant focus leaves focus outside visible modal content | audit:Dialog/accessibility |
-| FR4, AR2 | trigger capture/return regression tests | external trigger, descendant mount focus, removed trigger | descendant focus replaces the return owner or close fails to restore a connected trigger | audit:Dialog/behavior |
-| FR5 | inline Dialog tests | DialogHeader and focusable children | inline preview steals focus or invokes native modal methods | audit:Dialog/behavior |
-| FR6, AR3 | composed descendant focus fixtures | heading, input, action | focus depends on a private React child type or strips semantics from the target | audit:Dialog/public-api |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------ | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
+| FR1–FR3, AR1 | shared modal-dialog binding in `Dialog.a11y.test.tsx` and `Dialog.a11y.chromium.spec.ts`; local DialogHeader focus tests | header default, explicit descendant, no request | the shared contract fails when focus is applied before native modality, misses the declared target, or leaves the visible modal on native fallback | audit:Dialog/accessibility |
+| FR4, AR2 | shared modal-dialog browser binding plus the local unavailable-invoker close test | external trigger, descendant mount focus, removed trigger | the shared contract records an exact current failure when descendant focus replaces the return owner; the local test keeps close safe after invoker removal | audit:Dialog/behavior |
+| FR5 | inline Dialog tests | DialogHeader and focusable children | inline preview steals focus or invokes native modal methods | audit:Dialog/behavior |
+| FR6, AR3 | shared modal-dialog binding plus the local composed-action focus fixture | DialogHeader heading, TextInput, action button | focus depends on a private React child type or strips semantics from the target | audit:Dialog/public-api |
## Decision log
@@ -154,7 +156,10 @@ implementation evidence, not a permanent or newly admitted public API.
## Open questions
-None.
+- **Dialog focus containment.** Should native modal Dialog adopt APG forward and
+ reverse Tab wrapping as a required public behavior? Current authority owns focus
+ entry and return but does not settle this containment mechanic, so the shared
+ contract does not gate it.
## Content boundary
diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx
index 433caa8371..a7fc4ec22a 100644
--- a/packages/core/src/Dialog/Dialog.test.tsx
+++ b/packages/core/src/Dialog/Dialog.test.tsx
@@ -9,6 +9,7 @@
* SYNC: When Dialog.tsx changes, update tests to match new behavior
*/
+import {useState} from 'react';
import {readFileSync} from 'node:fs';
import {describe, it, expect, vi, beforeEach} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
@@ -145,6 +146,19 @@ describe('Dialog', () => {
expect(screen.getByRole('dialog')).toHaveAttribute('aria-modal', 'true');
});
+ it('honors an initial-focus request from an action descendant', () => {
+ render(
+ <Dialog isOpen={true} onOpenChange={() => {}}>
+ <DialogHeader title="Choose an action" />
+ <button type="button" data-autofocus>
+ Continue
+ </button>
+ </Dialog>,
+ );
+
+ expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus();
+ });
+
describe('purpose: info (default)', () => {
it('calls onOpenChange(false) when Escape is pressed', () => {
const handleHide = vi.fn();
@@ -413,6 +427,49 @@ describe('Dialog', () => {
});
});
+ describe('focus restoration', () => {
+ it('closes without error when the captured invoker is removed', () => {
+ function RemovedInvokerExample() {
+ const [isOpen, setIsOpen] = useState(false);
+ const [showInvoker, setShowInvoker] = useState(true);
+ return (
+ <>
+ {showInvoker && (
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open dialog
+ </button>
+ )}
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ aria-label="Review changes">
+ <button type="button" onClick={() => setShowInvoker(false)}>
+ Remove opener
+ </button>
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Close dialog
+ </button>
+ </Dialog>
+ </>
+ );
+ }
+
+ render(<RemovedInvokerExample />);
+ const invoker = screen.getByRole('button', {name: 'Open dialog'});
+ invoker.focus();
+ fireEvent.click(invoker);
+ const dialog = screen.getByRole('dialog');
+
+ fireEvent.click(screen.getByRole('button', {name: 'Remove opener'}));
+ expect(invoker.isConnected).toBe(false);
+
+ expect(() => {
+ fireEvent.click(screen.getByRole('button', {name: 'Close dialog'}));
+ }).not.toThrow();
+ expect(dialog).not.toHaveAttribute('open');
+ });
+ });
+
describe('variant: standard', () => {
it('renders with default variant', () => {
render(
diff --git a/packages/core/src/Dialog/__tests__/Dialog.a11y.chromium.spec.ts b/packages/core/src/Dialog/__tests__/Dialog.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..cca61838dd
--- /dev/null
+++ b/packages/core/src/Dialog/__tests__/Dialog.a11y.chromium.spec.ts
@@ -0,0 +1,210 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Dialog.a11y.chromium.spec.ts
+ * @input Uses the modal-dialog contract, Chromium harness, static Storybook,
+ * dedicated Dialog stories, state inventory, and exact known failures
+ * @output Browser-owned Dialog binding evidence for native modality,
+ * accessibility-tree exposure, focus entry and return, and background inertness
+ * @position High-fidelity lane; jsdom binds only DOM semantics.
+ */
+
+import {
+ expect,
+ test,
+ type CDPSession,
+ type Locator,
+ type Page,
+} from '@playwright/test';
+import {
+ MissingBindingCapability,
+ MODAL_DIALOG_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 {DIALOG_MODAL_KNOWN_FAILURES} from './Dialog.a11y.known-failures';
+import {
+ DIALOG_CONTRACT_BACKGROUND_LABEL,
+ DIALOG_CONTRACT_CLOSE_LABEL,
+ DIALOG_CONTRACT_OPEN_LABEL,
+ DIALOG_MODAL_BINDING_STATES,
+ type DialogModalBindingState,
+} from './Dialog.a11y.states';
+
+let storybook: StaticServer;
+
+type ModalFocusEntryGlobal = typeof globalThis & {
+ __astryxModalFocusEntryRecorderInstalled?: boolean;
+ __astryxModalFocusEntryWasModal?: boolean;
+};
+
+async function installModalFocusEntryRecorder(page: Page): Promise<void> {
+ await page.addInitScript(() => {
+ const runtime = globalThis as ModalFocusEntryGlobal;
+ if (runtime.__astryxModalFocusEntryRecorderInstalled === true) {
+ return;
+ }
+ runtime.__astryxModalFocusEntryRecorderInstalled = true;
+ runtime.__astryxModalFocusEntryWasModal = undefined;
+ document.addEventListener(
+ 'focusin',
+ event => {
+ if (runtime.__astryxModalFocusEntryWasModal !== undefined) {
+ return;
+ }
+ const target = event.target;
+ if (!(target instanceof Element)) {
+ return;
+ }
+ const dialog = target.closest('dialog');
+ if (dialog instanceof HTMLDialogElement) {
+ runtime.__astryxModalFocusEntryWasModal = dialog.matches(':modal');
+ }
+ },
+ true,
+ );
+ });
+}
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function mountState(
+ page: Page,
+ state: DialogModalBindingState,
+): Promise<{
+ readonly root: Locator;
+ readonly subject: Locator;
+ readonly focusEntryWasModal: boolean | undefined;
+}> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${state.storyId}&viewMode=story`,
+ {waitUntil: 'load'},
+ );
+ await holdMotionStill(page);
+ const root = page.locator('#storybook-root');
+ const subject = root.locator('dialog');
+ await root.getByRole('button', {name: DIALOG_CONTRACT_OPEN_LABEL}).click();
+ await expect
+ .poll(async () => subject.evaluate(element => element.matches(':modal')))
+ .toBe(true);
+ const focusEntryWasModal = await page.evaluate(() => {
+ const runtime = globalThis as ModalFocusEntryGlobal;
+ return runtime.__astryxModalFocusEntryWasModal;
+ });
+ return {root, subject, focusEntryWasModal};
+}
+
+function initialTarget(
+ root: Locator,
+ subject: Locator,
+ state: DialogModalBindingState,
+): Locator {
+ switch (state.initialTarget.kind) {
+ case 'dialog':
+ return subject;
+ case 'heading':
+ return root.getByRole('heading', {name: state.initialTarget.name});
+ case 'textbox':
+ return root.getByRole('textbox', {name: state.initialTarget.name});
+ }
+}
+
+async function runState(
+ page: Page,
+ cdp: CDPSession,
+ state: DialogModalBindingState,
+): Promise<BindingResult> {
+ await installModalFocusEntryRecorder(page);
+ let focusEntryWasModal: boolean | undefined;
+ return checkAccessibilitySpec({
+ spec: MODAL_DIALOG_PATTERN,
+ binding: 'Dialog',
+ state: state.id,
+ facts: state.facts,
+ knownFailures: DIALOG_MODAL_KNOWN_FAILURES,
+ mount: async () => {
+ const mounted = await mountState(page, state);
+ const {root, subject} = mounted;
+ focusEntryWasModal = mounted.focusEntryWasModal;
+ return createChromiumHarness({
+ page,
+ subject,
+ visibleLabel:
+ state.visibleTitle == null
+ ? null
+ : root.getByRole('heading', {name: state.visibleTitle}),
+ cdp,
+ related: {
+ initial: initialTarget(root, subject, state),
+ close: root.getByRole('button', {name: DIALOG_CONTRACT_CLOSE_LABEL}),
+ invoker: root.getByRole('button', {
+ name: DIALOG_CONTRACT_OPEN_LABEL,
+ }),
+ background: root.getByRole('button', {
+ name: DIALOG_CONTRACT_BACKGROUND_LABEL,
+ }),
+ },
+ });
+ },
+ initialFocusEntry: async () => {
+ if (focusEntryWasModal === undefined) {
+ throw new MissingBindingCapability(
+ 'Dialog binding supplies no focus-entry observation',
+ );
+ }
+ return {subjectWasModal: focusEntryWasModal};
+ },
+ });
+}
+
+test('every expectation is exercised and every known failure matches once', async ({
+ page,
+}) => {
+ test.setTimeout(5 * 60 * 1000);
+ const cdp = await page.context().newCDPSession(page);
+ const results: BindingResult[] = [];
+ for (const state of DIALOG_MODAL_BINDING_STATES) {
+ results.push(await runState(page, cdp, state));
+ }
+ expect(neverExercised(results)).toEqual([]);
+ expect(unmatchedKnownFailures(DIALOG_MODAL_KNOWN_FAILURES, results)).toEqual(
+ [],
+ );
+});
+
+for (const state of DIALOG_MODAL_BINDING_STATES) {
+ test(`Dialog [${state.id}] — ${state.summary}`, async ({page}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const result = await runState(page, cdp, state);
+ const report = summarize(MODAL_DIALOG_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/Dialog/__tests__/Dialog.a11y.known-failures.ts b/packages/core/src/Dialog/__tests__/Dialog.a11y.known-failures.ts
new file mode 100644
index 0000000000..e4c1050f76
--- /dev/null
+++ b/packages/core/src/Dialog/__tests__/Dialog.a11y.known-failures.ts
@@ -0,0 +1,42 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Dialog.a11y.known-failures.ts
+ * @input Uses KnownFailure from @astryxdesign/a11y-spec
+ * @output Exact public-safe baseline failures for Dialog's modal-dialog binding
+ * @position Shared by the jsdom and Chromium bindings. These records preserve
+ * current behavior during test migration; they do not approve remediation.
+ */
+
+import type {KnownFailure} from '@astryxdesign/a11y-spec';
+
+export const DIALOG_MODAL_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [
+ {
+ expectation: 'modal-dialog.focus.enters-after-modal',
+ binding: 'Dialog',
+ state: 'conditional-content-focus-restoration',
+ evidenceLayer: 'real-browser',
+ failureEquals:
+ "focus entered the dialog before it reached the browser's native modal state",
+ standardsReference:
+ 'Astryx component:Dialog FR1 — native Dialog must become visibly modal before Dialog applies its component-owned initial-focus request.',
+ userImpact:
+ 'When focus-requesting content mounts only while opening, focus enters the task before the browser has established the modal boundary that blocks the page behind it.',
+ reason:
+ 'This migration records the existing focus-order violation without changing the overlapping Dialog implementation path.',
+ },
+ {
+ expectation: 'modal-dialog.focus.restored',
+ binding: 'Dialog',
+ state: 'conditional-content-focus-restoration',
+ evidenceLayer: 'real-browser',
+ failureEquals:
+ 'closing the modal dialog did not return focus to its still-available invoker',
+ standardsReference:
+ 'Astryx component:Dialog FR4 — closing a native Dialog must return focus to its still-connected invoker when it can receive focus.',
+ userImpact:
+ 'When focus-moving content mounts only while the dialog is open, closing can leave the user at the document body instead of the control that opened the task.',
+ reason:
+ 'This migration records the existing restoration violation without changing the overlapping Dialog implementation path.',
+ },
+];
diff --git a/packages/core/src/Dialog/__tests__/Dialog.a11y.renders.tsx b/packages/core/src/Dialog/__tests__/Dialog.a11y.renders.tsx
new file mode 100644
index 0000000000..06e7bd58b0
--- /dev/null
+++ b/packages/core/src/Dialog/__tests__/Dialog.a11y.renders.tsx
@@ -0,0 +1,107 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file Dialog.a11y.renders.tsx
+ * @input Uses Dialog, DialogHeader, and the modal-dialog binding inventory
+ * @output The one render map shared by Dialog's jsdom and Storybook bindings
+ * @position Keeps both evidence lanes on identical component composition and
+ * controlled open/close wiring.
+ */
+
+import {useState, type ReactElement, type ReactNode} from 'react';
+import {Dialog} from '../Dialog';
+import {DialogHeader} from '../DialogHeader';
+import {TextInput} from '../../TextInput';
+import {
+ DIALOG_CONTRACT_BACKGROUND_LABEL,
+ DIALOG_CONTRACT_CLOSE_LABEL,
+ DIALOG_CONTRACT_OPEN_LABEL,
+ type DialogModalBindingState,
+} from './Dialog.a11y.states';
+
+function DialogBinding({state}: {state: DialogModalBindingState}) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [name, setName] = useState('');
+
+ let content: ReactNode;
+ switch (state.render) {
+ case 'labelled-described':
+ content = (
+ <>
+ <DialogHeader title="Review changes" />
+ <div id="dialog-contract-description">
+ Confirm the changes before continuing.
+ </div>
+ <button type="button">Previous</button>
+ <button type="button" onClick={() => setIsOpen(false)}>
+ {DIALOG_CONTRACT_CLOSE_LABEL}
+ </button>
+ </>
+ );
+ break;
+ case 'explicit-focus':
+ content = (
+ <>
+ <DialogHeader title="Edit profile" />
+ <button type="button">Before requested field</button>
+ <TextInput
+ label="Name"
+ value={name}
+ onChange={setName}
+ hasAutoFocus
+ />
+ <button type="button" onClick={() => setIsOpen(false)}>
+ {DIALOG_CONTRACT_CLOSE_LABEL}
+ </button>
+ </>
+ );
+ break;
+ case 'conditional':
+ content = isOpen ? (
+ <>
+ <DialogHeader title="Sensitive review" />
+ <div>This content exists only while the task is open.</div>
+ <button type="button" onClick={() => setIsOpen(false)}>
+ {DIALOG_CONTRACT_CLOSE_LABEL}
+ </button>
+ </>
+ ) : null;
+ break;
+ case 'no-focusable':
+ content = <div>There are no controls in this task.</div>;
+ break;
+ }
+
+ const namingProps =
+ state.render === 'labelled-described'
+ ? {'aria-describedby': 'dialog-contract-description'}
+ : state.render === 'explicit-focus'
+ ? {}
+ : state.render === 'conditional'
+ ? {'aria-label': 'Sensitive review'}
+ : {'aria-label': 'Read terms'};
+
+ return (
+ <>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ {DIALOG_CONTRACT_OPEN_LABEL}
+ </button>
+ <button type="button">{DIALOG_CONTRACT_BACKGROUND_LABEL}</button>
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ purpose={state.render === 'explicit-focus' ? 'form' : 'info'}
+ {...namingProps}>
+ {content}
+ </Dialog>
+ </>
+ );
+}
+
+export function renderDialogModalState(
+ state: DialogModalBindingState,
+): ReactElement {
+ return <DialogBinding state={state} />;
+}
diff --git a/packages/core/src/Dialog/__tests__/Dialog.a11y.states.ts b/packages/core/src/Dialog/__tests__/Dialog.a11y.states.ts
new file mode 100644
index 0000000000..43b3140b88
--- /dev/null
+++ b/packages/core/src/Dialog/__tests__/Dialog.a11y.states.ts
@@ -0,0 +1,104 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Dialog.a11y.states.ts
+ * @input Uses ModalDialogStateFacts from @astryxdesign/a11y-spec
+ * @output DIALOG_MODAL_BINDING_STATES — the Dialog states that can change the
+ * shared modal-dialog outcome
+ * @position Data-only inventory shared by the jsdom and Chromium bindings.
+ *
+ * `purpose="required"` and AlertDialog are excluded because they expose
+ * `alertdialog`, a distinct pattern. `isInline` is excluded because it
+ * deliberately has no modal behavior. MobileNav is excluded because its
+ * current record is draft and does not adopt this exact modal-dialog model.
+ * Nested-surface ordering remains owned by family:overlay-dismissal and the
+ * existing Dialog component tests.
+ *
+ * SYNC: Every storyId and label must match the dedicated stories in
+ * /apps/storybook/stories/DialogA11y.stories.tsx.
+ */
+
+import type {ModalDialogStateFacts} from '@astryxdesign/a11y-spec';
+
+export const DIALOG_CONTRACT_OPEN_LABEL = 'Open contract dialog';
+export const DIALOG_CONTRACT_BACKGROUND_LABEL = 'Background action';
+export const DIALOG_CONTRACT_CLOSE_LABEL = 'Close';
+
+export type DialogInitialTarget =
+ | {readonly kind: 'dialog'}
+ | {readonly kind: 'heading'; readonly name: string}
+ | {readonly kind: 'textbox'; readonly name: string};
+
+export interface DialogModalBindingState {
+ readonly id: string;
+ readonly summary: string;
+ readonly storyId: string;
+ readonly facts: ModalDialogStateFacts;
+ readonly initialTarget: DialogInitialTarget;
+ readonly visibleTitle: string | null;
+ readonly render:
+ 'labelled-described' | 'explicit-focus' | 'conditional' | 'no-focusable';
+}
+
+const MODAL_FACTS = {
+ labelledBy: true,
+ hasDescriptionReference: false,
+ hasDeclaredInitialTarget: true,
+ usesNativeFocusFallback: false,
+ exercisesFocusRestoration: true,
+ makesBackgroundInert: true,
+} as const satisfies ModalDialogStateFacts;
+
+export const DIALOG_MODAL_BINDING_STATES: ReadonlyArray<DialogModalBindingState> =
+ [
+ {
+ id: 'labelled-described-default-title',
+ summary:
+ 'an informational dialog labelled by DialogHeader, described by supporting text, and containing explicit actions',
+ storyId: 'a11y-dialog-modal-pattern--labelled-described-default-title',
+ render: 'labelled-described',
+ initialTarget: {kind: 'heading', name: 'Review changes'},
+ visibleTitle: 'Review changes',
+ facts: {
+ ...MODAL_FACTS,
+ hasDescriptionReference: true,
+ },
+ },
+ {
+ id: 'explicit-descendant-focus',
+ summary:
+ 'a form dialog whose supported TextInput request wins over an earlier focusable action',
+ storyId: 'a11y-dialog-modal-pattern--explicit-descendant-focus',
+ render: 'explicit-focus',
+ initialTarget: {kind: 'textbox', name: 'Name'},
+ visibleTitle: 'Edit profile',
+ facts: MODAL_FACTS,
+ },
+ {
+ id: 'conditional-content-focus-restoration',
+ summary:
+ 'a dialog whose focus-requesting content mounts only on the opening transition and unmounts on close',
+ storyId:
+ 'a11y-dialog-modal-pattern--conditional-content-focus-restoration',
+ render: 'conditional',
+ initialTarget: {kind: 'heading', name: 'Sensitive review'},
+ visibleTitle: 'Sensitive review',
+ facts: {...MODAL_FACTS, labelledBy: false},
+ },
+ {
+ id: 'no-focusable-content',
+ summary:
+ 'a named informational dialog with no eligible descendant focus request or tabbable content',
+ storyId: 'a11y-dialog-modal-pattern--no-focusable-content',
+ render: 'no-focusable',
+ initialTarget: {kind: 'dialog'},
+ visibleTitle: null,
+ facts: {
+ ...MODAL_FACTS,
+ labelledBy: false,
+ hasDeclaredInitialTarget: false,
+ usesNativeFocusFallback: true,
+ exercisesFocusRestoration: false,
+ },
+ },
+ ];
diff --git a/packages/core/src/Dialog/__tests__/Dialog.a11y.test.tsx b/packages/core/src/Dialog/__tests__/Dialog.a11y.test.tsx
new file mode 100644
index 0000000000..d3ae6ffc18
--- /dev/null
+++ b/packages/core/src/Dialog/__tests__/Dialog.a11y.test.tsx
@@ -0,0 +1,102 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file Dialog.a11y.test.tsx
+ * @input Uses the shared modal-dialog contract, @testing-library/react, and the
+ * actual Dialog binding render map
+ * @output Dialog's jsdom binding through expectAccessibilitySpec
+ * @position Fast DOM-semantics lane. Browser-owned focus, top-layer, inertness,
+ * and computed-tree outcomes run in Dialog.a11y.chromium.spec.ts.
+ */
+
+import {beforeEach, describe, expect, it, vi} from 'vitest';
+import {cleanup, fireEvent, render, screen} from '@testing-library/react';
+import {
+ MODAL_DIALOG_PATTERN,
+ checkAccessibilitySpec,
+ createJsdomHarness,
+ expectAccessibilitySpec,
+ summarize,
+ type BindingResult,
+} from '@astryxdesign/a11y-spec';
+import {DIALOG_MODAL_KNOWN_FAILURES} from './Dialog.a11y.known-failures';
+import {renderDialogModalState} from './Dialog.a11y.renders';
+import {
+ DIALOG_CONTRACT_OPEN_LABEL,
+ DIALOG_MODAL_BINDING_STATES,
+ type DialogModalBindingState,
+} from './Dialog.a11y.states';
+
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+function renderState(state: DialogModalBindingState): void {
+ render(renderDialogModalState(state));
+ fireEvent.click(
+ screen.getByRole('button', {name: DIALOG_CONTRACT_OPEN_LABEL}),
+ );
+}
+
+function dialogSubject(): HTMLElement {
+ return screen.getByRole('dialog', {hidden: true});
+}
+
+async function expectState(state: DialogModalBindingState): Promise<void> {
+ await expectAccessibilitySpec({
+ spec: MODAL_DIALOG_PATTERN,
+ binding: 'Dialog',
+ state: state.id,
+ facts: state.facts,
+ knownFailures: DIALOG_MODAL_KNOWN_FAILURES,
+ render: () => renderState(state),
+ subject: dialogSubject,
+ cleanup,
+ });
+}
+
+async function checkState(
+ state: DialogModalBindingState,
+): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: MODAL_DIALOG_PATTERN,
+ binding: 'Dialog',
+ state: state.id,
+ facts: state.facts,
+ knownFailures: DIALOG_MODAL_KNOWN_FAILURES,
+ mount: async () => {
+ renderState(state);
+ return createJsdomHarness({subject: dialogSubject()});
+ },
+ unmount: cleanup,
+ });
+}
+
+describe('Dialog — the shared modal-dialog pattern, jsdom lane', () => {
+ it.each(
+ DIALOG_MODAL_BINDING_STATES.map(
+ state => [state.id, state.summary, state] as const,
+ ),
+ )('%s (%s)', async (_id, _summary, state) => {
+ await expectState(state);
+ });
+
+ it('runs DOM semantics and reports browser-owned layers as unrun', async () => {
+ const results: BindingResult[] = [];
+ for (const state of DIALOG_MODAL_BINDING_STATES) {
+ results.push(await checkState(state));
+ }
+ const report = summarize(MODAL_DIALOG_PATTERN, results);
+ expect(report.counts.pass).toBeGreaterThan(0);
+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+});