An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): add native text-input accessibility contract (#6185)
Cindy Zhang64e8ee01d77c
diff --git a/apps/storybook/stories/TextInputA11y.stories.tsx b/apps/storybook/stories/TextInputA11y.stories.tsxnew file mode 100644index 0000000000..1e441a2d49--- /dev/null+++ b/apps/storybook/stories/TextInputA11y.stories.tsx@@ -0,0 +1,75 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TextInputA11y.stories.tsx+ * @input Uses the shared text-input binding inventory and render map+ * @output One checked-in reproduction story for every TextInput/TextArea state+ * @position Stable real-browser fixtures required by AST-009 FR30 and AST-021.+ */++import type {Meta, StoryObj} from '@storybook/react';+import {TEXT_INPUT_STATE_RENDERS} from '../../../packages/core/src/TextInput/__tests__/TextInput.a11y.renders';+import {TEXT_INPUT_BINDING_STATES} from '../../../packages/core/src/TextInput/__tests__/TextInput.a11y.states';++function storyFor(id: string): StoryObj {+ const state = TEXT_INPUT_BINDING_STATES.find(+ candidate => candidate.id === id,+ );+ if (state == null) {+ throw new Error(`no binding state "${id}" — see TextInput.a11y.states.ts`);+ }+ return {+ name: `${state.binding} — ${state.id}`,+ render: () => TEXT_INPUT_STATE_RENDERS[state.id](),+ };+}++const meta: Meta = {+ title: 'a11y/Text input pattern',+ tags: ['no-visual'],+ parameters: {+ docs: {+ description: {+ component:+ 'Binding states for the shared native text-input accessibility contract.',+ },+ },+ },+};++export default meta;++export const InputEmptyPlaceholder = storyFor('input-empty-placeholder');+export const InputValued = storyFor('input-valued');+export const InputHiddenLabel = storyFor('input-hidden-label');+export const InputDescribed = storyFor('input-described');+export const InputOptional = storyFor('input-optional');+export const InputRequired = storyFor('input-required');+export const InputError = storyFor('input-error');+export const InputErrorWithoutMessage = storyFor('input-error-without-message');+export const InputWarningDetached = storyFor('input-warning-detached');+export const InputSuccessTooltip = storyFor('input-success-tooltip');+export const InputDisabled = storyFor('input-disabled');+export const InputDisabledWithMessage = storyFor('input-disabled-with-message');+export const InputReadOnly = storyFor('input-read-only');+export const InputPassword = storyFor('input-password');+export const InputGroupDescribed = storyFor('input-group-described');++export const TextareaEmptyPlaceholder = storyFor('textarea-empty-placeholder');+export const TextareaValued = storyFor('textarea-valued');+export const TextareaHiddenLabel = storyFor('textarea-hidden-label');+export const TextareaDescribed = storyFor('textarea-described');+export const TextareaOptional = storyFor('textarea-optional');+export const TextareaRequired = storyFor('textarea-required');+export const TextareaError = storyFor('textarea-error');+export const TextareaErrorWithoutMessage = storyFor(+ 'textarea-error-without-message',+);+export const TextareaWarningDetached = storyFor('textarea-warning-detached');+export const TextareaSuccessTooltip = storyFor('textarea-success-tooltip');+export const TextareaDisabled = storyFor('textarea-disabled');+export const TextareaDisabledWithMessage = storyFor(+ 'textarea-disabled-with-message',+);+export const TextareaReadOnly = storyFor('textarea-read-only');+export const TextareaOverLimit = storyFor('textarea-over-limit');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex d3e621662d..fabe51df15 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -42,16 +42,24 @@ src/└── patterns/├── checkbox.* the checkbox pattern, same four files├── switch.* the switch pattern, same four files- └── button.* the button pattern, same four files+ ├── button.* the button pattern, same four files+ └── text-input.* the native text-input 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 |+| 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 |++The `text-input` contract is native rather than APG-derived. It covers the+role-bearing `<input>` or `<textarea>` only; composed clear and tooltip buttons+keep their button contract. Password fields bind to persistent naming, state,+focus, and editing expectations, while HTML-AAM defines no corresponding ARIA+role and leaves their protected value representation platform-specific.The button pattern covers the ordinary command button. A toggle button carries`aria-pressed` and is its own pattern; anything that adopts link semantics — an@@ -95,7 +103,8 @@ required failure is not "mostly conformant" (AST-021 FR11).## Authoring a pattern-1. Read the APG pattern and the WCAG success criteria it supports.+1. Read the applicable WCAG criteria and versioned web standards, plus the APG+ pattern only when a current Astryx record adopts one.2. Write the expectations. Each needs a stable id, a user outcome in plainlanguage, exact sources, an applicability condition, an evidence layer (plus`alsoNeeds` for any further layer its body reads), and an enforcement class.diff --git a/internal/a11y-spec/src/check.test.ts b/internal/a11y-spec/src/check.test.tsindex 15e209713a..d3c14253e7 100644--- a/internal/a11y-spec/src/check.test.ts+++ b/internal/a11y-spec/src/check.test.ts@@ -42,6 +42,8 @@ function harness(observes: readonly EvidenceLayer[]): Harness {subject: async () => subject,click: async () => {},abortedPress: async () => {},+ typeText: async () => {},+ clearText: async () => {},press: async () => {},resetFocus: async () => {},};diff --git a/internal/a11y-spec/src/checklist.ts b/internal/a11y-spec/src/checklist.tsindex 4c3e8f0082..d415c508cf 100644--- a/internal/a11y-spec/src/checklist.ts+++ b/internal/a11y-spec/src/checklist.ts@@ -79,6 +79,13 @@ export const CHECKLIST_DIMENSIONS = [outcome: 'Programmatic reading sequence preserves meaning.',usualOwnership: 'Component or composition',},+ {+ id: '1.3.5-identify-input-purpose',+ source: 'WCAG 2.2 1.3.5 Identify Input Purpose (AA)',+ outcome:+ 'Inputs collecting information about the user expose a programmatic purpose when the field purpose is listed by the standard.',+ usualOwnership: 'Component and caller content',+ },{id: '1.4.1-use-of-color',source: 'WCAG 2.2 1.4.1 Use of Color (A)',diff --git a/internal/a11y-spec/src/contract.test.ts b/internal/a11y-spec/src/contract.test.tsindex d1d2a7f1d9..fc54c41782 100644--- a/internal/a11y-spec/src/contract.test.ts+++ b/internal/a11y-spec/src/contract.test.ts@@ -3,7 +3,9 @@/*** @file contract.test.ts* @input Uses ./contract and ./checklist- * @output Proof that `definePattern` refuses a contract nobody could audit.+ * @output Proof that `definePattern` refuses contracts nobody could audit and+ * accepts native patterns grounded in versioned web standards without+ * misrepresenting them as APG patterns.* @position Schema self-test. Each case here is a way an expectation could look* finished and prove nothing.*@@ -21,6 +23,7 @@ import {type AstryxRecord,type Expectation,type PatternContract,+ type WebStandardRequirement,} from './contract';import {CHECKLIST_DIMENSIONS} from './checklist';import type {EvidenceLayer} from './harness';@@ -75,6 +78,23 @@ describe('definePattern', () => {expect(pattern()).not.toThrow();});+ it('cites a versioned web-standard requirement without pretending it is APG', () => {+ const source: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2',+ requirement:+ 'A textbox is an input that allows free-form text as its value.',+ url: 'https://www.w3.org/TR/wai-aria-1.2/#textbox',+ };++ expect(citeSource(source)).toBe(+ 'WAI-ARIA 1.2: A textbox is an input that allows free-form text as its value.',+ );+ expect(+ pattern({expectations: [expectation({sources: [WCAG_4_1_2, source]})]}),+ ).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.tsindex 05eb24fef8..07bdec9b1c 100644--- a/internal/a11y-spec/src/contract.ts+++ b/internal/a11y-spec/src/contract.ts@@ -67,6 +67,16 @@ export interface ApgRequirement {readonly url: string;}+/** An exact requirement from a versioned public web standard. */+export interface WebStandardRequirement {+ readonly standard: 'web-standard';+ /** Specification and version, e.g. `WAI-ARIA 1.2`. */+ readonly specification: string;+ /** The requirement, quoted closely enough to find on the page. */+ readonly requirement: string;+ readonly url: string;+}+/** A current Astryx knowledge record that adopts an outcome. */export interface AstryxRecord {readonly standard: 'astryx';@@ -88,7 +98,8 @@ export interface AstryxRecord {readonly url: string;}-export type NormativeSource = WcagCriterion | ApgRequirement | AstryxRecord;+export type NormativeSource =+ WcagCriterion | ApgRequirement | WebStandardRequirement | AstryxRecord;/** One-line citation, used in test names and failure output (AST-020 FR4). */export function citeSource(source: NormativeSource): string {@@ -97,6 +108,8 @@ export function citeSource(source: NormativeSource): string {return `WCAG 2.2 ${source.id} ${source.name} (${source.level})`;case 'apg':return `APG ${source.pattern}: ${source.requirement}`;+ case 'web-standard':+ return `${source.specification}: ${source.requirement}`;case 'astryx':return `Astryx ${source.id} ${source.clause}: ${source.requirement}`;}@@ -205,9 +218,9 @@ export interface Expectation<Facts> {}export interface PatternContract<Facts> {- /** APG pattern slug this contract adopts. */+ /** Stable pattern id, e.g. `switch` or `text-input`. */readonly pattern: string;- /** The adopted pattern's canonical URL. */+ /** The pattern's canonical public normative URL. */readonly url: string;/** What the pattern owns, in one line, for report headers. */readonly scope: string;@@ -271,7 +284,7 @@ export function unansweredDimensions<Facts>();}-const ID_SHAPE = /^[a-z][a-z0-9]*(\.[a-z0-9-]+)+$/;+const ID_SHAPE = /^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/;const EMPTY_EXEMPTION =/^(n\/?a|not applicable|none|unknown|tbd|does not apply)\.?$/i;const DIMENSION_IDS: readonly string[] = CHECKLIST_DIMENSIONS.map(diff --git a/internal/a11y-spec/src/harness.ts b/internal/a11y-spec/src/harness.tsindex c353d8c092..33fd70e0b6 100644--- a/internal/a11y-spec/src/harness.ts+++ b/internal/a11y-spec/src/harness.ts@@ -37,10 +37,9 @@ export type EvidenceLayer = (typeof EVIDENCE_LAYERS)[number];/*** What the browser computes for a node. Only an engine can answer this.*- * Requiredness is deliberately absent: Chromium's protocol does not emit a- * `required` property for a checkbox, so putting one here would be a field this- * package could only ever fill with a guess. The switch contract reads that- * declaration at the DOM layer instead.+ * Properties are nullable when the engine does not expose them for a role. For+ * example, Chromium emits `required` for native textboxes but not checkboxes;+ * callers must not substitute a DOM guess for a missing tree property.*/export interface ComputedNode {/** Computed role, e.g. `switch`. */@@ -49,6 +48,14 @@ export interface ComputedNode {readonly name: string;/** Computed accessible description. */readonly description: string;+ /** Computed text value, or null when the node exposes no value. */+ readonly value: string | null;+ /** Whether the engine exposes the textbox as multi-line. */+ readonly multiline: boolean | null;+ /** Whether the engine exposes the control as read-only. */+ readonly readOnly: boolean | null;+ /** Whether the engine exposes the control as required. */+ readonly required: boolean | null;/** Computed checked state, or null when the node exposes none. */readonly checked: 'true' | 'false' | 'mixed' | null;readonly disabled: boolean;@@ -65,6 +72,12 @@ export interface Subject {* is an id that resolves to nothing — a description the user never gets.*/idReferences(attribute: string): Promise<readonly (string | null)[]>;+ /** Real-browser layer: visible text for each id-list relationship target. */+ visibleIdReferences(attribute: string): Promise<readonly (string | null)[]>;+ /** DOM layer: persistent author-supplied label text, excluding placeholder. */+ labelText(): Promise<string | null>;+ /** DOM/runtime layer: the live value of a native text control, if this is one. */+ textValue(): Promise<string | null>;/** Accessibility-tree layer: what the engine computes for this node. */computed(): Promise<ComputedNode>;/**@@ -120,6 +133,10 @@ export interface Harness {* press, slide off, let go.*/abortedPress(subject: Subject): Promise<void>;+ /** Real-browser layer: type text into the focused subject. */+ typeText(subject: Subject, text: string): Promise<void>;+ /** Real-browser layer: select and delete all text from the subject. */+ clearText(subject: Subject): Promise<void>;/** Real-browser layer: send a key to whatever currently holds focus. */press(key: Key): Promise<void>;/** Real-browser layer: park focus at the document body, before the content. */diff --git a/internal/a11y-spec/src/harness/chromium.ts b/internal/a11y-spec/src/harness/chromium.tsindex d2bd176628..20025437d1 100644--- a/internal/a11y-spec/src/harness/chromium.ts+++ b/internal/a11y-spec/src/harness/chromium.ts@@ -84,6 +84,7 @@ interface AxNode {readonly role?: AxValue;readonly name?: AxValue;readonly description?: AxValue;+ readonly value?: AxValue;readonly backendDOMNodeId?: number;readonly properties?: readonly AxProperty[];}@@ -105,6 +106,17 @@ function flag(node: AxNode, name: string): boolean {return value === true || value === 'true' || value === 1;}+function optionalFlag(node: AxNode, name: string): boolean | null {+ const value = property(node, name);+ if (value === true || value === 'true' || value === 1) {+ return true;+ }+ if (value === false || value === 'false' || value === 0) {+ return false;+ }+ return null;+}+const AX_TARGET_ATTRIBUTE = 'data-a11y-spec-ax-target';/**@@ -154,19 +166,34 @@ async function computedNode(role: null,name: '',description: '',+ value: null,+ multiline: null,+ readOnly: null,+ required: null,checked: null,disabled: false,invalid: false,};}+ const role = text(node.role);const checked = property(node, 'checked');const invalid = property(node, 'invalid');+ const exposedValue = node.value?.value;return {- role: text(node.role) === '' ? null : text(node.role),+ role: role === '' ? null : role,name: text(node.name),description: text(node.description),+ value:+ typeof exposedValue === 'string'+ ? exposedValue+ : role === 'textbox'+ ? ''+ : null,+ multiline: optionalFlag(node, 'multiline'),+ readOnly: optionalFlag(node, 'readonly'),+ required: optionalFlag(node, 'required'),checked:checked === 'true' || checked === true? 'true'@@ -241,6 +268,141 @@ export function createChromiumHarness(}),attribute,),+ visibleIdReferences: attribute =>+ locator.evaluate((element, name) => {+ const isTransparentBox = (node: Element): boolean =>+ getComputedStyle(node).display === 'contents';+ const rendered = (node: Element): boolean => {+ if (isTransparentBox(node)) {+ return true;+ }+ if (+ !node.checkVisibility({+ visibilityProperty: true,+ opacityProperty: true,+ contentVisibilityAuto: true,+ })+ ) {+ return false;+ }+ const box = node.getBoundingClientRect();+ return box.width > 1 && box.height > 1;+ };+ const textIsReadable = (node: Element): boolean =>+ !/^rgba\(.*,\s*0\)$/.test(getComputedStyle(node).color);+ const paints = (node: Element): boolean => {+ if (!rendered(node)) {+ return false;+ }+ if (isTransparentBox(node)) {+ return true;+ }+ const box = node.getBoundingClientRect();+ const inlineStyle = (node as HTMLElement).style;+ const pointerTransparent =+ getComputedStyle(node).pointerEvents === 'none';+ const originalPointerEvents =+ inlineStyle.getPropertyValue('pointer-events');+ const originalPriority =+ inlineStyle.getPropertyPriority('pointer-events');+ if (pointerTransparent) {+ inlineStyle.setProperty('pointer-events', 'auto', 'important');+ }+ try {+ const samples: ReadonlyArray<readonly [number, number]> = [+ [box.x + box.width / 2, box.y + box.height / 2],+ [box.x + 1, box.y + box.height / 2],+ [box.right - 1, box.y + box.height / 2],+ ];+ return samples.some(([x, y]) => {+ const at = node.ownerDocument.elementFromPoint(x, y);+ return at != null && (at === node || node.contains(at));+ });+ } finally {+ if (pointerTransparent) {+ if (originalPointerEvents === '') {+ inlineStyle.removeProperty('pointer-events');+ } else {+ inlineStyle.setProperty(+ 'pointer-events',+ originalPointerEvents,+ originalPriority,+ );+ }+ }+ }+ };+ const visibleTextOf = (node: Element): string => {+ if (!paints(node)) {+ return '';+ }+ let value = '';+ for (const child of node.childNodes) {+ if (child.nodeType === Node.TEXT_NODE) {+ if (textIsReadable(node)) {+ value += child.nodeValue ?? '';+ }+ } else if (child.nodeType === Node.ELEMENT_NODE) {+ value += ` ${visibleTextOf(child as Element)} `;+ }+ }+ return value.replace(/\s+/g, ' ').trim();+ };++ return (element.getAttribute(name) ?? '')+ .split(/\s+/)+ .filter(Boolean)+ .map(id => {+ const target = element.ownerDocument.getElementById(id);+ if (target == null) {+ return null;+ }+ const text = visibleTextOf(target);+ return text === '' ? null : text;+ });+ }, attribute),+ labelText: () =>+ locator.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: () =>+ locator.evaluate(element => {+ if (+ element instanceof HTMLInputElement ||+ element instanceof HTMLTextAreaElement+ ) {+ return element.value;+ }+ return null;+ }),computed: () => computedNode(cdp, locator),visibleLabelText: async () => {const explicitLabel =@@ -531,6 +693,15 @@ export function createChromiumHarness(await page.mouse.move(releaseX, releaseY);await page.mouse.up();},+ typeText: async (_subject, text) => {+ await locator.focus();+ await page.keyboard.type(text);+ },+ clearText: async () => {+ await locator.focus();+ await page.keyboard.press('ControlOrMeta+A');+ await page.keyboard.press('Backspace');+ },press: async key => {await page.keyboard.press(KEYS[key]);},diff --git a/internal/a11y-spec/src/harness/jsdom.ts b/internal/a11y-spec/src/harness/jsdom.tsindex 89616ef6b2..aaf2c7d2e1 100644--- a/internal/a11y-spec/src/harness/jsdom.ts+++ b/internal/a11y-spec/src/harness/jsdom.ts@@ -54,6 +54,56 @@ function createSubject(element: Element): Subject {return target == null ? null : (target.textContent ?? '').trim();});},+ visibleIdReferences: async () =>+ unobservable(+ 'real-browser',+ 'whether referenced text is visibly rendered',+ ),+ labelText: async () => {+ const labelledBy = element.getAttribute('aria-labelledby');+ if (labelledBy != null && labelledBy.trim() !== '') {+ const text = (+ await Promise.all(+ labelledBy+ .split(/\s+/)+ .filter(Boolean)+ .map(+ async 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: async () => {+ if (+ element instanceof HTMLInputElement ||+ element instanceof HTMLTextAreaElement+ ) {+ return element.value;+ }+ return null;+ },computed: async () =>unobservable('accessibility-tree', 'a computed accessibility node'),visibleLabelText: async () =>@@ -83,6 +133,10 @@ export function createJsdomHarness(options: JsdomHarnessOptions): Harness {unobservable('real-browser', 'a real pointer activation'),abortedPress: async () =>unobservable('real-browser', 'a real pointer press'),+ typeText: async () =>+ unobservable('real-browser', 'real keyboard text entry'),+ clearText: async () =>+ unobservable('real-browser', 'real keyboard text deletion'),press: async () => unobservable('real-browser', 'a real key press'),resetFocus: async () => unobservable('real-browser', 'real focus'),};diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.tsindex 918b384fcb..8bf2b602b7 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -30,6 +30,7 @@ export {type NormativeSource,type PatternContract,type WcagCriterion,+ type WebStandardRequirement,} from './contract';export {@@ -77,6 +78,11 @@ export {export {createJsdomHarness, type JsdomHarnessOptions} from './harness/jsdom';+export {+ TEXT_INPUT_PATTERN,+ type TextInputStateFacts,+} from './patterns/text-input';+export {CHECKBOX_PATTERN, type CheckboxStateFacts} from './patterns/checkbox';export {SWITCH_PATTERN, type SwitchStateFacts} from './patterns/switch';diff --git a/internal/a11y-spec/src/patterns/button.ts b/internal/a11y-spec/src/patterns/button.tsindex ba67bebecf..cb633949cd 100644--- a/internal/a11y-spec/src/patterns/button.ts+++ b/internal/a11y-spec/src/patterns/button.ts@@ -565,6 +565,13 @@ export const BUTTON_PATTERN: PatternContract<ButtonStateFacts> =reason:'A button is a single control; the order it is read in relative to other content is decided by whatever composes it.',},+ '1.3.5-identify-input-purpose': {+ owner: 'the composing form and caller content',+ verifiedBy:+ 'form integration review for any user-information input composed with this action',+ reason:+ 'A button performs an action and does not itself collect user information whose purpose can be identified by an autocomplete token.',+ },'1.4.1-use-of-color': {owner: 'the binding component and the theme',verifiedBy:diff --git a/internal/a11y-spec/src/patterns/checkbox.ts b/internal/a11y-spec/src/patterns/checkbox.tsindex 8ce799cc6e..5d4f914c2e 100644--- a/internal/a11y-spec/src/patterns/checkbox.ts+++ b/internal/a11y-spec/src/patterns/checkbox.ts@@ -887,6 +887,13 @@ export const CHECKBOX_PATTERN: PatternContract<CheckboxStateFacts> =reason:'A checkbox is a single control; the order it is read in relative to other content is decided by whatever composes it.',},+ '1.3.5-identify-input-purpose': {+ owner: 'the composing form and caller content',+ verifiedBy:+ 'form integration review for any user-information input composed with this choice',+ reason:+ 'A checkbox records a choice and does not itself collect the user-information values covered by autocomplete purpose tokens.',+ },'1.4.1-use-of-color': {owner: 'the binding component and the theme',verifiedBy:diff --git a/internal/a11y-spec/src/patterns/switch.ts b/internal/a11y-spec/src/patterns/switch.tsindex f195b44a7b..8d8e3d28f1 100644--- a/internal/a11y-spec/src/patterns/switch.ts+++ b/internal/a11y-spec/src/patterns/switch.ts@@ -705,6 +705,13 @@ export const SWITCH_PATTERN: PatternContract<SwitchStateFacts> =reason:'A switch is a single control; the order it is read in relative to other content is decided by whatever composes it.',},+ '1.3.5-identify-input-purpose': {+ owner: 'the composing form and caller content',+ verifiedBy:+ 'form integration review for any user-information input composed near this setting',+ reason:+ 'A switch changes a setting and does not itself collect user information whose purpose can be identified by an autocomplete token.',+ },'1.4.1-use-of-color': {owner: 'the binding component and the theme',verifiedBy:diff --git a/internal/a11y-spec/src/patterns/text-input.chromium.spec.ts b/internal/a11y-spec/src/patterns/text-input.chromium.spec.tsnew file mode 100644index 0000000000..bf19034852--- /dev/null+++ b/internal/a11y-spec/src/patterns/text-input.chromium.spec.ts@@ -0,0 +1,90 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file text-input.chromium.spec.ts+ * @input Uses native text-input fixtures, the shared contract, and Chromium harness+ * @output Accessibility-tree positive and mutation proof for the text-input contract+ * @position Contract self-test; component bindings use checked-in Storybook stories.+ */++import {expect, test, type CDPSession, type Page} from '@playwright/test';+import {describeExpectation, requiredLayers} from '../contract';+import {checkAccessibilitySpec, type ExpectationResult} from '../check';+import {+ CHROMIUM_OBSERVES,+ createChromiumHarness,+ holdMotionStill,+} from '../harness/chromium';+import {TEXT_INPUT_PATTERN} from './text-input';+import {+ CONFORMING_FIXTURES,+ SUBJECT_SELECTOR,+ TEXT_INPUT_MUTATIONS,+ fixture,+ type TextInputFixture,+} from './text-input.fixtures';++async function resultsFor(+ page: Page,+ cdp: CDPSession,+ target: TextInputFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ return (+ await checkAccessibilitySpec({+ spec: TEXT_INPUT_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ mount: async () => {+ await page.setContent(+ `<button type="button">Before</button>${target.html}<button type="button">After</button>`,+ );+ await holdMotionStill(page);+ return createChromiumHarness({+ page,+ subject: page.locator(SUBJECT_SELECTOR),+ cdp,+ });+ },+ only,+ })+ ).results;+}++test.describe('text-input contract — conforming native fixtures', () => {+ for (const fixtureId of CONFORMING_FIXTURES) {+ test(`${fixtureId} passes every applicable Chromium expectation`, async ({+ page,+ }) => {+ const cdp = await page.context().newCDPSession(page);+ const results = await resultsFor(page, cdp, fixture(fixtureId));+ expect(results.filter(result => result.status === 'fail')).toEqual([]);+ expect(results.filter(result => result.status === 'unrun')).toEqual([]);+ });+ }+});++test.describe('text-input contract — deliberately violating fixtures', () => {+ for (const expectation of TEXT_INPUT_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of TEXT_INPUT_MUTATIONS[expectation.id] ?? []) {+ test(`${describeExpectation(expectation)} — fails against ${fixtureId}`, async ({+ page,+ }) => {+ const cdp = await page.context().newCDPSession(page);+ const [result] = await resultsFor(page, cdp, fixture(fixtureId), [+ expectation.id,+ ]);+ expect(result?.status).toBe('fail');+ expect(result?.detail).not.toBe('');+ });+ }+ }+});diff --git a/internal/a11y-spec/src/patterns/text-input.fixtures.ts b/internal/a11y-spec/src/patterns/text-input.fixtures.tsnew file mode 100644index 0000000000..9bef72386d--- /dev/null+++ b/internal/a11y-spec/src/patterns/text-input.fixtures.ts@@ -0,0 +1,366 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file text-input.fixtures.ts+ * @input Uses ./text-input (TextInputStateFacts)+ * @output TEXT_INPUT_FIXTURES — native conforming and deliberately violating+ * fixtures — plus TEXT_INPUT_MUTATIONS, which maps each expectation to proof+ * @position Contract self-test fixtures; no Astryx component is used here.+ */++import type {TextInputStateFacts} from './text-input';++export const SUBJECT_ATTRIBUTE = 'data-a11y-subject';+export const SUBJECT_SELECTOR = `[${SUBJECT_ATTRIBUTE}]`;++export interface TextInputFixture {+ readonly id: string;+ readonly summary: string;+ readonly facts: TextInputStateFacts;+ readonly html: string;+}++const DEFAULT_FACTS: TextInputStateFacts = {+ role: 'textbox',+ multiline: false,+ value: '',+ editable: true,+ focusable: true,+ disabled: false,+ readOnly: false,+ required: false,+ invalid: false,+ description: null,+ errorMessage: null,+};++function facts(+ overrides: Partial<TextInputStateFacts> = {},+): TextInputStateFacts {+ return {...DEFAULT_FACTS, ...overrides};+}++export const TEXT_INPUT_FIXTURES: readonly TextInputFixture[] = [+ {+ id: 'conforming-single-line',+ summary: 'a named native single-line text input',+ facts: facts(),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text">`,+ },+ {+ id: 'conforming-multi-line',+ summary: 'a named native multi-line text area',+ facts: facts({multiline: true, value: 'Existing note'}),+ html: `<label for="fx">Notes</label><textarea id="fx" ${SUBJECT_ATTRIBUTE}>Existing note</textarea>`,+ },+ {+ id: 'conforming-described',+ summary: 'a native text input with supporting text attached',+ facts: facts({description: 'Use your public display name.'}),+ html: `<label for="fx">Name</label><span id="hint">Use your public display name.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-describedby="hint">`,+ },+ {+ id: 'conforming-disabled',+ summary: 'a natively disabled text input outside the tab sequence',+ facts: facts({+ value: 'Fixed value',+ editable: false,+ focusable: false,+ disabled: true,+ }),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" value="Fixed value" disabled>`,+ },+ {+ id: 'conforming-focusable-disabled',+ summary: 'an aria-disabled text input kept focusable for its reason',+ facts: facts({+ value: 'Fixed value',+ editable: false,+ disabled: true,+ description: 'Managed by your administrator.',+ }),+ html: `<label for="fx">Name</label><span id="hint">Managed by your administrator.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" value="Fixed value" aria-disabled="true" readonly aria-describedby="hint">`,+ },+ {+ id: 'conforming-read-only',+ summary: 'a native read-only text input that stays focusable',+ facts: facts({+ value: 'Fixed value',+ editable: false,+ readOnly: true,+ }),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" value="Fixed value" readonly>`,+ },+ {+ id: 'conforming-required',+ summary: 'a required text input with its obligation exposed',+ facts: facts({required: true}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-required="true">`,+ },+ {+ id: 'conforming-invalid',+ summary: 'an invalid text input with textual error feedback attached',+ facts: facts({+ invalid: true,+ description: 'Enter a valid name.',+ errorMessage: 'Enter a valid name.',+ }),+ html: `<label for="fx">Name</label><span id="error">Enter a valid name.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true" aria-describedby="error">`,+ },+ {+ id: 'conforming-invalid-aria-errormessage',+ summary:+ 'an invalid text input using the standards-defined error relationship',+ facts: facts({+ invalid: true,+ errorMessage: 'Enter a valid name.',+ }),+ html: `<label for="fx">Name</label><span id="error">Enter a valid name.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true" aria-errormessage="error">`,+ },+ {+ id: 'violating-generic-role',+ summary: 'an editable generic element that never exposes the textbox role',+ facts: facts(),+ html: `<div ${SUBJECT_ATTRIBUTE} contenteditable="true">Name</div>`,+ },+ {+ id: 'violating-value-mismatch',+ summary: 'a text input whose exposed value differs from the rendered value',+ facts: facts({value: 'Expected value'}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" value="Wrong value">`,+ },+ {+ id: 'violating-multiline-mismatch',+ summary: 'a single-line input declared as the multi-line binding state',+ facts: facts({multiline: true}),+ html: `<label for="fx">Notes</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text">`,+ },+ {+ id: 'violating-unnamed',+ summary: 'a native text input with no accessible name',+ facts: facts(),+ html: `<input ${SUBJECT_ATTRIBUTE} type="text">`,+ },+ {+ id: 'violating-name-mismatch',+ summary: 'a text input whose aria-label replaces its visible label',+ facts: facts(),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-label="Search">`,+ },+ {+ id: 'violating-dangling-description',+ summary: 'a text input described by an id that resolves to nothing',+ facts: facts({description: 'Use your public display name.'}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-describedby="hint">`,+ },+ {+ id: 'violating-empty-description',+ summary: 'a text input described by an element that renders no text',+ facts: facts({description: 'Use your public display name.'}),+ html: `<label for="fx">Name</label><span id="hint"></span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-describedby="hint">`,+ },+ {+ id: 'violating-disabled-unexposed',+ summary: 'an unavailable text input that does not expose disabled state',+ facts: facts({value: 'Fixed value', editable: false, disabled: true}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" value="Fixed value" readonly>`,+ },+ {+ id: 'violating-disabled-overexposed',+ summary: 'an available text input falsely exposed as disabled',+ facts: facts({editable: false, focusable: false}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" disabled>`,+ },+ {+ id: 'violating-readonly-unexposed',+ summary: 'a read-only text input without a read-only declaration',+ facts: facts({value: 'Fixed value', editable: false, readOnly: true}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" value="Fixed value" onbeforeinput="event.preventDefault()">`,+ },+ {+ id: 'violating-readonly-overexposed',+ summary: 'an editable text input falsely exposed as read-only',+ facts: facts({value: 'Fixed value'}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" value="Fixed value" readonly>`,+ },+ {+ id: 'violating-required-unexposed',+ summary: 'a required text input with no required-state exposure',+ facts: facts({required: true}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text">`,+ },+ {+ id: 'violating-required-overexposed',+ summary: 'an optional text input falsely exposed as required',+ facts: facts(),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-required="true">`,+ },+ {+ id: 'violating-invalid-unexposed',+ summary:+ 'an invalid text input with feedback but no invalid-state exposure',+ facts: facts({+ invalid: true,+ description: 'Enter a valid name.',+ errorMessage: 'Enter a valid name.',+ }),+ html: `<label for="fx">Name</label><span id="error">Enter a valid name.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-describedby="error">`,+ },+ {+ id: 'violating-invalid-overexposed',+ summary: 'a valid text input falsely exposed as invalid',+ facts: facts(),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true">`,+ },+ {+ id: 'violating-error-without-text',+ summary: 'an invalid text input that supplies no textual error description',+ facts: facts({invalid: true}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true">`,+ },+ {+ id: 'violating-hidden-unrelated-error',+ summary: 'matching hidden text that is not related to the invalid control',+ facts: facts({invalid: true, errorMessage: 'Enter a valid name.'}),+ html: `<label for="fx">Name</label><span hidden>Enter a valid name.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true">`,+ },+ {+ id: 'violating-visible-unrelated-error',+ summary: 'matching visible text that is not related to the invalid control',+ facts: facts({invalid: true, errorMessage: 'Enter a valid name.'}),+ html: `<label for="fx">Name</label><span>Enter a valid name.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true">`,+ },+ {+ id: 'violating-multi-id-errormessage',+ summary:+ 'an aria-errormessage value containing more than its one allowed id',+ facts: facts({invalid: true, errorMessage: 'Enter a valid name.'}),+ html: `<label for="fx">Name</label><span id="other">Other error.</span><span id="error">Enter a valid name.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true" aria-errormessage="other error">`,+ },+ {+ id: 'violating-hidden-related-error',+ summary: 'an aria-errormessage target hidden while the control is invalid',+ facts: facts({invalid: true, errorMessage: 'Enter a valid name.'}),+ html: `<label for="fx">Name</label><span id="error" hidden>Enter a valid name.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true" aria-errormessage="error">`,+ },+ {+ id: 'violating-transparent-related-error',+ summary: 'a related error whose text is painted transparent',+ facts: facts({invalid: true, errorMessage: 'Enter a valid name.'}),+ html: `<label for="fx">Name</label><span id="error" style="color: transparent">Enter a valid name.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true" aria-errormessage="error">`,+ },+ {+ id: 'violating-clipped-related-error',+ summary: 'a related error clipped completely out of view',+ facts: facts({invalid: true, errorMessage: 'Enter a valid name.'}),+ html: `<label for="fx">Name</label><span id="error" style="position: absolute; clip-path: inset(100%)">Enter a valid name.</span><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true" aria-errormessage="error">`,+ },+ {+ id: 'violating-hidden-descendant-related-error',+ summary:+ 'a visible relationship target whose expected error words are hidden in a descendant',+ facts: facts({invalid: true, errorMessage: 'Enter a valid name.'}),+ html: `<label for="fx">Name</label><div id="error"><span>General guidance</span><span hidden>Enter a valid name.</span></div><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" aria-invalid="true" aria-errormessage="error">`,+ },+ {+ id: 'violating-editing-inert',+ summary: 'an apparently editable text input that refuses keyboard changes',+ facts: facts({value: 'Start'}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" value="Start" readonly>`,+ },+ {+ id: 'violating-unreachable',+ summary: 'a focusable text input removed from the tab sequence',+ facts: facts(),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" tabindex="-1">`,+ },+ {+ id: 'violating-keyboard-trap',+ summary: 'a text input that swallows the Tab key',+ facts: facts(),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" onkeydown="if (event.key === 'Tab') event.preventDefault()">`,+ },+ {+ id: 'violating-inoperable-edits',+ summary:+ 'a read-only binding state whose native control still accepts text',+ facts: facts({value: 'Fixed value', editable: false, readOnly: true}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" value="Fixed value">`,+ },+ {+ id: 'violating-focusable-disabled-edits',+ summary: 'a focusable aria-disabled text input that still accepts text',+ facts: facts({value: 'Fixed value', editable: false, disabled: true}),+ html: `<label for="fx">Name</label><input id="fx" ${SUBJECT_ATTRIBUTE} type="text" value="Fixed value" aria-disabled="true">`,+ },+ {+ id: 'violating-placeholder-only-label',+ summary:+ 'a text input that uses disappearing placeholder text as its only label',+ facts: facts(),+ html: `<input ${SUBJECT_ATTRIBUTE} type="text" placeholder="Name">`,+ },+];++export const CONFORMING_FIXTURES = [+ 'conforming-single-line',+ 'conforming-multi-line',+ 'conforming-described',+ 'conforming-disabled',+ 'conforming-focusable-disabled',+ 'conforming-read-only',+ 'conforming-required',+ 'conforming-invalid',+ 'conforming-invalid-aria-errormessage',+] as const;++export const TEXT_INPUT_MUTATIONS: Readonly<Record<string, readonly string[]>> =+ {+ 'text-input.role.exposed': ['violating-generic-role'],+ 'text-input.value.exposed': ['violating-value-mismatch'],+ 'text-input.multiline.exposed': ['violating-multiline-mismatch'],+ 'text-input.name.exposed': ['violating-unnamed'],+ 'text-input.name.matches-visible-label': ['violating-name-mismatch'],+ 'text-input.description.resolvable': ['violating-dangling-description'],+ 'text-input.description.exposed': ['violating-empty-description'],+ 'text-input.disabled.exposed': ['violating-disabled-unexposed'],+ 'text-input.disabled.not-exposed': ['violating-disabled-overexposed'],+ 'text-input.readonly.exposed': ['violating-readonly-unexposed'],+ 'text-input.readonly.not-exposed': ['violating-readonly-overexposed'],+ 'text-input.required.exposed': ['violating-required-unexposed'],+ 'text-input.required.not-exposed': ['violating-required-overexposed'],+ 'text-input.invalid.exposed': ['violating-invalid-unexposed'],+ 'text-input.invalid.not-exposed': ['violating-invalid-overexposed'],+ 'text-input.error.identified-in-text': [+ 'violating-error-without-text',+ 'violating-hidden-unrelated-error',+ 'violating-visible-unrelated-error',+ 'violating-multi-id-errormessage',+ ],+ 'text-input.error.related-text-visible': [+ 'violating-hidden-related-error',+ 'violating-transparent-related-error',+ 'violating-clipped-related-error',+ 'violating-hidden-descendant-related-error',+ ],+ 'text-input.editing.keyboard-round-trip': ['violating-editing-inert'],+ 'text-input.focus.reachable-and-escapable': [+ 'violating-unreachable',+ 'violating-keyboard-trap',+ ],+ 'text-input.editing.inoperable': ['violating-inoperable-edits'],+ 'text-input.editing.disabled-reason-inert': [+ 'violating-focusable-disabled-edits',+ ],+ 'text-input.label.persistently-associated': [+ 'violating-placeholder-only-label',+ ],+ };++export function fixture(id: string): TextInputFixture {+ const found = TEXT_INPUT_FIXTURES.find(candidate => candidate.id === id);+ if (found == null) {+ throw new Error(`unknown text-input fixture "${id}"`);+ }+ return found;+}diff --git a/internal/a11y-spec/src/patterns/text-input.jsdom.test.ts b/internal/a11y-spec/src/patterns/text-input.jsdom.test.tsnew file mode 100644index 0000000000..3563345e73--- /dev/null+++ b/internal/a11y-spec/src/patterns/text-input.jsdom.test.ts@@ -0,0 +1,167 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file text-input.jsdom.test.ts+ * @input Uses the text-input contract, fixtures, jsdom harness, and checker+ * @output DOM-layer positive, negative, traceability, and completeness proof+ * @position Contract self-test. Chromium proves browser/tree expectations.+ */++import {afterEach, describe, expect, it} from 'vitest';+import {+ citeSource,+ describeExpectation,+ requiredLayers,+ unansweredDimensions,+} from '../contract';+import {checkAccessibilitySpec, type ExpectationResult} from '../check';+import {JSDOM_OBSERVES, createJsdomHarness} from '../harness/jsdom';+import {TEXT_INPUT_PATTERN} from './text-input';+import {+ CONFORMING_FIXTURES,+ SUBJECT_SELECTOR,+ TEXT_INPUT_MUTATIONS,+ fixture,+ type TextInputFixture,+} from './text-input.fixtures';++function mount(target: TextInputFixture) {+ document.body.innerHTML = target.html;+ const subject = document.querySelector(SUBJECT_SELECTOR);+ if (subject == null) {+ throw new Error(`fixture ${target.id} has no subject`);+ }+ return createJsdomHarness({subject});+}++async function resultsFor(+ target: TextInputFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ return (+ await checkAccessibilitySpec({+ spec: TEXT_INPUT_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ mount: async () => mount(target),+ only,+ })+ ).results;+}++afterEach(() => {+ document.body.innerHTML = '';+});++describe('text-input contract — completeness', () => {+ it('answers every completeness dimension', () => {+ expect(unansweredDimensions(TEXT_INPUT_PATTERN)).toEqual([]);+ });++ it('gives every expectation at least one deliberately violating fixture', () => {+ expect(+ TEXT_INPUT_PATTERN.expectations+ .filter(+ expectation =>+ (TEXT_INPUT_MUTATIONS[expectation.id] ?? []).length === 0,+ )+ .map(expectation => expectation.id),+ ).toEqual([]);+ });++ it('has an expectation for every violating fixture it records', () => {+ const ids = new Set(+ TEXT_INPUT_PATTERN.expectations.map(expectation => expectation.id),+ );+ expect(+ Object.keys(TEXT_INPUT_MUTATIONS).filter(id => !ids.has(id)),+ ).toEqual([]);+ });++ it('names every fixture it records a mutation against', () => {+ for (const fixtures of Object.values(TEXT_INPUT_MUTATIONS)) {+ for (const id of fixtures) {+ expect(() => fixture(id)).not.toThrow();+ }+ }+ });+});++describe('text-input contract — jsdom evidence boundary', () => {+ it('reports every higher-layer expectation as unrun, never as pass', async () => {+ for (const expectation of TEXT_INPUT_PATTERN.expectations) {+ if (+ requiredLayers(expectation).every(layer =>+ JSDOM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ const fixtureId = CONFORMING_FIXTURES.find(id =>+ expectation.appliesWhen.test(fixture(id).facts),+ );+ expect(+ fixtureId,+ `${expectation.id} has no applicable conforming fixture`,+ ).toBeDefined();+ const [result] = await resultsFor(fixture(fixtureId!), [expectation.id]);+ expect(result?.status, expectation.id).toBe('unrun');+ }+ });+});++describe('text-input contract — positive and negative proof', () => {+ it('passes each observable expectation on every applicable conforming fixture', async () => {+ for (const expectation of TEXT_INPUT_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ JSDOM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of CONFORMING_FIXTURES) {+ const result = (+ await resultsFor(fixture(fixtureId), [expectation.id])+ )[0];+ expect(['pass', 'not-applicable']).toContain(result?.status);+ }+ }+ });++ it('fails each observable expectation against every mapped mutation', async () => {+ for (const expectation of TEXT_INPUT_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ JSDOM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of TEXT_INPUT_MUTATIONS[expectation.id] ?? []) {+ const result = (+ await resultsFor(fixture(fixtureId), [expectation.id])+ )[0];+ expect(result?.status, `${expectation.id} against ${fixtureId}`).toBe(+ 'fail',+ );+ expect(result?.detail).not.toBe('');+ }+ }+ });++ it('carries each expectation id and primary source into its result', async () => {+ for (const expectation of TEXT_INPUT_PATTERN.expectations) {+ const fixtureId =+ TEXT_INPUT_MUTATIONS[expectation.id]?.[0] ?? CONFORMING_FIXTURES[0];+ const result = (+ await resultsFor(fixture(fixtureId), [expectation.id])+ )[0];+ expect(result?.description).toContain(expectation.id);+ expect(result?.description).toContain(citeSource(expectation.sources[0]));+ expect(result?.description).toBe(describeExpectation(expectation));+ }+ });+});diff --git a/internal/a11y-spec/src/patterns/text-input.ts b/internal/a11y-spec/src/patterns/text-input.tsnew file mode 100644index 0000000000..c89ef6656e--- /dev/null+++ b/internal/a11y-spec/src/patterns/text-input.ts@@ -0,0 +1,942 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file text-input.ts+ * @input Uses ../contract (definePattern and the expectation vocabulary)+ * @output TEXT_INPUT_PATTERN — the native text-input pattern contract — and+ * TextInputStateFacts, what a binding declares each rendered state should expose+ * @position Shared accessibility contract for native single-line and multi-line+ * text controls; component-specific callbacks, form behavior, composition,+ * styling, and announcement behavior stay with each binding component.+ */++import {+ definePattern,+ type AstryxRecord,+ type PatternContract,+ type WcagCriterion,+ type WebStandardRequirement,+} from '../contract';+import type {Harness, Subject} from '../harness';+import {saysInOrder, spokenWords} from '../spoken';++const WCAG_1_3_1: WcagCriterion = {+ standard: 'wcag',+ id: '1.3.1',+ name: 'Info and Relationships',+ level: 'A',+ url: 'https://www.w3.org/WAI/WCAG22/Understanding/info-and-relationships.html',+};++const WCAG_2_1_1: WcagCriterion = {+ standard: 'wcag',+ id: '2.1.1',+ name: 'Keyboard',+ level: 'A',+ url: 'https://www.w3.org/WAI/WCAG22/Understanding/keyboard.html',+};++const WCAG_2_1_2: WcagCriterion = {+ standard: 'wcag',+ id: '2.1.2',+ name: 'No Keyboard Trap',+ level: 'A',+ url: 'https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap.html',+};++const WCAG_2_5_3: WcagCriterion = {+ standard: 'wcag',+ id: '2.5.3',+ name: 'Label in Name',+ level: 'A',+ url: 'https://www.w3.org/WAI/WCAG22/Understanding/label-in-name.html',+};++const WCAG_3_3_1: WcagCriterion = {+ standard: 'wcag',+ id: '3.3.1',+ name: 'Error Identification',+ level: 'A',+ url: 'https://www.w3.org/WAI/WCAG22/Understanding/error-identification.html',+};++const WCAG_3_3_2: WcagCriterion = {+ standard: 'wcag',+ id: '3.3.2',+ name: 'Labels or Instructions',+ level: 'A',+ url: 'https://www.w3.org/WAI/WCAG22/Understanding/labels-or-instructions.html',+};++const WCAG_4_1_2: WcagCriterion = {+ standard: 'wcag',+ id: '4.1.2',+ name: 'Name, Role, Value',+ level: 'A',+ url: 'https://www.w3.org/WAI/WCAG22/Understanding/name-role-value.html',+};++const AST_021_PRESERVE_BEHAVIOR: AstryxRecord = {+ standard: 'astryx',+ id: 'spec:AST-021',+ clause: 'FR7',+ requirement:+ 'Existing behavior is preserved unless a separate change authorizes it.',+ url: 'https://github.com/facebook/astryx/blob/029368bde880cb25a7912523510419285d803a90/docs/specs/AST-021/spec.md#L85-L89',+};++const INPUT_FIELDS_FR4: AstryxRecord = {+ standard: 'astryx',+ id: 'family:input-fields',+ clause: 'FR4',+ requirement:+ 'When a member exposes `disabledMessage`, the inactive field remains focusable enough to expose the reason while editing, selection, and activation stay blocked.',+ url: 'https://github.com/facebook/astryx/blob/029368bde880cb25a7912523510419285d803a90/docs/families/input-fields.md#L151-L154',+};++const WAI_ARIA_ERROR_MESSAGE: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'WAI-ARIA 1.2',+ requirement:+ 'When the error message is pertinent, authors MUST ensure the content is not hidden, so users can navigate to and examine the error message.',+ url: 'https://www.w3.org/TR/wai-aria-1.2/#aria-errormessage',+};++const HTML_AAM_INPUT_TEXTBOX: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'HTML Accessibility API Mappings 1.0',+ requirement: 'input type text, email, tel, and url map to the textbox role.',+ url: 'https://www.w3.org/TR/html-aam-1.0/#el-input-text',+};++const HTML_AAM_TEXTAREA: WebStandardRequirement = {+ standard: 'web-standard',+ specification: 'HTML Accessibility API Mappings 1.0',+ requirement: 'textarea maps to the textbox role.',+ url: 'https://www.w3.org/TR/html-aam-1.0/#el-textarea',+};++const ALWAYS = {+ condition: 'the binding renders a native text control',+ test: () => true,+};++function sameWords(actual: string, expected: string): boolean {+ const actualWords = spokenWords(actual);+ const expectedWords = spokenWords(expected);+ return (+ actualWords.length === expectedWords.length &&+ actualWords.every((word, index) => word === expectedWords[index])+ );+}++const TAB_BUDGET = 10;++async function assertKeyboardEditsBlocked(+ harness: Harness,+ subject: Subject,+): Promise<void> {+ await subject.focus();+ const initial = await subject.textValue();+ if (initial == null) {+ throw new Error(+ 'the role-bearing subject exposes no text value to protect',+ );+ }+ await harness.typeText(subject, 'x');+ if ((await subject.textValue()) !== initial) {+ throw new Error(+ 'typing changed a text control the binding declares non-editable',+ );+ }+ await harness.clearText(subject);+ if ((await subject.textValue()) !== initial) {+ throw new Error(+ 'keyboard deletion changed a text control the binding declares non-editable',+ );+ }+}++export interface TextInputStateFacts {+ /** Native role expected from this state; null for protected inputs with no cross-platform ARIA role mapping. */+ readonly role: 'textbox' | null;+ readonly multiline: boolean;+ readonly value: string | null;+ readonly editable: boolean;+ readonly focusable: boolean;+ readonly disabled: boolean;+ readonly readOnly: boolean;+ readonly required: boolean;+ readonly invalid: boolean;+ readonly description: string | null;+ readonly errorMessage: string | null;+}++export const TEXT_INPUT_PATTERN: PatternContract<TextInputStateFacts> =+ definePattern<TextInputStateFacts>({+ pattern: 'text-input',+ url: 'https://www.w3.org/TR/wai-aria-1.2/#textbox',+ scope:+ 'One native single-line or multi-line text control whose role, name, value, state, supporting text, focus, and editing behavior remain available to the user.',+ expectations: [+ {+ id: 'text-input.role.exposed',+ outcome:+ 'The browser exposes the control as a textbox, so the user knows it accepts text.',+ sources: [WCAG_4_1_2, HTML_AAM_INPUT_TEXTBOX, HTML_AAM_TEXTAREA],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the native control has a cross-platform textbox role mapping',+ test: facts => facts.role != null,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const {role} = await subject.computed();+ if (role !== facts.role) {+ throw new Error(+ role == null+ ? 'the browser exposes no role for this native text control, so the accessibility node does not identify what kind of input it is'+ : `the binding expects the ${facts.role} role, but the browser reports "${role}"`,+ );+ }+ },+ },+ {+ id: 'text-input.value.exposed',+ outcome:+ 'The accessibility node exposes the current text value instead of the placeholder or a stale value.',+ sources: [WCAG_4_1_2],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the binding exposes an ordinary, non-protected text value',+ test: facts => facts.value != null,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const expected = facts.value;+ if (expected == null) {+ throw new Error('value expectation ran without an expected value');+ }+ const {value} = await subject.computed();+ if (value !== expected) {+ throw new Error(+ `the binding renders the value ${JSON.stringify(expected)}, but the browser exposes ${JSON.stringify(value)}`,+ );+ }+ },+ },+ {+ id: 'text-input.multiline.exposed',+ outcome:+ 'The accessibility node distinguishes a multi-line text area from a single-line text input.',+ sources: [WCAG_4_1_2, HTML_AAM_INPUT_TEXTBOX, HTML_AAM_TEXTAREA],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition:+ 'the native control has a cross-platform textbox role mapping',+ test: facts => facts.role === 'textbox',+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const {multiline} = await subject.computed();+ if (multiline !== facts.multiline) {+ throw new Error(+ `the binding renders a ${facts.multiline ? 'multi-line' : 'single-line'} text control, but the browser exposes it as ${multiline ? 'multi-line' : 'single-line'}`,+ );+ }+ },+ },+ {+ id: 'text-input.name.exposed',+ outcome:+ 'The text control has an accessible name, so the user knows what to enter.',+ sources: [WCAG_4_1_2, WCAG_3_3_2],+ covers: ['4.1.2-name-role-value', '3.3.2-labels-or-instructions'],+ 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 text control, so nothing identifies what the user should enter',+ );+ }+ },+ },+ {+ id: 'text-input.label.persistently-associated',+ outcome:+ 'The text control has a persistent programmatic label instead of using placeholder text as its only identification.',+ sources: [WCAG_3_3_2, WCAG_1_3_1],+ covers: [+ '3.3.2-labels-or-instructions',+ '1.3.1-info-and-relationships',+ ],+ appliesWhen: ALWAYS,+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject}) => {+ const label = await subject.labelText();+ if (label == null || label.trim() === '') {+ throw new Error(+ 'the text control has no persistent label relationship; placeholder text alone disappears while the user enters a value',+ );+ }+ },+ },+ {+ id: 'text-input.name.matches-visible-label',+ outcome:+ 'The accessible name contains the visible label, so someone using speech input can say what they can 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 label text, 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 label reads "${visible}" but the browser computes the accessible name as "${name}", so speaking the visible label does not reach this control`,+ );+ }+ },+ },+ {+ id: 'text-input.description.resolvable',+ outcome:+ 'Every piece of supporting text the control points at exists and matches the intended description.',+ sources: [WCAG_1_3_1],+ covers: ['1.3.1-info-and-relationships'],+ appliesWhen: {+ condition: 'the binding renders supporting text for this state',+ test: facts => facts.description != null,+ },+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const expected = facts.description;+ if (expected == null) {+ throw new Error(+ 'description expectation ran without expected supporting text',+ );+ }+ const attribute = await subject.attribute('aria-describedby');+ const ids = (attribute ?? '').split(/\s+/).filter(Boolean);+ if (ids.length === 0) {+ throw new Error(+ 'the binding renders supporting text for this state, but the text control has no aria-describedby',+ );+ }+ 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`,+ );+ }+ const attached = targets+ .filter((text): text is string => text != null)+ .join(' ');+ if (!sameWords(attached, expected)) {+ throw new Error(+ `the binding expects the description "${expected}", but aria-describedby resolves to "${attached}"`,+ );+ }+ },+ },+ {+ id: 'text-input.description.exposed',+ outcome:+ 'The browser computes the intended supporting text as the control’s accessible description.',+ sources: [WCAG_4_1_2],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding renders supporting text for this state',+ test: facts => facts.description != null,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const expected = facts.description;+ if (expected == null) {+ throw new Error(+ 'description expectation ran without expected supporting text',+ );+ }+ const {description} = await subject.computed();+ if (!sameWords(description, expected)) {+ throw new Error(+ description.trim() === ''+ ? `the binding expects the description "${expected}", but the browser computes no accessible description`+ : `the binding expects the description "${expected}", but the browser computes "${description}"`,+ );+ }+ },+ },+ {+ id: 'text-input.disabled.exposed',+ outcome:+ 'A text control the binding marks unavailable is reported as unavailable.',+ sources: [WCAG_4_1_2],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding declares this state unavailable',+ test: facts => facts.disabled,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {disabled} = await subject.computed();+ if (!disabled) {+ throw new Error(+ 'the binding declares this text control unavailable, but the browser reports it as available',+ );+ }+ },+ },+ {+ id: 'text-input.disabled.not-exposed',+ outcome:+ 'An available text control does not expose a false disabled state.',+ sources: [WCAG_4_1_2],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'this state is available',+ test: facts => !facts.disabled,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {disabled} = await subject.computed();+ if (disabled) {+ throw new Error(+ 'this text control is available, but the browser exposes it as disabled',+ );+ }+ },+ },+ {+ id: 'text-input.readonly.exposed',+ outcome:+ 'A read-only text control is exposed as read-only, so the user knows its value cannot be edited.',+ sources: [WCAG_4_1_2],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'this state is read-only and not disabled',+ test: facts => facts.readOnly && !facts.disabled,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {readOnly} = await subject.computed();+ if (readOnly !== true) {+ throw new Error(+ 'the binding declares this text control read-only, but the browser does not expose a read-only state',+ );+ }+ },+ },+ {+ id: 'text-input.readonly.not-exposed',+ outcome:+ 'An editable, available text control does not expose a false read-only state.',+ sources: [WCAG_4_1_2],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'this state is editable and available',+ test: facts => !facts.readOnly && !facts.disabled,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {readOnly} = await subject.computed();+ if (readOnly === true) {+ throw new Error(+ 'this text control is editable, but the browser exposes it as read-only',+ );+ }+ },+ },+ {+ id: 'text-input.required.exposed',+ outcome:+ 'A required text control exposes that obligation before form submission.',+ sources: [WCAG_3_3_2, WCAG_4_1_2],+ covers: ['3.3.2-labels-or-instructions', '4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'this state is required',+ test: facts => facts.required,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {required} = await subject.computed();+ if (required !== true) {+ throw new Error(+ 'the binding declares this text control required, but the browser does not expose a required state',+ );+ }+ },+ },+ {+ id: 'text-input.required.not-exposed',+ outcome:+ 'An optional text control does not expose a false required state.',+ sources: [WCAG_4_1_2],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'this state is not required',+ test: facts => !facts.required,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {required} = await subject.computed();+ if (required === true) {+ throw new Error(+ 'this text control is optional, but the browser exposes it as required',+ );+ }+ },+ },+ {+ id: 'text-input.invalid.exposed',+ outcome:+ 'A text control in error is exposed as invalid, so the user can find what needs fixing.',+ sources: [WCAG_4_1_2],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'this state is invalid',+ test: facts => facts.invalid,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {invalid} = await subject.computed();+ if (!invalid) {+ throw new Error(+ 'the binding declares this text control invalid, but the browser reports it as valid',+ );+ }+ },+ },+ {+ id: 'text-input.invalid.not-exposed',+ outcome: 'A valid text control does not expose a false invalid state.',+ sources: [WCAG_4_1_2],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'this state is valid',+ test: facts => !facts.invalid,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {invalid} = await subject.computed();+ if (invalid) {+ throw new Error(+ 'this text control is valid, but the browser exposes it as invalid',+ );+ }+ },+ },+ {+ id: 'text-input.error.identified-in-text',+ outcome:+ 'An invalid text control renders textual error feedback and programmatically connects it to the field.',+ sources: [WCAG_3_3_1, WCAG_1_3_1],+ covers: ['3.3.1-error-identification'],+ appliesWhen: {+ condition: 'this state is invalid',+ test: facts => facts.invalid,+ },+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const expected = facts.errorMessage;+ if (expected == null || expected.trim() === '') {+ throw new Error(+ 'the binding declares this text control invalid but supplies no textual error description',+ );+ }+ const errorMessageAttribute =+ await subject.attribute('aria-errormessage');+ const errorMessageIds = (errorMessageAttribute ?? '')+ .split(/\s+/)+ .filter(Boolean);+ if (errorMessageIds.length > 1) {+ throw new Error(+ `aria-errormessage accepts exactly one id, but this control declares ${errorMessageIds.map(id => `"${id}"`).join(', ')}`,+ );+ }+ const relatedText = [+ ...(await subject.idReferences('aria-errormessage')),+ ...(await subject.idReferences('aria-describedby')),+ ];+ if (+ !relatedText.some(text => text != null && sameWords(text, expected))+ ) {+ throw new Error(+ `the binding identifies the error as "${expected}", but no aria-errormessage or aria-describedby target contains that text`,+ );+ }+ },+ },+ {+ id: 'text-input.error.related-text-visible',+ outcome:+ 'The textual error connected to an invalid control is visibly rendered while the error applies.',+ sources: [WCAG_3_3_1, WAI_ARIA_ERROR_MESSAGE],+ covers: ['3.3.1-error-identification', '1.3.1-info-and-relationships'],+ appliesWhen: {+ condition: 'this invalid state supplies textual error feedback',+ test: facts => facts.invalid && facts.errorMessage != null,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const expected = facts.errorMessage;+ if (expected == null) {+ throw new Error(+ 'error visibility expectation ran without expected error text',+ );+ }+ const visibleRelatedText = [+ ...(await subject.visibleIdReferences('aria-errormessage')),+ ...(await subject.visibleIdReferences('aria-describedby')),+ ];+ if (+ !visibleRelatedText.some(+ text => text != null && sameWords(text, expected),+ )+ ) {+ throw new Error(+ `the binding identifies the error as "${expected}", but no visibly rendered aria-errormessage or aria-describedby target contains that text`,+ );+ }+ },+ },+ {+ id: 'text-input.editing.keyboard-round-trip',+ outcome:+ 'A keyboard user can add text, clear it, and restore the starting value in an editable control.',+ sources: [WCAG_2_1_1],+ covers: ['2.1.1-keyboard'],+ appliesWhen: {+ condition: 'this state is editable and focusable',+ test: facts => facts.editable && facts.focusable,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject}) => {+ await subject.focus();+ if (!(await subject.isFocused())) {+ throw new Error(+ 'the text control did not take focus, so keyboard editing cannot reach it',+ );+ }+ const initial = await subject.textValue();+ if (initial == null) {+ throw new Error(+ 'the role-bearing subject exposes no editable text value',+ );+ }+ await harness.typeText(subject, 'x');+ const changed = await subject.textValue();+ if (+ changed == null ||+ changed === initial ||+ !changed.includes('x')+ ) {+ throw new Error(+ `typing "x" left the value ${JSON.stringify(changed)} instead of adding the typed text`,+ );+ }+ await harness.clearText(subject);+ const cleared = await subject.textValue();+ if (cleared !== '') {+ throw new Error(+ `clearing the text control left the value ${JSON.stringify(cleared)} instead of an empty value`,+ );+ }+ if (initial !== '') {+ await harness.typeText(subject, initial);+ const restored = await subject.textValue();+ if (restored !== initial) {+ throw new Error(+ `typing the starting value back left ${JSON.stringify(restored)} instead of ${JSON.stringify(initial)}`,+ );+ }+ }+ },+ },+ {+ id: 'text-input.focus.reachable-and-escapable',+ outcome:+ 'Tab reaches a focusable text control and Tab again leaves it, so a keyboard user can edit and continue.',+ sources: [WCAG_2_1_1, WCAG_2_1_2],+ covers: ['2.1.1-keyboard', '2.1.2-no-keyboard-trap'],+ appliesWhen: {+ condition: 'this state is meant to be in the tab sequence',+ test: facts => facts.focusable,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject}) => {+ await harness.resetFocus();+ let reached = false;+ for (let step = 0; step < TAB_BUDGET && !reached; step += 1) {+ await harness.press('Tab');+ reached = await subject.isFocused();+ }+ if (!reached) {+ throw new Error(+ `${TAB_BUDGET} presses of Tab from the start of the document never reached the text control`,+ );+ }+ await harness.press('Tab');+ if (await subject.isFocused()) {+ throw new Error(+ 'Tab did not move focus off the text control, so a keyboard user is trapped in it',+ );+ }+ },+ },+ {+ id: 'text-input.editing.disabled-reason-inert',+ outcome:+ 'A disabled text control kept focusable for its reason still blocks keyboard editing.',+ sources: [INPUT_FIELDS_FR4],+ covers: ['2.1.1-keyboard'],+ appliesWhen: {+ condition: 'this state is disabled and kept in the tab sequence',+ test: facts => facts.disabled && facts.focusable,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject}) => {+ await assertKeyboardEditsBlocked(harness, subject);+ },+ },+ {+ id: 'text-input.editing.inoperable',+ outcome:+ 'A focusable read-only text control does not accept keyboard edits.',+ sources: [AST_021_PRESERVE_BEHAVIOR],+ covers: ['2.1.1-keyboard'],+ appliesWhen: {+ condition: 'this state is read-only, focusable, and not disabled',+ test: facts => facts.readOnly && facts.focusable && !facts.disabled,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'advisory',+ advisoryBecause:+ 'AST-021 requires migrations to preserve existing behavior, but no current text-input component record makes one universal read-only inertness rule authoritative for every future binding.',+ run: async ({harness, subject}) => {+ await assertKeyboardEditsBlocked(harness, subject);+ },+ },+ ],+ exemptions: {+ '1.1.1-non-text-content': {+ owner: 'the binding component',+ verifiedBy:+ "the component's own icon and spinner tests plus the repository axe audit, `pnpm a11y:audit`",+ reason:+ 'Decorative and informative graphics are composed around the native text control, not exposed by the control node this pattern observes.',+ },+ '1.3.1-info-and-relationships': {+ owner: 'the binding component and composing page',+ verifiedBy:+ 'the description relationship expectation here plus component DOM-order tests and page-level structural review',+ reason:+ 'This contract proves the text-control relationships it can read. Broader field structure and surrounding page relationships remain with their composition owners.',+ coversRemainderOnly: true,+ },+ '1.3.2-meaningful-sequence': {+ owner: 'the binding component and composing page',+ verifiedBy: 'component DOM-order tests and page-level review',+ reason:+ 'Reading order includes labels, instructions, status content, and surrounding page content outside one native control node.',+ },+ '1.3.5-identify-input-purpose': {+ owner: 'the binding component and caller content',+ verifiedBy:+ 'TextInput and TextArea autocomplete passthrough tests plus form-level review that fields collecting information about the user receive the correct standard token',+ reason:+ 'The components forward the native autocomplete value, but only the caller knows whether a field collects a listed category of information about the user and which purpose applies.',+ },+ '1.4.1-use-of-color': {+ owner: 'the binding component and theme',+ verifiedBy: 'component status tests and the repository visual gate',+ reason:+ 'Whether status is distinguishable without color is a rendered composition and pixel outcome, not a native control-node semantic.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'the binding component and theme',+ verifiedBy:+ 'the repository axe audit over component stories plus the visual gate',+ reason:+ 'Text contrast depends on resolved colors and backdrop pixels outside this semantic contract.',+ },+ '1.4.11-non-text-contrast': {+ owner: 'the binding component and theme',+ verifiedBy:+ 'the repository axe audit over component stories plus the visual gate',+ reason:+ 'Control boundaries, status icons, and focus indicators are painted surfaces outside this semantic contract.',+ },+ '2.1.1-keyboard': {+ owner: 'the binding component',+ verifiedBy:+ 'the native keyboard-editing expectation here plus component tests for composed buttons and shortcuts',+ reason:+ 'This contract proves text entry and deletion on the role-bearing control. Clear buttons, Enter callbacks, and other composed functions remain with their own component or pattern tests.',+ coversRemainderOnly: true,+ },+ '2.4.2-page-titled': {+ owner: 'the page',+ verifiedBy: 'page-level review and the hosting application',+ reason: 'An isolated text control cannot supply the document title.',+ },+ '2.4.3-focus-order': {+ owner: 'the composing page',+ verifiedBy: 'page-level keyboard review',+ reason:+ 'Sequential order is a property of all focus stops a page composes, not one text control.',+ },+ '2.4.4-link-purpose': {+ owner: 'caller content',+ verifiedBy: 'review of any link composed near the field',+ reason: 'The native text-input pattern has no link part.',+ },+ '2.4.6-headings-and-labels': {+ owner: 'caller content and component review',+ verifiedBy:+ 'content review of whether each supplied label describes the field purpose',+ reason:+ 'Whether label wording describes its purpose is a content judgement no runtime check can settle.',+ },+ '2.4.7-focus-visible': {+ owner:+ 'the interaction-modality architecture record and binding component',+ verifiedBy:+ "the component's focus-ring styling tests and the repository visual gate",+ reason:+ 'A visible focus indicator is a paint result owned by the rendered component and theme.',+ },+ '2.4.11-focus-not-obscured': {+ owner: 'the composing page',+ verifiedBy: 'page-level and overlay review',+ reason:+ 'Whether author-created content obscures a focused field depends on the page composition.',+ },+ '2.5.2-pointer-cancellation': {+ owner: 'the binding component and browser',+ verifiedBy:+ 'component pointer tests for component-owned actions and native-browser behavior for caret placement',+ reason:+ 'The text control itself has no component-owned single-pointer action; clear and tooltip buttons are separate bound patterns.',+ },+ '2.5.8-target-size': {+ owner: 'the binding component and composing page',+ verifiedBy:+ 'real-browser geometry measurement plus review of applicable WCAG exceptions',+ reason:+ 'Target size and spacing depend on rendered geometry and neighbouring targets outside the control node.',+ },+ '3.1.1-language-of-page': {+ owner: 'the page',+ verifiedBy: 'page-level review and the hosting application',+ reason: 'An isolated text control cannot supply the document language.',+ },+ '3.2.2-on-input': {+ owner: 'the caller',+ verifiedBy:+ 'integration review of context changes performed by consumer callbacks',+ reason:+ 'TextInput and TextArea report value changes; the caller decides whether those changes navigate or replace surrounding content.',+ },+ '3.2.4-consistent-identification': {+ owner: 'the composing application and caller content',+ verifiedBy:+ 'cross-page review that equivalent fields use consistent names and identification',+ reason:+ 'One isolated binding cannot compare equivalent functions across pages or workflows.',+ },+ '3.3.1-error-identification': {+ owner: 'the binding component and caller',+ verifiedBy:+ 'the invalid-state error-text expectation here plus validation logic and content review in the binding application',+ reason:+ 'This contract proves that a bound invalid state carries attached error text. The caller still owns detecting the right error and supplying useful wording.',+ coversRemainderOnly: true,+ },+ '3.3.2-labels-or-instructions': {+ owner: 'the binding component and caller content',+ verifiedBy:+ 'the accessibility-tree naming expectation here plus component and content review for visible persistence and needed instructions',+ reason:+ 'This contract proves that a name exists. Whether the label stays visibly present and whether additional instructions are needed remain presentation and content outcomes.',+ coversRemainderOnly: true,+ },+ '4.1.2-name-role-value': {+ owner: 'the binding component and browser for specialized states',+ verifiedBy:+ 'the role, name, description, value, multiline, disabled, read-only, required, and invalid accessibility-tree expectations in this contract plus component-local tests for states outside the shared model',+ reason:+ 'The shared native textbox states are encoded here. Protected password-value representation, busy semantics not adopted by current authority, and component-specific composed parts remain with their narrower owners.',+ coversRemainderOnly: true,+ },+ '4.1.3-status-messages': {+ owner:+ 'the binding component and the assistive-technology verification record',+ verifiedBy:+ "the component's live-region regression tests plus real-AT evidence under `docs/specs/AST-009/spec.md` whenever a change claims what is announced",+ reason:+ 'This pattern can verify static descriptions and state exposure, not speech, timing, repetition, or announcement order.',+ },+ 'apg-interaction': {+ owner: 'a future current pattern owner, if Astryx adopts one',+ verifiedBy:+ 'review against current Astryx records before adding any APG-derived mechanic',+ reason:+ 'WAI-ARIA APG publishes no generic text-input widget pattern, and current Astryx authority adopts no substitute APG interaction model for native text controls.',+ },+ 'forced-colors': {+ owner: 'the binding component and theme',+ verifiedBy:+ "the component's compiled-CSS tests plus manual Windows High Contrast review",+ reason:+ 'Forced-colors behavior is a paint result outside this semantic contract.',+ },+ 'reduced-motion': {+ owner: 'the binding component and theme',+ verifiedBy:+ 'review of transition declarations and repository reduced-motion checks',+ reason:+ 'Motion is a rendered result over time, and the native editing contract introduces none.',+ },+ 'at-facing-strings': {+ owner: 'the binding component',+ verifiedBy:+ 'the repository i18n catalog check and source review of assistive-technology-facing text',+ reason:+ 'Translation is a source-level concern that the rendered semantic result cannot identify.',+ },+ },+ });diff --git a/packages/core/src/TextInput/__tests__/TextInput.a11y.chromium.spec.ts b/packages/core/src/TextInput/__tests__/TextInput.a11y.chromium.spec.tsnew file mode 100644index 0000000000..a30dc04e74--- /dev/null+++ b/packages/core/src/TextInput/__tests__/TextInput.a11y.chromium.spec.ts@@ -0,0 +1,206 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TextInput.a11y.chromium.spec.ts+ * @input Uses the shared text-input contract, Chromium harness, checked-in+ * TextInputA11y stories, state inventory, and exact known failures+ * @output Real-browser and accessibility-tree evidence for TextInput and TextArea+ * @position Browser lane required by AST-013; it makes no real-AT claim.+ */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ TEXT_INPUT_PATTERN,+ blockingResults,+ checkAccessibilitySpec,+ formatFailures,+ formatReport,+ neverExercised,+ spokenWords,+ 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 {TEXT_INPUT_KNOWN_FAILURES} from './TextInput.a11y.known-failures';+import {+ TEXT_INPUT_BINDING_STATES,+ type TextInputBindingRow,+} from './TextInput.a11y.states';++const SUBJECT_SELECTOR = '[data-a11y-text-input-subject]';+let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++function storyUrl(storyId: string): string {+ return `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story`;+}++function subjectFor(page: Page): Locator {+ return page.locator('#storybook-root').locator(SUBJECT_SELECTOR);+}++async function mountState(+ page: Page,+ state: TextInputBindingRow,+): Promise<void> {+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});+ await holdMotionStill(page);+ await subjectFor(page).waitFor({state: 'attached'});+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: TextInputBindingRow,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: TEXT_INPUT_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: TEXT_INPUT_KNOWN_FAILURES,+ mount: async () => {+ await mountState(page, state);+ return createChromiumHarness({page, subject: subjectFor(page), cdp});+ },+ });+}++const FIELD_MARKERS = ['required', 'optional'];++function sameVisibleWords(rendered: string, claimed: string): boolean {+ const words = [...spokenWords(rendered)];+ const last = words[words.length - 1];+ if (last != null && FIELD_MARKERS.includes(last)) {+ words.pop();+ }+ const expected = spokenWords(claimed);+ return (+ words.length === expected.length &&+ words.every((word, index) => word === expected[index])+ );+}++test('the state inventory describes each visible label', async ({page}) => {+ test.setTimeout(4 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const wrong: string[] = [];+ for (const state of TEXT_INPUT_BINDING_STATES) {+ await mountState(page, state);+ const subject = await createChromiumHarness({+ page,+ subject: subjectFor(page),+ cdp,+ }).subject();+ const rendered = await subject.visibleLabelText();+ const matches =+ state.visibleLabel == null+ ? rendered == null+ : rendered != null && sameVisibleWords(rendered, state.visibleLabel);+ if (!matches) {+ wrong.push(+ `${state.id}: inventory says ${JSON.stringify(state.visibleLabel)}, page renders ${JSON.stringify(rendered)}`,+ );+ }+ }+ expect(wrong).toEqual([]);+});++test('every state declaration matches the browser accessibility node', async ({+ page,+}) => {+ test.setTimeout(5 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const wrong: string[] = [];+ for (const state of TEXT_INPUT_BINDING_STATES) {+ await mountState(page, state);+ const subject = await createChromiumHarness({+ page,+ subject: subjectFor(page),+ cdp,+ }).subject();+ const computed = await subject.computed();+ const observed = {+ role: state.facts.role == null ? null : computed.role,+ value: state.facts.value == null ? null : computed.value,+ multiline: computed.multiline,+ disabled: computed.disabled,+ readOnly: state.facts.disabled ? false : computed.readOnly,+ required: computed.required,+ invalid: computed.invalid,+ description:+ computed.description.trim() === '' ? null : computed.description,+ } as const;+ const expected = {+ role: state.facts.role,+ value: state.facts.value,+ multiline: state.facts.multiline,+ disabled: state.facts.disabled,+ readOnly: state.facts.readOnly,+ required: state.facts.required,+ invalid: state.facts.invalid,+ description: state.facts.description,+ } as const;+ for (const fact of Object.keys(expected) as (keyof typeof expected)[]) {+ if (observed[fact] !== expected[fact]) {+ wrong.push(+ `${state.id}: declares ${fact}=${String(expected[fact])}, browser exposes ${String(observed[fact])}`,+ );+ }+ }+ }+ expect(wrong).toEqual([]);+});++test('every expectation is exercised and every known failure matches once', async ({+ page,+}) => {+ test.setTimeout(8 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of TEXT_INPUT_BINDING_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(neverExercised(results)).toEqual([]);+ expect(unmatchedKnownFailures(TEXT_INPUT_KNOWN_FAILURES, results)).toEqual(+ [],+ );+});++for (const state of TEXT_INPUT_BINDING_STATES) {+ test(`${state.binding} [${state.id}] — ${state.summary}`, async ({page}) => {+ test.setTimeout(3 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(TEXT_INPUT_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/TextInput/__tests__/TextInput.a11y.known-failures.ts b/packages/core/src/TextInput/__tests__/TextInput.a11y.known-failures.tsnew file mode 100644index 0000000000..62a69cf16d--- /dev/null+++ b/packages/core/src/TextInput/__tests__/TextInput.a11y.known-failures.ts@@ -0,0 +1,40 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TextInput.a11y.known-failures.ts+ * @input Uses KnownFailure from @astryxdesign/a11y-spec+ * @output TEXT_INPUT_KNOWN_FAILURES — exact public-safe historical failures+ * @position Runnable migration debt under AST-021 FR8–FR10.+ */++import type {KnownFailure} from '@astryxdesign/a11y-spec';++const ERROR_WITHOUT_TEXT =+ 'the binding declares this text control invalid but supplies no textual error description';++export const TEXT_INPUT_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [+ {+ expectation: 'text-input.error.identified-in-text',+ binding: 'TextInput',+ state: 'input-error-without-message',+ evidenceLayer: 'dom',+ failureEquals: ERROR_WITHOUT_TEXT,+ standardsReference: 'WCAG 2.2 3.3.1 Error Identification (Level A)',+ userImpact:+ 'A person receives an invalid field state with only visual styling and an icon; no text identifies what is wrong.',+ reason:+ 'TextInput permits an error status without a message. This migration records the existing failure without changing component behavior.',+ },+ {+ expectation: 'text-input.error.identified-in-text',+ binding: 'TextArea',+ state: 'textarea-error-without-message',+ evidenceLayer: 'dom',+ failureEquals: ERROR_WITHOUT_TEXT,+ standardsReference: 'WCAG 2.2 3.3.1 Error Identification (Level A)',+ userImpact:+ 'A person receives an invalid field state with only visual styling and an icon; no text identifies what is wrong.',+ reason:+ 'TextArea permits an error status without a message. This migration records the existing failure without changing component behavior.',+ },+];diff --git a/packages/core/src/TextInput/__tests__/TextInput.a11y.renders.tsx b/packages/core/src/TextInput/__tests__/TextInput.a11y.renders.tsxnew file mode 100644index 0000000000..fece29ebb8--- /dev/null+++ b/packages/core/src/TextInput/__tests__/TextInput.a11y.renders.tsx@@ -0,0 +1,202 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file TextInput.a11y.renders.tsx+ * @input Uses TextInput, TextArea, InputGroup, and the binding state-id union+ * @output TEXT_INPUT_STATE_RENDERS — one real component rendering per state row+ * @position Shared fixture layer for jsdom bindings and checked-in stories.+ */++import {useState, type ReactElement} from 'react';+import {InputGroup, InputGroupText} from '../../InputGroup';+import {TextArea, type TextAreaProps} from '../../TextArea';+import {TextInput, type TextInputProps} from '../TextInput';+import type {TextInputStateId} from './TextInput.a11y.states';++function ControlledTextInput({+ initial = '',+ ...props+}: Omit<TextInputProps, 'value' | 'onChange'> & {initial?: string}) {+ const [value, setValue] = useState(initial);+ return (+ <TextInput+ {...props}+ data-a11y-text-input-subject+ value={value}+ onChange={setValue}+ />+ );+}++function ControlledTextArea({+ initial = '',+ ...props+}: Omit<TextAreaProps, 'value' | 'onChange'> & {initial?: string}) {+ const [value, setValue] = useState(initial);+ return (+ <TextArea+ {...props}+ data-a11y-text-input-subject+ value={value}+ onChange={setValue}+ />+ );+}++export type TextInputStateRender = () => ReactElement;++export const TEXT_INPUT_STATE_RENDERS: Record<+ TextInputStateId,+ TextInputStateRender+> = {+ 'input-empty-placeholder': () => (+ <ControlledTextInput label="Name" placeholder="Enter your name" />+ ),+ 'input-valued': () => (+ <ControlledTextInput label="Name" initial="Ada Lovelace" />+ ),+ 'input-hidden-label': () => (+ <ControlledTextInput label="Search" isLabelHidden placeholder="Search" />+ ),+ 'input-described': () => (+ <ControlledTextInput+ label="Display name"+ description="Use the name shown on your profile."+ />+ ),+ 'input-optional': () => <ControlledTextInput label="Nickname" isOptional />,+ 'input-required': () => <ControlledTextInput label="Username" isRequired />,+ 'input-error': () => (+ <ControlledTextInput+ label="Email"+ initial="invalid@"+ status={{type: 'error', message: 'Enter a valid email address.'}}+ />+ ),+ 'input-error-without-message': () => (+ <ControlledTextInput+ label="Email"+ initial="invalid@"+ status={{type: 'error'}}+ />+ ),+ 'input-warning-detached': () => (+ <ControlledTextInput+ label="Username"+ initial="user123"+ status={{type: 'warning', message: 'This username may be taken.'}}+ statusVariant="detached"+ />+ ),+ 'input-success-tooltip': () => (+ <ControlledTextInput+ label="Username"+ initial="validuser"+ status={{type: 'success', message: 'Username is available.'}}+ statusVariant="tooltip"+ />+ ),+ 'input-disabled': () => (+ <ControlledTextInput label="Owner" initial="Locked" isDisabled />+ ),+ 'input-disabled-with-message': () => (+ <ControlledTextInput+ label="Owner"+ initial="[email protected]"+ isDisabled+ disabledMessage="You need the Editor role to change this."+ />+ ),+ 'input-read-only': () => (+ <ControlledTextInput+ label="Account number"+ initial="ACCT-4417-9920"+ isReadOnly+ />+ ),+ 'input-password': () => (+ <ControlledTextInput label="Password" type="password" />+ ),+ 'input-group-described': () => (+ <InputGroup label="Price" description="Enter the amount in USD.">+ <InputGroupText>$</InputGroupText>+ <ControlledTextInput label="Amount" isLabelHidden />+ </InputGroup>+ ),++ 'textarea-empty-placeholder': () => (+ <ControlledTextArea label="Description" placeholder="Enter a description" />+ ),+ 'textarea-valued': () => (+ <ControlledTextArea label="Notes" initial="Existing notes" />+ ),+ 'textarea-hidden-label': () => (+ <ControlledTextArea label="Comments" isLabelHidden placeholder="Comment" />+ ),+ 'textarea-described': () => (+ <ControlledTextArea+ label="Description"+ description="Summarize the change."+ />+ ),+ 'textarea-optional': () => (+ <ControlledTextArea label="Additional notes" isOptional />+ ),+ 'textarea-required': () => <ControlledTextArea label="Feedback" isRequired />,+ 'textarea-error': () => (+ <ControlledTextArea+ label="Description"+ initial="Too short"+ status={{+ type: 'error',+ message: 'Description must be at least 50 characters.',+ }}+ />+ ),+ 'textarea-error-without-message': () => (+ <ControlledTextArea+ label="Description"+ initial="Invalid"+ status={{type: 'error'}}+ />+ ),+ 'textarea-warning-detached': () => (+ <ControlledTextArea+ label="Content"+ initial="Review this text"+ status={{type: 'warning', message: 'Content may need review.'}}+ statusVariant="detached"+ />+ ),+ 'textarea-success-tooltip': () => (+ <ControlledTextArea+ label="Description"+ initial="Complete description"+ status={{type: 'success', message: 'Description looks good.'}}+ statusVariant="tooltip"+ />+ ),+ 'textarea-disabled': () => (+ <ControlledTextArea label="Notes" initial="Locked notes" isDisabled />+ ),+ 'textarea-disabled-with-message': () => (+ <ControlledTextArea+ label="Notes"+ initial="Locked notes"+ isDisabled+ disabledMessage="Notes are locked after submission."+ />+ ),+ 'textarea-read-only': () => (+ <ControlledTextArea+ label="Import summary"+ initial="Generated by the importer."+ isReadOnly+ />+ ),+ 'textarea-over-limit': () => (+ <ControlledTextArea label="Summary" initial="abcdef" maxLength={5} />+ ),+};diff --git a/packages/core/src/TextInput/__tests__/TextInput.a11y.states.ts b/packages/core/src/TextInput/__tests__/TextInput.a11y.states.tsnew file mode 100644index 0000000000..c93b330025--- /dev/null+++ b/packages/core/src/TextInput/__tests__/TextInput.a11y.states.ts@@ -0,0 +1,384 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TextInput.a11y.states.ts+ * @input Uses TextInputStateFacts from @astryxdesign/a11y-spec+ * @output TEXT_INPUT_BINDING_STATES — the AST-021 state inventory for the native+ * role-bearing controls rendered by TextInput and TextArea — plus explicit+ * exclusions for adjacent parts and states owned elsewhere+ * @position Data-only binding inventory. JSX lives in TextInput.a11y.renders.tsx.+ */++import type {TextInputStateFacts} from '@astryxdesign/a11y-spec';++export type TextInputBinding = 'TextInput' | 'TextArea';+export type TextInputBindingRow = (typeof TEXT_INPUT_BINDING_STATES)[number];+export type TextInputStateId = (typeof TEXT_INPUT_BINDING_STATES)[number]['id'];++export interface TextInputBindingState {+ readonly id: string;+ readonly binding: TextInputBinding;+ readonly summary: string;+ readonly facts: TextInputStateFacts;+ readonly visibleLabel: string | null;+ readonly storyId: string;+}++const DEFAULT_FACTS: TextInputStateFacts = {+ role: 'textbox',+ multiline: false,+ value: '',+ editable: true,+ focusable: true,+ disabled: false,+ readOnly: false,+ required: false,+ invalid: false,+ description: null,+ errorMessage: null,+};++function facts(+ overrides: Partial<TextInputStateFacts> = {},+): TextInputStateFacts {+ return {...DEFAULT_FACTS, ...overrides};+}++const areaFacts = (+ overrides: Partial<TextInputStateFacts> = {},+): TextInputStateFacts => facts({multiline: true, ...overrides});++export const TEXT_INPUT_BINDING_EXCLUSIONS = [+ {+ owner: 'TextInput type=email',+ reason:+ 'The native email control has the same textbox role, naming, state, focus, and text-editing contract as the bound single-line state; email parsing and browser validation remain component-local.',+ },+ {+ owner: 'TextInput type=password',+ reason:+ 'The password state is bound for persistent naming, state, focus, and editing. HTML-AAM defines no corresponding ARIA role and its protected value mapping is platform-specific, so role, multiline, and exact-value expectations are inapplicable.',+ },+ {+ owner: 'TextInput and TextArea loading',+ reason:+ 'Loading changes aria-busy and spinner composition, but no current Astryx record adopts aria-busy as a reusable native text-input requirement. Existing busy, callback, and optimistic-value tests remain local.',+ },+ {+ owner: 'TextInput clear button and status tooltip buttons',+ reason:+ 'Those are separate role-bearing button parts. The Button pattern and component-local composition tests own them; this binding targets only the native textbox.',+ },+ {+ owner: 'TextArea character-count announcements',+ reason:+ 'Static counter association is covered through the textbox description. Speech, timing, and repetition remain under AST-009 and TextArea local tests.',+ },+ {+ owner: 'FileInput',+ reason:+ 'FileInput uses the native file-upload model and is intentionally outside the text-input pattern.',+ },+ {+ owner: 'ChatComposerInput combobox mode',+ reason:+ 'When trigger-menu behavior is present the role-bearing editor adopts combobox semantics and belongs to the Combobox pattern.',+ },+ {+ owner: 'CodeEditor',+ reason:+ 'No current component, family, or system record adopts the Lab CodeEditor into the native text-input model.',+ },+] as const;++export const TEXT_INPUT_BINDING_STATES = [+ {+ id: 'input-empty-placeholder',+ binding: 'TextInput',+ summary:+ 'an empty editable single-line control with a visible label and placeholder',+ facts: facts(),+ visibleLabel: 'Name',+ storyId: 'a11y-text-input-pattern--input-empty-placeholder',+ },+ {+ id: 'input-valued',+ binding: 'TextInput',+ summary: 'an editable single-line control with an existing value',+ facts: facts({value: 'Ada Lovelace'}),+ visibleLabel: 'Name',+ storyId: 'a11y-text-input-pattern--input-valued',+ },+ {+ id: 'input-hidden-label',+ binding: 'TextInput',+ summary: 'a single-line control named by a visually hidden label',+ facts: facts(),+ visibleLabel: null,+ storyId: 'a11y-text-input-pattern--input-hidden-label',+ },+ {+ id: 'input-described',+ binding: 'TextInput',+ summary: 'a single-line control with helper text',+ facts: facts({description: 'Use the name shown on your profile.'}),+ visibleLabel: 'Display name',+ storyId: 'a11y-text-input-pattern--input-described',+ },+ {+ id: 'input-optional',+ binding: 'TextInput',+ summary: 'an optional single-line control',+ facts: facts(),+ visibleLabel: 'Nickname',+ storyId: 'a11y-text-input-pattern--input-optional',+ },+ {+ id: 'input-required',+ binding: 'TextInput',+ summary: 'a required single-line control',+ facts: facts({required: true}),+ visibleLabel: 'Username',+ storyId: 'a11y-text-input-pattern--input-required',+ },+ {+ id: 'input-error',+ binding: 'TextInput',+ summary: 'an invalid single-line control with textual error feedback',+ facts: facts({+ value: 'invalid@',+ invalid: true,+ description: 'Enter a valid email address.',+ errorMessage: 'Enter a valid email address.',+ }),+ visibleLabel: 'Email',+ storyId: 'a11y-text-input-pattern--input-error',+ },+ {+ id: 'input-error-without-message',+ binding: 'TextInput',+ summary: 'an invalid single-line control with no textual error feedback',+ facts: facts({value: 'invalid@', invalid: true}),+ visibleLabel: 'Email',+ storyId: 'a11y-text-input-pattern--input-error-without-message',+ },+ {+ id: 'input-warning-detached',+ binding: 'TextInput',+ summary: 'a valid single-line control with detached warning text',+ facts: facts({+ value: 'user123',+ description: 'This username may be taken.',+ }),+ visibleLabel: 'Username',+ storyId: 'a11y-text-input-pattern--input-warning-detached',+ },+ {+ id: 'input-success-tooltip',+ binding: 'TextInput',+ summary: 'a valid single-line control described by tooltip status text',+ facts: facts({+ value: 'validuser',+ description: 'Username is available.',+ }),+ visibleLabel: 'Username',+ storyId: 'a11y-text-input-pattern--input-success-tooltip',+ },+ {+ id: 'input-disabled',+ binding: 'TextInput',+ summary: 'a natively disabled single-line control outside the tab sequence',+ facts: facts({+ value: 'Locked',+ editable: false,+ focusable: false,+ disabled: true,+ }),+ visibleLabel: 'Owner',+ storyId: 'a11y-text-input-pattern--input-disabled',+ },+ {+ id: 'input-disabled-with-message',+ binding: 'TextInput',+ summary: 'an unavailable single-line control kept focusable for its reason',+ facts: facts({+ value: '[email protected]',+ editable: false,+ disabled: true,+ description: 'You need the Editor role to change this.',+ }),+ visibleLabel: 'Owner',+ storyId: 'a11y-text-input-pattern--input-disabled-with-message',+ },+ {+ id: 'input-read-only',+ binding: 'TextInput',+ summary: 'a read-only single-line control that stays focusable',+ facts: facts({+ value: 'ACCT-4417-9920',+ editable: false,+ readOnly: true,+ }),+ visibleLabel: 'Account number',+ storyId: 'a11y-text-input-pattern--input-read-only',+ },+ {+ id: 'input-password',+ binding: 'TextInput',+ summary: 'a password control whose protected value remains browser-owned',+ facts: facts({role: null, value: null}),+ visibleLabel: 'Password',+ storyId: 'a11y-text-input-pattern--input-password',+ },+ {+ id: 'input-group-described',+ binding: 'TextInput',+ summary: 'a grouped single-line control named and described by InputGroup',+ facts: facts({description: 'Enter the amount in USD.'}),+ visibleLabel: 'Price',+ storyId: 'a11y-text-input-pattern--input-group-described',+ },+ {+ id: 'textarea-empty-placeholder',+ binding: 'TextArea',+ summary: 'an empty editable multi-line control with a placeholder',+ facts: areaFacts(),+ visibleLabel: 'Description',+ storyId: 'a11y-text-input-pattern--textarea-empty-placeholder',+ },+ {+ id: 'textarea-valued',+ binding: 'TextArea',+ summary: 'an editable multi-line control with an existing value',+ facts: areaFacts({value: 'Existing notes'}),+ visibleLabel: 'Notes',+ storyId: 'a11y-text-input-pattern--textarea-valued',+ },+ {+ id: 'textarea-hidden-label',+ binding: 'TextArea',+ summary: 'a multi-line control named by a visually hidden label',+ facts: areaFacts(),+ visibleLabel: null,+ storyId: 'a11y-text-input-pattern--textarea-hidden-label',+ },+ {+ id: 'textarea-described',+ binding: 'TextArea',+ summary: 'a multi-line control with helper text',+ facts: areaFacts({description: 'Summarize the change.'}),+ visibleLabel: 'Description',+ storyId: 'a11y-text-input-pattern--textarea-described',+ },+ {+ id: 'textarea-optional',+ binding: 'TextArea',+ summary: 'an optional multi-line control',+ facts: areaFacts(),+ visibleLabel: 'Additional notes',+ storyId: 'a11y-text-input-pattern--textarea-optional',+ },+ {+ id: 'textarea-required',+ binding: 'TextArea',+ summary: 'a required multi-line control',+ facts: areaFacts({required: true}),+ visibleLabel: 'Feedback',+ storyId: 'a11y-text-input-pattern--textarea-required',+ },+ {+ id: 'textarea-error',+ binding: 'TextArea',+ summary: 'an invalid multi-line control with textual error feedback',+ facts: areaFacts({+ value: 'Too short',+ invalid: true,+ description: 'Description must be at least 50 characters.',+ errorMessage: 'Description must be at least 50 characters.',+ }),+ visibleLabel: 'Description',+ storyId: 'a11y-text-input-pattern--textarea-error',+ },+ {+ id: 'textarea-error-without-message',+ binding: 'TextArea',+ summary: 'an invalid multi-line control with no textual error feedback',+ facts: areaFacts({value: 'Invalid', invalid: true}),+ visibleLabel: 'Description',+ storyId: 'a11y-text-input-pattern--textarea-error-without-message',+ },+ {+ id: 'textarea-warning-detached',+ binding: 'TextArea',+ summary: 'a valid multi-line control with detached warning text',+ facts: areaFacts({+ value: 'Review this text',+ description: 'Content may need review.',+ }),+ visibleLabel: 'Content',+ storyId: 'a11y-text-input-pattern--textarea-warning-detached',+ },+ {+ id: 'textarea-success-tooltip',+ binding: 'TextArea',+ summary: 'a valid multi-line control described by tooltip status text',+ facts: areaFacts({+ value: 'Complete description',+ description: 'Description looks good.',+ }),+ visibleLabel: 'Description',+ storyId: 'a11y-text-input-pattern--textarea-success-tooltip',+ },+ {+ id: 'textarea-disabled',+ binding: 'TextArea',+ summary: 'a natively disabled multi-line control outside the tab sequence',+ facts: areaFacts({+ value: 'Locked notes',+ editable: false,+ focusable: false,+ disabled: true,+ }),+ visibleLabel: 'Notes',+ storyId: 'a11y-text-input-pattern--textarea-disabled',+ },+ {+ id: 'textarea-disabled-with-message',+ binding: 'TextArea',+ summary: 'an unavailable multi-line control kept focusable for its reason',+ facts: areaFacts({+ value: 'Locked notes',+ editable: false,+ disabled: true,+ description: 'Notes are locked after submission.',+ }),+ visibleLabel: 'Notes',+ storyId: 'a11y-text-input-pattern--textarea-disabled-with-message',+ },+ {+ id: 'textarea-read-only',+ binding: 'TextArea',+ summary: 'a read-only multi-line control that stays focusable',+ facts: areaFacts({+ value: 'Generated by the importer.',+ editable: false,+ readOnly: true,+ }),+ visibleLabel: 'Import summary',+ storyId: 'a11y-text-input-pattern--textarea-read-only',+ },+ {+ id: 'textarea-over-limit',+ binding: 'TextArea',+ summary:+ 'a multi-line control invalid because its character count is over the limit',+ facts: areaFacts({+ value: 'abcdef',+ invalid: true,+ description: '6/5',+ errorMessage: '6/5',+ }),+ visibleLabel: 'Summary',+ storyId: 'a11y-text-input-pattern--textarea-over-limit',+ },+] as const satisfies ReadonlyArray<TextInputBindingState>;diff --git a/packages/core/src/TextInput/__tests__/TextInput.a11y.test.tsx b/packages/core/src/TextInput/__tests__/TextInput.a11y.test.tsxnew file mode 100644index 0000000000..a29ebd2290--- /dev/null+++ b/packages/core/src/TextInput/__tests__/TextInput.a11y.test.tsx@@ -0,0 +1,130 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file TextInput.a11y.test.tsx+ * @input Uses the shared text-input contract and real TextInput/TextArea renders+ * @output DOM-layer binding evidence with exact known failures+ * @position Fast component-facing migration lane; browser-owned outcomes are unrun.+ */++import {describe, expect, it} from 'vitest';+import {cleanup, render} from '@testing-library/react';+import {+ TEXT_INPUT_PATTERN,+ checkAccessibilitySpec,+ createJsdomHarness,+ expectAccessibilitySpec,+ summarize,+ unmatchedKnownFailures,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {TEXT_INPUT_KNOWN_FAILURES} from './TextInput.a11y.known-failures';+import {TEXT_INPUT_STATE_RENDERS} from './TextInput.a11y.renders';+import {+ TEXT_INPUT_BINDING_EXCLUSIONS,+ TEXT_INPUT_BINDING_STATES,+ type TextInputBindingRow,+} from './TextInput.a11y.states';++const SUBJECT_SELECTOR = '[data-a11y-text-input-subject]';++function subjectFor(): HTMLInputElement | HTMLTextAreaElement {+ const subject = document.querySelector(SUBJECT_SELECTOR);+ if (!(+ subject instanceof HTMLInputElement ||+ subject instanceof HTMLTextAreaElement+ )) {+ throw new Error('binding did not render one native text-control subject');+ }+ return subject;+}++async function expectState(state: TextInputBindingRow): Promise<void> {+ await expectAccessibilitySpec({+ spec: TEXT_INPUT_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: TEXT_INPUT_KNOWN_FAILURES,+ render: () => {+ render(TEXT_INPUT_STATE_RENDERS[state.id]());+ },+ subject: subjectFor,+ cleanup,+ });+}++async function checkState(state: TextInputBindingRow): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: TEXT_INPUT_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: TEXT_INPUT_KNOWN_FAILURES,+ mount: async () => {+ render(TEXT_INPUT_STATE_RENDERS[state.id]());+ return createJsdomHarness({subject: subjectFor()});+ },+ unmount: cleanup,+ });+}++describe('the shared text-input pattern, jsdom lane', () => {+ it.each(+ TEXT_INPUT_BINDING_STATES.map(+ state =>+ [`${state.binding} [${state.id}]`, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectState(state);+ });++ it('runs DOM expectations and reports higher layers as unrun', async () => {+ const results: BindingResult[] = [];+ for (const state of TEXT_INPUT_BINDING_STATES) {+ results.push(await checkState(state));+ }+ const report = summarize(TEXT_INPUT_PATTERN, results);+ expect(report.counts.pass).toBeGreaterThan(0);+ expect(report.counts.knownFailure).toBe(2);+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);+ expect(report.counts.unexpectedPass).toBe(0);+ expect(unmatchedKnownFailures(TEXT_INPUT_KNOWN_FAILURES, results)).toEqual(+ [],+ );+ });+});++describe('the text-input binding inventory', () => {+ it('names a distinct checked-in story for every state', () => {+ const ids = TEXT_INPUT_BINDING_STATES.map(state => state.storyId);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('binds both native component controls', () => {+ expect(+ [+ ...new Set(TEXT_INPUT_BINDING_STATES.map(state => state.binding)),+ ].sort(),+ ).toEqual(['TextArea', 'TextInput']);+ });++ it('renders exactly one actual native subject for every state', () => {+ for (const state of TEXT_INPUT_BINDING_STATES) {+ render(TEXT_INPUT_STATE_RENDERS[state.id]());+ expect(subjectFor(), state.id).toBeTruthy();+ expect(document.querySelectorAll(SUBJECT_SELECTOR)).toHaveLength(1);+ cleanup();+ }+ });++ it('records every adjacent exclusion with an owner and reason', () => {+ expect(TEXT_INPUT_BINDING_EXCLUSIONS.length).toBeGreaterThan(0);+ expect(+ TEXT_INPUT_BINDING_EXCLUSIONS.every(+ exclusion => exclusion.owner.length > 0 && exclusion.reason.length > 0,+ ),+ ).toBe(true);+ });+});