Skip to content

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

TypeScript

[Component Audit] DropdownMenu: keep the focused row visible in forced colors (#7517)

Cindy Zhang48f6a067fc99
diff --git a/.changeset/dropdown-menu-docs-accuracy.md b/.changeset/dropdown-menu-docs-accuracy.md
new file mode 100644
index 0000000000..4889cb0afd
--- /dev/null
+++ b/.changeset/dropdown-menu-docs-accuracy.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] The development warning for passing both `button` and `renderTrigger` to `DropdownMenu` now names `renderTrigger`; it named a `trigger` prop that does not exist. The docs match the component too: `button` is mutually exclusive with `renderTrigger`, the private menu radius defaults to `--radius-container`, and a disabled `DropdownMenuCheckboxItem` or `DropdownMenuRadioItem` takes no focus — the arrow keys, typeahead, and the pointer highlight skip it — while it stays in the accessibility tree as disabled.
+
+@cixzhang
diff --git a/.changeset/dropdown-menu-forced-colors-focus.md b/.changeset/dropdown-menu-forced-colors-focus.md
new file mode 100644
index 0000000000..b5b4b36f06
--- /dev/null
+++ b/.changeset/dropdown-menu-forced-colors-focus.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A keyboard-focused `DropdownMenu` row now shows the standard focus ring, drawn inside the row, in every color mode. Rows showed focus only with a translucent background, which forced colors (Windows High Contrast and similar modes) replace with the page color, so a keyboard user there could not tell which row Enter would activate. The ring follows the last input: after a key press it marks the focused row, including a row the mouse then moves focus to; after a mouse or touch press it does not show. Action, destructive, checkbox, radio and sub-menu rows all show it, including in `ContextMenu` and breadcrumb menus. A `ContextMenu` opened by right-click or long-press focuses its first row without the ring; one opened from the keyboard shows it.
+
+@cixzhang
diff --git a/.changeset/dropdown-menu-popover-presentation-theming.md b/.changeset/dropdown-menu-popover-presentation-theming.md
new file mode 100644
index 0000000000..11e32ab2ce
--- /dev/null
+++ b/.changeset/dropdown-menu-popover-presentation-theming.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] The anchored `DropdownMenu` now reflects `data-presentation="popover"` on its `dropdown-menu` target, as the bottom sheet already reflected `bottom-sheet`. A theme rule written for `presentation:popover`, which the docs list as a visual prop of that target, now applies.
+
+@cixzhang
diff --git a/docs/specs/components/DropdownMenu/DropdownMenuCheckboxItem.spec.md b/docs/specs/components/DropdownMenu/DropdownMenuCheckboxItem.spec.md
index 67092e9a6f..1769b2d63f 100644
--- a/docs/specs/components/DropdownMenu/DropdownMenuCheckboxItem.spec.md
+++ b/docs/specs/components/DropdownMenu/DropdownMenuCheckboxItem.spec.md
@@ -131,10 +131,11 @@ Consumer migration instructions belong in consumer docs and release notes.
accessible name, checked state, focus, and activation; the marker is
decorative.
- **AR2 — Disabled state.** A disabled row is inert.
-- **AR3 — Focus visibility.** Keyboard focus paints only the menu overlay
- tint, about 1.1:1 against the menu surface in the default themes, with no
- outline, and nothing under forced colors. The shared row treatment is
- `component:DropdownMenuItem` OQ2.
+- **AR3 — Focus visibility.** Keyboard focus draws the shared focus ring
+ inside the row, inset by the ring's own width, in every color mode, forced
+ colors included; after pointer input the row shows only the overlay tint
+ (`architecture:interaction-modality` INV1, INV3). The shared row treatment is
+ `component:DropdownMenuItem` FR8.
## Design relationships
@@ -163,14 +164,10 @@ anatomy-theming map.
| FR4 | `DropdownMenuSelectable.test.tsx` "composes the caller pointer-move handler with menu hover focus" and "a ref reaches the menuitemcheckbox element" | Ref; pointer move | A dropped ref or handler fails. Evidence gap: no test asserts host attributes, `className`, `style`, or `xstyle` on the row. | `audit:DropdownMenuCheckboxItem/api` |
| FR5 | `DropdownMenuSelectable.test.tsx` "maps a small menu to the small shared checkbox marker" | Small menu | A marker that ignores the menu size fails. Evidence gap: no test asserts the `dropdown-menu-item` target on this row. | `audit:DropdownMenuCheckboxItem/theming` |
| FR6 | `DropdownMenu.test.tsx` "arrow navigation reaches consumer-rendered menuitemradio and menuitemcheckbox items" and "skips aria-disabled menuitemradio and menuitemcheckbox items during arrow navigation" | Enabled and disabled rows | A row the arrows miss, or a disabled row they land on, fails. | `audit:DropdownMenuCheckboxItem/accessibility` |
-| AR3, PR1 | Evidence gap: no test asserts the focus paint or the listener bound | — | — | `audit:DropdownMenuCheckboxItem/behavior` |
+| AR3, PR1 | `DropdownMenuForcedColors.test.tsx` (the row's `:focus-visible` ring and token inset); `DropdownMenuAudit.a11y.chromium.spec.ts` forced-colors frames. Evidence gap: no test asserts the listener bound | — | — | `audit:DropdownMenuCheckboxItem/behavior` |
## Current-state impact
-- **Focus visibility (AR3).** Keyboard focus on a checkbox row shows only an
- overlay tint about 1.1:1 against the menu surface, and no indicator in
- forced-colors mode; the shared row treatment is `component:DropdownMenuItem`
- OQ2.
- **Enter keeps the menu open (FR2).** Enter on a checkbox row toggles it and
leaves the menu open by default, against the Menu pattern's Enter that
`spec:AST-020` FR15 adopts, with no named exception (OQ1).
diff --git a/docs/specs/components/DropdownMenu/DropdownMenuItem.spec.md b/docs/specs/components/DropdownMenu/DropdownMenuItem.spec.md
index d9ea1f8cfa..0d0af7180c 100644
--- a/docs/specs/components/DropdownMenu/DropdownMenuItem.spec.md
+++ b/docs/specs/components/DropdownMenu/DropdownMenuItem.spec.md
@@ -110,7 +110,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR5 | The visible root carries `dropdown-menu-item`; size and destructive state reflect on it (`data-size`, `data-variant`); semantic tokens own layout and paint before caller styling inputs compose. | `architecture:component-theming-surface`; current source and tests |
| FR6 | Ref, supported host attributes and handlers, `className`, `style`, and `xstyle` reach or compose on the row root without replacing owned role, tab stop, disabled behavior, destination handling, or activation order. | `architecture:public-component-api` INV5–INV9; current tests |
| FR7 | Disabled menu rows are inert, and the parent menu's arrow keys and typeahead skip them. Shipped behavior, not a requirement until OQ1 is ruled. | `component:DropdownMenu` FR17, OQ1 |
-| FR8 | Keyboard focus paints the row's hover background with no outline, about 1.1:1 against the menu surface in the default themes; in forced-colors mode that background is not drawn, so focus has no visible indicator. Shipped behavior; the focus treatment is OQ2. | Current source |
+| FR8 | Keyboard focus draws the shared focus ring inside the row, inset by the ring's own width, in every color mode; forced colors keep that ring as the focus indicator. After pointer input the row shows only its hover background (`architecture:interaction-modality` INV1); the focused row owns the indicator (INV3). | Current source; `architecture:interaction-modality` INV1, INV3 |
### Allowed variation
@@ -153,8 +153,9 @@ Consumer migration instructions belong in consumer docs and release notes.
- **AR2 — Disabled state.** Disabled rows expose state and cannot activate or navigate.
- **AR3 — Keyboard ownership.** DropdownMenu owns focus collection and activation;
the item remains a single row in that model.
-- **AR4 — Focus perception.** Focus paints a low-contrast row background in
- ordinary themes and no indicator in forced-colors mode (FR8, OQ2).
+- **AR4 — Focus perception.** After keyboard input the focused row draws the
+ shared focus ring inside its edge in every color mode, forced colors
+ included; after pointer input it shows only its hover background (FR8).
## Design relationships
@@ -162,7 +163,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| ---------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------- | -------------- | ------------------ |
| Row | One full-width action/destination target with tokenized insets and start alignment. | Current source and parent menu composition | prominent | FR1–FR6 |
| Supporting text | Description and end content remain subordinate to the row label. | Delegated Item layout and current consumer docs | supporting | FR1 |
-| Interaction | Hover, focus, press, disabled, and destructive states remain distinguishable. | Current source; forced-colors focus is OQ2 | prominent | FR5, FR8, AR4 |
+| Interaction | Hover, focus, press, disabled, and destructive states remain distinguishable. | Current source; FR8 | prominent | FR5, FR8, AR4 |
No component-local visual decision is recorded.
@@ -188,14 +189,12 @@ No component-local visual decision is recorded.
| FR5 | `DropdownMenu.test.tsx` destructive-variant cases; `themingTargets.test.ts` | Default and destructive; data and compound mode | A missing `data-variant` fails; a rendered class absent from the documented targets fails. Evidence gap: no test asserts the `dropdown-menu-item` class or `data-size`. | `audit:DropdownMenuItem/theming` |
| FR6 | `DropdownMenu.test.tsx` ref and host-attribute cases ("a ref reaches the menuitem element", "puts aria-\*, data-\* and id on the row root, a link row included", "runs the DOM handlers the caller attaches, such as a drop target") | Ref; host attributes; caller handlers | A dropped ref, attribute, or handler fails. Evidence gap: no test asserts `className`, `style`, or `xstyle` on the row. | `audit:DropdownMenuItem/api` |
| FR7 | `DropdownMenu.test.tsx` "skips aria-disabled menuitemradio and menuitemcheckbox items during arrow navigation" (the shipped behavior OQ1 leaves open) | Disabled rows | A disabled row that activates fails. | `audit:DropdownMenuItem/accessibility` |
-| FR8, AR4, PR1 | Evidence gap: no test asserts the focus paint, forced-colors focus, or the listener bound | — | — | `audit:DropdownMenuItem/visual` |
+| FR8, AR4, PR1 | `DropdownMenuForcedColors.test.tsx` (each row's `:focus-visible` ring and token inset); `DropdownMenuAudit.a11y.chromium.spec.ts` forced-colors frames | Action and destructive rows; light, dark, forced colors | A row without the ring after keyboard input, or a ring not inset by the ring width, fails. Evidence gap: no test asserts the listener bound. | `audit:DropdownMenuItem/visual` |
| RTL | `apps/storybook/rtl-audit/verified-not-applicable.json` DropdownMenuItem entry | LTR and RTL | A changed source hash fails the receipt. | `audit:DropdownMenuItem/rtl` |
## Current-state impact
-- **Focus visibility (FR8).** Keyboard focus on a row shows only a background
- tint about 1.1:1 against the menu surface, and no indicator in forced-colors
- mode; the treatment is OQ2.
+No known difference between shipped behavior and this contract.
## Decision log
@@ -205,8 +204,6 @@ No component-local decision.
- **OQ1 — Which shared keyboard owner should keep disabled menu items discoverable
while preserving their inert behavior?** (`human-api`)
-- **OQ2 — Should forced-colors focus use a component-specific system outline, or a
- shared row-focus treatment that also governs ordinary themes?** (`human-design`)
## Content boundary
diff --git a/docs/specs/components/DropdownMenu/DropdownMenuRadioItem.spec.md b/docs/specs/components/DropdownMenu/DropdownMenuRadioItem.spec.md
index 095a9f3333..6b1d666fde 100644
--- a/docs/specs/components/DropdownMenu/DropdownMenuRadioItem.spec.md
+++ b/docs/specs/components/DropdownMenu/DropdownMenuRadioItem.spec.md
@@ -128,14 +128,14 @@ Consumer migration instructions belong in consumer docs and release notes.
### 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. |
+| 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 AR4. |
+| 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
@@ -161,10 +161,11 @@ Consumer migration instructions belong in consumer docs and release notes.
- **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.** Keyboard focus paints only the menu overlay
- tint, about 1.1:1 against the menu surface in the default themes, with no
- outline, and nothing under forced colors. The shared row
- treatment is `component:DropdownMenuItem` OQ2.
+- **AR4 — Focus visibility.** Keyboard focus draws the shared focus ring
+ inside the row, inset by the ring's own width, in every color mode, forced
+ colors included; after pointer input the row shows only the overlay tint
+ (`architecture:interaction-modality` INV1, INV3). The shared row treatment is
+ `component:DropdownMenuItem` FR8.
## Design relationships
@@ -182,8 +183,8 @@ No component-local visual decision is recorded.
- `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).
+ keyboard discoverability (its OQ1), and the shared row focus treatment
+ together with `component:DropdownMenuItem` (its FR8).
- `architecture:public-component-api` owns root input and handler composition.
- `architecture:component-theming-surface` owns target placement and state
reflection.
@@ -200,14 +201,11 @@ No component-local visual decision is recorded.
| FR4, AR2 | `DropdownMenuSelectable.test.tsx` "does not select, close, or call the caller click handler when disabled"; `DropdownMenu.test.tsx` "does not move focus on hover for a disabled item" | Disabled | A selection, close, or caller `onClick` while disabled, or hover focus on a disabled row, fails. Evidence gap: no test asserts the absent `tabindex` or the half-opacity paint. | `audit:DropdownMenuRadioItem/behavior` |
| FR5 | `DropdownMenuSelectable.test.tsx` "composes caller root inputs without replacing the row semantics", "composes the caller pointer-move handler with menu hover focus", and "a ref reaches the menuitemradio element" | Ref, host attributes, class, style, pointer move | A dropped ref, attribute, class, style, or handler fails. Evidence gap: no test asserts `xstyle` on the row. | `audit:DropdownMenuRadioItem/api` |
| FR6, FR7 | `DropdownMenuSelectable.test.tsx` "renders the shared radio indicator in the menu marker"; `DropdownMenuRadioItemAudit.a11y.chromium.spec.ts` | Marker in the row | A missing shared radio marker fails. Evidence gap: no test asserts the marker size by menu size, its fine and coarse placement, or the `dropdown-menu-radio` reflections. | `audit:DropdownMenuRadioItem/visual` |
-| AR4, PR1 | Evidence gap: no test asserts the focus paint, forced-colors focus, or the absence of lifecycle resources | — | — | `audit:DropdownMenuRadioItem/visual` |
+| AR4, PR1 | `DropdownMenuForcedColors.test.tsx` (the row's `:focus-visible` ring and token inset); `DropdownMenuAudit.a11y.chromium.spec.ts` forced-colors frames. Evidence gap: no test asserts the absence of lifecycle resources | — | — | `audit:DropdownMenuRadioItem/visual` |
## Current-state impact
-- **Focus visibility (AR4).** Keyboard focus on a radio row shows only an
- overlay tint about 1.1:1 against the menu surface, and no indicator in
- forced-colors mode; the shared row treatment is
- `component:DropdownMenuItem` OQ2.
+No known difference between shipped behavior and this contract.
## Decision log
diff --git a/docs/specs/components/DropdownMenu/DropdownMenuSubMenu.spec.md b/docs/specs/components/DropdownMenu/DropdownMenuSubMenu.spec.md
index ea57fc2cbf..1e55493170 100644
--- a/docs/specs/components/DropdownMenu/DropdownMenuSubMenu.spec.md
+++ b/docs/specs/components/DropdownMenu/DropdownMenuSubMenu.spec.md
@@ -162,10 +162,11 @@ Consumer migration instructions belong in consumer docs and release notes.
Escape; a deeper level's keys never act on its parent.
- **AR3 — Disabled discoverability.** Whether disabled rows stay
keyboard-discoverable is owned by `component:DropdownMenu` (its OQ1).
-- **AR4 — Focus visibility.** Keyboard focus paints only the menu overlay
- tint, about 1.1:1 against the menu surface in the default themes, with no
- outline, and nothing under forced colors. The shared row
- treatment is `component:DropdownMenuItem` OQ2.
+- **AR4 — Focus visibility.** Keyboard focus draws the shared focus ring
+ inside the row, inset by the ring's own width, in every color mode, forced
+ colors included; after pointer input the row shows only the overlay tint
+ (`architecture:interaction-modality` INV1, INV3). The shared row treatment is
+ `component:DropdownMenuItem` FR8.
## Design relationships
@@ -202,16 +203,12 @@ No component-local visual decision is recorded.
| FR6 | `DropdownMenuSubMenu.test.tsx` "reports each flyout open and close to onOpenChange once" | Flyout open and close | A missing or repeated report fails. Evidence gap: the drill-in reset gap is not asserted. | `audit:DropdownMenuSubMenu/behavior` |
| FR7, FR9 | `DropdownMenuSubMenu.test.tsx` "does not open a disabled submenu", "a disabled row does not pass a click on to the caller's onClick", host-attribute and ref cases ("aria-\*, data-\* and id reach the trigger row, and the flyout stays labelled by it", "a ref reaches the trigger row", "a caller's handlers run after the row's own, and the row still opens and takes the hover focus") | Disabled; caller handlers and attributes | A disabled open or caller click, or a dropped attribute, ref, or handler, fails. Evidence gap: no test asserts `className`, `style`, or `xstyle` on the row. | `audit:DropdownMenuSubMenu/api` |
| FR8 | `BusyOwnerAnnouncement.test.tsx` "DropdownMenuSubMenu loading state" cases; `DropdownMenuSubMenu.test.tsx` loading-flyout cases | Loading closed and open | A busy start announced while closed, twice, or not at all, or an announced Spinner, fails. | `audit:DropdownMenuSubMenu/accessibility` |
-| AR4, PR1 | Evidence gap: no test asserts the focus paint, forced-colors focus, or the timer bounds | — | — | `audit:DropdownMenuSubMenu/visual` |
+| AR4, PR1 | `DropdownMenuForcedColors.test.tsx` (the row's `:focus-visible` ring and token inset); `DropdownMenuAudit.a11y.chromium.spec.ts` forced-colors frames. Evidence gap: no test asserts the timer bounds | — | — | `audit:DropdownMenuSubMenu/visual` |
## Current-state impact
- **Drill-in close report (FR6).** When the root menu closes a drilled-in view,
`onOpenChange(false)` does not run (OQ1).
-- **Focus visibility (AR4).** Keyboard focus on the row shows only an
- overlay tint about 1.1:1 against the menu surface, and no indicator in
- forced-colors mode; the shared row treatment is
- `component:DropdownMenuItem` OQ2.
## Decision log
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index 8352ba2bb3..e14cd2eeda 100644
--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx
@@ -189,6 +189,27 @@ describe('ContextMenu', () => {
expect(screen.getByTestId('ctx')).not.toHaveAttribute('aria-haspopup');
});
+ // architecture:interaction-modality INV1: a pointer-opened menu focuses its
+ // first row without the keyboard ring; a keyboard open keeps it.
+ it('focuses the first row with the focus the last input calls for', async () => {
+ const focus = vi.spyOn(HTMLElement.prototype, 'focus');
+ render(
+ <ContextMenu items={[{label: 'Cut'}, {label: 'Copy'}]}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+ const target = screen.getByText('Right-click me');
+ fireEvent.pointerDown(target, {pointerType: 'mouse', button: 2});
+ fireEvent.contextMenu(target);
+ await waitFor(() =>
+ expect(focus).toHaveBeenCalledWith(
+ expect.objectContaining({focusVisible: false}),
+ ),
+ );
+ expect(focus.mock.contexts.at(-1)).toHaveTextContent('Cut');
+ focus.mockRestore();
+ });
+
it('opens menu on right-click', () => {
render(
<ContextMenu items={[{label: 'Item 1'}]}>
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index 84e95dadd0..59aa0f5461 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -75,7 +75,7 @@ import {
} from '../DropdownMenu/menuItemRoles';
import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow';
import {useMenuDrillIn} from '../DropdownMenu/useMenuDrillIn';
-import {useListFocus} from '../hooks/useListFocus';
+import {useInternalListFocus} from '../hooks/useListFocus';
import {useMenuPress} from '../hooks/useMenuPress';
import {useTypeahead} from '../hooks/useTypeahead';
import {useLongPress} from '../hooks/useLongPress';
@@ -465,12 +465,15 @@ export function ContextMenu({
focusItem,
ownsEvent,
getItems: getMenuItems,
- } = useListFocus<HTMLDivElement>({
+ } = useInternalListFocus<HTMLDivElement>({
itemSelector: MENU_ITEM_SELECTOR,
boundarySelector: MENU_BOUNDARY_SELECTOR,
// Menus wrap from the last row to the first and back.
wrap: true,
hasPaging: true,
+ // A right-click or long-press focuses the first row without the keyboard
+ // ring; the context-menu key or Shift+F10 shows it.
+ focusFollowsLastInput: true,
});
focusFirstRef.current = focusFirst;
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index 949d2c551a..c2121be176 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -158,7 +158,7 @@ export const docs = {
{
name: '--_dropdown-menu-radius',
description: 'Border radius of the menu popup',
- default: 'var(--radius-element)',
+ default: 'var(--radius-container)',
private: true,
},
{
@@ -180,7 +180,7 @@ export const docs = {
name: 'button',
type: 'DropdownMenuButtonProps',
description:
- 'Props for the trigger button (Button props except onClick). Mutually exclusive with `trigger`.',
+ 'Props for the trigger button (Button props except onClick). Mutually exclusive with `renderTrigger`.',
default: "{ label: 'Menu' }",
},
{
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 370e758c84..e9075c67ef 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -351,7 +351,7 @@ export type DropdownMenuButtonProps = Omit<ButtonProps, 'onClick'>;
export type DropdownMenuPresentation = AdaptivePresentation;
/**
- * The props a custom `trigger` spreads onto the control that opens the menu.
+ * The props `renderTrigger` spreads onto the control that opens the menu.
* They carry the press model — a mouse opens on press-down, a held finger
* opens with the finger down — the keyboard opens (Enter, Space, ArrowDown,
* ArrowUp), the toggle click, and the ARIA wiring that names the menu after
@@ -1736,7 +1736,7 @@ function DropdownMenuPopover({
}}
{...menuPress.menuProps}
{...mergeProps(
- themeProps('dropdown-menu'),
+ themeProps('dropdown-menu', {presentation: 'popover'}),
stylex.props(
styles.dropdown,
resolvedMaxHeight != null &&
@@ -1790,8 +1790,8 @@ export function DropdownMenu(props: DropdownMenuProps) {
// Both presentations hang the menu off ONE control.
useDevWarning(
'DropdownMenu',
- '`button` and `trigger` are mutually exclusive: the menu hangs off one ' +
- 'control. `trigger` wins; drop `button`.',
+ '`button` and `renderTrigger` are mutually exclusive: the menu hangs ' +
+ 'off one control. `renderTrigger` wins; drop `button`.',
props.button != null && props.renderTrigger != null,
);
const requestedPresentation =
diff --git a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs
index 9b1e7f351e..2cd1169b7f 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs
@@ -70,7 +70,7 @@ export const docs = {
type: 'boolean',
default: 'false',
description:
- 'Whether the item is disabled. Disabled items expose aria-disabled, block activation, and are currently skipped by DropdownMenu arrow-key navigation.',
+ 'Whether the item is disabled. A disabled item stays in the accessibility tree as disabled (aria-disabled) but takes no focus: the arrow keys, typeahead, and the pointer highlight skip it, and activation is blocked.',
},
{
name: 'hasCloseOnSelect',
@@ -134,7 +134,7 @@ export const docsDense = {
value: 'checked state (controlled, w/ onChange)',
onChange: 'fired w/ next checked state on toggle',
isDisabled:
- 'disabled; aria-disabled, no activation; current menu focus skips the row',
+ 'disabled (aria-disabled); skipped by arrows/typeahead, not focusable',
hasCloseOnSelect: 'close menu on toggle (default false, stays open)',
ref: 'forwarded to the row root (the role="menuitemcheckbox" element)',
endContent: 'content after label+description',
diff --git a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx
index 5eb2263a62..e1e343f708 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx
@@ -37,8 +37,9 @@ import {renderIconSlot, type IconType} from '../Icon';
import {useIndicator} from '../Indicator';
import {Item} from '../Item';
import {useDropdownMenuContext} from './DropdownMenuContext';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {focusMenuItemOnHover} from './menuItemHover';
-import {colorVars, spacingVars} from '../theme/tokens.stylex';
+import {colorVars, focusVars, spacingVars} from '../theme/tokens.stylex';
import {composeEventHandlers, mergeProps, themeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
@@ -55,7 +56,10 @@ const styles = stylex.create({
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
- outline: 'none',
+ // Rows show focus with a translucent overlay, which forced colors replace
+ // with the page color. The standard focus ring (focusOutlineStyles), drawn
+ // inside the row by its own width, marks the focused row in every mode.
+ outlineOffset: `calc(-1 * ${focusVars['--focus-outline-width']})`,
},
disabled: {
opacity: 0.5,
@@ -110,8 +114,9 @@ export interface DropdownMenuCheckboxItemProps extends Omit<
*/
onChange?: (checked: boolean) => void;
/**
- * Whether the item is disabled. Disabled items expose `aria-disabled`, block
- * activation, and are currently skipped by DropdownMenu arrow-key navigation.
+ * Whether the item is disabled. A disabled item stays in the accessibility
+ * tree as disabled (`aria-disabled`) but takes no focus: the arrow keys,
+ * typeahead, and the pointer highlight skip it, and activation is blocked.
* @default false
*/
isDisabled?: boolean;
@@ -223,7 +228,12 @@ export function DropdownMenuCheckboxItem({
endContent={endContent}
onClick={handleClick}
isDisabled={isDisabled}
- xstyle={[styles.root, isDisabled && styles.disabled, xstyle]}
+ xstyle={[
+ focusOutlineStyles.focusVisible,
+ styles.root,
+ isDisabled && styles.disabled,
+ xstyle,
+ ]}
{...mergeProps(themeProps('dropdown-menu-item', {size: menuSize}), {
className,
style,
diff --git a/packages/core/src/DropdownMenu/DropdownMenuForcedColors.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuForcedColors.test.tsx
new file mode 100644
index 0000000000..f7dc0fbd92
--- /dev/null
+++ b/packages/core/src/DropdownMenu/DropdownMenuForcedColors.test.tsx
@@ -0,0 +1,188 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuForcedColors.test.tsx
+ * @input vitest, @testing-library/react, DropdownMenu row components, the
+ * forced-colors CSS helper
+ * @output Asserts every focusable menu row draws the standard focus ring,
+ * inset by its own width, which forced colors keep
+ * @position Component-local; the real-engine frames live in
+ * __tests__/DropdownMenuAudit.a11y.chromium.spec.ts
+ *
+ * A menu row shows focus — the one highlight the keyboard and the mouse both
+ * drive — with a translucent overlay background. Forced colors replace that
+ * background with the page color, so a focused row would look like its
+ * neighbours and a keyboard user in a high-contrast mode could not tell which
+ * row Enter will activate (WCAG 2.4.7). Every row therefore draws the
+ * standard focus ring after keyboard input, inset by the ring's own width, in
+ * every color mode; forced colors keep an outline where they drop the
+ * overlay, and leave labels, icons, and end content under user-agent control.
+ * jsdom cannot render forced colors, so these assert the compiled rules each
+ * focusable row carries; the Chromium spec observes the rendered result.
+ */
+
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {getAllInjectedCss} from '../__tests__/forcedColors';
+import {DropdownMenu} from './DropdownMenu';
+import {DropdownMenuItem} from './DropdownMenuItem';
+import {DropdownMenuCheckboxItem} from './DropdownMenuCheckboxItem';
+import {DropdownMenuRadioGroup} from './DropdownMenuRadioGroup';
+import {DropdownMenuRadioItem} from './DropdownMenuRadioItem';
+import {DropdownMenuSubMenu} from './DropdownMenuSubMenu';
+
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ const originalMatches = HTMLElement.prototype.matches;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+/**
+ * The declarations the row's own classes apply, joined into one string: on
+ * `:focus-visible` (the ring), or unconditionally.
+ */
+function rowDeclarations(
+ row: HTMLElement,
+ condition: ':focus-visible' | '' = ':focus-visible',
+): string {
+ const css = getAllInjectedCss();
+ const declarations: string[] = [];
+ for (const className of Array.from(row.classList)) {
+ const escaped = className.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const pattern = new RegExp(
+ condition === ''
+ ? // StyleX may raise a rule's priority with `:not(#\#)` suffixes.
+ `\\.${escaped}(?::not\\(#\\\\#\\))*\\s*\\{([^}]*)\\}`
+ : `\\.${escaped}:focus-visible[^{,]*\\{([^}]*)\\}`,
+ 'g',
+ );
+ for (const match of css.matchAll(pattern)) {
+ declarations.push(match[1] ?? '');
+ }
+ }
+ return declarations.join(' ');
+}
+
+function expectSystemFocusOutline(row: HTMLElement) {
+ const declarations = rowDeclarations(row);
+ expect(declarations).toContain('outline-width: var(--focus-outline-width)');
+ expect(declarations).toContain('outline-style: var(--focus-outline-style)');
+ expect(declarations).toContain('outline-color: var(--focus-outline-color)');
+ expect(declarations).not.toContain('background-color: highlight');
+ expect(declarations).not.toContain('color: highlighttext');
+ // Inset by the ring's own width, from the token rather than a fixed length.
+ expect(rowDeclarations(row, '').replace(/\s+/g, '')).toContain(
+ 'outline-offset:calc(-1*var(--focus-outline-width))',
+ );
+}
+
+async function openMenu() {
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+}
+
+describe('a focused menu row draws the standard focus ring, kept under forced colors (WCAG 2.4.7)', () => {
+ it('an action row paints the outline on focus', async () => {
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem label="Edit" onClick={() => {}} />
+ </DropdownMenu>,
+ );
+ await openMenu();
+ expectSystemFocusOutline(
+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),
+ );
+ });
+
+ it('a data-mode row paints the same outline', async () => {
+ render(
+ <DropdownMenu button={{label: 'Actions'}} items={[{label: 'Edit'}]} />,
+ );
+ await openMenu();
+ expectSystemFocusOutline(
+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),
+ );
+ });
+
+ it('a destructive row keeps a visible outline without forcing its content colors', async () => {
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem
+ label="Delete"
+ variant="destructive"
+ onClick={() => {}}
+ />
+ </DropdownMenu>,
+ );
+ await openMenu();
+ expectSystemFocusOutline(
+ screen.getByRole('menuitem', {name: 'Delete', hidden: true}),
+ );
+ });
+
+ it('a checkbox row paints the outline on focus', async () => {
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuCheckboxItem label="Show archived" value={false} />
+ </DropdownMenu>,
+ );
+ await openMenu();
+ expectSystemFocusOutline(
+ screen.getByRole('menuitemcheckbox', {
+ name: /Show archived/,
+ hidden: true,
+ }),
+ );
+ });
+
+ it('a radio row paints the outline on focus', async () => {
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuRadioGroup
+ value="newest"
+ onChange={() => {}}
+ label="Sort by">
+ <DropdownMenuRadioItem value="newest" label="Newest" />
+ </DropdownMenuRadioGroup>
+ </DropdownMenu>,
+ );
+ await openMenu();
+ expectSystemFocusOutline(
+ screen.getByRole('menuitemradio', {name: /Newest/, hidden: true}),
+ );
+ });
+
+ it('a sub-menu row paints the outline on focus', async () => {
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuSubMenu label="Share" presentation="flyout">
+ <DropdownMenuItem label="Copy link" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await openMenu();
+ expectSystemFocusOutline(
+ screen.getByRole('menuitem', {name: /Share/, hidden: true}),
+ );
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
index 89bef86c2e..72980e4bc5 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
@@ -43,10 +43,12 @@ import {
spacingVars,
typographyVars,
typeScaleVars,
+ focusVars,
} from '../theme/tokens.stylex';
import {composeEventHandlers, mergeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {useDropdownMenuContext} from './DropdownMenuContext';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {focusMenuItemOnHover} from './menuItemHover';
import {isModifiedClick} from './menuItemRoles';
import {themeProps} from '../utils/themeProps';
@@ -81,7 +83,10 @@ const menuItemStyles = stylex.create({
':is(:disabled,[aria-disabled="true"])': 'default',
},
textAlign: 'start',
- outline: 'none',
+ // Rows show focus with a translucent overlay, which forced colors replace
+ // with the page color. The standard focus ring (focusOutlineStyles), drawn
+ // inside the row by its own width, marks the focused row in every mode.
+ outlineOffset: `calc(-1 * ${focusVars['--focus-outline-width']})`,
},
disabled: {
opacity: 0.5,
@@ -296,6 +301,7 @@ export function DropdownMenuItem({
draggable={href != null ? false : undefined}
isDisabled={isDisabled}
xstyle={[
+ focusOutlineStyles.focusVisible,
menuItemStyles.root,
itemSizeStyles[menuSize],
isDestructive && menuItemStyles.destructive,
diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs
index ef2eaa06b6..483a522f7f 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs
@@ -52,7 +52,7 @@ export const docs = {
type: 'boolean',
default: 'false',
description:
- 'Whether this individual radio item is disabled. Disabled items expose aria-disabled, block selection, and are currently skipped by DropdownMenu arrow-key navigation.',
+ 'Whether this individual radio item is disabled. A disabled item stays in the accessibility tree as disabled (aria-disabled) but takes no focus: the arrow keys, typeahead, and the pointer highlight skip it, and selection is blocked.',
},
{
name: 'endContent',
@@ -97,7 +97,7 @@ export const docsDense = {
description: 'secondary text below label',
icon: 'icon before label',
isDisabled:
- 'disabled; aria-disabled, blocks selection, skipped by arrow keys',
+ 'disabled (aria-disabled); skipped by arrows/typeahead, not focusable',
endContent: 'content after label+description',
ref: 'forwarded to the row root (the role="menuitemradio" element)',
},
diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
index 57f2125886..b543714f0c 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
@@ -33,8 +33,9 @@ import {renderIconSlot, type IconType} from '../Icon';
import {useIndicator} from '../Indicator';
import {Item} from '../Item';
import {useDropdownMenuContext} from './DropdownMenuContext';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {focusMenuItemOnHover} from './menuItemHover';
-import {colorVars, spacingVars} from '../theme/tokens.stylex';
+import {colorVars, focusVars, spacingVars} from '../theme/tokens.stylex';
import {composeEventHandlers, mergeProps, themeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {useDropdownMenuRadioGroupContext} from './DropdownMenuContext';
@@ -52,7 +53,10 @@ const styles = stylex.create({
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
- outline: 'none',
+ // Rows show focus with a translucent overlay, which forced colors replace
+ // with the page color. The standard focus ring (focusOutlineStyles), drawn
+ // inside the row by its own width, marks the focused row in every mode.
+ outlineOffset: `calc(-1 * ${focusVars['--focus-outline-width']})`,
},
disabled: {
opacity: 0.5,
@@ -103,9 +107,10 @@ export interface DropdownMenuRadioItemProps extends Omit<
*/
icon?: ReactNode | IconType;
/**
- * Whether this individual radio item is disabled. Disabled items expose
- * `aria-disabled`, block selection, and are currently skipped by
- * DropdownMenu arrow-key navigation.
+ * Whether this individual radio item is disabled. A disabled item stays in
+ * the accessibility tree as disabled (`aria-disabled`) but takes no focus:
+ * the arrow keys, typeahead, and the pointer highlight skip it, and
+ * selection is blocked.
* @default false
*/
isDisabled?: boolean;
@@ -210,7 +215,12 @@ export function DropdownMenuRadioItem({
endContent={endContent}
onClick={handleClick}
isDisabled={isDisabled}
- xstyle={[styles.root, isDisabled && styles.disabled, xstyle]}
+ xstyle={[
+ focusOutlineStyles.focusVisible,
+ styles.root,
+ isDisabled && styles.disabled,
+ xstyle,
+ ]}
{...mergeProps(themeProps('dropdown-menu-item', {size: menuSize}), {
className,
style,
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
index 52fa94314d..74079aedef 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
@@ -89,6 +89,7 @@ import {
shadowVars,
typographyVars,
typeScaleVars,
+ focusVars,
} from '../theme/tokens.stylex';
import {
composeEventHandlers,
@@ -148,7 +149,10 @@ const triggerStyles = stylex.create({
':is(:disabled,[aria-disabled="true"])': 'default',
},
textAlign: 'start',
- outline: 'none',
+ // Rows show focus with a translucent overlay, which forced colors replace
+ // with the page color. The standard focus ring (focusOutlineStyles), drawn
+ // inside the row by its own width, marks the focused row in every mode.
+ outlineOffset: `calc(-1 * ${focusVars['--focus-outline-width']})`,
},
// While the flyout is open, keep the trigger visibly active so the open
// branch reads as the current path even when focus has moved into the child.
@@ -1144,7 +1148,7 @@ export function DropdownMenuSubMenu(
? // The flyout's frame paints its surface, so the menu target rides
// on it; a drilled-in view sits inside the root's surface.
mergeProps(
- themeProps('dropdown-menu'),
+ themeProps('dropdown-menu', {presentation: 'popover'}),
stylex.props(regionStyles.frame, regionStyles.flyoutSurface),
)
: stylex.props(
@@ -1231,6 +1235,7 @@ export function DropdownMenuSubMenu(
onKeyDown={composeEventHandlers(handleTriggerKeyDown, onKeyDown)}
isDisabled={isDisabled}
xstyle={[
+ focusOutlineStyles.focusVisible,
triggerStyles.root,
triggerSizeStyles[menuSize],
isOpen && triggerStyles.open,
@@ -1361,7 +1366,7 @@ export function DropdownMenuSubMenu(
data-testid={menuDataTestId}
{...menuPress.menuProps}
{...mergeProps(
- themeProps('dropdown-menu'),
+ themeProps('dropdown-menu', {presentation: 'popover'}),
stylex.props(
flyoutStyles.menu,
hasOverflow
diff --git a/packages/core/src/DropdownMenu/DropdownMenuThemeReflection.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuThemeReflection.test.tsx
new file mode 100644
index 0000000000..432ab6a299
--- /dev/null
+++ b/packages/core/src/DropdownMenu/DropdownMenuThemeReflection.test.tsx
@@ -0,0 +1,124 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuThemeReflection.test.tsx
+ * @input vitest, @testing-library/react, DropdownMenu
+ * @output Asserts the `dropdown-menu` target reflects its documented
+ * `presentation` capability on both menu surfaces
+ * @position Component-local theming-reach test
+ *
+ * `DropdownMenu.doc.mjs` documents `presentation` as a visual prop of the
+ * `dropdown-menu` target, so a theme can write `presentation:popover` or
+ * `presentation:bottom-sheet` rules (architecture:component-theming-surface
+ * INV6). Each surface must carry the attribute those rules select on.
+ */
+
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {DropdownMenu} from './DropdownMenu';
+import {DropdownMenuItem} from './DropdownMenuItem';
+import {DropdownMenuSubMenu} from './DropdownMenuSubMenu';
+
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ const originalMatches = HTMLElement.prototype.matches;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+describe('dropdown-menu target presentation reflection', () => {
+ it('the anchored menu reflects presentation="popover"', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem label="Edit" onClick={() => {}} />
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const menu = screen.getByRole('menu', {hidden: true});
+ expect(menu).toHaveClass('astryx-dropdown-menu');
+ expect(menu).toHaveAttribute('data-presentation', 'popover');
+ });
+
+ it('a data-mode menu resolved to the popover reflects it too', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ presentation="popover"
+ items={[{label: 'Edit'}]}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ expect(screen.getByRole('menu', {hidden: true})).toHaveAttribute(
+ 'data-presentation',
+ 'popover',
+ );
+ });
+});
+
+describe('dropdown-menu target presentation reflection: nested flyout', () => {
+ it('a sub-menu flyout, another pointer menu surface, reflects it too', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuSubMenu label="Share" presentation="flyout">
+ <DropdownMenuItem label="Copy link" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ await user.click(
+ screen.getByRole('menuitem', {name: /Share/, hidden: true}),
+ );
+ const menus = screen.getAllByRole('menu', {hidden: true});
+ expect(menus).toHaveLength(2);
+ for (const menu of menus) {
+ expect(menu).toHaveClass('astryx-dropdown-menu');
+ expect(menu).toHaveAttribute('data-presentation', 'popover');
+ }
+ });
+});
+
+describe('mutually exclusive trigger props', () => {
+ it('the dev warning names the props a caller can actually pass', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ More
+ </button>
+ )}>
+ <DropdownMenuItem label="Profile" onClick={() => {}} />
+ </DropdownMenu>,
+ );
+ const message = warn.mock.calls.map(call => String(call[0])).join('\n');
+ expect(message).toContain('`renderTrigger`');
+ expect(message).not.toMatch(/`trigger`/);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuAudit.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuAudit.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..62f8a1c27d
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuAudit.a11y.chromium.spec.ts
@@ -0,0 +1,1100 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y audit DropdownMenu
+
+/**
+ * @file DropdownMenuAudit.a11y.chromium.spec.ts
+ * @input Component-owned `Core/DropdownMenu` Storybook fixtures, the exact-head
+ * build stamp, and real keyboard, mouse, and touch-emulated input
+ * @output Chromium screenshots plus fail-closed sensor receipts, a
+ * state-visual matrix, and a rendered contrast-pair matrix
+ * @position Browser evidence for the DropdownMenu component audit; it also
+ * observes the forced-colors focus outline every menu row paints
+ *
+ * Each frame drives an existing story into one state — closed, keyboard open,
+ * pointer open, hovered and pressed rows, disabled, destructive, selectable,
+ * nested, sheet, overflow, header and footer, narrow and coarse — and records
+ * what the page actually rendered: build, story, theme, mode, direction,
+ * viewport and media, the focused element, geometry, and errors. The receipts
+ * are evidence; the spec fails only when a frame could not be taken truthfully
+ * or when the forced-colors focus outline is missing.
+ */
+
+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 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('test-results/dropdown-menu-audit-evidence');
+const WIDE = {width: 1024, height: 720};
+const PHONE = {width: 390, height: 720};
+const NARROW = {width: 320, height: 640};
+const TRIGGER = '#storybook-root button[aria-haspopup]';
+
+type Theme = 'neutral' | 'butter' | 'probe';
+type Mode = 'light' | 'dark';
+type Direction = 'ltr' | 'rtl';
+
+/** How the frame drives the story into its state. */
+type Drive =
+ | 'closed'
+ | 'keyboard-open'
+ | 'pointer-open'
+ | 'hover-second-row'
+ | 'press-second-row'
+ | 'keyboard-last-row'
+ | 'keyboard-submenu'
+ | 'story-play';
+
+interface Case {
+ state: string;
+ storyId: string;
+ drive: Drive;
+ theme: Theme;
+ mode: Mode;
+ direction: Direction;
+ viewport: {width: number; height: number};
+ pointer?: 'coarse';
+ forcedColors?: 'after' | 'before-control';
+ /** The approved state representation this frame claims. */
+ representation: string;
+}
+
+function c(
+ state: string,
+ storyId: string,
+ drive: Drive,
+ representation: string,
+ options: Partial<Omit<Case, 'state' | 'storyId' | 'drive'>> = {},
+): Case {
+ return {
+ state,
+ storyId: `core-dropdownmenu--${storyId}`,
+ drive,
+ theme: 'neutral',
+ mode: 'light',
+ direction: 'ltr',
+ viewport: WIDE,
+ representation,
+ ...options,
+ };
+}
+
+const OVERLAY =
+ 'Hovered/Focused — Overlay style (alpha tint over the row base)';
+
+const CASES: Case[] = [
+ c('trigger-rest', 'default', 'closed', 'Button rest (delegated)'),
+ c('trigger-rest-dark', 'default', 'closed', 'Button rest (delegated)', {
+ mode: 'dark',
+ }),
+ c('keyboard-open', 'default', 'keyboard-open', OVERLAY),
+ c('keyboard-open-dark', 'default', 'keyboard-open', OVERLAY, {mode: 'dark'}),
+ c('keyboard-open-butter', 'default', 'keyboard-open', OVERLAY, {
+ theme: 'butter',
+ }),
+ c('keyboard-open-butter-dark', 'default', 'keyboard-open', OVERLAY, {
+ theme: 'butter',
+ mode: 'dark',
+ }),
+ c('keyboard-open-probe', 'default', 'keyboard-open', OVERLAY, {
+ theme: 'probe',
+ }),
+ c('keyboard-open-rtl', 'with-icons', 'keyboard-open', OVERLAY, {
+ direction: 'rtl',
+ }),
+ c(
+ 'pointer-open',
+ 'default',
+ 'pointer-open',
+ 'Pointer open: menu container focused, no row highlighted',
+ ),
+ c('hover-row', 'default', 'hover-second-row', OVERLAY),
+ c('hover-row-dark', 'default', 'hover-second-row', OVERLAY, {mode: 'dark'}),
+ c(
+ 'pressed-row',
+ 'default',
+ 'press-second-row',
+ 'Pressed — overlay (row archetype: no scale)',
+ ),
+ c(
+ 'disabled-row',
+ 'with-disabled-items',
+ 'keyboard-last-row',
+ 'Disabled — aria-disabled row, muted, skipped by focus',
+ ),
+ c(
+ 'disabled-row-dark',
+ 'with-disabled-items',
+ 'keyboard-last-row',
+ 'Disabled — aria-disabled row, muted, skipped by focus',
+ {mode: 'dark'},
+ ),
+ c(
+ 'destructive-row',
+ 'destructive-item',
+ 'keyboard-last-row',
+ `${OVERLAY}; destructive text in the error color`,
+ ),
+ c(
+ 'destructive-row-dark',
+ 'destructive-item',
+ 'keyboard-last-row',
+ `${OVERLAY}; destructive text in the error color`,
+ {mode: 'dark'},
+ ),
+ c(
+ 'checkbox-rows',
+ 'lab-checkbox-items',
+ // The story's play opens its own menu; Enter on the trigger would close it.
+ 'story-play',
+ 'Selected — aria-checked backs the shared checkbox indicator',
+ ),
+ c(
+ 'checkbox-rows-dark',
+ 'lab-checkbox-items',
+ // The story's play opens its own menu; Enter on the trigger would close it.
+ 'story-play',
+ 'Selected — aria-checked backs the shared checkbox indicator',
+ {mode: 'dark'},
+ ),
+ c(
+ 'radio-rows',
+ 'lab-radio-group',
+ 'keyboard-open',
+ 'Selected — aria-checked backs the shared radio indicator',
+ ),
+ c(
+ 'submenu-open',
+ 'submenu',
+ 'keyboard-submenu',
+ 'Open branch keeps the overlay on its row; flyout focused',
+ ),
+ c(
+ 'submenu-open-dark',
+ 'submenu',
+ 'keyboard-submenu',
+ 'Open branch keeps the overlay on its row; flyout focused',
+ {mode: 'dark'},
+ ),
+ c(
+ 'submenu-open-rtl',
+ 'submenu',
+ 'keyboard-submenu',
+ 'Open branch keeps the overlay on its row; flyout focused',
+ {direction: 'rtl'},
+ ),
+ c(
+ 'overflow-scroll',
+ 'tall-content-overflow',
+ 'story-play',
+ 'Overflow — capped menu scrolls internally',
+ {viewport: PHONE},
+ ),
+ c(
+ 'bottom-sheet',
+ 'action-sheet-presentation',
+ 'story-play',
+ 'Touch sheet frame delegated to BottomSheet',
+ {viewport: PHONE},
+ ),
+ c(
+ 'bottom-sheet-dark',
+ 'action-sheet-presentation',
+ 'story-play',
+ 'Touch sheet frame delegated to BottomSheet',
+ {viewport: PHONE, mode: 'dark'},
+ ),
+ c(
+ 'adaptive-narrow-coarse',
+ 'adaptive-action-presentation',
+ 'story-play',
+ 'Adaptive resolves to the touch sheet on a compact coarse layout',
+ {viewport: NARROW, pointer: 'coarse'},
+ ),
+ c(
+ 'popover-narrow',
+ 'default',
+ 'keyboard-open',
+ 'Anchored menu within a 320px viewport',
+ {viewport: NARROW},
+ ),
+ c(
+ 'header-footer',
+ 'header-and-footer',
+ 'pointer-open',
+ 'Header and footer regions beside the menu element',
+ ),
+ c(
+ 'forced-colors-focus-icon-end-content',
+ 'mode-parity',
+ 'keyboard-open',
+ 'Forced colors: focused icon/end-content row has a Highlight outline',
+ {forcedColors: 'after'},
+ ),
+ c(
+ 'forced-colors-focus-icon-end-content-dark',
+ 'mode-parity',
+ 'keyboard-open',
+ 'Forced colors: focused icon/end-content row has a Highlight outline',
+ {forcedColors: 'after', mode: 'dark'},
+ ),
+ c(
+ 'forced-colors-focus-destructive',
+ 'mode-parity',
+ 'keyboard-last-row',
+ 'Forced colors: focused destructive icon row has a Highlight outline',
+ {forcedColors: 'after'},
+ ),
+ c(
+ 'forced-colors-focus-before-control',
+ 'mode-parity',
+ 'keyboard-open',
+ 'Helper-isolated control: forced Canvas focus paint with no outline',
+ {forcedColors: 'before-control'},
+ ),
+];
+
+const frames: Record<string, unknown>[] = [];
+const stateVisualMatrix: Record<string, unknown>[] = [];
+const contrastPairMatrix: Record<string, unknown>[] = [];
+let storybook: StaticServer;
+let checkoutSha: string;
+let storybookSha: string;
+let browserVersion = 'unknown';
+
+test.beforeAll(async () => {
+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ }).trim();
+ const expectedHead = process.env.ASTRYX_HEAD_SHA;
+ if (expectedHead && expectedHead !== checkoutSha) {
+ throw new Error('The audited checkout does not match the PR head');
+ }
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ const stamp = await fetch(`${storybook.origin}/astryx-build-sha.txt`);
+ if (!stamp.ok) {
+ throw new Error(
+ `The Storybook build has no source stamp (${stamp.status})`,
+ );
+ }
+ storybookSha = (await stamp.text()).trim();
+ if (storybookSha !== checkoutSha) {
+ throw new Error(
+ 'The served Storybook build does not match the audited checkout',
+ );
+ }
+ fs.mkdirSync(OUTPUT, {recursive: true});
+});
+
+test.afterAll(async () => {
+ if (checkoutSha && storybookSha) {
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify(
+ {
+ version: 1,
+ component: 'core/DropdownMenu',
+ headSha: checkoutSha,
+ storybookSha,
+ browser: browserVersion,
+ frames,
+ stateVisualMatrix,
+ contrastPairMatrix,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ }
+ await storybook?.close();
+});
+
+async function nextFrames(page: Page) {
+ await page.evaluate(
+ async () =>
+ new Promise<void>(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ ),
+ );
+}
+
+/** The role and accessible-ish name of the focused element, read structurally. */
+async function focusedSummary(page: Page) {
+ return page.evaluate(() => {
+ const active = document.activeElement as HTMLElement | null;
+ if (active == null || active === document.body) {
+ return null;
+ }
+ return {
+ role: active.getAttribute('role') ?? active.tagName.toLowerCase(),
+ className: [...active.classList]
+ .filter(name => name.startsWith('astryx-'))
+ .join(' '),
+ label:
+ active.getAttribute('aria-label') ??
+ (active.innerText ?? '').trim().split('\n')[0] ??
+ '',
+ ariaChecked: active.getAttribute('aria-checked'),
+ ariaExpanded: active.getAttribute('aria-expanded'),
+ };
+ });
+}
+
+async function drive(page: Page, scenario: Case) {
+ const trigger = page.locator(TRIGGER).first();
+ if (scenario.drive === 'story-play') {
+ await page
+ .locator('.astryx-dropdown-menu')
+ .first()
+ .waitFor({state: 'visible'});
+ return;
+ }
+ await trigger.waitFor();
+ if (scenario.drive === 'closed') {
+ return;
+ }
+ if (scenario.drive === 'pointer-open') {
+ await trigger.click();
+ await page.getByRole('menu').first().waitFor({state: 'visible'});
+ return;
+ }
+ // Keyboard-driven opens: focus the trigger, then Enter.
+ await trigger.focus();
+ await page.keyboard.press('Enter');
+ const menu = page.getByRole('menu').first();
+ await menu.waitFor({state: 'visible'});
+ await page.waitForFunction(() =>
+ (document.activeElement?.getAttribute('role') ?? '').startsWith('menuitem'),
+ );
+ if (scenario.drive === 'keyboard-last-row') {
+ await page.keyboard.press('End');
+ } else if (scenario.drive === 'keyboard-submenu') {
+ await page.keyboard.press('ArrowDown');
+ await page.keyboard.press(
+ scenario.direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight',
+ );
+ // `:popover-open` belongs to the flyout's layer host, not to its inner
+ // role="menu" element, so wait on what a user sees instead: a second
+ // visible menu, with focus on a row inside it. Bounded, so a flyout that
+ // never opens fails this frame quickly instead of stalling the chunk.
+ await page.waitForFunction(
+ () => {
+ const menus = [
+ ...document.querySelectorAll<HTMLElement>('[role="menu"]'),
+ ].filter(menu => menu.getBoundingClientRect().height > 0);
+ const active = document.activeElement;
+ return (
+ menus.length > 1 &&
+ active?.getAttribute('role') === 'menuitem' &&
+ active.closest('[role="menu"]') === menus[1]
+ );
+ },
+ undefined,
+ {timeout: 5000},
+ );
+ } else if (
+ scenario.drive === 'hover-second-row' ||
+ scenario.drive === 'press-second-row'
+ ) {
+ const row = menu.locator('[role^="menuitem"]').nth(1);
+ const box = await row.boundingBox();
+ if (box == null) {
+ throw new Error(`${scenario.state}: second row has no box`);
+ }
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, {
+ steps: 4,
+ });
+ if (scenario.drive === 'press-second-row') {
+ await page.mouse.down();
+ }
+ }
+}
+
+/** The computed system-color focus indicator on the active menu row. */
+async function forcedColorsFocusIndicator(page: Page) {
+ return page.locator(':focus').evaluate(node => {
+ const probe = document.createElement('span');
+ probe.style.color = 'Highlight';
+ document.body.append(probe);
+ const expectedHighlight = getComputedStyle(probe).color;
+ probe.remove();
+ const style = getComputedStyle(node);
+ return {
+ expectedHighlight,
+ color: style.outlineColor,
+ style: style.outlineStyle,
+ width: Number.parseFloat(style.outlineWidth),
+ offset: style.outlineOffset,
+ };
+ });
+}
+
+type Observed = {
+ presentation: string | null;
+ menuCount: number;
+ rowsSummary: {
+ role: string | null;
+ label: string;
+ checked: string | null;
+ disabled: boolean;
+ variant: string | null;
+ }[];
+ focusedRowIndex: number;
+ focusedItem: {role: string | null; label: string; menuIndex: number} | null;
+ activeIsMenu: boolean;
+ menuScroll: {
+ scrollHeight: number;
+ clientHeight: number;
+ overflowY: string;
+ } | null;
+ regionControls: {inputs: string[]; buttons: string[]};
+ triggerExpanded: string | null;
+ dialogCount: number;
+};
+
+/**
+ * Each frame proves the state it claims, not merely that a menu exists. A
+ * frame whose claim this cannot check fails rather than passing silently.
+ */
+function assertClaimedState(
+ scenario: Case,
+ observed: Observed,
+ box: {x: number; y: number; width: number; height: number},
+) {
+ const {state} = scenario;
+ const rows = observed.rowsSummary;
+ const focusedRow = rows[observed.focusedRowIndex];
+ const expectAnchored = () => {
+ expect(observed.presentation, `${state}: anchored menu`).toBe('popover');
+ };
+ const expectSheet = () => {
+ expect(observed.presentation, `${state}: bottom sheet`).toBe(
+ 'bottom-sheet',
+ );
+ expect(observed.dialogCount, `${state}: sheet dialog`).toBeGreaterThan(0);
+ };
+
+ if (state.startsWith('trigger-rest')) {
+ expect(observed.menuCount, `${state}: no menu open`).toBe(0);
+ expect(observed.triggerExpanded).toBe('false');
+ return;
+ }
+ if (state.startsWith('forced-colors-focus')) {
+ expectAnchored();
+ expect(observed.triggerExpanded).toBe('true');
+ const expectedIndex =
+ scenario.drive === 'keyboard-last-row' ? rows.length - 1 : 0;
+ expect(observed.focusedRowIndex, `${state}: expected row focused`).toBe(
+ expectedIndex,
+ );
+ expect(focusedRow?.disabled).toBe(false);
+ return;
+ }
+ if (state.startsWith('keyboard-open') || state === 'popover-narrow') {
+ expectAnchored();
+ expect(observed.triggerExpanded).toBe('true');
+ expect(observed.focusedRowIndex, `${state}: first row focused`).toBe(0);
+ expect(focusedRow?.disabled).toBe(false);
+ if (state === 'popover-narrow') {
+ expect(box.x).toBeGreaterThanOrEqual(0);
+ expect(box.x + box.width).toBeLessThanOrEqual(
+ scenario.viewport.width + 0.5,
+ );
+ }
+ return;
+ }
+ if (state === 'pointer-open' || state === 'header-footer') {
+ expectAnchored();
+ expect(observed.activeIsMenu, `${state}: the menu itself is focused`).toBe(
+ true,
+ );
+ expect(observed.focusedRowIndex, `${state}: no row focused`).toBe(-1);
+ if (state === 'header-footer') {
+ expect(observed.regionControls.inputs).toContain('Filter labels');
+ expect(observed.regionControls.buttons).toContain('Create label');
+ }
+ return;
+ }
+ if (state.startsWith('hover-row') || state === 'pressed-row') {
+ expectAnchored();
+ expect(observed.focusedRowIndex, `${state}: second row focused`).toBe(1);
+ return;
+ }
+ if (state.startsWith('disabled-row')) {
+ expectAnchored();
+ const disabledIndexes = rows.flatMap((row, index) =>
+ row.disabled ? [index] : [],
+ );
+ const lastEnabled = rows.reduce(
+ (last, row, index) => (row.disabled ? last : index),
+ -1,
+ );
+ expect(disabledIndexes.length, `${state}: a disabled row`).toBeGreaterThan(
+ 0,
+ );
+ // End lands on the last enabled row: the trailing disabled row is skipped.
+ expect(lastEnabled).toBeLessThan(rows.length - 1);
+ expect(observed.focusedRowIndex).toBe(lastEnabled);
+ expect(focusedRow?.disabled).toBe(false);
+ return;
+ }
+ if (state.startsWith('destructive-row')) {
+ expectAnchored();
+ expect(focusedRow?.variant, `${state}: destructive row focused`).toBe(
+ 'destructive',
+ );
+ return;
+ }
+ if (state.startsWith('checkbox-rows')) {
+ expectAnchored();
+ // Show archived, Show drafts, Sync folders, and the disabled managed row.
+ expect(rows.map(row => row.role)).toEqual([
+ 'menuitemcheckbox',
+ 'menuitemcheckbox',
+ 'menuitemcheckbox',
+ 'menuitemcheckbox',
+ ]);
+ expect(rows.map(row => row.checked)).toEqual([
+ 'false',
+ 'true',
+ 'true',
+ 'true',
+ ]);
+ return;
+ }
+ if (state === 'radio-rows') {
+ expectAnchored();
+ expect(rows.map(row => row.role)).toEqual([
+ 'menuitemradio',
+ 'menuitemradio',
+ 'menuitemradio',
+ ]);
+ const checked = rows.filter(row => row.checked === 'true');
+ expect(checked.map(row => row.label)).toEqual(['Newest']);
+ return;
+ }
+ if (state.startsWith('submenu-open')) {
+ expectAnchored();
+ expect(observed.menuCount).toBeGreaterThan(1);
+ // Focus is on the flyout's first row, not anywhere in the root menu.
+ expect(observed.focusedItem, `${state}: a row is focused`).not.toBeNull();
+ expect(observed.focusedItem?.role).toBe('menuitem');
+ expect(observed.focusedItem?.label).toBe('Folder A');
+ expect(observed.focusedItem?.menuIndex, `${state}: in the flyout`).toBe(1);
+ expect(observed.focusedRowIndex, `${state}: not a root row`).toBe(-1);
+ return;
+ }
+ if (state === 'overflow-scroll') {
+ expectAnchored();
+ const scroll = observed.menuScroll;
+ expect(scroll, `${state}: menu measured`).not.toBeNull();
+ expect(scroll?.scrollHeight ?? 0).toBeGreaterThan(
+ (scroll?.clientHeight ?? 0) + 1,
+ );
+ expect(['auto', 'scroll']).toContain(scroll?.overflowY);
+ return;
+ }
+ if (state.startsWith('bottom-sheet') || state === 'adaptive-narrow-coarse') {
+ expectSheet();
+ return;
+ }
+ throw new Error(`${state}: no claimed-state assertion`);
+}
+
+async function capture(page: Page, scenario: Case) {
+ const pageErrors: string[] = [];
+ const onError = (error: Error) => pageErrors.push(String(error));
+ page.on('pageerror', onError);
+ try {
+ await page.emulateMedia({
+ reducedMotion: 'reduce',
+ forcedColors: scenario.forcedColors != null ? 'active' : 'none',
+ colorScheme: scenario.mode,
+ });
+ browserVersion = page.context().browser()?.version() ?? 'unknown';
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${scenario.storyId}&viewMode=story&globals=colorMode:${scenario.mode};astryxTheme:${scenario.theme};direction:${scenario.direction}`,
+ {waitUntil: 'load'},
+ );
+ await page.locator('#storybook-root').waitFor();
+ await holdMotionStill(page);
+ await page.evaluate(async () => document.fonts.ready);
+ await page.waitForFunction(
+ expected =>
+ document.documentElement.getAttribute('data-theme') === expected,
+ scenario.mode,
+ );
+ if (scenario.forcedColors === 'before-control') {
+ // Helper-isolated control, not a base build: restore the forced Canvas
+ // focus paint and remove the head outline, leaving the rest of the head
+ // build in place.
+ await page.addStyleTag({
+ content:
+ '[role^="menuitem"]:focus { background-color: rgb(0 0 0 / 0.06) !important; color: rgb(0 0 0) !important; outline: none !important; }',
+ });
+ }
+ await nextFrames(page);
+ await drive(page, scenario);
+ await nextFrames(page);
+
+ const subject = page.locator('.astryx-dropdown-menu').first();
+ const isOpen = scenario.drive !== 'closed';
+ const measureBox = async () =>
+ isOpen ? subject.boundingBox() : page.locator(TRIGGER).boundingBox();
+ const firstBox = await measureBox();
+ await nextFrames(page);
+ const box = await measureBox();
+ if (firstBox == null || box == null) {
+ throw new Error(`${scenario.state}: subject has no layout box`);
+ }
+ const geometryDelta = Math.max(
+ Math.abs(box.x - firstBox.x),
+ Math.abs(box.y - firstBox.y),
+ Math.abs(box.width - firstBox.width),
+ Math.abs(box.height - firstBox.height),
+ );
+
+ const observed = await page.evaluate(
+ ({open}) => {
+ type Color = {r: number; g: number; b: number; a: number};
+ const parseColor = (value: string): Color => {
+ const channels = value.match(/[\d.]+/g)?.map(Number);
+ if (!channels || channels.length < 3) {
+ return {r: 0, g: 0, b: 0, a: 0};
+ }
+ return {
+ r: channels[0] ?? 0,
+ g: channels[1] ?? 0,
+ b: channels[2] ?? 0,
+ a: channels[3] ?? 1,
+ };
+ };
+ const composite = (fg: Color, bg: Color): Color => {
+ const a = fg.a + bg.a * (1 - fg.a);
+ if (a === 0) {
+ return {r: 0, g: 0, b: 0, a: 0};
+ }
+ const mix = (f: number, b: number) =>
+ (f * fg.a + b * bg.a * (1 - fg.a)) / a;
+ return {
+ r: mix(fg.r, bg.r),
+ g: mix(fg.g, bg.g),
+ b: mix(fg.b, bg.b),
+ a,
+ };
+ };
+ const backdrop = (node: Element): Color => {
+ const layers: Color[] = [];
+ let current: Element | null = node;
+ while (current) {
+ const layer = parseColor(getComputedStyle(current).backgroundColor);
+ if (layer.a > 0) {
+ layers.push(layer);
+ }
+ if (layer.a >= 0.999) {
+ break;
+ }
+ current = current.parentElement;
+ }
+ const page = parseColor(
+ getComputedStyle(document.body).backgroundColor,
+ );
+ return layers
+ .reverse()
+ .reduce(
+ (bg, fg) => composite(fg, bg),
+ page.a > 0 ? page : {r: 255, g: 255, b: 255, a: 1},
+ );
+ };
+ const luminance = ({r, g, b}: Color) => {
+ const ch = (v: number) => {
+ const n = v / 255;
+ return n <= 0.04045 ? n / 12.92 : ((n + 0.055) / 1.055) ** 2.4;
+ };
+ return 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b);
+ };
+ const ratio = (x: Color, y: Color) => {
+ const a = luminance(x);
+ const b = luminance(y);
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
+ };
+ const fmt = ({r, g, b, a}: Color) =>
+ `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${a.toFixed(3)})`;
+ const pair = (node: Element | null) => {
+ if (node == null) {
+ return null;
+ }
+ const style = getComputedStyle(node);
+ const bg = backdrop(node);
+ const fg = composite(parseColor(style.color), bg);
+ return {
+ color: style.color,
+ renderedBackdrop: fmt(bg),
+ contrastRatio: Number(ratio(fg, bg).toFixed(2)),
+ fontSize: style.fontSize,
+ fontWeight: style.fontWeight,
+ };
+ };
+ const menus = [
+ ...document.querySelectorAll<HTMLElement>('.astryx-dropdown-menu'),
+ ].filter(el => el.getBoundingClientRect().height > 0);
+ const menu = menus[0] ?? null;
+ // The root menu's own rows: a flyout renders inside the root menu's
+ // DOM, so rows belonging to a nested menu are left out here.
+ const rows = menu
+ ? [
+ ...menu.querySelectorAll<HTMLElement>('[role^="menuitem"]'),
+ ].filter(row => row.closest('[role="menu"]') === menu)
+ : [];
+ const active = document.activeElement as HTMLElement | null;
+ const focusedRow =
+ active != null &&
+ (active.getAttribute('role') ?? '').startsWith('menuitem')
+ ? active
+ : null;
+ const restRow =
+ rows.find(
+ row => row !== focusedRow && !row.matches('[aria-disabled="true"]'),
+ ) ?? null;
+ // The elements that own a row's visible text: the first text run is
+ // the label, a later run in another element is the description.
+ const textOwners = (row: Element | null): Element[] => {
+ if (row == null) {
+ return [];
+ }
+ const owners: Element[] = [];
+ const walker = document.createTreeWalker(row, NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const owner = node.parentElement;
+ if (
+ owner != null &&
+ (node.textContent ?? '').trim() !== '' &&
+ !owner.closest('[aria-hidden="true"]') &&
+ !owners.includes(owner)
+ ) {
+ owners.push(owner);
+ }
+ }
+ return owners;
+ };
+ const label = (row: Element | null) => textOwners(row)[0] ?? null;
+ const destructive = menu?.querySelector(
+ '.astryx-dropdown-menu-item[data-variant="destructive"]',
+ );
+ const describedRow = rows.find(row => textOwners(row).length > 1);
+ const description = describedRow ? textOwners(describedRow)[1] : null;
+ const heading = menu?.querySelector(
+ '.astryx-dropdown-menu-section-heading',
+ );
+ const focusStyle = focusedRow ? getComputedStyle(focusedRow) : null;
+ const isShown = (el: Element) => {
+ const rect = el.getBoundingClientRect();
+ return rect.width > 0 && rect.height > 0;
+ };
+ // Controls in the popover but outside the role="menu" element: the
+ // header and footer regions.
+ const host = menu?.closest('[popover]') ?? null;
+ const outside =
+ host != null && menu != null
+ ? [...host.querySelectorAll('input, button')].filter(
+ el => !menu.contains(el) && isShown(el),
+ )
+ : [];
+ const menuStyle = menu ? getComputedStyle(menu) : null;
+ return {
+ open,
+ rowsSummary: rows.map(row => ({
+ role: row.getAttribute('role'),
+ label: (label(row)?.textContent ?? '').trim(),
+ checked: row.getAttribute('aria-checked'),
+ disabled: row.getAttribute('aria-disabled') === 'true',
+ variant: row.getAttribute('data-variant'),
+ })),
+ focusedRowIndex: focusedRow ? rows.indexOf(focusedRow) : -1,
+ // The focused row wherever it is — root menu or a flyout — and the
+ // position of its own menu among the visible menus.
+ focusedItem: focusedRow
+ ? {
+ role: focusedRow.getAttribute('role'),
+ label: (label(focusedRow)?.textContent ?? '').trim(),
+ menuIndex: menus.indexOf(
+ focusedRow.closest<HTMLElement>(
+ '[role="menu"]',
+ ) as HTMLElement,
+ ),
+ }
+ : null,
+ activeIsMenu: menu != null && active === menu,
+ menuScroll:
+ menu && menuStyle
+ ? {
+ scrollHeight: menu.scrollHeight,
+ clientHeight: menu.clientHeight,
+ overflowY: menuStyle.overflowY,
+ }
+ : null,
+ regionControls: {
+ inputs: outside
+ .filter(el => el.matches('input'))
+ .map(el => el.getAttribute('placeholder') ?? ''),
+ buttons: outside
+ .filter(el => el.matches('button'))
+ .map(el => (el.textContent ?? '').trim()),
+ },
+ triggerExpanded:
+ document
+ .querySelector('#storybook-root button[aria-haspopup]')
+ ?.getAttribute('aria-expanded') ?? null,
+ dialogCount: [
+ ...document.querySelectorAll('[role="dialog"], dialog'),
+ ].filter(isShown).length,
+ menuCount: menus.length,
+ menuRole: menu?.getAttribute('role') ?? null,
+ presentation: menu?.getAttribute('data-presentation') ?? null,
+ menuDirection: menu ? getComputedStyle(menu).direction : null,
+ rowCount: rows.length,
+ disabledRows: rows.filter(row =>
+ row.matches('[aria-disabled="true"]'),
+ ).length,
+ focusedRowOutline: focusStyle
+ ? {
+ style: focusStyle.outlineStyle,
+ color: focusStyle.outlineColor,
+ width: focusStyle.outlineWidth,
+ }
+ : null,
+ focusedRowBackground: focusStyle?.backgroundColor ?? null,
+ pairs: {
+ restLabel: pair(label(restRow)),
+ focusedLabel: pair(label(focusedRow)),
+ destructiveLabel: pair(destructive ? label(destructive) : null),
+ description: pair(description ?? null),
+ sectionHeading: pair(heading ?? null),
+ },
+ };
+ },
+ {open: isOpen},
+ );
+
+ const environment = await page.evaluate(() => ({
+ theme: document
+ .querySelector('[data-astryx-theme]')
+ ?.getAttribute('data-astryx-theme'),
+ mode: document.documentElement.getAttribute('data-theme'),
+ documentDirection:
+ document.querySelector('[dir]')?.getAttribute('dir') ?? null,
+ fonts: document.fonts.status,
+ viewport: {width: innerWidth, height: innerHeight},
+ devicePixelRatio,
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ coarsePointer: matchMedia('(pointer: coarse)').matches,
+ hover: matchMedia('(hover: hover)').matches,
+ forcedColors: matchMedia('(forced-colors: active)').matches,
+ horizontalOverflow: document.documentElement.scrollWidth > innerWidth + 1,
+ storyError: [
+ ...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'
+ );
+ }),
+ }));
+ const focused = await focusedSummary(page);
+ const focusIndicator =
+ scenario.forcedColors != null
+ ? await forcedColorsFocusIndicator(page)
+ : null;
+
+ // Fail closed when the frame is not what it claims to be.
+ expect(environment.theme).toBe(scenario.theme);
+ expect(environment.mode).toBe(scenario.mode);
+ expect(environment.fonts).toBe('loaded');
+ expect(environment.viewport).toEqual(scenario.viewport);
+ expect(environment.reducedMotion).toBe(true);
+ expect(environment.coarsePointer).toBe(scenario.pointer === 'coarse');
+ expect(environment.forcedColors).toBe(scenario.forcedColors != null);
+ expect(environment.storyError).toBe(false);
+ expect(pageErrors).toEqual([]);
+ expect(geometryDelta).toBeLessThanOrEqual(0.5);
+ if (isOpen) {
+ expect(observed.menuCount).toBeGreaterThan(0);
+ expect(
+ observed.rowCount + (observed.presentation === 'bottom-sheet' ? 1 : 0),
+ ).toBeGreaterThan(0);
+ if (scenario.direction === 'rtl' && observed.menuDirection != null) {
+ expect(observed.menuDirection).toBe('rtl');
+ }
+ }
+ if (scenario.viewport.width <= NARROW.width) {
+ expect(environment.horizontalOverflow).toBe(false);
+ }
+ if (
+ scenario.drive === 'keyboard-open' ||
+ scenario.drive === 'keyboard-last-row'
+ ) {
+ expect(focused?.role ?? '').toMatch(/^menuitem/);
+ }
+ if (scenario.drive === 'keyboard-submenu') {
+ expect(observed.menuCount).toBeGreaterThan(1);
+ }
+ assertClaimedState(scenario, observed, box);
+ if (scenario.forcedColors === 'after') {
+ expect(focusIndicator?.style).toBe('solid');
+ expect(focusIndicator?.width ?? 0).toBeGreaterThanOrEqual(2);
+ // Inset by the ring's own width (the focus-outline-width token).
+ expect(focusIndicator?.offset).toBe(`-${focusIndicator?.width}px`);
+ expect(focusIndicator?.color).toBe(focusIndicator?.expectedHighlight);
+ }
+ if (scenario.forcedColors === 'before-control') {
+ // With `outline-style: none`, Chromium still computes the declared
+ // width, so the style alone says no outline paints.
+ expect(focusIndicator?.style).toBe('none');
+ }
+
+ const file = `DropdownMenu__${scenario.state}.png`;
+ const png = await page.screenshot({animations: 'disabled'});
+ expect(png.length).toBeGreaterThan(100);
+
+ const stateRow = {
+ stateCaptured: scenario.state,
+ screenshot: file,
+ approvedRepresentation: scenario.representation,
+ tokenSignature: {
+ focusedRowBackground: observed.focusedRowBackground,
+ focusedRowOutline: observed.focusedRowOutline,
+ presentation: observed.presentation,
+ },
+ };
+ const contrastRows = Object.entries(observed.pairs)
+ .filter(([, value]) => value != null)
+ .map(([part, value]) => ({
+ screenshot: file,
+ theme: scenario.theme,
+ mode: scenario.mode,
+ direction: scenario.direction,
+ forcedColors: scenario.forcedColors ?? null,
+ part,
+ meaningful: true,
+ foreground: value?.color,
+ renderedBackdrop: value?.renderedBackdrop,
+ ratio: value?.contrastRatio,
+ threshold: 4.5,
+ passed: (value?.contrastRatio ?? 0) >= 4.5,
+ }));
+ const receipt = {
+ expected: {
+ build: checkoutSha,
+ storyId: scenario.storyId,
+ drive: scenario.drive,
+ theme: scenario.theme,
+ mode: scenario.mode,
+ direction: scenario.direction,
+ pointer: scenario.pointer ?? 'fine',
+ forcedColors: scenario.forcedColors ?? 'none',
+ viewport: scenario.viewport,
+ },
+ observed: {
+ build: storybookSha,
+ storyId: scenario.storyId,
+ ...observed,
+ ...environment,
+ focused,
+ forcedColorsFocusIndicator: focusIndicator,
+ pageErrors: pageErrors.length,
+ geometry: box,
+ settledRender: {initial: firstBox, final: box, maxDelta: geometryDelta},
+ },
+ image: {
+ file,
+ sha256: createHash('sha256').update(png).digest('hex'),
+ width: png.readUInt32BE(16),
+ height: png.readUInt32BE(20),
+ },
+ stateVisualMatrix: [stateRow],
+ contrastPairMatrix: contrastRows,
+ browser: browserVersion,
+ passed: true,
+ };
+ fs.writeFileSync(path.join(OUTPUT, file), png);
+ fs.writeFileSync(
+ path.join(OUTPUT, `${file}.sensors.json`),
+ `${JSON.stringify(receipt, null, 2)}\n`,
+ );
+ frames.push({state: scenario.state, receipt: `${file}.sensors.json`});
+ stateVisualMatrix.push(stateRow);
+ contrastPairMatrix.push(...contrastRows);
+ if (scenario.drive === 'press-second-row') {
+ await page.mouse.up();
+ }
+ return observed;
+ } finally {
+ page.off('pageerror', onError);
+ }
+}
+
+// One frame takes about half a minute on the CI runner, so the frames run as
+// bounded serial chunks rather than one long test. They share one results map
+// and one manifest; the cross-frame checks run after the last chunk.
+const CHUNK_SIZE = 8;
+const CHUNKS = Array.from(
+ {length: Math.ceil(CASES.length / CHUNK_SIZE)},
+ (_, index) => CASES.slice(index * CHUNK_SIZE, (index + 1) * CHUNK_SIZE),
+);
+const results = new Map<string, Awaited<ReturnType<typeof capture>>>();
+
+test.describe.configure({mode: 'serial'});
+
+for (const [index, chunk] of CHUNKS.entries()) {
+ test(`captures DropdownMenu states ${index + 1}/${CHUNKS.length} with sensor receipts`, async ({
+ browser,
+ }: {
+ browser: Browser;
+ }) => {
+ test.setTimeout(10 * 60 * 1000);
+ for (const scenario of chunk) {
+ const context = await browser.newContext({
+ viewport: scenario.viewport,
+ deviceScaleFactor: 2,
+ hasTouch: scenario.pointer === 'coarse',
+ isMobile: scenario.pointer === 'coarse',
+ });
+ const page = await context.newPage();
+ try {
+ results.set(scenario.state, await capture(page, scenario));
+ } finally {
+ await context.close();
+ }
+ }
+ });
+}
+
+test('every frame was captured, and the frames agree across states', () => {
+ expect([...results.keys()]).toEqual(CASES.map(scenario => scenario.state));
+ // The anchored menu reflects its documented presentation capability.
+ expect(results.get('keyboard-open')?.presentation).toBe('popover');
+ expect(results.get('bottom-sheet')?.presentation).toBe('bottom-sheet');
+ // A non-default theme visibly reaches the menu rows.
+ const neutral = results.get('keyboard-open')?.pairs.focusedLabel;
+ const probe = results.get('keyboard-open-probe')?.pairs.focusedLabel;
+ expect(
+ neutral?.renderedBackdrop !== probe?.renderedBackdrop ||
+ neutral?.color !== probe?.color,
+ 'the probe theme must visibly reach the focused row',
+ ).toBe(true);
+});
diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.ts
index 358bb97621..e72d49f9b0 100644
--- a/packages/core/src/hooks/useListFocus.ts
+++ b/packages/core/src/hooks/useListFocus.ts
@@ -21,6 +21,7 @@
import {useCallback, useRef} from 'react';
import {isRtlElement} from './isRtlElement';
import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
+import {focusForLastInput} from '../utils/focusReturn';
/**
* Navigation orientation for a linear list.
@@ -134,6 +135,14 @@ export interface InternalListFocusOptions extends UseListFocusOptions {
* Unset (the default): no item holds the stop while every item is disabled.
*/
disabledTabStop?: (list: HTMLElement) => ReadonlyArray<HTMLElement>;
+ /**
+ * Moves focus with the focus the last input calls for
+ * (`architecture:interaction-modality` INV1): after a pointer press a
+ * focused item shows no keyboard ring, after a key press it does. For a list
+ * whose items draw the ring and that opens from a pointer, such as a context
+ * menu. Unset (the default): a plain `focus()`.
+ */
+ focusFollowsLastInput?: boolean;
}
/**
@@ -362,6 +371,7 @@ export function useInternalListFocus<T extends HTMLElement = HTMLElement>(
hasRovingTabIndex = false,
disabledTabStop,
hasCaretGuard = false,
+ focusFollowsLastInput = false,
} = options;
const listRef = useRef<T>(null);
@@ -531,9 +541,13 @@ export function useInternalListFocus<T extends HTMLElement = HTMLElement>(
setTabIndex(el, el === target ? 0 : -1);
}
}
- target.focus();
+ if (focusFollowsLastInput) {
+ focusForLastInput(target);
+ } else {
+ target.focus();
+ }
},
- [hasRovingTabIndex, setTabIndex],
+ [hasRovingTabIndex, setTabIndex, focusFollowsLastInput],
);
/**