Skip to content

Encode APG patterns as reusable ARIA conformance contracts (internal aria-spec suite) #4112

Open

Description

@cixzhang

Summary

We've landed a lot of accessibility work recently, but the knowledge lives in ~120 per-component tests with no shared contract. There's no way to answer "which APG patterns are fully covered, across which components?" This proposes an internal, unpublished package (@astryxdesign/aria-spec at internal/aria-spec/) that encodes each WAI-ARIA APG pattern as a reusable, data-driven conformance contract, and binds components to it. It covers behavior, structure, and (scoped) visual checks, and emits a coverage matrix so conformance becomes a tracked metric rather than scattered green/red tests.

Internal-only to start (private: true, alongside test-utils, vibe-tests, etc.). Not published to npm.

Motivation

  • No pattern-level view. APG interaction IDs already show up ad-hoc in test names (menus-11, menus-13, checkbox-42, switch-1) — the instinct exists, but there's no system behind it.
  • Contracts are copy-pasted. Each component re-derives "a checkbox should toggle on Space, expose aria-checked, be labelled." That logic should be authored once per pattern and reused.
  • Gaps are invisible. When a component partially conforms, that gap isn't recorded anywhere greppable.
  • Unused deps. @axe-core/playwright and @playwright/test are in package.json but wired to nothing.

Design

Three-layer architecture

internal/aria-spec/                         (private, unpublished)
├── patterns/            one contract per APG pattern, authored as DATA + assertions
│   switch.ts    →  expectations: [
│                      { id: 'switch-role-and-checked', priority: 'blocker', run },
│                      { id: 'switch-space-toggles',    priority: 'blocker', run },
│                      { id: 'switch-labelled',         priority: 'blocker', run },
│                      { id: 'switch-optionally-described', priority: 'major', run },
│                      ...
│                    ]
├── primitives/          keyboard / focus / aria / dom helpers (runtime-agnostic)
├── harness/             AriaHarness adapter interface (jsdom + browser implementations)
├── runner/              runContract(pattern, { harness, bindings, expectedFailures })
└── report/              emits JSON → coverage matrix (pattern × component × expectation)

1. Patterns as data, with priority tiers

Each pattern is a typed set of expectations, each tagged with a priority: blocker | major | minor | optional. CI gates on blocker; the rest are reported. This lets us gate meaningfully without blocking on optional-authoring niceties.

2. Components bind the contract + declare expectedFailures

The per-component test stays tiny and is honest about gaps:

runSwitchContract({
  render: () => <Switch label="Notifications" isOn={false} onChange={() => {}} />,
  expectedFailures: [
    // tracked gap, not a missing test
  ],
});

expectedFailures is the key adoption mechanism: we roll the contract across all 122 components immediately, and every gap becomes an explicit, greppable, reviewable line instead of a missing test. Burning down expectedFailures becomes the hardening backlog.

3. Coverage matrix

The runner emits pattern × component × expectation results → a coverage report (% of expectations passing per component, per pattern). This turns APG conformance into a dashboard metric.

Runtime: two tiers, runtime-agnostic contracts

Expectations are authored against an abstract AriaHarness adapter (render / query-by-role / get-attribute / press-key / focus / accessible-name), so the same contract runs in either tier. This mirrors the proven internal ARIA-spec design (specs take an optional device param; default = in-process, override = real browser).

Tier 1 — jsdom (default, fast, every PR)

Vitest + Testing Library + user-event — the stack our existing tests already use. Genuinely covers the majority of APG expectations: role presence, accessible-name computation, ARIA state wiring (aria-expanded/-controls/-checked/-selected/-activedescendant, aria-labelledby/-describedby), and keyboard behavior (arrows, Home/End, typeahead, Enter/Space, Escape, Tab moving activeElement). Runs in the existing pnpm test path.

Tier 2 — real browser (gated, for fidelity-critical expectations)

jsdom fakes exactly the things composite APG widgets depend on, so a browser tier is necessary — not optional — for full conformance:

  • The real accessibility tree as exposed to AT (jsdom only approximates it) → toMatchAriaSnapshot
  • Focus-trap Tab wrapping, inert, native <dialog>.showModal(), Popover API top layer (all currently mocked in our tests — e.g. Switch/DropdownMenu stub showPopover)
  • :focus-visible and forced-colors state (CSS-engine, invisible to jsdom)

