Skip to content

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

TypeScript

[Component Audit] DropdownMenuRadioItem: caller click and hover handlers now run on radio rows (#8191)

Cindy Zhanga8ef89f26ef9
diff --git a/.changeset/dropdown-menu-radio-item-caller-handlers.md b/.changeset/dropdown-menu-radio-item-caller-handlers.md
new file mode 100644
index 0000000000..131e47dfb6
--- /dev/null
+++ b/.changeset/dropdown-menu-radio-item-caller-handlers.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `DropdownMenuRadioItem` now runs a caller's `onClick` and `onPointerMove`. Before, the row's own selection and hover-focus handlers replaced them, so they never ran. They now run after the row selects its value and takes hover focus, as they already do on `DropdownMenuItem` and `DropdownMenuCheckboxItem`; a disabled row still selects nothing and does not call `onClick`. The documentation also marks `value` and `label` as required and no longer says disabled radio items stay reachable with the arrow keys, which DropdownMenu currently skips.
+
+@cixzhang
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7d19b9322e..681682dae9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -3124,6 +3124,38 @@ jobs:
retention-days: 30
if-no-files-found: error
+ # DropdownMenuRadioItem owns one menuitemradio row: its checked state,
+ # decorative radio marker, icon, description, end content, disabled
+ # paint, and composition of caller handlers with row activation. The
+ # group owns value propagation; DropdownMenu owns keyboard navigation.
+ - name: Run DropdownMenuRadioItem audit browser evidence
+ if: ${{ !cancelled() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] DropdownMenuRadioItem:') }}
+ env:
+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ status=0
+ node .github/scripts/accessibility-audit.js \
+ --storybook-dir apps/storybook/dist \
+ --output dropdown-menu-radio-item-a11y-report.json \
+ --components DropdownMenuRadioItem \
+ --baseline .github/a11y-baseline.json \
+ --fail-on-new || status=1
+ pnpm exec playwright test \
+ packages/core/src/DropdownMenu/__tests__/DropdownMenuRadioItemAudit.a11y.chromium.spec.ts \
+ --project chromium || status=1
+ exit "$status"
+
+ - name: Upload DropdownMenuRadioItem audit evidence
+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] DropdownMenuRadioItem:')
+ uses: actions/upload-artifact@v7
+ with:
+ name: dropdown-menu-radio-item-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: |
+ dropdown-menu-radio-item-a11y-report.json
+ dropdown-menu-radio-item-audit-evidence/
+ retention-days: 30
+ if-no-files-found: error
+
# ContextMenu owns pointer and touch presentations across cursor anchoring,
# selectable rows, sections, inline triggers, RTL, and narrow viewports.
# Its audit lane binds the rendered matrix to the exact pull-request head.
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 5206f413bf..0644d3f102 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -415,5 +415,14 @@
"packages/core/src/DropdownMenu/DropdownMenuRadioGroup.tsx": "sha256:3be897ab21dcc6a37fb7ab8a1b6d48254e406c544d95a3b939dfc6593ea99cf1",
"packages/core/src/DropdownMenu/index.ts": "sha256:59bf02be4a577cbecf3ad7e981e2577602375892f74548593aa9b998cae733fa"
}
+ },
+ {
+ "component": "core/DropdownMenuRadioItem",
+ "reason": "DropdownMenuRadioItem renders one menuitemradio row through Item: a decorative radio marker, an optional icon, the label and description, and end content in logical inline order. Its only inline placement is the coarse-pointer move of the marker to the row's inline end through flex order and marginInlineStart auto, which mirrors with direction. It draws no directional glyph or contextual separator and uses no physical property, horizontal scroll or drag, side-placed overlay, or horizontal keyboard behavior; DropdownMenu owns placement and navigation. Exact-head frames render RTL, including coarse-pointer RTL, and assert the marker's inline-start and inline-end placement without adding a component-owned RTL dimension.",
+ "evidence": {
+ "apps/storybook/stories/DropdownMenuRadioItem.stories.tsx": "sha256:cfe1bd90a8fc189f0f3a94992dee2a148b7256433775c511099b57690c01a614",
+ "packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx": "sha256:7d7ce618b802170660763de820c0551fc3c63530ba1c105cb4bf7146d30ad518",
+ "packages/core/src/DropdownMenu/index.ts": "sha256:59bf02be4a577cbecf3ad7e981e2577602375892f74548593aa9b998cae733fa"
+ }
}
]
diff --git a/apps/storybook/stories/DropdownMenuRadioItem.stories.tsx b/apps/storybook/stories/DropdownMenuRadioItem.stories.tsx
new file mode 100644
index 0000000000..c11b7a07cc
--- /dev/null
+++ b/apps/storybook/stories/DropdownMenuRadioItem.stories.tsx
@@ -0,0 +1,114 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuRadioItem.stories.tsx
+ * @input One open, controlled menu whose radio rows cover checked, unchecked, icon, description, end content, long text, disabled, and consumer handlers
+ * @output Component-owned rendered evidence for DropdownMenuRadioItem rows at each menu size
+ * @position Storybook audit surface; the group and parent menu keep their own stories
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {useState} from 'react';
+import {expect, within} from 'storybook/test';
+import {Badge} from '@astryxdesign/core/Badge';
+import {
+ DropdownMenu,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+} from '@astryxdesign/core/DropdownMenu';
+
+type RowStatesArgs = {size: 'sm' | 'md' | 'lg'};
+
+const meta: Meta<RowStatesArgs> = {
+ title: 'Core/DropdownMenuRadioItem',
+ tags: ['autodocs', 'visual-theme-matrix'],
+ parameters: {
+ layout: 'centered',
+ docs: {
+ description: {
+ component:
+ 'One menuitemradio row inside a DropdownMenuRadioGroup. The row owns its checked state, decorative radio marker, icon, description, end content, and disabled paint; the group owns the value and DropdownMenu owns keyboard navigation.',
+ },
+ },
+ },
+ argTypes: {
+ size: {control: 'inline-radio', options: ['sm', 'md', 'lg']},
+ },
+ args: {size: 'md'},
+};
+
+export default meta;
+type Story = StoryObj<RowStatesArgs>;
+
+function RowStatesFixture({size}: RowStatesArgs) {
+ const [view, setView] = useState('board');
+ const [clickCount, setClickCount] = useState(0);
+ const [pointerMoveCount, setPointerMoveCount] = useState(0);
+ // Consumer handlers on every row record what reaches them, so browser
+ // evidence can observe that row activation and hover focus compose with
+ // the caller's own handlers.
+ const consumerHandlers = {
+ onClick: () => setClickCount(count => count + 1),
+ onPointerMove: () => setPointerMoveCount(count => count + 1),
+ };
+ return (
+ <div
+ data-testid="dropdown-menu-radio-item-audit"
+ data-row-click-count={clickCount}
+ data-row-pointer-move-count={pointerMoveCount}>
+ <DropdownMenu
+ button={{label: 'View', size}}
+ isMenuOpen
+ menuWidth={300}
+ presentation="popover">
+ <DropdownMenuRadioGroup
+ value={view}
+ onChange={setView}
+ label="View as"
+ hasCloseOnSelect={false}>
+ <DropdownMenuRadioItem
+ {...consumerHandlers}
+ value="board"
+ label="Board"
+ icon="viewColumns"
+ />
+ <DropdownMenuRadioItem
+ {...consumerHandlers}
+ value="list"
+ label="List"
+ description="One row per card"
+ />
+ <DropdownMenuRadioItem
+ {...consumerHandlers}
+ value="timeline"
+ label="Timeline"
+ endContent={<Badge label="Beta" />}
+ />
+ <DropdownMenuRadioItem
+ {...consumerHandlers}
+ value="calendar"
+ label="Calendar with every scheduled milestone, review, and release date"
+ />
+ <DropdownMenuRadioItem
+ {...consumerHandlers}
+ value="archive"
+ label="Archive"
+ description="Requires an owner role"
+ isDisabled
+ />
+ </DropdownMenuRadioGroup>
+ </DropdownMenu>
+ </div>
+ );
+}
+
+export const RowStates: Story = {
+ render: args => <RowStatesFixture {...args} />,
+ play: async () => {
+ const menu = await within(document.body).findByRole('menu');
+ const rows = within(menu).getAllByRole('menuitemradio');
+ await expect(rows).toHaveLength(5);
+ await expect(rows[0]).toHaveAttribute('aria-checked', 'true');
+ await expect(rows[4]).toHaveAttribute('aria-disabled', 'true');
+ },
+};
diff --git a/packages/cli/test/core-prop-docs.known-drift.json b/packages/cli/test/core-prop-docs.known-drift.json
index e500884789..53352e9117 100644
--- a/packages/cli/test/core-prop-docs.known-drift.json
+++ b/packages/cli/test/core-prop-docs.known-drift.json
@@ -19,8 +19,6 @@
"src/DropdownMenu/DropdownMenu.doc.mjs DropdownMenu.items required_mismatch",
"src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs DropdownMenuCheckboxItem.label required_mismatch",
"src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs DropdownMenuCheckboxItem.value required_mismatch",
- "src/DropdownMenu/DropdownMenuRadioItem.doc.mjs DropdownMenuRadioItem.label required_mismatch",
- "src/DropdownMenu/DropdownMenuRadioItem.doc.mjs DropdownMenuRadioItem.value required_mismatch",
"src/DropdownMenu/DropdownMenuSubMenu.doc.mjs DropdownMenuSubMenu.children required_mismatch",
"src/DropdownMenu/DropdownMenuSubMenu.doc.mjs DropdownMenuSubMenu.label required_mismatch",
"src/DropdownMenu/DropdownMenuSubMenu.doc.mjs DropdownMenuSubMenu.menuDataTestId not_in_doc",
diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs
index 5173a0f48f..ef2eaa06b6 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs
@@ -26,12 +26,14 @@ export const docs = {
{
name: 'value',
type: 'string',
+ required: true,
description:
"The value this item represents within its group. The group's value matches against this to determine the checked state.",
},
{
name: 'label',
type: 'ReactNode',
+ required: true,
description: 'Primary label text identifying the option.',
},
{
@@ -50,7 +52,7 @@ export const docs = {
type: 'boolean',
default: 'false',
description:
- 'Whether this individual radio item is disabled. Disabled items stay focusable (via aria-disabled) so they remain discoverable by keyboard and assistive technology, but selection is blocked.',
+ 'Whether this individual radio item is disabled. Disabled items expose aria-disabled, block selection, and are currently skipped by DropdownMenu arrow-key navigation.',
},
{
name: 'endContent',
@@ -94,7 +96,8 @@ export const docsDense = {
label: 'primary label text',
description: 'secondary text below label',
icon: 'icon before label',
- isDisabled: 'disabled; stays focusable via aria-disabled',
+ isDisabled:
+ 'disabled; aria-disabled, blocks selection, skipped by arrow keys',
endContent: 'content after label+description',
ref: 'forwarded to the row root (the role="menuitemradio" element)',
},
diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.spec.md b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.spec.md
new file mode 100644
index 0000000000..1f8dbff77d
--- /dev/null
+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.spec.md
@@ -0,0 +1,226 @@
+---
+schema_version: 3
+template_version: 7
+kind: component
+id: component:DropdownMenuRadioItem
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang]
+review_triggers: [public-api, behavior, accessibility, theming, testing]
+verified_by:
+ [
+ packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx,
+ packages/core/src/DropdownMenu/__tests__/Menu.a11y.test.tsx,
+ packages/core/src/RadioList/__tests__/RadioGroup.a11y.test.tsx,
+ packages/core/src/DropdownMenu/__tests__/DropdownMenuRadioItemAudit.a11y.chromium.spec.ts,
+ apps/storybook/stories/DropdownMenuRadioItem.stories.tsx,
+ apps/storybook/rtl-audit/verified-not-applicable.json,
+ scripts/check-knowledge.mjs,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:public-component-api,
+ architecture:component-theming-surface,
+ architecture:component-test-sufficiency,
+ architecture:interaction-modality,
+ ]
+contributing: []
+system_specs: [spec:AST-020, spec:AST-029]
+---
+
+# DropdownMenuRadioItem component contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | One `menuitemradio` row inside a DropdownMenuRadioGroup with a required value and label, optional description, icon, end content, disabled state, root inputs, and an explicit React 19 ref. |
+| Behavior | Enabled activation emits the row value through the group, applies the group close policy, then runs the caller click handler; disabled activation does none of these. |
+| End-user impact | Assistive technology hears one radio option with its checked state; pointer and keyboard selection commit the same value, and a disabled option cannot be chosen. |
+| Builder impact | Place the row inside a DropdownMenuRadioGroup and give it a unique value and a label; caller handlers run alongside the row's own behavior. |
+| Compatibility/readiness | Released subcomponent; observational draft of current behavior. Authority stays `draft` until owner approval. |
+| Review checks | Reject a nested semantic radio, a second keyboard owner, local selection state, a dropped caller input, or disabled activation that selects, closes, or calls the caller click handler. |
+| Governing rules | WAI-ARIA menu pattern; `architecture:public-component-api/INV5–INV8`; `architecture:component-theming-surface/INV4–INV6`; `spec:AST-020/FR1,FR2`. |
+
+This table is a review projection; the body below is authoritative.
+
+## Intent
+
+DropdownMenuRadioItem renders one selectable option of a single-choice group in
+the pointer presentation of DropdownMenu. The row owns its `menuitemradio`
+semantics, checked state, decorative radio marker, visible content, disabled
+paint, and activation order. DropdownMenuRadioGroup owns the controlled value
+and close policy; DropdownMenu owns focus movement, typeahead, keyboard
+activation, and the menu lifecycle.
+
+## Compatibility and migration
+
+- Released default preserved: yes (`isDisabled=false`).
+- Compatibility class: no public API change; caller `onClick` and
+ `onPointerMove` compose with the row's own behavior.
+- Controlled behavior: the checked state always derives from the group `value`;
+ the row holds no selection state.
+- Migration decision: none.
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- One row root with `role="menuitemradio"` and `aria-checked` derived from the
+ group value.
+- Selection order: disabled guard, group `onChange(value)`, optional close, then
+ the caller click handler.
+- The decorative shared radio marker, its size, and its inline placement.
+- Label, description, icon, and end content composition through Item.
+- Disabled state exposure and paint, and hover focus for enabled rows.
+- Root composition of ref, supported host inputs, `className`, `style`, and
+ `xstyle`.
+
+**Does not own / non-goals**
+
+- The selected value, change callback, and close policy — owned by
+ `component:DropdownMenuRadioGroup`.
+- Focus entry, arrow-key navigation, typeahead, Enter/Space click synthesis,
+ press gestures, and closing — owned by `component:DropdownMenu`.
+- Touch bottom-sheet rendering of selectable rows — owned by the parent
+ presentation.
+- The radio marker's paint — owned by the shared radio Indicator.
+
+## Public concepts
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ------------ | ---------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------- | -------- | --------------------------------- | --------- | -------------------------------------------------------- |
+| Option value | any string | The value the group emits and compares to decide the checked row. | Every row | required | `component:DropdownMenuRadioItem` | stable | A value no group value matches leaves the row unchecked. |
+| Checked | checked; unchecked | Whether the group value equals this row's value. | Every row | derived | group context and row | stable | No local override exists. |
+| Availability | enabled; disabled | Whether the row can take hover focus and commit its value. | Every row | enabled | `component:DropdownMenuRadioItem` | stable | Disabled blocks every activation path. |
+| Content | label; description; icon; end content | Visible identification of the option, in reading order. | Every row | label | row through Item | stable | `label` is required by the public type. |
+| Root surface | ref; DOM/data/ARIA; class/style/xstyle; events | Extends the row root while preserving its role and checked state. | Every row | omitted | public component API | stable | `role`, `aria-checked`, and `tabIndex` are not accepted. |
+
+## Behavioral and layout contract
+
+Draft requirements identify their basis so observed code is not mistaken for an
+intentional decision.
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | ------------------ |
+| FR1 | The row MUST render one element with `role="menuitemradio"` whose `aria-checked` is true exactly when the group value equals the row value. It MUST NOT nest a native or ARIA radio. | WAI-ARIA menu pattern; current source and focused tests | verify |
+| FR2 | Rendering the row outside a DropdownMenuRadioGroup MUST throw. | Current source and focused tests | verify |
+| FR3 | Enabled activation, by pointer or by the parent's synthesized Enter/Space click, MUST call the group `onChange` with the row value, then ask DropdownMenu to close when the group's close policy is on, then call the caller `onClick`. | Released behavior; `architecture:public-component-api/INV7`; focused tests | verify |
+| FR4 | A disabled row MUST expose `aria-disabled="true"`, render no `tabindex`, take no hover focus, and on any activation, including an assistive-technology click, MUST NOT call `onChange`, close the menu, or call the caller `onClick`. It paints at half opacity with a default cursor. | Current source, focused tests, and browser evidence | verify |
+| FR5 | Ref, supported host attributes and handlers, `className`, `style`, and `xstyle` MUST reach or compose on the row root. Caller `onPointerMove` MUST run after the row's hover focus, and caller handlers MUST NOT replace the row's own behavior. | `architecture:public-component-api/INV5–INV8`; focused tests | verify |
+| FR6 | The marker MUST be the shared radio Indicator, hidden from assistive technology, never the pointer target, sized `sm` in a small menu and `md` otherwise, at the row's inline start on a fine pointer and its inline end on a coarse pointer. | Current source, focused tests, and browser evidence | verify |
+| FR7 | The row MUST carry the `dropdown-menu-item` target with the menu size and the marker MUST carry the `dropdown-menu-radio` target with size, checked, and disabled reflections. | `architecture:component-theming-surface/INV4–INV6`; current source/docs | verify |
+| FR8 | The row MUST add no key handler or tab stop of its own: enabled rows are `tabindex="-1"` for the parent's roving focus, and keyboard selection arrives as the parent's synthesized click. | `architecture:interaction-modality`; parent keyboard tests | verify |
+
+### Allowed variation
+
+- **AV1 — Content.** Label, description, icon, and end content may vary in
+ length and kind; long string labels truncate on one line.
+- **AV2 — Size.** The marker follows the parent menu size: `sm` in a small
+ menu, `md` otherwise. Row padding does not currently vary with the menu size,
+ unlike action rows; this is an observation, not an invariant.
+- **AV3 — Root styling.** Caller style inputs may extend the row while its role,
+ checked state, and marker remain intact.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| -------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------- |
+| Checked | `aria-checked=true`; the marker shows its checked dot. | Content, size, theme, and mode. |
+| Unchecked | `aria-checked=false`; the marker shows an empty circle. | Content, size, theme, and mode. |
+| Focused | The row holds focus. | Pointer hover or keyboard arrival; focus paint is the AR4 gap. |
+| Disabled | `aria-disabled=true`, no tab stop, half opacity, and no activation. | Checked or unchecked value. |
+| Coarse pointer | The marker sits at the inline end of the row. | Direction mirrors the placement. |
+| RTL / narrow | Content and marker follow logical order with no horizontal page overflow. | Parent menu placement and width. |
+
+### Transformation and precedence order
+
+- **ORD1 — Activation.** Disabled guard → group `onChange(value)` → close when
+ the group's close policy is on → caller `onClick`.
+- **ORD2 — Pointer move.** Hover focus for an enabled row → caller
+ `onPointerMove`.
+- **ORD3 — Root composition.** Base row styles → disabled paint → caller
+ `xstyle`; caller `className` and `style` merge with the row target.
+
+### Performance and resources
+
+- **PR1 — Render only.** The row owns no Effect, listener, observer, timer,
+ request, or local state.
+
+## Accessibility contract
+
+- **AR1 — One radio option.** The row is the only announced control; its
+ accessible name comes from its visible content and its state from
+ `aria-checked`.
+- **AR2 — Disabled state.** A disabled row exposes `aria-disabled` and cannot
+ commit a value through any input.
+- **AR3 — Keyboard ownership.** DropdownMenu owns focus movement and activation;
+ the row adds no key handling. Whether disabled rows stay keyboard-discoverable
+ is owned by `component:DropdownMenu` (its OQ1).
+- **AR4 — Focus visibility (objective gap).** Keyboard focus MUST be
+ perceivable (WCAG 2.2 SC 2.4.7 and 1.4.11). The row currently paints focus
+ only as the menu overlay tint with no outline, which measures about 1.1:1
+ against the menu surface and paints nothing under forced colors. The
+ remediation is a shared row-visual decision with `component:DropdownMenuItem`
+ (its OQ2); this draft records the gap and does not settle it.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | ---------------------------------------------------------------- | -------------------------------- | -------------- | ------------------ |
+| Row | Menu row paint and radius; focus paint is the AR4 objective gap. | Current source and menu tokens | structural | FR7, AR4 |
+| Radio marker | Shared radio Indicator at the menu's control size. | Shared radio Indicator | prominent | FR1, FR6 |
+| Disabled | Half-opacity row with a default cursor. | Current source | supporting | FR4 |
+| Direction/touch | Logical marker placement that mirrors and moves on touch. | Bidirectionality and current CSS | structural | FR6 |
+
+No new component-local visual decision is settled by this draft.
+
+## Family and system relationships
+
+- `component:DropdownMenuRadioGroup` owns value, change callback, and close policy.
+- `component:DropdownMenu` owns keyboard navigation, the press model, the
+ `dropdown-menu-item` and `dropdown-menu-radio` target inventory, disabled
+ keyboard discoverability (its OQ1), and forced-colors row focus together with
+ `component:DropdownMenuItem` (its OQ2).
+- `architecture:public-component-api` owns root input and handler composition.
+- `architecture:component-theming-surface` owns target placement and state
+ reflection.
+- `architecture:component-test-sufficiency` owns proportionate observable evidence.
+- `spec:AST-020` supplies WCAG/APG adoption and evidence-layer boundaries.
+- `spec:AST-029` keeps this observational draft separate from the audit receipt.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
+| FR1, FR2, AR1 | `DropdownMenuSelectable.test.tsx`; reusable radio-group and Menu contracts; scoped axe | checked, unchecked, outside a group | A nested radio, wrong checked row, extra announced control, or missing throw fails | `audit:DropdownMenuRadioItem/§1,§4,§6` |
+| FR3, FR5, FR8 | `DropdownMenuSelectable.test.tsx` handler, keyboard, close, and ref cases; browser fixture counters | pointer and keyboard activation, close on/off, caller handlers | A dropped caller handler, wrong order, or missing close fails | `audit:DropdownMenuRadioItem/§3,§4,§6` |
+| FR4, AR2 | Disabled focused test with an assistive-technology click; browser disabled-hover frame | disabled checked/unchecked | Removing the disabled guard makes the focused test fail | `audit:DropdownMenuRadioItem/§1,§4` |
+| AR4 | Exact-head keyboard-focus and forced-colors frames with rendered contrast | Neutral/Butter light/dark focus, forced colors | Current frames record the gap; a remediation passes only with a perceivable indicator in every theme and under forced colors | `audit:DropdownMenuRadioItem/§1,§5` |
+| FR6, FR7 | Marker and target tests; exact-head Neutral/Butter/RTL/narrow/size/coarse/focus frames | sm/md/lg, fine/coarse, LTR/RTL, light/dark | A lost target or reflection, a marker that is announced, wrongly sized, or misplaced fails | `audit:DropdownMenuRadioItem/§2,§5,§9,§10` |
+
+## Decision log
+
+None. This draft records current facts and introduces no product decision.
+
+## Open questions
+
+- **OQ1 — Should the shared `dropdown-menu-item` target reflect the disabled
+ state its rows paint?** (`human-api`) Selectable and action rows paint disabled
+ rows at half opacity, but the target reflects only size and variant, so a theme
+ cannot style disabled rows through it. The target inventory is owned by
+ `component:DropdownMenu`.
+
+## Content boundary
+
+This file does not duplicate consumer prop tables/examples, current audit scores,
+screenshot matrices, implementation steps, or group/parent contracts. The audit
+pull request owns the closed run evidence required by `spec:AST-029/FR5`.
diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
index cb8c7aaff7..57f2125886 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
@@ -12,7 +12,8 @@
* (role="menuitemradio"). The row owns the role and aria-checked; there is no
* nested native <input> (per the WAI-ARIA menuitemradio pattern). Selection
* state + onChange come from DropdownMenuRadioGroupContext. Keyboard nav +
- * Enter/Space activation come from the parent DropdownMenu.
+ * Enter/Space activation come from the parent DropdownMenu. Caller onClick and
+ * onPointerMove run after the row's own selection and hover focus.
*
* The round radio visual is the shared radio indicator, decorative
* (aria-hidden) — the row owns the checked state, and menu radios pick up the
@@ -21,7 +22,12 @@
* the inline-end of the row on coarse-pointer (touch) devices via CSS `order`.
*/
-import {useCallback, type PointerEvent, type ReactNode} from 'react';
+import {
+ useCallback,
+ type MouseEvent,
+ type PointerEvent,
+ type ReactNode,
+} from 'react';
import * as stylex from '@stylexjs/stylex';
import {renderIconSlot, type IconType} from '../Icon';
import {useIndicator} from '../Indicator';
@@ -29,7 +35,7 @@ import {Item} from '../Item';
import {useDropdownMenuContext} from './DropdownMenuContext';
import {focusMenuItemOnHover} from './menuItemHover';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
-import {mergeProps, themeProps} from '../utils';
+import {composeEventHandlers, mergeProps, themeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {useDropdownMenuRadioGroupContext} from './DropdownMenuContext';
@@ -97,9 +103,9 @@ export interface DropdownMenuRadioItemProps extends Omit<
*/
icon?: ReactNode | IconType;
/**
- * Whether this individual radio item is disabled. Disabled items stay
- * focusable (via `aria-disabled`) so they remain discoverable by keyboard
- * and assistive technology, but selection is blocked.
+ * Whether this individual radio item is disabled. Disabled items expose
+ * `aria-disabled`, block selection, and are currently skipped by
+ * DropdownMenu arrow-key navigation.
* @default false
*/
isDisabled?: boolean;
@@ -115,6 +121,10 @@ export interface DropdownMenuRadioItemProps extends Omit<
/**
* A single option in a DropdownMenuRadioGroup (role="menuitemradio").
*
+ * Consumer click and pointer-move handlers compose after the row's own
+ * selection and hover-focus behavior; disabled activation stops before the
+ * consumer click handler.
+ *
* @example
* ```
* <DropdownMenuRadioGroup value={sort} onChange={setSort} label="Sort by">
@@ -133,6 +143,8 @@ export function DropdownMenuRadioItem({
xstyle,
className,
style,
+ onClick,
+ onPointerMove,
...rest
}: DropdownMenuRadioItemProps) {
const menuCtx = useDropdownMenuContext();
@@ -147,15 +159,19 @@ export function DropdownMenuRadioItem({
const isChecked = groupCtx.value === value;
const RadioControl = useIndicator('radio');
- const handleClick = useCallback(() => {
- if (isDisabled) {
- return;
- }
- groupCtx.onChange(value);
- if (groupCtx.hasCloseOnSelect) {
- menuCtx?.closeMenu();
- }
- }, [isDisabled, groupCtx, value, menuCtx]);
+ const handleClick = useCallback(
+ (event: MouseEvent) => {
+ if (isDisabled) {
+ return;
+ }
+ groupCtx.onChange(value);
+ if (groupCtx.hasCloseOnSelect) {
+ menuCtx?.closeMenu();
+ }
+ onClick?.(event as MouseEvent<HTMLElement>);
+ },
+ [isDisabled, groupCtx, value, menuCtx, onClick],
+ );
const handlePointerMove = useCallback(
(e: PointerEvent<HTMLElement>) => focusMenuItemOnHover(e, isDisabled),
@@ -168,7 +184,7 @@ export function DropdownMenuRadioItem({
role="menuitemradio"
aria-checked={isChecked}
tabIndex={isDisabled ? undefined : -1}
- onPointerMove={handlePointerMove}
+ onPointerMove={composeEventHandlers(handlePointerMove, onPointerMove)}
marker={
// No wrapper — see DropdownMenuCheckboxItem: the target belongs on the
// visible circle, and the indicator already owns its control size.
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx
index 06577e89f3..75b10caf3c 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx
@@ -338,6 +338,132 @@ describe('DropdownMenuRadioGroup / RadioItem', () => {
expect(HTMLElement.prototype.hidePopover).toHaveBeenCalledTimes(1);
});
+ it('composes the caller click handler with the selection', async () => {
+ const user = userEvent.setup();
+ const calls: string[] = [];
+ const onChange = vi.fn(() => calls.push('change'));
+ const onClick = vi.fn(() => calls.push('click'));
+ render(
+ <DropdownMenu button={{label: 'Sort'}}>
+ <DropdownMenuRadioGroup
+ value="newest"
+ onChange={onChange}
+ label="Sort by"
+ hasCloseOnSelect={false}>
+ <DropdownMenuRadioItem value="newest" label="Newest" />
+ <DropdownMenuRadioItem
+ value="oldest"
+ label="Oldest"
+ onClick={onClick}
+ />
+ </DropdownMenuRadioGroup>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Sort/}));
+ await user.click(
+ screen.getByRole('menuitemradio', {name: 'Oldest', hidden: true}),
+ );
+ expect(onChange).toHaveBeenCalledWith('oldest');
+ expect(onClick).toHaveBeenCalledOnce();
+ expect(calls).toEqual(['change', 'click']);
+ });
+
+ it('composes the caller pointer-move handler with menu hover focus', async () => {
+ const user = userEvent.setup();
+ const onPointerMove = vi.fn(() => document.activeElement);
+ render(
+ <DropdownMenu button={{label: 'Sort'}}>
+ <DropdownMenuRadioGroup
+ value="newest"
+ onChange={() => {}}
+ label="Sort by">
+ <DropdownMenuRadioItem value="newest" label="Newest" />
+ <DropdownMenuRadioItem
+ value="oldest"
+ label="Oldest"
+ onPointerMove={onPointerMove}
+ />
+ </DropdownMenuRadioGroup>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Sort/}));
+ const item = screen.getByRole('menuitemradio', {
+ name: 'Oldest',
+ hidden: true,
+ });
+ fireEvent.pointerMove(item, {pointerType: 'mouse'});
+ expect(item).toHaveFocus();
+ expect(onPointerMove).toHaveBeenCalledOnce();
+ expect(onPointerMove).toHaveReturnedWith(item);
+ });
+
+ it('composes the caller click handler on keyboard activation', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const onClick = vi.fn();
+ render(
+ <DropdownMenu button={{label: 'Sort'}}>
+ <DropdownMenuRadioGroup
+ value="oldest"
+ onChange={onChange}
+ label="Sort by">
+ <DropdownMenuRadioItem
+ value="newest"
+ label="Newest"
+ onClick={onClick}
+ />
+ <DropdownMenuRadioItem value="oldest" label="Oldest" />
+ </DropdownMenuRadioGroup>
+ </DropdownMenu>,
+ );
+ screen.getByRole('button', {name: /Sort/}).focus();
+ await user.keyboard('{Enter}');
+ const item = screen.getByRole('menuitemradio', {
+ name: 'Newest',
+ hidden: true,
+ });
+ await waitFor(() => expect(item).toHaveFocus());
+ await user.keyboard('{Enter}');
+ expect(onChange).toHaveBeenCalledWith('newest');
+ expect(onClick).toHaveBeenCalledOnce();
+ });
+
+ it('does not select, close, or call the caller click handler when disabled', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const onClick = vi.fn();
+ render(
+ <DropdownMenu button={{label: 'Sort'}}>
+ <DropdownMenuRadioGroup
+ value="newest"
+ onChange={onChange}
+ label="Sort by">
+ <DropdownMenuRadioItem value="newest" label="Newest" />
+ <DropdownMenuRadioItem
+ value="oldest"
+ label="Oldest"
+ onClick={onClick}
+ isDisabled
+ />
+ </DropdownMenuRadioGroup>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Sort/}));
+ const item = screen.getByRole('menuitemradio', {
+ name: 'Oldest',
+ hidden: true,
+ });
+ expect(item).toHaveAttribute('aria-disabled', 'true');
+ await user.click(item);
+ // A screen reader's activation reaches the row as a detail-0 click that
+ // the menu's press model does not intercept.
+ fireEvent.click(item, {detail: 0});
+ expect(onChange).not.toHaveBeenCalled();
+ expect(onClick).not.toHaveBeenCalled();
+ expect(item).toHaveAttribute('aria-checked', 'false');
+ expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled();
+ });
+
it('keeps the menu open while controlled selection updates when requested', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
@@ -423,6 +549,38 @@ describe('DropdownMenuRadioGroup / RadioItem', () => {
expect(onClick).toHaveBeenCalledTimes(1);
});
+ it('composes caller root inputs without replacing the row semantics', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Sort'}}>
+ <DropdownMenuRadioGroup
+ value="newest"
+ onChange={() => {}}
+ label="Sort by">
+ <DropdownMenuRadioItem
+ value="newest"
+ label="Newest"
+ data-owner="consumer"
+ aria-describedby="sort-hint"
+ className="consumer-row"
+ style={{inlineSize: 240}}
+ />
+ </DropdownMenuRadioGroup>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Sort/}));
+ const item = screen.getByRole('menuitemradio', {
+ name: 'Newest',
+ hidden: true,
+ });
+ expect(item).toHaveAttribute('data-owner', 'consumer');
+ expect(item).toHaveAttribute('aria-describedby', 'sort-hint');
+ expect(item).toHaveAttribute('aria-checked', 'true');
+ expect(item).toHaveClass('consumer-row');
+ expect(item).toHaveClass('astryx-dropdown-menu-item');
+ expect(item).toHaveStyle({inlineSize: '240px'});
+ });
+
it('throws when a radio item is used outside a group', () => {
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() =>
diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuRadioItemAudit.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuRadioItemAudit.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..1d0eba82d8
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuRadioItemAudit.a11y.chromium.spec.ts
@@ -0,0 +1,539 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuRadioItemAudit.a11y.chromium.spec.ts
+ * @input Exact-head DropdownMenuRadioItem row-state story across states, themes, sizes, direction, pointer, forced colors, and viewport widths
+ * @output Screenshots and fail-closed sensor receipts for the DropdownMenuRadioItem component audit
+ * @position Component-owned Night Watch browser evidence; CI runs it only for a DropdownMenuRadioItem audit pull request
+ */
+
+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 Page} from '@playwright/test';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const OUTPUT = path.resolve('dropdown-menu-radio-item-audit-evidence');
+const STORY_ID = 'core-dropdownmenuradioitem--row-states';
+const WIDE = {width: 1024, height: 768};
+const NARROW = {width: 320, height: 720};
+
+type Interaction =
+ 'rest' | 'hover' | 'focus' | 'pressed' | 'select' | 'disabled-hover';
+type AuditCase = {
+ key: string;
+ mode: 'light' | 'dark';
+ direction: 'ltr' | 'rtl';
+ theme: 'neutral' | 'butter';
+ size: 'sm' | 'md' | 'lg';
+ pointer: 'fine' | 'coarse';
+ forcedColors: boolean;
+ viewport: {width: number; height: number};
+ interaction: Interaction;
+};
+
+const defaults: Omit<AuditCase, 'key' | 'interaction'> = {
+ mode: 'light',
+ direction: 'ltr',
+ theme: 'neutral',
+ size: 'md',
+ pointer: 'fine',
+ forcedColors: false,
+ viewport: WIDE,
+};
+
+const overrides: (Partial<AuditCase> &
+ Pick<AuditCase, 'key' | 'interaction'>)[] = [
+ {key: 'neutral-light-rest', interaction: 'rest'},
+ {key: 'neutral-dark-rest', mode: 'dark', interaction: 'rest'},
+ {key: 'butter-light-rest', theme: 'butter', interaction: 'rest'},
+ {key: 'butter-dark-rest', theme: 'butter', mode: 'dark', interaction: 'rest'},
+ {key: 'rtl-light-rest', direction: 'rtl', interaction: 'rest'},
+ {key: 'rtl-dark-rest', direction: 'rtl', mode: 'dark', interaction: 'rest'},
+ {key: 'narrow-light-rest', viewport: NARROW, interaction: 'rest'},
+ {
+ key: 'narrow-dark-rest',
+ viewport: NARROW,
+ mode: 'dark',
+ interaction: 'rest',
+ },
+ {key: 'size-sm-light-rest', size: 'sm', interaction: 'rest'},
+ {key: 'size-lg-light-rest', size: 'lg', interaction: 'rest'},
+ {key: 'size-sm-dark-rest', size: 'sm', mode: 'dark', interaction: 'rest'},
+ {key: 'size-lg-dark-rest', size: 'lg', mode: 'dark', interaction: 'rest'},
+ {key: 'coarse-light-rest', pointer: 'coarse', interaction: 'rest'},
+ {
+ key: 'coarse-rtl-light-rest',
+ pointer: 'coarse',
+ direction: 'rtl',
+ interaction: 'rest',
+ },
+ {key: 'neutral-light-hover', interaction: 'hover'},
+ {key: 'neutral-dark-hover', mode: 'dark', interaction: 'hover'},
+ {key: 'neutral-light-focus', interaction: 'focus'},
+ {key: 'neutral-dark-focus', mode: 'dark', interaction: 'focus'},
+ {key: 'butter-light-focus', theme: 'butter', interaction: 'focus'},
+ {key: 'neutral-light-pressed', interaction: 'pressed'},
+ {key: 'neutral-light-select', interaction: 'select'},
+ {key: 'neutral-dark-pressed', mode: 'dark', interaction: 'pressed'},
+ {key: 'neutral-dark-select', mode: 'dark', interaction: 'select'},
+ {key: 'neutral-light-disabled-hover', interaction: 'disabled-hover'},
+ {
+ key: 'neutral-dark-disabled-hover',
+ mode: 'dark',
+ interaction: 'disabled-hover',
+ },
+ {key: 'forced-colors-focus', forcedColors: true, interaction: 'focus'},
+];
+const cases: AuditCase[] = overrides.map(item => ({...defaults, ...item}));
+
+// Authored before observation: which row each interaction leaves checked and
+// active, and how many consumer handler calls the fixture must record.
+const expectedChecked = (item: AuditCase) =>
+ item.interaction === 'select' ? 'List' : 'Board';
+const expectedActive = (item: AuditCase) =>
+ ({
+ rest: undefined,
+ hover: 'List',
+ focus: 'Board',
+ pressed: 'List',
+ select: 'List',
+ 'disabled-hover': null,
+ })[item.interaction];
+
+let server: StaticServer;
+let checkoutSha: string;
+let storybookSha: string;
+
+function storyUrl(item: AuditCase) {
+ return `${server.origin}/iframe.html?id=${STORY_ID}&viewMode=story&args=size:${item.size}&globals=colorMode:${item.mode};astryxTheme:${item.theme};direction:${item.direction}`;
+}
+
+async function settle(page: Page) {
+ await holdMotionStill(page);
+ await page.evaluate(async () => document.fonts.ready);
+ await page.waitForTimeout(60);
+}
+
+test.beforeAll(async () => {
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ }).trim();
+ const expected = process.env.ASTRYX_HEAD_SHA;
+ if (expected && expected !== checkoutSha) {
+ throw new Error(
+ `checkout ${checkoutSha} does not match expected head ${expected}`,
+ );
+ }
+ server = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ const response = await fetch(`${server.origin}/astryx-build-sha.txt`);
+ if (!response.ok) {
+ throw new Error(`Storybook build has no SHA stamp (${response.status})`);
+ }
+ storybookSha = (await response.text()).trim();
+ if (storybookSha !== checkoutSha) {
+ throw new Error(
+ `Storybook ${storybookSha} does not match checkout ${checkoutSha}`,
+ );
+ }
+});
+
+test.afterAll(async () => {
+ await server?.close();
+ const receipts = fs
+ .readdirSync(OUTPUT)
+ .filter(file => file.endsWith('.sensors.json'))
+ .sort();
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify(
+ {
+ schemaVersion: 1,
+ component: 'core/DropdownMenuRadioItem',
+ build: checkoutSha,
+ expectedFrames: cases.map(item => item.key),
+ receipts: receipts.map(file => {
+ const receipt = JSON.parse(
+ fs.readFileSync(path.join(OUTPUT, file), 'utf8'),
+ );
+ return {
+ key: file.replace('.sensors.json', ''),
+ passed: receipt.passed,
+ };
+ }),
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+});
+
+for (const item of cases) {
+ test(item.key, async ({browser}) => {
+ const coarse = item.pointer === 'coarse';
+ const context = await browser.newContext({
+ viewport: item.viewport,
+ colorScheme: item.mode,
+ reducedMotion: 'reduce',
+ forcedColors: item.forcedColors ? 'active' : 'none',
+ hasTouch: coarse,
+ isMobile: coarse,
+ });
+ const page = await context.newPage();
+ const pageErrors: string[] = [];
+ page.on('pageerror', error => pageErrors.push(String(error)));
+ await page.goto(storyUrl(item), {waitUntil: 'load'});
+ await page.locator('#storybook-root').waitFor();
+
+ const fixture = page.getByTestId('dropdown-menu-radio-item-audit');
+ const menu = page.getByRole('menu').last();
+ await expect(menu).toBeVisible();
+ const row = (name: string) =>
+ menu.getByRole('menuitemradio', {name: new RegExp(`^${name}`)});
+ await expect(menu.getByRole('menuitemradio')).toHaveCount(5);
+
+ if (item.interaction === 'hover') {
+ await row('List').hover();
+ await expect(row('List')).toBeFocused();
+ } else if (item.interaction === 'focus') {
+ await page.getByRole('button', {name: 'View'}).focus();
+ await page.keyboard.press('ArrowDown');
+ await expect(row('Board')).toBeFocused();
+ } else if (item.interaction === 'pressed') {
+ await row('List').hover();
+ await page.mouse.down();
+ } else if (item.interaction === 'select') {
+ await row('List').click();
+ await expect(row('List')).toHaveAttribute('aria-checked', 'true');
+ } else if (item.interaction === 'disabled-hover') {
+ await row('Archive').hover();
+ }
+ await settle(page);
+
+ // Geometry must be settled before any frame is trusted: read every row and
+ // marker box, wait two animation frames plus a pause, and read again.
+ const settledGeometry = await menu.evaluate(async element => {
+ const read = () =>
+ [
+ element,
+ ...Array.from(
+ element.querySelectorAll(
+ '[role="menuitemradio"], .astryx-dropdown-menu-radio',
+ ),
+ ),
+ ]
+ .map(node => {
+ const box = node.getBoundingClientRect();
+ return [box.x, box.y, box.width, box.height]
+ .map(value => value.toFixed(2))
+ .join(',');
+ })
+ .join('|');
+ const first = read();
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => setTimeout(resolve, 120)),
+ );
+ });
+ const second = read();
+ return {stable: first === second, boxes: first.split('|').length};
+ });
+
+ const observed = await menu.evaluate(element => {
+ const canvas = document.createElement('canvas');
+ canvas.width = 1;
+ canvas.height = 1;
+ const ctx = canvas.getContext('2d', {willReadFrequently: true});
+ if (ctx === null) {
+ throw new Error('2d canvas context is unavailable');
+ }
+ type Rgba = [number, number, number, number];
+ const rgba = (color: string): Rgba => {
+ ctx.clearRect(0, 0, 1, 1);
+ ctx.fillStyle = '#000';
+ ctx.fillStyle = color;
+ ctx.fillRect(0, 0, 1, 1);
+ const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
+ return [r, g, b, a / 255];
+ };
+ const over = (top: Rgba, bottom: Rgba): Rgba => {
+ const alpha = top[3] + bottom[3] * (1 - top[3]);
+ if (alpha === 0) {
+ return [0, 0, 0, 0];
+ }
+ const mix = (i: number) =>
+ (top[i] * top[3] + bottom[i] * bottom[3] * (1 - top[3])) / alpha;
+ return [mix(0), mix(1), mix(2), alpha];
+ };
+ const backdrop = (node: Element): Rgba => {
+ const layers: Rgba[] = [];
+ for (let n: Element | null = node; n; n = n.parentElement) {
+ layers.push(rgba(getComputedStyle(n).backgroundColor));
+ }
+ let acc: Rgba = [255, 255, 255, 1];
+ for (let i = layers.length - 1; i >= 0; i--) {
+ acc = over(layers[i], acc);
+ }
+ return acc;
+ };
+ const luminance = ([r, g, b]: Rgba) => {
+ const f = (v: number) => {
+ const c = v / 255;
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
+ };
+ return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
+ };
+ const ratio = (fg: Rgba, bg: Rgba) => {
+ const [hi, lo] = [luminance(over(fg, bg)), luminance(bg)].sort(
+ (a, b) => b - a,
+ );
+ return Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100;
+ };
+ const hex = (c: Rgba) =>
+ `#${c
+ .slice(0, 3)
+ .map(v => Math.round(v).toString(16).padStart(2, '0'))
+ .join('')}${c[3] < 1 ? `@${c[3].toFixed(2)}` : ''}`;
+ const fade = (c: Rgba, opacity: number): Rgba => [
+ c[0],
+ c[1],
+ c[2],
+ c[3] * opacity,
+ ];
+ const menuBackdrop = backdrop(element);
+ const rows = Array.from(
+ element.querySelectorAll<HTMLElement>('[role="menuitemradio"]'),
+ ).map(row => {
+ const box = row.getBoundingClientRect();
+ const style = getComputedStyle(row);
+ const opacity = Number(style.opacity);
+ const rowBackdrop = backdrop(row);
+ const texts = Array.from(row.querySelectorAll('span'))
+ .filter(n => n.children.length === 0 && n.textContent?.trim())
+ .map(n => {
+ const color = rgba(getComputedStyle(n).color);
+ const nodeBackdrop = backdrop(n);
+ return {
+ text: (n.textContent ?? '').trim().slice(0, 24),
+ fontSize: getComputedStyle(n).fontSize,
+ color: hex(color),
+ backdrop: hex(nodeBackdrop),
+ contrast: ratio(fade(color, opacity), nodeBackdrop),
+ };
+ });
+ const indicator = row.querySelector<HTMLElement>(
+ '.astryx-dropdown-menu-radio',
+ );
+ const indicatorStyle = indicator ? getComputedStyle(indicator) : null;
+ const indicatorBox = indicator?.getBoundingClientRect() ?? null;
+ const border = indicatorStyle
+ ? rgba(indicatorStyle.borderTopColor)
+ : null;
+ const fill = indicatorStyle
+ ? rgba(indicatorStyle.backgroundColor)
+ : null;
+ const isRtl = style.direction === 'rtl';
+ return {
+ name: row.textContent?.replace(/\s+/g, ' ').trim() ?? '',
+ checked: row.getAttribute('aria-checked'),
+ disabled: row.getAttribute('aria-disabled'),
+ tabIndex: row.getAttribute('tabindex'),
+ focused: document.activeElement === row,
+ focusVisible: row.matches(':focus-visible'),
+ cursor: style.cursor,
+ opacity,
+ outline: `${style.outlineStyle} ${style.outlineWidth}`,
+ background: hex(rgba(style.backgroundColor)),
+ rowBackdrop: hex(rowBackdrop),
+ rowAgainstMenu: ratio(rowBackdrop, menuBackdrop),
+ texts,
+ indicator:
+ indicator && indicatorBox && indicatorStyle && border && fill
+ ? {
+ classes: Array.from(indicator.classList).filter(c =>
+ c.startsWith('astryx-'),
+ ),
+ dataSize: indicator.getAttribute('data-size'),
+ dataChecked: indicator.getAttribute('data-checked'),
+ hidden: indicator.closest('[aria-hidden="true"]') !== null,
+ width: indicatorBox.width,
+ height: indicatorBox.height,
+ inlineStartOffset: isRtl
+ ? box.right - indicatorBox.right
+ : indicatorBox.left - box.left,
+ inlineEndOffset: isRtl
+ ? indicatorBox.left - box.left
+ : box.right - indicatorBox.right,
+ border: hex(border),
+ fill: hex(fill),
+ borderContrast: ratio(fade(border, opacity), rowBackdrop),
+ fillContrast:
+ fill[3] > 0
+ ? ratio(fade(fill, opacity), rowBackdrop)
+ : null,
+ }
+ : null,
+ geometry: {
+ x: box.x,
+ y: box.y,
+ width: box.width,
+ height: box.height,
+ },
+ };
+ });
+ const fixtureNode = element.ownerDocument.querySelector(
+ '[data-testid="dropdown-menu-radio-item-audit"]',
+ );
+ const menuBox = element.getBoundingClientRect();
+ return {
+ theme:
+ document
+ .querySelector('[data-astryx-theme]')
+ ?.getAttribute('data-astryx-theme') ?? null,
+ mode: document.documentElement.getAttribute('data-theme'),
+ direction: getComputedStyle(element).direction,
+ viewport: {width: innerWidth, height: innerHeight},
+ media: {
+ pointerCoarse: matchMedia('(pointer: coarse)').matches,
+ forcedColors: matchMedia('(forced-colors: active)').matches,
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ devicePixelRatio,
+ },
+ fonts: document.fonts.status,
+ horizontalOverflow:
+ document.documentElement.scrollWidth > innerWidth + 1,
+ menuBackdrop: hex(menuBackdrop),
+ menu: {
+ x: menuBox.x,
+ y: menuBox.y,
+ width: menuBox.width,
+ height: menuBox.height,
+ },
+ activeRow:
+ document.activeElement?.getAttribute('role') === 'menuitemradio'
+ ? (document.activeElement.textContent
+ ?.replace(/\s+/g, ' ')
+ .trim() ?? null)
+ : null,
+ consumerClicks: Number(
+ fixtureNode?.getAttribute('data-row-click-count') ?? 'NaN',
+ ),
+ consumerPointerMoves: Number(
+ fixtureNode?.getAttribute('data-row-pointer-move-count') ?? 'NaN',
+ ),
+ rows,
+ };
+ });
+ await expect(fixture).toBeAttached();
+
+ const checked = observed.rows
+ .filter(row => row.checked === 'true')
+ .map(row => row.name);
+ const active = expectedActive(item);
+ const markerSize = item.size === 'sm' ? 'sm' : 'md';
+ const checks = {
+ build: storybookSha === checkoutSha,
+ noPageErrors: pageErrors.length === 0,
+ theme: observed.theme === item.theme,
+ mode: observed.mode === item.mode,
+ direction: observed.direction === item.direction,
+ viewport:
+ observed.viewport.width === item.viewport.width &&
+ observed.viewport.height === item.viewport.height,
+ pointer: observed.media.pointerCoarse === (item.pointer === 'coarse'),
+ forcedColors: observed.media.forcedColors === item.forcedColors,
+ reducedMotion: observed.media.reducedMotion,
+ fonts: observed.fonts === 'loaded',
+ noHorizontalOverflow: !observed.horizontalOverflow,
+ rows: observed.rows.length === 5,
+ checked:
+ checked.length === 1 && checked[0].startsWith(expectedChecked(item)),
+ disabledRow:
+ observed.rows[4]?.disabled === 'true' &&
+ observed.rows[4]?.tabIndex === null,
+ activeRow:
+ active === undefined
+ ? true
+ : active === null
+ ? !(observed.activeRow ?? '').startsWith('Archive')
+ : (observed.activeRow ?? '').startsWith(active),
+ decorativeMarker: observed.rows.every(
+ row =>
+ row.indicator !== null &&
+ row.indicator.hidden &&
+ row.indicator.dataSize === markerSize &&
+ row.indicator.width > 0 &&
+ row.indicator.classes.includes('astryx-radio-indicator'),
+ ),
+ markerPlacement: observed.rows.every(row =>
+ row.indicator === null
+ ? false
+ : item.pointer === 'coarse'
+ ? row.indicator.inlineEndOffset < row.indicator.inlineStartOffset
+ : row.indicator.inlineStartOffset < row.indicator.inlineEndOffset,
+ ),
+ geometrySettled: settledGeometry.stable && settledGeometry.boxes === 11,
+ geometry: observed.rows.every(
+ row => row.geometry.width > 0 && row.geometry.height >= 24,
+ ),
+ // The fixture's consumer handlers record every call; a selection click
+ // must reach the consumer click handler and the hover that preceded it
+ // must reach the consumer pointer-move handler.
+ consumerHandlers:
+ item.interaction === 'select'
+ ? observed.consumerClicks === 1 && observed.consumerPointerMoves > 0
+ : observed.consumerClicks === 0,
+ };
+
+ const png = await page.screenshot({animations: 'disabled'});
+ if (item.interaction === 'pressed') {
+ await page.mouse.up();
+ }
+ const image = `${item.key}.png`;
+ const receipt = {
+ schemaVersion: 1,
+ expected: {
+ build: checkoutSha,
+ storyId: STORY_ID,
+ ...item,
+ checked: expectedChecked(item),
+ activeRow: active,
+ },
+ observed: {
+ build: storybookSha,
+ browser: context.browser()?.version() ?? null,
+ ...observed,
+ settledGeometry,
+ pageErrors,
+ },
+ image: {
+ file: image,
+ sha256: createHash('sha256').update(png).digest('hex'),
+ width: png.readUInt32BE(16),
+ height: png.readUInt32BE(20),
+ },
+ checks,
+ passed: Object.values(checks).every(Boolean),
+ };
+ fs.writeFileSync(path.join(OUTPUT, image), png);
+ fs.writeFileSync(
+ path.join(OUTPUT, `${item.key}.sensors.json`),
+ `${JSON.stringify(receipt, null, 2)}\n`,
+ );
+ await context.close();
+ expect(
+ Object.entries(checks)
+ .filter(([, passed]) => !passed)
+ .map(([name]) => name),
+ ).toEqual([]);
+ });
+}