An open source design system that's fully customizable and agent ready
TypeScript
test(a11y): add Table contract and bind Table (#7695)
Cindy Zhangbe8e7208cae3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 33da6f1b06..0c4430a133 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -2092,6 +2092,55 @@ jobs:retention-days: 30if-no-files-found: warn+ # The table contract's table role and name, header and cell roles, and+ # their place in the table's accessibility subtree are accessibility-tree+ # facts that jsdom cannot observe. Run the contract's own fixture proof and+ # the Table binding whenever Table source, the binding's stories, or the+ # contract changes. Its own --output directory; the JSON report is the+ # head-bound record, uploaded next.+ - name: Run Table accessibility contract+ id: table-contract+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}+ env:+ BASE_SHA: ${{ github.event.pull_request.base.sha }}+ PLAYWRIGHT_JSON_OUTPUT_FILE: table-contract/report.json+ run: |+ should_run=false+ # Table and the contract are matched by file name.+ # The helper comes from the base, since an older PR head lacks it.+ # Exit 1 means out of scope; 0 in scope; 2 unknown, so run.+ scope=2+ helper="$(mktemp)"+ if git fetch --quiet --no-tags --depth=1 origin "$BASE_SHA" \+ && git show "$BASE_SHA:.github/scripts/pr-scope-touches.sh" > "$helper"; then+ scope=0+ bash "$helper" "$BASE_SHA" \+ '^(internal/a11y-spec/src/patterns/table\.|packages/core/src/Table/|apps/storybook/stories/TableA11y)' || scope=$?+ fi+ if [ "$scope" != 1 ]; then+ should_run=true+ fi+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"+ if [ "$should_run" != true ]; then+ echo "Table and the table contract are not in PR scope; skipping table evidence."+ exit 0+ fi+ pnpm exec playwright test \+ internal/a11y-spec/src/patterns/table.chromium.spec.ts \+ packages/core/src/Table/__tests__/Table.a11y.chromium.spec.ts \+ --project chromium \+ --reporter list,json \+ --output table-contract-output++ - name: Upload Table accessibility contract evidence+ if: ${{ !cancelled() && steps.table-contract.outputs.should_run == 'true' }}+ uses: actions/upload-artifact@v7+ with:+ name: table-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: table-contract/+ retention-days: 30+ if-no-files-found: warn+# The toolbar contract's role and name, the controls inside it, the single# Tab stop, and the arrow (wrap, RTL, vertical) and Home/End movement are# accessibility-tree and real-browser facts that jsdom cannot observe. Rundiff --git a/apps/storybook/stories/TableA11y.stories.tsx b/apps/storybook/stories/TableA11y.stories.tsxnew file mode 100644index 0000000000..0a408490c4--- /dev/null+++ b/apps/storybook/stories/TableA11y.stories.tsx@@ -0,0 +1,31 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** One checked-in Storybook fixture for every Table binding state. */++import type {Meta, StoryObj} from '@storybook/react';+import {TABLE_A11Y_RENDERS} from '../../../packages/core/src/Table/__tests__/Table.a11y.renders';+import {TABLE_A11Y_STATES} from '../../../packages/core/src/Table/__tests__/Table.a11y.states';++function storyFor(id: (typeof TABLE_A11Y_STATES)[number]['id']): StoryObj {+ const state = TABLE_A11Y_STATES.find(candidate => candidate.id === id);+ if (state == null) {+ throw new Error(`no Table binding state "${id}"`);+ }+ return {+ name: `Table — ${state.id}`,+ render: () => TABLE_A11Y_RENDERS[state.id](),+ };+}++const meta: Meta = {+ title: 'a11y/Table pattern',+ tags: ['no-visual'],+ parameters: {layout: 'padded'},+};++export default meta;++export const DataColumns = storyFor('data-columns');+export const SortedDescending = storyFor('sorted-descending');+export const ChildrenRowHeadersRtl = storyFor('children-row-headers-rtl');+export const EmptyData = storyFor('empty-data');diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.mdindex 7eb22364b6..5d3985a574 100644--- a/internal/a11y-spec/README.md+++ b/internal/a11y-spec/README.md@@ -66,41 +66,43 @@ src/├── breadcrumb.* landmark, list-trail, current-page, and separator semantics├── combobox.* control identity, state, popup, and active-descendant semantics├── landmark.* one component-owned landmark region's role, name, and content boundary- └── link.* one available link's role, name, current state, focus, and activation+ ├── link.* one available link's role, name, current state, focus, and activation+ └── table.* a static data table's role and name and its header and cell roles; Table modules compose their own semantics```## The patterns-| Pattern | Adopted from | Bound by |-| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `radio-group` | [APG radio group](https://www.w3.org/WAI/ARIA/apg/patterns/radio/) | RadioList, SegmentedControl; role/state portions of DropdownMenu radio items |-| `checkbox` | [APG checkbox](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/) | CheckboxInput, CheckboxListItem, DropdownMenuCheckboxItem, SelectableCard |-| `switch` | [APG switch](https://www.w3.org/WAI/ARIA/apg/patterns/switch/) | Switch |-| `button` | [APG button](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | Button, IconButton, ClickableCard, SideNavCollapseButton, ChatSendButton |-| `toggle-button` | Toggle-button semantics in the [APG button pattern](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | ToggleButton, including standalone and grouped states |-| `text-input` | Native HTML controls and [WAI-ARIA textbox](https://www.w3.org/TR/wai-aria-1.2/#textbox) | TextInput, TextArea |-| `modal-dialog` | [APG dialog (modal)](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/) | Dialog |-| `status-message` | [WCAG 2.2 Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html) | Toast, FieldStatus, Spinner, ChatSystemMessage, ChatTypingIndicator, ProgressBar |-| `tabs` | [APG Tabs](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/) | Explicit `role="tablist"` TabList, Tab, and caller-authored tabpanels |-| `listbox` | [WAI-ARIA 1.2 Listbox](https://www.w3.org/TR/wai-aria-1.2/#listbox) and WCAG 2.2 semantics | Selector and MultiSelector popup listbox, group, and option parts |-| `spinbutton` | WCAG 2.2 semantics and [APG Spinbutton](https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/) | NumberInput |-| `disclosure` | [APG Disclosure](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/) | Standalone Collapsible triggers and their controlled content |-| `menu-button` | [APG Menu Button](https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/) required parts; the optional ArrowDown/ArrowUp opens Astryx ships are advisory | Anchored DropdownMenu and MoreMenu triggers: button role and name, `aria-haspopup="menu"`, `aria-expanded`, `aria-controls`, Enter/Space open on the first enabled item (advisory: ArrowDown on the first, ArrowUp on the last) |-| `menu` | [APG Menu and Menubar](https://www.w3.org/WAI/ARIA/apg/patterns/menubar/) menu; arrows (with wrap) and Home/End per AST-020 FR15; typeahead advisory | DropdownMenu pointer menu: named `menu`, item roles/names, `aria-checked`, `aria-disabled`, arrows with wrap, Home/End, Enter and Escape back to the trigger, Tab out (advisory: typeahead) |-| `toolbar` | [APG Toolbar](https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/); arrows (with wrap) and Home/End per AST-020 FR15 | Toolbar: named `toolbar`, `aria-orientation`, controls inside it, one Tab stop entering on the first enabled control, next/previous arrows (RTL-mirrored, Down/Up when vertical) with wrap, Home/End |-| `tooltip` | [APG Tooltip](https://www.w3.org/WAI/ARIA/apg/patterns/tooltip/) role and relationship per AST-020 FR15; WCAG 1.4.13; three rows advisory | Tooltip, useTooltip: `tooltip` role, `aria-describedby` and computed description, focus shows it (focus stays), Escape dismisses, hover keeps it over trigger and tooltip (advisory: blur hides, hover shows, pointer leaving hides) |-| `accordion` | [APG Accordion](https://www.w3.org/WAI/ARIA/apg/patterns/accordion/) required parts | CollapsibleGroup headers: button role and name, expanded state, controlled panel, Enter/Space, single-expansion sibling collapse, page Tab order, no arrow-key movement (single-expansion collapse, grouped Tab order, no arrow movement are advisory until `component:CollapsibleGroup` AR4 is current) |-| `breadcrumb` | WCAG 2.2 semantics; [APG Breadcrumb](https://www.w3.org/WAI/ARIA/apg/patterns/breadcrumb/) as context | Breadcrumbs landmarks, list trails, current-page state, and separators |-| `combobox` | WCAG 2.2 + [WAI-ARIA 1.2 Combobox](https://www.w3.org/TR/wai-aria-1.2/#combobox); APG as context | Selector trigger identity, state, popup, and active-descendant relationships |-| `landmark` | WCAG 2.2 semantics; [APG Landmark Regions](https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/) as context | LayoutHeader, LayoutContent, LayoutFooter, and LayoutPanel caller-declared landmarks |-| `slider` | [APG Slider](https://www.w3.org/WAI/ARIA/apg/patterns/slider/) role, values, name, orientation and keys | Slider thumbs: role, name, now/min/max, value text, orientation, arrows (RTL-mirrored), Page, Home/End, disabled keeps value |-| `progressbar` | WCAG 2.2 4.1.2 and [WAI-ARIA 1.2 progressbar](https://www.w3.org/TR/wai-aria-1.2/#progressbar); no APG pattern exists | ProgressBar, Lab CircularProgress: progressbar role and name, now/min/max, indeterminate claims no value, value text, no focusable descendants (target marks sit beside the bar) |-| `treeview` | [APG Tree View](https://www.w3.org/WAI/ARIA/apg/patterns/treeview/) structure and keyboard model | TreeList rows: tree/treeitem/group, aria-expanded, level/position, one Tab stop, Up/Down, Right/Left (RTL-mirrored), Home/End, Enter or Space, typeahead |-| `carousel` | [APG Carousel](https://www.w3.org/WAI/ARIA/apg/patterns/carousel/) and WCAG 2.2 semantics | Carousel container, slides, scroll area, and stable navigation-control focus |-| `alertdialog` | [APG Alert Dialog](https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/) role, references, modality, focus, dismissal | AlertDialog: alertdialog role and name, aria-describedby to the message, modal, Cancel first (advisory), Escape closes, click beside inert (advisory); modal mechanics stay with the modal-dialog contract through Dialog |-| `grid` | [APG Grid](https://www.w3.org/WAI/ARIA/apg/patterns/grid/) role, structure, name, selection and data-grid keys | Calendar month grids: grid role/name, row and gridcell/columnheader structure, one Tab stop, aria-selected/aria-multiselectable, arrows in reading order, Home/End, Enter selects (advisory) |-| `windowsplitter` | [APG Window Splitter](https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/) role, values, name, relationship and keys | ResizeHandle: separator role/name, now/min/max, orientation, aria-controls to the pane, arrows, Enter collapse/restore, Home/End, disabled keeps position |-| `link` | WCAG 2.2 semantics; [APG Link](https://www.w3.org/WAI/ARIA/apg/patterns/link/) role and Enter mechanics | Link, including LinkProvider and `as` router components |+| Pattern | Adopted from | Bound by |+| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `radio-group` | [APG radio group](https://www.w3.org/WAI/ARIA/apg/patterns/radio/) | RadioList, SegmentedControl; role/state portions of DropdownMenu radio items |+| `checkbox` | [APG checkbox](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/) | CheckboxInput, CheckboxListItem, DropdownMenuCheckboxItem, SelectableCard |+| `switch` | [APG switch](https://www.w3.org/WAI/ARIA/apg/patterns/switch/) | Switch |+| `button` | [APG button](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | Button, IconButton, ClickableCard, SideNavCollapseButton, ChatSendButton |+| `toggle-button` | Toggle-button semantics in the [APG button pattern](https://www.w3.org/WAI/ARIA/apg/patterns/button/) | ToggleButton, including standalone and grouped states |+| `text-input` | Native HTML controls and [WAI-ARIA textbox](https://www.w3.org/TR/wai-aria-1.2/#textbox) | TextInput, TextArea |+| `modal-dialog` | [APG dialog (modal)](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/) | Dialog |+| `status-message` | [WCAG 2.2 Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html) | Toast, FieldStatus, Spinner, ChatSystemMessage, ChatTypingIndicator, ProgressBar |+| `tabs` | [APG Tabs](https://www.w3.org/WAI/ARIA/apg/patterns/tabs/) | Explicit `role="tablist"` TabList, Tab, and caller-authored tabpanels |+| `listbox` | [WAI-ARIA 1.2 Listbox](https://www.w3.org/TR/wai-aria-1.2/#listbox) and WCAG 2.2 semantics | Selector and MultiSelector popup listbox, group, and option parts |+| `spinbutton` | WCAG 2.2 semantics and [APG Spinbutton](https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/) | NumberInput |+| `disclosure` | [APG Disclosure](https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/) | Standalone Collapsible triggers and their controlled content |+| `menu-button` | [APG Menu Button](https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/) required parts; the optional ArrowDown/ArrowUp opens Astryx ships are advisory | Anchored DropdownMenu and MoreMenu triggers: button role and name, `aria-haspopup="menu"`, `aria-expanded`, `aria-controls`, Enter/Space open on the first enabled item (advisory: ArrowDown on the first, ArrowUp on the last) |+| `menu` | [APG Menu and Menubar](https://www.w3.org/WAI/ARIA/apg/patterns/menubar/) menu; arrows (with wrap) and Home/End per AST-020 FR15; typeahead advisory | DropdownMenu pointer menu: named `menu`, item roles/names, `aria-checked`, `aria-disabled`, arrows with wrap, Home/End, Enter and Escape back to the trigger, Tab out (advisory: typeahead) |+| `toolbar` | [APG Toolbar](https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/); arrows (with wrap) and Home/End per AST-020 FR15 | Toolbar: named `toolbar`, `aria-orientation`, controls inside it, one Tab stop entering on the first enabled control, next/previous arrows (RTL-mirrored, Down/Up when vertical) with wrap, Home/End |+| `tooltip` | [APG Tooltip](https://www.w3.org/WAI/ARIA/apg/patterns/tooltip/) role and relationship per AST-020 FR15; WCAG 1.4.13; three rows advisory | Tooltip, useTooltip: `tooltip` role, `aria-describedby` and computed description, focus shows it (focus stays), Escape dismisses, hover keeps it over trigger and tooltip (advisory: blur hides, hover shows, pointer leaving hides) |+| `accordion` | [APG Accordion](https://www.w3.org/WAI/ARIA/apg/patterns/accordion/) required parts | CollapsibleGroup headers: button role and name, expanded state, controlled panel, Enter/Space, single-expansion sibling collapse, page Tab order, no arrow-key movement (single-expansion collapse, grouped Tab order, no arrow movement are advisory until `component:CollapsibleGroup` AR4 is current) |+| `breadcrumb` | WCAG 2.2 semantics; [APG Breadcrumb](https://www.w3.org/WAI/ARIA/apg/patterns/breadcrumb/) as context | Breadcrumbs landmarks, list trails, current-page state, and separators |+| `combobox` | WCAG 2.2 + [WAI-ARIA 1.2 Combobox](https://www.w3.org/TR/wai-aria-1.2/#combobox); APG as context | Selector trigger identity, state, popup, and active-descendant relationships |+| `landmark` | WCAG 2.2 semantics; [APG Landmark Regions](https://www.w3.org/WAI/ARIA/apg/patterns/landmarks/) as context | LayoutHeader, LayoutContent, LayoutFooter, and LayoutPanel caller-declared landmarks |+| `slider` | [APG Slider](https://www.w3.org/WAI/ARIA/apg/patterns/slider/) role, values, name, orientation and keys | Slider thumbs: role, name, now/min/max, value text, orientation, arrows (RTL-mirrored), Page, Home/End, disabled keeps value |+| `progressbar` | WCAG 2.2 4.1.2 and [WAI-ARIA 1.2 progressbar](https://www.w3.org/TR/wai-aria-1.2/#progressbar); no APG pattern exists | ProgressBar, Lab CircularProgress: progressbar role and name, now/min/max, indeterminate claims no value, value text, no focusable descendants (target marks sit beside the bar) |+| `treeview` | [APG Tree View](https://www.w3.org/WAI/ARIA/apg/patterns/treeview/) structure and keyboard model | TreeList rows: tree/treeitem/group, aria-expanded, level/position, one Tab stop, Up/Down, Right/Left (RTL-mirrored), Home/End, Enter or Space, typeahead |+| `carousel` | [APG Carousel](https://www.w3.org/WAI/ARIA/apg/patterns/carousel/) and WCAG 2.2 semantics | Carousel container, slides, scroll area, and stable navigation-control focus |+| `alertdialog` | [APG Alert Dialog](https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/) role, references, modality, focus, dismissal | AlertDialog: alertdialog role and name, aria-describedby to the message, modal, Cancel first (advisory), Escape closes, click beside inert (advisory); modal mechanics stay with the modal-dialog contract through Dialog |+| `grid` | [APG Grid](https://www.w3.org/WAI/ARIA/apg/patterns/grid/) role, structure, name, selection and data-grid keys | Calendar month grids: grid role/name, row and gridcell/columnheader structure, one Tab stop, aria-selected/aria-multiselectable, arrows in reading order, Home/End, Enter selects (advisory) |+| `windowsplitter` | [APG Window Splitter](https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/) role, values, name, relationship and keys | ResizeHandle: separator role/name, now/min/max, orientation, aria-controls to the pane, arrows, Enter collapse/restore, Home/End, disabled keeps position |+| `link` | WCAG 2.2 semantics; [APG Link](https://www.w3.org/WAI/ARIA/apg/patterns/link/) role and Enter mechanics | Link, including LinkProvider and `as` router components |+| `table` | [APG Table](https://www.w3.org/WAI/ARIA/apg/patterns/table/) roles and name per AST-020 FR15; no keyboard (the pattern defines none); modules add theirs | Table, in data-driven and children mode: table role and name, `row`/`columnheader`/`rowheader`/`cell` roles inside the table; the sort module adds `aria-sort` on sorted headers only |The `progressbar` contract owns what one rendered progress indicator exposes ineach state: the progressbar role and the operation's name (never a meter or a@@ -178,6 +180,25 @@ keep their member-owned semantics, and navigation aggregates such asbreadcrumbs, side and top navigation, citations, and clickable cards bindseparately.+The table contract owns a static data table: the table role, the label its+binding declares, the `row`, `columnheader`, `rowheader`, and `cell` roles of+the rows, headers, and cells the binding designates, and each header and cell's+place in a row of the table. `spec:AST-020/FR15` adopts the APG Table pattern's+role, name, and row and cell roles because Table already plays the table role;+the pattern defines no keyboard interaction, so none is adopted. Each Table+module brings its own accessibility semantics as a module contract owned beside+the module and composed onto the base with `composeTablePattern`, only for the+states a binding renders with that module: the sort module contract+(`packages/core/src/Table/plugins/sortable/__tests__/useTableSortable.a11y.ts`)+adds `aria-sort` on exactly the sorted column headers, and a later module (tree+or grid rows, for example) brings its semantics the same way. The first binding covers a labelled data-driven table, a table sorted+through `useTableSortable`, a composed right-to-left table named by a visible+heading with row headers, and the default empty state. Captions, spans, row and+column counts and indexes, and the rows and controls that selection, expansion,+grouping, and tree modules add stay with their modules and later bindings, and+the filter button and resize separator that sit inside header cells bind with+their modules; the Scroll region keeps its own browser evidence.+The `listbox` contract is a bounded semantic migration, not blanket APGinteraction adoption. Its first bindings cover 21 existing scenarios acrosssingle/multiple selection, disabled options, groups, filtering, custom content,diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.tsindex 8e1cab99df..4e4449c6c9 100644--- a/internal/a11y-spec/src/index.ts+++ b/internal/a11y-spec/src/index.ts@@ -176,5 +176,13 @@ export {type LinkCurrentToken,type LinkStateFacts,} from './patterns/link';+export {+ TABLE_AST_020_FR15,+ TABLE_PATTERN,+ composeTablePattern,+ tableApgRequirement,+ type TableModuleContract,+ type TableStateFacts,+} from './patterns/table';export {TOOLBAR_PATTERN, type ToolbarStateFacts} from './patterns/toolbar';export {TOOLTIP_PATTERN, type TooltipStateFacts} from './patterns/tooltip';diff --git a/internal/a11y-spec/src/patterns/table.chromium.spec.ts b/internal/a11y-spec/src/patterns/table.chromium.spec.tsnew file mode 100644index 0000000000..1e1b5f2bc9--- /dev/null+++ b/internal/a11y-spec/src/patterns/table.chromium.spec.ts@@ -0,0 +1,120 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Real-browser positive and mutation proof for the Table contract. */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {describeExpectation, requiredLayers} from '../contract';+import {checkAccessibilitySpec, type ExpectationResult} from '../check';+import {+ CHROMIUM_OBSERVES,+ createChromiumHarness,+ holdMotionStill,+} from '../harness/chromium';+import {TABLE_PATTERN} from './table';+import {+ CONFORMING_TABLE_FIXTURES,+ TABLE_CELL_SELECTOR,+ TABLE_COLUMN_HEADER_SELECTOR,+ TABLE_MUTATIONS,+ TABLE_ROW_HEADER_SELECTOR,+ TABLE_ROW_SELECTOR,+ TABLE_SUBJECT_SELECTOR,+ tableFixture,+ type TableFixture,+} from './table.fixtures';++function fixturePage(html: string): string {+ return `<!doctype html><html lang="en"><body>${html}</body></html>`;+}++async function results(+ page: Page,+ cdp: CDPSession,+ target: TableFixture,+ only?: readonly string[],+): Promise<readonly ExpectationResult[]> {+ const run = await checkAccessibilitySpec({+ spec: TABLE_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ only,+ mount: async () => {+ await page.setContent(fixturePage(target.html));+ await holdMotionStill(page);+ const related: Record<string, Locator> = {};+ const designate = (selector: string, prefix: string, count: number) => {+ const elements = page.locator(selector);+ for (let index = 0; index < count; index += 1) {+ related[`${prefix}-${index}`] = elements.nth(index);+ }+ };+ designate(TABLE_ROW_SELECTOR, 'row', target.facts.rows);+ designate(+ TABLE_COLUMN_HEADER_SELECTOR,+ 'column-header',+ target.facts.columnHeaders.length,+ );+ designate(+ TABLE_ROW_HEADER_SELECTOR,+ 'row-header',+ target.facts.rowHeaders.length,+ );+ designate(TABLE_CELL_SELECTOR, 'cell', target.facts.cells);+ return createChromiumHarness({+ page,+ cdp,+ subject: page.locator(TABLE_SUBJECT_SELECTOR),+ related,+ });+ },+ });+ return run.results;+}++test.describe('Table contract — conforming fixtures', () => {+ for (const id of CONFORMING_TABLE_FIXTURES) {+ test(`${id}: every applicable expectation passes`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const observed = await results(page, cdp, tableFixture(id));+ expect(+ observed+ .filter(+ result =>+ result.status !== 'pass' && result.status !== 'not-applicable',+ )+ .map(result => `${result.expectation}: ${result.detail ?? ''}`),+ ).toEqual([]);+ });+ }+});++test.describe('Table contract — deliberately violating fixtures', () => {+ for (const expectation of TABLE_PATTERN.expectations) {+ if (+ !requiredLayers(expectation).every(layer =>+ CHROMIUM_OBSERVES.includes(layer),+ )+ ) {+ continue;+ }+ for (const fixtureId of TABLE_MUTATIONS[expectation.id] ?? []) {+ test(`${describeExpectation(expectation)} — fails against ${fixtureId}`, async ({+ page,+ }) => {+ const cdp = await page.context().newCDPSession(page);+ const [result] = await results(page, cdp, tableFixture(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/table.fixtures.ts b/internal/a11y-spec/src/patterns/table.fixtures.tsnew file mode 100644index 0000000000..4c56634a66--- /dev/null+++ b/internal/a11y-spec/src/patterns/table.fixtures.ts@@ -0,0 +1,311 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Plain-HTML positive and mutation fixtures for the Table contract. */++import type {TableStateFacts} from './table';++export const TABLE_SUBJECT_SELECTOR = '[data-a11y-table]';+export const TABLE_COLUMN_HEADER_SELECTOR = '[data-a11y-table-column-header]';+export const TABLE_ROW_SELECTOR = '[data-a11y-table-row]';+export const TABLE_ROW_HEADER_SELECTOR = '[data-a11y-table-row-header]';+export const TABLE_CELL_SELECTOR = '[data-a11y-table-cell]';++export interface TableFixture {+ readonly id: string;+ readonly summary: string;+ readonly facts: TableStateFacts;+ readonly html: string;+}++const COLUMNS = ['Name', 'Role', 'Location'] as const;+const ROWS = [+ ['Ada', 'Engineer', 'London'],+ ['Grace', 'Admiral', 'Arlington'],+] as const;++interface Options {+ /** The table element's role attribute, or null for the native role. */+ readonly role?: string | null;+ /** `aria-label` on the table, or null for none. */+ readonly label?: string | null;+ /** Name the table from a visible heading through `aria-labelledby`. */+ readonly labelledBy?: string;+ /** An explicit role that overrides the column header cells' native role. */+ readonly columnHeaderRole?: string;+ /** An `aria-label` that replaces the second column header's name. */+ readonly columnHeaderRename?: string;+ /** An explicit role that overrides the first body row's native role. */+ readonly rowRole?: string;+ /** Render each body row's first cell as a row header. */+ readonly rowHeaders?: boolean;+ /** Element used for row header cells. */+ readonly rowHeaderTag?: 'th' | 'td';+ /** An `aria-label` that replaces the first row header's name. */+ readonly rowHeaderRename?: string;+ /** Render the designated data cell as a column header instead. */+ readonly cellAsHeader?: boolean;+ /** Designate a data cell that sits outside the table. */+ readonly cellOutside?: boolean;+ /**+ * Move one designated part into a second, separately labelled data table,+ * keeping its role and name, so only its place in the subject table is wrong.+ */+ readonly otherTable?: 'row' | 'column-header' | 'row-header' | 'cell';+}++function attr(name: string, value: string | null | undefined): string {+ return value == null ? '' : `${name}="${value}"`;+}++function html(options: Options = {}): string {+ const role = options.role ?? null;+ const label = options.label === undefined ? 'Team members' : options.label;+ const rowHeaderTag = options.rowHeaderTag ?? 'th';+ const heading =+ options.labelledBy == null+ ? ''+ : `<h2 id="a11y-table-heading">${options.labelledBy}</h2>`;+ const headers = COLUMNS.map((column, index) => {+ const role = attr('role', options.columnHeaderRole);+ const rename =+ index === 1 ? attr('aria-label', options.columnHeaderRename) : '';+ const designated =+ index === 2 && options.otherTable === 'column-header'+ ? ''+ : 'data-a11y-table-column-header';+ return `<th ${designated} scope="col" ${role} ${rename}>${column}</th>`;+ }).join('');+ const body = ROWS.map((row, rowIndex) => {+ const cells = row+ .map((value, cellIndex) => {+ if (options.rowHeaders && cellIndex === 0) {+ const scope = rowHeaderTag === 'th' ? 'scope="row"' : '';+ const rename =+ rowIndex === 0 ? attr('aria-label', options.rowHeaderRename) : '';+ const designated =+ rowIndex === 1 && options.otherTable === 'row-header'+ ? ''+ : 'data-a11y-table-row-header';+ return `<${rowHeaderTag} ${designated} ${scope} ${rename}>${value}</${rowHeaderTag}>`;+ }+ const designated =+ rowIndex === 0 &&+ cellIndex === 1 &&+ !options.cellOutside &&+ options.otherTable !== 'cell';+ if (designated && options.cellAsHeader) {+ return `<th data-a11y-table-cell scope="col">${value}</th>`;+ }+ return `<td ${designated ? 'data-a11y-table-cell' : ''}>${value}</td>`;+ })+ .join('');+ const role = rowIndex === 0 ? attr('role', options.rowRole) : '';+ const designated =+ rowIndex === 1 && options.otherTable === 'row'+ ? ''+ : 'data-a11y-table-row';+ return `<tr ${designated} ${role}>${cells}</tr>`;+ }).join('');+ const outside = options.cellOutside+ ? '<div data-a11y-table-cell>Engineer</div>'+ : '';+ const other = options.otherTable;+ // The second table keeps a header cell so the browser treats it as a data+ // table rather than a layout table; its moved part keeps its role and name.+ const otherTable =+ other == null+ ? ''+ : `+ <table aria-label="Other team">+ <thead><tr>${+ other === 'column-header'+ ? '<th data-a11y-table-column-header scope="col">Location</th>'+ : '<th scope="col">Team</th>'+ }<th scope="col">Note</th></tr></thead>+ <tbody><tr ${other === 'row' ? 'data-a11y-table-row' : ''}>${+ other === 'row-header'+ ? '<th data-a11y-table-row-header scope="row">Grace</th>'+ : '<td>Other</td>'+ }${+ other === 'cell'+ ? '<td data-a11y-table-cell>Engineer</td>'+ : '<td>Note</td>'+ }</tr></tbody>+ </table>`;+ return `+ ${heading}+ <table data-a11y-table ${attr('role', role)} ${attr('aria-label', label)} ${+ options.labelledBy == null ? '' : 'aria-labelledby="a11y-table-heading"'+ }>+ <thead><tr data-a11y-table-row>${headers}</tr></thead>+ <tbody>${body}</tbody>+ </table>+ ${outside}+ ${otherTable}+ `;+}++function facts(overrides: Partial<TableStateFacts> = {}): TableStateFacts {+ return {+ label: 'Team members',+ columnHeaders: [...COLUMNS],+ rows: 3,+ rowHeaders: [],+ cells: 1,+ ...overrides,+ };+}++const ROW_HEADERS = ROWS.map(row => row[0]);++export const TABLE_FIXTURES: readonly TableFixture[] = [+ {+ id: 'conforming-labelled',+ summary: 'a labelled data table with column headers and data cells',+ facts: facts(),+ html: html(),+ },+ {+ id: 'conforming-labelledby-row-headers',+ summary: 'a table named by a visible heading, with a row header per row',+ facts: facts({label: 'Crew roster', rowHeaders: ROW_HEADERS}),+ html: html({label: null, labelledBy: 'Crew roster', rowHeaders: true}),+ },+ {+ id: 'conforming-unlabelled',+ summary: 'a table whose binding declares no label',+ facts: facts({label: null}),+ html: html({label: null}),+ },+ {+ id: 'violating-role-grid',+ summary: 'a static table that claims the interactive grid role',+ facts: facts(),+ html: html({role: 'grid'}),+ },+ {+ id: 'violating-role-presentation',+ // Unlabelled: a global ARIA attribute such as aria-label makes the browser+ // ignore a presentational role, so a labelled table keeps its semantics.+ summary:+ 'an unlabelled table whose semantics are removed with role="presentation"',+ facts: facts(),+ html: html({role: 'presentation', label: null}),+ },+ {+ id: 'violating-name-missing',+ summary: 'a table that drops its declared label',+ facts: facts(),+ html: html({label: null}),+ },+ {+ id: 'violating-name-wrong',+ summary: 'a table exposing a different label',+ facts: facts(),+ html: html({label: 'Members'}),+ },+ {+ id: 'violating-column-header-cell',+ summary:+ 'column titles whose header role is overridden to an ordinary cell',+ facts: facts(),+ html: html({columnHeaderRole: 'cell'}),+ },+ {+ id: 'violating-column-header-name',+ summary: 'a column header whose computed name differs from its title',+ facts: facts(),+ html: html({columnHeaderRename: 'Column 2'}),+ },+ {+ id: 'violating-row-group',+ summary: 'a body row whose row role is overridden to a group',+ facts: facts(),+ html: html({rowRole: 'group'}),+ },+ {+ id: 'violating-row-other-table',+ summary: 'a designated row that belongs to a second table',+ facts: facts(),+ html: html({otherTable: 'row'}),+ },+ {+ id: 'violating-column-header-other-table',+ summary: 'a correctly named column header that belongs to a second table',+ facts: facts(),+ html: html({otherTable: 'column-header'}),+ },+ {+ id: 'violating-row-header-other-table',+ summary: 'a correctly named row header that belongs to a second table',+ facts: facts({rowHeaders: ROW_HEADERS}),+ html: html({rowHeaders: true, otherTable: 'row-header'}),+ },+ {+ id: 'violating-cell-other-table',+ summary: 'a data cell that belongs to a second table',+ facts: facts(),+ html: html({otherTable: 'cell'}),+ },+ {+ id: 'violating-row-header-td',+ summary: 'row titles rendered as ordinary data cells',+ facts: facts({rowHeaders: ROW_HEADERS}),+ html: html({rowHeaders: true, rowHeaderTag: 'td'}),+ },+ {+ id: 'violating-row-header-name',+ summary: 'a row header whose computed name differs from its title',+ facts: facts({rowHeaders: ROW_HEADERS}),+ html: html({rowHeaders: true, rowHeaderRename: 'Row 1'}),+ },+ {+ id: 'violating-cell-as-header',+ summary: 'a data value marked up as a column header',+ facts: facts(),+ html: html({cellAsHeader: true}),+ },+ {+ id: 'violating-cell-outside',+ summary: 'a data value rendered outside the table it belongs to',+ facts: facts(),+ html: html({cellOutside: true}),+ },+];++export const CONFORMING_TABLE_FIXTURES = TABLE_FIXTURES.filter(fixture =>+ fixture.id.startsWith('conforming-'),+).map(fixture => fixture.id);++export const TABLE_MUTATIONS: Readonly<Record<string, readonly string[]>> = {+ 'table.role.exposed': ['violating-role-grid', 'violating-role-presentation'],+ 'table.name.exposed': ['violating-name-missing', 'violating-name-wrong'],+ 'table.column-headers.exposed': [+ 'violating-column-header-cell',+ 'violating-column-header-name',+ 'violating-column-header-other-table',+ ],+ 'table.rows.exposed': [+ 'violating-row-group',+ 'violating-row-other-table',+ 'violating-cell-outside',+ ],+ 'table.row-headers.exposed': [+ 'violating-row-header-td',+ 'violating-row-header-name',+ 'violating-row-header-other-table',+ ],+ 'table.cells.exposed': [+ 'violating-cell-as-header',+ 'violating-cell-outside',+ 'violating-cell-other-table',+ ],+};++export function tableFixture(id: string): TableFixture {+ const fixture = TABLE_FIXTURES.find(candidate => candidate.id === id);+ if (fixture == null) {+ throw new Error(`unknown Table fixture "${id}"`);+ }+ return fixture;+}diff --git a/internal/a11y-spec/src/patterns/table.jsdom.test.ts b/internal/a11y-spec/src/patterns/table.jsdom.test.tsnew file mode 100644index 0000000000..58f4f55f2e--- /dev/null+++ b/internal/a11y-spec/src/patterns/table.jsdom.test.ts@@ -0,0 +1,209 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/** Contract self-tests for Table DOM expectations and completeness. */++import {afterEach, describe, expect, it} from 'vitest';+import {+ citeSource,+ describeExpectation,+ requiredLayers,+ unansweredDimensions,+} from '../contract';+import {checkAccessibilitySpec, type ExpectationResult} from '../check';+import {JSDOM_OBSERVES, createJsdomHarness} from '../harness/jsdom';+import {TABLE_PATTERN, composeTablePattern} from './table';+import {+ CONFORMING_TABLE_FIXTURES,+ TABLE_CELL_SELECTOR,+ TABLE_COLUMN_HEADER_SELECTOR,+ TABLE_MUTATIONS,+ TABLE_ROW_HEADER_SELECTOR,+ TABLE_ROW_SELECTOR,+ TABLE_FIXTURES,+ TABLE_SUBJECT_SELECTOR,+ tableFixture,+ type TableFixture,+} from './table.fixtures';++afterEach(() => document.body.replaceChildren());++async function resultsFor(target: TableFixture) {+ const container = document.createElement('div');+ document.body.append(container);+ const run = await checkAccessibilitySpec({+ spec: TABLE_PATTERN,+ binding: 'fixture',+ state: target.id,+ facts: target.facts,+ mount: async () => {+ container.innerHTML = target.html;+ const subject = container.querySelector(TABLE_SUBJECT_SELECTOR);+ if (subject == null) {+ throw new Error(`fixture "${target.id}" is missing its table`);+ }+ const related: Record<string, Element> = {};+ const designate = (selector: string, prefix: string) =>+ container.querySelectorAll(selector).forEach((element, index) => {+ related[`${prefix}-${index}`] = element;+ });+ designate(TABLE_ROW_SELECTOR, 'row');+ designate(TABLE_COLUMN_HEADER_SELECTOR, 'column-header');+ designate(TABLE_ROW_HEADER_SELECTOR, 'row-header');+ designate(TABLE_CELL_SELECTOR, 'cell');+ return createJsdomHarness({subject, related});+ },+ unmount: () => {+ container.innerHTML = '';+ },+ });+ return run.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;+}++const observableHere = TABLE_PATTERN.expectations.filter(expectation =>+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),+);++describe('Table contract — completeness', () => {+ it('answers every completeness dimension', () => {+ expect(unansweredDimensions(TABLE_PATTERN)).toEqual([]);+ });++ it('gives every expectation at least one deliberately violating fixture', () => {+ expect(+ TABLE_PATTERN.expectations+ .filter(+ expectation => (TABLE_MUTATIONS[expectation.id] ?? []).length === 0,+ )+ .map(expectation => expectation.id),+ ).toEqual([]);+ });++ it('has an expectation for every mutation it records', () => {+ const ids = new Set(+ TABLE_PATTERN.expectations.map(expectation => expectation.id),+ );+ expect(Object.keys(TABLE_MUTATIONS).filter(id => !ids.has(id))).toEqual([]);+ });++ it('makes every expectation required under AST-020 FR15 or WCAG 2.2', () => {+ expect(+ TABLE_PATTERN.expectations+ .filter(expectation => expectation.enforcement !== 'required')+ .map(expectation => expectation.id),+ ).toEqual([]);+ });++ it('adds no keyboard expectation to a static table', () => {+ expect(+ TABLE_PATTERN.expectations+ .filter(expectation => expectation.covers.includes('2.1.1-keyboard'))+ .map(expectation => expectation.id),+ ).toEqual([]);+ });+});++describe('Table contract — module composition', () => {+ const MODULE = {+ module: 'useExampleModule',+ scope: 'an example outcome.',+ expectations: [+ {+ ...TABLE_PATTERN.expectations[0]!,+ id: 'table.example.exposed',+ },+ ],+ };++ it('adds a module’s expectations to the base and keeps the base exemptions', () => {+ const composed = composeTablePattern(MODULE);+ expect(composed.pattern).toBe('table');+ expect(composed.expectations.map(expectation => expectation.id)).toEqual([+ ...TABLE_PATTERN.expectations.map(expectation => expectation.id),+ 'table.example.exposed',+ ]);+ expect(composed.exemptions).toEqual(TABLE_PATTERN.exemptions);+ expect(composed.scope).toContain('useExampleModule');+ });++ it('keeps module semantics out of the base contract', () => {+ expect(+ TABLE_PATTERN.expectations.map(expectation => expectation.id),+ ).not.toContain('table.example.exposed');+ });++ it('refuses a module expectation outside the table pattern', () => {+ expect(() =>+ composeTablePattern({+ ...MODULE,+ expectations: [+ {...MODULE.expectations[0]!, id: 'grid.example.exposed'},+ ],+ }),+ ).toThrow(/does not belong to pattern table/);+ });+});++describe('Table contract — the jsdom harness stays within its evidence boundary', () => {+ it('runs no base expectation, since each is an accessibility-tree fact', async () => {+ // The base contract reads only the accessibility tree; DOM-layer module+ // expectations (sort) prove themselves beside their module.+ const results = await resultsFor(tableFixture('conforming-labelled'));+ expect(results.some(result => result.status === 'pass')).toBe(false);+ const unrun = results.filter(result => result.status === 'unrun');+ expect(unrun.length).toBeGreaterThan(0);+ for (const result of unrun) {+ expect(result.missingLayers).toContain('accessibility-tree');+ }+ });+});++describe.each(observableHere.map(expectation => [expectation.id] as const))(+ '%s',+ id => {+ const expectation = TABLE_PATTERN.expectations.find(+ candidate => candidate.id === id,+ )!;++ it.each(CONFORMING_TABLE_FIXTURES.map(name => [name] as const))(+ 'passes against %s (or does not apply to it)',+ async name => {+ const result = resultFor(await resultsFor(tableFixture(name)), id);+ expect(+ ['pass', 'not-applicable'],+ `${id} against ${name}: ${result.detail ?? ''}`,+ ).toContain(result.status);+ },+ );++ it.each((TABLE_MUTATIONS[id] ?? []).map(name => [name] as const))(+ 'fails against %s, which removes its outcome',+ async name => {+ const result = resultFor(await resultsFor(tableFixture(name)), id);+ expect(result.status, `${id} against ${name}`).toBe('fail');+ expect(result.detail ?? '').not.toBe('');+ },+ );++ it('carries its id and primary source into every result description', async () => {+ const target = tableFixture(+ TABLE_MUTATIONS[id]?.[0] ?? CONFORMING_TABLE_FIXTURES[0]!,+ );+ const result = resultFor(await resultsFor(target), id);+ 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/table.ts b/internal/a11y-spec/src/patterns/table.tsnew file mode 100644index 0000000000..9598cf13c5--- /dev/null+++ b/internal/a11y-spec/src/patterns/table.ts@@ -0,0 +1,514 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file table.ts+ * @input WCAG 2.2 A/AA success criteria and the APG Table pattern's roles, name, and sort-state requirements+ * @output TABLE_PATTERN, TableStateFacts, TableModuleContract, and composeTablePattern — the base contract a static data table binds to (its table role and name, its rows, column headers, row headers, and data cells), and the seam through which a Table module adds the semantics it brings, such as sort state from the sort module+ * @position Pattern contract; bound by Table (`spec:AST-020/FR15`: Table plays the table role, so it adopts the pattern's role, name, and row and cell roles; the APG Table pattern defines no keyboard interaction, so nothing is adopted there). Each Table module owns its own contract and is composed in only for the states that use it+ */++import type {Harness, Subject} from '../harness';+import {+ definePattern,+ type ApgRequirement,+ type Expectation,+ type AstryxRecord,+ type PatternContract,+ type WcagCriterion,+} from '../contract';++const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/table/';+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`,+};++/** An APG Table pattern requirement, for the base and for module contracts. */+export const tableApgRequirement = (requirement: string): ApgRequirement => ({+ standard: 'apg',+ pattern: 'table',+ requirement,+ url: `${APG_URL}#wai-ariaroles,states,andproperties`,+});+const APG_ROLE = tableApgRequirement('The table container has role table.');+const APG_ROWS = tableApgRequirement(+ 'Each row container has role row and is either a DOM descendant of or owned by the table element or an element with role rowgroup.',+);+const APG_CELLS = tableApgRequirement(+ 'Each cell is either a DOM descendant of or owned by a row element and has one of the following roles: columnheader if the cell contains a title or header information for the column. rowheader if the cell contains title or header information for the row. cell if the cell does not contain column or row header information.',+);+const APG_NAME = tableApgRequirement(+ 'If there is an element in the user interface that serves as a label for the table, aria-labelledby is set on the table element with a value that refers to the labelling element. Otherwise, a label is specified for the table element using aria-label.',+);++/** AST-020 FR15, which adopts the APG Table pattern for Table and its modules. */+export const TABLE_AST_020_FR15: AstryxRecord = {+ standard: 'astryx',+ id: 'spec:AST-020',+ clause: 'FR15',+ url: 'https://github.com/facebook/astryx/blob/878fad9d7ac23cd3f4c5def64595abd770bb01a3/docs/specs/AST-020/spec.md#L83-L92',+ requirement:+ "Where a component part already plays an APG pattern's role, Astryx adopts that pattern's required parts for it: the role, the accessible name, the state and relationship properties, and activation by Tab plus Enter or Space.",+};++/**+ * What a binding knows about one table (the subject). The binding also+ * designates related subjects: `row-<i>` for `rows` rows,+ * `column-header-<i>` for each entry of `columnHeaders`, `row-header-<i>` for+ * each entry of `rowHeaders`, and `cell-<i>` for `cells` ordinary data cells.+ * Every designated header and cell sits in one of the designated rows.+ */+export interface TableStateFacts {+ /** The accessible name the binding declares, or null when it declares none. */+ readonly label: string | null;+ /** How many rows the binding designates. */+ readonly rows: number;+ /**+ * The accessible name the binding declares for each designated column+ * header, in order. A header that holds a control (a sort button) computes+ * its name from that control, so the binding declares that name.+ */+ readonly columnHeaders: readonly string[];+ /** The accessible name the binding declares for each designated row header, in order. */+ readonly rowHeaders: readonly string[];+ /** How many ordinary data cells the binding designates. */+ readonly cells: number;+}++/**+ * The semantics one Table module adds to the base table contract. A module+ * owns its facts and expectations (ids under `table.`); a binding composes it+ * only for the states rendered with that module.+ */+export interface TableModuleContract<ModuleFacts> {+ /** The module, e.g. `useTableSortable`, for report headers. */+ readonly module: string;+ /** What the module adds, in one clause, appended to the base scope. */+ readonly scope: string;+ readonly expectations: readonly Expectation<TableStateFacts & ModuleFacts>[];+}++function describeRole(role: string | null): string {+ return role == null ? 'no role' : `"${role}"`;+}++function describeName(name: string): string {+ return name === '' ? 'no name' : `"${name}"`;+}++/**+ * Every designated header must compute the expected role and title and sit in+ * the table's accessibility subtree, so the table's own structure carries it.+ */+async function expectHeaders(+ harness: Harness,+ table: Subject,+ prefix: string,+ role: 'columnheader' | 'rowheader',+ titles: readonly string[],+): Promise<void> {+ for (const [index, title] of titles.entries()) {+ const header = await harness.related(`${prefix}-${index}`);+ const computed = await header.computed();+ if (computed.role !== role) {+ throw new Error(+ `the "${title}" header is exposed as ${describeRole(computed.role)}, not as a ${role}`,+ );+ }+ if (computed.name !== title) {+ throw new Error(+ `the "${title}" ${role} computes ${describeName(computed.name)} instead`,+ );+ }+ if (!(await harness.containsSemantically(table, header))) {+ throw new Error(+ `the "${title}" ${role} is not part of the table's accessibility subtree`,+ );+ }+ }+}++const TABLE_BASE: PatternContract<TableStateFacts> = {+ pattern: 'table',+ url: APG_URL,+ scope:+ "A static data table's role and name and the roles of its rows, column headers, row headers, and data cells. Table modules add their own semantics through composeTablePattern; interactive content inside cells binds its own patterns.",+ expectations: [+ {+ id: 'table.role.exposed',+ outcome:+ 'The browser exposes the table as a table, so people can move through it by row and column and hear where they are.',+ sources: [WCAG_1_3_1, APG_ROLE],+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],+ appliesWhen: {+ condition: 'the binding designates a table',+ test: () => true,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject}) => {+ const {role} = await subject.computed();+ if (role !== 'table') {+ throw new Error(+ `the browser exposes ${describeRole(role)} instead of a table`,+ );+ }+ },+ },+ {+ id: 'table.name.exposed',+ outcome:+ 'When the binding declares a label, the table computes exactly that name, so people can tell which table they are in.',+ sources: [TABLE_AST_020_FR15, APG_NAME],+ wcagOutcome:+ 'Supports WCAG 2.2 1.3.1 Info and Relationships and 2.4.6 Headings and Labels by keeping the table’s purpose programmatically available.',+ covers: ['2.4.6-headings-and-labels', 'apg-interaction'],+ appliesWhen: {+ condition: 'the binding declares a label for the table',+ test: facts => facts.label != null,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({subject, facts}) => {+ const {name} = await subject.computed();+ if (name !== facts.label) {+ throw new Error(+ `the table should be named "${facts.label}", but the browser computes ${describeName(name)}`,+ );+ }+ },+ },+ {+ id: 'table.rows.exposed',+ outcome:+ 'Each row is a row inside the table and holds the headers and cells shown in it, so people can move row by row and hear each row’s values together.',+ sources: [WCAG_1_3_1, APG_ROWS],+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],+ appliesWhen: {+ condition: 'the binding designates rows',+ test: facts => facts.rows > 0,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ const rows: Subject[] = [];+ for (let index = 0; index < facts.rows; index += 1) {+ const row = await harness.related(`row-${index}`);+ const {role} = await row.computed();+ if (role !== 'row') {+ throw new Error(+ `row ${index + 1} is exposed as ${describeRole(role)}, not as a row`,+ );+ }+ if (!(await harness.containsSemantically(subject, row))) {+ throw new Error(+ `row ${index + 1} is not part of the table's accessibility subtree`,+ );+ }+ rows.push(row);+ }+ const parts = [+ ...facts.columnHeaders.map(+ (title, index) =>+ [+ `column-header-${index}`,+ `the "${title}" column header`,+ ] as const,+ ),+ ...facts.rowHeaders.map(+ (title, index) =>+ [`row-header-${index}`, `the "${title}" row header`] as const,+ ),+ ...Array.from(+ {length: facts.cells},+ (_, index) => [`cell-${index}`, `data cell ${index + 1}`] as const,+ ),+ ];+ for (const [relation, description] of parts) {+ const part = await harness.related(relation);+ let inRow = false;+ for (const row of rows) {+ if (await harness.containsSemantically(row, part)) {+ inRow = true;+ break;+ }+ }+ if (!inRow) {+ throw new Error(`${description} sits in no row of the table`);+ }+ }+ },+ },+ {+ id: 'table.column-headers.exposed',+ outcome:+ 'Each column title is a column header inside the table with the name the binding declares, so people hear which column a value belongs to.',+ sources: [WCAG_1_3_1, APG_CELLS],+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],+ appliesWhen: {+ condition: 'the binding designates column headers',+ test: facts => facts.columnHeaders.length > 0,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ await expectHeaders(+ harness,+ subject,+ 'column-header',+ 'columnheader',+ facts.columnHeaders,+ );+ },+ },+ {+ id: 'table.row-headers.exposed',+ outcome:+ 'Each row title is a row header inside the table with the name the binding declares, so people hear which row a value belongs to.',+ sources: [WCAG_1_3_1, APG_CELLS],+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],+ appliesWhen: {+ condition: 'the binding designates row headers',+ test: facts => facts.rowHeaders.length > 0,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ await expectHeaders(+ harness,+ subject,+ 'row-header',+ 'rowheader',+ facts.rowHeaders,+ );+ },+ },+ {+ id: 'table.cells.exposed',+ outcome:+ 'Each data value is an ordinary cell inside the table, so it is announced with its headers rather than as a header or loose text.',+ sources: [WCAG_1_3_1, APG_CELLS],+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],+ appliesWhen: {+ condition: 'the binding designates data cells',+ test: facts => facts.cells > 0,+ },+ evidenceLayer: 'accessibility-tree',+ enforcement: 'required',+ run: async ({harness, subject, facts}) => {+ for (let index = 0; index < facts.cells; index += 1) {+ const cell = await harness.related(`cell-${index}`);+ const {role} = await cell.computed();+ if (role !== 'cell') {+ throw new Error(+ `data cell ${index + 1} is exposed as ${describeRole(role)}, not as a cell`,+ );+ }+ if (!(await harness.containsSemantically(subject, cell))) {+ throw new Error(+ `data cell ${index + 1} is not part of the table's accessibility subtree`,+ );+ }+ }+ },+ },+ ],+ exemptions: {+ '1.1.1-non-text-content': {+ owner: 'Caller cell content and the Icon component',+ verifiedBy: 'Content review, Icon tests, and the repository axe audit',+ reason:+ 'A table adds no informative non-text content of its own; sort and expansion glyphs are decorative Icon output and cell images belong to their content owners.',+ },+ '1.3.1-info-and-relationships': {+ owner:+ 'Caller content and the Table modules that add rows or cells (row expansion, grouped rows, tree, row index)',+ verifiedBy:+ 'Each module’s own tests and later bindings of those modules to this contract',+ reason:+ 'This contract encodes the table, row, header, and cell roles and the table name; a composed module encodes what it adds, such as sort state. Captions and descriptions, cell spans, column and row counts and indexes, detail and group rows, and header association in tables with irregular headers are not encoded here.',+ coversRemainderOnly: true,+ },+ '1.3.2-meaningful-sequence': {+ owner: 'The binding and caller data order',+ verifiedBy: 'Table structure tests and rendered review',+ reason:+ 'Row and column order follow the caller’s data and column definitions; the table semantics expose that order as rendered.',+ },+ '1.3.5-identify-input-purpose': {+ owner: 'Form controls placed in cells',+ verifiedBy: 'Their own contracts and form review',+ reason: 'A table collects no information about the user.',+ },+ '1.4.1-use-of-color': {+ owner: 'The binding, row-status module, and the active theme',+ verifiedBy: 'Rendered review and the repository visual gate',+ reason:+ 'Striping, hover, dividers, and status color are paint outcomes outside this semantic contract.',+ },+ '1.4.3-contrast-minimum': {+ owner: 'Caller content and the active theme',+ verifiedBy: 'Rendered contrast audit',+ reason: 'Text contrast depends on resolved colors and backdrop.',+ },+ '1.4.11-non-text-contrast': {+ owner: 'The binding and the active theme',+ verifiedBy: 'Rendered divider and control contrast review',+ reason: 'Dividers and control boundaries are paint outcomes.',+ },+ '2.1.1-keyboard': {+ owner:+ 'The Table Scroll region (component:Table FR1) and the pattern owners of controls placed in cells',+ verifiedBy:+ 'The Table scroll real-browser spec and each control’s own contract',+ reason:+ 'The APG Table pattern defines no keyboard interaction: a table is not a widget and its cells are not focusable. Keyboard reach to overflowing content belongs to the Scroll region, and controls in cells keep their own keys.',+ },+ '2.1.2-no-keyboard-trap': {+ owner: 'The Scroll region and controls placed in cells',+ verifiedBy: 'Their contracts and real-browser keyboard review',+ reason: 'The table itself takes no focus and cannot trap it.',+ },+ '2.4.2-page-titled': {+ owner: 'The page',+ verifiedBy: 'Page-level title review',+ reason: 'A table does not own the document title.',+ },+ '2.4.3-focus-order': {+ owner: 'The Scroll region and controls placed in cells',+ verifiedBy: 'Real-browser keyboard-order review',+ reason:+ 'Each control inside a table is its own stop in the page Tab sequence, in DOM order; the table adds no stop of its own.',+ },+ '2.4.4-link-purpose': {+ owner: 'The link pattern and caller content',+ verifiedBy: 'Link contract bindings plus content review',+ reason: 'A table contains links but does not define their purpose.',+ },+ '2.4.6-headings-and-labels': {+ owner: 'Caller-provided table labels and column titles',+ verifiedBy: 'Content review of each table label and header',+ reason:+ 'This contract proves the table computes the declared name, not that the caller supplies one or that its wording describes the data.',+ coversRemainderOnly: true,+ },+ '2.4.7-focus-visible': {+ owner: 'The Scroll region, controls in cells, and the active theme',+ verifiedBy: 'Rendered keyboard-focus review',+ reason: 'The table and its cells are not focusable.',+ },+ '2.4.11-focus-not-obscured': {+ owner: 'The sticky-columns module, the Scroll region, and the page',+ verifiedBy: 'Constrained-viewport and sticky-column browser review',+ reason:+ 'Whether a sticky header or column hides a focused control depends on layout, not table semantics.',+ },+ '2.5.2-pointer-cancellation': {+ owner: 'Controls placed in cells',+ verifiedBy: 'Their pointer activation tests',+ reason: 'A table has no pointer action of its own.',+ },+ '2.5.3-label-in-name': {+ owner: 'Controls placed in cells',+ verifiedBy: 'Their visible-label versus computed-name checks',+ reason:+ 'A table is not a labelled user-interface component; label-in-name applies to the controls inside it.',+ },+ '2.5.8-target-size': {+ owner: 'Controls placed in cells',+ verifiedBy: 'Rendered target geometry review',+ reason: 'A table has no pointer target of its own.',+ },+ '3.1.1-language-of-page': {+ owner: 'The page and localization provider',+ verifiedBy: 'Document-language checks',+ reason: 'A table does not own the document language.',+ },+ '3.2.2-on-input': {+ owner: 'Controls placed in cells',+ verifiedBy: 'Role-specific interaction tests',+ reason: 'A table has no input event.',+ },+ '3.2.4-consistent-identification': {+ owner: 'The design system and caller content',+ verifiedBy: 'Cross-page review of repeated tables',+ reason:+ 'Consistency is a property of repeated pages and tables, not one isolated binding.',+ },+ '3.3.1-error-identification': {+ owner: 'The composing form and the row-status module',+ verifiedBy: 'Form-level and row-status review',+ reason: 'A table defines no validation error state.',+ },+ '3.3.2-labels-or-instructions': {+ owner: 'Form controls placed in cells',+ verifiedBy: 'Form-level label and instruction review',+ reason: 'A table is not a form input.',+ },+ '4.1.2-name-role-value': {+ owner:+ 'The button pattern (sort control), the checkbox pattern (selection), and the row-expansion module',+ verifiedBy:+ 'Their reusable contracts and the Table module tests named in component:Table',+ reason:+ 'A table and its cells are structure rather than user-interface components; their roles and name are encoded here under 1.3.1 and AST-020 FR15, while the sort, selection, and expansion controls inside them keep their own patterns.',+ },+ '4.1.3-status-messages': {+ owner: 'The status-message pattern and caller content',+ verifiedBy:+ 'Status-message tests and AST-009 when spoken timing is claimed',+ reason:+ 'Rendering or re-sorting a table is not a status message; any announcement of a change belongs to its owner.',+ },+ 'apg-interaction': {+ owner:+ 'Caller content, the row-index module, and each Table module that adds rows or cells',+ verifiedBy:+ 'Module tests and later bindings of those modules to this contract',+ reason:+ 'The APG Table pattern defines no keyboard interaction. Its aria-describedby caption reference, aria-colcount, aria-rowcount, aria-colindex, aria-rowindex, aria-colspan, aria-rowspan, and aria-owns guidance is not encoded here.',+ coversRemainderOnly: true,+ },+ 'forced-colors': {+ owner: 'The binding and the active theme',+ verifiedBy: 'Rendered forced-colors review',+ reason: 'Semantic exposure does not prove forced-colors paint.',+ },+ 'reduced-motion': {+ owner: 'The binding and its modules',+ verifiedBy: 'Component motion tests and rendered review',+ reason: 'Table semantics add no motion.',+ },+ 'at-facing-strings': {+ owner: 'The binding’s localization and caller-provided labels',+ verifiedBy:+ 'Catalog checks and localized component tests; AST-009 for speech claims',+ reason:+ 'The contract verifies deterministic computed names without claiming spoken wording, order, or timing.',+ },+ },+};++/** The base table contract: role, name, rows, headers, and cells. */+export const TABLE_PATTERN: PatternContract<TableStateFacts> =+ definePattern<TableStateFacts>(TABLE_BASE);++/**+ * The base table contract plus one module's semantics, for the states a+ * binding renders with that module. The result is still the `table` pattern,+ * so module expectation ids keep their `table.` prefix.+ */+export function composeTablePattern<ModuleFacts>(+ module: TableModuleContract<ModuleFacts>,+): PatternContract<TableStateFacts & ModuleFacts> {+ return definePattern<TableStateFacts & ModuleFacts>({+ ...TABLE_BASE,+ scope: `${TABLE_BASE.scope} With ${module.module}: ${module.scope}`,+ expectations: [...TABLE_BASE.expectations, ...module.expectations],+ });+}diff --git a/packages/core/src/Table/Table.spec.md b/packages/core/src/Table/Table.spec.mdindex 2d2abeb353..02495d4cbf 100644--- a/packages/core/src/Table/Table.spec.md+++ b/packages/core/src/Table/Table.spec.md@@ -15,9 +15,12 @@ verified_by:apps/storybook/stories/Table.stories.tsx,packages/core/src/Table/Table.test.tsx,packages/core/src/Table/__tests__/TableScroll.a11y.chromium.spec.ts,+ packages/core/src/Table/__tests__/Table.a11y.test.tsx,+ packages/core/src/Table/__tests__/Table.a11y.chromium.spec.ts,packages/core/src/Table/Table.perf.test.tsx,packages/core/src/Table/plugins/selection/useTableSelection.test.tsx,packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx,+ packages/core/src/Table/plugins/sortable/__tests__/useTableSortable.a11y.test.tsx,packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx,packages/cli/foundation/discovery/theming-targets.test.mjs,packages/cli/api/theme/targets/targets.test.mjs,@@ -319,19 +322,20 @@ for this aggregate ownership.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |-| FR1-FR3 | `Table.test.tsx` render, structure, fit/overflow transitions, children-mode, section, and target assertions | Fitting and inline-overflowing data-driven tables, empty data, and children composition | Removing Table, Scroll region, observed content box, conditional keyboard access, or effective-axis containment fails existing role, structure, state, class, style, or prop-forwarding assertions; Row and Cell are conditional on rendered data or caller composition. | `audit:Table/anatomy` |-| FR4 | CLI discovery and API target tests plus source inspection | Direct member docs and unfiltered/scoped target output | Duplicating a parent/member target or changing the canonical owner fails parent-aware discovery assertions; section target placement remains source-inspected. | `audit:Table/theming` |-| FR5 | `plugins/sortable/useTableSortable.test.tsx` plus source inspection | Unsorted, ascending, descending, and multi-sort | Removing the Sort control, conditional priority, or ARIA state fails existing assertions. Removing the Sort indicator glyph does not currently fail a focused test; glyph presence and delegated Icon target placement remain source-inspected. | `audit:Table/anatomy` |-| FR6 | `plugins/selection/useTableSelection.test.tsx` | Select all, individual, disabled, and non-selectable | Removing header/body Selection controls or row selection state fails existing structure, label, interaction, and ARIA assertions; delegated CheckboxInput target placement remains source-inspected. | `audit:Table/anatomy` |-| FR7 | `plugins/rowExpansion/useTableRowExpansion.test.tsx` plus source inspection | Collapsed, expanded, and non-expandable rows | Removing the Expansion control, conditional detail panel, captured-count `colSpan`, or ARIA state fails existing assertions in the covered plugin order; later column transforms, delegated Icon target placement, and untargeted panel wrappers remain source-inspected. | `audit:Table/anatomy` |-| FR8 | `Table.test.tsx` empty-state suite plus EmptyState public target metadata | Default, custom, disabled, and non-empty | Removing conditional empty behavior fails existing assertions; default EmptyState delegation remains source-inspected. | `audit:Table/anatomy` |-| FR9-FR11 | `Table.test.tsx`, `types.ts`, `BaseTable.tsx`, and `useBaseTablePlugins.ts` | Built-in plus known and custom named plugins; every transform phase | Sequential composition, base-before-user behavior, transform application, and slot output have focused coverage; complete known-name sorting, phase order, exception continuation, and context nesting remain source-inspected. | `audit:Table/plugins` |-| FR12, PR1 | `Table.perf.test.tsx` plus `useBaseTablePlugins.ts` source inspection | Same plugin references, recreated record, and changed plugin value | Unchanged plugin values must preserve the resolved array and representative no-op row-update budgets; focused named-record identity coverage remains partial. | `audit:Table/performance` |-| FR13, PR3 | `Table.test.tsx`, `plugins/columnResize/useTableColumnResize.test.tsx`, `plugins/stickyColumns/useTableStickyColumns.test.tsx`, and `Table.stories.tsx` ResponsiveScroll play assertions | Width-less columns with empty, short, and long-token rows; mixed explicit widths; pinned columns; narrow and fitting containers | Removing the 60px floor, deriving it from row content, changing explicit width semantics, desynchronizing resize bounds or sticky offsets, or preventing the existing Scroll region from activating fails focused unit or real-browser geometry assertions. | `audit:Table/layout` |-| Module backlink | `scripts/check-knowledge.mjs` | Active parent and colocated module record | A missing, duplicate, mis-parented, wrong-kind, misnamed, or undiscovered module record fails knowledge validation. | `audit:Table/modules` |-| Theming anatomy map | `scripts/check-knowledge.mjs`, `themingTargets.test.ts`, and CLI parent-aware target discovery tests | Canonical anatomy and eight current targets | Missing, extra, duplicated, prefixed, stale, or independently owned member mappings fail repository validation or discovery coverage. | `audit:Table/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |+| FR1-FR3 | `Table.test.tsx` render, structure, fit/overflow transitions, children-mode, section, and target assertions | Fitting and inline-overflowing data-driven tables, empty data, and children composition | Removing Table, Scroll region, observed content box, conditional keyboard access, or effective-axis containment fails existing role, structure, state, class, style, or prop-forwarding assertions; Row and Cell are conditional on rendered data or caller composition. | `audit:Table/anatomy` |+| FR4 | CLI discovery and API target tests plus source inspection | Direct member docs and unfiltered/scoped target output | Duplicating a parent/member target or changing the canonical owner fails parent-aware discovery assertions; section target placement remains source-inspected. | `audit:Table/theming` |+| FR5 | `plugins/sortable/useTableSortable.test.tsx`; the sort module contract (`plugins/sortable/__tests__/useTableSortable.a11y.ts`, self-tested by `useTableSortable.a11y.test.tsx`), which the Table binding composes onto the base Table contract for its sorted state (`__tests__/Table.a11y.test.tsx`, `__tests__/Table.a11y.chromium.spec.ts`); plus source inspection | Unsorted, ascending, descending, and multi-sort | Removing the Sort control, conditional priority, or ARIA state fails existing assertions. Removing the Sort indicator glyph does not currently fail a focused test; glyph presence and delegated Icon target placement remain source-inspected. | `audit:Table/anatomy` |+| FR6 | `plugins/selection/useTableSelection.test.tsx` | Select all, individual, disabled, and non-selectable | Removing header/body Selection controls or row selection state fails existing structure, label, interaction, and ARIA assertions; delegated CheckboxInput target placement remains source-inspected. | `audit:Table/anatomy` |+| FR7 | `plugins/rowExpansion/useTableRowExpansion.test.tsx` plus source inspection | Collapsed, expanded, and non-expandable rows | Removing the Expansion control, conditional detail panel, captured-count `colSpan`, or ARIA state fails existing assertions in the covered plugin order; later column transforms, delegated Icon target placement, and untargeted panel wrappers remain source-inspected. | `audit:Table/anatomy` |+| FR8 | `Table.test.tsx` empty-state suite plus EmptyState public target metadata | Default, custom, disabled, and non-empty | Removing conditional empty behavior fails existing assertions; default EmptyState delegation remains source-inspected. | `audit:Table/anatomy` |+| FR9-FR11 | `Table.test.tsx`, `types.ts`, `BaseTable.tsx`, and `useBaseTablePlugins.ts` | Built-in plus known and custom named plugins; every transform phase | Sequential composition, base-before-user behavior, transform application, and slot output have focused coverage; complete known-name sorting, phase order, exception continuation, and context nesting remain source-inspected. | `audit:Table/plugins` |+| FR12, PR1 | `Table.perf.test.tsx` plus `useBaseTablePlugins.ts` source inspection | Same plugin references, recreated record, and changed plugin value | Unchanged plugin values must preserve the resolved array and representative no-op row-update budgets; focused named-record identity coverage remains partial. | `audit:Table/performance` |+| FR13, PR3 | `Table.test.tsx`, `plugins/columnResize/useTableColumnResize.test.tsx`, `plugins/stickyColumns/useTableStickyColumns.test.tsx`, and `Table.stories.tsx` ResponsiveScroll play assertions | Width-less columns with empty, short, and long-token rows; mixed explicit widths; pinned columns; narrow and fitting containers | Removing the 60px floor, deriving it from row content, changing explicit width semantics, desynchronizing resize bounds or sticky offsets, or preventing the existing Scroll region from activating fails focused unit or real-browser geometry assertions. | `audit:Table/layout` |+| Accessibility contract | `__tests__/Table.a11y.test.tsx` and `__tests__/Table.a11y.chromium.spec.ts` bind Table to the base Table contract (`internal/a11y-spec`), composing each module's contract only for the states rendered with that module: the sort module contract (`plugins/sortable/__tests__/useTableSortable.a11y.ts`) for the sorted state; `__tests__/TableScroll.a11y.chromium.spec.ts` keeps the Scroll region evidence | Labelled data-driven, sorted descending, composed RTL with row headers, and empty data | Losing the table role or declared name, row, header, or cell roles, or a part leaving its row or the table, fails the base binding; a missing or stale `aria-sort` fails the composed sort module contract. | `audit:Table/accessibility` |+| Module backlink | `scripts/check-knowledge.mjs` | Active parent and colocated module record | A missing, duplicate, mis-parented, wrong-kind, misnamed, or undiscovered module record fails knowledge validation. | `audit:Table/modules` |+| Theming anatomy map | `scripts/check-knowledge.mjs`, `themingTargets.test.ts`, and CLI parent-aware target discovery tests | Canonical anatomy and eight current targets | Missing, extra, duplicated, prefixed, stale, or independently owned member mappings fail repository validation or discovery coverage. | `audit:Table/theming` |## Decision logdiff --git a/packages/core/src/Table/__tests__/Table.a11y.chromium.spec.ts b/packages/core/src/Table/__tests__/Table.a11y.chromium.spec.tsnew file mode 100644index 0000000000..0ac4720992--- /dev/null+++ b/packages/core/src/Table/__tests__/Table.a11y.chromium.spec.ts@@ -0,0 +1,128 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Real-browser and accessibility-tree binding evidence for Table. */++import {+ expect,+ test,+ type CDPSession,+ type Locator,+ type Page,+} from '@playwright/test';+import {+ blockingResults,+ checkAccessibilitySpec,+ formatFailures,+ neverExercised,+ 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 {TABLE_A11Y_STATES, type TableA11yRow} from './Table.a11y.states';+import {tableContractFor} from './Table.a11y.contracts';++const SUBJECT_SELECTOR = '[data-a11y-table]';+const ROWS = `${SUBJECT_SELECTOR} > thead > tr, ${SUBJECT_SELECTOR} > tbody > tr`;+const COLUMN_HEADERS = `${SUBJECT_SELECTOR} > thead > tr > th`;+const ROW_HEADERS = `${SUBJECT_SELECTOR} > tbody > tr > th`;+const FIRST_ROW_CELLS = `${SUBJECT_SELECTOR} > tbody > tr:first-child > td`;+let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => storybook?.close());++function storyUrl(id: string): string {+ return `${storybook.origin}/iframe.html?id=${id}&viewMode=story`;+}++function relatedFor(page: Page, state: TableA11yRow): Record<string, Locator> {+ const related: Record<string, Locator> = {};+ const designate = (selector: string, prefix: string, count: number) => {+ const elements = page.locator(selector);+ for (let index = 0; index < count; index += 1) {+ related[`${prefix}-${index}`] = elements.nth(index);+ }+ };+ designate(ROWS, 'row', state.facts.rows);+ designate(COLUMN_HEADERS, 'column-header', state.facts.columnHeaders.length);+ designate(ROW_HEADERS, 'row-header', state.facts.rowHeaders.length);+ designate(FIRST_ROW_CELLS, 'cell', state.facts.cells);+ return related;+}++async function runState(+ page: Page,+ cdp: CDPSession,+ state: TableA11yRow,+): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: tableContractFor(state),+ binding: 'Table',+ state: state.id,+ facts: state.facts,+ mount: async () => {+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});+ await holdMotionStill(page);+ const subject = page.locator(SUBJECT_SELECTOR);+ await subject.waitFor({state: 'attached'});+ await expect(subject).toHaveCount(1);+ await expect(page.locator(ROWS)).toHaveCount(state.facts.rows);+ await expect(page.locator(COLUMN_HEADERS)).toHaveCount(+ state.facts.columnHeaders.length,+ );+ await expect(page.locator(ROW_HEADERS)).toHaveCount(+ state.facts.rowHeaders.length,+ );+ await expect(page.locator(FIRST_ROW_CELLS)).toHaveCount(+ state.facts.cells,+ );+ return createChromiumHarness({+ page,+ cdp,+ subject,+ related: relatedFor(page, state),+ });+ },+ });+}++test('every Table expectation is exercised by at least one Table state', async ({+ page,+}) => {+ const cdp = await page.context().newCDPSession(page);+ const results: BindingResult[] = [];+ for (const state of TABLE_A11Y_STATES) {+ results.push(await runState(page, cdp, state));+ }+ expect(neverExercised(results)).toEqual([]);+});++for (const state of TABLE_A11Y_STATES) {+ test(`Table [${state.id}] — ${state.summary}`, async ({page}) => {+ const cdp = await page.context().newCDPSession(page);+ const result = await runState(page, cdp, state);+ const report = summarize(tableContractFor(state), [result]);+ expect(formatFailures(blockingResults([result]))).toBe('');+ expect(+ result.results+ .filter(row => row.status === 'fail')+ .map(row => `${row.expectation}: ${row.detail ?? ''}`),+ 'this binding expects no failures',+ ).toEqual([]);+ expect(report.unrunLayers).toEqual([]);+ expect(report.counts.unexpectedPass).toBe(0);+ });+}diff --git a/packages/core/src/Table/__tests__/Table.a11y.contracts.ts b/packages/core/src/Table/__tests__/Table.a11y.contracts.tsnew file mode 100644index 0000000000..4575a960e0--- /dev/null+++ b/packages/core/src/Table/__tests__/Table.a11y.contracts.ts@@ -0,0 +1,35 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * The contract each Table binding state checks: the base table contract, plus+ * a module's contract for the states rendered with that module.+ */++import {+ TABLE_PATTERN,+ type PatternContract,+ type TableStateFacts,+} from '@astryxdesign/a11y-spec';+import {+ TABLE_SORTABLE_PATTERN,+ type TableSortFacts,+} from '../plugins/sortable/__tests__/useTableSortable.a11y';+import type {TableA11yState} from './Table.a11y.states';++/** Whether a state renders with useTableSortable. */+export function tableUsesSort(state: TableA11yState): boolean {+ return state.modules.includes('sort');+}++export function tableContractFor(+ state: TableA11yState,+): PatternContract<TableStateFacts> {+ return (+ tableUsesSort(state) ? TABLE_SORTABLE_PATTERN : TABLE_PATTERN+ ) as PatternContract<TableStateFacts>;+}++/** The sort a state declares, or none when it renders without the sort module. */+export function tableSortFor(state: TableA11yState): TableSortFacts['sort'] {+ return 'sort' in state.facts ? state.facts.sort : [];+}diff --git a/packages/core/src/Table/__tests__/Table.a11y.renders.tsx b/packages/core/src/Table/__tests__/Table.a11y.renders.tsxnew file mode 100644index 0000000000..23525ab467--- /dev/null+++ b/packages/core/src/Table/__tests__/Table.a11y.renders.tsx@@ -0,0 +1,112 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/** Stable Table renders shared by jsdom, Storybook, and Chromium. */++import {useState, type ReactElement} from 'react';+import {useTableSortable, type TableSortState} from '../plugins/sortable';+import {Table} from '../Table';+import {TableBody} from '../TableBody';+import {TableCell} from '../TableCell';+import {TableHeader} from '../TableHeader';+import {TableHeaderCell} from '../TableHeaderCell';+import {TableRow} from '../TableRow';+import type {TableColumn} from '../types';+import type {TableA11yRow} from './Table.a11y.states';++type Member = {name: string; role: string; location: string};++const MEMBERS: Member[] = [+ {name: 'Ada', role: 'Engineer', location: 'London'},+ {name: 'Grace', role: 'Admiral', location: 'Arlington'},+];++const COLUMNS: TableColumn<Member>[] = [+ {key: 'name', header: 'Name'},+ {key: 'role', header: 'Role'},+ {key: 'location', header: 'Location'},+];++const SORTABLE_COLUMNS: TableColumn<Member>[] = COLUMNS.map(column => ({+ ...column,+ sortable: true,+}));++// useTableSortable only exposes the sort state; the caller orders the data.+// Rows follow the state so the exposed aria-sort always matches the rows.+function sortMembers(members: Member[], sort: TableSortState): Member[] {+ const [primary] = sort;+ if (primary == null) {+ return members;+ }+ const key = primary.sortKey as keyof Member;+ const sign = primary.direction === 'descending' ? -1 : 1;+ return [...members].sort(+ (a, b) => sign * (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0),+ );+}++function SortedTable(): ReactElement {+ const [sort, setSort] = useState<TableSortState>([+ {sortKey: 'name', direction: 'descending'},+ ]);+ const sortPlugin = useTableSortable<Member>({sort, onSortChange: setSort});+ return (+ <Table<Member>+ data-a11y-table+ aria-label="Team members"+ columns={SORTABLE_COLUMNS}+ data={sortMembers(MEMBERS, sort)}+ plugins={{sort: sortPlugin}}+ />+ );+}++export const TABLE_A11Y_RENDERS: Readonly<+ Record<TableA11yRow['id'], () => ReactElement>+> = {+ 'data-columns': () => (+ <Table<Member>+ data-a11y-table+ aria-label="Team members"+ columns={COLUMNS}+ data={MEMBERS}+ />+ ),+ 'sorted-descending': () => <SortedTable />,+ 'children-row-headers-rtl': () => (+ <div dir="rtl">+ <h2 id="a11y-table-quarterly-heading">Quarterly totals</h2>+ <Table data-a11y-table aria-labelledby="a11y-table-quarterly-heading">+ <TableHeader>+ <TableRow>+ <TableHeaderCell>Region</TableHeaderCell>+ <TableHeaderCell>Q1</TableHeaderCell>+ <TableHeaderCell>Q2</TableHeaderCell>+ </TableRow>+ </TableHeader>+ <TableBody>+ <TableRow>+ <TableHeaderCell scope="row">North</TableHeaderCell>+ <TableCell>120</TableCell>+ <TableCell>135</TableCell>+ </TableRow>+ <TableRow>+ <TableHeaderCell scope="row">South</TableHeaderCell>+ <TableCell>98</TableCell>+ <TableCell>104</TableCell>+ </TableRow>+ </TableBody>+ </Table>+ </div>+ ),+ 'empty-data': () => (+ <Table<Member>+ data-a11y-table+ aria-label="Team members"+ columns={COLUMNS}+ data={[]}+ />+ ),+};diff --git a/packages/core/src/Table/__tests__/Table.a11y.states.ts b/packages/core/src/Table/__tests__/Table.a11y.states.tsnew file mode 100644index 0000000000..90436e61f6--- /dev/null+++ b/packages/core/src/Table/__tests__/Table.a11y.states.ts@@ -0,0 +1,140 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * AST-021 state inventory for the Table binding to the shared Table contract.+ * A state rendered with a Table module also binds that module's contract+ * (`Table.a11y.contracts.ts`); the others bind the base contract alone.+ */++import type {TableStateFacts} from '@astryxdesign/a11y-spec';+import type {TableSortFacts} from '../plugins/sortable/__tests__/useTableSortable.a11y';++export interface TableA11yState {+ readonly id:+ | 'data-columns'+ | 'sorted-descending'+ | 'children-row-headers-rtl'+ | 'empty-data';+ readonly mode: 'data-driven' | 'children';+ readonly summary: string;+ /** The Table modules the state renders with; each adds its own contract. */+ readonly modules: ReadonlyArray<'sort'>;+ readonly facts: TableStateFacts | (TableStateFacts & TableSortFacts);+ readonly storyId: string;+}++export type TableA11yRow = (typeof TABLE_A11Y_STATES)[number];++const story = (id: string) => `a11y-table-pattern--${id}`;++export const TABLE_A11Y_STATES = [+ {+ id: 'data-columns',+ mode: 'data-driven',+ summary:+ 'a labelled data-driven table with three column headers and data rows',+ modules: [],+ facts: {+ label: 'Team members',+ columnHeaders: ['Name', 'Role', 'Location'],+ rows: 3,+ rowHeaders: [],+ cells: 3,+ },+ storyId: story('data-columns'),+ },+ {+ id: 'sorted-descending',+ mode: 'data-driven',+ summary:+ 'every column sortable through useTableSortable, sorted by Name descending',+ modules: ['sort'],+ facts: {+ label: 'Team members',+ columnHeaders: [+ 'Sort by Name, sorted descending',+ 'Sort by Role',+ 'Sort by Location',+ ],+ rows: 3,+ rowHeaders: [],+ cells: 3,+ sort: [{column: 0, direction: 'descending'}],+ },+ storyId: story('sorted-descending'),+ },+ {+ id: 'children-row-headers-rtl',+ mode: 'children',+ summary:+ 'a composed right-to-left table named by a visible heading, with a row header per row',+ modules: [],+ facts: {+ label: 'Quarterly totals',+ columnHeaders: ['Region', 'Q1', 'Q2'],+ rows: 3,+ rowHeaders: ['North', 'South'],+ cells: 2,+ },+ storyId: story('children-row-headers-rtl'),+ },+ {+ id: 'empty-data',+ mode: 'data-driven',+ summary:+ 'a labelled data-driven table with no rows, whose default empty state is one spanning data cell',+ modules: [],+ facts: {+ label: 'Team members',+ columnHeaders: ['Name', 'Role', 'Location'],+ rows: 2,+ rowHeaders: [],+ cells: 1,+ },+ storyId: story('empty-data'),+ },+] as const satisfies ReadonlyArray<TableA11yState>;++export const TABLE_A11Y_EXCLUSIONS = [+ {+ owner: 'useTableSelection tests and the checkbox contract',+ reason:+ 'Selection controls, their labels, and row aria-selected are module behavior under component:Table FR6; this binding does not add the selection column.',+ },+ {+ owner: 'useTableRowStatus tests (module:Table/useTableRowStatus)',+ reason:+ 'The generated status column adds a visually hidden header name and per-row indicator cells, which are exactly the parts this contract checks; this binding does not add the status column, so those parts bind separately.',+ },+ {+ owner:+ 'useTableRowExpansion, useTableGroupedRows, and useTableTreeData tests',+ reason:+ 'Expansion detail rows, group header rows, and tree rows add rows and cells with their own semantics; each module binds separately.',+ },+ {+ owner: 'BaseTable row-index tests',+ reason:+ 'aria-rowcount and aria-rowindex for paged or windowed views are not encoded by the Table contract yet.',+ },+ {+ owner: 'useTableSortable tests',+ reason:+ 'Sort header buttons, their click and keyboard cycling, multi-sort priority, and sort context-menu actions stay with the module; this binding checks only the header role, name, and aria-sort it produces.',+ },+ {+ owner: 'useTableFiltering and useTableColumnResize tests',+ reason:+ 'The filter button and the resize separator render inside header cells and can change the header names this contract checks; each module keeps its own control semantics, and its header states bind separately.',+ },+ {+ owner: 'TableScroll real-browser spec (component:Table FR1)',+ reason:+ 'The named Scroll region, its conditional Tab stop, and overflow containment have their own browser evidence.',+ },+ {+ owner: 'AST-009',+ reason:+ 'This binding claims DOM and browser accessibility-tree exposure, not table navigation, speech, braille, or virtual-cursor behavior.',+ },+] as const;diff --git a/packages/core/src/Table/__tests__/Table.a11y.test.tsx b/packages/core/src/Table/__tests__/Table.a11y.test.tsxnew file mode 100644index 0000000000..21ad2f82ed--- /dev/null+++ b/packages/core/src/Table/__tests__/Table.a11y.test.tsx@@ -0,0 +1,198 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/** Fast DOM binding for Table against the shared Table contract. */++import {cleanup, render} from '@testing-library/react';+import {describe, expect, it} from 'vitest';+import {+ checkAccessibilitySpec,+ createJsdomHarness,+ expectAccessibilitySpec,+ summarize,+ type BindingResult,+} from '@astryxdesign/a11y-spec';+import {TABLE_A11Y_RENDERS} from './Table.a11y.renders';+import {+ tableContractFor,+ tableSortFor,+ tableUsesSort,+} from './Table.a11y.contracts';+import {TABLE_SORTABLE_PATTERN} from '../plugins/sortable/__tests__/useTableSortable.a11y';+import {+ TABLE_A11Y_EXCLUSIONS,+ TABLE_A11Y_STATES,+ type TableA11yRow,+} from './Table.a11y.states';++const SUBJECT_SELECTOR = '[data-a11y-table]';+const ROWS = ':scope > thead > tr, :scope > tbody > tr';+const COLUMN_HEADERS = ':scope > thead > tr > th';+const ROW_HEADERS = ':scope > tbody > tr > th';+const FIRST_ROW_CELLS = ':scope > tbody > tr:first-child > td';++function subjectFor(): HTMLElement {+ const subjects = document.querySelectorAll(SUBJECT_SELECTOR);+ if (subjects.length !== 1 || !(subjects[0] instanceof HTMLElement)) {+ throw new Error(+ `binding rendered ${subjects.length} table subjects instead of one`,+ );+ }+ return subjects[0];+}++function relatedFor(state: TableA11yRow): Record<string, Element> {+ const table = subjectFor();+ const related: Record<string, Element> = {};+ const designate = (selector: string, prefix: string, count: number) => {+ const elements = table.querySelectorAll(selector);+ if (elements.length < count) {+ throw new Error(+ `binding rendered ${elements.length} ${prefix} elements, fewer than the ${count} it declares`,+ );+ }+ for (let index = 0; index < count; index += 1) {+ related[`${prefix}-${index}`] = elements[index]!;+ }+ };+ designate(ROWS, 'row', state.facts.rows);+ designate(COLUMN_HEADERS, 'column-header', state.facts.columnHeaders.length);+ designate(ROW_HEADERS, 'row-header', state.facts.rowHeaders.length);+ designate(FIRST_ROW_CELLS, 'cell', state.facts.cells);+ return related;+}++async function checkState(state: TableA11yRow): Promise<BindingResult> {+ return checkAccessibilitySpec({+ spec: tableContractFor(state),+ binding: 'Table',+ state: state.id,+ facts: state.facts,+ mount: async () => {+ render(TABLE_A11Y_RENDERS[state.id]());+ return createJsdomHarness({+ subject: subjectFor(),+ related: relatedFor(state),+ });+ },+ unmount: cleanup,+ });+}++describe('the shared Table pattern, jsdom lane', () => {+ it.each(+ TABLE_A11Y_STATES.map(+ state => [`Table [${state.id}]`, state.summary, state] as const,+ ),+ )('%s — %s', async (_id, _summary, state) => {+ await expectAccessibilitySpec({+ spec: tableContractFor(state),+ binding: 'Table',+ state: state.id,+ facts: state.facts,+ render: () => {+ render(TABLE_A11Y_RENDERS[state.id]());+ },+ subject: subjectFor,+ related: () => relatedFor(state),+ cleanup,+ });+ });++ it('runs DOM expectations and reports accessibility-tree outcomes as unrun', async () => {+ const results: BindingResult[] = [];+ for (const state of TABLE_A11Y_STATES) {+ results.push(await checkState(state));+ }+ // The sortable contract is the base plus the sort module, so it reports+ // every expectation any state ran.+ const report = summarize(TABLE_SORTABLE_PATTERN, results);+ expect(report.counts.pass).toBeGreaterThan(0);+ expect(report.unrunLayers).toEqual(['accessibility-tree']);+ expect(report.counts.unexpectedPass).toBe(0);+ });+});++describe('the Table binding inventory', () => {+ it('names a distinct checked-in story for every state', () => {+ const ids = TABLE_A11Y_STATES.map(state => state.storyId);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('binds only labelled tables, so every state exercises the table name', () => {+ for (const state of TABLE_A11Y_STATES) {+ expect(state.facts.label, state.id).not.toBeNull();+ }+ });++ it('covers data-driven and children composition, row headers, sort, and empty data', () => {+ expect(new Set(TABLE_A11Y_STATES.map(state => state.mode))).toEqual(+ new Set(['data-driven', 'children']),+ );+ expect(+ TABLE_A11Y_STATES.some(state => state.facts.rowHeaders.length > 0),+ ).toBe(true);+ expect(+ TABLE_A11Y_STATES.some(state => tableSortFor(state).length > 0),+ ).toBe(true);+ expect(TABLE_A11Y_STATES.map(state => state.id)).toContain('empty-data');+ });++ it('renders the rows of every sorted state in the order its sort state declares', () => {+ // useTableSortable exposes aria-sort but never reorders data, so a binding+ // can claim a direction its own rows contradict.+ for (const state of TABLE_A11Y_STATES) {+ for (const {column, direction} of tableSortFor(state)) {+ render(TABLE_A11Y_RENDERS[state.id]());+ const values = [+ ...subjectFor().querySelectorAll(':scope > tbody > tr'),+ ].map(row => row.children[column]?.textContent ?? '');+ const ordered = [...values].sort();+ if (direction === 'descending') {+ ordered.reverse();+ }+ expect(values.length, state.id).toBeGreaterThan(1);+ expect(values, `${state.id} column ${column}`).toEqual(ordered);+ cleanup();+ }+ }+ });++ it('composes the sort module only for states rendered with useTableSortable', () => {+ for (const state of TABLE_A11Y_STATES) {+ const ids = tableContractFor(state).expectations.map(+ expectation => expectation.id,+ );+ expect(ids.includes('table.sort.exposed'), state.id).toBe(+ tableUsesSort(state),+ );+ expect('sort' in state.facts, state.id).toBe(tableUsesSort(state));+ }+ });++ it('records every adjacent exclusion with an owner and reason', () => {+ expect(TABLE_A11Y_EXCLUSIONS.every(row => row.owner && row.reason)).toBe(+ true,+ );+ });++ it('declares exactly the rows, headers, and first-row cells each state renders', () => {+ for (const state of TABLE_A11Y_STATES) {+ render(TABLE_A11Y_RENDERS[state.id]());+ const table = subjectFor();+ expect(table.querySelectorAll(ROWS).length, state.id).toBe(+ state.facts.rows,+ );+ expect(table.querySelectorAll(COLUMN_HEADERS).length, state.id).toBe(+ state.facts.columnHeaders.length,+ );+ expect(table.querySelectorAll(ROW_HEADERS).length, state.id).toBe(+ state.facts.rowHeaders.length,+ );+ expect(table.querySelectorAll(FIRST_ROW_CELLS).length, state.id).toBe(+ state.facts.cells,+ );+ cleanup();+ }+ });+});diff --git a/packages/core/src/Table/plugins/sortable/__tests__/useTableSortable.a11y.test.tsx b/packages/core/src/Table/plugins/sortable/__tests__/useTableSortable.a11y.test.tsxnew file mode 100644index 0000000000..150b807317--- /dev/null+++ b/packages/core/src/Table/plugins/sortable/__tests__/useTableSortable.a11y.test.tsx@@ -0,0 +1,174 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @vitest-environment jsdom */++/**+ * @file useTableSortable.a11y.test.tsx+ * @input Uses the sort module contract and plain-HTML positive and mutation fixtures+ * @output Self-tests for the sort module's `table.sort.exposed` expectation+ * @position Testing; proves the module contract the Table binding composes for sorted states+ */++import {afterEach, describe, expect, it} from 'vitest';+import {+ TABLE_PATTERN,+ checkAccessibilitySpec,+ createJsdomHarness,+ type TableStateFacts,+} from '@astryxdesign/a11y-spec';+import {+ TABLE_SORTABLE_PATTERN,+ TABLE_SORT_MODULE,+ type TableSortFacts,+} from './useTableSortable.a11y';++const COLUMNS = ['Name', 'Role', 'Location'] as const;+const ADA = ['Ada', 'Engineer', 'London'] as const;+const GRACE = ['Grace', 'Admiral', 'Arlington'] as const;+const SORTED: TableSortFacts['sort'] = [{column: 0, direction: 'descending'}];++interface Fixture {+ readonly id: string;+ readonly facts: TableStateFacts & TableSortFacts;+ readonly html: string;+}++/** A labelled data table; `ariaSort` is authored per column header index. */+function html(+ ariaSort: Readonly<Record<number, string>>,+ rows: ReadonlyArray<ReadonlyArray<string>>,+): string {+ const headers = COLUMNS.map((column, index) => {+ const sort =+ ariaSort[index] == null ? '' : `aria-sort="${ariaSort[index]}"`;+ return `<th data-header scope="col" ${sort}>${column}</th>`;+ }).join('');+ const body = rows+ .map(row => `<tr>${row.map(value => `<td>${value}</td>`).join('')}</tr>`)+ .join('');+ return `<table data-table aria-label="Team members"><thead><tr>${headers}</tr></thead><tbody>${body}</tbody></table>`;+}++const facts = (sort: TableSortFacts['sort']): Fixture['facts'] => ({+ label: 'Team members',+ columnHeaders: [...COLUMNS],+ rows: 3,+ rowHeaders: [],+ cells: 0,+ sort,+});++// The sorted fixtures render Grace before Ada, so the rows follow the+// descending Name sort they declare; the violating twins keep those rows so+// only the exposed state is wrong.+const CONFORMING: ReadonlyArray<Fixture> = [+ {+ id: 'conforming-sorted',+ facts: facts(SORTED),+ html: html({0: 'descending', 2: 'none'}, [GRACE, ADA]),+ },+ {id: 'conforming-unsorted', facts: facts([]), html: html({}, [ADA, GRACE])},+];+const VIOLATING: ReadonlyArray<Fixture> = [+ {+ id: 'violating-sort-missing',+ facts: facts(SORTED),+ html: html({}, [GRACE, ADA]),+ },+ {+ id: 'violating-sort-direction',+ facts: facts(SORTED),+ html: html({0: 'ascending'}, [GRACE, ADA]),+ },+ {+ id: 'violating-sort-stale',+ facts: facts([]),+ html: html({1: 'ascending'}, [ADA, GRACE]),+ },+];++afterEach(() => document.body.replaceChildren());++async function sortResult(fixture: Fixture) {+ const container = document.createElement('div');+ document.body.append(container);+ const run = await checkAccessibilitySpec({+ spec: TABLE_SORTABLE_PATTERN,+ binding: 'fixture',+ state: fixture.id,+ facts: fixture.facts,+ mount: async () => {+ container.innerHTML = fixture.html;+ const related: Record<string, Element> = {};+ container.querySelectorAll('[data-header]').forEach((header, index) => {+ related[`column-header-${index}`] = header;+ });+ return createJsdomHarness({+ subject: container.querySelector('[data-table]')!,+ related,+ });+ },+ unmount: () => {+ container.innerHTML = '';+ },+ });+ const result = run.results.find(+ row => row.expectation === 'table.sort.exposed',+ );+ if (result == null) {+ throw new Error(`no table.sort.exposed result for ${fixture.id}`);+ }+ return result;+}++describe('the sort module contract', () => {+ it('composes into the table pattern without changing the base', () => {+ expect(TABLE_SORTABLE_PATTERN.pattern).toBe('table');+ expect(+ TABLE_SORTABLE_PATTERN.expectations.map(expectation => expectation.id),+ ).toEqual([+ ...TABLE_PATTERN.expectations.map(expectation => expectation.id),+ 'table.sort.exposed',+ ]);+ expect(+ TABLE_PATTERN.expectations.map(expectation => expectation.id),+ ).not.toContain('table.sort.exposed');+ expect(TABLE_SORT_MODULE.module).toBe('useTableSortable');+ });++ it.each(CONFORMING.map(fixture => [fixture.id, fixture] as const))(+ 'passes against %s',+ async (_id, fixture) => {+ const result = await sortResult(fixture);+ expect(result.status, result.detail ?? '').toBe('pass');+ },+ );++ it.each(VIOLATING.map(fixture => [fixture.id, fixture] as const))(+ 'fails against %s, which removes its outcome',+ async (_id, fixture) => {+ const result = await sortResult(fixture);+ expect(result.status).toBe('fail');+ expect(result.detail ?? '').not.toBe('');+ },+ );++ it.each(+ [...CONFORMING, ...VIOLATING]+ .filter(fixture => fixture.facts.sort.length > 0)+ .map(fixture => [fixture.id, fixture] as const),+ )('%s renders its rows in the declared order', (_id, fixture) => {+ const container = document.createElement('div');+ container.innerHTML = fixture.html;+ for (const {column, direction} of fixture.facts.sort) {+ const values = [...container.querySelectorAll('tbody > tr')].map(+ row => row.children[column]?.textContent ?? '',+ );+ const ordered = [...values].sort();+ if (direction === 'descending') {+ ordered.reverse();+ }+ expect(values.length).toBeGreaterThan(1);+ expect(values).toEqual(ordered);+ }+ });+});diff --git a/packages/core/src/Table/plugins/sortable/__tests__/useTableSortable.a11y.ts b/packages/core/src/Table/plugins/sortable/__tests__/useTableSortable.a11y.tsnew file mode 100644index 0000000000..82569344ef--- /dev/null+++ b/packages/core/src/Table/plugins/sortable/__tests__/useTableSortable.a11y.ts@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useTableSortable.a11y.ts+ * @input The shared Table contract's module seam and the APG Table pattern's sort-state requirement+ * @output TABLE_SORT_MODULE, TableSortFacts, TableSortDirection, and TABLE_SORTABLE_PATTERN — the accessibility semantics the sort module adds to a table: `aria-sort` on exactly the sorted column headers+ * @position Module contract owned beside useTableSortable; a Table binding composes it only for states rendered with the sort module (`spec:AST-020/FR15`)+ */++import {+ TABLE_AST_020_FR15,+ composeTablePattern,+ tableApgRequirement,+ type TableModuleContract,+} from '@astryxdesign/a11y-spec';++const APG_SORT = tableApgRequirement(+ 'If the table contains sortable columns or rows, aria-sort is set to an appropriate value on the header cell element for the sorted column or row as described in the Grid and Table Properties Practice.',+);++const TABLE_ACCESSIBILITY = {+ standard: 'astryx',+ id: 'component:Table',+ clause: 'Accessibility contract',+ url: 'https://github.com/facebook/astryx/blob/6d4f178a24a8fee1f201911a55f595db9e5ae117/packages/core/src/Table/Table.spec.md#L216-L218',+ requirement:+ 'Native table semantics, column-header scope, sort `aria-sort`, selection `aria-selected`, CheckboxInput labels, and expansion `aria-expanded` remain unchanged.',+} as const;++/** The two directions a sorted header can expose. */+export type TableSortDirection = 'ascending' | 'descending';++/** What a binding knows about the sort state of one table. */+export interface TableSortFacts {+ /** The sorted columns, by index into `columnHeaders`. Empty when unsorted. */+ readonly sort: ReadonlyArray<{+ readonly column: number;+ readonly direction: TableSortDirection;+ }>;+}++export const TABLE_SORT_MODULE: TableModuleContract<TableSortFacts> = {+ module: 'useTableSortable',+ scope: 'the sort state on its column headers.',+ expectations: [+ {+ id: 'table.sort.exposed',+ outcome:+ 'The header of each sorted column states its sort direction and no other header claims one, so people know how the rows are ordered.',+ sources: [TABLE_AST_020_FR15, APG_SORT, TABLE_ACCESSIBILITY],+ wcagOutcome:+ 'Supports WCAG 2.2 1.3.1 Info and Relationships by making the order the rows are presented in programmatically available.',+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],+ appliesWhen: {+ condition: 'the binding designates column headers',+ test: facts => facts.columnHeaders.length > 0,+ },+ evidenceLayer: 'dom',+ enforcement: 'required',+ run: async ({harness, facts}) => {+ for (const [index, title] of facts.columnHeaders.entries()) {+ const header = await harness.related(`column-header-${index}`);+ const sort = await header.attribute('aria-sort');+ const expected =+ facts.sort.find(entry => entry.column === index)?.direction ?? null;+ if (expected == null) {+ if (sort != null && sort !== 'none') {+ throw new Error(+ `the unsorted "${title}" header claims aria-sort="${sort}"`,+ );+ }+ } else if (sort !== expected) {+ throw new Error(+ `the "${title}" header is sorted ${expected} but exposes ${+ sort == null ? 'no aria-sort' : `aria-sort="${sort}"`+ }`,+ );+ }+ }+ },+ },+ ],+};++/** The table contract for states rendered with the sort module. */+export const TABLE_SORTABLE_PATTERN = composeTablePattern(TABLE_SORT_MODULE);diff --git a/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx b/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsxindex 51a3b2bbac..5f212653bc 100644--- a/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx+++ b/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx@@ -421,18 +421,6 @@ describe('useTableSortable', () => {expect(nameHeader).toHaveAttribute('aria-sort', 'ascending');});- it('sets aria-sort="descending" on sorted descending th', () => {- render(- <SortableTable- initialSort={[{sortKey: 'name', direction: 'descending'}]}- />,- );-- const headers = screen.getAllByRole('columnheader');- const nameHeader = headers.find(h => h.textContent?.includes('Name'));- expect(nameHeader).toHaveAttribute('aria-sort', 'descending');- });-it('does not set aria-sort on unsorted columns', () => {render(<SortableTable