Runner decision: Vitest Browser Mode (@vitest/browser + Playwright/Chromium provider), added as a third Vitest project (browser) alongside the existing ui/node projects. Rationale: one runner, one config, same render()/Testing-Library API as Tier 1 — but document is real Chromium, and the Playwright provider gives native toMatchAriaSnapshot + toHaveScreenshot. Only fidelity-critical expectations opt into this tier.

Runner-up considered: Storybook Test Runner (reuses our 169 stories as fixtures, and CI already builds Storybook) — attractive for a cheap axe-per-story sweep, but it's a second test system with its own conventions. Likely a complement later (axe-per-story in the storybook job), not the primary contract runtime.

Structure & visual layers

  • Structure (static): wire axe-core (vitest-axe in Tier 1) as a per-component pass — contrast/name/dup-id/role violations. Complements, does not replace, the behavior expectations.
  • Structure (tree): accessibility-tree snapshot (toMatchAriaSnapshot) — a text YAML of roles/names, reviewable in PRs, no pixels. Tier 2.
  • Visual (pixels): scoped tight — screenshots only for inherently-visual a11y states (:focus-visible ring, forced-colors/high-contrast, reduced-motion). Real screenshots + browser, its own opt-in/nightly job, ~2 themes. Not in the blocking path.

CI shape

Leverages the existing check-scope gating (jobs already skip docsite-only PRs) and the existing build-storybook job.

check-scope ──┬─► test (jsdom Tier 1, fast)          ← blocker + all, every PR   [existing]
              ├─► build-storybook                    ← + optional axe-per-story sweep
              ├─► aria-spec-browser (Tier 2)         ← blocker-gated, component PRs only, cached Chromium
              └─► aria-spec-visual (screenshots)     ← nightly / labeled, non-blocking

Streamlining levers:

  • Gate Tier 2 on a component_changed scope output (extend the existing changed-files step) — don't run the browser tier on non-component PRs.
  • Gate the build only on blocker expectations; upload the full coverage matrix as an artifact for major/minor. Lets us enable across 122 components without a wall of red.
  • Cache the Playwright browser (~/.cache/ms-playwright, keyed on Playwright version) — the install is the slow part, not the tests.
  • Chromium-only per-PR (the a11y tree + keyboard are engine-consistent); cross-browser is a nightly concern.
  • Shard Tier 2 (--shard=i/N) only if/when the suite grows.

Consolidation

Existing a11y assertions scattered across *.test.tsx should move/consolidate into the pattern contracts. The ad-hoc APG-tagged tests (menus-*, checkbox-42, switch-1) become the first expectedFailures-free contract bindings. Goal: one authoritative place per pattern, per-component tests reduced to a binding + a gap list.

Scope of the first prototype (separate PR)

Prove the architecture end-to-end on one pattern before authoring all patterns:

  • internal/aria-spec/ package scaffold (private: true), AriaHarness interface + jsdom adapter
  • Runner with priority tiers + expectedFailures, coverage-matrix emit
  • Author the Switch/Checkbox pattern contract (existing switch-1/checkbox-42 tags to migrate)
  • Bind Switch (+ Checkbox) as jsdom (Tier 1) contract tests, running in the existing suite
  • Wire the Tier 2 browser project (Vitest Browser Mode) + one browser binding proving toMatchAriaSnapshot
  • Emit a JSON coverage matrix + human-readable summary
  • Migrate the existing ad-hoc APG-tagged assertions into the new contract

Explicitly out of scope (follow-ups)

  • vitest-axe structural pass wiring (dep not yet installed)
  • Pixel screenshots for focus/contrast states
  • Authoring the remaining ~22 patterns
  • Coverage dashboard UI
  • Storybook axe-per-story sweep

Open questions

  • Package name / location: @astryxdesign/aria-spec at internal/aria-spec/ — OK?
  • Pattern authoring format — pure TS modules vs. a declarative spec object the runner interprets?
  • Do we gate CI on blocker expectations from day one, or report-only until coverage is broad?

