Skip to content

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

TypeScript

test(a11y): Tree View contract and TreeList binding (#7477)

Cindy Zhang2873b939878b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ae5b44bad5..936d5df6ea 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1720,6 +1720,54 @@ jobs:
retention-days: 30
if-no-files-found: warn
+ # The tree-view contract's roles and names, one Tab stop, arrow/Home/End,
+ # Enter and typeahead movement are accessibility-tree and real-browser
+ # facts that jsdom cannot observe. Run the contract's own fixture proof
+ # and the TreeList binding whenever TreeList, its focus hook, the
+ # binding's stories, or the contract changes. Its own --output directory;
+ # the JSON report is the head-bound record, uploaded next.
+ - name: Run Tree View accessibility contract
+ id: tree-view-contract
+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}
+ env:
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ PLAYWRIGHT_JSON_OUTPUT_FILE: tree-view-contract/report.json
+ run: |
+ should_run=false
+ # 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/tree-view|internal/a11y-spec/src/harness|packages/core/src/TreeList/|packages/core/src/hooks/useTreeFocus|apps/storybook/stories/TreeListTreeViewA11y)' || scope=$?
+ fi
+ if [ "$scope" != 1 ]; then
+ should_run=true
+ fi
+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"
+ if [ "$should_run" != true ]; then
+ echo "TreeList and the tree-view contract are not in PR scope; skipping tree-view evidence."
+ exit 0
+ fi
+ pnpm exec playwright test \
+ internal/a11y-spec/src/patterns/tree-view.chromium.spec.ts \
+ packages/core/src/TreeList/__tests__/TreeList.a11y.chromium.spec.ts \
+ --project chromium \
+ --reporter list,json \
+ --output tree-view-contract-output
+
+ - name: Upload Tree View accessibility contract evidence
+ if: ${{ !cancelled() && steps.tree-view-contract.outputs.should_run == 'true' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: tree-view-contract-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: tree-view-contract/
+ retention-days: 30
+ if-no-files-found: warn
+
# The link contract's role, name, Tab, Enter, and pointer-release outcomes
# are accessibility-tree and real-browser facts that jsdom cannot observe.
# Run the contract's own fixture proof and the Link binding whenever Link
diff --git a/apps/storybook/stories/TreeListTreeViewA11y.stories.tsx b/apps/storybook/stories/TreeListTreeViewA11y.stories.tsx
new file mode 100644
index 0000000000..c9341292ff
--- /dev/null
+++ b/apps/storybook/stories/TreeListTreeViewA11y.stories.tsx
@@ -0,0 +1,35 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TreeListTreeViewA11y.stories.tsx
+ * @input The TreeList tree-view binding states, rendered through the binding's own renderer so the jsdom and Chromium lanes see the same tree
+ * @output One checked-in story per state for the Chromium accessibility lane; excluded from the visual matrix
+ * @position Browser fixtures for component:TreeList AR1 (TREE_VIEW_PATTERN)
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {renderTreeListState} from '../../../packages/core/src/TreeList/__tests__/TreeList.a11y.renders';
+import {TREE_LIST_BINDING_STATES} from '../../../packages/core/src/TreeList/__tests__/TreeList.a11y.states';
+
+const meta = {
+ title: 'A11y/TreeList Tree View',
+ tags: ['no-visual'],
+ parameters: {layout: 'padded'},
+} satisfies Meta;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+function storyFor(id: (typeof TREE_LIST_BINDING_STATES)[number]['id']): Story {
+ const state = TREE_LIST_BINDING_STATES.find(candidate => candidate.id === id);
+ if (state == null) {
+ throw new Error(`no TreeList tree-view state "${id}"`);
+ }
+ return {render: () => renderTreeListState(state)};
+}
+
+export const ClosedParentTabStop = storyFor('closed-parent-tab-stop');
+export const OpenParentTabStop = storyFor('open-parent-tab-stop');
+export const EndNode = storyFor('end-node');
+export const ClosedParentRtl = storyFor('closed-parent-rtl');
+export const DisabledEndNode = storyFor('disabled-end-node');
diff --git a/internal/a11y-spec/README.md b/internal/a11y-spec/README.md
index e4b796a644..977047505c 100644
--- a/internal/a11y-spec/README.md
+++ b/internal/a11y-spec/README.md
@@ -51,6 +51,7 @@ src/
├── listbox.* listbox, group, and option semantics
├── spinbutton.* numeric role, value, bounds, state, and arrow stepping
├── disclosure.* standalone disclosure state/content semantics
+ ├── tree-view.* a tree's roles, names, expanded state, one Tab stop, and arrow/Home/End/Enter-or-Space/typeahead movement
├── slider.* a thumb's role, name, values, text, orientation, and arrow/Page/Home/End keys (RTL-mirrored arrows)
├── accordion.* a group's header role and name, panel state, single-expansion collapse, page Tab order
├── breadcrumb.* landmark, list-trail, current-page, and separator semantics
@@ -78,6 +79,7 @@ src/
| `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 |
| `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 |
+| `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 |
| `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 |
The toggle-button contract owns the persistent-action extension of button
diff --git a/internal/a11y-spec/src/index.ts b/internal/a11y-spec/src/index.ts
index fcef90e569..bd4e8a246a 100644
--- a/internal/a11y-spec/src/index.ts
+++ b/internal/a11y-spec/src/index.ts
@@ -140,6 +140,7 @@ export {
} from './patterns/landmark';
export {SLIDER_PATTERN, type SliderStateFacts} from './patterns/slider';
+export {TREE_VIEW_PATTERN, type TreeViewStateFacts} from './patterns/tree-view';
export {
ACCORDION_PATTERN,
type AccordionStateFacts,
diff --git a/internal/a11y-spec/src/patterns/tree-view.chromium.spec.ts b/internal/a11y-spec/src/patterns/tree-view.chromium.spec.ts
new file mode 100644
index 0000000000..feccc93678
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/tree-view.chromium.spec.ts
@@ -0,0 +1,103 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file tree-view.chromium.spec.ts
+ * @input TREE_VIEW_PATTERN and its fixtures in real Chromium (the fixture script implements the APG keyboard model)
+ * @output Proof that every expectation passes conforming fixtures and fails its mutation at the layers only a browser observes
+ * @position Contract self-test, Chromium lane
+ */
+
+import {expect, test, type CDPSession, type Page} from '@playwright/test';
+import {describeExpectation, requiredLayers} from '../contract';
+import {checkAccessibilitySpec, type ExpectationResult} from '../check';
+import {
+ CHROMIUM_OBSERVES,
+ createChromiumHarness,
+ holdMotionStill,
+} from '../harness/chromium';
+import {TREE_VIEW_PATTERN} from './tree-view';
+import {
+ TREE_VIEW_MUTATIONS,
+ CONFORMING_FIXTURES,
+ RELATION_SELECTORS,
+ SUBJECT_SELECTOR,
+ fixture,
+ type TreeViewFixture,
+} from './tree-view.fixtures';
+
+function fixturePage(html: string): string {
+ // The fixture carries its own before/after controls.
+ return `<!doctype html><html lang="en"><body>${html}</body></html>`;
+}
+
+async function results(
+ page: Page,
+ cdp: CDPSession,
+ target: TreeViewFixture,
+ only?: readonly string[],
+): Promise<readonly ExpectationResult[]> {
+ const run = await checkAccessibilitySpec({
+ spec: TREE_VIEW_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ only,
+ mount: async () => {
+ await page.setContent(fixturePage(target.html));
+ await holdMotionStill(page);
+ return createChromiumHarness({
+ page,
+ cdp,
+ subject: page.locator(SUBJECT_SELECTOR),
+ related: Object.fromEntries(
+ Object.entries(RELATION_SELECTORS).map(([name, selector]) => [
+ name,
+ page.locator(selector),
+ ]),
+ ),
+ });
+ },
+ });
+ return run.results;
+}
+
+test.describe('tree-view contract — conforming fixtures', () => {
+ for (const id of CONFORMING_FIXTURES) {
+ test(`${id}: every applicable expectation passes`, async ({page}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const observed = await results(page, cdp, fixture(id));
+ expect(
+ observed
+ .filter(
+ result =>
+ result.status !== 'pass' && result.status !== 'not-applicable',
+ )
+ .map(result => `${result.expectation}: ${result.detail ?? ''}`),
+ ).toEqual([]);
+ });
+ }
+});
+
+test.describe('tree-view contract — deliberately violating fixtures', () => {
+ for (const expectation of TREE_VIEW_PATTERN.expectations) {
+ if (
+ !requiredLayers(expectation).every(layer =>
+ CHROMIUM_OBSERVES.includes(layer),
+ )
+ ) {
+ continue;
+ }
+ for (const fixtureId of TREE_VIEW_MUTATIONS[expectation.id] ?? []) {
+ test(`${describeExpectation(expectation)} — fails against ${fixtureId}`, async ({
+ page,
+ }) => {
+ const cdp = await page.context().newCDPSession(page);
+ const [result] = await results(page, cdp, fixture(fixtureId), [
+ expectation.id,
+ ]);
+ expect(result?.status, result?.detail ?? 'no result').toBe('fail');
+ expect(result?.detail ?? '').not.toBe('');
+ });
+ }
+ }
+});
diff --git a/internal/a11y-spec/src/patterns/tree-view.fixtures.ts b/internal/a11y-spec/src/patterns/tree-view.fixtures.ts
new file mode 100644
index 0000000000..0794c57116
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/tree-view.fixtures.ts
@@ -0,0 +1,400 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file tree-view.fixtures.ts
+ * @input Plain HTML trees (one script implements the APG keyboard model; the DOM lane never runs it), conforming and deliberately violating
+ * @output TREE_VIEW_FIXTURES, the subject and relation selectors, and the expectation → violating-fixture map
+ * @position Contract self-test data for tree-view.jsdom.test.ts and tree-view.chromium.spec.ts
+ */
+
+import type {TreeViewStateFacts} from './tree-view';
+
+const SUBJECT_ATTRIBUTE = 'data-a11y-subject';
+export const SUBJECT_SELECTOR = `[${SUBJECT_ATTRIBUTE}]`;
+export const RELATION_SELECTORS = {
+ tree: '#tree',
+ before: '#before',
+ after: '#after',
+ group: '#group-docs',
+ 'first-child': '#node-annual',
+ parent: '#node-docs',
+ next: '[data-next]',
+ previous: '[data-previous]',
+ first: '#node-docs',
+ last: '#node-trash',
+ 'typeahead-target': '[data-typeahead-target]',
+} as const;
+
+export interface TreeViewFixture {
+ readonly id: string;
+ readonly summary: string;
+ readonly facts: TreeViewStateFacts;
+ readonly html: string;
+}
+
+/**
+ * The tree: Documents (parent, closed unless `docsOpen`) › Annual report, Budget;
+ * Photos (end node); Trash (end node). The subject is Documents unless
+ * `subject` says otherwise. `data-next` / `data-previous` mark the subject's
+ * neighbours in visible order.
+ */
+const SCRIPT = `<script>
+(() => {
+ const tree = document.getElementById('tree');
+ const items = () => Array.from(tree.querySelectorAll('[role="treeitem"]')).filter(el => {
+ let p = el.parentElement;
+ while (p && p !== tree) { if (p.hidden) return false; p = p.parentElement; }
+ return true;
+ });
+ const focusItem = el => { for (const i of items()) i.tabIndex = -1; el.tabIndex = 0; el.focus(); };
+ const level = el => Number(el.getAttribute('aria-level'));
+ const toggle = el => { const open = el.getAttribute('aria-expanded') === 'true'; el.setAttribute('aria-expanded', String(!open)); const g = el.querySelector('[role="group"]'); if (g) g.hidden = open; };
+ const rtl = tree.getAttribute('dir') === 'rtl';
+ tree.addEventListener('keydown', e => {
+ const list = items(); const cur = e.target.closest('[role="treeitem"]'); const i = list.indexOf(cur); if (i < 0) return;
+ let key = e.key;
+ if (rtl && (key === 'ArrowLeft' || key === 'ArrowRight')) key = key === 'ArrowLeft' ? 'ArrowRight' : 'ArrowLeft';
+ if (window.__treeNoRtl && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) key = e.key;
+ switch (key) {
+ case 'ArrowDown': e.preventDefault(); if (list[i+1]) focusItem(list[i+1]); break;
+ case 'ArrowUp': e.preventDefault(); if (list[i-1]) focusItem(list[i-1]); break;
+ case 'ArrowRight': e.preventDefault(); if (cur.getAttribute('aria-expanded') === 'false') { toggle(cur); if (window.__treeMoveOnOpen) focusItem(items()[i+1]); } else if (cur.getAttribute('aria-expanded') === 'true') { const n = items()[i+1]; if (n && level(n) > level(cur)) focusItem(n); } break;
+ case 'ArrowLeft': e.preventDefault(); if (cur.getAttribute('aria-expanded') === 'true') toggle(cur); else { for (let j = i-1; j >= 0; j--) if (level(list[j]) < level(cur)) { focusItem(list[j]); break; } } break;
+ case 'Home': e.preventDefault(); focusItem(list[0]); break;
+ case 'End': e.preventDefault(); if (window.__treeEndOpens && cur.getAttribute('aria-expanded') === 'false') toggle(cur); focusItem(window.__treeEndIsFirst ? list[0] : list[list.length-1]); break;
+ case 'Enter': case ' ': e.preventDefault(); if (cur.hasAttribute('aria-expanded') && !window.__treeEnterInert) toggle(cur); break;
+ default:
+ if (key.length === 1 && !window.__treeNoTypeahead) { const q = key.toLowerCase(); const ordered = list.slice(i+1).concat(list.slice(0, i+1)); const m = ordered.find(el => (el.querySelector('.label')?.textContent ?? '').trim().toLowerCase().startsWith(q)); if (m) { e.preventDefault(); focusItem(m); } }
+ }
+ });
+})();
+</script>`;
+
+function node(
+ id: string,
+ label: string,
+ {
+ level,
+ pos,
+ size,
+ subject = false,
+ next = false,
+ previous = false,
+ typeaheadTarget = false,
+ tabbable = false,
+ expanded,
+ children = '',
+ role = 'treeitem',
+ groupRole = 'group',
+ hidden = false,
+ }: {
+ level: number;
+ pos: number;
+ size: number;
+ subject?: boolean;
+ next?: boolean;
+ previous?: boolean;
+ typeaheadTarget?: boolean;
+ tabbable?: boolean;
+ expanded?: boolean | null;
+ children?: string;
+ role?: string;
+ groupRole?: string;
+ hidden?: boolean;
+ },
+): string {
+ return `<li id="node-${id}" role="${role}"${subject ? ` ${SUBJECT_ATTRIBUTE}` : ''}${next ? ' data-next' : ''}${previous ? ' data-previous' : ''}${typeaheadTarget ? ' data-typeahead-target' : ''} tabindex="${tabbable ? 0 : -1}" aria-level="${level}" aria-posinset="${pos}" aria-setsize="${size}"${expanded == null ? '' : ` aria-expanded="${expanded}"`}><span class="label">${label}</span>${children === '' ? '' : `<ul id="group-${id}" role="${groupRole}"${hidden ? ' hidden' : ''}>${children}</ul>`}</li>`;
+}
+
+type SubjectId = 'docs' | 'photos' | 'annual';
+
+function tree({
+ subject = 'docs',
+ docsOpen = false,
+ treeRole = 'tree',
+ treeLabel = 'Files',
+ groupRole = 'group',
+ docsRole = 'treeitem',
+ docsExpandedAttr = true,
+ photosExpandedAttr = false,
+ docsLevel = 1,
+ multiselectable = false,
+ twoTabStops = false,
+ rtl = false,
+}: {
+ subject?: SubjectId;
+ docsOpen?: boolean;
+ treeRole?: string;
+ treeLabel?: string | null;
+ groupRole?: string;
+ docsRole?: string;
+ docsExpandedAttr?: boolean;
+ photosExpandedAttr?: boolean;
+ docsLevel?: number;
+ multiselectable?: boolean;
+ twoTabStops?: boolean;
+ rtl?: boolean;
+} = {}): string {
+ // Visible order: docs, (annual, budget when open), photos, trash.
+ const nextOf: Record<SubjectId, string> = {
+ docs: docsOpen ? 'annual' : 'photos',
+ annual: 'budget',
+ photos: 'trash',
+ };
+ const previousOf: Record<SubjectId, string | null> = {
+ docs: null,
+ annual: 'docs',
+ photos: docsOpen ? 'budget' : 'docs',
+ };
+ // Typeahead: 't' from Documents reaches Trash; 'd' from Photos wraps to
+ // Documents.
+ const typeaheadTargetOf: Record<SubjectId, string> = {
+ docs: 'trash',
+ annual: 'trash',
+ photos: 'docs',
+ };
+ const is = (id: string) => ({
+ subject: subject === id,
+ next: nextOf[subject] === id,
+ previous: previousOf[subject] === id,
+ typeaheadTarget: typeaheadTargetOf[subject] === id,
+ });
+ const tabStop: SubjectId = subject === 'photos' ? 'photos' : 'docs';
+ const tabbable = (id: string) => id === tabStop || twoTabStops;
+ const children =
+ node('annual', 'Annual report', {
+ level: 2,
+ pos: 1,
+ size: 2,
+ ...is('annual'),
+ }) + node('budget', 'Budget', {level: 2, pos: 2, size: 2, ...is('budget')});
+ const docs = node('docs', 'Documents', {
+ level: docsLevel,
+ pos: 1,
+ size: 3,
+ ...is('docs'),
+ tabbable: tabbable('docs'),
+ expanded: docsExpandedAttr ? docsOpen : null,
+ children,
+ groupRole,
+ hidden: !docsOpen,
+ role: docsRole,
+ });
+ const photos = node('photos', 'Photos', {
+ level: 1,
+ pos: 2,
+ size: 3,
+ ...is('photos'),
+ tabbable: tabbable('photos'),
+ expanded: photosExpandedAttr ? false : null,
+ });
+ const trash = node('trash', 'Trash', {
+ level: 1,
+ pos: 3,
+ size: 3,
+ ...is('trash'),
+ });
+ return `<button type="button" id="before">Before</button><ul id="tree" role="${treeRole}"${treeLabel == null ? '' : ` aria-label="${treeLabel}"`}${multiselectable ? ' aria-multiselectable="true"' : ''}${rtl ? ' dir="rtl"' : ''}>${docs}${photos}${trash}</ul><button type="button" id="after">After</button>${SCRIPT}`;
+}
+
+const facts = (
+ overrides: Partial<TreeViewStateFacts> = {},
+): TreeViewStateFacts => ({
+ hasChildren: true,
+ expanded: false,
+ disabled: false,
+ tabbable: true,
+ level: 1,
+ position: 1,
+ setSize: 3,
+ hasNext: true,
+ hasPrevious: false,
+ hasParent: false,
+ rtl: false,
+ typeaheadCharacter: 't',
+ enterToggles: true,
+ ...overrides,
+});
+
+const flag = (name: string, html: string) =>
+ html.replace('<script>', `<script>window.${name} = true;</script><script>`);
+
+export const TREE_VIEW_FIXTURES: readonly TreeViewFixture[] = [
+ {
+ id: 'conforming-closed-parent',
+ summary: "the closed Documents parent, the tree's Tab stop",
+ facts: facts(),
+ html: tree(),
+ },
+ {
+ id: 'conforming-open-parent',
+ summary: 'the open Documents parent with its child group',
+ facts: facts({expanded: true}),
+ html: tree({docsOpen: true}),
+ },
+ {
+ id: 'conforming-end-node',
+ summary: 'the Photos end node, not the Tab stop',
+ facts: facts({
+ hasChildren: false,
+ expanded: false,
+ tabbable: false,
+ position: 2,
+ hasNext: true,
+ hasPrevious: true,
+ typeaheadCharacter: 'd',
+ enterToggles: false,
+ }),
+ html: tree({subject: 'photos'}),
+ },
+ {
+ id: 'conforming-rtl-closed-parent',
+ summary: 'the closed Documents parent in a right-to-left tree',
+ facts: facts({rtl: true}),
+ html: tree({rtl: true}),
+ },
+ {
+ id: 'violating-tree-role',
+ summary: 'a container that is a list, not a tree',
+ facts: facts(),
+ html: tree({treeRole: 'list'}),
+ },
+ {
+ id: 'violating-tree-name',
+ summary: 'a tree with no accessible name',
+ facts: facts(),
+ html: tree({treeLabel: null}),
+ },
+ {
+ id: 'violating-item-role',
+ summary: 'a node that is a listitem, not a treeitem',
+ facts: facts(),
+ html: tree({docsRole: 'listitem'}),
+ },
+ {
+ id: 'violating-parent-without-expanded',
+ summary: 'a parent node with no aria-expanded',
+ facts: facts(),
+ html: tree({docsExpandedAttr: false}),
+ },
+ {
+ id: 'violating-end-node-expanded',
+ summary: 'an end node that claims aria-expanded',
+ facts: facts({
+ hasChildren: false,
+ expanded: false,
+ tabbable: false,
+ position: 2,
+ hasPrevious: true,
+ typeaheadCharacter: 'd',
+ enterToggles: false,
+ }),
+ html: tree({subject: 'photos', photosExpandedAttr: true}),
+ },
+ {
+ id: 'violating-children-not-grouped',
+ summary: 'an open parent whose children sit in a plain list, not a group',
+ facts: facts({expanded: true}),
+ html: tree({docsOpen: true, groupRole: 'list'}),
+ },
+ {
+ id: 'violating-wrong-level',
+ summary: 'a root node that claims level 2',
+ facts: facts(),
+ html: tree({docsLevel: 2}),
+ },
+ {
+ id: 'violating-multiselect-claim',
+ summary: 'a single-selection tree that claims aria-multiselectable',
+ facts: facts(),
+ html: tree({multiselectable: true}),
+ },
+ {
+ id: 'violating-two-tab-stops',
+ summary: 'a tree with two tabbable nodes',
+ facts: facts(),
+ html: tree({twoTabStops: true}),
+ },
+ {
+ id: 'violating-no-down-up',
+ summary: 'a tree whose Down and Up arrows do nothing',
+ facts: facts(),
+ html: tree().replace(
+ "case 'ArrowDown': e.preventDefault(); if (list[i+1]) focusItem(list[i+1]); break;",
+ "case 'ArrowDown': e.preventDefault(); break;",
+ ),
+ },
+ {
+ id: 'violating-open-moves-focus',
+ summary: 'a tree whose Right arrow opens a parent and moves focus at once',
+ facts: facts(),
+ html: flag('__treeMoveOnOpen', tree()),
+ },
+ {
+ id: 'violating-rtl-not-mirrored',
+ summary: 'a right-to-left tree whose Right and Left arrows are not swapped',
+ facts: facts({rtl: true}),
+ html: flag('__treeNoRtl', tree({rtl: true})),
+ },
+ {
+ id: 'violating-end-key',
+ summary: 'a tree whose End key goes to the first node',
+ facts: facts(),
+ html: flag('__treeEndIsFirst', tree()),
+ },
+ {
+ id: 'violating-end-opens',
+ summary: 'a tree whose End key also opens the focused parent',
+ facts: facts(),
+ html: flag('__treeEndOpens', tree()),
+ },
+ {
+ id: 'violating-enter-inert',
+ summary: 'a parent node that neither Enter nor Space opens',
+ facts: facts(),
+ html: flag('__treeEnterInert', tree()),
+ },
+ {
+ id: 'violating-no-typeahead',
+ summary: 'a tree with no typeahead',
+ facts: facts(),
+ html: flag('__treeNoTypeahead', tree()),
+ },
+];
+
+export function fixture(id: string): TreeViewFixture {
+ const found = TREE_VIEW_FIXTURES.find(candidate => candidate.id === id);
+ if (found == null) {
+ throw new Error(`unknown tree-view fixture "${id}"`);
+ }
+ return found;
+}
+
+export const CONFORMING_FIXTURES: readonly string[] = TREE_VIEW_FIXTURES.filter(
+ candidate => candidate.id.startsWith('conforming-'),
+).map(candidate => candidate.id);
+
+export const TREE_VIEW_MUTATIONS: Readonly<Record<string, readonly string[]>> =
+ {
+ 'treeview.tree.role-and-name': [
+ 'violating-tree-role',
+ 'violating-tree-name',
+ ],
+ 'treeview.item.role-and-name': ['violating-item-role'],
+ 'treeview.item.expanded-state': [
+ 'violating-parent-without-expanded',
+ 'violating-end-node-expanded',
+ ],
+ 'treeview.item.children-in-group': ['violating-children-not-grouped'],
+ 'treeview.item.level-and-position': ['violating-wrong-level'],
+ 'treeview.tree.no-multiselect-claim': ['violating-multiselect-claim'],
+ 'treeview.focus.single-tab-stop': ['violating-two-tab-stops'],
+ 'treeview.keys.down-and-up': ['violating-no-down-up'],
+ 'treeview.keys.open-close-and-descend': [
+ 'violating-open-moves-focus',
+ 'violating-rtl-not-mirrored',
+ ],
+ 'treeview.keys.home-and-end': ['violating-end-key', 'violating-end-opens'],
+ 'treeview.keys.enter-or-space-activates': ['violating-enter-inert'],
+ 'treeview.keys.typeahead': ['violating-no-typeahead'],
+ };
diff --git a/internal/a11y-spec/src/patterns/tree-view.jsdom.test.ts b/internal/a11y-spec/src/patterns/tree-view.jsdom.test.ts
new file mode 100644
index 0000000000..5ca89ba19d
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/tree-view.jsdom.test.ts
@@ -0,0 +1,162 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file tree-view.jsdom.test.ts
+ * @input TREE_VIEW_PATTERN and its conforming and violating fixtures
+ * @output Proof that the contract is complete, that every DOM-layer expectation passes conforming fixtures and fails its mutation, and that jsdom reports browser layers as unrun
+ * @position Contract self-test, jsdom lane
+ */
+
+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 {TREE_VIEW_PATTERN} from './tree-view';
+import {
+ TREE_VIEW_MUTATIONS,
+ CONFORMING_FIXTURES,
+ RELATION_SELECTORS,
+ SUBJECT_SELECTOR,
+ fixture,
+ type TreeViewFixture,
+} from './tree-view.fixtures';
+
+const observableHere = TREE_VIEW_PATTERN.expectations.filter(expectation =>
+ requiredLayers(expectation).every(layer => JSDOM_OBSERVES.includes(layer)),
+);
+
+afterEach(() => document.body.replaceChildren());
+
+async function resultsFor(target: TreeViewFixture) {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const result = await checkAccessibilitySpec({
+ spec: TREE_VIEW_PATTERN,
+ binding: 'fixture',
+ state: target.id,
+ facts: target.facts,
+ mount: async () => {
+ container.innerHTML = target.html;
+ const subject = container.querySelector(SUBJECT_SELECTOR);
+ if (subject == null) {
+ throw new Error(`fixture "${target.id}" is missing its subject`);
+ }
+ const related: Record<string, Element> = {};
+ for (const [name, selector] of Object.entries(RELATION_SELECTORS)) {
+ const element = container.querySelector(selector);
+ if (element != null) {
+ related[name] = element;
+ }
+ }
+ return createJsdomHarness({subject, related});
+ },
+ unmount: () => {
+ container.innerHTML = '';
+ },
+ });
+ return result.results;
+}
+
+function resultFor(
+ results: readonly ExpectationResult[],
+ id: string,
+): ExpectationResult {
+ const found = results.find(result => result.expectation === id);
+ if (found == null) {
+ throw new Error(`no result for ${id}`);
+ }
+ return found;
+}
+
+describe('tree-view contract — completeness', () => {
+ it('answers every completeness dimension', () => {
+ expect(unansweredDimensions(TREE_VIEW_PATTERN)).toEqual([]);
+ });
+
+ it('gives every expectation at least one deliberately violating fixture', () => {
+ const missing = TREE_VIEW_PATTERN.expectations
+ .filter(
+ expectation => (TREE_VIEW_MUTATIONS[expectation.id] ?? []).length === 0,
+ )
+ .map(expectation => expectation.id);
+ expect(missing).toEqual([]);
+ });
+
+ it('has an expectation for every mutation it records', () => {
+ const ids = new Set(
+ TREE_VIEW_PATTERN.expectations.map(expectation => expectation.id),
+ );
+ expect(Object.keys(TREE_VIEW_MUTATIONS).filter(id => !ids.has(id))).toEqual(
+ [],
+ );
+ });
+
+ it('names every fixture it records a mutation against', () => {
+ for (const fixtures of Object.values(TREE_VIEW_MUTATIONS)) {
+ for (const id of fixtures) {
+ expect(() => fixture(id)).not.toThrow();
+ }
+ }
+ });
+});
+
+describe('tree-view contract — the jsdom harness stays within its evidence boundary', () => {
+ it('runs DOM expectations and reports browser expectations as unrun', async () => {
+ const results = await resultsFor(fixture('conforming-closed-parent'));
+ expect(results.some(result => result.status === 'pass')).toBe(true);
+ const above = results.filter(result => result.status === 'unrun');
+ expect(above.length).toBeGreaterThan(0);
+ for (const result of above) {
+ expect(
+ (result.missingLayers ?? []).some(
+ layer => layer === 'real-browser' || layer === 'accessibility-tree',
+ ),
+ ).toBe(true);
+ }
+ });
+});
+
+describe.each(observableHere.map(expectation => [expectation.id] as const))(
+ '%s',
+ id => {
+ const expectation = TREE_VIEW_PATTERN.expectations.find(
+ candidate => candidate.id === id,
+ )!;
+
+ it.each(CONFORMING_FIXTURES.map(name => [name] as const))(
+ 'passes against %s (or does not apply to it)',
+ async name => {
+ const result = resultFor(await resultsFor(fixture(name)), id);
+ expect(
+ ['pass', 'not-applicable'],
+ `${id} against ${name}: ${result.detail ?? ''}`,
+ ).toContain(result.status);
+ },
+ );
+
+ it.each((TREE_VIEW_MUTATIONS[id] ?? []).map(name => [name] as const))(
+ 'fails against %s, which removes its outcome',
+ async name => {
+ const result = resultFor(await resultsFor(fixture(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 = fixture(
+ TREE_VIEW_MUTATIONS[id]?.[0] ?? CONFORMING_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/tree-view.ts b/internal/a11y-spec/src/patterns/tree-view.ts
new file mode 100644
index 0000000000..453976a6b5
--- /dev/null
+++ b/internal/a11y-spec/src/patterns/tree-view.ts
@@ -0,0 +1,763 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file tree-view.ts
+ * @input WCAG 2.2 A/AA success criteria and the APG Tree View pattern's structure, state, name, and keyboard requirements
+ * @output TREE_VIEW_PATTERN — the reusable contract a composite tree binds to when it adopts Tree View (TreeList under component:TreeList AR1, `spec:AST-020/FR15`)
+ * @position Pattern contract; bound by TreeList
+ */
+
+import {
+ definePattern,
+ type ApgRequirement,
+ type AstryxRecord,
+ type PatternContract,
+ type WcagCriterion,
+} from '../contract';
+import type {Harness, Subject} from '../harness';
+
+const APG_URL = 'https://www.w3.org/WAI/ARIA/apg/patterns/treeview/';
+const UNDERSTANDING = 'https://www.w3.org/WAI/WCAG22/Understanding';
+
+const WCAG_1_3_1: WcagCriterion = {
+ standard: 'wcag',
+ id: '1.3.1',
+ name: 'Info and Relationships',
+ level: 'A',
+ url: `${UNDERSTANDING}/info-and-relationships.html`,
+};
+const WCAG_2_1_1: WcagCriterion = {
+ standard: 'wcag',
+ id: '2.1.1',
+ name: 'Keyboard',
+ level: 'A',
+ url: `${UNDERSTANDING}/keyboard.html`,
+};
+const WCAG_2_4_3: WcagCriterion = {
+ standard: 'wcag',
+ id: '2.4.3',
+ name: 'Focus Order',
+ level: 'A',
+ url: `${UNDERSTANDING}/focus-order.html`,
+};
+const WCAG_4_1_2: WcagCriterion = {
+ standard: 'wcag',
+ id: '4.1.2',
+ name: 'Name, Role, Value',
+ level: 'A',
+ url: `${UNDERSTANDING}/name-role-value.html`,
+};
+
+const apgReq = (requirement: string, anchor: string): ApgRequirement => ({
+ standard: 'apg',
+ pattern: 'treeview',
+ requirement,
+ url: `${APG_URL}#${anchor}`,
+});
+const A = 'wai-ariaroles,states,andproperties';
+const K = 'keyboardinteraction';
+const APG_TREE_ROLE = apgReq(
+ 'All tree nodes are contained in or owned by an element with role tree.',
+ A,
+);
+const APG_TREE_NAME = apgReq(
+ 'The element with role tree has either a visible label referenced by aria-labelledby or a value specified for aria-label.',
+ A,
+);
+const APG_ITEM_ROLE = apgReq(
+ 'Each element serving as a tree node has role treeitem.',
+ A,
+);
+const APG_GROUP = apgReq(
+ 'Each parent node contains or owns an element with role group. Each child node is contained in or owned by an element with role group that is contained in or owned by the node that serves as the parent of that child.',
+ A,
+);
+const APG_EXPANDED = apgReq(
+ 'Each element with role treeitem that serves as a parent node has aria-expanded set to false when the node is in a closed state and set to true when the node is in an open state. End nodes do not have the aria-expanded attribute.',
+ A,
+);
+const APG_MULTISELECT = apgReq(
+ 'If the tree supports selection of more than one node, the element with role tree has aria-multiselectable set to true. Otherwise, aria-multiselectable is either set to false or the default value of false is implied.',
+ A,
+);
+const APG_LEVEL = apgReq(
+ 'If the complete set of available nodes is not present in the DOM due to dynamic loading as the user moves focus in or scrolls the tree, each node has aria-level, aria-setsize, and aria-posinset specified.',
+ A,
+);
+const APG_DOWN_UP = apgReq(
+ 'Down Arrow: Moves focus to the next node that is focusable without opening or closing a node. Up Arrow: Moves focus to the previous node that is focusable without opening or closing a node.',
+ K,
+);
+const APG_RIGHT = apgReq(
+ 'Right arrow: When focus is on a closed node, opens the node; focus does not move. When focus is on a open node, moves focus to the first child node. When focus is on an end node, does nothing.',
+ K,
+);
+const APG_LEFT = apgReq(
+ 'Left arrow: When focus is on an open node, closes the node. When focus is on a child node that is also either an end node or a closed node, moves focus to its parent node.',
+ K,
+);
+const APG_HOME_END = apgReq(
+ 'Home: Moves focus to the first node in the tree without opening or closing a node. End: Moves focus to the last node in the tree that is focusable without opening a node.',
+ K,
+);
+const TREELIST_AR1_LEVEL: AstryxRecord = {
+ standard: 'astryx',
+ id: 'component:TreeList',
+ clause: 'AR1',
+ url: 'https://github.com/facebook/astryx/blob/458a74c2a65a44c1fc7f76266e812e6d47213080/packages/core/src/TreeList/TreeList.spec.md#L155-L157',
+ requirement:
+ 'every row is role="treeitem", named by its label and described by its description, aria-expanded when it has children, aria-selected when it is the selected row, aria-level for its depth, and aria-posinset/aria-setsize among its siblings.',
+};
+const TREELIST_AR1_ACTIVATION: AstryxRecord = {
+ standard: 'astryx',
+ id: 'component:TreeList',
+ clause: 'AR1',
+ url: 'https://github.com/facebook/astryx/blob/250fd9ac197381ec06900279efc31cbb03544ca9/packages/core/src/TreeList/TreeList.spec.md#L151-L161',
+ requirement: 'Enter and Space activate the focused row.',
+};
+const APG_ENTER = apgReq(
+ 'Enter: activates a node, i.e., performs its default action. For parent nodes, one possible default action is to open or close the node.',
+ K,
+);
+const APG_TYPEAHEAD = apgReq(
+ 'Type a character: focus moves to the next node with a name that starts with the typed character.',
+ K,
+);
+const APG_FOCUS_ENTRY = apgReq(
+ 'When a single-select tree receives focus: if none of the nodes are selected before the tree receives focus, focus is set on the first node; if a node is selected before the tree receives focus, focus is set on the selected node.',
+ K,
+);
+const TREELIST_AR1_RTL: AstryxRecord = {
+ standard: 'astryx',
+ id: 'component:TreeList',
+ clause: 'AR1',
+ url: 'https://github.com/facebook/astryx/blob/250fd9ac197381ec06900279efc31cbb03544ca9/packages/core/src/TreeList/TreeList.spec.md#L151-L161',
+ requirement:
+ 'ArrowRight expands a closed row, then moves into its first child, and ArrowLeft collapses an open row or moves to the parent — mirrored under RTL.',
+};
+
+/**
+ * What a binding knows about one tree node (the subject) and the tree around
+ * it. Relations: `tree` (the role=tree element), `before` and `after` (the
+ * focusable controls around the tree in the page Tab order), and, when the
+ * facts say they exist, `group` (the node's child group), `first-child`,
+ * `parent`, `next`, `previous`, `first`, `last`, and `typeahead-target`.
+ */
+export interface TreeViewStateFacts {
+ /** Whether this node has children (a parent node). */
+ readonly hasChildren: boolean;
+ /** Whether a parent node is open in this state. */
+ readonly expanded: boolean;
+ /** Whether this node can be operated (not disabled). */
+ readonly disabled: boolean;
+ /** Whether this node is the tree's one Tab stop. */
+ readonly tabbable: boolean;
+ /** 1-based depth of the node. */
+ readonly level: number;
+ /** 1-based position among its siblings and the sibling count. */
+ readonly position: number;
+ readonly setSize: number;
+ /** Whether the binding supplies `next` / `previous` / `parent` relations. */
+ readonly hasNext: boolean;
+ readonly hasPrevious: boolean;
+ readonly hasParent: boolean;
+ /** Whether the tree is rendered right-to-left (Right and Left arrows swap). */
+ readonly rtl: boolean;
+ /** A character whose typeahead target the binding supplies, or null. */
+ readonly typeaheadCharacter: string | null;
+ /** Whether Enter on this node opens or closes it (a parent without its own action). */
+ readonly enterToggles: boolean;
+}
+
+const ALWAYS = {
+ condition: 'the binding designates a tree node',
+ test: () => true,
+};
+
+async function authoredExpanded(subject: Subject): Promise<boolean | null> {
+ const value = await subject.attribute('aria-expanded');
+ return value === 'true' ? true : value === 'false' ? false : null;
+}
+
+async function focusOrFail(subject: Subject, forWhat: string): Promise<void> {
+ await subject.focus();
+ if (!(await subject.isFocused())) {
+ throw new Error(
+ `the tree node did not take focus, so ${forWhat} never reaches it`,
+ );
+ }
+}
+
+async function expectFocused(target: Subject, after: string): Promise<void> {
+ if (!(await target.isFocused())) {
+ throw new Error(`${after} did not move focus to the expected node`);
+ }
+}
+
+function inlineKeys(rtl: boolean): {
+ open: 'ArrowRight' | 'ArrowLeft';
+ close: 'ArrowRight' | 'ArrowLeft';
+} {
+ return rtl
+ ? {open: 'ArrowLeft', close: 'ArrowRight'}
+ : {open: 'ArrowRight', close: 'ArrowLeft'};
+}
+
+async function restoreExpansion(
+ harness: Harness,
+ subject: Subject,
+ wanted: boolean,
+ key: 'ArrowRight' | 'ArrowLeft',
+): Promise<void> {
+ if ((await authoredExpanded(subject)) !== wanted) {
+ await focusOrFail(subject, 'restoring the node');
+ await harness.press(key);
+ }
+}
+
+export const TREE_VIEW_PATTERN: PatternContract<TreeViewStateFacts> =
+ definePattern<TreeViewStateFacts>({
+ pattern: 'treeview',
+ url: APG_URL,
+ scope:
+ "A tree's role and name; each node's treeitem role, name, expanded state, child group, and level/position; one Tab stop for the whole tree; Up/Down, Right/Left (mirrored under RTL), Home/End, Enter or Space activation and typeahead movement.",
+ expectations: [
+ {
+ id: 'treeview.tree.role-and-name',
+ outcome:
+ 'The browser exposes the tree as a named tree, so a user hears what the hierarchy is for.',
+ sources: [WCAG_4_1_2, APG_TREE_ROLE, APG_TREE_NAME],
+ covers: [
+ '4.1.2-name-role-value',
+ '2.4.6-headings-and-labels',
+ 'apg-interaction',
+ ],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({harness}) => {
+ const tree = await harness.related('tree');
+ const {role, name} = await tree.computed();
+ if (role !== 'tree') {
+ throw new Error(
+ `the browser exposes the container as ${role == null ? 'no role' : `"${role}"`}, not as a tree`,
+ );
+ }
+ if (!name || name.trim() === '') {
+ throw new Error(
+ 'the browser computes no accessible name for the tree',
+ );
+ }
+ },
+ },
+ {
+ id: 'treeview.item.role-and-name',
+ outcome:
+ 'The browser exposes the node as a named treeitem inside the tree.',
+ sources: [WCAG_4_1_2, APG_ITEM_ROLE],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'accessibility-tree',
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const {role, name} = await subject.computed();
+ if (role !== 'treeitem') {
+ throw new Error(
+ `the browser exposes this node as ${role == null ? 'no role' : `"${role}"`}, not as a treeitem`,
+ );
+ }
+ if (!name || name.trim() === '') {
+ throw new Error(
+ 'the browser computes no accessible name for this node',
+ );
+ }
+ const tree = await harness.related('tree');
+ if (!(await harness.containsSemantically(tree, subject))) {
+ throw new Error(
+ 'the tree does not own this node in the accessibility tree',
+ );
+ }
+ },
+ },
+ {
+ id: 'treeview.item.expanded-state',
+ outcome:
+ 'A parent node reports whether it is open; an end node carries no expanded state, so it is never mistaken for a parent.',
+ sources: [WCAG_4_1_2, APG_EXPANDED],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject, facts}) => {
+ const value = await subject.attribute('aria-expanded');
+ if (!facts.hasChildren) {
+ if (value != null) {
+ throw new Error(`an end node carries aria-expanded="${value}"`);
+ }
+ return;
+ }
+ if (value !== String(facts.expanded)) {
+ throw new Error(
+ `the parent node is ${facts.expanded ? 'open' : 'closed'} but aria-expanded is ${value ?? 'absent'}`,
+ );
+ }
+ },
+ },
+ {
+ id: 'treeview.item.children-in-group',
+ outcome:
+ "An open parent's children sit in a group the parent owns, so the hierarchy is programmatic.",
+ sources: [WCAG_1_3_1, APG_GROUP],
+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the node is an open parent',
+ test: facts => facts.hasChildren && facts.expanded,
+ },
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const group = await harness.related('group');
+ const firstChild = await harness.related('first-child');
+ if ((await group.attribute('role')) !== 'group') {
+ throw new Error(
+ "the parent's children are not in an element with role group",
+ );
+ }
+ if (!(await harness.contains(subject, group))) {
+ throw new Error(
+ 'the child group is not contained by its parent node',
+ );
+ }
+ if (!(await harness.contains(group, firstChild))) {
+ throw new Error("the first child is not inside its parent's group");
+ }
+ },
+ },
+ {
+ id: 'treeview.item.level-and-position',
+ outcome:
+ 'The node states its depth and its place among its siblings, so a user hears "level 2, 3 of 5" instead of guessing from indentation.',
+ sources: [WCAG_1_3_1, APG_LEVEL, TREELIST_AR1_LEVEL],
+ covers: ['1.3.1-info-and-relationships', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({subject, facts}) => {
+ const level = await subject.attribute('aria-level');
+ const pos = await subject.attribute('aria-posinset');
+ const size = await subject.attribute('aria-setsize');
+ if (level !== String(facts.level)) {
+ throw new Error(
+ `aria-level is ${level ?? 'absent'}, not ${facts.level}`,
+ );
+ }
+ if (
+ pos !== String(facts.position) ||
+ size !== String(facts.setSize)
+ ) {
+ throw new Error(
+ `aria-posinset/aria-setsize are ${pos ?? 'absent'}/${size ?? 'absent'}, not ${facts.position}/${facts.setSize}`,
+ );
+ }
+ },
+ },
+ {
+ id: 'treeview.tree.no-multiselect-claim',
+ outcome:
+ 'A tree where at most one node is selected does not claim multiple selection.',
+ sources: [WCAG_4_1_2, APG_MULTISELECT],
+ covers: ['4.1.2-name-role-value', 'apg-interaction'],
+ appliesWhen: ALWAYS,
+ evidenceLayer: 'dom',
+ enforcement: 'required',
+ run: async ({harness}) => {
+ const tree = await harness.related('tree');
+ if ((await tree.attribute('aria-multiselectable')) === 'true') {
+ throw new Error('the tree claims aria-multiselectable="true"');
+ }
+ },
+ },
+ {
+ id: 'treeview.focus.single-tab-stop',
+ outcome:
+ 'The whole tree is one Tab stop: Tab from before it lands on its one tabbable node, and Tab again leaves the tree.',
+ sources: [WCAG_2_1_1, WCAG_2_4_3, APG_FOCUS_ENTRY],
+ covers: [
+ '2.1.1-keyboard',
+ '2.1.2-no-keyboard-trap',
+ '2.4.3-focus-order',
+ 'apg-interaction',
+ ],
+ appliesWhen: {
+ condition: "the node is the tree's Tab stop",
+ test: facts => facts.tabbable,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const before = await harness.related('before');
+ const after = await harness.related('after');
+ if ((await subject.attribute('tabindex')) !== '0') {
+ throw new Error('the tabbable node does not carry tabindex="0"');
+ }
+ await before.focus();
+ await harness.press('Tab');
+ await expectFocused(subject, 'Tab from before the tree');
+ await harness.press('Tab');
+ await expectFocused(after, 'Tab from the tree');
+ },
+ },
+ {
+ id: 'treeview.keys.down-and-up',
+ outcome:
+ 'ArrowDown moves to the next visible node and ArrowUp back, without opening or closing anything.',
+ sources: [WCAG_2_1_1, APG_DOWN_UP],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the node can be operated and a visible node follows it',
+ test: facts => !facts.disabled && facts.hasNext,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ const next = await harness.related('next');
+ const before = await authoredExpanded(subject);
+ await focusOrFail(subject, 'ArrowDown');
+ await harness.press('ArrowDown');
+ await expectFocused(next, 'ArrowDown');
+ await harness.press('ArrowUp');
+ await expectFocused(subject, 'ArrowUp');
+ if (
+ facts.hasChildren &&
+ (await authoredExpanded(subject)) !== before
+ ) {
+ throw new Error(
+ "ArrowDown or ArrowUp changed the node's expanded state",
+ );
+ }
+ },
+ },
+ {
+ id: 'treeview.keys.open-close-and-descend',
+ outcome:
+ 'On a closed parent the inline-forward arrow opens it without moving focus, pressed again moves into the first child, and the inline-back arrow returns to the parent and then closes it — mirrored under right-to-left.',
+ sources: [WCAG_2_1_1, APG_RIGHT, APG_LEFT, TREELIST_AR1_RTL],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the node is a closed parent that can be operated',
+ test: facts =>
+ facts.hasChildren && !facts.expanded && !facts.disabled,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ const {open, close} = inlineKeys(facts.rtl);
+ const firstChild = await harness.related('first-child');
+ try {
+ await focusOrFail(subject, open);
+ await harness.press(open);
+ if ((await authoredExpanded(subject)) !== true) {
+ throw new Error(`${open} did not open the closed parent`);
+ }
+ await expectFocused(
+ subject,
+ `${open} on a closed parent (focus must stay)`,
+ );
+ await harness.press(open);
+ await expectFocused(firstChild, `${open} on an open parent`);
+ await harness.press(close);
+ await expectFocused(subject, `${close} on a child`);
+ await harness.press(close);
+ if ((await authoredExpanded(subject)) !== false) {
+ throw new Error(`${close} did not close the open parent`);
+ }
+ } finally {
+ await restoreExpansion(harness, subject, false, close);
+ }
+ },
+ },
+ {
+ id: 'treeview.keys.home-and-end',
+ outcome:
+ 'Home moves to the first node and End to the last visible node, without opening or closing anything.',
+ sources: [WCAG_2_1_1, APG_HOME_END],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition: 'the node can be operated',
+ test: facts => !facts.disabled,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject}) => {
+ const first = await harness.related('first');
+ const last = await harness.related('last');
+ const before = await authoredExpanded(subject);
+ await focusOrFail(subject, 'Home');
+ await harness.press('End');
+ await expectFocused(last, 'End');
+ await harness.press('Home');
+ await expectFocused(first, 'Home');
+ if ((await authoredExpanded(subject)) !== before) {
+ throw new Error("Home or End changed the node's expanded state");
+ }
+ },
+ },
+ {
+ id: 'treeview.keys.enter-or-space-activates',
+ outcome:
+ "Enter and Space perform the node's default action: a parent without its own action opens on one and closes on the other.",
+ sources: [WCAG_2_1_1, APG_ENTER, TREELIST_AR1_ACTIVATION],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition:
+ 'Enter or Space opens or closes this node and it can be operated',
+ test: facts => facts.enterToggles && !facts.disabled,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ const {close} = inlineKeys(facts.rtl);
+ try {
+ await focusOrFail(subject, 'Enter and Space');
+ await harness.press('Enter');
+ if ((await authoredExpanded(subject)) !== !facts.expanded) {
+ throw new Error('Enter did not toggle the parent node');
+ }
+ await harness.press('Space');
+ if ((await authoredExpanded(subject)) !== facts.expanded) {
+ throw new Error('Space did not toggle the parent node back');
+ }
+ } finally {
+ await restoreExpansion(harness, subject, facts.expanded, close);
+ }
+ },
+ },
+ {
+ id: 'treeview.keys.typeahead',
+ outcome:
+ 'Typing a character moves focus to the next node whose name starts with it.',
+ sources: [WCAG_2_1_1, APG_TYPEAHEAD],
+ covers: ['2.1.1-keyboard', 'apg-interaction'],
+ appliesWhen: {
+ condition:
+ 'the binding names a typeahead character and its target, and the node can be operated',
+ test: facts => facts.typeaheadCharacter != null && !facts.disabled,
+ },
+ evidenceLayer: 'real-browser',
+ alsoNeeds: ['dom'],
+ enforcement: 'required',
+ run: async ({harness, subject, facts}) => {
+ const target = await harness.related('typeahead-target');
+ await focusOrFail(subject, 'typing');
+ await harness.typeText(subject, facts.typeaheadCharacter ?? '');
+ await expectFocused(target, `typing "${facts.typeaheadCharacter}"`);
+ },
+ },
+ ],
+ exemptions: {
+ '1.1.1-non-text-content': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ "the component's decorative-icon tests and the repository axe audit, `pnpm a11y:audit`",
+ reason:
+ 'This contract owns tree structure and movement. Chevrons, row icons, and any image a caller places in a row are binding or caller composition.',
+ },
+ '1.3.1-info-and-relationships': {
+ owner: 'the binding component and caller content',
+ verifiedBy: "the component's row tests and caller content review",
+ reason:
+ "This contract proves the tree/group/treeitem hierarchy and each node's level and position. Relationships inside a row (a description, start or end content) are the binding's and the caller's.",
+ coversRemainderOnly: true,
+ },
+ '1.3.2-meaningful-sequence': {
+ owner: 'the binding component and composing page',
+ verifiedBy:
+ "the component's DOM-order tests and page-level reading-order review",
+ reason:
+ 'Row order within the tree follows the data the caller supplies; where the tree sits in the page is composition.',
+ },
+ '1.3.5-identify-input-purpose': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ "this contract's structure rows (every treeitem is a named navigation node) and source review of caller start and end content",
+ reason:
+ "A tree row is a navigation node, not an input that collects information about the user; the rows carry no form control of their own, and any control a caller places in start or end content is the caller's to name for autofill.",
+ },
+ '1.4.1-use-of-color': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ "the component's selected, focused and disabled state tests plus rendered review",
+ reason:
+ 'Selected, focused and disabled cues are paint results owned by the binding and theme; this contract proves the programmatic states.',
+ },
+ '1.4.3-contrast-minimum': {
+ owner: 'the binding component and theme',
+ verifiedBy: 'the repository axe audit plus rendered contrast review',
+ reason:
+ 'Row text contrast is a paint outcome owned by the binding and theme.',
+ },
+ '1.4.11-non-text-contrast': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ 'the repository axe audit plus rendered review of the focus indicator, guides and chevrons',
+ reason:
+ 'Focus indicator, guide line and chevron contrast are paint outcomes owned by the binding and theme.',
+ },
+ '2.1.1-keyboard': {
+ owner: 'the composing page',
+ verifiedBy: 'page-level keyboard review',
+ reason:
+ "This contract encodes the tree's keyboard model: one Tab stop, Up/Down, Right/Left, Home/End, Enter or Space and typeahead. Other page keyboard paths remain with the composition.",
+ coversRemainderOnly: true,
+ },
+ '2.1.2-no-keyboard-trap': {
+ owner: 'the composing page',
+ verifiedBy:
+ 'page-level keyboard review; this contract proves Tab leaves the tree after its one stop',
+ reason:
+ 'The single-Tab-stop expectation shows Tab exits the tree; other trap sources are composition.',
+ coversRemainderOnly: true,
+ },
+ '2.4.2-page-titled': {
+ owner: 'the page',
+ verifiedBy: 'page-level review',
+ reason: 'A tree rendered in isolation owns no document title.',
+ },
+ '2.4.3-focus-order': {
+ owner: 'the composing page',
+ verifiedBy:
+ 'page-level focus-order review; this contract proves the one Tab stop and where the tree keys move focus',
+ reason:
+ "The tree's place among surrounding controls depends on composition.",
+ coversRemainderOnly: true,
+ },
+ '2.4.4-link-purpose': {
+ owner: 'the link pattern and caller content',
+ verifiedBy:
+ 'LINK_PATTERN for rows that navigate, plus caller content review',
+ reason:
+ "A row with an address renders its own link; the link's purpose is that pattern's and the caller's.",
+ },
+ '2.4.6-headings-and-labels': {
+ owner: 'the binding component and caller content',
+ verifiedBy: "the component's name tests and caller content review",
+ reason:
+ 'This contract proves the tree has a name; whether that name and the node labels are descriptive is caller content.',
+ coversRemainderOnly: true,
+ },
+ '2.4.7-focus-visible': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ "the component's focus-outline tests and rendered focus review",
+ reason:
+ "The focused row's indicator is a paint result owned by the binding and theme.",
+ },
+ '2.4.11-focus-not-obscured': {
+ owner: 'the composing page',
+ verifiedBy: 'page-level layout review',
+ reason:
+ 'Whether another surface covers the focused row depends on composition.',
+ },
+ '2.5.2-pointer-cancellation': {
+ owner: 'the binding component',
+ verifiedBy: "the component's row press tests",
+ reason:
+ "A tree node activates on click, not on pointer-down; press cancellation is the row control's generic behavior, outside this keyboard-model contract.",
+ },
+ '2.5.3-label-in-name': {
+ owner: 'the binding component',
+ verifiedBy: "the component's accessible-name tests",
+ reason:
+ "Whether a row's accessible name contains its visible label is the binding's row-naming requirement.",
+ },
+ '2.5.8-target-size': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ "the repository axe audit's target-size rule over rows and chevrons",
+ reason:
+ 'Row and chevron hit areas are geometry owned by the binding and theme.',
+ },
+ '3.1.1-language-of-page': {
+ owner: 'the page',
+ verifiedBy: 'page-level review',
+ reason: 'A tree owns no document language.',
+ },
+ '3.2.2-on-input': {
+ owner: 'the caller and composing page',
+ verifiedBy:
+ "integration review of what a node's own action does on Enter or click",
+ reason:
+ "Moving focus and opening a node are the tree's own keyboard model; any further context change is the caller's action.",
+ },
+ '3.2.4-consistent-identification': {
+ owner: 'the composing page',
+ verifiedBy:
+ 'this shared contract across bindings plus content review of repeated row labels',
+ reason:
+ 'Consistency is a property of the full set of repeated functions, not one isolated tree.',
+ },
+ '3.3.1-error-identification': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ "this contract's structure rows (every treeitem is a named navigation node) and source review of caller start and end content",
+ reason:
+ 'A tree row collects no input of its own, so there is no entry to be in error; a control a caller places in start or end content reports its own errors.',
+ },
+ '3.3.2-labels-or-instructions': {
+ owner: 'the binding component and caller content',
+ verifiedBy: "the component's name tests and caller content review",
+ reason:
+ 'A tree row collects no input that needs instructions; this contract proves rows are named, and the caller supplies any guidance around the tree.',
+ },
+ '4.1.2-name-role-value': {
+ owner: 'the link and button patterns, and the binding component',
+ verifiedBy:
+ 'LINK_PATTERN and BUTTON_PATTERN for the controls a row renders, plus binding-local name tests',
+ reason:
+ "This contract encodes the tree and node roles and names, the expanded state, and the multiselect claim. A row's inner link or button keeps its own pattern.",
+ coversRemainderOnly: true,
+ },
+ '4.1.3-status-messages': {
+ owner:
+ 'the caller and the assistive-technology verification record, spec:AST-009',
+ verifiedBy:
+ 'the status-message pattern and real-AT evidence under AST-009 when a change claims spoken or braille output',
+ reason:
+ 'Opening a node or moving focus is not a status-message contract, and this pattern makes no announcement claim.',
+ },
+ 'apg-interaction': {
+ owner: "the binding component's record",
+ verifiedBy:
+ 'component:TreeList AR1 and DEC-2, which adopt the model and name what is left out',
+ reason:
+ "This contract encodes the Tree View structure and keyboard model. Selection keyboard (Shift/Control combinations) and the optional * key are not adopted by the binding's record; Space is activation here, not selection.",
+ coversRemainderOnly: true,
+ },
+ 'forced-colors': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ "the component's forced-colors tests plus rendered Windows High Contrast review",
+ reason:
+ 'Forced-colors output is a paint result owned by the binding and theme.',
+ },
+ 'reduced-motion': {
+ owner: 'the binding component and theme',
+ verifiedBy:
+ "the component's reduced-motion source tests and rendered motion review",
+ reason:
+ 'Expand and collapse motion is binding-specific paint over time and is not part of tree semantics.',
+ },
+ 'at-facing-strings': {
+ owner: 'the binding component and caller content',
+ verifiedBy:
+ 'the repository i18n catalog check and source review of authored labels',
+ reason:
+ 'The tree contract introduces no string; the tree name and row text come from the binding or caller.',
+ },
+ },
+ });
diff --git a/packages/core/src/TreeList/__tests__/TreeList.a11y.chromium.spec.ts b/packages/core/src/TreeList/__tests__/TreeList.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..452f70b8fd
--- /dev/null
+++ b/packages/core/src/TreeList/__tests__/TreeList.a11y.chromium.spec.ts
@@ -0,0 +1,125 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TreeList.a11y.chromium.spec.ts
+ * @input Built TreeList tree-view stories and TREE_VIEW_PATTERN in real Chromium
+ * @output Browser evidence for every tree-view expectation across the binding's states
+ * @position Chromium lane of the TreeList tree-view binding (component:TreeList AR1)
+ */
+
+import {
+ expect,
+ test,
+ type CDPSession,
+ type Locator,
+ type Page,
+} from '@playwright/test';
+import {
+ TREE_VIEW_PATTERN,
+ 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 {
+ TREE_LIST_BINDING_STATES,
+ type TreeListBindingState,
+} from './TreeList.a11y.states';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+function storyUrl(storyId: string): string {
+ return `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story`;
+}
+
+function rowLocator(page: Page, id: string): Locator {
+ return page.locator(
+ `#storybook-root [role="treeitem"][data-tree-id="${id}"]`,
+ );
+}
+
+async function mountState(
+ page: Page,
+ state: TreeListBindingState,
+): Promise<{subject: Locator; related: Record<string, Locator>}> {
+ await page.goto(storyUrl(state.storyId), {waitUntil: 'load'});
+ await holdMotionStill(page);
+ const subject = rowLocator(page, state.subject);
+ await subject.waitFor({state: 'attached'});
+ const root = page.locator('#storybook-root');
+ const related: Record<string, Locator> = {
+ tree: root.getByRole('tree'),
+ before: root.getByRole('button', {name: 'Before the tree'}),
+ after: root.getByRole('button', {name: 'After the tree'}),
+ group: subject.locator('[role="group"]'),
+ };
+ for (const [name, id] of Object.entries(state.relations)) {
+ related[name] = rowLocator(page, id);
+ }
+ return {subject, related};
+}
+
+async function runState(
+ page: Page,
+ cdp: CDPSession,
+ state: TreeListBindingState,
+): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: TREE_VIEW_PATTERN,
+ binding: 'TreeList',
+ state: state.id,
+ facts: state.facts,
+ mount: async () => {
+ const {subject, related} = await mountState(page, state);
+ return createChromiumHarness({page, cdp, subject, related});
+ },
+ });
+}
+
+test('every tree-view expectation is exercised by a TreeList state', async ({
+ page,
+}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const results: BindingResult[] = [];
+ for (const state of TREE_LIST_BINDING_STATES) {
+ results.push(await runState(page, cdp, state));
+ }
+ expect(neverExercised(results)).toEqual([]);
+});
+
+for (const state of TREE_LIST_BINDING_STATES) {
+ test(`TreeList [${state.id}] — ${state.summary}`, async ({page}) => {
+ const cdp = await page.context().newCDPSession(page);
+ const result = await runState(page, cdp, state);
+ const report = summarize(TREE_VIEW_PATTERN, [result]);
+ expect(formatFailures(blockingResults([result]))).toBe('');
+ expect(
+ result.results.filter(
+ row => row.status !== 'pass' && row.status !== 'not-applicable',
+ ),
+ ).toEqual([]);
+ expect(report.unrunLayers).toEqual([]);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+}
diff --git a/packages/core/src/TreeList/__tests__/TreeList.a11y.renders.tsx b/packages/core/src/TreeList/__tests__/TreeList.a11y.renders.tsx
new file mode 100644
index 0000000000..e6a6bd52e8
--- /dev/null
+++ b/packages/core/src/TreeList/__tests__/TreeList.a11y.renders.tsx
@@ -0,0 +1,44 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TreeList.a11y.renders.tsx
+ * @input One TreeList tree-view binding state
+ * @output The React tree every lane renders for that state (the jsdom test directly, the story through Storybook)
+ * @position Shared fixture for the TreeList tree-view binding
+ */
+
+import type {ReactElement} from 'react';
+import {TreeList} from '../TreeList';
+import type {TreeListItemData} from '../TreeListTypes';
+import {
+ TREE_LIST_LABEL,
+ type TreeListBindingState,
+} from './TreeList.a11y.states';
+
+export function renderTreeListState(
+ state: Pick<TreeListBindingState, 'expanded' | 'disabled' | 'direction'>,
+): ReactElement {
+ const expanded = (id: string) => state.expanded.includes(id);
+ const disabled = (id: string) => state.disabled?.includes(id) ?? false;
+ const items: TreeListItemData[] = [
+ {
+ id: 'docs',
+ label: 'Documents',
+ isExpanded: expanded('docs'),
+ isDisabled: disabled('docs'),
+ children: [
+ {id: 'annual', label: 'Annual report'},
+ {id: 'budget', label: 'Budget'},
+ ],
+ },
+ {id: 'photos', label: 'Photos', isDisabled: disabled('photos')},
+ {id: 'trash', label: 'Trash', isDisabled: disabled('trash')},
+ ];
+ return (
+ <div dir={state.direction ?? 'ltr'}>
+ <button type="button">Before the tree</button>
+ <TreeList aria-label={TREE_LIST_LABEL} items={items} />
+ <button type="button">After the tree</button>
+ </div>
+ );
+}
diff --git a/packages/core/src/TreeList/__tests__/TreeList.a11y.states.ts b/packages/core/src/TreeList/__tests__/TreeList.a11y.states.ts
new file mode 100644
index 0000000000..6806aac36c
--- /dev/null
+++ b/packages/core/src/TreeList/__tests__/TreeList.a11y.states.ts
@@ -0,0 +1,164 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TreeList.a11y.states.ts
+ * @input TreeList's representative tree-view states and the facts TREE_VIEW_PATTERN reads
+ * @output TREE_LIST_BINDING_STATES, the shared item data, and the explicit ownership exclusions for this binding
+ * @position Binding inventory shared by the jsdom test, the Chromium spec, and the story (component:TreeList AR1)
+ */
+
+import type {TreeViewStateFacts} from '@astryxdesign/a11y-spec';
+
+export interface TreeListBindingState {
+ readonly id: string;
+ readonly summary: string;
+ readonly storyId: string;
+ /** `data-tree-id` of the subject row. */
+ readonly subject: string;
+ /** `data-tree-id` of each relation row the facts say exists. */
+ readonly relations: Readonly<
+ Partial<
+ Record<
+ 'first-child' | 'parent' | 'next' | 'previous' | 'typeahead-target',
+ string
+ >
+ >
+ > & {readonly first: string; readonly last: string};
+ readonly facts: TreeViewStateFacts;
+ /** Which parent rows start expanded. */
+ readonly expanded: ReadonlyArray<string>;
+ /** Which rows are disabled. */
+ readonly disabled?: ReadonlyArray<string>;
+ readonly direction?: 'ltr' | 'rtl';
+}
+
+export const TREE_LIST_LABEL = 'Files';
+
+function facts(
+ overrides: Partial<TreeViewStateFacts> = {},
+): TreeViewStateFacts {
+ return {
+ hasChildren: true,
+ expanded: false,
+ disabled: false,
+ tabbable: true,
+ level: 1,
+ position: 1,
+ setSize: 3,
+ hasNext: true,
+ hasPrevious: false,
+ hasParent: false,
+ rtl: false,
+ typeaheadCharacter: 't',
+ enterToggles: true,
+ ...overrides,
+ };
+}
+
+const story = (id: string) => `a11y-treelist-tree-view--${id}`;
+
+export const TREE_LIST_BINDING_STATES = [
+ {
+ id: 'closed-parent-tab-stop',
+ summary: "the closed Documents parent, the tree's one Tab stop",
+ storyId: story('closed-parent-tab-stop'),
+ subject: 'docs',
+ relations: {
+ next: 'photos',
+ first: 'docs',
+ last: 'trash',
+ 'first-child': 'annual',
+ 'typeahead-target': 'trash',
+ },
+ facts: facts(),
+ expanded: [],
+ },
+ {
+ id: 'open-parent-tab-stop',
+ summary: 'the open Documents parent with its child group',
+ storyId: story('open-parent-tab-stop'),
+ subject: 'docs',
+ relations: {
+ next: 'annual',
+ first: 'docs',
+ last: 'trash',
+ 'first-child': 'annual',
+ 'typeahead-target': 'trash',
+ },
+ facts: facts({expanded: true}),
+ expanded: ['docs'],
+ },
+ {
+ id: 'end-node',
+ summary: 'the Photos end node, which is not the Tab stop',
+ storyId: story('end-node'),
+ subject: 'photos',
+ relations: {
+ next: 'trash',
+ previous: 'docs',
+ first: 'docs',
+ last: 'trash',
+ 'typeahead-target': 'docs',
+ },
+ facts: facts({
+ hasChildren: false,
+ tabbable: false,
+ position: 2,
+ hasPrevious: true,
+ typeaheadCharacter: 'd',
+ enterToggles: false,
+ }),
+ expanded: [],
+ },
+ {
+ id: 'closed-parent-rtl',
+ summary: 'the closed Documents parent in a right-to-left tree',
+ storyId: story('closed-parent-rtl'),
+ subject: 'docs',
+ relations: {
+ next: 'photos',
+ first: 'docs',
+ last: 'trash',
+ 'first-child': 'annual',
+ 'typeahead-target': 'trash',
+ },
+ facts: facts({rtl: true}),
+ expanded: [],
+ direction: 'rtl',
+ },
+ {
+ id: 'disabled-end-node',
+ summary:
+ 'the disabled Trash end node: exposed and positioned, not operable',
+ storyId: story('disabled-end-node'),
+ subject: 'trash',
+ relations: {previous: 'photos', first: 'docs', last: 'trash'},
+ facts: facts({
+ hasChildren: false,
+ disabled: true,
+ tabbable: false,
+ position: 3,
+ hasNext: false,
+ hasPrevious: true,
+ typeaheadCharacter: null,
+ enterToggles: false,
+ }),
+ expanded: [],
+ disabled: ['trash'],
+ },
+] as const satisfies ReadonlyArray<TreeListBindingState>;
+
+export const TREE_LIST_EXCLUSIONS = [
+ {
+ id: 'row-name-composition',
+ owner: 'component:TreeList AR1 and TreeList.test.tsx',
+ reason:
+ "This binding proves each row has a treeitem role and a non-empty name. Which text makes up that name — the label alone, without the chevron toggle, description, or start and end content — is the record's row-naming requirement, proven by TreeList's own name tests and browser evidence rather than by the shared pattern.",
+ },
+ {
+ id: 'selection-keyboard',
+ owner: 'component:TreeList AR1 and DEC-2',
+ reason:
+ 'Selection is caller-owned (isSelected) with at most one row selected; the tree adopts no selection keyboard (Shift or Control combinations; Space is activation, covered by the contract) and not the optional * key, so the contract asserts only that the tree makes no multiselect claim.',
+ },
+] as const;
diff --git a/packages/core/src/TreeList/__tests__/TreeList.a11y.test.tsx b/packages/core/src/TreeList/__tests__/TreeList.a11y.test.tsx
new file mode 100644
index 0000000000..dfdd3f11d5
--- /dev/null
+++ b/packages/core/src/TreeList/__tests__/TreeList.a11y.test.tsx
@@ -0,0 +1,138 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @vitest-environment jsdom */
+
+/**
+ * @file TreeList.a11y.test.tsx
+ * @input TREE_VIEW_PATTERN bound to TreeList's representative states
+ * @output jsdom-lane proof of the DOM expectations and an honest "unrun" report for the browser layers
+ * @position Binding test for component:TreeList AR1 (the Chromium spec covers the rest)
+ */
+
+import {cleanup, render, screen} from '@testing-library/react';
+import {describe, expect, it} from 'vitest';
+import {
+ TREE_VIEW_PATTERN,
+ checkAccessibilitySpec,
+ createJsdomHarness,
+ expectAccessibilitySpec,
+ summarize,
+ type BindingResult,
+} from '@astryxdesign/a11y-spec';
+import {renderTreeListState} from './TreeList.a11y.renders';
+import {
+ TREE_LIST_BINDING_STATES,
+ TREE_LIST_EXCLUSIONS,
+ type TreeListBindingState,
+} from './TreeList.a11y.states';
+
+function row(id: string): Element {
+ const element = document.querySelector(
+ `[role="treeitem"][data-tree-id="${id}"]`,
+ );
+ if (element == null) {
+ throw new Error(`no treeitem row "${id}"`);
+ }
+ return element;
+}
+
+function relatedFor(
+ state: TreeListBindingState,
+): Readonly<Record<string, Element>> {
+ const related: Record<string, Element> = {
+ tree: screen.getByRole('tree'),
+ before: screen.getByRole('button', {name: 'Before the tree'}),
+ after: screen.getByRole('button', {name: 'After the tree'}),
+ };
+ for (const [name, id] of Object.entries(state.relations)) {
+ const element = document.querySelector(
+ `[role="treeitem"][data-tree-id="${id}"]`,
+ );
+ if (element != null) {
+ related[name] = element;
+ }
+ }
+ const group = row(state.subject).querySelector('[role="group"]');
+ if (group != null) {
+ related.group = group;
+ }
+ return related;
+}
+
+async function checkState(state: TreeListBindingState): Promise<BindingResult> {
+ return checkAccessibilitySpec({
+ spec: TREE_VIEW_PATTERN,
+ binding: 'TreeList',
+ state: state.id,
+ facts: state.facts,
+ mount: async () => {
+ render(renderTreeListState(state));
+ return createJsdomHarness({
+ subject: row(state.subject),
+ related: relatedFor(state),
+ });
+ },
+ unmount: cleanup,
+ });
+}
+
+describe('TreeList — tree-view pattern, jsdom lane', () => {
+ it.each(
+ TREE_LIST_BINDING_STATES.map(
+ state => [state.id, state.summary, state] as const,
+ ),
+ )('%s — %s', async (_id, _summary, state) => {
+ await expectAccessibilitySpec({
+ spec: TREE_VIEW_PATTERN,
+ binding: 'TreeList',
+ state: state.id,
+ facts: state.facts,
+ render: () => {
+ render(renderTreeListState(state));
+ },
+ subject: () => row(state.subject),
+ related: () => relatedFor(state),
+ cleanup,
+ });
+ });
+
+ it('runs the DOM layer and reports the browser-owned outcomes as unrun', async () => {
+ const results: BindingResult[] = [];
+ for (const state of TREE_LIST_BINDING_STATES) {
+ results.push(await checkState(state));
+ }
+ const report = summarize(TREE_VIEW_PATTERN, results);
+ expect(report.counts.pass).toBeGreaterThan(0);
+ expect(report.unrunLayers).toEqual(['accessibility-tree', 'real-browser']);
+ expect(report.counts.unexpectedPass).toBe(0);
+ });
+});
+
+describe('TreeList tree-view binding inventory', () => {
+ it('gives every representative state a distinct checked-in story', () => {
+ const stories = TREE_LIST_BINDING_STATES.map(state => state.storyId);
+ expect(new Set(stories).size).toBe(stories.length);
+ });
+
+ it('keeps row-name composition and selection ownership explicit', () => {
+ expect(TREE_LIST_EXCLUSIONS.map(exclusion => exclusion.id)).toEqual([
+ 'row-name-composition',
+ 'selection-keyboard',
+ ]);
+ for (const exclusion of TREE_LIST_EXCLUSIONS) {
+ expect(exclusion.owner.length, exclusion.id).toBeGreaterThan(20);
+ expect(exclusion.reason.length, exclusion.id).toBeGreaterThan(80);
+ }
+ });
+
+ it('renders the subject row, the tree, and the first/last rows for every state', () => {
+ for (const state of TREE_LIST_BINDING_STATES) {
+ render(renderTreeListState(state));
+ expect(row(state.subject), state.id).toBeTruthy();
+ const related = relatedFor(state);
+ expect(Object.keys(related), state.id).toEqual(
+ expect.arrayContaining(['tree', 'before', 'after', 'first', 'last']),
+ );
+ cleanup();
+ }
+ });
+});