An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] CheckboxList: keep each saving option busy until its change settles (#6777)
Cindy Zhang85bdae535255
diff --git a/.changeset/checkbox-list-concurrent-pending.md b/.changeset/checkbox-list-concurrent-pending.mdnew file mode 100644index 0000000000..86ad939773--- /dev/null+++ b/.changeset/checkbox-list-concurrent-pending.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A CheckboxList option that is saving through `changeAction` now keeps its spinner, busy state, and re-toggle guard when another option is toggled before it settles.++@cixzhangdiff --git a/.changeset/checkbox-list-docs-read-only.md b/.changeset/checkbox-list-docs-read-only.mdnew file mode 100644index 0000000000..f9d6e401c1--- /dev/null+++ b/.changeset/checkbox-list-docs-read-only.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[docs] Document CheckboxList's `isReadOnly` prop, and separate the select-all block example's rows with `hasDividers` instead of placing a Divider inside the options list.++@cixzhangdiff --git a/.changeset/checkbox-list-read-only-item-click.md b/.changeset/checkbox-list-read-only-item-click.mdnew file mode 100644index 0000000000..171976b19f--- /dev/null+++ b/.changeset/checkbox-list-read-only-item-click.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Clicking a read-only CheckboxList option that has an `onClick` now fires that handler once, instead of re-dispatching the click until the browser's call stack overflows.++@cixzhangdiff --git a/.github/a11y-baseline.json b/.github/a11y-baseline.jsonindex 03f106f402..7bcdcf8bc7 100644--- a/.github/a11y-baseline.json+++ b/.github/a11y-baseline.json@@ -108,21 +108,6 @@"impact": "serious","helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"},- {- "key": "CheckboxList::Inside Card::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },- {- "key": "CheckboxList::Standalone Mode::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },- {- "key": "CheckboxList::With End Content::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },{"key": "ClickableCard::Disabled::color-contrast","impact": "serious",diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 88d52bafcb..bf90975392 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1132,6 +1132,49 @@ jobs:retention-days: 30if-no-files-found: error+ # CheckboxList's component audit grades interactive row paint, focus,+ # busy, disabled, read-only, status, narrow, forced-colors, and RTL states+ # from exact-head Chromium receipts. The shared checkbox contract also runs+ # for its CheckboxListItem bindings, with its own output directory so it+ # cannot clear the receipts. Each lane runs even when another fails, and+ # the step still runs after an earlier audit step fails, so a+ # failing-before head banks complete evidence.+ - name: Run CheckboxList audit browser evidence+ if: ${{ !cancelled() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] CheckboxList:') }}+ env:+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ PLAYWRIGHT_JSON_OUTPUT_NAME: checkbox-list-pattern-results.json+ run: |+ status=0+ node .github/scripts/accessibility-audit.js \+ --storybook-dir apps/storybook/dist \+ --output checkbox-list-a11y-report.json \+ --components CheckboxList \+ --baseline .github/a11y-baseline.json \+ --fail-on-new || status=1+ pnpm exec playwright test \+ packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.chromium.spec.ts \+ --project chromium \+ --grep 'CheckboxListItem \[' \+ --output checkbox-list-pattern-output \+ --reporter=list,json || status=1+ pnpm exec playwright test \+ packages/core/src/CheckboxList/__tests__/CheckboxList.a11y.chromium.spec.ts \+ --project chromium || status=1+ exit "$status"++ - name: Upload CheckboxList audit evidence+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] CheckboxList:')+ uses: actions/upload-artifact@v7+ with:+ name: checkbox-list-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: |+ checkbox-list-a11y-report.json+ checkbox-list-pattern-results.json+ test-results/checkbox-list-audit-evidence/+ retention-days: 30+ if-no-files-found: error+# Run the exhaustive contract/fixture matrix at release time. PRs retain# scoped axe validation and the fast interaction guards above; they must# not pay for every component's browser bindings on every change.diff --git a/apps/storybook/stories/CheckboxList.stories.tsx b/apps/storybook/stories/CheckboxList.stories.tsxindex 57995cc21c..a61b5ec473 100644--- a/apps/storybook/stories/CheckboxList.stories.tsx+++ b/apps/storybook/stories/CheckboxList.stories.tsx@@ -4,8 +4,10 @@ import {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {CheckboxList, CheckboxListItem} from '@astryxdesign/core/CheckboxList';import {List} from '@astryxdesign/core/List';+import {Badge} from '@astryxdesign/core/Badge';import {Card} from '@astryxdesign/core/Card';import {Link} from '@astryxdesign/core/Link';+import CheckboxListSelectAllPattern from '../../../packages/cli/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern';const meta: Meta<typeof CheckboxList> = {title: 'Core/CheckboxList',@@ -242,6 +244,14 @@ export const SelectAllWithIndeterminate: Story = {},};+/**+ * The select-all block exactly as the CLI ships it, so browser and axe audits+ * cover the copied template rather than a look-alike.+ */+export const SelectAllPatternBlock: Story = {+ render: () => <CheckboxListSelectAllPattern />,+};+export const Disabled: Story = {render: args => {const [value, setValue] = useState<string[]>(['email']);@@ -352,19 +362,19 @@ export const WithEndContent: Story = {label="Free tier"value="free"description="Basic features included"- endContent={<span style={{color: '#0D8626'}}>$0/mo</span>}+ endContent={<Badge variant="success" label="$0/mo" />}/><CheckboxListItemlabel="Pro tier"value="pro"description="Advanced features"- endContent={<span style={{color: '#0064E0'}}>$9/mo</span>}+ endContent={<Badge variant="info" label="$9/mo" />}/><CheckboxListItemlabel="Enterprise"value="enterprise"description="Custom solutions"- endContent={<span style={{color: '#5B08D8'}}>Custom</span>}+ endContent={<Badge variant="purple" label="Custom" />}/></CheckboxList>);@@ -499,6 +509,48 @@ export const InsideCardWithDividers: Story = {},};+// Long option content in a sized field. String labels and descriptions stay on+// one line with an ellipsis (the full string still names the checkbox); rich+// labels and descriptions wrap. `width` sizes the label, list, and status+// together.+export const LongContent: Story = {+ render: args => {+ const [value, setValue] = useState<string[]>(['comments']);+ const {value: _value, onChange: _onChange, ...restArgs} = args;+ return (+ <CheckboxList {...restArgs} value={value} onChange={setValue}>+ <CheckboxListItem+ label="Comments, mentions, and replies across every shared workspace"+ value="comments"+ description="Delivered to the primary address listed in your account settings"+ />+ <CheckboxListItem+ label={+ <span>+ Security alerts for new sign-ins on phones, tablets, and desktops+ </span>+ }+ value="security"+ description={+ <span>+ Includes a weekly summary of every device that accessed your+ account+ </span>+ }+ />+ <CheckboxListItem label="SMS" value="sms" />+ </CheckboxList>+ );+ },+ args: {+ label: 'Notification channels for workspace activity and account security',+ description:+ 'Choose every channel that should receive these notifications. You can change this at any time.',+ width: 280,+ hasDividers: true,+ },+};+// Disabled with an explanation tooltip. Hover or keyboard-focus the group to see// why it's disabled — the reason is announced to assistive tech via// aria-describedby, and the checkboxes stay focusable (toggling is stilldiff --git a/packages/cli/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern.doc.mjs b/packages/cli/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern.doc.mjsindex 9d6757c00d..f2581695ea 100644--- a/packages/cli/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern.doc.mjs@@ -10,5 +10,5 @@ export const doc = {'A "select all" toggle at the top of a checkbox list that switches to an indeterminate dash when only some items are checked, useful for bulk actions like exporting documents or assigning permissions where users often want everything at once.',isReady: true,aspectRatio: 16 / 9,- componentsUsed: ['CheckboxList', 'Divider'],+ componentsUsed: ['CheckboxList'],};diff --git a/packages/cli/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern.tsx b/packages/cli/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern.tsxindex 3b100d8afc..418619e221 100644--- a/packages/cli/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern.tsx+++ b/packages/cli/assets/templates/blocks/components/CheckboxList/CheckboxListSelectAllPattern.tsx@@ -4,7 +4,6 @@import {useState} from 'react';import {CheckboxList, CheckboxListItem} from '@astryxdesign/core/CheckboxList';-import {Divider} from '@astryxdesign/core/Divider';const DOCUMENTS = [{id: 'transactions', label: 'Transaction history'},@@ -27,7 +26,7 @@ export default function CheckboxListSelectAllPattern() {: ('indeterminate' as const);return (- <CheckboxList label="Include in export">+ <CheckboxList label="Include in export" hasDividers><CheckboxListItemlabel="Select all"isChecked={selectAllState}@@ -35,7 +34,6 @@ export default function CheckboxListSelectAllPattern() {setSelected(checked ? [...ALL_IDS] : []);}}/>- <Divider />{DOCUMENTS.map(doc => (<CheckboxListItemkey={doc.id}diff --git a/packages/core/src/CheckboxList/CheckboxList.doc.mjs b/packages/core/src/CheckboxList/CheckboxList.doc.mjsindex 3dc819e32d..c9bb9de85b 100644--- a/packages/core/src/CheckboxList/CheckboxList.doc.mjs+++ b/packages/core/src/CheckboxList/CheckboxList.doc.mjs@@ -151,6 +151,13 @@ export const docs = {description:'Explains why the group is disabled. Applies to the whole-group disabled state (isDisabled), not per item. With isDisabled, shows a tooltip on hover/keyboard focus and keeps the checkboxes focusable via aria-disabled (toggling stays blocked). Use this instead of wrapping a disabled CheckboxList in Tooltip. Disabled controls swallow the hover events an external Tooltip needs.',},+ {+ name: 'isReadOnly',+ type: 'boolean',+ description:+ 'Whether all checkbox items are read-only. Displays the current state at full opacity but prevents interaction. Unlike isDisabled, read-only checkboxes are not visually dimmed.',+ default: 'false',+ },{name: 'status',type: "{type: 'warning' | 'error' | 'success', message?: string}",diff --git a/packages/core/src/CheckboxList/CheckboxList.spec.md b/packages/core/src/CheckboxList/CheckboxList.spec.mdindex cae69d4d7c..47f06cfded 100644--- a/packages/core/src/CheckboxList/CheckboxList.spec.md+++ b/packages/core/src/CheckboxList/CheckboxList.spec.md@@ -1,6 +1,6 @@---schema_version: 3-template_version: 3+template_version: 6kind: componentid: component:CheckboxListauthority: draft@@ -9,36 +9,61 @@ superseded_by: nullapproved_by: nullapproved_at: nullowners: [cixzhang]-review_triggers: [theming]+review_triggers:+ [public-api, behavior, interaction, theming, accessibility, visual]verified_by:[packages/core/src/CheckboxList/CheckboxList.test.tsx,+ packages/core/src/CheckboxList/__tests__/CheckboxList.a11y.chromium.spec.ts,+ packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.test.tsx,+ packages/core/src/CheckboxInput/__tests__/Checkbox.a11y.chromium.spec.ts,packages/core/src/theme/themingTargets.test.ts,+ apps/storybook/stories/CheckboxList.stories.tsx,scripts/check-knowledge.mjs,]modules: []families: []design_specs: []-architecture: [architecture:component-theming-surface]+architecture:+ [+ architecture:public-component-api,+ architecture:component-theming-surface,+ architecture:component-test-sufficiency,+ architecture:interaction-modality,+ ]contributing: []-system_specs: []+system_specs: [spec:AST-011, spec:AST-021, spec:AST-038]---# CheckboxList component contract+## Contract at a glance++| Area | Contract |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `CheckboxList` is a labeled `role="group"` of `CheckboxListItem` rows. A `value` array selects controlled collection mode (`onChange`, `changeAction`); without it, items use standalone `isChecked`/`onCheck`. The group owns disabled, disabled-reason, read-only, and status. |+| Behavior | Each option is one native checkbox and one tab stop; the row surface delegates clicks to it. A toggled item stays busy and cannot be re-toggled while its `changeAction` is pending, while other items stay interactive. |+| End-user impact | People can identify the group, operate every option by pointer, touch, and keyboard, learn why a group is unavailable, and see which options are still saving. |+| Builder impact | Builders choose collection or standalone mode and supply stable item `value`s in collection mode. Handlerless, invalid-status, pass-through-target, checked-row theming and feedback, and focus-ring ownership remain owner decisions. |+| Compatibility/readiness | Released API, defaults, DOM ownership, and targets are unchanged. This draft records shipped behavior plus two objective remediations: concurrent pending items keep their busy state, and a read-only item's `onClick` fires once per click instead of looping. |+| Review checks | Reject a second tab stop per option, a pending item that loses busy or its re-toggle guard, an item `onClick` that fires more than once per click, dropped group naming or description ids, disabled or read-only mutation, or new target/state API introduced without an owner decision. |+| Governing rules | `architecture:public-component-api/INV1–INV9`; `architecture:component-theming-surface/INV3–INV6`; `architecture:interaction-modality/INV1–INV4`; `architecture:component-test-sufficiency/INV1–INV7`; `spec:AST-021/FR8–FR10`; `spec:AST-038/FR7`; WCAG 2.2 1.3.1, 2.1.1, 4.1.2. |++This table is a review projection; the body below becomes authoritative only after owner approval.+## Intent-CheckboxList presents a labeled group of checkbox options. This draft records-its current consumer anatomy and the theming ownership of parts rendered by-CheckboxList, List, CheckboxInput, Field, FieldStatus, and Spinner. It changes no-runtime behavior or public API.+Present a small, labeled set of independent checkbox options whose checked,+available, read-only, busy, and status states stay aligned across pointer,+touch, keyboard, and assistive technology.## Compatibility and migration- Released default preserved: `yes`-- Compatibility class: additive documentation only; runtime, DOM, styling,- targets, and public API remain unchanged-- Controlled/uncontrolled behavior: unchanged+- Compatibility class: observational record plus two objective bug fixes; public+ types, defaults, DOM ownership, targets, and focus order are unchanged+- Controlled/uncontrolled behavior: collection mode is controlled by `value`;+ standalone items are controlled by `isChecked`; no uncontrolled mode exists- Migration decision: noneConsumer migration instructions belong in consumer docs and release notes.@@ -47,8 +72,13 @@ Consumer migration instructions belong in consumer docs and release notes.**Owns**-- The checkbox-group composition and its existing `checkbox-list` target.-- Collection state shared with CheckboxListItem.+- The labeled checkbox group, its `checkbox-list` target, and the group's+ description, status, and disabled-reason relationships.+- Collection state shared with CheckboxListItem: checked membership, change+ ordering, optimistic pending values, and group-level availability.+- CheckboxListItem's option composition: one CheckboxInput per row, row-surface+ click delegation, naming and description relationships, and the checked-row+ fill.**Does not own / non-goals**@@ -57,64 +87,123 @@ Consumer migration instructions belong in consumer docs and release notes.- Standard option-label and option-description wrappers — rendered as separate,untargeted spans by Item rather than Text; rich label content and end contentremain caller-owned.-- The checkbox indicator — owned by `component:CheckboxInput`.+- The checkbox control, its indicator, focus ring, and pressed overlay — owned+ by `component:CheckboxInput` and `component:CheckboxIndicator`.- Group-label and validation-message presentation — owned by `component:Field`and `component:FieldStatus`.-- Loading-indicator presentation — owned by `component:Spinner`.-- New targets for untargeted descriptions or caller-provided item content.+- Loading-indicator presentation — owned by `component:Spinner`; tooltip+ behavior — owned by `useTooltip`.+- New targets or reflected states for the row, descriptions, or caller content.## Public concepts-No new public concept is introduced. Consumer props, collection and standalone-item modes, and usage remain documented in `CheckboxList.doc.mjs` and-`CheckboxListItem.doc.mjs`.+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| -------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ------------------------- | ---------------------- | -------------------------------------- | --------------------------------------------- |+| group naming | `label`, `isLabelHidden`, `description` | Names and describes the `role="group"`; a hidden label still names it. | All states. | label required; visible | caller and Field | stable | rejected by the public type |+| selection mode | collection (`value` set), standalone in group, standalone in List | Collection derives checked state from membership; standalone items read `isChecked`. | Standalone item props are ignored in collection mode. | standalone | component | stable | a collection item without `value` throws |+| change path | `onChange`, `changeAction` (collection); `onCheck` (standalone); none | Reports the next value array or boolean; `changeAction` runs after `onChange` in a transition. | Enabled, non-read-only, non-busy items. | none | caller and component | shipped; handlerless meaning unsettled | no handler means no component-owned mutation |+| checked state | unchecked, checked, mixed (standalone only) | Native checkbox state; mixed uses the native `indeterminate` property. | All states. | unchecked | caller | stable | rejected by the public type |+| availability | enabled, group disabled, group disabled with reason, item disabled | Blocks toggling; a reason keeps checkboxes focusable through `aria-disabled` and shows a group tooltip. | Reason applies only with group `isDisabled`. | enabled | component | stable | a reason without `isDisabled` renders nothing |+| read-only | group `isReadOnly` | Keeps values visible, focusable, and full-opacity while blocking toggling. | Group-wide; not available on a standalone List item. | false | component | stable | boolean only |+| busy | item `isLoading`; pending collection `changeAction` | Shows Spinner in the checkbox, marks the row and checkbox busy, and blocks re-toggling that item. | Per item; other items remain interactive. | idle | component | stable | boolean/transition state only |+| status | `warning`, `error`, `success`, optional message | A message renders a detached FieldStatus after the list and describes the group. | All states. | none | caller and FieldStatus | shipped; invalid semantics unsettled | a status without a message renders nothing |+| row layout | `density` compact/balanced/spacious; `hasDividers`; `width` | Row padding and checkbox size (`sm` for compact); dividers between rows; field width for label, list, and status. | All states. | balanced; none; intrinsic | component and List | stable | rejected by the public types |+| option content | string or node `label`, `aria-label`, `description`, `endContent` | Names and describes the checkbox; end content stays caller-owned. | All states. | label required | caller | stable | typed values only |+| pass-through | CheckboxList rest, `ref`, styling; CheckboxListItem rest, `ref`, styling, `onClick` | CheckboxList inputs reach the field root; item inputs reach the row; item `onClick` rides the checkbox. | All states. | none | component | shipped; ARIA target unsettled | component-owned attributes win |## Behavioral and layout contract-| ID | Candidate invariant | Basis | Draft review state |-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------- | -------------------------------------------------- |-| FR1 | The current render places CheckboxListItem children inside a List and a group named by the group label. | Current source, docs, and focused tests | Verified current behavior; no new behavior decided |-| FR2 | The CheckboxList root carries the current `checkbox-list` target. | Current source and public docs | Verified current behavior; no target change |-| FR3 | The option-row root and checkbox indicator continue to be rendered by List and CheckboxInput rather than reimplemented. | Current source | Verified composition boundary |-| FR5 | Item renders option label and description as separate untargeted children; end content remains caller-provided inside its own untargeted slot wrapper. | Current source and focused tests | Verified child ownership; no target change |-| FR4 | A pending item renders Spinner inside that item's checkbox; a status message renders through detached FieldStatus. | Current source, docs, and focused tests | Verified conditional composition |+Draft requirements identify their basis so observed code is not mistaken for an+intentional decision. A `current` contract contains no unresolved rows.++| ID | Candidate invariant | Basis | Draft review state |+| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |+| FR1 | The render MUST place CheckboxListItem children inside a List within a `role="group"` named by the group label through `aria-labelledby`; its `aria-describedby` MUST list the description, status message, and disabled-reason tooltip that are present, in that order. | shipped source; focused tests; WCAG 1.3.1 and 4.1.2 | verify |+| FR2 | The CheckboxList root MUST carry the current `checkbox-list` target. | shipped source and public docs | settled |+| FR3 | The option-row root and checkbox MUST continue to be rendered by List and CheckboxInput rather than reimplemented. | shipped source | settled |+| FR4 | A busy item MUST render Spinner inside that item's checkbox and mark both the row and the checkbox busy; a status message MUST render through a detached FieldStatus after the list. | shipped source, focused tests, and Chromium receipts | verify |+| FR5 | Item MUST render the option label and description as separate untargeted children; end content MUST remain caller-provided inside its own untargeted slot wrapper. | shipped source and focused tests | settled |+| FR6 | In collection mode, items MUST derive checked state from `value` membership; toggling MUST call `onChange` with the next array (appending or filtering the item's `value`) and then run `changeAction` with the same array in a transition with an optimistic value. | shipped source and focused tests | verify |+| FR7 | While an item's `changeAction` is pending, that item MUST show Spinner, expose busy state, and refuse re-toggling; toggling another item MUST NOT clear it. Concurrent pending items settle together, after which every busy state clears. | shipped public `changeAction` promise; focused regression test; Chromium receipts | verify (remediated by this audit) |+| FR8 | Without a `value` array, or inside a plain List, items MUST read `isChecked` and call `onCheck` with the next boolean; a mixed item proposes `true`. | shipped source and focused tests | verify |+| FR9 | Group `isDisabled` MUST natively disable every checkbox unless `disabledMessage` is set; with a reason, checkboxes MUST stay focusable through `aria-disabled`, show the reason tooltip on group hover and focus, and refuse toggling. Item `isDisabled` MUST natively disable that item. | shipped source, focused tests, and shared checkbox binding | verify |+| FR10 | Group `isReadOnly` MUST expose read-only state on every checkbox, keep it focusable and full-opacity, and refuse every toggle, whether it comes from the checkbox, the keyboard, or the row. Row-surface clicks still delegate to the checkbox when the item has an `onClick`, which fires once per click; without one, the row does not delegate. | shipped source; focused read-only test; shared checkbox binding; `spec:AST-011` read-only vocabulary | verify (row-click loop remediated by this audit) |+| FR11 | Each option MUST expose exactly one tab stop, its checkbox. A click on the row surface outside interactive descendants MUST toggle through that checkbox, and an item `onClick` MUST fire once for each direct, keyboard, or delegated click. | shipped source and focused tests; WCAG 2.1.1 and 4.1.2 | verify |+| FR12 | A string `label` MUST name the checkbox; a node `label` MUST name it from its visible text through `aria-labelledby`; `aria-label` MUST replace the derived name; a renderable `description` MUST describe the checkbox. | shipped source and focused tests | verify |+| FR13 | `compact` density MUST render the `sm` checkbox and other densities `md`; `hasDividers` MUST separate rows without a divider after the last row; `width` MUST size the label, list, and status together. | shipped source, docs, and Chromium receipts | verify |+| GAP1 | A standalone item with `isChecked` and no `onCheck` is inert but exposed as an editable checkbox. | exact `spec:AST-021` known failure `list-item-handlerless-read-only`; WCAG 4.1.2 | owner decision |+| GAP2 | CheckboxListItem paints the checked-row fill itself, but no selection state is reflected on the row's `list-item`/`item` targets, so a theme cannot restyle checked rows apart from unchecked rows. | `architecture:component-theming-surface/INV6`; shipped source | owner decision |+| GAP3 | An error `status` exposes no programmatic invalid state on the group or its checkboxes, and a status without a message renders nothing. | shipped source; `spec:AST-002/FR15` | owner decision |+| GAP4 | Consumer ARIA pass-throughs on CheckboxList reach the field root rather than the named `role="group"`. | shipped source; `architecture:public-component-api/INV5` | owner decision |+| GAP5 | On an enabled, editable checked row, the checked-row fill replaces the row's hover and pressed overlays, so pointer hover and hold give no row feedback on checked options. | exact-head Chromium `hover-checked` and `pressed-checked` receipts; `design:user-states` leaves hover and selection treatments outside its current claim | authority gap (unscored); owner decision |+| GAP6 | Keyboard focus on an option paints two rings for one focus move: Item's row focus-within outline and CheckboxInput's indicator ring. | exact-head Chromium `focus-visible` receipts; `architecture:interaction-modality/INV3` | owner decision |### Allowed variation-- Option labels, descriptions, and end content may vary with caller-provided- CheckboxListItem content without becoming new CheckboxList targets.-- Density, dividers, checked state, and disabled state remain capabilities of- their current owning components rather than separate anatomy parts.+- **AV1 — Option content.** Option labels, descriptions, and end content may+ vary with caller-provided CheckboxListItem content without becoming new+ CheckboxList targets.+- **AV2 — Composed ownership.** Density, dividers, disabled dimming, hover and+ pressed row overlays, and the checkbox indicator remain capabilities of their+ current owning components rather than separate anatomy parts.+- **AV3 — Theme paint.** Semantic tokens and composed targets may change+ admitted visual properties without changing semantics, tab order, or state+ precedence.### Representative states-| State | Required invariant | Allowed variation |-| ------------------------- | --------------------------------------------------------------- | ---------------------------------- |-| Default collection | Named group, options list, rows, and checkbox indicators render | Option content and selected values |-| Item pending | Only the pending checkbox includes a Spinner | Which option is pending |-| Group status with message | Detached FieldStatus follows the group | Error, warning, or success status |+| State | Required invariant | Allowed variation |+| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- |+| Default collection | Named group, options list, rows, and checkboxes render; one tab stop per option | Option content and selected values |+| Item pending | Each pending checkbox includes Spinner and busy state and refuses re-toggling | Which options are pending |+| Group disabled with reason | Checkboxes stay focusable and inoperable; the reason is reachable by hover, focus, and AT | Reason text |+| Group read-only | Values stay visible, focusable, full-opacity, and immutable with read-only semantics; an item `onClick` fires once per click | Which values are checked |+| Group status with message | Detached FieldStatus follows the group and describes it | Error, warning, or success status |+| Handlerless standalone | Inert; read-only, unavailable, or invalid-usage meaning is unsettled | No policy is introduced by this draft |### Transformation and precedence order-- No new state, event, layout, or styling precedence rule is introduced.+- **ORD1 — Checked state.** Collection `value` → optimistic pending value →+ item membership; standalone items use `isChecked` only outside collection+ mode.+- **ORD2 — Toggle.** disabled, read-only, or busy guard → next value →+ `onChange` → `changeAction` in a transition that adds the item to the pending+ set.+- **ORD3 — Availability.** Item disabled or group disabled wins; a group reason+ changes focusability, not operability; read-only applies to mutation only.### Performance and resources-- No new performance or resource rule is introduced.+- **PR1 — Bounded resources.** The component owns no observer or global+ listener. Tooltip listeners are scoped to the group element and its lifetime.++Current measurements belong in the audit record; this subsection owns only+durable constraints and their verification target.## Accessibility contract-This draft does not change or extend CheckboxList's existing group naming,-checkbox semantics, focus order, busy state, or description/status association.+- **AR1 — Group identity.** The group name and its description, status, and+ disabled-reason relationships MUST remain programmatically determinable.+- **AR2 — Option semantics.** Each option MUST remain a native checkbox with a+ determinable name, checked or mixed state, disabled, read-only, and busy+ state.+- **AR3 — Keyboard parity.** Tab MUST reach each option's checkbox exactly once+ and Space MUST follow the same availability and change rules as pointer+ activation.+- **AR4 — Disabled reasons.** A group reason MUST stay discoverable by keyboard+ focus and assistive technology while toggling stays blocked.+- **AR5 — Busy perception.** A pending option MUST expose busy state in the+ accessibility tree and visibly through Spinner.## Design relationships-| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |-| ------------------ | ---------------------------------------------------------------------------- | ------------------------------- | -------------- | ------------------ |-| Group | Contains the current checkbox-group composition. | Current source and public docs | Supporting | FR1, FR2 |-| Options and rows | Present the List-owned list and row root plus Item-rendered child structure. | Current source | Supporting | FR1, FR3 |-| Checkbox | Presents each option's current selection indicator. | Current CheckboxInput source | Prominent | FR3 |-| Spinner and status | Present the current conditional feedback components. | Current shared-component source | Supporting | FR4 |+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ------------------ | ---------------------------------------------------------------------------- | ---------------------------------------------------------- | -------------- | ------------------ |+| Group | Contains the current checkbox-group composition. | Current source and public docs | Supporting | FR1, FR2 |+| Options and rows | Present the List-owned list and row root plus Item-rendered child structure. | Current source | Supporting | FR1, FR3, FR13 |+| Checkbox | Presents each option's current selection indicator. | CheckboxInput owner and `design:user-states` for its press | Prominent | FR3, FR9–FR11 |+| Checked-row fill | Supplements the checkbox state on enabled, editable checked rows. | unsettled (GAP2) | Supporting | GAP2 |+| Spinner and status | Present the current conditional feedback components. | Current shared-component source | Supporting | FR4, FR7 |### Theming anatomy@@ -175,41 +264,71 @@ reaches it. Item, not Text, renders option labels and descriptions in separateuntargeted spans, so neither delegates to Text nor inherits the row-root`list-item` target; future exposure remains unsettled. Rich label content and endcontent are caller-provided, and end content intentionally stays outside-CheckboxList's public theming ownership.+CheckboxList's public theming ownership. The `Option row` delegation reaches the+row surface, but not a checked-row state (GAP2).## Family and system relationships+- `architecture:public-component-api` owns export reachability, pass-through+ preservation, styling composition, refs, and released-change rules.- `architecture:component-theming-surface` owns anatomy qualification, factual- `none` dispositions, and composition-preserving target ownership.-- List, CheckboxInput, Field, FieldStatus, and Spinner retain their existing- public target contracts when composed by CheckboxList.+ `none` dispositions, composition-preserving target ownership, and state+ reflection.+- `architecture:interaction-modality` owns focus visibility and the boundary+ between the focused checkbox and the element that paints its ring.+- `spec:AST-021` owns the reusable checkbox accessibility binding for+ CheckboxListItem and its exact known-failure lifecycle.+- `spec:AST-011` records `isReadOnly` as the name for visible, focusable,+ non-editable values.+- `spec:AST-038/FR7` stops CheckboxList context at a layer boundary; an item+ inside a layer needs its own provider.+- List, CheckboxInput, Field, FieldStatus, Spinner, and Tooltip retain their+ existing public target and behavior contracts when composed by CheckboxList.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |-| FR1, FR3, FR5 | `CheckboxList.test.tsx` structure, content, and interaction suites plus `Item.tsx` source inspection | Collection mode; string/rich label; description; end content | Removing the group, row, checkbox, or separate content children breaks existing DOM and interaction assertions. | `audit:CheckboxList/anatomy` |-| FR4 | `CheckboxList.test.tsx` loading and status suites | Pending item and detached status | Removing composed feedback breaks existing spinner, busy-state, or message assertions. | `audit:CheckboxList/anatomy` |-| Local target source | `themingTargets.test.ts` | `checkbox-list` | Source/docs target drift fails the repository target guard. | `audit:CheckboxList/theming` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local target | Canonical-key drift, invalid dispositions or target spelling, or an unclaimed current local target fails repository validation. | `audit:CheckboxList/theming` |--The focused CheckboxList suite does not pin the exact delegated target classes-or the local `checkbox-list` class in rendered DOM. The source/metadata target-guard independently verifies that each owner's emitted targets remain-documented. No current repository check resolves `delegatesTo` owner/target-pairs; the pairs in this draft were verified manually, so semantic delegation-drift remains a validation gap.+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| -------------------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- |+| FR1, AR1 | `CheckboxList.test.tsx` group naming, description, status, and disabled-reason assertions | Named group; description plus status; disabled reason | Dropping the label, description, status, or tooltip id from the group fails the accessible name or description assertions. | `audit:CheckboxList/a11y` |+| FR3, FR5, FR11, FR12 | `CheckboxList.test.tsx` structure, naming, delegation, and tab-order suites | Collection mode; string/rich label; description; end content; row-surface click | A second tab stop, lost delegation, or a wrong name or description breaks existing interaction and ARIA assertions. | `audit:CheckboxList/behavior` |+| FR4, FR7, AR5 | `CheckboxList.test.tsx` loading and pending suites; Chromium `pending-*` receipts | Item loading; one pending item; two pending items; settled | Clearing an earlier pending item, allowing its re-toggle, or leaving busy state after settlement fails the tests and receipts. | `audit:CheckboxList/behavior` |+| FR6, FR8 | `CheckboxList.test.tsx` collection and standalone suites | add, remove, mixed, select-all | A wrong array, wrong boolean, or missing `value` error fails callback assertions. | `audit:CheckboxList/behavior` |+| FR9, FR10, AR2–AR4 | Shared checkbox jsdom and Chromium bindings; `CheckboxList.test.tsx` disabled and read-only suites | Group disabled; disabled with reason; item disabled; read-only with and without an item `onClick`; handlerless known failure | A focusability, state, reason, or single-fire expectation fails, a read-only toggle succeeds, or the recorded known failure becomes stale. | `audit:CheckboxList/a11y` |+| FR13 | Chromium density, divider, long-content, and RTL receipts | compact, balanced, spacious; dividers; 320px long content; RTL | A size, divider, width, overflow, or direction sensor fails. | `audit:CheckboxList/responsive` |+| Local target source | `themingTargets.test.ts` | `checkbox-list` | Source/docs target drift fails the repository target guard. | `audit:CheckboxList/theming` |+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local target | Canonical-key drift, invalid dispositions or target spelling, or an unclaimed current local target fails repository validation. | `audit:CheckboxList/theming` |++No current repository check resolves `delegatesTo` owner/target pairs; the pairs+in this draft were verified manually, so semantic delegation drift remains a+validation gap.## Decision log-None. This draft records current facts and introduces no component-local design-or API decision.+None. This draft records shipped behavior and two objective remediations; it+introduces no new API, default, target, or subjective visual decision.## Open questions-None.+- **OQ1 — What does a standalone item with `isChecked` and no `onCheck`+ mean?** (`human-api`) It is inert while exposed as editable. Direction must+ choose read-only, unavailable, or invalid usage, consistent with the matching+ CheckboxInput decision.+- **OQ2 — How should a theme reach the checked-row fill?** (`human-api`) The+ fill is component-owned paint on a delegated List row with no reflected state;+ exposing it needs a target or state decision.+- **OQ3 — Should an error status expose invalid state, and what should a status+ without a message render?** (`human-api`)+- **OQ4 — Which element owns consumer ARIA pass-throughs on CheckboxList?**+ (`human-api`) They currently reach the field root rather than the group.+- **OQ5 — What hover and pressed feedback should a checked row show?**+ (`human-design`) The checked-row fill currently replaces both overlays.+- **OQ6 — Which element paints the focus ring for an option?** (`human-design`)+ The row ring and the indicator ring both paint today;+ `architecture:interaction-modality/INV3` requires one owning indicator, and+ RadioList composes the same two painters.## Content boundary-This file does not duplicate consumer prop tables, examples, implementation-steps, or shared-component contracts. It links to their owners.+This file does not duplicate consumer prop tables/examples, current audit+results, implementation steps, or shared-component contracts. It links to their+owners.diff --git a/packages/core/src/CheckboxList/CheckboxList.test.tsx b/packages/core/src/CheckboxList/CheckboxList.test.tsxindex 98bb90c7b8..ce017528d0 100644--- a/packages/core/src/CheckboxList/CheckboxList.test.tsx+++ b/packages/core/src/CheckboxList/CheckboxList.test.tsx@@ -10,6 +10,7 @@*/import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {createRef} from 'react';import {render,screen,@@ -450,6 +451,58 @@ describe('CheckboxList', () => {expect(screen.getByText('Choose your preferences')).toBeInTheDocument();});+ it('describes the group with its description and status message', () => {+ render(+ <CheckboxList+ label="Preferences"+ description="Choose your preferences"+ status={{type: 'error', message: 'Select at least one'}}+ value={[]}+ onChange={() => {}}>+ <CheckboxListItem label="Option A" value="a" />+ </CheckboxList>,+ );+ expect(+ screen.getByRole('group', {name: 'Preferences'}),+ ).toHaveAccessibleDescription(+ 'Choose your preferences Select at least one',+ );+ });++ it('forwards ref, className, and style to the field root and the item row', () => {+ const listRef = createRef<HTMLDivElement>();+ const itemRef = createRef<HTMLLIElement>();+ render(+ <CheckboxList+ ref={listRef}+ label="Preferences"+ className="consumer-list"+ style={{marginTop: 12}}+ value={[]}+ onChange={() => {}}>+ <CheckboxListItem+ ref={itemRef}+ label="Option A"+ value="a"+ className="consumer-item"+ style={{marginTop: 4}}+ />+ </CheckboxList>,+ );+ expect(listRef.current).toContainElement(+ screen.getByRole('group', {name: 'Preferences'}),+ );+ expect(listRef.current).toHaveClass(+ 'consumer-list',+ 'astryx-checkbox-list',+ );+ expect(listRef.current).toHaveStyle({marginTop: '12px'});+ const row = screen.getByRole('listitem');+ expect(itemRef.current).toBe(row);+ expect(row).toHaveClass('consumer-item', 'astryx-list-item');+ expect(row).toHaveStyle({marginTop: '4px'});+ });+it('supports data-testid on CheckboxList', () => {render(<CheckboxList@@ -834,6 +887,80 @@ describe('CheckboxListItem ARIA props', () => {expect(changeAction).toHaveBeenCalledWith(['a']);});+ it('keeps a read-only item onClick while refusing every toggle', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ const onItemClick = vi.fn();+ render(+ <CheckboxList label="Prefs" value={[]} onChange={onChange} isReadOnly>+ <CheckboxListItem label="Option A" value="a" onClick={onItemClick} />+ <CheckboxListItem label="Option B" value="b" />+ </CheckboxList>,+ );+ const [itemA, itemB] = screen.getAllByRole('listitem');+ const checkboxA = within(itemA).getByRole('checkbox');+ const checkboxB = within(itemB).getByRole('checkbox');++ // With an onClick, a row-surface click still delegates to the checkbox.+ // The text also exists in the checkbox's visually hidden <label>; target+ // the row's label <span> to click the row surface.+ fireEvent.click(within(itemA).getByText('Option A', {selector: 'span'}));+ expect(onItemClick).toHaveBeenCalledTimes(1);+ fireEvent.click(checkboxA);+ expect(onItemClick).toHaveBeenCalledTimes(2);+ checkboxA.focus();+ await user.keyboard(' ');+ expect(onItemClick).toHaveBeenCalledTimes(3);+ expect(checkboxA).toHaveAttribute('aria-readonly', 'true');+ expect(checkboxA).not.toBeChecked();++ // Without one, the read-only row does not delegate at all.+ const delegated = vi.fn();+ checkboxB.addEventListener('click', delegated);+ fireEvent.click(within(itemB).getByText('Option B', {selector: 'span'}));+ expect(delegated).not.toHaveBeenCalled();+ fireEvent.click(checkboxB);+ expect(checkboxB).not.toBeChecked();+ expect(onChange).not.toHaveBeenCalled();+ });++ it('keeps an earlier toggled item busy and locked while its changeAction is still pending', async () => {+ // Never-resolving actions keep both toggles pending for the assertions.+ const changeAction = vi.fn(async () => {+ await new Promise<void>(() => {});+ });+ const onChange = vi.fn();+ render(+ <CheckboxList+ label="Prefs"+ value={[]}+ onChange={onChange}+ changeAction={changeAction}>+ <CheckboxListItem label="Option A" value="a" />+ <CheckboxListItem label="Option B" value="b" />+ </CheckboxList>,+ );++ const [itemA, itemB] = screen.getAllByRole('listitem');+ fireEvent.click(within(itemA).getByRole('checkbox'));+ await waitFor(() => expect(itemA).toHaveAttribute('aria-busy', 'true'));++ // Other items stay interactive, and toggling one must not clear the+ // pending state of the item that is still saving.+ fireEvent.click(within(itemB).getByRole('checkbox'));+ await waitFor(() => expect(itemB).toHaveAttribute('aria-busy', 'true'));+ expect(itemA).toHaveAttribute('aria-busy', 'true');+ expect(+ within(itemA).getByRole('status', {hidden: true}),+ ).toBeInTheDocument();++ // Re-toggling the still-pending item stays blocked.+ fireEvent.click(within(itemA).getByRole('checkbox'));+ expect(onChange).toHaveBeenCalledTimes(2);+ expect(changeAction).toHaveBeenCalledTimes(2);+ expect(changeAction).toHaveBeenLastCalledWith(['a', 'b']);+ });+it('forwards arbitrary aria attributes to the list item, but aria-label names the checkbox', () => {render(<List>diff --git a/packages/core/src/CheckboxList/CheckboxList.tsx b/packages/core/src/CheckboxList/CheckboxList.tsxindex 8c40dda8d5..f34ff119ca 100644--- a/packages/core/src/CheckboxList/CheckboxList.tsx+++ b/packages/core/src/CheckboxList/CheckboxList.tsx@@ -174,9 +174,15 @@ export function CheckboxList({const isCollectionMode = value !== undefined;const effectiveValue = value ?? EMPTY_ARRAY;const [optimisticValue, setOptimisticValue] = useOptimistic(effectiveValue);- // Tracks which item has a pending `changeAction`. Auto-reverts to null when- // the transition settles, so the spinner clears without manual cleanup.- const [loadingValue, setLoadingValue] = useOptimistic<string | null>(null);+ // Values whose `changeAction` is pending. React settles concurrent+ // transitions together, so each toggled value stays listed until they all+ // finish, then reverts to empty without manual cleanup.+ const [loadingValues, addLoadingValue] = useOptimistic<+ ReadonlyArray<string>,+ string+ >(EMPTY_ARRAY, (pending, toggled) =>+ pending.includes(toggled) ? pending : [...pending, toggled],+ );// Disabled-reason tooltip. Applies to the whole-group disabled state. Disabled// controls swallow pointer events, so the tooltip listeners attach to the@@ -198,7 +204,7 @@ export function CheckboxList({startTransition(async () => {setOptimisticValue(newValues);if (toggledValue !== undefined) {- setLoadingValue(toggledValue);+ addLoadingValue(toggledValue);}await changeAction(newValues);});@@ -209,7 +215,7 @@ export function CheckboxList({changeAction,startTransition,setOptimisticValue,- setLoadingValue,+ addLoadingValue,],);@@ -220,7 +226,7 @@ export function CheckboxList({isDisabled,hasDisabledMessage: showsDisabledMessage,isReadOnly,- loadingValue,+ loadingValues,}),[isCollectionMode,@@ -229,7 +235,7 @@ export function CheckboxList({isDisabled,showsDisabledMessage,isReadOnly,- loadingValue,+ loadingValues,],);diff --git a/packages/core/src/CheckboxList/CheckboxListContext.tsx b/packages/core/src/CheckboxList/CheckboxListContext.tsxindex b7dd5783b5..791ae16d43 100644--- a/packages/core/src/CheckboxList/CheckboxListContext.tsx+++ b/packages/core/src/CheckboxList/CheckboxListContext.tsx@@ -30,10 +30,11 @@ export interface CheckboxListContextValue {hasDisabledMessage?: boolean;isReadOnly: boolean;/**- * The value of the item with a pending `changeAction`, or null when idle.- * The matching item renders an in-checkbox spinner and blocks re-toggling.+ * Values of the items whose `changeAction` is pending. Each matching item+ * renders an in-checkbox spinner and blocks re-toggling; the list is empty+ * when idle.*/- loadingValue?: string | null;+ loadingValues?: ReadonlyArray<string>;}export const CheckboxListContext =diff --git a/packages/core/src/CheckboxList/CheckboxListItem.tsx b/packages/core/src/CheckboxList/CheckboxListItem.tsxindex 0e32fdbf49..bf762ba797 100644--- a/packages/core/src/CheckboxList/CheckboxListItem.tsx+++ b/packages/core/src/CheckboxList/CheckboxListItem.tsx@@ -220,13 +220,11 @@ export function CheckboxListItem({// Disabled: parent-level OR item-levelconst effectiveDisabled = (ctx?.isDisabled ?? false) || isItemDisabled;const effectiveReadOnly = ctx?.isReadOnly ?? false;- // Loading is per-item: explicit item prop OR (collection mode) the item+ // Loading is per-item: explicit item prop OR (collection mode) an item// whose `changeAction` is currently pending in the parent.const isBusy =isItemLoading ||- (ctx?.loadingValue != null && value !== undefined- ? ctx.loadingValue === value- : false);+ (value !== undefined && (ctx?.loadingValues?.includes(value) ?? false));// Resolve checked state:// 1. Collection mode (inside CheckboxList with value[])@@ -250,6 +248,18 @@ export function CheckboxListItem({const checkboxRef = useRef<HTMLInputElement | null>(null);const hasRowInteraction = isInteractive || onClickProp != null;+ // A read-only checkbox carries aria-readonly, which the row's clickable+ // container treats as a non-interactive target, so a click on it would be+ // delegated straight back to the checkbox without end. Stop that click at+ // the checkbox; the consumer onClick still fires once per click.+ const handleCheckboxClick: typeof onClickProp =+ effectiveReadOnly && onClickProp != null+ ? event => {+ onClickProp(event);+ event.stopPropagation();+ }+ : onClickProp;+const handleToggle = () => {if (effectiveDisabled || effectiveReadOnly || isBusy) {return;@@ -308,7 +318,7 @@ export function CheckboxListItem({isLabelHiddenvalue={resolvedChecked}onChange={() => handleToggle()}- onClick={onClickProp}+ onClick={handleCheckboxClick}isDisabled={effectiveDisabled}isReadOnly={effectiveReadOnly}isLoading={isBusy}diff --git a/packages/core/src/CheckboxList/__tests__/CheckboxList.a11y.chromium.spec.ts b/packages/core/src/CheckboxList/__tests__/CheckboxList.a11y.chromium.spec.tsnew file mode 100644index 0000000000..acb5562e23--- /dev/null+++ b/packages/core/src/CheckboxList/__tests__/CheckboxList.a11y.chromium.spec.ts@@ -0,0 +1,1996 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CheckboxList.a11y.chromium.spec.ts+ * @input Exact-head Storybook build and the CheckboxList stories+ * @output Light/dark PNGs, 10-sensor receipts, D7 contrast pairs, recorded+ * measurements, a contact sheet, and a fail-closed manifest+ * @position Real-browser evidence for the CheckboxList component audit. Sensors+ * prove that each frame is the intended render; measurements (focus+ * indicators, row paint, hit targets, wrapping, list structure) are recorded+ * for the audit and never gate. Only frames that prove a shipped remediation+ * gate on its outcome. The select-all CLI block renders through its own+ * story, and its source blob is bound in the manifest.+ */++import {createHash} from 'node:crypto';+import {execFileSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ expect,+ test,+ type Browser,+ type BrowserContext,+ type Page,+} from '@playwright/test';+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.+import {PNG} from 'pngjs';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const OUTPUT = path.resolve('test-results/checkbox-list-audit-evidence');+const PREFIX = 'core-checkboxlist--';+const BLOCK_DIR =+ 'packages/cli/assets/templates/blocks/components/CheckboxList';+const BLOCK_SOURCE = `${BLOCK_DIR}/CheckboxListSelectAllPattern.tsx`;++type Mode = 'light' | 'dark';+type Direction = 'ltr' | 'rtl';+type Interaction = 'rest' | 'hover' | 'pressed' | 'focus-visible';+type Checked = boolean | 'mixed';+type Disabled = 'native' | 'focusable' | false;++interface Rgba {+ r: number;+ g: number;+ b: number;+ a: number;+}++interface Box {+ x: number;+ y: number;+ width: number;+ height: number;+}++interface RowExpectation {+ checked: Checked;+ disabled?: Disabled;+ busy?: boolean;+ readOnly?: boolean;+}++interface CaseExpectation {+ /** Accessible name of the role="group"; null means a standalone List. */+ groupName: string | null;+ rows: RowExpectation[];+ status?: {type: 'error' | 'warning' | 'success'; text: string};+ tooltipText?: string;+ density?: 'compact' | 'balanced' | 'spacious';+ labelHidden?: boolean;+}++interface AuditCase {+ key: string;+ story: string;+ modes: ReadonlyArray<Mode>;+ direction?: Direction;+ narrowCoarse?: boolean;+ forcedColors?: boolean;+ /** Pointer clicks on rows (by index) before args and the interaction. */+ clickRows?: number[];+ /** Args applied through the Storybook channel after mount. */+ args?: Record<string, unknown>;+ /** Freeze timers so a pending changeAction stays pending for capture. */+ pauseClock?: boolean;+ /** Advance the frozen clock after the clicks (settled evidence). */+ settleMs?: number;+ interaction?: Interaction;+ interactionRow?: number;+ expect: CaseExpectation;+ /** A remediation this frame proves; its outcome is authored from the contract. */+ remediation?: string;+}++interface SensorResult {+ expected: unknown;+ observed: unknown;+ passed: boolean;+}++interface ContrastPair {+ part: string;+ /** The component or caller that owns the painted part. */+ owner: string;+ meaningful: boolean;+ foreground: string;+ backdrop: string;+ ratio: number | null;+ threshold: number | null;+ exception: string | null;+ passed: boolean;+}++interface ImageReceipt {+ file: string;+ sha256: string;+ width: number;+ height: number;+ distinctColors: number;+ nonBlank: boolean;+}++interface FrameReceipt {+ frame: string;+ case: string;+ story: string;+ mode: Mode;+ direction: Direction;+ remediation: string | null;+ passed: boolean;+ failures: string[];+ sensors: Record<string, SensorResult>;+ contrastPairs: ContrastPair[];+ measurements: Record<string, unknown>;+ ariaSnapshot: string;+ image: ImageReceipt;+}++const ROWS_DEFAULT: RowExpectation[] = [+ {checked: false},+ {checked: false},+ {checked: false},+];+const EMAIL_CHECKED: RowExpectation[] = [+ {checked: true},+ {checked: false},+ {checked: false},+];+const BOTH: ReadonlyArray<Mode> = ['light', 'dark'];+const GROUP = 'Notification preferences';++const CASES: AuditCase[] = [+ {+ key: 'rest',+ story: 'default',+ modes: BOTH,+ expect: {groupName: GROUP, rows: ROWS_DEFAULT},+ },+ {+ key: 'checked',+ story: 'default',+ modes: BOTH,+ clickRows: [0],+ expect: {groupName: GROUP, rows: EMAIL_CHECKED},+ },+ {+ key: 'hover-unchecked',+ story: 'default',+ modes: BOTH,+ interaction: 'hover',+ interactionRow: 1,+ expect: {groupName: GROUP, rows: ROWS_DEFAULT},+ },+ {+ key: 'hover-checked',+ story: 'default',+ modes: BOTH,+ clickRows: [0],+ interaction: 'hover',+ interactionRow: 0,+ expect: {groupName: GROUP, rows: EMAIL_CHECKED},+ },+ {+ key: 'pressed-unchecked',+ story: 'default',+ modes: BOTH,+ interaction: 'pressed',+ interactionRow: 1,+ expect: {groupName: GROUP, rows: ROWS_DEFAULT},+ },+ {+ key: 'pressed-checked',+ story: 'default',+ modes: BOTH,+ clickRows: [0],+ interaction: 'pressed',+ interactionRow: 0,+ expect: {groupName: GROUP, rows: EMAIL_CHECKED},+ },+ {+ key: 'focus-visible',+ story: 'default',+ modes: BOTH,+ interaction: 'focus-visible',+ interactionRow: 0,+ expect: {groupName: GROUP, rows: ROWS_DEFAULT},+ },+ {+ key: 'descriptions-dividers',+ story: 'with-descriptions',+ modes: BOTH,+ expect: {groupName: GROUP, rows: ROWS_DEFAULT},+ },+ {+ key: 'rich-content',+ story: 'rich-descriptions',+ modes: BOTH,+ expect: {+ groupName: 'Data sharing',+ rows: [{checked: true}, {checked: false}],+ },+ },+ {+ key: 'end-content',+ story: 'with-end-content',+ modes: BOTH,+ expect: {+ groupName: 'Add-on packages',+ rows: [{checked: true}, {checked: false}, {checked: false}],+ },+ },+ {+ key: 'indeterminate',+ story: 'select-all-with-indeterminate',+ modes: BOTH,+ expect: {+ groupName: 'Notifications',+ rows: [+ {checked: 'mixed'},+ {checked: true},+ {checked: false},+ {checked: false},+ ],+ },+ },+ {+ key: 'select-all-block',+ story: 'select-all-pattern-block',+ modes: BOTH,+ expect: {+ groupName: 'Include in export',+ rows: [+ {checked: 'mixed'},+ {checked: true},+ {checked: false},+ {checked: false},+ {checked: false},+ ],+ },+ },+ {+ key: 'disabled-group',+ story: 'disabled',+ modes: BOTH,+ expect: {+ groupName: GROUP,+ rows: [+ {checked: true, disabled: 'native'},+ {checked: false, disabled: 'native'},+ {checked: false, disabled: 'native'},+ ],+ },+ },+ {+ key: 'disabled-item',+ story: 'disabled-item',+ modes: BOTH,+ expect: {+ groupName: GROUP,+ rows: [+ {checked: false, disabled: false},+ {checked: false, disabled: 'native'},+ {checked: false, disabled: false},+ ],+ },+ },+ {+ key: 'disabled-message-focus',+ story: 'disabled-with-message',+ modes: BOTH,+ interaction: 'focus-visible',+ interactionRow: 0,+ expect: {+ groupName: GROUP,+ rows: [+ {checked: true, disabled: 'focusable'},+ {checked: false, disabled: 'focusable'},+ {checked: false, disabled: 'focusable'},+ ],+ tooltipText: 'Notifications are managed by your administrator',+ },+ },+ {+ key: 'loading-item',+ story: 'loading',+ modes: BOTH,+ expect: {+ groupName: GROUP,+ rows: [+ {checked: true, busy: false},+ {checked: false, busy: true},+ {checked: false, busy: false},+ ],+ },+ },+ {+ key: 'pending-single',+ story: 'change-action',+ modes: BOTH,+ pauseClock: true,+ clickRows: [1],+ expect: {+ groupName: GROUP,+ rows: [+ {checked: true, busy: false},+ {checked: true, busy: true},+ {checked: false, busy: false},+ ],+ },+ },+ {+ // The changeAction contract: while an item's action is pending it shows a+ // spinner, is marked aria-busy, and cannot be re-toggled; other items stay+ // interactive. Toggling a second item must not clear the first.+ key: 'pending-concurrent',+ story: 'change-action',+ modes: BOTH,+ pauseClock: true,+ clickRows: [1, 2],+ remediation: 'concurrent-changeAction-pending',+ expect: {+ groupName: GROUP,+ rows: [+ {checked: true, busy: false},+ {checked: true, busy: true},+ {checked: true, busy: true},+ ],+ },+ },+ {+ key: 'pending-settled',+ story: 'change-action',+ modes: BOTH,+ pauseClock: true,+ clickRows: [1, 2],+ settleMs: 1600,+ expect: {+ groupName: GROUP,+ rows: [+ {checked: true, busy: false},+ {checked: true, busy: false},+ {checked: true, busy: false},+ ],+ },+ },+ {+ key: 'status-error',+ story: 'with-error-status',+ modes: BOTH,+ expect: {+ groupName: GROUP,+ rows: ROWS_DEFAULT,+ status: {+ type: 'error',+ text: 'Please select at least one notification method',+ },+ },+ },+ {+ key: 'status-warning',+ story: 'default',+ modes: BOTH,+ args: {+ status: {type: 'warning', message: 'SMS delivery may be delayed'},+ },+ expect: {+ groupName: GROUP,+ rows: ROWS_DEFAULT,+ status: {type: 'warning', text: 'SMS delivery may be delayed'},+ },+ },+ {+ key: 'status-success',+ story: 'default',+ modes: BOTH,+ args: {status: {type: 'success', message: 'Preferences saved'}},+ expect: {+ groupName: GROUP,+ rows: ROWS_DEFAULT,+ status: {type: 'success', text: 'Preferences saved'},+ },+ },+ {+ key: 'read-only',+ story: 'default',+ modes: BOTH,+ clickRows: [0],+ args: {isReadOnly: true},+ expect: {+ groupName: GROUP,+ rows: [+ {checked: true, readOnly: true},+ {checked: false, readOnly: true},+ {checked: false, readOnly: true},+ ],+ },+ },+ {+ key: 'density-compact',+ story: 'default',+ modes: BOTH,+ args: {density: 'compact'},+ expect: {groupName: GROUP, rows: ROWS_DEFAULT, density: 'compact'},+ },+ {+ key: 'density-spacious',+ story: 'default',+ modes: BOTH,+ args: {density: 'spacious'},+ expect: {groupName: GROUP, rows: ROWS_DEFAULT, density: 'spacious'},+ },+ {+ key: 'label-hidden',+ story: 'default',+ modes: BOTH,+ args: {isLabelHidden: true},+ expect: {groupName: GROUP, rows: ROWS_DEFAULT, labelHidden: true},+ },+ {+ key: 'standalone',+ story: 'standalone-mode',+ modes: BOTH,+ expect: {+ groupName: null,+ rows: [{checked: false}, {checked: true}, {checked: false}],+ },+ },+ {+ // Records the exact AST-021 known failure; the handlerless meaning is an+ // owner decision, so no read-only expectation is authored here.+ key: 'handlerless',+ story: 'read-only',+ modes: BOTH,+ expect: {+ groupName: null,+ rows: [{checked: true}, {checked: false}, {checked: 'mixed'}],+ },+ },+ {+ key: 'inside-card',+ story: 'inside-card',+ modes: BOTH,+ expect: {+ groupName: 'Notifications',+ rows: [+ {checked: true},+ {checked: false},+ {checked: false, disabled: 'native'},+ ],+ },+ },+ {+ key: 'long-content-narrow',+ story: 'long-content',+ modes: BOTH,+ narrowCoarse: true,+ expect: {+ groupName:+ 'Notification channels for workspace activity and account security',+ rows: [{checked: true}, {checked: false}, {checked: false}],+ },+ },+ {+ key: 'rtl',+ story: 'with-descriptions',+ modes: BOTH,+ direction: 'rtl',+ expect: {groupName: GROUP, rows: ROWS_DEFAULT},+ },+ {+ key: 'forced-colors-checked',+ story: 'default',+ modes: ['light'],+ forcedColors: true,+ clickRows: [0],+ expect: {groupName: GROUP, rows: EMAIL_CHECKED},+ },+ {+ key: 'forced-colors-focus',+ story: 'default',+ modes: ['light'],+ forcedColors: true,+ interaction: 'focus-visible',+ interactionRow: 1,+ expect: {groupName: GROUP, rows: ROWS_DEFAULT},+ },+];++let server: StaticServer | undefined;+let head = '';+let storybookHead = '';+let blockBlob = '';+let browserVersion = 'unknown';+const receipts: FrameReceipt[] = [];++function frameName(auditCase: AuditCase, mode: Mode): string {+ const theme = auditCase.forcedColors ? `forced-${mode}` : `neutral-${mode}`;+ return `${auditCase.key}__${theme}__${auditCase.direction ?? 'ltr'}`;+}++function inspectPng(file: string, bytes: Buffer): ImageReceipt {+ const png = PNG.sync.read(bytes);+ const colors = new Set<string>();+ for (let index = 0; index < png.data.length; index += 4) {+ colors.add(+ `${png.data[index]},${png.data[index + 1]},${png.data[index + 2]},${png.data[index + 3]}`,+ );+ }+ return {+ file,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ width: png.width,+ height: png.height,+ distinctColors: colors.size,+ nonBlank: colors.size > 1,+ };+}++function composite(front: Rgba, back: Rgba): Rgba {+ const alpha = front.a + back.a * (1 - front.a);+ const channel = (f: number, b: number) =>+ alpha === 0 ? 0 : (f * front.a + b * back.a * (1 - front.a)) / alpha;+ return {+ r: channel(front.r, back.r),+ g: channel(front.g, back.g),+ b: channel(front.b, back.b),+ a: alpha,+ };+}++function luminance(color: Rgba): number {+ const linear = [color.r, color.g, color.b].map(channel => {+ const value = channel / 255;+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;+ });+ return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];+}++function contrast(front: Rgba | null, back: Rgba | null): number | null {+ if (front == null || back == null) {+ return null;+ }+ const resolved = front.a < 1 ? composite(front, back) : front;+ const first = luminance(resolved);+ const second = luminance(back);+ return Number(+ (+ (Math.max(first, second) + 0.05) /+ (Math.min(first, second) + 0.05)+ ).toFixed(2),+ );+}++function css(color: Rgba | null): string {+ if (color == null) {+ return 'unresolved';+ }+ const round = (value: number) => Math.round(value);+ return `rgba(${round(color.r)}, ${round(color.g)}, ${round(color.b)}, ${Number(color.a.toFixed(3))})`;+}++function pair(+ part: string,+ owner: string,+ front: Rgba | null,+ back: Rgba | null,+ threshold: number | null,+ exception: string | null = null,+): ContrastPair {+ const ratio = contrast(front, back);+ const meaningful = threshold != null && exception == null;+ return {+ part,+ owner,+ meaningful,+ foreground: css(front),+ backdrop: css(back),+ ratio,+ threshold: meaningful ? threshold : null,+ exception,+ passed: !meaningful || (ratio != null && ratio >= (threshold ?? 0)),+ };+}++function storyUrl(auditCase: AuditCase, mode: Mode): string {+ return (+ `${server?.origin}/iframe.html?id=${PREFIX}${auditCase.story}&viewMode=story` ++ `&globals=colorMode:${mode};astryxTheme:neutral;direction:${auditCase.direction ?? 'ltr'}`+ );+}++async function openCase(+ browser: Browser,+ auditCase: AuditCase,+ mode: Mode,+): Promise<{context: BrowserContext; page: Page; errors: string[]}> {+ const context = await browser.newContext(+ auditCase.narrowCoarse+ ? {+ viewport: {width: 320, height: 640},+ deviceScaleFactor: 1,+ hasTouch: true,+ isMobile: true,+ }+ : {viewport: {width: 1024, height: 768}, deviceScaleFactor: 1},+ );+ const page = await context.newPage();+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(String(error)));+ browserVersion = browser.version();+ if (auditCase.pauseClock) {+ await page.clock.install();+ }+ await page.goto(storyUrl(auditCase, mode));+ await page.locator('#storybook-root li').first().waitFor();+ await page.waitForFunction(+ expected =>+ document.documentElement.getAttribute('data-theme') === expected,+ mode,+ );+ await holdMotionStill(page);+ if (auditCase.forcedColors) {+ await page.emulateMedia({forcedColors: 'active', reducedMotion: 'reduce'});+ }+ await page.evaluate(async () => {+ await document.fonts.ready;+ if (document.activeElement instanceof HTMLElement) {+ document.activeElement.blur();+ }+ });+ await page.mouse.move(0, 0);+ if (auditCase.pauseClock) {+ await page.clock.pauseAt(Date.now() + 60_000);+ }+ return {context, page, errors};+}++function rowCheckbox(page: Page, index: number) {+ return page+ .locator('#storybook-root li')+ .nth(index)+ .locator('input[type="checkbox"]');+}++async function rowLabelCenter(+ page: Page,+ index: number,+): Promise<{x: number; y: number}> {+ const label = page+ .locator('#storybook-root li')+ .nth(index)+ .locator(':scope > span:nth-of-type(2) > span')+ .first();+ const box = await label.boundingBox();+ if (box == null) {+ throw new Error(`row ${index} label has no layout box`);+ }+ return {x: box.x + Math.min(box.width / 2, 40), y: box.y + box.height / 2};+}++async function settleFrames(page: Page): Promise<void> {+ // Real-time wait: page timers may be frozen, so no rAF here.+ await page.waitForTimeout(150);+}++async function applyArgs(page: Page, auditCase: AuditCase): Promise<void> {+ if (auditCase.args == null) {+ return;+ }+ await page.evaluate(+ ({storyId, updatedArgs}) => {+ const channel = (+ window as unknown as {+ __STORYBOOK_ADDONS_CHANNEL__?: {+ emit: (event: string, payload: unknown) => void;+ };+ }+ ).__STORYBOOK_ADDONS_CHANNEL__;+ if (channel == null) {+ throw new Error('Storybook channel is unavailable');+ }+ channel.emit('updateStoryArgs', {storyId, updatedArgs});+ },+ {storyId: `${PREFIX}${auditCase.story}`, updatedArgs: auditCase.args},+ );+ await settleFrames(page);+}++async function drive(page: Page, auditCase: AuditCase): Promise<void> {+ for (const index of auditCase.clickRows ?? []) {+ // A frozen page clock also freezes rAF-based actionability polling, so+ // pending-action cases click without waiting on it.+ await rowCheckbox(page, index).click({+ force: auditCase.pauseClock === true,+ });+ await settleFrames(page);+ }+ if (auditCase.settleMs != null) {+ await page.clock.runFor(auditCase.settleMs);+ await settleFrames(page);+ }+ await applyArgs(page, auditCase);+ if (auditCase.clickRows != null && auditCase.clickRows.length > 0) {+ // Pointer clicks leave focus on the checkbox without :focus-visible and+ // the pointer over the row; park the pointer so rest frames are clean.+ await page.mouse.move(0, 0);+ }+ const row = auditCase.interactionRow ?? 0;+ switch (auditCase.interaction ?? 'rest') {+ case 'hover': {+ const point = await rowLabelCenter(page, row);+ await page.mouse.move(point.x, point.y);+ break;+ }+ case 'pressed': {+ const point = await rowLabelCenter(page, row);+ await page.mouse.move(point.x, point.y);+ await page.mouse.down();+ break;+ }+ case 'focus-visible': {+ await page.evaluate(() => {+ if (document.activeElement instanceof HTMLElement) {+ document.activeElement.blur();+ }+ });+ const target = rowCheckbox(page, row);+ for (let press = 0; press < 8; press += 1) {+ await page.keyboard.press('Tab');+ if (await target.evaluate(el => document.activeElement === el)) {+ break;+ }+ }+ if (auditCase.expect.tooltipText != null) {+ await page+ .locator('[role="tooltip"]')+ .filter({hasText: auditCase.expect.tooltipText})+ .waitFor({state: 'visible', timeout: 5000})+ .catch(() => undefined);+ }+ break;+ }+ case 'rest':+ break;+ }+ await settleFrames(page);+}++/**+ * Everything read from the page in one pass. Colors are resolved in the page+ * and composited down the ancestor chain so contrast uses the painted backdrop.+ */+async function readPage(page: Page, auditCase: AuditCase) {+ return page.evaluate(+ ({interactionRow, groupExpected}) => {+ type Color = {r: number; g: number; b: number; a: number};+ const canvas = document.createElement('canvas');+ canvas.width = 1;+ canvas.height = 1;+ const context = canvas.getContext('2d', {willReadFrequently: true});+ const parse = (value: string | null | undefined): Color | null => {+ if (value == null || value === '' || value === 'none') {+ return null;+ }+ const rgb = value.match(+ /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+%?))?\s*\)$/,+ );+ if (rgb) {+ const alpha =+ rgb[4] == null+ ? 1+ : rgb[4].endsWith('%')+ ? Number.parseFloat(rgb[4]) / 100+ : Number(rgb[4]);+ return {+ r: Number(rgb[1]),+ g: Number(rgb[2]),+ b: Number(rgb[3]),+ a: alpha,+ };+ }+ const srgb = value.match(+ /^color\(srgb\s+([\d.e-]+)\s+([\d.e-]+)\s+([\d.e-]+)(?:\s*\/\s*([\d.e-]+))?\)$/,+ );+ if (srgb) {+ return {+ r: Number(srgb[1]) * 255,+ g: Number(srgb[2]) * 255,+ b: Number(srgb[3]) * 255,+ a: srgb[4] == null ? 1 : Number(srgb[4]),+ };+ }+ if (context == null) {+ return null;+ }+ context.clearRect(0, 0, 1, 1);+ context.fillStyle = value;+ context.fillRect(0, 0, 1, 1);+ const data = context.getImageData(0, 0, 1, 1).data;+ return {r: data[0], g: data[1], b: data[2], a: data[3] / 255};+ };+ const over = (front: Color, back: Color): Color => {+ const alpha = front.a + back.a * (1 - front.a);+ const channel = (f: number, b: number) =>+ alpha === 0 ? 0 : (f * front.a + b * back.a * (1 - front.a)) / alpha;+ return {+ r: channel(front.r, back.r),+ g: channel(front.g, back.g),+ b: channel(front.b, back.b),+ a: alpha,+ };+ };+ const canvasColor = (): Color =>+ getComputedStyle(document.documentElement).colorScheme.includes('dark')+ ? {r: 18, g: 18, b: 18, a: 1}+ : {r: 255, g: 255, b: 255, a: 1};+ const gradientColors = (image: string): Color[] =>+ image === 'none'+ ? []+ : (image.match(/(rgba?\([^)]+\)|color\(srgb[^)]+\))/g) ?? [])+ .map(value => parse(value))+ .filter((value): value is Color => value != null)+ .slice(0, 1);+ const backdrop = (element: Element | null): Color => {+ const layers: Color[] = [];+ let base: Color | null = null;+ for (let node = element; node != null; node = node.parentElement) {+ const style = getComputedStyle(node);+ layers.push(...gradientColors(style.backgroundImage));+ const color = parse(style.backgroundColor);+ if (color != null && color.a >= 0.999) {+ base = color;+ break;+ }+ if (color != null && color.a > 0) {+ layers.push(color);+ }+ }+ let result = base ?? canvasColor();+ for (let index = layers.length - 1; index >= 0; index -= 1) {+ result = over(layers[index], result);+ }+ return result;+ };+ const box = (element: Element | null) => {+ if (element == null) {+ return null;+ }+ const rect = element.getBoundingClientRect();+ return {x: rect.x, y: rect.y, width: rect.width, height: rect.height};+ };+ const text = (element: Element | null) =>+ element == null+ ? null+ : ((element as HTMLElement).innerText ?? element.textContent ?? '')+ .replace(/\s+/g, ' ')+ .trim();+ const firstTextElement = (element: Element | null): Element | null => {+ if (element == null) {+ return null;+ }+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);+ for (+ let node = walker.nextNode();+ node != null;+ node = walker.nextNode()+ ) {+ if ((node.textContent ?? '').trim() !== '' && node.parentElement) {+ return node.parentElement;+ }+ }+ return null;+ };+ const byIds = (ids: string | null) =>+ (ids ?? '')+ .split(/\s+/)+ .filter(Boolean)+ .map(id => document.getElementById(id))+ .filter((node): node is HTMLElement => node != null);+ const simpleName = (input: HTMLInputElement): string => {+ const label = input.getAttribute('aria-label');+ if (label) {+ return label.trim();+ }+ const labelled = byIds(input.getAttribute('aria-labelledby'));+ if (labelled.length > 0) {+ return labelled+ .map(node => text(node))+ .join(' ')+ .trim();+ }+ const own = input.id+ ? document.querySelector(`label[for="${CSS.escape(input.id)}"]`)+ : null;+ return (own?.textContent ?? '').replace(/\s+/g, ' ').trim();+ };+ const effectiveOpacity = (element: Element) => {+ let opacity = 1;+ for (+ let node: Element | null = element;+ node != null;+ node = node.parentElement+ ) {+ opacity *= Number(getComputedStyle(node).opacity);+ }+ return opacity;+ };+ const outlineOf = (element: Element) => {+ const style = getComputedStyle(element);+ const width = Number.parseFloat(style.outlineWidth);+ return style.outlineStyle !== 'none' && width > 0+ ? {+ className: element.getAttribute('class') ?? '',+ tag: element.tagName,+ opacity: effectiveOpacity(element),+ color: parse(style.outlineColor),+ width,+ offset: Number.parseFloat(style.outlineOffset),+ backdrop: backdrop(element.parentElement),+ }+ : null;+ };++ const storyRoot = document.getElementById('storybook-root');+ const groupRoots = document.querySelectorAll('.astryx-checkbox-list');+ const root: Element | null = groupExpected+ ? (groupRoots[0] ?? null)+ : (storyRoot?.querySelector('ul, ol') ?? null);+ const group = root?.querySelector('[role="group"]') ?? null;+ const listElement = root?.matches('ul, ol')+ ? root+ : (root?.querySelector('ul, ol') ?? null);+ const listChildren = [...(listElement?.children ?? [])].map(child => ({+ tag: child.tagName.toLowerCase(),+ role: child.getAttribute('role'),+ }));+ const labelNode =+ byIds(group?.getAttribute('aria-labelledby') ?? null)[0] ?? null;+ const describedNodes = byIds(+ group?.getAttribute('aria-describedby') ?? null,+ );+ const statusNode = root?.querySelector('.astryx-field-status') ?? null;+ const tooltip =+ [...document.querySelectorAll('[role="tooltip"]')].find(node => {+ const rect = node.getBoundingClientRect();+ return (+ rect.width > 0 &&+ rect.height > 0 &&+ getComputedStyle(node).visibility !== 'hidden'+ );+ }) ?? null;+ const descriptionNode =+ describedNodes.find(+ node =>+ node !== statusNode && node.getAttribute('role') !== 'tooltip',+ ) ?? null;+ const rows = [...(root?.querySelectorAll('li') ?? [])].map(+ (row, index) => {+ const input = row.querySelector<HTMLInputElement>(+ 'input[type="checkbox"]',+ );+ const content = row.querySelector(':scope > span:nth-of-type(2)');+ const label =+ content?.querySelector(':scope > span:nth-of-type(1)') ?? null;+ const description =+ content?.querySelector(':scope > span:nth-of-type(2)') ?? null;+ const endSlot = row.querySelector(':scope > span:nth-of-type(3)');+ const endText = firstTextElement(endSlot);+ const indicator = row.querySelector('.astryx-checkbox-indicator');+ const check = row.querySelector('.astryx-checkbox-indicator-check');+ const dash = row.querySelector('.astryx-checkbox-indicator-dash');+ const spinner = row.querySelector('.astryx-spinner');+ const rowStyle = getComputedStyle(row);+ const indicatorStyle =+ indicator == null ? null : getComputedStyle(indicator);+ const labelBox = box(label);+ const labelElement = label as HTMLElement | null;+ const descriptionElement = description as HTMLElement | null;+ const lineHeight =+ labelElement == null+ ? 0+ : Number.parseFloat(getComputedStyle(labelElement).lineHeight) ||+ 0;+ return {+ index,+ checked:+ input == null+ ? null+ : input.indeterminate+ ? 'mixed'+ : input.checked,+ disabled:+ input == null+ ? null+ : input.disabled+ ? 'native'+ : input.getAttribute('aria-disabled') === 'true'+ ? 'focusable'+ : false,+ busy: row.getAttribute('aria-busy') === 'true',+ inputBusy: input?.getAttribute('aria-busy') === 'true',+ spinner: spinner != null,+ readOnly: input?.getAttribute('aria-readonly') === 'true',+ name: input == null ? null : simpleName(input),+ descriptionText: text(+ byIds(input?.getAttribute('aria-describedby') ?? null)[0] ?? null,+ ),+ hovered: row.matches(':hover'),+ active: row.matches(':active'),+ focused: input != null && document.activeElement === input,+ focusVisible: input != null && input.matches(':focus-visible'),+ density: row.getAttribute('data-density'),+ rowCursor: rowStyle.cursor,+ inputCursor: input == null ? null : getComputedStyle(input).cursor,+ rowBackgroundColor: rowStyle.backgroundColor,+ rowBackgroundImage: rowStyle.backgroundImage,+ dividerWidth: Number.parseFloat(rowStyle.borderBlockEndWidth) || 0,+ rowBox: box(row),+ inputBox: box(input),+ indicatorBox: box(indicator),+ labelBox,+ labelTruncated:+ labelElement != null &&+ labelElement.scrollWidth > labelElement.clientWidth + 1,+ labelLines:+ labelBox == null || lineHeight === 0+ ? null+ : Math.round(labelBox.height / lineHeight),+ descriptionTruncated:+ descriptionElement == null+ ? null+ : descriptionElement.scrollWidth >+ descriptionElement.clientWidth + 1,+ paint: {+ rowBackdrop: backdrop(row),+ label: parse(+ label == null ? null : getComputedStyle(label).color,+ ),+ labelBackdrop: backdrop(label),+ description: parse(+ description == null+ ? null+ : getComputedStyle(description).color,+ ),+ descriptionBackdrop: backdrop(description),+ endText: parse(+ endText == null ? null : getComputedStyle(endText).color,+ ),+ endBackdrop: backdrop(endText),+ indicatorBorder: parse(indicatorStyle?.borderTopColor),+ indicatorBorderWidth:+ indicatorStyle == null+ ? 0+ : Number.parseFloat(indicatorStyle.borderTopWidth) || 0,+ indicatorFill: parse(indicatorStyle?.backgroundColor),+ indicatorBackdrop: backdrop(indicator?.parentElement ?? null),+ check: parse(+ check == null ? null : getComputedStyle(check).color,+ ),+ dash: parse(+ dash == null ? null : getComputedStyle(dash).backgroundColor,+ ),+ spinner: parse(+ spinner == null ? null : getComputedStyle(spinner).color,+ ),+ contentOpacity:+ content == null ? 1 : Number(getComputedStyle(content).opacity),+ },+ };+ },+ );+ const focusIndicators = [+ ...(root == null ? [] : [root, ...root.querySelectorAll('*')]),+ ]+ .map(node => outlineOf(node))+ .filter(value => value != null);+ const rootElement = root as HTMLElement | null;+ const rootStyle =+ rootElement == null ? null : getComputedStyle(rootElement);+ const surface = backdrop(root?.parentElement ?? storyRoot);+ const surfaceLuminance = (() => {+ const linear = [surface.r, surface.g, surface.b].map(channel => {+ const value = channel / 255;+ return value <= 0.04045+ ? value / 12.92+ : ((value + 0.055) / 1.055) ** 2.4;+ });+ return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];+ })();+ const errorScreen = [+ ...document.querySelectorAll(+ '.sb-errordisplay, [data-testid="story-error"]',+ ),+ ].some(node => {+ const rect = node.getBoundingClientRect();+ const style = getComputedStyle(node);+ return (+ rect.width > 0 &&+ rect.height > 0 &&+ style.display !== 'none' &&+ style.visibility !== 'hidden'+ );+ });+ return {+ storyId: new URL(location.href).searchParams.get('id'),+ groupRootCount: groupRoots.length,+ listChildren,+ listCount: storyRoot?.querySelectorAll('ul, ol').length ?? 0,+ rootFound: root != null,+ groupFound: group != null,+ groupLabelledBy: group?.getAttribute('aria-labelledby') ?? null,+ groupLabelText: text(labelNode),+ groupLabelVisible:+ labelNode != null && labelNode.getBoundingClientRect().width > 1,+ groupDescribedBy: group?.getAttribute('aria-describedby') ?? null,+ describedTexts: describedNodes.map(node => text(node)),+ descriptionText: text(descriptionNode),+ status:+ statusNode == null+ ? null+ : {+ type: statusNode.getAttribute('data-type'),+ text: text(statusNode),+ describesGroup: describedNodes.includes(+ statusNode as HTMLElement,+ ),+ iconCount: statusNode.querySelectorAll(+ '.astryx-field-status-icon',+ ).length,+ color: parse(getComputedStyle(statusNode).color),+ backdrop: backdrop(statusNode),+ iconColor: parse(+ statusNode.querySelector('.astryx-field-status-icon') == null+ ? null+ : getComputedStyle(+ statusNode.querySelector(+ '.astryx-field-status-icon',+ ) as Element,+ ).color,+ ),+ },+ tooltip:+ tooltip == null+ ? null+ : {+ text: text(tooltip),+ open: tooltip.matches(':popover-open'),+ describesGroup: describedNodes.includes(tooltip as HTMLElement),+ color: parse(getComputedStyle(tooltip).color),+ backdrop: backdrop(tooltip),+ box: box(tooltip),+ },+ groupLabelPaint:+ labelNode == null+ ? null+ : {+ color: parse(getComputedStyle(labelNode).color),+ backdrop: backdrop(labelNode),+ },+ descriptionPaint:+ descriptionNode == null+ ? null+ : {+ color: parse(getComputedStyle(descriptionNode).color),+ backdrop: backdrop(descriptionNode),+ },+ rows,+ focusIndicators,+ activeInsideRoot:+ root != null &&+ document.activeElement != null &&+ root.contains(document.activeElement),+ interactionRow,+ direction: rootStyle?.direction ?? null,+ rootBox: box(root),+ rootScrollFits:+ rootElement == null ||+ rootElement.scrollWidth <= rootElement.clientWidth + 1,+ documentScrollFits:+ document.documentElement.scrollWidth <= innerWidth + 1,+ viewport: {width: innerWidth, height: innerHeight},+ devicePixelRatio,+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,+ forcedColors: matchMedia('(forced-colors: active)').matches,+ coarsePointer: matchMedia('(pointer: coarse)').matches,+ hoverCapable: matchMedia('(hover: hover)').matches,+ mode: document.documentElement.getAttribute('data-theme'),+ colorScheme: getComputedStyle(document.documentElement).colorScheme,+ theme:+ document+ .querySelector('[data-astryx-theme]')+ ?.getAttribute('data-astryx-theme') ?? null,+ surface,+ surfaceLuminanceClass: surfaceLuminance > 0.5 ? 'light' : 'dark',+ fontsReady: document.fonts.status === 'loaded',+ errorScreen,+ };+ },+ {+ interactionRow: auditCase.interactionRow ?? null,+ groupExpected: auditCase.expect.groupName != null,+ },+ );+}++type PageRead = Awaited<ReturnType<typeof readPage>>;++const INACTIVE = 'WCAG 1.4.3/1.4.11 inactive user interface component';++/** Focus rings that actually paint; an outline on an opacity:0 input does not. */+function paintedFocusIndicators(actual: PageRead) {+ return actual.focusIndicators.filter(+ (indicator): indicator is NonNullable<typeof indicator> =>+ indicator != null && indicator.opacity > 0,+ );+}++function focusOwner(tag: string): string {+ return tag === 'LI'+ ? 'component:Item (row focus-within ring)'+ : tag === 'SPAN'+ ? 'component:CheckboxInput (indicator ring)'+ : `unexpected ${tag}`;+}++function contrastPairs(actual: PageRead, auditCase: AuditCase): ContrastPair[] {+ const pairs: ContrastPair[] = [];+ if (auditCase.forcedColors) {+ return pairs;+ }+ // A group whose every option is disabled is an inactive component; its+ // label and description carry the same WCAG exception as the options.+ const groupInactive =+ actual.rows.length > 0 &&+ actual.rows.every(+ row => row.disabled === 'native' || row.disabled === 'focusable',+ )+ ? `${INACTIVE} (every option in the group is disabled)`+ : null;+ if (actual.groupLabelPaint != null && actual.groupLabelVisible) {+ pairs.push(+ pair(+ 'group label',+ 'component:Field',+ actual.groupLabelPaint.color,+ actual.groupLabelPaint.backdrop,+ 4.5,+ groupInactive,+ ),+ );+ }+ if (actual.descriptionPaint != null && actual.groupLabelVisible) {+ pairs.push(+ pair(+ 'group description',+ 'component:Field',+ actual.descriptionPaint.color,+ actual.descriptionPaint.backdrop,+ 4.5,+ groupInactive,+ ),+ );+ }+ for (const row of actual.rows) {+ const inactive =+ row.disabled === 'native' || row.disabled === 'focusable'+ ? INACTIVE+ : null;+ const prefix = `row ${row.index + 1}`;+ pairs.push(+ pair(+ `${prefix} label`,+ 'component:Item',+ row.paint.label,+ row.paint.labelBackdrop,+ 4.5,+ inactive,+ ),+ );+ if (row.paint.description != null && row.descriptionText) {+ pairs.push(+ pair(+ `${prefix} description`,+ 'component:Item',+ row.paint.description,+ row.paint.descriptionBackdrop,+ 4.5,+ inactive,+ ),+ );+ }+ if (row.paint.endText != null) {+ pairs.push(+ pair(+ `${prefix} end content`,+ 'caller (story fixture)',+ row.paint.endText,+ row.paint.endBackdrop,+ 4.5,+ inactive,+ ),+ );+ }+ if (row.checked === false && row.paint.indicatorBorderWidth > 0) {+ pairs.push(+ pair(+ `${prefix} checkbox boundary`,+ 'component:CheckboxIndicator',+ row.paint.indicatorBorder,+ row.paint.indicatorBackdrop,+ 3,+ inactive,+ ),+ );+ }+ if (row.checked !== false && row.paint.indicatorFill != null) {+ pairs.push(+ pair(+ `${prefix} checkbox fill`,+ 'component:CheckboxIndicator',+ row.paint.indicatorFill,+ row.paint.indicatorBackdrop,+ 3,+ inactive,+ ),+ );+ const fill =+ row.paint.indicatorFill.a < 1+ ? composite(row.paint.indicatorFill, row.paint.indicatorBackdrop)+ : row.paint.indicatorFill;+ const mark = row.checked === 'mixed' ? row.paint.dash : row.paint.check;+ if (!row.spinner) {+ pairs.push(+ pair(+ `${prefix} check mark`,+ 'component:CheckboxIndicator',+ mark,+ fill,+ 3,+ inactive,+ ),+ );+ }+ }+ if (row.spinner && row.paint.spinner != null) {+ const surface =+ row.paint.indicatorFill != null && row.paint.indicatorFill.a > 0+ ? composite(row.paint.indicatorFill, row.paint.indicatorBackdrop)+ : row.paint.indicatorBackdrop;+ pairs.push(+ pair(+ `${prefix} busy spinner`,+ 'component:Spinner',+ row.paint.spinner,+ surface,+ 3,+ inactive,+ ),+ );+ }+ if (row.checked === true) {+ pairs.push(+ pair(+ `${prefix} checked-row fill`,+ 'component:CheckboxList',+ row.paint.rowBackdrop,+ actual.surface,+ null,+ 'Redundant: the checkbox state carries selection; the row fill is supplementary.',+ ),+ );+ }+ }+ if (actual.status != null) {+ pairs.push(+ pair(+ 'status message',+ 'component:FieldStatus',+ actual.status.color,+ actual.status.backdrop,+ 4.5,+ ),+ );+ if (actual.status.iconColor != null) {+ pairs.push(+ pair(+ 'status icon',+ 'component:FieldStatus',+ actual.status.iconColor,+ actual.status.backdrop,+ null,+ 'Redundant: the adjacent message text names the status.',+ ),+ );+ }+ }+ if (actual.tooltip != null) {+ pairs.push(+ pair(+ 'disabled-reason tooltip text',+ 'Tooltip',+ actual.tooltip.color,+ actual.tooltip.backdrop,+ 4.5,+ ),+ );+ }+ paintedFocusIndicators(actual).forEach((indicator, index) => {+ pairs.push(+ pair(+ `focus indicator ${index + 1} (${indicator.tag})`,+ focusOwner(indicator.tag),+ indicator.color,+ indicator.backdrop,+ 3,+ ),+ );+ });+ return pairs;+}++async function screenshot(page: Page, actual: PageRead, file: string) {+ const boxes = [actual.rootBox, actual.tooltip?.box ?? null].filter(+ (value): value is Box => value != null,+ );+ const pad = 12;+ const left = Math.max(0, Math.min(...boxes.map(b => b.x)) - pad);+ const top = Math.max(0, Math.min(...boxes.map(b => b.y)) - pad);+ const right = Math.min(+ actual.viewport.width,+ Math.max(...boxes.map(b => b.x + b.width)) + pad,+ );+ const bottom = Math.min(+ actual.viewport.height,+ Math.max(...boxes.map(b => b.y + b.height)) + pad,+ );+ const bytes = await page.screenshot({+ animations: 'disabled',+ clip: {x: left, y: top, width: right - left, height: bottom - top},+ });+ fs.writeFileSync(path.join(OUTPUT, file), bytes);+ return inspectPng(file, bytes);+}++function sameRows(+ observed: PageRead['rows'],+ expected: RowExpectation[],+): string[] {+ const failures: string[] = [];+ if (observed.length !== expected.length) {+ failures.push(+ `expected ${expected.length} options, observed ${observed.length}`,+ );+ return failures;+ }+ expected.forEach((row, index) => {+ const actual = observed[index];+ if (actual.checked !== row.checked) {+ failures.push(+ `row ${index + 1}: expected checked=${row.checked}, observed ${actual.checked}`,+ );+ }+ if (row.disabled !== undefined && actual.disabled !== row.disabled) {+ failures.push(+ `row ${index + 1}: expected disabled=${row.disabled}, observed ${actual.disabled}`,+ );+ }+ if (row.busy !== undefined) {+ const busy = actual.busy && actual.spinner;+ const idle = !actual.busy && !actual.spinner;+ if (row.busy ? !busy : !idle) {+ failures.push(+ `row ${index + 1}: expected busy=${row.busy}, observed aria-busy=${actual.busy} spinner=${actual.spinner}`,+ );+ }+ }+ if (row.readOnly !== undefined && actual.readOnly !== row.readOnly) {+ failures.push(+ `row ${index + 1}: expected aria-readonly=${row.readOnly}, observed ${actual.readOnly}`,+ );+ }+ });+ return failures;+}++async function capture(browser: Browser, auditCase: AuditCase, mode: Mode) {+ const frame = frameName(auditCase, mode);+ const {context, page, errors} = await openCase(browser, auditCase, mode);+ try {+ await drive(page, auditCase);+ const actual = await readPage(page, auditCase);+ const groupNameCount =+ auditCase.expect.groupName == null+ ? await page.locator('#storybook-root').getByRole('group').count()+ : await page+ .locator('#storybook-root')+ .getByRole('group', {name: auditCase.expect.groupName, exact: true})+ .count();+ const ariaSnapshot = await page.locator('#storybook-root').ariaSnapshot();+ const image = await screenshot(page, actual, `CheckboxList__${frame}.png`);+ if (auditCase.interaction === 'pressed') {+ await page.mouse.move(0, 0);+ await page.mouse.up();+ }++ const direction = auditCase.direction ?? 'ltr';+ const stateFailures = sameRows(actual.rows, auditCase.expect.rows);+ const expectGroup = auditCase.expect.groupName != null;+ if (expectGroup) {+ if (groupNameCount !== 1) {+ stateFailures.push(+ `expected one group named "${auditCase.expect.groupName}", observed ${groupNameCount}`,+ );+ }+ } else if (groupNameCount !== 0 || actual.groupRootCount !== 0) {+ stateFailures.push(+ 'standalone fixture unexpectedly renders a CheckboxList group',+ );+ }+ const status = auditCase.expect.status;+ if (status != null) {+ if (+ actual.status == null ||+ actual.status.type !== status.type ||+ actual.status.text !== status.text ||+ actual.status.iconCount !== 1+ ) {+ stateFailures.push(+ `expected ${status.type} status "${status.text}" with one icon`,+ );+ }+ } else if (actual.status != null) {+ stateFailures.push('unexpected status message');+ }+ if (auditCase.expect.tooltipText != null) {+ if (+ actual.tooltip == null ||+ actual.tooltip.text !== auditCase.expect.tooltipText ||+ !actual.tooltip.open+ ) {+ stateFailures.push('expected the open disabled-reason tooltip');+ }+ } else if (actual.tooltip != null) {+ stateFailures.push('unexpected visible tooltip');+ }+ if (auditCase.expect.density != null) {+ if (actual.rows.some(row => row.density !== auditCase.expect.density)) {+ stateFailures.push(`expected density ${auditCase.expect.density}`);+ }+ }+ if (auditCase.expect.labelHidden === true) {+ if (actual.groupLabelVisible) {+ stateFailures.push('expected the group label to be visually hidden');+ }+ } else if (expectGroup && !actual.groupLabelVisible) {+ stateFailures.push('expected a visible group label');+ }+ const interaction = auditCase.interaction ?? 'rest';+ const row = actual.rows[auditCase.interactionRow ?? 0];+ if (interaction === 'hover' && !(row?.hovered ?? false)) {+ stateFailures.push('target row is not hovered');+ }+ if (interaction === 'pressed' && !(row?.active ?? false)) {+ stateFailures.push('target row is not :active');+ }+ if (+ interaction === 'focus-visible' &&+ !(row?.focused && row.focusVisible)+ ) {+ stateFailures.push('target checkbox does not have keyboard focus');+ }+ if (+ interaction !== 'focus-visible' &&+ actual.rows.some(candidate => candidate.focusVisible)+ ) {+ stateFailures.push('unexpected :focus-visible checkbox');+ }+ if (+ interaction !== 'hover' &&+ interaction !== 'pressed' &&+ actual.rows.some(candidate => candidate.hovered)+ ) {+ stateFailures.push('unexpected hovered row');+ }++ const viewport = auditCase.narrowCoarse+ ? {width: 320, height: 640}+ : {width: 1024, height: 768};+ const sensors: Record<string, SensorResult> = {+ Build: {+ expected: head,+ observed: storybookHead,+ passed: head !== '' && head === storybookHead,+ },+ Story: {+ expected: `${PREFIX}${auditCase.story}`,+ observed: actual.storyId,+ passed: actual.storyId === `${PREFIX}${auditCase.story}`,+ },+ Theme: {+ expected: 'neutral',+ observed: actual.theme,+ passed: actual.theme === 'neutral',+ },+ 'Color mode': {+ expected: {+ mode,+ colorScheme: mode,+ surface: auditCase.forcedColors ? 'forced' : mode,+ },+ observed: {+ mode: actual.mode,+ colorScheme: actual.colorScheme,+ surface: actual.surfaceLuminanceClass,+ },+ passed:+ actual.mode === mode &&+ actual.colorScheme.includes(mode) &&+ (auditCase.forcedColors === true ||+ actual.surfaceLuminanceClass === mode),+ },+ Direction: {+ expected: direction,+ observed: actual.direction,+ passed: actual.direction === direction,+ },+ 'Viewport/media': {+ expected: {+ ...viewport,+ devicePixelRatio: 1,+ reducedMotion: true,+ forcedColors: auditCase.forcedColors === true,+ coarsePointer: auditCase.narrowCoarse === true,+ },+ observed: {+ ...actual.viewport,+ devicePixelRatio: actual.devicePixelRatio,+ reducedMotion: actual.reducedMotion,+ forcedColors: actual.forcedColors,+ coarsePointer: actual.coarsePointer,+ hoverCapable: actual.hoverCapable,+ },+ passed:+ actual.viewport.width === viewport.width &&+ actual.viewport.height === viewport.height &&+ actual.devicePixelRatio === 1 &&+ actual.reducedMotion &&+ actual.forcedColors === (auditCase.forcedColors === true) &&+ actual.coarsePointer === (auditCase.narrowCoarse === true),+ },+ 'Rendered state': {+ expected: {interaction, ...auditCase.expect},+ observed: {+ groupNameCount,+ groupLabel: actual.groupLabelText,+ status:+ actual.status == null+ ? null+ : {type: actual.status.type, text: actual.status.text},+ tooltip:+ actual.tooltip == null+ ? null+ : {text: actual.tooltip.text, open: actual.tooltip.open},+ rows: actual.rows.map(candidate => ({+ checked: candidate.checked,+ disabled: candidate.disabled,+ busy: candidate.busy,+ spinner: candidate.spinner,+ readOnly: candidate.readOnly,+ name: candidate.name,+ hovered: candidate.hovered,+ active: candidate.active,+ focusVisible: candidate.focusVisible,+ density: candidate.density,+ })),+ },+ passed: stateFailures.length === 0,+ },+ 'Subject geometry': {+ expected: {+ subjectCount: expectGroup ? 1 : 0,+ visible: true,+ insideViewport: true,+ overflowFree: true,+ },+ observed: {+ groupRootCount: actual.groupRootCount,+ rootBox: actual.rootBox,+ rootScrollFits: actual.rootScrollFits,+ documentScrollFits: actual.documentScrollFits,+ },+ passed:+ actual.rootFound &&+ actual.groupRootCount === (expectGroup ? 1 : 0) &&+ actual.rootBox != null &&+ actual.rootBox.width > 0 &&+ actual.rootBox.height > 0 &&+ actual.rootBox.x >= 0 &&+ actual.rootBox.x + actual.rootBox.width <=+ actual.viewport.width + 0.5 &&+ actual.rootScrollFits &&+ actual.documentScrollFits,+ },+ 'Settled render': {+ expected: {fontsReady: true, pageErrors: 0, storyError: false},+ observed: {+ fontsReady: actual.fontsReady,+ pageErrors: errors,+ storyError: actual.errorScreen,+ },+ passed: actual.fontsReady && errors.length === 0 && !actual.errorScreen,+ },+ Image: {+ expected: {nonBlank: true},+ observed: image,+ passed: image.nonBlank && image.width > 0 && image.height > 0,+ },+ };++ const pairs = contrastPairs(actual, auditCase);+ const failures = [+ ...Object.entries(sensors)+ .filter(([, sensor]) => !sensor.passed)+ .map(([name]) => `${name} sensor failed`),+ ...stateFailures,+ ];+ const receipt: FrameReceipt = {+ frame,+ case: auditCase.key,+ story: `${PREFIX}${auditCase.story}`,+ mode,+ direction,+ remediation: auditCase.remediation ?? null,+ passed: failures.length === 0,+ failures,+ sensors,+ contrastPairs: pairs,+ measurements: {+ // Painted rings only; an outline on the opacity:0 native input is+ // listed separately because it never reaches the screen.+ paintedFocusIndicators: paintedFocusIndicators(actual).map(+ indicator => ({+ tag: indicator.tag,+ owner: focusOwner(indicator.tag),+ color: css(indicator.color),+ width: indicator.width,+ offset: indicator.offset,+ }),+ ),+ unpaintedOutlines: actual.focusIndicators+ .filter(indicator => indicator != null && indicator.opacity === 0)+ .map(indicator => ({+ tag: indicator?.tag,+ opacity: indicator?.opacity,+ })),+ groupDescribedBy: actual.groupDescribedBy,+ describedTexts: actual.describedTexts,+ rows: actual.rows.map(candidate => ({+ index: candidate.index,+ name: candidate.name,+ descriptionText: candidate.descriptionText,+ inputBusy: candidate.inputBusy,+ rowCursor: candidate.rowCursor,+ inputCursor: candidate.inputCursor,+ rowBackgroundColor: candidate.rowBackgroundColor,+ rowBackgroundImage: candidate.rowBackgroundImage,+ rowBackdrop: css(candidate.paint.rowBackdrop),+ dividerWidth: candidate.dividerWidth,+ rowBox: candidate.rowBox,+ inputBox: candidate.inputBox,+ indicatorBox: candidate.indicatorBox,+ labelBox: candidate.labelBox,+ labelTruncated: candidate.labelTruncated,+ labelLines: candidate.labelLines,+ descriptionTruncated: candidate.descriptionTruncated,+ contentOpacity: candidate.paint.contentOpacity,+ })),+ surface: css(actual.surface),+ hoverCapable: actual.hoverCapable,+ listChildren: actual.listChildren,+ },+ ariaSnapshot,+ image,+ };+ fs.writeFileSync(+ path.join(OUTPUT, `${frame}.sensors.json`),+ `${JSON.stringify(receipt, null, 2)}\n`,+ );+ receipts.push(receipt);+ return receipt;+ } finally {+ await context.close();+ }+}++async function writeContactSheet(browser: Browser): Promise<ImageReceipt> {+ const context = await browser.newContext({+ viewport: {width: 1400, height: 900},+ deviceScaleFactor: 1,+ });+ const page = await context.newPage();+ const figures = receipts+ .map(receipt => {+ const bytes = fs.readFileSync(path.join(OUTPUT, receipt.image.file));+ const verdict = receipt.passed ? 'pass' : 'FAIL';+ return `<figure><img src="data:image/png;base64,${bytes.toString('base64')}" alt=""><figcaption>${receipt.frame} — ${verdict}</figcaption></figure>`;+ })+ .join('');+ await page.setContent(`<!doctype html>+ <style>+ html { color-scheme: light; background: #f3f4f6; }+ body { margin: 20px; font: 12px/1.35 system-ui, sans-serif; color: #111827; }+ h1 { margin: 0 0 16px; font-size: 20px; }+ main { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }+ figure { margin: 0; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px; background: white; }+ img { display: block; width: 100%; height: 180px; object-fit: contain; }+ figcaption { margin-top: 8px; overflow-wrap: anywhere; }+ </style>+ <h1>CheckboxList exact-head evidence (${head.slice(0, 12)})</h1>+ <main>${figures}</main>`);+ await page.locator('img').evaluateAll(async images => {+ await Promise.all(+ images.map(async image =>+ (image as HTMLImageElement).decode().catch(() => undefined),+ ),+ );+ });+ const file = 'CheckboxList__contact-sheet.png';+ const bytes = await page.screenshot({fullPage: true, animations: 'disabled'});+ fs.writeFileSync(path.join(OUTPUT, file), bytes);+ await context.close();+ return inspectPng(file, bytes);+}++test.describe.configure({mode: 'serial', retries: 0});++test.beforeAll(async () => {+ head = execFileSync('git', ['rev-parse', 'HEAD'], {encoding: 'utf8'}).trim();+ const dirty = execFileSync(+ 'git',+ [+ 'status',+ '--porcelain',+ '--untracked-files=all',+ '--',+ 'apps/storybook/stories/CheckboxList.stories.tsx',+ 'packages/core/src/CheckboxList',+ BLOCK_DIR,+ ],+ {encoding: 'utf8'},+ ).trim();+ if (dirty !== '') {+ throw new Error(+ `browser evidence requires committed source files: ${dirty}`,+ );+ }+ if (process.env.ASTRYX_HEAD_SHA && process.env.ASTRYX_HEAD_SHA !== head) {+ throw new Error('PR head differs from the checked out source');+ }+ blockBlob = execFileSync('git', ['hash-object', BLOCK_SOURCE], {+ encoding: 'utf8',+ }).trim();+ fs.mkdirSync(OUTPUT, {recursive: true});+ server = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+ const stamp = await fetch(`${server.origin}/astryx-build-sha.txt`);+ if (!stamp.ok) {+ throw new Error('Storybook build is missing its source stamp');+ }+ storybookHead = (await stamp.text()).trim();+ if (storybookHead !== head) {+ throw new Error('Storybook bytes differ from the PR head');+ }+});++test.afterAll(async () => {+ await server?.close();+});++test('captures the fail-closed CheckboxList state matrix', async ({+ browser,+}) => {+ test.setTimeout(15 * 60 * 1000);+ const failures: string[] = [];+ for (const auditCase of CASES) {+ for (const mode of auditCase.modes) {+ try {+ const receipt = await capture(browser, auditCase, mode);+ failures.push(+ ...receipt.failures.map(failure => `${receipt.frame}: ${failure}`),+ );+ } catch (error) {+ failures.push(+ `${frameName(auditCase, mode)}: capture error ${String(error)}`,+ );+ }+ }+ }+ const expectedFrames = CASES.flatMap(auditCase =>+ auditCase.modes.map(mode => frameName(auditCase, mode)),+ );+ const observed = new Set(receipts.map(receipt => receipt.frame));+ for (const frame of expectedFrames) {+ if (!observed.has(frame)) {+ failures.push(`missing frame: ${frame}`);+ }+ }+ const contactSheet = await writeContactSheet(browser);+ if (!contactSheet.nonBlank) {+ failures.push('contact sheet is blank');+ }+ const failedPairs = receipts.flatMap(receipt =>+ receipt.contrastPairs+ .filter(candidate => !candidate.passed)+ .map(+ candidate => `${receipt.frame}: ${candidate.part} ${candidate.ratio}:1`,+ ),+ );+ fs.writeFileSync(+ path.join(OUTPUT, 'manifest.json'),+ `${JSON.stringify(+ {+ version: 1,+ component: 'core/CheckboxList',+ headSha: head,+ storybookSha: storybookHead,+ browser: browserVersion,+ sources: {block: {path: BLOCK_SOURCE, gitBlob: blockBlob}},+ failClosed: true,+ matrixComplete: failures.length === 0,+ matrixFailures: failures,+ contrastFailures: failedPairs,+ sensorCount: 10,+ requiredSensors: [+ 'Build',+ 'Story',+ 'Theme',+ 'Color mode',+ 'Direction',+ 'Viewport/media',+ 'Rendered state',+ 'Subject geometry',+ 'Settled render',+ 'Image',+ ],+ remediationFrames: receipts+ .filter(receipt => receipt.remediation != null)+ .map(receipt => ({+ frame: receipt.frame,+ remediation: receipt.remediation,+ passed: receipt.passed,+ })),+ contactSheet,+ notMeasured: {+ assistiveTechnology:+ 'Browser semantics and the accessibility tree are recorded; spoken output was not tested with assistive technology.',+ subjectiveVisualAcceptance:+ 'Frames are objective evidence; subjective visual direction is not settled here.',+ },+ frames: receipts,+ },+ null,+ 2,+ )}\n`,+ );+ // Contrast failures are recorded for the audit and do not gate: token-layer+ // pairs belong to the theme, and the evidence must survive to be reviewed.+ expect(failures, 'complete exact-head evidence matrix').toEqual([]);+});