Activity

  1. self-assigned this
    on Jul 20, 2026
  2. added
    enhancement
    needs-scoping
    on Jul 20, 2026
  3. cixzhang commented on Jul 20, 2026

    @cixzhang
    ContributorAuthor

    Draft prototype up in #4113 — full architecture proven end-to-end on the Switch pattern (both tiers), with the contract verified to catch regressions. Kept as a draft for architecture review before scaling to the remaining patterns.

  4. cixzhang commented on Jul 20, 2026

    @cixzhang
    ContributorAuthor

    Addendum: how Base UI (@base-ui-components/react) tests accessibility

    Looked at Base UI's actual test source (successor to MUI Base, by the Floating UI + MUI teams) since it's the closest modern analog to what we're building. Findings, and what they validate or challenge in our design:

    Their architecture

    • describeConformance(<Component />, options) — a shared, reusable structural contract every component runs: prop spreading, ref forwarding, className/render-prop forwarding, data-* passthrough. This is exactly our "one contract, many components" idea, but scoped to composition/structure rather than APG semantics.
    • popupConformanceTests(config) — a shared behavioral contract for popup-family components (Menu, Select, Popover, Tooltip…): open/close in controlled + uncontrolled modes, correct role, aria-haspopup, focus behavior. Config-driven (expectedPopupRole, expectedAriaHasPopupValue, triggerMouseAction) — the same "contract + per-component bindings + expected values" shape as our pattern contracts.
    • Custom a11y matchers, e.g. toBeInaccessible() — they assert an element is removed from the accessibility tree, not just visually hidden. Worth stealing for our closed/hidden-state expectations.
    • Per-component tests still hand-write the pattern-specific keyboard/ARIA assertions (e.g. Switch: aria-checked toggling via click, external state, underlying input, and Enter/Space via user.keyboard('[Tab]') then [Space]). There is no single APG-pattern abstraction across components — each component re-derives its own keyboard/role assertions. This is the gap our pattern contracts close.

    The big one: Base UI runs unit tests in a REAL browser by default

    Their pnpm test maps to test:chromium — the unit suite runs in real Chromium via Vitest Browser Mode + @vitest/browser-playwright. jsdom is the opt-in fallback (test:jsdom), and test:browsers runs the same suite across Chromium + Firefox + WebKit. A single vitest.shared.mts switches environment off a VITEST_ENV var; e2e is a separate project served by Vite.

    This is strong external validation of two of our calls:

    1. Vitest Browser Mode + Playwright provider is the right runner — it's what Base UI standardized on (same defineProject + playwright() provider factory our vitest.config.browser.ts uses).
    2. The browser tier isn't a nice-to-have. A leading a11y-focused component library runs its entire unit suite in real browsers because jsdom fidelity isn't enough. It nudges us to keep the browser tier first-class rather than a rarely-run afterthought.

    Where we differ (deliberately)

    Base UI This proposal
    Shared contract Structural (describeConformance) + popup-behavior APG-pattern conformance (role + name + state + keyboard, per W3C pattern)
    Pattern abstraction None — each component hand-writes keyboard/ARIA One contract per APG pattern, bound to N components
    Coverage view Pass/fail per test pattern × component matrix + 0–100 score
    Known gaps Skipped/omitted tests expectedFailures — explicit, greppable, un-skips on regression
    Default runtime Real browser (jsdom opt-in) jsdom default (fast), browser tier gated

    What to adopt from them

    • toBeInaccessible()-style matchers for closed/hidden state assertions (better than checking display:none).
    • Config-driven behavioral contracts for component families (their popup pattern) — a good model for our composite patterns (menu/listbox/dialog) where one "pattern" spans a trigger + popup + items.
    • Reconsider making the browser tier heavier per-PR. Base UI proves it's viable to run a large unit suite in-browser. We can start gated, but their setup shows the browser tier can scale to be the primary one if jsdom gaps bite.
    • Their env-var-driven single shared config (VITEST_ENV=chromium|jsdom|all-browsers) is a cleaner multi-tier switch than my separate vitest.config.browser.ts — worth folding our two configs into one.

    Net: Base UI independently arrived at "shared reusable conformance contracts + Vitest Browser Mode," which de-risks our approach. Our net-new contribution over Base UI is the APG-pattern layer (semantics keyed off role, reused across components, with a coverage matrix) — the thing that makes it a specification suite rather than per-component tests.

  5. cixzhang commented on Jul 28, 2026

    @cixzhang
    ContributorAuthor

    Tracked in the accessibility program tracker: #4475

  6. cixzhang commented on Jul 28, 2026

    @cixzhang
    ContributorAuthor

    Tracked in the accessibility program tracker: #4475

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:coreenhancementneeds-scopingtype:test

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions