An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): reusable button-pattern accessibility contract, bound to five components (#6131)
Cindy Zhang5967c0764b6f
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.jsonindex 548887ab19..ecd9c0c825 100644--- a/apps/storybook/rtl-audit/verified-not-applicable.json+++ b/apps/storybook/rtl-audit/verified-not-applicable.json@@ -50,5 +50,13 @@{"component": "unknown/ThreeD","reason": "The ThreeD documentation family renders Cartesian x/y/z data visualizations in SVG and WebGL. Its axes and pointer-drag rotation are physical data-space interactions that intentionally remain invariant across writing directions; it has no reading-order controls, inline-start/end placement, directional glyphs, or overlays to mirror."+ },+ {+ "component": "core/Button",+ "reason": "Button lays out icon, label, and end content in an inline flex row with logical gap and `paddingInline` only; its source carries no physical `left`/`right`, margin, padding, border, or inset anywhere, and the loading overlay is pinned with `insetInlineStart`/`insetInlineEnd`. Nothing is side-specific, nothing scrolls or drags, and the only positioned affordance is the disabled-reason tooltip, which sits on the block axis (above) rather than to a side. The icon slot mirrors with the flex row by construction, and the glyphs the stories use are non-directional. Verified by the audit's own detectors over every Button and IconButton story: D1 icon-mirror, D5 positional-mirror, and the decoration pass all returned N-A with zero not-RTL findings."+ },+ {+ "component": "core/IconButton",+ "reason": "IconButton is a thin wrapper that renders Button with `isIconOnly`, adding no layout, no positioning, and no directional affordance of its own, so it inherits `core/Button`'s verification above exactly. Its single icon is centred in a square control, which has no reading direction to mirror."}]diff --git a/apps/storybook/stories/ButtonA11y.stories.tsx b/apps/storybook/stories/ButtonA11y.stories.tsxnew file mode 100644index 0000000000..a7d358d4ef--- /dev/null+++ b/apps/storybook/stories/ButtonA11y.stories.tsx@@ -0,0 +1,139 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ButtonA11y.stories.tsx+ * @input Uses BUTTON_BINDING_STATES and BUTTON_PATTERN_EXCLUSIONS from the+ * shared button-pattern binding inventory+ * @output One story per state in that inventory, each counting its own+ * activations.+ * @position The reproduction path for the Chromium half of the button-pattern+ * contract (`docs/specs/AST-009/spec.md` FR30: a browser claim is checked+ * against a checked-in story, not a page a test builds and throws away).+ *+ * Every story body is `storyFor('<state id>')`. What each state IS lives in the+ * inventory beside its facts, not here — one definition, rendered identically+ * by the jsdom lane and by this story, so the two lanes cannot drift into+ * testing different things under the same name.+ *+ * The activation count is both visible text and a `data-a11y-activations`+ * attribute: a person reading the story and the test reading the DOM see the+ * same number. A button's action leaves no trace on the button, so counting the+ * handler is the only honest way to ask whether pressing it did anything.+ *+ * SYNC: A new row in Button.a11y.states.ts needs a named export here. Nothing+ * at compile time catches a missing or renamed one — the Chromium binding+ * does, when it navigates to the row's `storyId` and finds no story.+ */++import {useState, type ReactNode} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+// Relative, not `@astryxdesign/core/…`: the package specifier would claim these+// are published entry points, and they are deliberately not — `__tests__` is+// excluded from the build and ships in no `dist`. A repo-private path says what+// this actually is, and matches how other stories reach package internals.+import {+ BUTTON_BINDING_STATES,+ BUTTON_PATTERN_EXCLUSIONS,+} from '../../../packages/core/src/Button/__tests__/Button.a11y.states';+import {+ BUTTON_EXCLUSION_RENDERS,+ BUTTON_STATE_RENDERS,+} from '../../../packages/core/src/Button/__tests__/Button.a11y.renders';++/** Render one control and count how many times its action ran. */+function Counted({+ children,+}: {+ children: (activate: () => void) => ReactNode;+}): ReactNode {+ const [count, setCount] = useState(0);+ return (+ <div data-a11y-activations={count}>+ {children(() => {+ setCount(current => current + 1);+ })}+ <p>+ activations: <output>{count}</output>+ </p>+ </div>+ );+}++function storyFor(id: string): StoryObj {+ const state = BUTTON_BINDING_STATES.find(candidate => candidate.id === id);+ if (state == null) {+ throw new Error(`no binding state "${id}" — see Button.a11y.states.ts`);+ }+ return {+ name: `${state.binding} — ${state.id}`,+ render: () => (+ <Counted>{activate => BUTTON_STATE_RENDERS[state.id](activate)}</Counted>+ ),+ };+}++/** An excluded part, rendered so its exclusion can be checked in a browser. */+function exclusionStory(id: string): StoryObj {+ const exclusion = BUTTON_PATTERN_EXCLUSIONS.find(+ candidate => candidate.id === id,+ );+ if (exclusion == null) {+ throw new Error(`no exclusion "${id}" — see Button.a11y.states.ts`);+ }+ return {+ name: `excluded — ${exclusion.id}`,+ render: () => (+ <Counted>+ {activate => BUTTON_EXCLUSION_RENDERS[exclusion.id](activate)}+ </Counted>+ ),+ };+}++const meta: Meta = {+ title: 'a11y/Button pattern',+ // `no-visual` is the visual gate's supported explicit exclusion, and these+ // fixtures are what it is for: they exist to be DRIVEN by the accessibility+ // contract, not to be photographed. Several deliberately render a state no+ // product ships — a disabled card, a button mid-action — so a baseline frame+ // would be a picture nobody reviews, and a diff on one would ask a question+ // nobody can answer. Excluding them costs no coverage: every one of these+ // stories is still driven, in a real browser, by the Chromium contract lane.+ tags: ['no-visual'],+ parameters: {+ docs: {+ description: {+ component:+ 'Binding states for the shared button-pattern accessibility contract. Each story counts its own activations, because a button leaves no trace of having been pressed.',+ },+ },+ },+};++export default meta;++export const ButtonText = storyFor('button-text');+export const ButtonIconOnly = storyFor('button-icon-only');+export const ButtonComposedLabel = storyFor('button-composed-label');+export const ButtonDisabled = storyFor('button-disabled');+export const ButtonDisabledWithTooltip = storyFor(+ 'button-disabled-with-tooltip',+);+export const ButtonLoading = storyFor('button-loading');++export const IconButtonDefault = storyFor('icon-button');+export const IconButtonDisabled = storyFor('icon-button-disabled');+export const IconButtonLoading = storyFor('icon-button-loading');++export const ClickableCardDefault = storyFor('clickable-card');+export const ClickableCardDisabled = storyFor('clickable-card-disabled');++export const SidenavCollapseIcon = storyFor('sidenav-collapse-icon');+export const SidenavCollapseLabelled = storyFor('sidenav-collapse-labelled');++export const ChatSend = storyFor('chat-send');+export const ChatSendDisabled = storyFor('chat-send-disabled');+export const ChatSendStop = storyFor('chat-send-stop');++export const ButtonAsLink = exclusionStory('button-as-link');+export const ClickableCardAsLink = exclusionStory('clickable-card-as-link');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex fdeded284b..f53ed43686 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -12,7 +12,7 @@ explains the code that implements them.## Why a contract instead of more component tests-Every component that adopts the APG switch pattern owes the same things: the+Take the switch pattern. Every component that adopts it owes the same things: thecontrol is reported as a switch, it has a name that does not change when thestate does, its on/off state is exposed and matches what is rendered, pointerand keyboard both turn it on and back off, a press slid off and released@@ -36,14 +36,35 @@ src/├── harness/│ ├── jsdom.ts observes unit + DOM. Refuses everything above.│ └── chromium.ts observes DOM + accessibility tree + real browser.+├── spoken.ts how a visible label is compared against a computed name├── storybook.ts a static server over a built Storybook, for the browser lane└── patterns/├── switch.ts the switch pattern├── switch.fixtures.ts conforming + deliberately violating fixtures├── switch.jsdom.test.ts the contract's own proof, DOM layer- └── switch.chromium.spec.ts the same proof in a real engine+ ├── switch.chromium.spec.ts the same proof in a real engine+ └── button.* the button pattern, same four files```+## The patterns++| Pattern | Adopted from | Bound by |+| -------- | -------------------------------------------------------------- | ------------------------------------------------------------------------ |+| `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 |++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+Astryx button given `href` renders an anchor — belongs to the link pattern,+because the APG is explicit that the two functions are distinct.++Some patterns need something the control itself cannot show. A switch says+whether it is on, so "pressing it worked" is readable from the control; a+button's action leaves no trace on the button at all. A pattern like that reads+`activations()` from the run context, and the BINDING supplies the count — a+binding that does not makes every expectation reading it fail loudly, never+pass quietly.+## Evidence layers are the load-bearing ideaAn expectation names the layer that characterizes its claim, plus — in@@ -100,7 +121,16 @@ required failure is not "mostly conformant" (AST-021 FR11).`required` is earned by a directly applicable WCAG 2.2 A/AA criterion, or by acurrent Astryx record adopting the outcome — never by how easy the check was to-write. "Directly applicable" means the criterion is the expectation's PRIMARY+write.++An Astryx record can therefore make an expectation gate, so citing one is held+to the same standard as citing a specification: name the record (`family:buttons`),+name the clause (`FR3`), quote the requirement exactly, and link to a public+GitHub URL pinned to a full commit sha. `definePattern` refuses anything less —+a branch or tag link moves out from under the quote, and a link into an internal+system is one a reviewer of this repository cannot open. Quote the operative+sentence only: splicing a MUST to the MAY that follows it cites a requirement+the record does not make. "Directly applicable" means the criterion is the expectation's PRIMARYsource: a supporting citation further down the list is not adoption, or anyexpectation could buy a gate by appending a plausible criterion. Everything elseis `advisory` and has to say why.diff --git a/internal/a11y-spec/src/contract.test.ts b/internal/a11y-spec/src/contract.test.tsindex d88ebc608a..d1d2a7f1d9 100644--- a/internal/a11y-spec/src/contract.test.ts+++ b/internal/a11y-spec/src/contract.test.ts@@ -15,8 +15,10 @@import {describe, expect, it} from 'vitest';import {+ citeSource,definePattern,unansweredDimensions,+ type AstryxRecord,type Expectation,type PatternContract,} from './contract';@@ -150,6 +152,84 @@ describe('definePattern', () => {).toThrow(/unknown evidence layer/);});+ describe('an Astryx record as a source', () => {+ // It can make an expectation GATE (FR9), so a citation a reviewer cannot+ // check is not good enough.+ const record = (+ overrides: Partial<Omit<AstryxRecord, 'standard'>> = {},+ ): AstryxRecord => ({+ standard: 'astryx',+ id: 'family:probes',+ clause: 'FR1',+ requirement: 'A probe MUST probe.',+ url: `https://github.com/facebook/astryx/blob/${'a'.repeat(40)}/docs/families/probes.md`,+ ...overrides,+ });++ it('accepts one that names its record, its clause, and its bytes', () => {+ expect(+ pattern({expectations: [expectation({sources: [record()]})]}),+ ).not.toThrow();+ });++ it.each([['id'], ['clause'], ['requirement']] as const)(+ 'refuses one with no %s',+ field => {+ expect(+ pattern({+ expectations: [expectation({sources: [record({[field]: ' '})]})],+ }),+ ).toThrow(new RegExp(`cites an Astryx record with no ${field}`));+ },+ );++ const PIN = 'a'.repeat(40);++ it.each([+ // Only resolves inside a checkout.+ ['docs/families/probes.md'],+ // Not public: a reviewer of this repository cannot open it, and it must+ // never appear in it.+ ['https://www.internalfb.com/code/astryx/docs/families/probes.md'],+ ['http://github.com/facebook/astryx/blob/' + PIN + '/docs/x.md'],+ // Every one of these moves out from under the quote.+ ['https://github.com/facebook/astryx/blob/main/docs/x.md'],+ ['https://github.com/facebook/astryx/blob/HEAD/docs/x.md'],+ ['https://github.com/facebook/astryx/blob/develop/docs/x.md'],+ ['https://github.com/facebook/astryx/blob/v1.2.3/docs/x.md'],+ ['https://github.com/facebook/astryx/blob/refs/heads/main/docs/x.md'],+ ['https://github.com/facebook/astryx/raw/' + PIN + '/docs/x.md'],+ // A short sha is ambiguous over a long enough history.+ ['https://github.com/facebook/astryx/blob/abc1234/docs/x.md'],+ ])('refuses %s', url => {+ expect(+ pattern({expectations: [expectation({sources: [record({url})]})]}),+ ).toThrow(/pinned to the bytes the requirement was quoted from/);+ });++ it('accepts a public GitHub URL pinned to a full commit sha', () => {+ expect(+ pattern({+ expectations: [+ expectation({+ sources: [+ record({+ url: `https://github.com/facebook/astryx/blob/${PIN}/docs/families/probes.md#L1-L2`,+ }),+ ],+ }),+ ],+ }),+ ).not.toThrow();+ });++ it('says which record and clause in the citation, not just the id', () => {+ expect(citeSource(record())).toBe(+ 'Astryx family:probes FR1: A probe MUST probe.',+ );+ });+ });+it('refuses an unknown layer in alsoNeeds', () => {expect(pattern({diff --git a/internal/a11y-spec/src/contract.ts b/internal/a11y-spec/src/contract.tsindex c639f262aa..05eb24fef8 100644--- a/internal/a11y-spec/src/contract.ts+++ b/internal/a11y-spec/src/contract.ts@@ -70,8 +70,21 @@ export interface ApgRequirement {/** A current Astryx knowledge record that adopts an outcome. */export interface AstryxRecord {readonly standard: 'astryx';- /** Record id, e.g. `spec:AST-013`. */+ /** The record's own stable id, e.g. `spec:AST-013` or `family:buttons`. */readonly id: string;+ /** The clause within it, e.g. `FR3`. */+ readonly clause: string;+ /**+ * The requirement, quoted exactly — the same discipline the APG sources+ * follow. A citation a reader cannot check against the record is not a+ * citation, and an id alone does not say what was adopted.+ */+ readonly requirement: string;+ /**+ * A public URL pinned to the bytes this quote was taken from. `main` moves;+ * a citation that moves with it is a citation to whatever the record becomes,+ * which is exactly what a normative reference must not be.+ */readonly url: string;}@@ -85,7 +98,7 @@ export function citeSource(source: NormativeSource): string {case 'apg':return `APG ${source.pattern}: ${source.requirement}`;case 'astryx':- return `Astryx ${source.id}`;+ return `Astryx ${source.id} ${source.clause}: ${source.requirement}`;}}@@ -131,6 +144,19 @@ export interface ExpectationContext<Facts> {* excuse itself: a reader sees which states did not exercise it.*/readonly notApplicable: (reason: string) => never;+ /**+ * How many times the control's action has run since it was mounted.+ *+ * Some patterns have no state to read. A switch says whether it is on, so+ * "pressing it worked" is observable from the control itself; a button's+ * action leaves no trace on the button at all. The BINDING knows — it renders+ * the component and can count the handler — so it supplies this and the+ * contract asks.+ *+ * A binding that does not supply it makes every expectation reading it fail+ * as a harness fault, loudly, rather than quietly passing.+ */+ readonly activations: () => Promise<number>;}export interface Expectation<Facts> {@@ -202,6 +228,17 @@ export function requiredLayers<Facts>(return [expectation.evidenceLayer, ...(expectation.alsoNeeds ?? [])];}+/**+ * A public GitHub URL pinned to one commit.+ *+ * A full 40-character sha, not a branch or a tag: both move, and a normative+ * citation that moves cites whatever the record later becomes. Public GitHub+ * rather than any https URL, because a link into an internal system is one a+ * reviewer of this repository cannot open — and must never appear in it.+ */+const PINNED_PUBLIC_SOURCE =+ /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/blob\/[0-9a-f]{40}\/\S+$/;+/** Test name and failure prefix. Carries the id and the source (AST-020 FR4). */export function describeExpectation<Facts>(expectation: Expectation<Facts>,@@ -278,6 +315,34 @@ export function definePattern<Facts>(if (expectation.sources.length === 0) {problems.push(`${id} cites no normative source`);}+ // An Astryx record can make an expectation gate (FR9), so a citation nobody+ // can check is not good enough: it must say WHICH record, WHICH clause,+ // quote the requirement, and link to bytes that cannot move underneath it.+ for (const source of expectation.sources) {+ if (source.standard !== 'astryx') {+ continue;+ }+ for (const [field, value] of [+ ['id', source.id],+ ['clause', source.clause],+ ['requirement', source.requirement],+ ] as const) {+ if (value.trim() === '') {+ problems.push(+ `${id} cites an Astryx record with no ${field} (AST-020 FR1)`,+ );+ }+ }+ // One exact shape, rather than a list of the ways a URL can go wrong.+ // Anything looser lets through the two failures that matter: a link only+ // this checkout can open, and a link whose bytes move out from under the+ // quote — `main`, `HEAD`, a tag, a branch named anything at all.+ if (!PINNED_PUBLIC_SOURCE.test(source.url)) {+ problems.push(+ `${id} cites Astryx record "${source.id}" at "${source.url}". A record cited by a contract has to be readable by anyone reviewing it and pinned to the bytes the requirement was quoted from, so the URL must look like https://github.com/<org>/<repo>/blob/<full commit sha>/<path> (AST-020 FR1)`,+ );+ }+ }if (expectation.sources[0]?.standard === 'apg' &&(expectation.wcagOutcome ?? '').trim() === ''diff --git a/internal/a11y-spec/src/harness.ts b/internal/a11y-spec/src/harness.tsindex f99cfba89f..c353d8c092 100644--- a/internal/a11y-spec/src/harness.ts+++ b/internal/a11y-spec/src/harness.ts@@ -91,7 +91,7 @@ export interface Subject {}/** A key an expectation can send. Spelled by intent, not by engine syntax. */-export type Key = 'Space' | 'Tab';+export type Key = 'Space' | 'Enter' | 'Tab';/*** A mounted binding, observed at whatever layers this runtime can honestly see.diff --git a/internal/a11y-spec/src/harness/chromium.ts b/internal/a11y-spec/src/harness/chromium.tsindex f27c47cc8d..32ffde3e6f 100644--- a/internal/a11y-spec/src/harness/chromium.ts+++ b/internal/a11y-spec/src/harness/chromium.ts@@ -27,6 +27,7 @@* to ../harness/jsdom.ts — both implement Harness in ../harness.ts.*/+import {errors as playwrightErrors} from '@playwright/test';import type {CDPSession, Locator, Page} from '@playwright/test';import {type ComputedNode,@@ -44,8 +45,27 @@ export const CHROMIUM_OBSERVES: readonly EvidenceLayer[] = ['real-browser',];+/**+ * How long a pointer gets to reach a control before the attempt is a failure.+ *+ * Generous for a control that is reachable at all — Playwright's actionability+ * check normally settles in single-digit milliseconds — and short enough that a+ * control a pointer can never reach reports why instead of hanging.+ */+const POINTER_REACH_BUDGET_MS = 2_000;++/**+ * Playwright's own timeout type, rather than a regex over the message: the+ * message is prose that can be reworded in any release, and matching it would+ * turn a wording change into a mystery failure.+ */+function isTimeout(error: unknown): boolean {+ return error instanceof playwrightErrors.TimeoutError;+}+const KEYS: Record<Key, string> = {Space: ' ',+ Enter: 'Enter',Tab: 'Tab',};@@ -218,28 +238,30 @@ export function createChromiumHarness(computed: () => computedNode(cdp, locator),visibleLabelText: () =>locator.evaluate(element => {- // Whether a person can actually read this text.- //- // Two questions, because no single API answers both.+ // Whether a person can actually read this text. Two questions, because+ // no single API answers both.//// `checkVisibility` is the platform's own answer to "is this rendered- // at all", and it walks ancestors — so a label inside a+ // at all", and it walks ancestors — so a node inside a// `visibility: hidden`, `opacity: 0`, or `display: none` wrapper is// correctly invisible without this code reimplementing the cascade.- //- // What it cannot answer is whether anything of the element actually- // lands on screen: every sr-only recipe stays "visible" to it. So the- // element is sampled — if a point over it resolves to the element, to- // something inside it, or to something COVERING it, the element paints- // there. If every sample resolves to one of the element's own- // ancestors, nothing of it paints: it is clipped away, whatever its box- // says. If a sample resolves to nothing at all, that point is outside- // the viewport.- //- // Occlusion is deliberately not hiding: a label under an overlay is- // still a label a person can read when the overlay moves, and treating- // it as hidden would silently switch off the criterion that reads it.- const paints = (node: Element): boolean => {+ // What it cannot answer is whether anything of the node LANDS on+ // screen: every sr-only recipe stays "visible" to it. Hence the box.+ /**+ * A wrapper that generates no box of its own and lets its children lay+ * out as if it were not there. Judging it by its own box would be+ * wrong twice over: it has none, and its children may be perfectly+ * readable. Astryx wraps button content in one, so this is not an edge+ * case — it is the common path.+ */+ const isTransparentBox = (node: Element): boolean =>+ getComputedStyle(node).display === 'contents';++ const rendered = (node: Element): boolean => {+ if (isTransparentBox(node)) {+ // Nothing to judge here; each child is judged on its own.+ return true;+ }if (!node.checkVisibility({visibilityProperty: true,@@ -250,6 +272,50 @@ export function createChromiumHarness(return false;}const box = node.getBoundingClientRect();+ // The sr-only recipe: clipped to a 1px box, still in the tree.+ return box.width > 1 && box.height > 1;+ };++ /**+ * Whether text sitting directly in this node can be read.+ *+ * Separate from `rendered` because `color` inherits but is overridable:+ * a transparent wrapper whose child re-colours its own text is showing+ * that child's words, and judging the wrapper would erase them. So this+ * asks only about the node the text is actually in.+ *+ * Astryx dims a button's label with `color: transparent` while it waits+ * on an action, so this is a real case, not a hypothetical one.+ */+ const textIsReadable = (node: Element): boolean =>+ !/^rgba\(.*,\s*0\)$/.test(getComputedStyle(node).color);++ /**+ * Whether the label element as a whole paints anywhere.+ *+ * Sampling catches the case the box cannot: a FULL-SIZE element clipped+ * away entirely (`clip-path: inset(100%)`), which keeps its box and+ * stays "visible" to the platform. If a point over it resolves to the+ * element, to something inside it, or to something covering it, it+ * paints there; if every sample resolves to one of its own ancestors,+ * nothing of it paints.+ *+ * Applied only to the element being measured, never to its descendants:+ * a span inside a button legitimately hit-tests to the button, and+ * treating that as hidden would erase every nested label.+ *+ * Occlusion is deliberately not hiding: a label under an overlay is+ * still a label a person can read when the overlay moves.+ */+ const paints = (node: Element): boolean => {+ if (!rendered(node)) {+ return false;+ }+ if (isTransparentBox(node)) {+ // No box to sample; whether anything shows is up to the children.+ return true;+ }+ const box = node.getBoundingClientRect();const samples: ReadonlyArray<readonly [number, number]> = [[box.x + box.width / 2, box.y + box.height / 2],[box.x + 1, box.y + box.height / 2],@@ -264,9 +330,36 @@ export function createChromiumHarness(return at === node || node.contains(at) || !at.contains(node);});};++ // The text a person can actually READ inside this node.+ //+ // Not `textContent`: a control commonly carries a visually-hidden live+ // region or an sr-only span inside it, and counting that text would+ // report words nobody sees — which then reads as a label mismatch+ // against a name that (correctly) does not contain them. So the walk+ // descends and drops any subtree that is not rendered.+ const visibleTextOf = (node: Element): string => {+ let text = '';+ for (const child of node.childNodes) {+ if (child.nodeType === Node.TEXT_NODE) {+ if (textIsReadable(node)) {+ text += child.nodeValue ?? '';+ }+ } else if (+ child.nodeType === Node.ELEMENT_NODE &&+ rendered(child as Element)+ ) {+ text += ` ${visibleTextOf(child as Element)} `;+ }+ }+ return text.replace(/\s+/g, ' ').trim();+ };const textOf = (node: Element): string | null => {- const text = (node.textContent ?? '').replace(/\s+/g, ' ').trim();- return text !== '' && paints(node) ? text : null;+ if (!paints(node)) {+ return null;+ }+ const text = visibleTextOf(node);+ return text === '' ? null : text;};// The platform's own labelling order, not any design system's.@@ -314,17 +407,51 @@ export function createChromiumHarness(click: async (_subject, options) => {// Without `force`, Playwright first satisfies itself that the control is// visible, stable, enabled, and actually receives pointer events — so an- // ordinary click here also proves a pointer could reach the switch.+ // ordinary click here also proves a pointer could reach the control.// `ignoreAvailability` skips that judgement, which is the only way to ask// a control the browser calls unavailable what it does when clicked// anyway.- await locator.click({force: options?.ignoreAvailability === true});+ try {+ await locator.click({+ force: options?.ignoreAvailability === true,+ // Bounded, and short. A control a pointer cannot reach — one covered+ // by something else, or clipped to nothing — otherwise sits here+ // until the whole test times out, and a timeout says nothing about+ // WHY. This turns that into a legible failure the report can carry.+ timeout: POINTER_REACH_BUDGET_MS,+ });+ } catch (error) {+ if (isTimeout(error)) {+ throw new Error(+ `a pointer could not reach this control within ${POINTER_REACH_BUDGET_MS}ms: the browser never found it visible, stable, and able to receive a pointer event. Something is covering it, or it is clipped to nothing.`,+ {cause: error},+ );+ }+ throw error;+ }},abortedPress: async () => {const box = await locator.boundingBox();if (box == null) {throw new Error('the subject has no box to press on');}+ // A press that never lands on the control proves nothing about what+ // releasing it elsewhere does. Without this, a control a pointer cannot+ // reach reports a serene pass for pointer cancellation — the exact+ // vacuous green the evidence-layer rules exist to prevent.+ const reachable = await locator.evaluate(element => {+ const rect = element.getBoundingClientRect();+ const at = element.ownerDocument.elementFromPoint(+ rect.x + rect.width / 2,+ rect.y + rect.height / 2,+ );+ return at != null && (at === element || element.contains(at));+ });+ if (!reachable) {+ throw new Error(+ 'a pointer press cannot land on this control: something else is on top of it at its own centre, so there is no press here to abort',+ );+ }const viewport = await page.evaluate(() => ({width: window.innerWidth,height: window.innerHeight,diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.tsindex de2129cc96..b1cff5d90f 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -50,6 +50,7 @@ export {} from './harness';export {+ MissingBindingCapability,runBinding,type BindingResult,type ExpectationResult,@@ -70,8 +71,8 @@ export {export {createJsdomHarness, type JsdomHarnessOptions} from './harness/jsdom';-export {- SWITCH_PATTERN,- spokenWords,- type SwitchStateFacts,-} from './patterns/switch';+export {SWITCH_PATTERN, type SwitchStateFacts} from './patterns/switch';++export {saysInOrder, spokenWords} from './spoken';++export {BUTTON_PATTERN, type ButtonStateFacts} from './patterns/button';diff --git a/internal/a11y-spec/src/patterns/button.chromium.spec.ts b/internal/a11y-spec/src/patterns/button.chromium.spec.tsnew file mode 100644index 0000000000..32a013075a--- /dev/null+++ b/internal/a11y-spec/src/patterns/button.chromium.spec.ts@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file button.chromium.spec.ts+ * @input Uses @playwright/test, ./button (the contract), ./button.fixtures,+ * ../harness/chromium, ../run+ * @output The contract's own proof in a real engine: every expectation passes+ * against a conforming fixture and fails against each fixture that removes+ * its outcome.+ * @position Self-test, the Chromium half of ./button.jsdom.test.ts. Both halves+ * read the same fixtures, so the same positive and negative proof runs at+ * every layer that can see it.+ *+ * The fixtures are hand-written HTML with no Astryx in them, because what is+ * under test here is the CONTRACT — whether an expectation can actually fail.+ * A component binding proves the different claim that the component delivers+ * the outcome.+ *+ * SYNC: Fixtures and mutations live in ./button.fixtures.ts, shared with the+ * jsdom half.+ */++import {expect, test, type CDPSession, type Page} from '@playwright/test';+import {describeExpectation, requiredLayers} from '../contract';+import {+ CHROMIUM_OBSERVES,+ createChromiumHarness,+ holdMotionStill,+} from '../harness/chromium';+import {runBinding, type ExpectationResult} from '../run';+import {BUTTON_PATTERN} from './button';+import {+ CONFORMING_FIXTURES,+ SUBJECT_SELECTOR,+ BUTTON_MUTATIONS,+ fixture,+ type ButtonFixture,+} from './button.fixtures';++/** The counter every fixture increments from its own handler. */+interface ActivationWindow extends Window {+ __activations?: number;+}++/**+ * A tab stop after the button, so "focus can leave it" has somewhere to go.+ * Without it the browser moves focus to its own chrome and the fixture could+ * not tell an escape from a trap.+ */+function fixturePage(html: string): string {+ return `<!doctype html><html lang="en"><body>${html}<button type="button" id="after">after</button></body></html>`;+}++async function results(+ page: Page,+ cdp: CDPSession,+ target: ButtonFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ const run = await runBinding({+ contract: BUTTON_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ only,+ mount: async () => {+ await page.setContent(fixturePage(target.html));+ await holdMotionStill(page);+ await page.evaluate(() => {+ (window as ActivationWindow).__activations = 0;+ });+ return createChromiumHarness({+ page,+ subject: page.locator(SUBJECT_SELECTOR),+ cdp,+ });+ },+ // Every fixture counts its own presses; a button's action leaves no trace+ // on the button, so the contract asks the binding rather than the control.+ activations: () =>+ page.evaluate(() => (window as ActivationWindow).__activations ?? 0),+ });+ return run.results;+}++test.describe('button contract — conforming fixtures', () => {+ for (const id of CONFORMING_FIXTURES) {+ test(`${id}: every applicable expectation passes`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const observed = await results(page, cdp, fixture(id));+ const notPassing = observed.filter(+ result =>+ result.status !== 'pass' && result.status !== 'not-applicable',+ );+ expect(+ notPassing.map(+ result => `${result.expectation}: ${result.detail ?? ''}`,+ ),+ ).toEqual([]);+ });+ }+});++test.describe('button contract — deliberately violating fixtures', () => {+ for (const expectation of BUTTON_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of BUTTON_MUTATIONS[expectation.id] ?? []) {+ test(`${describeExpectation(expectation)} — fails against ${fixtureId}`, async ({+ page,+ }) => {+ const cdp = await page.context().newCDPSession(page);+ const [result] = await results(page, cdp, fixture(fixtureId), [+ expectation.id,+ ]);+ expect(result?.status, result?.detail ?? 'no result').toBe('fail');+ expect(result?.detail ?? '').not.toBe('');+ });+ }+ }+});diff --git a/internal/a11y-spec/src/patterns/button.fixtures.ts b/internal/a11y-spec/src/patterns/button.fixtures.tsnew file mode 100644index 0000000000..9f7f91c9b9--- /dev/null+++ b/internal/a11y-spec/src/patterns/button.fixtures.ts@@ -0,0 +1,330 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file button.fixtures.ts+ * @input Uses ./button (ButtonStateFacts)+ * @output BUTTON_FIXTURES — hand-written buttons, one conforming per state and+ * one deliberately violating per expectation — and BUTTON_MUTATIONS, which+ * says which fixture each expectation must fail against.+ * @position The contract's own proof (AST-020 FR11). Read by the jsdom+ * self-test and the Chromium self-test, so the same positive and negative+ * fixtures run at every layer that can see them.+ *+ * These are plain HTML on purpose. They prove the CONTRACT — that each+ * expectation passes when the outcome is present and fails when it is removed —+ * so they must not depend on any Astryx component. A component binding proves+ * something different: that the component delivers the outcome.+ *+ * Every fixture counts its own activations on `window.__activations`, because a+ * button's action leaves no trace on the button. That counter is what the+ * contract reads through the binding's `activations()` seam.+ *+ * SYNC: A new expectation in ./button.ts needs a row in BUTTON_MUTATIONS, and+ * the self-tests fail until it has one.+ */++import type {ButtonStateFacts} from './button';++/** The attribute a fixture marks its control with. */+const SUBJECT_ATTRIBUTE = 'data-a11y-subject';++/** How a lane finds the control a fixture designates. */+export const SUBJECT_SELECTOR = `[${SUBJECT_ATTRIBUTE}]`;++export interface ButtonFixture {+ readonly id: string;+ /** What this fixture is, in one line, for the test name. */+ readonly summary: string;+ /** What the fixture declares itself to be. */+ readonly facts: ButtonStateFacts;+ readonly html: string;+}++const CONFORMING_FACTS: ButtonStateFacts = {+ operable: true,+ focusable: true,+ unavailable: false,+ described: false,+};++function facts(overrides: Partial<ButtonStateFacts> = {}): ButtonStateFacts {+ return {...CONFORMING_FACTS, ...overrides};+}++/** Count an activation the way a binding's own handler would. */+const COUNT = `window.__activations = (window.__activations || 0) + 1`;++/**+ * A native button — the platform's own, which the APG prefers.+ *+ * The counting handler comes FIRST and is opt-out, because HTML keeps the first+ * of a duplicated attribute: a fixture that supplies its own `onclick` must say+ * `counts: false`, or its handler would be silently discarded and the fixture+ * would quietly stop testing what it claims to.+ */+function nativeButton(+ attributes = '',+ {+ label = 'Save changes',+ counts = true,+ }: {label?: string; counts?: boolean} = {},+): string {+ const onClick = counts ? ` onclick="${COUNT}"` : '';+ return `<button type="button" ${SUBJECT_ATTRIBUTE}${onClick}${attributes ? ` ${attributes}` : ''}>${label}</button>`;+}++/** A div promoted to a button, so a fixture can withhold what a native one gives. */+function divButton(attributes: string, label = 'Save changes'): string {+ return `<div ${SUBJECT_ATTRIBUTE} role="button" ${attributes}>${label}</div>`;+}++/** The APG's own div-button recipe: click plus both activation keys. */+const DIV_BUTTON_BEHAVIOUR = `tabindex="0" onclick="${COUNT}" onkeydown="if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); ${COUNT}; }"`;++export const BUTTON_FIXTURES: readonly ButtonFixture[] = [+ // ---- conforming, one per representative state ---------------------------+ {+ id: 'conforming-native',+ summary: 'a native button labelled by its own text',+ facts: facts(),+ html: nativeButton(),+ },+ {+ id: 'conforming-div',+ summary:+ "a div promoted to a button, with the APG's own keyboard recipe — the case a native element does not cover for free",+ facts: facts(),+ html: divButton(DIV_BUTTON_BEHAVIOUR),+ },+ {+ id: 'conforming-icon-only',+ summary: 'a button with no text, named by aria-label',+ facts: facts(),+ html: `<button type="button" ${SUBJECT_ATTRIBUTE} onclick="${COUNT}" aria-label="Delete conversation"><span aria-hidden="true">🗑</span></button>`,+ },+ {+ id: 'conforming-described',+ summary: 'a button with supporting text attached as its description',+ facts: facts({described: true}),+ html:+ '<p id="hint">This cannot be undone.</p>' ++ nativeButton('aria-describedby="hint"'),+ },+ {+ id: 'conforming-unavailable-native',+ summary: 'a natively disabled button, out of the tab sequence',+ facts: facts({operable: false, focusable: false, unavailable: true}),+ html: nativeButton('disabled'),+ },+ {+ id: 'conforming-unavailable-focusable',+ summary:+ 'a button kept focusable while unavailable, the way a reason stays discoverable — announced unavailable, and it refuses to act',+ facts: facts({operable: false, unavailable: true}),+ html: nativeButton(+ `aria-disabled="true" onclick="event.preventDefault(); return false;" onkeydown="if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); }"`,+ {counts: false},+ ),+ },+ {+ id: 'conforming-busy',+ summary:+ 'a button waiting on the action it started: still focusable, reported busy, and refusing a second press',+ facts: facts({operable: false}),+ html: nativeButton(+ `aria-busy="true" aria-disabled="true" onclick="event.preventDefault(); return false;" onkeydown="if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); }"`,+ {counts: false},+ ),+ },++ // ---- one deliberate violation per expectation ---------------------------+ {+ id: 'violating-generic-element',+ summary: 'a plain element with no role at all',+ facts: facts({operable: false, focusable: false}),+ html: `<div ${SUBJECT_ATTRIBUTE}>Save changes</div>`,+ },+ {+ id: 'violating-link-role',+ summary:+ 'an anchor doing a button\u2019s job, so it is announced as a link and promises navigation it does not do',+ facts: facts(),+ html: `<a href="#" ${SUBJECT_ATTRIBUTE} onclick="event.preventDefault(); ${COUNT}">Save changes</a>`,+ },+ {+ id: 'violating-unnamed',+ summary: 'an icon-only button with nothing to name it',+ facts: facts(),+ html: `<button type="button" ${SUBJECT_ATTRIBUTE} onclick="${COUNT}"><span aria-hidden="true">🗑</span></button>`,+ },+ {+ id: 'violating-name-mismatch',+ summary:+ 'a button whose aria-label replaces the words a person can read, so speaking them reaches nothing',+ facts: facts(),+ html: nativeButton('aria-label="Submit"'),+ },+ {+ id: 'violating-dangling-description',+ summary: 'a button described by an id that resolves to nothing',+ facts: facts({described: true}),+ html: nativeButton('aria-describedby="hint"'),+ },+ {+ id: 'violating-empty-description',+ summary: 'a button described by an element that renders no text',+ facts: facts({described: true}),+ html: '<p id="hint"></p>' + nativeButton('aria-describedby="hint"'),+ },+ {+ id: 'violating-inert',+ summary: 'a button that does nothing when it is pressed',+ facts: facts(),+ html: divButton('tabindex="0"'),+ },+ {+ id: 'violating-pointer-only',+ summary: 'a button that answers a pointer but ignores the keyboard',+ facts: facts(),+ html: divButton(`tabindex="0" onclick="${COUNT}"`),+ },+ {+ id: 'violating-enter-only',+ summary:+ 'a button that answers Enter but not Space — the half of the keyboard a div-button usually forgets',+ facts: facts(),+ html: divButton(+ `tabindex="0" onclick="${COUNT}" onkeydown="if (event.key === 'Enter') { event.preventDefault(); ${COUNT}; }"`,+ ),+ },+ {+ id: 'violating-space-only',+ summary: 'a button that answers Space but not Enter',+ facts: facts(),+ html: divButton(+ `tabindex="0" onclick="${COUNT}" onkeydown="if (event.key === ' ') { event.preventDefault(); ${COUNT}; }"`,+ ),+ },+ {+ id: 'violating-unreachable',+ summary: 'a button that is not in the tab sequence',+ facts: facts(),+ html: divButton(+ `onclick="${COUNT}" onkeydown="if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); ${COUNT}; }"`,+ ),+ },+ {+ id: 'violating-keyboard-trap',+ summary: 'a button that swallows the Tab that would leave it',+ facts: facts(),+ html: nativeButton(+ `onkeydown="if (event.key === 'Tab') { event.preventDefault(); }"`,+ ),+ },+ {+ id: 'violating-down-event-activation',+ summary:+ 'a button that acts on the way down, so a press slid off cannot be taken back',+ facts: facts(),+ html: divButton(+ `tabindex="0" onpointerdown="${COUNT}" onkeydown="if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); ${COUNT}; }"`,+ ),+ },+ {+ id: 'violating-unavailable-unexposed',+ summary:+ 'a button that refuses to act without ever saying it is unavailable',+ facts: facts({operable: false, unavailable: true}),+ html: nativeButton('onclick="event.preventDefault(); return false;"', {+ counts: false,+ }),+ },+ {+ id: 'violating-unavailable-still-acts',+ summary: 'a button marked unavailable that runs its action anyway',+ facts: facts({operable: false, unavailable: true}),+ html: nativeButton(`aria-disabled="true"`),+ },+ {+ id: 'violating-unavailable-acts-on-key',+ summary:+ 'a button marked unavailable that refuses a click but still runs on Enter or Space — the half a pointer-only check would miss',+ facts: facts({operable: false, unavailable: true}),+ html: nativeButton(+ `aria-disabled="true" onclick="event.preventDefault(); return false;" onkeydown="if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); ${COUNT}; }"`,+ {counts: false},+ ),+ },+ {+ id: 'violating-unavailable-unfocusable',+ summary:+ 'a button declared focusable so its reason stays reachable, but natively disabled — so it cannot take focus at all, the reason is unreadable, and its refusal is unverifiable',+ facts: facts({operable: false, unavailable: true}),+ // `tabindex="-1"` would NOT do: it removes a control from the tab sequence+ // while leaving it programmatically focusable, so `focus()` still succeeds.+ // The native attribute is what actually refuses focus — and it is what the+ // real components do, which is why this shape is worth a fixture.+ html: nativeButton('disabled aria-disabled="true"', {counts: false}),+ },+ {+ id: 'violating-busy-unfocusable',+ summary:+ 'a button that goes natively disabled while busy, so focus is dropped mid-task and Tab can no longer reach it',+ facts: facts({operable: false}),+ html: nativeButton('aria-busy="true" disabled'),+ },+];++export function fixture(id: string): ButtonFixture {+ const found = BUTTON_FIXTURES.find(candidate => candidate.id === id);+ if (found == null) {+ throw new Error(`unknown button fixture "${id}"`);+ }+ return found;+}++/** The conforming fixtures every expectation must pass against (AST-020 FR11). */+export const CONFORMING_FIXTURES: readonly string[] = BUTTON_FIXTURES.filter(+ candidate => candidate.id.startsWith('conforming-'),+).map(candidate => candidate.id);++/**+ * For each expectation, the fixtures that remove its outcome. Every expectation+ * needs at least one, and the self-tests fail when one is missing — that is how+ * "the contract can actually fail" stops being a claim (AST-020 FR11).+ */+export const BUTTON_MUTATIONS: Readonly<Record<string, readonly string[]>> = {+ 'button.role.exposed': ['violating-generic-element', 'violating-link-role'],+ 'button.name.exposed': ['violating-unnamed'],+ 'button.name.matches-visible-label': ['violating-name-mismatch'],+ 'button.description.resolvable': ['violating-dangling-description'],+ 'button.description.exposed': ['violating-empty-description'],+ 'button.action.runs-on-pointer': ['violating-inert'],+ 'button.action.runs-on-enter': [+ 'violating-inert',+ 'violating-pointer-only',+ 'violating-space-only',+ ],+ 'button.action.runs-on-space': [+ 'violating-inert',+ 'violating-pointer-only',+ 'violating-enter-only',+ ],+ 'button.action.survives-an-aborted-press': [+ 'violating-down-event-activation',+ ],+ 'button.focus.reachable-and-escapable': [+ 'violating-unreachable',+ 'violating-keyboard-trap',+ // Natively disabled while busy: out of the tab sequence exactly when the+ // user most needs to get back to it. This is the shape of a real defect in+ // two shipped components, recorded in Button.a11y.known-failures.ts.+ 'violating-busy-unfocusable',+ ],+ 'button.unavailable.exposed': ['violating-unavailable-unexposed'],+ 'button.unavailable.inert': [+ 'violating-unavailable-still-acts',+ 'violating-unavailable-acts-on-key',+ 'violating-unavailable-unfocusable',+ ],+};diff --git a/internal/a11y-spec/src/patterns/button.jsdom.test.ts b/internal/a11y-spec/src/patterns/button.jsdom.test.tsnew file mode 100644index 0000000000..a5d3377732--- /dev/null+++ b/internal/a11y-spec/src/patterns/button.jsdom.test.ts@@ -0,0 +1,178 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file button.jsdom.test.ts+ * @input Uses ./button (the contract), ./button.fixtures (conforming and+ * violating fixtures), ../harness/jsdom, ../run+ * @output The contract's own proof at the DOM layer: every expectation passes+ * against a conforming fixture, fails against a fixture that removes its+ * outcome, and reports `unrun` when this harness cannot observe its layer.+ * @position Self-test. Proves the CONTRACT, not any component — the fixtures are+ * hand-written HTML with no Astryx in them.+ *+ * `docs/specs/AST-020/spec.md` FR11: each expectation must pass against a+ * minimally conforming fixture and fail when its required outcome is+ * deliberately removed, and the suite must tell a real violation apart from an+ * unsupported harness operation.+ *+ * SYNC: The Chromium half of this proof is ./button.chromium.spec.ts. Both read+ * the same fixtures, so a new fixture is covered at whichever layers can see it.+ */++import {afterEach, describe, expect, it} from 'vitest';+import {+ citeSource,+ describeExpectation,+ requiredLayers,+ unansweredDimensions,+} from '../contract';+import {JSDOM_OBSERVES, createJsdomHarness} from '../harness/jsdom';+import {runBinding, type ExpectationResult} from '../run';+import {BUTTON_PATTERN} from './button';+import {+ CONFORMING_FIXTURES,+ SUBJECT_SELECTOR,+ BUTTON_MUTATIONS,+ fixture,+ type ButtonFixture,+} from './button.fixtures';++/** The counter every fixture increments from its own handler. */+interface ActivationWindow extends Window {+ __activations?: number;+}++const observableHere = BUTTON_PATTERN.expectations.filter(expectation =>+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),+);++afterEach(() => {+ document.body.replaceChildren();+});++async function resultsFor(target: ButtonFixture) {+ const container = document.createElement('div');+ document.body.append(container);+ const result = await runBinding({+ contract: BUTTON_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ mount: async () => {+ (window as ActivationWindow).__activations = 0;+ container.innerHTML = target.html;+ const subject = container.querySelector(SUBJECT_SELECTOR);+ if (subject == null) {+ throw new Error(`fixture "${target.id}" marks no subject element`);+ }+ return createJsdomHarness({subject});+ },+ unmount: () => {+ container.innerHTML = '';+ },+ // Every fixture counts its own presses; a button's action leaves no trace+ // on the button, so the contract asks the binding rather than the control.+ activations: async () => (window as ActivationWindow).__activations ?? 0,+ });+ return result.results;+}++function resultFor(+ results: readonly ExpectationResult[],+ id: string,+): ExpectationResult {+ const found = results.find(result => result.expectation === id);+ if (found == null) {+ throw new Error(`no result for ${id}`);+ }+ return found;+}++describe('button contract — completeness', () => {+ it('answers every completeness dimension', () => {+ expect(unansweredDimensions(BUTTON_PATTERN)).toEqual([]);+ });++ it('gives every expectation at least one deliberately violating fixture', () => {+ const missing = BUTTON_PATTERN.expectations+ .filter(+ expectation => (BUTTON_MUTATIONS[expectation.id] ?? []).length === 0,+ )+ .map(expectation => expectation.id);+ expect(missing).toEqual([]);+ });++ it('has an expectation for every violating fixture it records', () => {+ const ids = new Set(+ BUTTON_PATTERN.expectations.map(expectation => expectation.id),+ );+ const orphans = Object.keys(BUTTON_MUTATIONS).filter(id => !ids.has(id));+ expect(orphans).toEqual([]);+ });++ it('names every fixture it records a mutation against', () => {+ for (const fixtures of Object.values(BUTTON_MUTATIONS)) {+ for (const id of fixtures) {+ expect(() => fixture(id)).not.toThrow();+ }+ }+ });+});++describe('button contract — the jsdom harness reports what it cannot see', () => {+ it('reports an expectation above the DOM layer as unrun, never as a pass', async () => {+ const results = await resultsFor(fixture('conforming-native'));+ const above = results.filter(result => result.status === 'unrun');+ // There is at least one, or the contract would be provable without a browser.+ expect(above.length).toBeGreaterThan(0);+ for (const result of above) {+ expect(+ ['unrun', 'not-applicable'],+ `${result.expectation} in jsdom`,+ ).toContain(result.status);+ }+ });+});++describe.each(observableHere.map(expectation => [expectation.id] as const))(+ '%s',+ id => {+ const expectation = BUTTON_PATTERN.expectations.find(+ candidate => candidate.id === id,+ )!;++ it.each(CONFORMING_FIXTURES.map(name => [name] as const))(+ 'passes against %s (or does not apply to it)',+ async name => {+ const target = fixture(name);+ const result = resultFor(await resultsFor(target), id);+ expect(+ ['pass', 'not-applicable'],+ `${id} against ${name}: ${result.detail ?? ''}`,+ ).toContain(result.status);+ },+ );++ it.each((BUTTON_MUTATIONS[id] ?? []).map(name => [name] as const))(+ 'fails against %s, which removes its outcome',+ async name => {+ const target = fixture(name);+ const result = resultFor(await resultsFor(target), id);+ expect(result.status, `${id} against ${name}`).toBe('fail');+ expect(result.detail ?? '').not.toBe('');+ },+ );++ it('carries its id and its normative source into every failure it reports', async () => {+ const [violating] = BUTTON_MUTATIONS[id] ?? [];+ const target = fixture(violating ?? CONFORMING_FIXTURES[0]!);+ const result = resultFor(await resultsFor(target), id);+ // AST-020 FR4: a failure has to be understandable without opening the+ // runner, so the id and the citation travel with the result.+ expect(result.description).toContain(id);+ expect(result.description).toContain(citeSource(expectation.sources[0]));+ expect(describeExpectation(expectation)).toBe(result.description);+ });+ },+);diff --git a/internal/a11y-spec/src/patterns/button.ts b/internal/a11y-spec/src/patterns/button.tsnew file mode 100644index 0000000000..ba67bebecf--- /dev/null+++ b/internal/a11y-spec/src/patterns/button.ts@@ -0,0 +1,703 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file button.ts+ * @input Uses ../contract (definePattern and the expectation vocabulary)+ * @output BUTTON_PATTERN — the adopted WAI-ARIA APG "button" pattern as a+ * reusable contract — and ButtonStateFacts, what a binding declares each of+ * its states is supposed to be.+ * @position The second authored pattern, modelled on ./switch.ts.+ *+ * Adopted pattern: https://www.w3.org/WAI/ARIA/apg/patterns/button/+ *+ * What this contract owns is the part of "is it a button" that is the same for+ * every component that adopts the pattern: the control is reported as a button+ * and not a link, it is named, its description reaches the user, a pointer runs+ * its action, BOTH Enter and Space run its action, a press slid off the control+ * is taken back, focus can reach it and leave it, and a button that cannot act+ * says so and stays inert.+ *+ * Two things the APG names are deliberately out of scope. A TOGGLE button+ * carries `aria-pressed` and has its own contract; this one covers the ordinary+ * command button. And an element that adopts LINK semantics — Astryx buttons+ * render an anchor when given `href` — is a link, so the APG's own note applies+ * ("the types of actions performed by buttons are distinctly different from the+ * function of a link") and the link pattern owns it.+ *+ * SYNC: When an expectation changes, update+ * - /internal/a11y-spec/README.md+ * - /packages/core/src/Button/__tests__/Button.a11y.test.tsx (the jsdom binding)+ * - /packages/core/src/Button/__tests__/Button.a11y.chromium.spec.ts (Chromium)+ */++import {+ definePattern,+ type ApgRequirement,+ type AstryxRecord,+ type PatternContract,+ type WcagCriterion,+} from '../contract';+import {saysInOrder, spokenWords} from '../spoken';++const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/button/';+const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';++const WCAG_1_3_1: WcagCriterion = {+ standard: 'wcag',+ id: '1.3.1',+ name: 'Info and Relationships',+ level: 'A',+ url: `${UNDERSTANDING}/info-and-relationships.html`,+};+const WCAG_2_1_1: WcagCriterion = {+ standard: 'wcag',+ id: '2.1.1',+ name: 'Keyboard',+ level: 'A',+ url: `${UNDERSTANDING}/keyboard.html`,+};+const WCAG_2_1_2: WcagCriterion = {+ standard: 'wcag',+ id: '2.1.2',+ name: 'No Keyboard Trap',+ level: 'A',+ url: `${UNDERSTANDING}/no-keyboard-trap.html`,+};+const WCAG_2_5_2: WcagCriterion = {+ standard: 'wcag',+ id: '2.5.2',+ name: 'Pointer Cancellation',+ level: 'A',+ url: `${UNDERSTANDING}/pointer-cancellation.html`,+};+const WCAG_2_5_3: WcagCriterion = {+ standard: 'wcag',+ id: '2.5.3',+ name: 'Label in Name',+ level: 'A',+ url: `${UNDERSTANDING}/label-in-name.html`,+};+const WCAG_4_1_2: WcagCriterion = {+ standard: 'wcag',+ id: '4.1.2',+ name: 'Name, Role, Value',+ level: 'A',+ url: `${UNDERSTANDING}/name-role-value.html`,+};++/**+ * The buttons family record: `authority: current`, approved 2026-09-04.+ *+ * Pinned to the commit that wrote these clauses rather than to a branch. A+ * normative citation that follows `main` cites whatever the record later+ * becomes, and the whole point of quoting it is that the quote stays true.+ */+const FAMILY_BUTTONS =+ 'https://github.com/facebook/astryx/blob/cb13c1eaa89065cf7656a0d647be428447040d71/docs/families/buttons.md';++/**+ * The clause that adopts operability and keyboard activation.+ *+ * Reading it as adopting POINTER operability is an interpretation, and worth+ * naming as one: the clause never says "pointer". It attaches three properties+ * to the noun "an operable button" — keyboard activation, focus-visible+ * feedback, `type="button"` — which makes operability a property in its own+ * right rather than a synonym for the keyboard half, and the clause heading is+ * "Native action semantics are the default". A control that swallows a click+ * has no native action semantics. If the family owner reads it more narrowly,+ * the fix is one line here and the expectation becomes advisory.+ */+const FAMILY_BUTTONS_FR2: AstryxRecord = {+ standard: 'astryx',+ id: 'family:buttons',+ clause: 'FR2',+ requirement:+ 'A momentary or persistent action renders an operable button with keyboard activation, focus-visible feedback, and `type="button"` unless the component\'s documented form mode says otherwise.',+ // The lines the quoted sentence spans. A line anchor cannot stop mid-line, so+ // the range also shows the start of the sentence that follows it; the+ // `requirement` above is the exact text this expectation rests on.+ url: `${FAMILY_BUTTONS}#L108-L111`,+};++/**+ * The clause that adopts inertness. Quoted as the MUST sentence alone: the+ * sentence after it is a MAY about focusable `aria-disabled`, and splicing the+ * two would quote a requirement the record does not make.+ */+const FAMILY_BUTTONS_FR3: AstryxRecord = {+ standard: 'astryx',+ id: 'family:buttons',+ clause: 'FR3',+ requirement: 'A disabled member MUST NOT invoke its callback or Action.',+ // The lines the MUST sentence spans. It ends mid-L114, so the range also+ // shows the start of the MAY that follows — which is a limit of line anchors,+ // not a widening of the citation: `requirement` above is the MUST alone.+ url: `${FAMILY_BUTTONS}#L113-L114`,+};++const APG_ROLE: ApgRequirement = {+ standard: 'apg',+ pattern: 'button',+ requirement: 'The button has role of button.',+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,+};+const APG_LABEL: ApgRequirement = {+ standard: 'apg',+ pattern: 'button',+ requirement:+ 'The button has an accessible label. By default, the accessible name is computed from any text content inside the button element. However, it can also be provided with aria-labelledby or aria-label.',+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,+};+const APG_DESCRIBEDBY: ApgRequirement = {+ standard: 'apg',+ pattern: 'button',+ requirement:+ "If a description of the button's function is present, the button element has aria-describedby set to the ID of the element containing the description.",+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,+};+const APG_UNAVAILABLE: ApgRequirement = {+ standard: 'apg',+ pattern: 'button',+ requirement:+ 'When the action associated with a button is unavailable, the button has aria-disabled set to true.',+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,+};+const APG_ENTER: ApgRequirement = {+ standard: 'apg',+ pattern: 'button',+ requirement: 'Enter: Activates the button.',+ url: `${APG_URL}#keyboardinteraction`,+};+const APG_SPACE: ApgRequirement = {+ standard: 'apg',+ pattern: 'button',+ requirement: 'Space: Activates the button.',+ url: `${APG_URL}#keyboardinteraction`,+};++/**+ * What a binding declares one of its states is supposed to be. The contract+ * asks the browser what it actually exposes and compares against this — so a+ * binding cannot pass by being consistently wrong, and an expectation knows+ * which states it applies to (AST-020 FR5, AST-021 FR4).+ */+export interface ButtonStateFacts {+ /** Whether pressing it is meant to run its action. */+ readonly operable: boolean;+ /** Whether it is meant to be reachable in the tab sequence. */+ readonly focusable: boolean;+ /** Whether its action is meant to be exposed as unavailable. */+ readonly unavailable: boolean;+ /** Whether supporting text is meant to be attached as a description. */+ readonly described: boolean;+}++/** Applies to every state; the outcome never stops mattering. */+const ALWAYS = {+ condition: 'the binding renders the pattern at all',+ test: () => true,+};++/**+ * How many Tab presses count as "reachable". Ten is generous for one control on+ * a fixture page and short enough that an unreachable button fails fast.+ */+const TAB_BUDGET = 10;++export const BUTTON_PATTERN: PatternContract<ButtonStateFacts> =+ definePattern<ButtonStateFacts>({+ pattern: 'button',+ url: APG_URL,+ scope:+ 'One command control that is reported as a button, named, described, and runs its action from a pointer, Enter, and Space alike — or says it cannot.',++ expectations: [+ {+ id: 'button.role.exposed',+ outcome:+ 'It is announced as a button, so the user knows it does something here rather than taking them somewhere else.',+ sources: [WCAG_4_1_2, APG_ROLE],+ covers: ['4.1.2-name-role-value', 'apg-interaction'],+ appliesWhen: ALWAYS,+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {role} = await subject.computed();+ if (role !== 'button') {+ throw new Error(+ role == null+ ? 'the browser exposes no role for this control — it is not in the accessibility tree at all, so assistive technology cannot announce it'+ : role === 'link'+ ? 'the browser reports this control as a link, so it promises navigation while performing an action; the APG is explicit that the two are distinctly different'+ : `the browser reports this control as "${role}", not as a button`,+ );+ }+ },+ },+ {+ id: 'button.name.exposed',+ outcome:+ 'The button has an accessible name, so the user knows what pressing it will do.',+ sources: [WCAG_4_1_2, APG_LABEL],+ covers: ['4.1.2-name-role-value', '2.4.6-headings-and-labels'],+ 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 button, so it is announced as an unlabelled control and nothing says what it does',+ );+ }+ },+ },+ {+ id: 'button.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, APG_LABEL],+ covers: ['2.5.3-label-in-name'],+ // Both sides are read off the rendered page: a criterion a binding could+ // switch off by describing itself would not be a criterion.+ appliesWhen: ALWAYS,+ evidenceLayer: 'accessibility-tree',+ alsoNeeds: ['real-browser'],+ enforcement: 'required',+ run: async ({subject, notApplicable}) => {+ const visible = await subject.visibleLabelText();+ if (visible == null) {+ // An icon-only button presents no words, so there is nothing for a+ // speech user to say: 2.5.3 applies to "components with labels that+ // include text or images of text".+ return notApplicable(+ 'this state renders no label where a person can read it, 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: 'button.description.resolvable',+ outcome:+ 'Every piece of supporting text the button points at exists, so none of the explanation is silently dropped.',+ sources: [WCAG_1_3_1, APG_DESCRIBEDBY],+ covers: ['1.3.1-info-and-relationships'],+ appliesWhen: {+ condition: 'the binding renders supporting text for this state',+ test: facts => facts.described,+ },+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({subject}) => {+ const attribute = await subject.attribute('aria-describedby');+ const ids = (attribute ?? '').split(/\s+/).filter(Boolean);+ if (ids.length === 0) {+ throw new Error(+ 'the binding renders supporting text for this state, but the button has no aria-describedby, so the text is never attached to the control',+ );+ }+ 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; that description never reaches anyone`,+ );+ }+ },+ },+ {+ id: 'button.description.exposed',+ outcome:+ "The supporting text reaches the user as the control's description, not just as nearby markup.",+ sources: [WCAG_4_1_2, APG_DESCRIBEDBY],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding renders supporting text for this state',+ test: facts => facts.described,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {description} = await subject.computed();+ if (description.trim() === '') {+ throw new Error(+ 'the binding renders supporting text for this state, but the browser computes no accessible description, so the explanation is never announced with the control',+ );+ }+ },+ },+ {+ id: 'button.unavailable.exposed',+ outcome:+ 'A button whose action is unavailable says so, instead of looking available and doing nothing.',+ sources: [WCAG_4_1_2, APG_UNAVAILABLE],+ covers: ['4.1.2-name-role-value'],+ appliesWhen: {+ condition: 'the binding declares this state unavailable',+ test: facts => facts.unavailable,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {disabled} = await subject.computed();+ if (!disabled) {+ throw new Error(+ 'this state is declared unavailable, but the browser reports the button as available, so the user is invited to do something that will not happen',+ );+ }+ },+ },+ {+ id: 'button.action.runs-on-pointer',+ outcome: 'Clicking the button runs its action.',+ // Astryx-primary. FR2 requires "an operable button with keyboard+ // activation" — operability and keyboard activation as two properties,+ // not one — so a control that does nothing when clicked fails the+ // first of them. 4.1.2 is listed after because it governs how a control+ // is EXPOSED, not what it does, and leading with it would buy the gate+ // with a citation that does not carry the claim.+ sources: [FAMILY_BUTTONS_FR2, APG_ROLE, WCAG_4_1_2],+ covers: ['apg-interaction'],+ appliesWhen: {+ condition: 'pressing this state is meant to run its action',+ test: facts => facts.operable,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject, activations}) => {+ const before = await activations();+ await harness.click(subject);+ const after = await activations();+ if (after === before) {+ throw new Error(+ 'clicking the button ran nothing, so the control announces an action it does not perform',+ );+ }+ },+ },+ {+ id: 'button.action.runs-on-enter',+ outcome:+ 'With focus on the button, Enter runs its action — the keyboard reaches the same function the pointer does.',+ sources: [WCAG_2_1_1, APG_ENTER],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition:+ 'pressing this state is meant to run its action and it is meant to be focusable',+ test: facts => facts.operable && facts.focusable,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject, activations}) => {+ await subject.focus();+ if (!(await subject.isFocused())) {+ throw new Error(+ 'the button did not take focus, so Enter never reaches it',+ );+ }+ const before = await activations();+ await harness.press('Enter');+ if ((await activations()) === before) {+ throw new Error(+ 'pressing Enter on the focused button ran nothing, so this action is out of reach from the keyboard',+ );+ }+ },+ },+ {+ id: 'button.action.runs-on-space',+ outcome:+ 'With focus on the button, Space runs its action too — the APG requires both keys, and a div-button usually forgets one.',+ sources: [WCAG_2_1_1, APG_SPACE],+ covers: ['2.1.1-keyboard', 'apg-interaction'],+ appliesWhen: {+ condition:+ 'pressing this state is meant to run its action and it is meant to be focusable',+ test: facts => facts.operable && facts.focusable,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject, activations}) => {+ await subject.focus();+ if (!(await subject.isFocused())) {+ throw new Error(+ 'the button did not take focus, so Space never reaches it',+ );+ }+ const before = await activations();+ await harness.press('Space');+ if ((await activations()) === before) {+ throw new Error(+ 'pressing Space on the focused button ran nothing; the APG requires Enter AND Space, and a control that answers only one leaves half its keyboard users stuck',+ );+ }+ },+ },+ {+ id: 'button.action.survives-an-aborted-press',+ outcome:+ 'A press the user slides off and releases elsewhere runs nothing, so a misplaced touch can be taken back.',+ sources: [WCAG_2_5_2],+ covers: ['2.5.2-pointer-cancellation'],+ appliesWhen: {+ condition: 'pressing this state is meant to run its action',+ test: facts => facts.operable,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject, activations}) => {+ const before = await activations();+ await harness.abortedPress(subject);+ if ((await activations()) !== before) {+ throw new Error(+ 'pressing the button and releasing away from it still ran the action: it fires on the way down, so a press cannot be taken back',+ );+ }+ },+ },+ {+ id: 'button.focus.reachable-and-escapable',+ outcome:+ 'Tab reaches the button, and Tab again leaves it, so a keyboard user can get to the action and carry on past it.',+ 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 button, so a keyboard user cannot get to this action`,+ );+ }+ await harness.press('Tab');+ if (await subject.isFocused()) {+ throw new Error(+ 'Tab did not move focus off the button, so a keyboard user is stuck on it',+ );+ }+ },+ },+ {+ id: 'button.unavailable.inert',+ outcome:+ 'A button reported as unavailable runs nothing when it is clicked — nor when Enter or Space is pressed on it, wherever it can still be focused.',+ // Astryx-primary. 4.1.2 requires unavailability to be EXPOSED — which+ // button.unavailable.exposed gates on — and says nothing about whether+ // the control then declines to act. What DOES require the behaviour is+ // a current Astryx record, so under AST-020 FR9 this gates on that.+ sources: [FAMILY_BUTTONS_FR3, APG_UNAVAILABLE, WCAG_4_1_2],+ covers: ['apg-interaction'],+ appliesWhen: {+ condition: 'the binding declares this state unavailable',+ test: facts => facts.unavailable,+ },+ evidenceLayer: 'real-browser',+ enforcement: 'required',+ run: async ({harness, subject, facts, activations}) => {+ const before = await activations();+ await harness.click(subject, {ignoreAvailability: true});+ if ((await activations()) !== before) {+ throw new Error(+ 'the button is reported as unavailable, but clicking it ran the action anyway',+ );+ }+ // The keyboard half exists only for a state a keyboard can reach. A+ // natively disabled button is out of the tab sequence, so there is no+ // "press Enter on it" to prove, and claiming one would report an+ // observation nobody made.+ if (!facts.focusable) {+ return;+ }+ // Past here the binding has DECLARED this state focusable — the usual+ // way to keep the reason for unavailability discoverable. A state+ // that then cannot take focus has broken its own declaration, and+ // reporting a pass would hide that behind the very check meant to+ // catch it.+ await subject.focus();+ if (!(await subject.isFocused())) {+ throw new Error(+ 'this state is declared focusable so its reason stays reachable, but it cannot take focus — so a keyboard user can neither read why it is unavailable nor reach it to confirm it refuses to act',+ );+ }+ for (const key of ['Enter', 'Space'] as const) {+ await harness.press(key);+ if ((await activations()) !== before) {+ throw new Error(+ `the button is reported as unavailable, but pressing ${key} on it ran the action anyway`,+ );+ }+ }+ },+ },+ ],++ // Every completeness dimension this pattern does not own, and who does.+ // A dimension answered neither here nor by an expectation's `covers` list is+ // reported by `unansweredDimensions` and asserted empty by this pattern's+ // suite (AST-020 FR5).+ exemptions: {+ '1.1.1-non-text-content': {+ owner: 'the binding component',+ verifiedBy:+ "the component's own suite (an icon-only button names itself with aria-label and hides its glyph) and the repository axe audit, `pnpm a11y:audit`",+ reason:+ 'The pattern owns one control node. Which decorative graphics a binding paints inside it, and whether each is hidden, is a per-component composition fact this contract never sees.',+ },+ '1.3.2-meaningful-sequence': {+ owner: 'the composing page',+ verifiedBy: "the component's DOM-order tests and page-level review",+ reason:+ 'A button is a single control; the order it is read in relative to other content is decided by whatever composes it.',+ },+ '1.4.1-use-of-color': {+ owner: 'the binding component and the theme',+ verifiedBy:+ "the component's forced-colors suite and the repository visual gate",+ reason:+ 'WCAG is explicit that exposure to assistive technology contributes nothing here: "even if information that is conveyed by color differences is appropriately conveyed to assistive technologies, it does not necessarily pass this criterion". It is entirely about what a sighted person who cannot distinguish two colours can see, which is a pixel fact no layer this contract observes can read.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'the binding component and the theme',+ verifiedBy:+ 'the repository axe audit, `pnpm a11y:audit`, over the component stories, plus the visual gate',+ reason:+ 'Contrast is measured from resolved rendered colours over a real backdrop, which is the axe and visual layer rather than the accessibility tree.',+ },+ '1.4.11-non-text-contrast': {+ owner: 'the binding component and the theme',+ verifiedBy:+ 'the repository axe audit, `pnpm a11y:audit`, plus the visual gate',+ reason:+ "A button's boundary, its icon, and its focus indicator are painted surfaces; their contrast is a rendered-colour measurement this contract cannot make.",+ },+ '2.4.2-page-titled': {+ owner: 'the page',+ verifiedBy:+ 'page-level review and the application that hosts the control',+ reason:+ 'A component rendered in isolation owns no document title and cannot supply one.',+ },+ '2.4.3-focus-order': {+ owner: 'the composing page',+ verifiedBy:+ 'page-level review; this contract proves only that the button is one reachable stop that focus can also leave',+ reason:+ 'Order is a property of the sequence a page builds, not of a single focus stop.',+ },+ '2.4.4-link-purpose': {+ owner: 'the link pattern and caller content',+ verifiedBy:+ 'review of any link a caller places near the control, and the link pattern for a button-styled element that adopts link semantics',+ reason:+ 'This contract covers command buttons. An element rendered as a link — an Astryx button given `href` — adopts link semantics, and the APG is explicit that the two are distinctly different functions.',+ },+ '2.4.6-headings-and-labels': {+ owner: 'caller content and component review',+ verifiedBy:+ 'review of the label text against the action it performs; button.name.exposed proves a name exists, not that "Save changes" beats "OK"',+ reason:+ 'Whether a label describes its purpose is a judgement about wording that no runtime layer can make.',+ coversRemainderOnly: true,+ },+ '2.4.7-focus-visible': {+ owner:+ 'the interaction-modality architecture record and the binding component',+ verifiedBy:+ "the repository visual gate and the component's own focus-ring styling",+ reason:+ 'A focus indicator is a painted result, so proving it means comparing pixels, which is the visual layer.',+ },+ '2.4.11-focus-not-obscured': {+ owner: 'the composing page',+ verifiedBy:+ 'page-level and overlay review, plus the repository modal-close visibility guard',+ reason:+ 'Whether something covers a focused control depends on what else the page renders over it.',+ },+ '2.5.8-target-size': {+ owner: 'the binding component and the composing page',+ verifiedBy:+ "the repository axe audit's `target-size` rule, which applies WCAG 2.2's spacing exception across neighbouring targets",+ reason:+ 'The exception that decides most real buttons depends on the clearance between a target and its neighbours, which a binding rendered on its own cannot see.',+ },+ '3.1.1-language-of-page': {+ owner: 'the page',+ verifiedBy:+ 'page-level review and the application that hosts the control',+ reason:+ 'A component rendered in isolation owns no document language and cannot supply one.',+ },+ '3.2.4-consistent-identification': {+ owner: 'the design system',+ verifiedBy:+ 'this shared contract itself: every component that adopts the pattern binds to the same expectations, so repeated buttons are identified the same way',+ reason:+ 'Consistency is a property of the whole set of adopters, which one binding cannot demonstrate.',+ },+ '3.2.2-on-input': {+ owner: 'the caller, for what its own handler does',+ verifiedBy:+ 'integration and page-level review of what a caller does in response to the press',+ reason:+ 'Not part-encoded, and deliberately so: 3.2.2 does not reach a button at all. It governs "changing the setting of any user interface component", and its Understanding text draws the line outright — "checking a checkbox, entering text into a text field, or changing the selected option in a list control changes its setting, but activating a link or a button does not". A button has no setting. What a CALLER does in response to a press can change the context, and that is the caller\'s to warn about.',+ },+ '3.3.2-labels-or-instructions': {+ owner: 'the composing form and caller content',+ verifiedBy: 'form-level review of the instructions around the control',+ reason:+ '3.3.2 is about labels and instructions "when content requires user input" — what a form tells someone about what to enter. A command button collects no input, and proving the control has a name is a different fact from a form saying what is expected.',+ },+ '3.3.1-error-identification': {+ owner: 'the binding component and the composing form',+ verifiedBy: "the component's own status-message tests and form review",+ reason:+ 'A command button reports no validation state of its own. 3.3.1 is satisfied in text by whatever describes the error, which is composed around the button rather than being part of it.',+ },+ '4.1.3-status-messages': {+ owner:+ 'the binding component, and the assistive-technology verification record for the announcement itself',+ verifiedBy:+ "the component's own live-region regression test, plus real-AT evidence under `docs/specs/AST-009/spec.md` whenever a change claims what is announced",+ reason:+ 'A status message is composed around the button rather than being part of the control, and whether it is announced is a real-AT claim no automated layer here can settle.',+ },+ 'forced-colors': {+ owner: 'the binding component and the theme',+ verifiedBy:+ "the component's forced-colors suite over the compiled CSS, plus manual review under Windows High Contrast",+ reason:+ 'Forced-colors output is a paint result; this contract observes semantics and behaviour, not paint.',+ },+ 'reduced-motion': {+ owner: 'the binding component and the theme',+ verifiedBy:+ "the component's `prefers-reduced-motion` guard and the repository visual gate",+ reason:+ 'Motion is a rendered result over time, and no layer this contract observes can watch it.',+ },+ 'at-facing-strings': {+ owner: 'the binding component',+ verifiedBy:+ 'the repository i18n catalog check and review of the strings a component renders for assistive technology',+ reason:+ 'Translation is a source-level concern: the rendered result this contract observes looks the same whichever language the string is in, so a lint-layer check is the only one that can see an untranslated string.',+ },+ },+ });diff --git a/internal/a11y-spec/src/patterns/switch.ts b/internal/a11y-spec/src/patterns/switch.tsindex a480275253..f195b44a7b 100644--- a/internal/a11y-spec/src/patterns/switch.ts+++ b/internal/a11y-spec/src/patterns/switch.ts@@ -31,6 +31,7 @@ import {type PatternContract,type WcagCriterion,} from '../contract';+import {saysInOrder, spokenWords} from '../spoken';const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/switch/';const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';@@ -193,47 +194,6 @@ function collapse(value: string): string {return value.toLowerCase().replace(/\s+/g, ' ').trim();}-/**- * The words of a label, as a speech-input user would say them.- *- * Exported: a binding comparing its own state inventory against the page needs- * the same notion of "the label's words" this contract uses, or the two would- * disagree about a label the component renders with a decorative separator.- *- * WCAG 2.5.3 is about words: its Understanding text asks that "the words which- * visually label a component are also the words associated with the component- * programmatically". Punctuation is not spoken, and Astryx renders a required- * marker as "Label ∙ Required" visually while the name computes as "Label- * Required" — the same words, one decorative separator apart. Comparing raw- * strings would report that as a failure, which would be wrong.- */-export function spokenWords(value: string): readonly string[] {- return collapse(value)- .replace(/[^\p{L}\p{N}]+/gu, ' ')- .split(' ')- .filter(word => word !== '');-}--/**- * Whether `whole` says `part`'s words, in order and unbroken.- *- * A substring test would be wrong here: "Sync" is a substring of "Syncing- * photos" but a speech-input user saying "Sync" is not saying the label. Words- * are compared whole, and their order is kept.- *- */-function saysInOrder(- whole: readonly string[],- part: readonly string[],-): boolean {- if (part.length === 0) {- return true;- }- return whole.some((_, index) =>- part.every((word, offset) => whole[index + offset] === word),- );-}-/*** Turn the switch and turn it back, checking the exposed state after each move.* Half a round trip is not the outcome: a control that turns on and cannot turndiff --git a/internal/a11y-spec/src/run.ts b/internal/a11y-spec/src/run.tsindex b73366e820..e99b104e66 100644--- a/internal/a11y-spec/src/run.ts+++ b/internal/a11y-spec/src/run.ts@@ -116,6 +116,14 @@ export interface RunBindingOptions<Facts> {readonly mount: () => Promise<Harness>;/** Unmount between expectations. */readonly unmount?: () => Promise<void> | void;+ /**+ * How many times this binding's action has run since the current mount.+ *+ * Required by any pattern whose expectations read it — a button's activation+ * leaves no trace on the button, so only the binding can count it. Omitting+ * it where the pattern needs it is a binding fault and fails loudly.+ */+ readonly activations?: () => Promise<number>;/*** Run only these expectation ids. Used by the contract's own mutation proof,* which asks one expectation at a time whether it notices its outcome being@@ -125,6 +133,19 @@ export interface RunBindingOptions<Facts> {readonly knownFailures?: readonly KnownFailure[];}+/**+ * Thrown when an expectation reads something only the binding can supply and+ * the binding did not supply it. A binding fault, not a contract result: it+ * escapes `runBinding` rather than being recorded as a failure, because the+ * outcome was never actually tested.+ */+export class MissingBindingCapability extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'MissingBindingCapability';+ }+}+function messageOf(error: unknown): string {return error instanceof Error ? error.message : String(error);}@@ -203,8 +224,20 @@ export async function runBinding<Facts>(notApplicable: reason => {throw new NotApplicableHere(reason);},+ activations: async () => {+ if (options.activations == null) {+ throw new MissingBindingCapability(+ `${expectation.id} counts how many times the action ran, but this binding supplies no activation count`,+ );+ }+ return options.activations();+ },});} catch (error) {+ if (error instanceof MissingBindingCapability) {+ // Never a contract result: the outcome was not tested at all.+ throw error;+ }if (error instanceof NotApplicableHere) {notApplicableReason = error.message;} else {diff --git a/internal/a11y-spec/src/spoken.ts b/internal/a11y-spec/src/spoken.tsnew file mode 100644index 0000000000..7b30446a41--- /dev/null+++ b/internal/a11y-spec/src/spoken.ts@@ -0,0 +1,48 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file spoken.ts+ * @input None (pure functions)+ * @output `spokenWords` and `saysInOrder` — how this package compares a label a+ * person can read against the name a browser computes.+ * @position Shared by every pattern that encodes WCAG 2.5.3, and by the+ * bindings that check their own state inventory against the page. One rule,+ * one implementation: two copies of "does the name contain the label" would+ * be free to drift, and the day they disagreed neither would be wrong on its+ * own terms.+ */++/**+ * The words of a label, as a speech-input user would say them.+ *+ * WCAG 2.5.3 is about words: its Understanding text asks that "the words which+ * visually label a component are also the words associated with the component+ * programmatically", and notes that "differences in capitalization and+ * punctuation are not relevant". So case and punctuation are dropped, and what+ * is left is what somebody would actually say.+ */+export function spokenWords(value: string): readonly string[] {+ return value+ .toLowerCase()+ .replace(/[^\p{L}\p{N}]+/gu, ' ')+ .split(' ')+ .filter(word => word !== '');+}++/**+ * Whether `whole` says `part`'s words, in order and unbroken.+ *+ * A substring test would be wrong here: "Sync" is a substring of "Syncing+ * photos", but a speech-input user saying "Sync" is not saying that label.+ */+export function saysInOrder(+ whole: readonly string[],+ part: readonly string[],+): boolean {+ if (part.length === 0) {+ return true;+ }+ return whole.some((_, index) =>+ part.every((word, offset) => whole[index + offset] === word),+ );+}diff --git a/packages/core/src/Button/Button.test.tsx b/packages/core/src/Button/Button.test.tsxindex 0618b3875c..e5bc78267b 100644--- a/packages/core/src/Button/Button.test.tsx+++ b/packages/core/src/Button/Button.test.tsx@@ -17,9 +17,14 @@ import {Badge} from '../Badge/Badge';import {InternationalizationProvider} from '../i18n';describe('Button', () => {+ // Retained, narrowed: the shared contract proves the ROLE and the accessible+ // NAME in a real engine (button.role.exposed, button.name.exposed), which is+ // strictly stronger than asserting them here. What stays is the part it does+ // not own — that Button renders `label` as text a person can read, rather+ // than only as an accessible name.it('renders label as visible text', () => {render(<Button label="Click me" />);- expect(screen.getByRole('button', {name: 'Click me'})).toBeInTheDocument();+ expect(screen.getByRole('button')).toHaveTextContent('Click me');});it('renders children instead of label when provided', () => {@@ -42,7 +47,11 @@ describe('Button', () => {expect(screen.getByRole('button')).toBeInTheDocument();});- it('renders icon-only button with aria-label', () => {+ // Retained, narrowed: the shared contract proves an icon-only button HAS an+ // accessible name, computed by a real engine. What stays is Button's own+ // mapping — `isIconOnly` routes `label` to `aria-label` instead of to text,+ // and the icon is still rendered.+ it('maps label to aria-label and keeps the icon when icon-only', () => {render(<Buttonlabel="Settings"@@ -50,8 +59,9 @@ describe('Button', () => {isIconOnly/>,);- const button = screen.getByRole('button', {name: 'Settings'});+ const button = screen.getByRole('button');expect(button).toHaveAttribute('aria-label', 'Settings');+ expect(button).not.toHaveTextContent('Settings');expect(screen.getByTestId('icon')).toBeInTheDocument();});diff --git a/packages/core/src/Button/__tests__/Button.a11y.chromium.spec.ts b/packages/core/src/Button/__tests__/Button.a11y.chromium.spec.tsnew file mode 100644index 0000000000..ecffa105f8--- /dev/null+++ b/packages/core/src/Button/__tests__/Button.a11y.chromium.spec.ts@@ -0,0 +1,336 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Button.a11y.chromium.spec.ts+ * @input Uses @playwright/test, @astryxdesign/a11y-spec (the button contract,+ * the Chromium harness, the static Storybook server), and the checked-in+ * ButtonA11y stories+ * @output The real-browser lane of every binding to the shared button pattern:+ * computed role, name and description, native activation by pointer, Enter+ * and Space, pointer cancellation, tab reachability, and inertness.+ * @position The half of the binding jsdom cannot honestly reach+ * (`docs/specs/AST-013/spec.md`: a browser claim is made in a browser).+ *+ * Each state drives a checked-in story rather than a page this file builds, so+ * the reproduction path for any failure is a URL a person can open+ * (`docs/specs/AST-009/spec.md` FR30). Each story counts its own activations,+ * which is what the contract reads through the binding's `activations()` seam —+ * a button's action leaves no trace on the button itself.+ *+ * SYNC: States live in ./Button.a11y.states.ts, known failures in+ * ./Button.a11y.known-failures.ts, both shared with the jsdom lane.+ */++import {expect, test, type CDPSession, type Page} from '@playwright/test';+import {+ BUTTON_PATTERN,+ blockingResults,+ formatFailures,+ formatReport,+ neverExercised,+ runBinding,+ spokenWords,+ summarize,+ 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 {BUTTON_KNOWN_FAILURES} from './Button.a11y.known-failures';+import {+ BUTTON_BINDING_STATES,+ BUTTON_PATTERN_EXCLUSIONS,+ type ButtonBindingRow,+ type ButtonBindingState,+} from './Button.a11y.states';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++function storyUrl(storyId: string): string {+ return `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story`;+}++/** Load the story this state names and wait for its control to exist. */+async function mountState(page: Page, state: ButtonBindingRow): Promise<void> {+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});+ await holdMotionStill(page);+ await page+ .locator('#storybook-root')+ .getByRole('button')+ .first()+ .waitFor({state: 'attached'});+}++/**+ * How many times this story's own handler has run.+ *+ * The story publishes the count as an attribute, so this reads a fact the story+ * renders rather than instrumenting the page from the test — which means a+ * person opening the story sees the same number the contract does.+ */+async function activationsOn(page: Page): Promise<number> {+ const raw = await page+ .locator('[data-a11y-activations]')+ .first()+ .getAttribute('data-a11y-activations');+ return Number(raw ?? '0');+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: ButtonBindingRow,+): Promise<BindingResult> {+ return runBinding({+ contract: BUTTON_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: BUTTON_KNOWN_FAILURES,+ // Reload per expectation: each one starts from the state the story renders,+ // not from whatever the previous expectation left behind.+ mount: async () => {+ await mountState(page, state);+ return createChromiumHarness({+ page,+ subject: page.locator('#storybook-root').getByRole('button').first(),+ cdp,+ });+ },+ activations: async () => activationsOn(page),+ });+}++/**+ * Whether the page renders exactly the label the inventory claims, word for+ * word — a prefix test would accept "Save" for "Save changes" and let a+ * half-written entry sit here unnoticed.+ */+function namesTheSameLabel(rendered: string, claimed: string): boolean {+ const words = spokenWords(rendered);+ const expected = spokenWords(claimed);+ return (+ words.length === expected.length &&+ words.every((word, index) => word === expected[index])+ );+}++/**+ * The inventory AST-021 FR2 asks for, checked against the page rather than+ * trusted. Deliberately NOT part of the shared contract: a wrong entry here is a+ * stale inventory, and reporting it as a WCAG 2.5.3 failure would put a metadata+ * typo and a real accessibility defect in the same bucket.+ */+test('the state inventory describes the labels the page actually renders', async ({+ page,+}) => {+ test.setTimeout(3 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const wrong: string[] = [];+ for (const state of BUTTON_BINDING_STATES) {+ await mountState(page, state);+ const harness = createChromiumHarness({+ page,+ subject: page.locator('#storybook-root').getByRole('button').first(),+ cdp,+ });+ const rendered = await (await harness.subject()).visibleLabelText();+ const matches =+ state.visibleLabel == null+ ? rendered == null+ : rendered != null && namesTheSameLabel(rendered, state.visibleLabel);+ if (!matches) {+ wrong.push(+ `${state.id}: inventory says ${JSON.stringify(state.visibleLabel)}, page renders ${JSON.stringify(rendered)}`,+ );+ }+ }+ expect(wrong).toEqual([]);+});++/**+ * Every applicability fact, checked against the page.+ *+ * An applicability fact can switch a REQUIRED expectation off — declare a state+ * available and `unavailable.inert` never runs; declare it unfocusable and the+ * keyboard outcomes never run. So a binding that described itself wrongly could+ * quietly opt out of the gates that matter most, and nothing else in this+ * system would notice: the contract reads facts, it does not audit them.+ *+ * A mismatch is a stale inventory unless the row lists it in+ * `declaredNotDelivered` with a known-failure record behind it. Listing a fact+ * that actually matches fails too, so the escape cannot be padded.+ */+test('every applicability fact matches what the page exposes', async ({+ page,+}) => {+ test.setTimeout(3 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const wrong: string[] = [];+ for (const state of BUTTON_BINDING_STATES) {+ await mountState(page, state);+ const subject = page.locator('#storybook-root').getByRole('button').first();+ const harness = createChromiumHarness({page, subject, cdp});+ const computed = await (await harness.subject()).computed();+ // Focusability means REACHABLE BY TAB, which is what the expectations mean+ // by it. `element.focus()` succeeds on a `tabindex="-1"` control no Tab will+ // ever reach, so measuring it that way would call a real gap a match.+ await page.evaluate(() => {+ (document.activeElement as HTMLElement | null)?.blur();+ });+ let reachedByTab = false;+ for (let step = 0; step < 10 && !reachedByTab; step += 1) {+ await page.keyboard.press('Tab');+ reachedByTab = await subject.evaluate(+ element => element.ownerDocument.activeElement === element,+ );+ }+ const observed: Record<'unavailable' | 'focusable' | 'described', boolean> =+ {+ unavailable: computed.disabled,+ focusable: reachedByTab,+ // Whether supporting text really is attached, which gates two required+ // expectations. `operable` has no counterpart here: it means "pressing+ // this is MEANT to act", and observing it would mean running the very+ // expectations this check exists to protect.+ described: computed.description.trim() !== '',+ };+ // `as const satisfies` keeps each row's literal type, so an optional field+ // is absent from the union member of a row that omits it. The interface is+ // the shape to read it through.+ const excused = (state as ButtonBindingState).declaredNotDelivered ?? [];+ for (const fact of ['unavailable', 'focusable', 'described'] as const) {+ const matches = state.facts[fact] === observed[fact];+ const excuse = excused.find(entry => entry.fact === fact);+ if (!matches && excuse == null) {+ wrong.push(+ `${state.id}: declares ${fact}=${state.facts[fact]}, page exposes ${observed[fact]} — either the declaration is stale, or this is a real gap that needs a known-failure record and a declaredNotDelivered entry`,+ );+ }+ if (matches && excuse != null) {+ wrong.push(+ `${state.id}: lists ${fact} as declared-but-not-delivered, yet the page delivers it — remove the entry and its known-failure record`,+ );+ }+ // An excuse with no record behind it is an unowned exception, which is+ // exactly what AST-021 FR8 prohibits.+ if (+ excuse != null &&+ !BUTTON_KNOWN_FAILURES.some(+ record =>+ record.expectation === excuse.owned && record.state === state.id,+ )+ ) {+ wrong.push(+ `${state.id}: excuses ${fact} against "${excuse.owned}", but no known-failure record names that expectation for this state`,+ );+ }+ }+ }+ expect(wrong).toEqual([]);+});++/**+ * The exclusions, checked in a real engine. An excluded part is only honestly+ * excluded while it really does present the other pattern's semantics — the day+ * one of these computes as a button, this contract owns it.+ */+test('every excluded part presents the semantics its exclusion claims', async ({+ page,+}) => {+ const cdp = await page.context().newCDPSession(page);+ const wrong: string[] = [];+ for (const exclusion of BUTTON_PATTERN_EXCLUSIONS) {+ await page.goto(storyUrl(exclusion.storyId), {waitUntil: 'load'});+ const subject = page+ .locator('#storybook-root')+ .getByRole(exclusion.presentsRole)+ .first();+ await subject.waitFor({state: 'attached'});+ const harness = createChromiumHarness({page, subject, cdp});+ const {role} = await (await harness.subject()).computed();+ if (role !== exclusion.presentsRole) {+ wrong.push(+ `${exclusion.id}: excluded as a ${exclusion.presentsRole}, but the browser computes "${role}"`,+ );+ }+ }+ expect(wrong).toEqual([]);+});++test('every expectation is exercised by at least one bound state', async ({+ page,+}) => {+ test.setTimeout(5 * 60 * 1000);+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of BUTTON_BINDING_STATES) {+ // One mount per STATE, not per expectation. The per-state tests above take+ // the expensive isolated path; this one only asks WHICH expectations ran,+ // never whether they passed, and that answer does not depend on starting+ // each expectation from a fresh page. Reloading 14 times per state instead+ // would turn a ten-second check into a ten-minute one for no extra truth.+ let mounted = false;+ results.push(+ await runBinding({+ contract: BUTTON_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: BUTTON_KNOWN_FAILURES,+ mount: async () => {+ if (!mounted) {+ await mountState(page, state);+ mounted = true;+ }+ return createChromiumHarness({+ page,+ subject: page+ .locator('#storybook-root')+ .getByRole('button')+ .first(),+ cdp,+ });+ },+ activations: async () => activationsOn(page),+ }),+ );+ }+ // An expectation that applies to nothing is not coverage, however green it+ // looks. This is the only place that can notice: the contract never sees the+ // states, so whether a condition matches a real one is a binding-side fact.+ expect(neverExercised(results)).toEqual([]);+});++for (const state of BUTTON_BINDING_STATES) {+ test(`${state.binding} [${state.id}] — ${state.summary}`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(BUTTON_PATTERN, [result]);+ // eslint-disable-next-line no-console -- the report is this run's artifact+ console.log(formatReport(report));++ expect(formatFailures(blockingResults([result]))).toBe('');+ // Every layer this contract assigns is observable here, so a state that+ // reports one as unrun means the harness lost a capability, not that the+ // outcome is covered.+ expect(report.unrunLayers).toEqual([]);+ expect(report.counts.unexpectedPass).toBe(0);+ });+}diff --git a/packages/core/src/Button/__tests__/Button.a11y.harnesses.tsx b/packages/core/src/Button/__tests__/Button.a11y.harnesses.tsxnew file mode 100644index 0000000000..918a95885b--- /dev/null+++ b/packages/core/src/Button/__tests__/Button.a11y.harnesses.tsx@@ -0,0 +1,47 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file Button.a11y.harnesses.tsx+ * @input Uses SideNavCollapseButton+ * @output The small consumer-side wiring some binding states need in order to+ * be rendered at all.+ * @position Kept beside the state table rather than inside it, so a row stays a+ * description of a state rather than a place stateful wiring accumulates.+ *+ * Carries the client directive because it holds state, like any component that+ * does — the repository's `check:use-client` gate applies to every file under+ * core's source, test infrastructure included.+ */++import {useState, type ReactNode} from 'react';+import {SideNavCollapseButton} from '../../SideNav/SideNavCollapseButton';++/**+ * The collapse control is controlled, so rendering one means owning its state.+ * This is the consumer's own wiring, and it is what the component is designed+ * to be given — a binding that pinned `isCollapsed` would be testing a control+ * nobody ships.+ */+export function CollapseHarness({+ label,+ onActivate,+}: {+ label?: string;+ onActivate: () => void;+}): ReactNode {+ const [isCollapsed, setIsCollapsed] = useState(false);+ return (+ <SideNavCollapseButton+ label={label}+ collapsible={{+ isCollapsed,+ onCollapsedChange: next => {+ setIsCollapsed(next);+ onActivate();+ },+ }}+ />+ );+}diff --git a/packages/core/src/Button/__tests__/Button.a11y.known-failures.ts b/packages/core/src/Button/__tests__/Button.a11y.known-failures.tsnew file mode 100644index 0000000000..d24fffa6c5--- /dev/null+++ b/packages/core/src/Button/__tests__/Button.a11y.known-failures.ts@@ -0,0 +1,106 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Button.a11y.known-failures.ts+ * @input Uses KnownFailure from @astryxdesign/a11y-spec+ * @output BUTTON_KNOWN_FAILURES — the exact outcomes a component that adopts the+ * button pattern does not deliver yet, each scoped to one expectation, one+ * binding, one state, and one public issue.+ * @position Recorded debt, not permission. `docs/specs/AST-021/spec.md` FR8–FR10+ * govern this: FR8 requires every record to name the expectation, binding,+ * state, user impact, evidence layer, issue, and reason; FR9 is the exact+ * gate — the expectation still RUNS and reports `known-failure`, never+ * `pass`, and "a different error, another state, a new expectation, or a+ * wider failure MUST fail". When the component is fixed the record stops+ * matching and the run reports `unexpected-pass`, which gates, so a fix+ * cannot land while leaving a stale record behind.+ *+ * A record is never a way to make a run green. It is a way to say, in public and+ * in one place, precisely what is broken and where the fix is being tracked.+ */++import type {KnownFailure} from '@astryxdesign/a11y-spec';++const BUSY_FOCUS_ISSUE = 'https://github.com/facebook/astryx/issues/4871';+const CARD_POINTER_ISSUE = 'https://github.com/facebook/astryx/issues/6132';++export const BUTTON_KNOWN_FAILURES: ReadonlyArray<KnownFailure> = [+ // ---- Button and IconButton go natively disabled while busy --------------+ // One defect, one record per component.+ // They are written out rather than generated, because a record has to name+ // exactly one thing that is broken — a loop would make it easy to widen this+ // later without anyone noticing.+ {+ expectation: 'button.focus.reachable-and-escapable',+ binding: 'Button',+ state: 'button-loading',+ evidenceLayer: 'real-browser',+ failureIncludes: 'never reached the button',+ userImpact:+ 'A keyboard user who activates Save and waits is dropped to the top of the document the moment the action starts, and the button leaves the tab sequence entirely — so they cannot get back to it, to see that it is busy or to interrupt it. The next Tab restarts from the beginning of the page.',+ issue: BUSY_FOCUS_ISSUE,+ reason:+ 'Button sets the native disabled attribute while a clickAction is pending. A natively disabled element is neither focusable nor a tab stop. Two fixes are already open against the issue; whichever lands turns this record into an unexpected pass.',+ },+ {+ expectation: 'button.focus.reachable-and-escapable',+ binding: 'IconButton',+ state: 'icon-button-loading',+ evidenceLayer: 'real-browser',+ failureIncludes: 'never reached the button',+ userImpact:+ 'The same drop from an icon button, where it is worse: an icon button is usually one of several in a row, so the user loses their place among them.',+ issue: BUSY_FOCUS_ISSUE,+ reason:+ 'IconButton is a thin wrapper over Button and inherits the behaviour exactly.',+ },++ {+ expectation: 'button.unavailable.inert',+ binding: 'Button',+ state: 'button-loading',+ evidenceLayer: 'real-browser',+ failureIncludes: 'declared focusable so its reason stays reachable',+ userImpact:+ 'The third face of the same defect: because the busy button cannot take focus, there is no way to confirm from the keyboard that it declines a second press — the user can neither reach it nor see why it is unavailable.',+ issue: BUSY_FOCUS_ISSUE,+ reason:+ 'Same native disabled attribute. Recorded separately because a record names exactly one outcome, and a fix that restored focus without keeping the button inert would satisfy one of these and not the other.',+ },+ {+ expectation: 'button.unavailable.inert',+ binding: 'IconButton',+ state: 'icon-button-loading',+ evidenceLayer: 'real-browser',+ failureIncludes: 'declared focusable so its reason stays reachable',+ userImpact: 'The same, from an icon button.',+ issue: BUSY_FOCUS_ISSUE,+ reason: 'Inherited from Button, as above.',+ },++ // ---- ClickableCard's role-bearing element cannot be clicked -------------+ {+ expectation: 'button.action.survives-an-aborted-press',+ binding: 'ClickableCard',+ state: 'clickable-card',+ evidenceLayer: 'real-browser',+ failureIncludes: 'a pointer press cannot land on this control',+ userImpact:+ 'The same defect seen from the other side: pointer cancellation cannot be demonstrated on a control no pointer press can land on. Recorded rather than reported green — a serene pass here would claim an outcome nobody observed.',+ issue: CARD_POINTER_ISSUE,+ reason:+ 'Same cause as the record above. It is a second record rather than a wider one because a known failure names exactly one outcome, and these two would be fixed and verified separately.',+ },+ {+ expectation: 'button.action.runs-on-pointer',+ binding: 'ClickableCard',+ state: 'clickable-card',+ evidenceLayer: 'real-browser',+ failureIncludes: 'a pointer could not reach this control',+ userImpact:+ "Anyone whose tooling acts on the accessible object rather than on pixels — a speech-input user saying the card's name, or assistive technology dispatching a click at the element it is told is the button — aims at a 1×1 control the card's own content paints over. A sighted mouse user is unaffected: they click the card surface, which handles it.",+ issue: CARD_POINTER_ISSUE,+ reason:+ 'ClickableCard deliberately splits the surface that takes the click from the hidden button that carries the role and name. Reconciling the two is a design-system decision, not a change this contract should make.',+ },+];diff --git a/packages/core/src/Button/__tests__/Button.a11y.renders.tsx b/packages/core/src/Button/__tests__/Button.a11y.renders.tsxnew file mode 100644index 0000000000..e87015db19--- /dev/null+++ b/packages/core/src/Button/__tests__/Button.a11y.renders.tsx@@ -0,0 +1,132 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Button.a11y.renders.tsx+ * @input Uses the five components that adopt the button pattern, and the id+ * unions from ./Button.a11y.states+ * @output BUTTON_STATE_RENDERS and BUTTON_EXCLUSION_RENDERS — how each row of+ * the binding inventory is rendered.+ * @position One definition of what each state IS, shared by the jsdom lane and+ * by the Storybook story for the same state, so the two cannot drift into+ * testing different things under the same name.+ *+ * Split from the inventory because that file must stay importable from+ * Playwright's plain Node runtime, which applies no StyleX transform, and+ * importing a component there would break the browser lane before it started.+ * The split costs nothing in drift: both maps are keyed by an id union, so a+ * state without a rendering does not compile.+ *+ * `activate` stands in for whatever handler a consumer would pass, and every+ * lane counts how many times it runs — a button's action leaves no trace on the+ * button, so counting the handler is the only honest way to ask whether+ * pressing it did anything.+ */++import type {ReactNode} from 'react';+import {TrashIcon} from '@heroicons/react/24/outline';+import {Button} from '../Button';+import {IconButton} from '../../IconButton/IconButton';+import {ClickableCard} from '../../ClickableCard/ClickableCard';+import {ChatSendButton} from '../../Chat/ChatSendButton';+import {CollapseHarness} from './Button.a11y.harnesses';+import type {ButtonExclusionId, ButtonStateId} from './Button.a11y.states';++export type StateRender = (activate: () => void) => ReactNode;++export const BUTTON_STATE_RENDERS: Record<ButtonStateId, StateRender> = {+ 'button-text': activate => <Button label="Save changes" onClick={activate} />,+ 'button-icon-only': activate => (+ <Button+ label="Delete conversation"+ isIconOnly+ icon={<TrashIcon />}+ onClick={activate}+ />+ ),+ 'button-composed-label': activate => (+ <Button label="Save changes" onClick={activate}>+ Save changes+ </Button>+ ),+ 'button-disabled': activate => (+ <Button label="Save changes" isDisabled onClick={activate} />+ ),+ 'button-disabled-with-tooltip': activate => (+ <Button+ label="Save changes"+ isDisabled+ tooltip="Fill in every required field first"+ onClick={activate}+ />+ ),+ 'button-loading': activate => (+ <Button label="Save changes" isLoading onClick={activate} />+ ),++ 'icon-button': activate => (+ <IconButton+ label="Delete conversation"+ icon={<TrashIcon />}+ onClick={activate}+ />+ ),+ 'icon-button-disabled': activate => (+ <IconButton+ label="Delete conversation"+ icon={<TrashIcon />}+ isDisabled+ onClick={activate}+ />+ ),+ 'icon-button-loading': activate => (+ <IconButton+ label="Delete conversation"+ icon={<TrashIcon />}+ isLoading+ onClick={activate}+ />+ ),++ 'clickable-card': activate => (+ <ClickableCard label="Open billing settings" onClick={activate}>+ <div>Billing</div>+ </ClickableCard>+ ),+ 'clickable-card-disabled': activate => (+ <ClickableCard label="Open billing settings" isDisabled onClick={activate}>+ <div>Billing</div>+ </ClickableCard>+ ),++ 'sidenav-collapse-icon': activate => (+ <CollapseHarness onActivate={activate} />+ ),+ 'sidenav-collapse-labelled': activate => (+ <CollapseHarness label="Collapse sidebar" onActivate={activate} />+ ),++ 'chat-send': activate => (+ <ChatSendButton isDisabled={false} onSend={activate} />+ ),+ 'chat-send-disabled': activate => (+ <ChatSendButton isDisabled onSend={activate} />+ ),+ 'chat-send-stop': activate => (+ <ChatSendButton isStopShown onStop={activate} />+ ),+};++export const BUTTON_EXCLUSION_RENDERS: Record<ButtonExclusionId, StateRender> =+ {+ 'button-as-link': activate => (+ <Button label="Read the guide" href="#guide" onClick={activate} />+ ),+ 'clickable-card-as-link': activate => (+ <ClickableCard+ label="Open billing settings"+ href="#billing"+ onClick={activate}>+ <div>Billing</div>+ </ClickableCard>+ ),+ };diff --git a/packages/core/src/Button/__tests__/Button.a11y.states.ts b/packages/core/src/Button/__tests__/Button.a11y.states.tsnew file mode 100644index 0000000000..63ef1a7601--- /dev/null+++ b/packages/core/src/Button/__tests__/Button.a11y.states.ts@@ -0,0 +1,317 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Button.a11y.states.ts+ * @input Uses ButtonStateFacts from @astryxdesign/a11y-spec+ * @output BUTTON_BINDING_STATES — every state of every component that adopts the+ * button pattern that can change what the pattern promises — and+ * BUTTON_PATTERN_EXCLUSIONS, the parts deliberately left to another pattern.+ * @position The binding inventory required before any assertion moves+ * (`docs/specs/AST-021/spec.md` FR2, FR4), and the single definition of what+ * each state IS.+ *+ * A state earns a row when it can change what the button pattern promises: a+ * different name source, a different operability, a different exposure of+ * unavailability, a different attached description. States that change only+ * appearance — variant, size, elevation, width, end content, theme — cannot, so+ * they stay in each component's own suite where that component owns them.+ *+ * This file is DATA ONLY — no JSX, no component imports. The Chromium lane runs+ * under Playwright's plain Node runtime, which does not apply the StyleX+ * transform, so importing a component here would break that lane before it+ * started. How each state is rendered lives beside it in+ * ./Button.a11y.renders.tsx, in a map TypeScript requires to be exhaustive: a+ * new row here is a compile error until it has a rendering.+ *+ * A row without a rendering is a compile error, so that half needs no+ * vigilance. The story export is the half that does.+ *+ * SYNC: Every row needs a named export in+ * - /apps/storybook/stories/ButtonA11y.stories.tsx+ * Caught at run time, not compile time: the Chromium binding navigates to+ * each row's `storyId`, so a missing or renamed export fails that lane.+ */++import type {ButtonStateFacts} from '@astryxdesign/a11y-spec';++/** The five components the queue binds to this pattern. */+export type ButtonBinding =+ | 'Button'+ | 'IconButton'+ | 'ClickableCard'+ | 'SideNavCollapseButton'+ | 'ChatSendButton';++/**+ * One row of the inventory, with its id kept as a literal. This — not the wider+ * `ButtonBindingState` interface — is what a lane should accept, so a row it is+ * handed can still index the render map.+ */+export type ButtonBindingRow = (typeof BUTTON_BINDING_STATES)[number];++/**+ * Every state id, as a union of the literals above. The render map is keyed by+ * this, so a row without a rendering — or a rendering for a state that does not+ * exist — is a compile error rather than something a test has to notice.+ */+export type ButtonStateId = (typeof BUTTON_BINDING_STATES)[number]['id'];++/** Every excluded part's id, for the same reason. */+export type ButtonExclusionId =+ (typeof BUTTON_PATTERN_EXCLUSIONS)[number]['id'];++export interface ButtonBindingState {+ /** Stable id, unique across bindings. Named by known-failure records. */+ readonly id: string;+ /** Which component this state belongs to. */+ readonly binding: ButtonBinding;+ /** What this state is, for the report and the test name. */+ readonly summary: string;+ /**+ * What the state is SUPPOSED to be. These select which expectations apply —+ * declaring a state unavailable or described turns those expectations on, and+ * they do not assert the negative when false.+ *+ * Intent, not observation, and the difference matters: a busy button is meant+ * to stay focusable, and two components do not deliver that. Recording what+ * those components actually do would make the expectations that catch it+ * not-applicable — a contract that quietly stops noticing a defect by+ * describing it. The gap is recorded in ./Button.a11y.known-failures.ts+ * instead, and the Chromium binding checks every fact against the page so a+ * declaration cannot drift from reality unnoticed.+ */+ readonly facts: ButtonStateFacts;+ /**+ * The label this state is expected to render where a person can read it, or+ * null when it renders none (an icon-only button).+ *+ * INVENTORY, not contract input. The shared 2.5.3 expectation reads the+ * rendered label itself and never consults this — otherwise a binding could+ * switch a criterion off by describing itself. This exists so the inventory+ * AST-021 FR2 asks for is checked against the page rather than trusted, and a+ * typo here is reported as a stale inventory, not as a standards failure.+ */+ readonly visibleLabel: string | null;+ /** The checked-in Storybook story the Chromium lane drives. */+ readonly storyId: string;+ /**+ * Facts this state deliberately declares as intent that the component does+ * NOT deliver today, each with the known-failure record that owns the gap.+ *+ * The fact-truth check reads this: an unlisted mismatch is a stale inventory+ * and fails, a listed one is recorded debt. Listing something that is not+ * actually mismatched also fails, so this cannot be padded.+ */+ readonly declaredNotDelivered?: ReadonlyArray<{+ readonly fact: 'unavailable' | 'focusable' | 'described';+ /** The known-failure record that owns this gap, by expectation id. */+ readonly owned: string;+ }>;+}++const OPERABLE: ButtonStateFacts = {+ operable: true,+ focusable: true,+ unavailable: false,+ described: false,+};++function facts(overrides: Partial<ButtonStateFacts> = {}): ButtonStateFacts {+ return {...OPERABLE, ...overrides};+}++export const BUTTON_BINDING_STATES = [+ // ---- Button -------------------------------------------------------------+ {+ id: 'button-text',+ binding: 'Button',+ summary: 'the default: a button named by the text a person can read',+ facts: facts(),+ visibleLabel: 'Save changes',+ storyId: 'a11y-button-pattern--button-text',+ },+ {+ id: 'button-icon-only',+ binding: 'Button',+ summary:+ 'an icon-only button, where the label is the accessible name and nothing else',+ facts: facts(),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--button-icon-only',+ },+ {+ id: 'button-composed-label',+ binding: 'Button',+ summary:+ 'children rendered as the visible content with a separate label as the accessible name — the composed case where the two can drift apart',+ facts: facts(),+ visibleLabel: 'Save changes',+ storyId: 'a11y-button-pattern--button-composed-label',+ },+ {+ id: 'button-disabled',+ binding: 'Button',+ summary: 'a hard-disabled button: unavailable, and out of the tab sequence',+ facts: facts({operable: false, focusable: false, unavailable: true}),+ visibleLabel: 'Save changes',+ storyId: 'a11y-button-pattern--button-disabled',+ },+ {+ id: 'button-disabled-with-tooltip',+ binding: 'Button',+ summary:+ 'a disabled button kept focusable by its tooltip, so the reason it is unavailable stays reachable',+ facts: facts({operable: false, unavailable: true, described: true}),+ visibleLabel: 'Save changes',+ storyId: 'a11y-button-pattern--button-disabled-with-tooltip',+ },+ {+ id: 'button-loading',+ binding: 'Button',+ summary:+ 'a button waiting on the action it started: the action is unavailable, and it is meant to stay focusable so the user can see that and interrupt it',+ // `focusable: true` is the declaration, and the component does not deliver+ // it — see the known-failure records. Declaring what the component does+ // instead would make the expectations that catch it not-applicable, which+ // is how a contract quietly stops noticing a defect.+ facts: facts({operable: false, unavailable: true}),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--button-loading',+ declaredNotDelivered: [+ {fact: 'focusable', owned: 'button.focus.reachable-and-escapable'},+ ],+ },++ // ---- IconButton ---------------------------------------------------------+ {+ id: 'icon-button',+ binding: 'IconButton',+ summary: 'an icon-only button named by its label alone',+ facts: facts(),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--icon-button-default',+ },+ {+ id: 'icon-button-disabled',+ binding: 'IconButton',+ summary: 'a disabled icon button',+ facts: facts({operable: false, focusable: false, unavailable: true}),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--icon-button-disabled',+ },+ {+ id: 'icon-button-loading',+ binding: 'IconButton',+ summary:+ 'an icon button waiting on the action it started, meant to stay focusable for the same reason',+ facts: facts({operable: false, unavailable: true}),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--icon-button-loading',+ declaredNotDelivered: [+ {fact: 'focusable', owned: 'button.focus.reachable-and-escapable'},+ ],+ },++ // ---- ClickableCard ------------------------------------------------------+ {+ id: 'clickable-card',+ binding: 'ClickableCard',+ summary:+ "a card whose whole surface performs an action, through the hidden button that carries the card's role and name",+ facts: facts(),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--clickable-card-default',+ },+ {+ id: 'clickable-card-disabled',+ binding: 'ClickableCard',+ summary: 'a disabled action card',+ facts: facts({operable: false, focusable: false, unavailable: true}),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--clickable-card-disabled',+ },++ // ---- SideNavCollapseButton ----------------------------------------------+ {+ id: 'sidenav-collapse-icon',+ binding: 'SideNavCollapseButton',+ summary:+ 'the default collapse control: icon-only, named by the direction it will move the sidebar',+ facts: facts(),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--sidenav-collapse-icon',+ },+ {+ id: 'sidenav-collapse-labelled',+ binding: 'SideNavCollapseButton',+ summary:+ 'the collapse control given a label of its own, which reaches the accessible name only — the component hardcodes icon-only, so no visible text is rendered (see the adjacent-findings note in the PR)',+ facts: facts(),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--sidenav-collapse-labelled',+ },++ // ---- ChatSendButton -----------------------------------------------------+ {+ id: 'chat-send',+ binding: 'ChatSendButton',+ summary: 'the composer send control, enabled and ready to send',+ facts: facts(),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--chat-send',+ },+ {+ id: 'chat-send-disabled',+ binding: 'ChatSendButton',+ summary: 'the send control with nothing to send',+ facts: facts({operable: false, focusable: false, unavailable: true}),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--chat-send-disabled',+ },+ {+ id: 'chat-send-stop',+ binding: 'ChatSendButton',+ summary:+ 'the same control turned into Stop while a response streams — a different action under a different name, and it must stay operable',+ facts: facts(),+ visibleLabel: null,+ storyId: 'a11y-button-pattern--chat-send-stop',+ },+ // `as const satisfies` rather than a `: ReadonlyArray<…>` annotation: the+ // annotation would widen every `id` to `string`, and ButtonStateId with it,+ // so the render map would silently accept a missing state and an invented+ // one alike. This keeps the literal ids AND still checks every row.+] as const satisfies ReadonlyArray<ButtonBindingState>;++/**+ * Parts that look like they belong to this pattern and deliberately do not,+ * with the reason and the pattern that owns each (AST-021 FR2 asks for the+ * inventory; an exclusion is part of the inventory, not an omission from it).+ *+ * The binding suites assert that each of these really does present the+ * semantics claimed here, so an exclusion cannot quietly become wrong.+ */+interface ButtonPatternExclusion {+ readonly id: string;+ readonly reason: string;+ readonly storyId: string;+ /** The role this part presents instead, checked by the binding suite. */+ readonly presentsRole: string;+}++export const BUTTON_PATTERN_EXCLUSIONS = [+ {+ id: 'button-as-link',+ reason:+ 'A Button given `href` renders an anchor and navigates. The APG is explicit that the two functions are distinctly different, so the link pattern owns it — including its own name and purpose requirements.',+ storyId: 'a11y-button-pattern--button-as-link',+ presentsRole: 'link',+ },+ {+ id: 'clickable-card-as-link',+ reason:+ 'A ClickableCard given `href` renders an anchor for the same reason.',+ storyId: 'a11y-button-pattern--clickable-card-as-link',+ presentsRole: 'link',+ },+] as const satisfies ReadonlyArray<ButtonPatternExclusion>;diff --git a/packages/core/src/Button/__tests__/Button.a11y.test.tsx b/packages/core/src/Button/__tests__/Button.a11y.test.tsxnew file mode 100644index 0000000000..739ffc230f--- /dev/null+++ b/packages/core/src/Button/__tests__/Button.a11y.test.tsx@@ -0,0 +1,167 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file Button.a11y.test.tsx+ * @input Uses @astryxdesign/a11y-spec (the button contract, the jsdom harness,+ * the runner), @testing-library/react, and the shared binding inventory with+ * its renderings+ * @output The jsdom lane of every binding to the shared button pattern.+ * @position Binds Button, IconButton, ClickableCard, SideNavCollapseButton, and+ * ChatSendButton to the reusable contract at the layers jsdom can honestly+ * observe. The accessibility-tree and real-browser layers are bound in+ * Button.a11y.chromium.spec.ts, and this lane reports them as unrun rather+ * than pretending markup proves them.+ *+ * What is NOT here is as deliberate as what is. Callback payloads, icon+ * resolution, composer wiring, elevation and styling stay in each component's+ * own suite: those are that component's contract, not the button pattern's+ * (`docs/specs/AST-021/spec.md` FR5).+ *+ * SYNC: States live in ./Button.a11y.states.ts, known failures in+ * ./Button.a11y.known-failures.ts, both shared with the Chromium lane.+ */++import {describe, expect, it} from 'vitest';+import {cleanup, render, screen} from '@testing-library/react';+import {+ BUTTON_PATTERN,+ blockingResults,+ createJsdomHarness,+ formatFailures,+ summarize,+ runBinding,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {BUTTON_KNOWN_FAILURES} from './Button.a11y.known-failures';+import {+ BUTTON_EXCLUSION_RENDERS,+ BUTTON_STATE_RENDERS,+} from './Button.a11y.renders';+import {+ BUTTON_BINDING_STATES,+ BUTTON_PATTERN_EXCLUSIONS,+ type ButtonBindingRow,+} from './Button.a11y.states';++/**+ * The control the pattern is about.+ *+ * Every binding resolves the same way — by role — and that is the point: a+ * ClickableCard puts its role and name on a visually hidden button inside the+ * card rather than on the card itself, and asking for the role finds it without+ * this test knowing anything about that structure.+ */+function subjectFor(): Element {+ return screen.getByRole('button', {hidden: true});+}++async function runState(state: ButtonBindingRow): Promise<BindingResult> {+ let activations = 0;+ return runBinding({+ contract: BUTTON_PATTERN,+ binding: state.binding,+ state: state.id,+ facts: state.facts,+ knownFailures: BUTTON_KNOWN_FAILURES,+ mount: async () => {+ activations = 0;+ render(+ BUTTON_STATE_RENDERS[state.id](() => {+ activations += 1;+ }),+ );+ return createJsdomHarness({subject: subjectFor()});+ },+ unmount: cleanup,+ activations: async () => activations,+ });+}++describe('the shared button pattern, jsdom lane', () => {+ it.each(+ BUTTON_BINDING_STATES.map(+ state =>+ [`${state.binding} [${state.id}]`, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ const result = await runState(state);+ expect(formatFailures(blockingResults([result]))).toBe('');+ });++ it('runs the DOM layer here and reports the higher layers as unrun', async () => {+ const results: BindingResult[] = [];+ for (const state of BUTTON_BINDING_STATES) {+ results.push(await runState(state));+ }+ const report = summarize(BUTTON_PATTERN, results);++ // Something actually ran, or this lane would prove nothing at all.+ expect(report.counts.pass).toBeGreaterThan(0);+ // And what it could not see is named, not quietly counted as covered.+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);+ expect(report.counts.unexpectedPass).toBe(0);+ });+});++describe('parts this pattern deliberately does not cover', () => {+ it('a Button given href presents link semantics, not a button', () => {+ render(BUTTON_EXCLUSION_RENDERS['button-as-link'](() => {}));+ // The exclusion is only honest while it stays true: if this ever renders a+ // button, the pattern owns it and the inventory is wrong.+ expect(screen.queryByRole('button')).toBeNull();+ expect(screen.getByRole('link', {name: 'Read the guide'})).toBeTruthy();+ cleanup();+ });++ it('a ClickableCard given href presents link semantics, not a button', () => {+ render(BUTTON_EXCLUSION_RENDERS['clickable-card-as-link'](() => {}));+ expect(screen.queryByRole('button')).toBeNull();+ expect(+ screen.getByRole('link', {name: 'Open billing settings'}),+ ).toBeTruthy();+ cleanup();+ });++ it('records a reason and a story for every exclusion', () => {+ expect(BUTTON_PATTERN_EXCLUSIONS.length).toBeGreaterThan(0);+ for (const exclusion of BUTTON_PATTERN_EXCLUSIONS) {+ expect(exclusion.reason.length, exclusion.id).toBeGreaterThan(40);+ expect(exclusion.storyId, exclusion.id).toContain(+ 'a11y-button-pattern--',+ );+ }+ });+});++describe('the state inventory', () => {+ it('names a distinct story for every state', () => {+ const ids = BUTTON_BINDING_STATES.map(state => state.storyId);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('covers every component the queue binds to this pattern', () => {+ const bound = new Set(BUTTON_BINDING_STATES.map(state => state.binding));+ expect([...bound].sort()).toEqual([+ 'Button',+ 'ChatSendButton',+ 'ClickableCard',+ 'IconButton',+ 'SideNavCollapseButton',+ ]);+ });++ it('renders in jsdom, and presents one button, for every state', () => {+ // The visible-label half of the inventory is checked in Chromium, not here:+ // whether a label is VISIBLE takes layout, and a loading Button keeps its+ // text in the DOM while hiding it, so textContent would answer the wrong+ // question.+ for (const state of BUTTON_BINDING_STATES) {+ expect(() => {+ render(BUTTON_STATE_RENDERS[state.id](() => {}));+ }, state.id).not.toThrow();+ expect(subjectFor(), state.id).toBeTruthy();+ cleanup();+ }+ });+});diff --git a/packages/core/src/IconButton/IconButton.test.tsx b/packages/core/src/IconButton/IconButton.test.tsxindex 56970fefb0..275c6ca20a 100644--- a/packages/core/src/IconButton/IconButton.test.tsx+++ b/packages/core/src/IconButton/IconButton.test.tsx@@ -15,12 +15,18 @@ import userEvent from '@testing-library/user-event';import {IconButton} from './IconButton';describe('IconButton', () => {- it('renders as an icon-only button with aria-label', () => {+ // Retained, narrowed: the shared button-pattern contract proves the role and+ // the computed accessible name in a real engine. What stays is IconButton's+ // own mapping — it always routes `label` to `aria-label`, and renders the+ // icon it was given.+ it('maps label to aria-label and renders the icon', () => {render(<IconButton label="Settings" icon={<span data-testid="icon">⚙</span>} />,);- const button = screen.getByRole('button', {name: 'Settings'});- expect(button).toHaveAttribute('aria-label', 'Settings');+ expect(screen.getByRole('button')).toHaveAttribute(+ 'aria-label',+ 'Settings',+ );expect(screen.getByTestId('icon')).toBeInTheDocument();});