Skip to content

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

TypeScript

fix(DropdownMenu): a popover with a header or footer is a modal dialog, and Tab wraps (#7515)

Cindy Zhangc2e7d8b4c3f0
diff --git a/.changeset/dropdown-menu-regions-dialog.md b/.changeset/dropdown-menu-regions-dialog.md
new file mode 100644
index 0000000000..745e0c208e
--- /dev/null
+++ b/.changeset/dropdown-menu-regions-dialog.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A `DropdownMenu` with `header` or `footer` is now exposed as a modal dialog around its menu, as the APG Dialog pattern requires. The popover is a named `role="dialog"` with `aria-modal` and the `role="menu"` inside it; the trigger says `aria-haspopup="dialog"` and its `aria-controls` names the popover holding the dialog. Tab and Shift+Tab wrap through the header, the menu and the footer instead of closing the menu at either end. Escape still closes and returns focus to the trigger. A menu without either prop is unchanged.
+
+@cixzhang
diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsx
index 3bfc0925ca..a4f32bb2d7 100644
--- a/apps/storybook/stories/DropdownMenu.stories.tsx
+++ b/apps/storybook/stories/DropdownMenu.stories.tsx
@@ -1470,8 +1470,8 @@ const LABELS = ['Bug', 'Feature', 'Documentation', 'Design', 'Performance'];
* A filter field above the rows and a "Create" button below them. Both sit in
* the popover beside the menu, never inside it: the menu holds only its rows,
* so it stays a valid menu to a screen reader, and the field and button keep
- * their own keys and presses. Tab walks field, menu, button; Tab past the
- * button or Shift+Tab before the field closes the menu.
+ * their own keys and presses. The popover is a modal dialog around the menu:
+ * Tab walks field, menu, button and wraps at either end; Escape closes.
*/
export const HeaderAndFooter: Story = {
render: () => {
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index 745eadc897..949d2c551a 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -231,13 +231,13 @@ export const docs = {
name: 'header',
type: 'ReactNode',
description:
- 'Content above the rows and outside the menu itself — a filter field, a toggle. A menu holds only its rows, so a control that is not a row goes here or in `footer`, never among the rows. It keeps its own keys and presses; Tab moves from it into the menu, and Shift+Tab before its first control closes the menu. The bottom sheet shows it above the actions.',
+ 'Content above the rows and outside the menu itself — a filter field, a toggle. A menu holds only its rows, so a control that is not a row goes here or in `footer`, never among the rows. It keeps its own keys and presses. With a header or footer the popover is a modal dialog around the menu: Tab and Shift+Tab move through the header, the menu and the footer and wrap at either end, and Escape closes. The bottom sheet shows it above the actions.',
},
{
name: 'footer',
type: 'ReactNode',
description:
- 'Content below the rows and outside the menu itself — a "Create" button. Tab from the menu moves into it, and Tab past its last control closes the menu. The bottom sheet shows it below the actions.',
+ 'Content below the rows and outside the menu itself — a "Create" button. Tab from the menu moves into it, and Tab past its last control wraps to the start of the dialog (see `header`). The bottom sheet shows it below the actions.',
},
{
name: 'placement',
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
index 18e3362d7b..2355e3db18 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md
+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
@@ -89,34 +89,34 @@ Consumer props, item shapes, subcomponents, and presentation policy remain
documented in `DropdownMenu.doc.mjs` and the subcomponent docs. Three component-local concepts are added, by DEC-2, DEC-3 and DEC-8; each
keeps its released default.
-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
-| ----------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -------- | ------------------------ | --------- | --------------------------------------------------- |
-| Menu height cap | `menuMaxHeight`: a number of pixels | Lifts the 300px cap for a menu that must fit its rows; the viewport still bounds it. | Pointer presentation | `300px` | `component:DropdownMenu` | stable | Ignored by the touch sheet. |
-| Trigger source | `button` (Button props) or `renderTrigger` (render prop) | Which control the menu hangs off. `trigger` receives `DropdownMenuTriggerProps` — the press model, keyboard opens, toggle click and ARIA wiring — and names the menu. | Both presentations | `button` | `component:DropdownMenu` | stable | Both given: `trigger` wins and a dev warning fires. |
-| Header and footer | `header`, `footer`: any React node | Content above and below the rows, beside the menu inside the same popover or sheet — never inside the `role="menu"` element. | Both presentations | none | `component:DropdownMenu` | stable | A false or empty value renders no region. |
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ----------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------- | -------- | ------------------------ | --------- | --------------------------------------------------- |
+| Menu height cap | `menuMaxHeight`: a number of pixels | Lifts the 300px cap for a menu that must fit its rows; the viewport still bounds it. | Pointer presentation | `300px` | `component:DropdownMenu` | stable | Ignored by the touch sheet. |
+| Trigger source | `button` (Button props) or `renderTrigger` (render prop) | Which control the menu hangs off. `trigger` receives `DropdownMenuTriggerProps` — the press model, keyboard opens, toggle click and ARIA wiring — and names the menu. | Both presentations | `button` | `component:DropdownMenu` | stable | Both given: `trigger` wins and a dev warning fires. |
+| Header and footer | `header`, `footer`: any React node | Content above and below the rows, beside the menu inside the same popover or sheet — never inside the `role="menu"` element. With either, the pointer popover is a modal dialog around the menu. | Both presentations | none | `component:DropdownMenu` | stable | A false or empty value renders no region. |
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
-| FR1 | Every current render contains a Trigger button. Pointer presentation renders a Pointer menu surface with pointer-owned rows and optional pointer headings, dividers, indicators, and nested flyouts. Touch presentation renders a Touch sheet frame containing a Touch menu surface, Touch heading, Touch action list, and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR2 | The six current local targets are `dropdown-menu`, `dropdown-menu-item`, `dropdown-menu-radio`, `dropdown-menu-section-heading`, `dropdown-menu-divider`, and `dropdown-menu-indicator-icon`; every target remains on its current painted element. | Current source, docs, and tests | Verified current inventory; no target change |
-| FR3 | Button owns the Trigger button, BottomSheet owns the Touch sheet frame, List owns the Touch action list and Touch action rows, Indicator owns checkbox chrome, and Icon owns ordinary rendered icons. | Current source and owner docs | Verified current delegation; no ownership change |
-| FR4 | The same `dropdown-menu` target reaches the alternative Pointer menu surface and Touch menu surface. Pointer action rows retain `dropdown-menu-item`; touch action rows instead use List's `list-item` target. | Current source and tests | Verified modality split; no target change |
-| FR5 | Both menu surfaces carry `data-astryx-menu-press` and follow `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the browser's stray click never acts, and the Pointer menu surface declares `touch-action` by overflow. Trigger opening and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom and real Chromium |
-| FR6 | When the pointer menu closes, focus returns to the Trigger button with a visible ring only when the menu was driven by keyboard; a press outside that landed on a focusable control keeps focus there. | `architecture:interaction-modality` INV1; proposed in this change; `DropdownMenu.test.tsx` closing suite | Proposed; verified in jsdom, pending owner review |
-| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
-| FR8 | The Trigger button opens the pointer menu on a mouse press-down and on a finger held for the long-press delay, with the module's settle rule on the opening release; pressing the trigger of an open menu closes it without reopening in the same gesture; a tap and the keyboard open as before (`module:DropdownMenu/useMenuPress` proposed FR8, FR9). | Proposed `module:DropdownMenu/useMenuPress/DEC-4`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom, pending owner review |
-| Trigger source | `button` (Button props) or `renderTrigger` (render prop) | Which control the menu hangs off. `trigger` receives `DropdownMenuTriggerProps` — the press model, keyboard opens, toggle click and ARIA wiring — and names the menu. | Both presentations | `button` | `component:DropdownMenu` | stable | Both given: `trigger` wins and a dev warning fires. |
-| FR9 | With `renderTrigger`, the rendered control MUST carry `aria-haspopup`, `aria-expanded`, `aria-controls` and the `id` the menu's `aria-labelledby` points at, and MUST receive the same press-model, keyboard-open and toggle-click handlers as the Button path; the menu is named by that control. `button` and `trigger` are mutually exclusive: both given, `trigger` wins and a dev warning fires, in both presentations. A drilled-in Back row (FR11) returns to the menu by that same name: the caller's `aria-label` when given, else the control's accessible name, read as the menu opens. | `component:DropdownMenu/DEC-2` | Proposed; verified in jsdom; owner to confirm DEC-2 |
-| Row destination | `href` (+ `target`, `rel`) on an action item | The row's act is navigation: the row itself is the link (`family:navigation-destinations`). | Pointer action row and Touch action row, compound and data mode | none (an action row) | `component:DropdownMenu` | stable | Blocked schemes follow the family rule; a disabled row has none. |
-| FR10 | An action row with `href` MUST render as one anchor carrying `role="menuitem"` (the pointer menu) or the touch sheet's link row, routed through `LinkProvider`; a plain click MUST run `onClick`, then close the menu (`hasCloseOnSelect`), then let the browser navigate; a modified click or middle click MUST be left to the browser and MUST NOT run `onClick`; Enter and Space MUST activate through a synthesized click that carries the key's modifiers. A disabled link row has no `href`. | `component:DropdownMenu/DEC-2`; `family:navigation-destinations` | Proposed; verified in jsdom; owner to confirm DEC-1 |
-| Sub-menu presentation | `presentation` on a sub-menu row: `flyout`, `drill-in`, `adaptive` | Whether a sub-menu opens beside its row or replaces the menu's rows with its own and a Back row, in the same box. `adaptive` drills in when a coarse pointer opened the menu. | Pointer presentation, compound and data mode | `adaptive` | `component:DropdownMenu` | stable | An unknown value reads as `adaptive`. |
-| FR11 | When a compact touch display opened the pointer menu (`COMPACT_TOUCH_PRESENTATION_QUERY`, the same query the root presentation uses for its bottom sheet, sampled once as it opens) an `adaptive` sub-menu row MUST drill in: its rows and a leading Back row named "Back to <parent>" replace the menu's rows in the same Pointer menu surface, no flyout opens, the drilled list is a `menu` named by the row's label, and Back, Escape and ArrowLeft MUST return to the row with focus on it; a pick inside closes the whole menu. Roving focus and typeahead scope to the shown rows; sibling rows and dividers need no knowledge of it. `presentation="flyout"` keeps the flyout; `"drill-in"` drills in on any pointer. | `component:DropdownMenu/DEC-2`; `architecture:interaction-modality` | Proposed; verified in jsdom and Chromium (coarse pointer); owner to confirm DEC-5 |
-| FR12 | In the pointer menu ArrowDown on the last enabled row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp move to the last and first fully visible enabled row and, pressed there again, one viewport further without wrapping; ArrowUp on the trigger opens with the last enabled row highlighted; the key that opened the menu and its auto-repeats do not activate; typeahead matches the row's label element alone and ignores Control/Command chords and input-method composition. | Proposed in this change; `DropdownMenu.test.tsx` keyboard suite, `useListFocus.test.tsx`, `useTypeahead.test.tsx` | Proposed; verified in jsdom, pending owner review |
-| FR13 | On a mouse, a nested flyout stays open while the pointer is inside the triangle from where it left its row to the flyout's near edge — including while the pointer is paused there — and closes after the existing delay once the pointer has left both the row and that triangle. The row's click toggle and its guard window are unchanged. | Proposed in this change; `DropdownMenuSubMenu.test.tsx` safe-triangle suite, `useMenuHover.test.tsx` | Proposed; verified in jsdom, pending owner review |
-| FR14 | A compound `DropdownMenuGroup` is one `role="group"` named by its heading through `aria-labelledby`; the heading carries `dropdown-menu-section-heading`, is plain text rather than a menu item, and is skipped by roving focus and typeahead. An untitled group is an unnamed `role="group"`. | DEC-1, docs, and tests | Proposed; awaiting owner approval |
-| FR15 | With `header` or `footer`, the pointer popover holds the header, then the `role="menu"` element, then the footer, and the menu element holds only its rows. A region keeps its own keys and presses: neither the menu's key handling nor its press model claims an event that begins there. The menu is one Tab stop between the regions. Tab from the menu moves to the footer, and Shift+Tab to the header, when that region holds a control Tab can reach; otherwise Tab closes the menu as before. Tab past the footer's last control or Shift+Tab before the header's first closes the menu, and focus returns to the trigger. From a row of an open sub-menu, Tab and Shift+Tab close every open flyout and continue as they do from a row of the root menu. Escape closes from anywhere in the popover. The bottom sheet shows the header above the actions and the footer below them. Without either, the menu renders and behaves exactly as it does without the props. | DEC-8, docs, and tests | Proposed; awaiting owner approval |
+| ID | Candidate invariant | Basis | Draft review state |
+| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
+| FR1 | Every current render contains a Trigger button. Pointer presentation renders a Pointer menu surface with pointer-owned rows and optional pointer headings, dividers, indicators, and nested flyouts. Touch presentation renders a Touch sheet frame containing a Touch menu surface, Touch heading, Touch action list, and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
+| FR2 | The six current local targets are `dropdown-menu`, `dropdown-menu-item`, `dropdown-menu-radio`, `dropdown-menu-section-heading`, `dropdown-menu-divider`, and `dropdown-menu-indicator-icon`; every target remains on its current painted element. | Current source, docs, and tests | Verified current inventory; no target change |
+| FR3 | Button owns the Trigger button, BottomSheet owns the Touch sheet frame, List owns the Touch action list and Touch action rows, Indicator owns checkbox chrome, and Icon owns ordinary rendered icons. | Current source and owner docs | Verified current delegation; no ownership change |
+| FR4 | The same `dropdown-menu` target reaches the alternative Pointer menu surface and Touch menu surface. Pointer action rows retain `dropdown-menu-item`; touch action rows instead use List's `list-item` target. | Current source and tests | Verified modality split; no target change |
+| FR5 | Both menu surfaces carry `data-astryx-menu-press` and follow `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the browser's stray click never acts, and the Pointer menu surface declares `touch-action` by overflow. Trigger opening and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom and real Chromium |
+| FR6 | When the pointer menu closes, focus returns to the Trigger button with a visible ring only when the menu was driven by keyboard; a press outside that landed on a focusable control keeps focus there. | `architecture:interaction-modality` INV1; proposed in this change; `DropdownMenu.test.tsx` closing suite | Proposed; verified in jsdom, pending owner review |
+| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
+| FR8 | The Trigger button opens the pointer menu on a mouse press-down and on a finger held for the long-press delay, with the module's settle rule on the opening release; pressing the trigger of an open menu closes it without reopening in the same gesture; a tap and the keyboard open as before (`module:DropdownMenu/useMenuPress` proposed FR8, FR9). | Proposed `module:DropdownMenu/useMenuPress/DEC-4`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom, pending owner review |
+| Trigger source | `button` (Button props) or `renderTrigger` (render prop) | Which control the menu hangs off. `trigger` receives `DropdownMenuTriggerProps` — the press model, keyboard opens, toggle click and ARIA wiring — and names the menu. | Both presentations | `button` | `component:DropdownMenu` | stable | Both given: `trigger` wins and a dev warning fires. |
+| FR9 | With `renderTrigger`, the rendered control MUST carry `aria-haspopup`, `aria-expanded`, `aria-controls` and the `id` the menu's `aria-labelledby` points at, and MUST receive the same press-model, keyboard-open and toggle-click handlers as the Button path; the menu is named by that control. `button` and `trigger` are mutually exclusive: both given, `trigger` wins and a dev warning fires, in both presentations. A drilled-in Back row (FR11) returns to the menu by that same name: the caller's `aria-label` when given, else the control's accessible name, read as the menu opens. | `component:DropdownMenu/DEC-2` | Proposed; verified in jsdom; owner to confirm DEC-2 |
+| Row destination | `href` (+ `target`, `rel`) on an action item | The row's act is navigation: the row itself is the link (`family:navigation-destinations`). | Pointer action row and Touch action row, compound and data mode | none (an action row) | `component:DropdownMenu` | stable | Blocked schemes follow the family rule; a disabled row has none. |
+| FR10 | An action row with `href` MUST render as one anchor carrying `role="menuitem"` (the pointer menu) or the touch sheet's link row, routed through `LinkProvider`; a plain click MUST run `onClick`, then close the menu (`hasCloseOnSelect`), then let the browser navigate; a modified click or middle click MUST be left to the browser and MUST NOT run `onClick`; Enter and Space MUST activate through a synthesized click that carries the key's modifiers. A disabled link row has no `href`. | `component:DropdownMenu/DEC-2`; `family:navigation-destinations` | Proposed; verified in jsdom; owner to confirm DEC-1 |
+| Sub-menu presentation | `presentation` on a sub-menu row: `flyout`, `drill-in`, `adaptive` | Whether a sub-menu opens beside its row or replaces the menu's rows with its own and a Back row, in the same box. `adaptive` drills in when a coarse pointer opened the menu. | Pointer presentation, compound and data mode | `adaptive` | `component:DropdownMenu` | stable | An unknown value reads as `adaptive`. |
+| FR11 | When a compact touch display opened the pointer menu (`COMPACT_TOUCH_PRESENTATION_QUERY`, the same query the root presentation uses for its bottom sheet, sampled once as it opens) an `adaptive` sub-menu row MUST drill in: its rows and a leading Back row named "Back to <parent>" replace the menu's rows in the same Pointer menu surface, no flyout opens, the drilled list is a `menu` named by the row's label, and Back, Escape and ArrowLeft MUST return to the row with focus on it; a pick inside closes the whole menu. Roving focus and typeahead scope to the shown rows; sibling rows and dividers need no knowledge of it. `presentation="flyout"` keeps the flyout; `"drill-in"` drills in on any pointer. | `component:DropdownMenu/DEC-2`; `architecture:interaction-modality` | Proposed; verified in jsdom and Chromium (coarse pointer); owner to confirm DEC-5 |
+| FR12 | In the pointer menu ArrowDown on the last enabled row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp move to the last and first fully visible enabled row and, pressed there again, one viewport further without wrapping; ArrowUp on the trigger opens with the last enabled row highlighted; the key that opened the menu and its auto-repeats do not activate; typeahead matches the row's label element alone and ignores Control/Command chords and input-method composition. | Proposed in this change; `DropdownMenu.test.tsx` keyboard suite, `useListFocus.test.tsx`, `useTypeahead.test.tsx` | Proposed; verified in jsdom, pending owner review |
+| FR13 | On a mouse, a nested flyout stays open while the pointer is inside the triangle from where it left its row to the flyout's near edge — including while the pointer is paused there — and closes after the existing delay once the pointer has left both the row and that triangle. The row's click toggle and its guard window are unchanged. | Proposed in this change; `DropdownMenuSubMenu.test.tsx` safe-triangle suite, `useMenuHover.test.tsx` | Proposed; verified in jsdom, pending owner review |
+| FR14 | A compound `DropdownMenuGroup` is one `role="group"` named by its heading through `aria-labelledby`; the heading carries `dropdown-menu-section-heading`, is plain text rather than a menu item, and is skipped by roving focus and typeahead. An untitled group is an unnamed `role="group"`. | DEC-1, docs, and tests | Proposed; awaiting owner approval |
+| FR15 | With `header` or `footer`, the pointer popover is a `role="dialog"` with `aria-modal="true"`, named like the menu, holding the header, then the `role="menu"` element, then the footer; the menu element holds only its rows. The trigger says `aria-haspopup="dialog"` and its `aria-controls` names the popover that holds the dialog. A region keeps its own keys and presses: neither the menu's key handling nor its press model claims an event that begins there. The menu is one Tab stop between the regions. Tab and Shift+Tab move through the header's controls, the menu, then the footer's controls, and wrap at either end; a control that is hidden, or under a hidden ancestor within its region, is not a stop. From a row, or a row of an open sub-menu, Tab and Shift+Tab close every open flyout and continue from the menu's stop. With no other stop, focus stays in the menu. Escape closes from anywhere in the popover, and focus returns to the trigger. The bottom sheet, already a dialog, shows the header above the actions and the footer below them. Without either prop, the menu renders and behaves exactly as it does without them: no dialog, `aria-haspopup="menu"`, and Tab closes the menu. | DEC-8, DEC-10, docs, and tests | Proposed; awaiting owner approval |
### Allowed variation
@@ -186,9 +186,18 @@ visibility helper.
this component already ships. A `renderTrigger` control receives
`aria-haspopup`, `aria-expanded`, `aria-controls`, and the keyboard and focus
handlers through the spread props (FR9); the caller's control supplies its
- own `button` role and accessible name. The bottom-sheet presentation is
- outside this pattern: its trigger opens a dialog and says
- `aria-haspopup="dialog"`.
+ own `button` role and accessible name. The bottom-sheet presentation and a
+ pointer menu with `header` or `footer` are outside this pattern: their
+ trigger opens a dialog and says `aria-haspopup="dialog"` (AR5).
+- **AR5 — With a header or footer, the pointer popover adopts the APG Dialog
+ (Modal) pattern's required parts** (`spec:AST-020/FR15`): `role="dialog"`,
+ `aria-modal="true"`, and an accessible name, the menu's; focus moves into
+ the dialog on open, to the menu or its first enabled row as FR6 and FR12
+ already state; Tab and Shift+Tab cycle within it (FR15); Escape closes it
+ and focus returns to the trigger. The menu inside keeps AR1–AR3. The
+ trigger keeps `aria-expanded`; its `aria-haspopup` says `dialog`, and its
+ `aria-controls` names the popover that holds the dialog rather than the
+ menu, as Popover's own trigger does.
## Design relationships
@@ -287,23 +296,23 @@ than adding a DropdownMenu-owned heading target.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
-| FR1, FR4 | `DropdownMenu.test.tsx` pointer, bottom-sheet, adaptive, section, divider, and drill-in suites | Root pointer, nested pointer, root touch, drill-in | Collapsing presentation-specific parts or owners fails structure, target, or role assertions. | `audit:DropdownMenu/anatomy` |
-| FR2 | DropdownMenu target suites, source inspection, and theming target inventories | All six local targets | Removing, renaming, or assigning a current target to the wrong part fails evidence or inventory. | `audit:DropdownMenu/theming` |
-| FR3 | `DropdownMenuSelectable.test.tsx` plus BottomSheet, List, Indicator, Icon, and Divider owner tests | Trigger, touch actions, icons, checkbox, radio | A composed part loses its owner target or is documented as a new local target. | `audit:DropdownMenu/theming` |
-| Layer relationships | `DropdownMenu.test.tsx`, `DropdownMenuSubMenu.test.tsx`, and current layer/dismissal architecture records | Light dismiss, nested flyout, sheet dismissal | Documentation claims a shared owner where current source retains local behavior, or the reverse. | `audit:DropdownMenu/behavior` |
-| FR5 | `DropdownMenu.test.tsx` press model suite; the module record's own map | Finger slide across rows, outside release by mouse and finger, `touch-action`, root marker | A row acting on the press or the stray click, a lost `touch-action`, or a finger release that closes fails. | `audit:DropdownMenu/behavior` |
-| FR6 | `DropdownMenu.test.tsx` dismissal, closing and press model suites; `__tests__/MenuPress.a11y.chromium.spec.ts` in real Chromium | keyboard/pointer dismissal, Escape after press-open, press outside on a control, pointer pick, closed menu | Focus left on the body after a pointer pick, on the control focused before a press-open, or a ring after pointer input, fails. | `audit:DropdownMenu/behavior` |
-| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:DropdownMenu/theming` |
-| FR8 | `DropdownMenu.test.tsx` press model suite (trigger cases) | Press-open + drag-release, unsettled opening release, trigger toggle, held touch, tap | A menu that does not open on a mouse press, an unsettled release that acts, or a trigger that reopens in the same gesture fails. | `audit:DropdownMenu/behavior` |
-| FR9 | `DropdownMenu.test.tsx` custom trigger suite; `DropdownMenuSubMenu.test.tsx` custom-trigger Back row cases | Icon button, chip, list row; open, toggle, keyboard open, name; drill-in Back row | A rendered control missing `aria-haspopup`, `aria-expanded` or `aria-controls`, an unnamed menu, a lost keyboard open, or a "Back to Menu" row, fails. | `audit:DropdownMenu/anatomy` |
-| AR4 | `DropdownMenu.test.tsx` cases "has aria-haspopup and aria-expanded attributes", "keyboard open via Enter focuses the first enabled item", "walks into a mounted-open menu with ArrowDown from the focused trigger", "keyboard open via ArrowDown skips a disabled leading item", "ArrowUp on the trigger opens with the last row highlighted", and "a custom trigger opens from the keyboard and lands on the first row"; Space opening and `aria-controls` under the Menu Button accessibility contract (`internal/a11y-spec`, pending) bound to the anchored trigger | Button and `renderTrigger` controls; closed/open; Enter, Space, ArrowDown, ArrowUp open | The trigger loses its name, `aria-haspopup="menu"`, `aria-expanded` or `aria-controls`; a keyboard open lands focus somewhere other than the first (or, for ArrowUp, last) enabled row | `audit:DropdownMenu/accessibility` |
-| FR8, AR2 | `DropdownMenu.test.tsx` "DropdownMenuItem href" suite (pointer menu and bottom sheet) | Plain click, ⌘-click, Enter with modifiers, disabled link row | A row rendering an inner anchor, running `onClick` on a modified click, or a synthesized click dropping the modifiers fails. | `audit:DropdownMenu/behavior` |
-| FR12, AR3 | `DropdownMenuSubMenu.test.tsx` "drill-in on a phone" suite; `__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts` (real Chromium, coarse pointer) | Drill in, Back, Escape, ArrowLeft, nested level, scoped typeahead, forced presentations, close resets | A flyout opening on a coarse pointer, a missing Back row, sibling rows staying in the order, or focus not returning to the row fails. | `audit:DropdownMenu/behavior` |
-| FR10 | `DropdownMenuSubMenu.test.tsx` safe-triangle suite; `useMenuHover.test.tsx` `isPointInSafeTriangle` and click-guard suites | diagonal path toward the flyout, a pause inside it, path away, click-opened and hover-opened guard windows | A flyout that closes while the pointer is inside the triangle or paused in it, one that never closes after leaving it, or a changed guard-window rule, fails. | `audit:DropdownMenu/behavior` |
-| FR15 | `DropdownMenu.test.tsx` header and footer suite; `__tests__/MenuHeaderFooter.a11y.chromium.spec.ts` in real Chromium | regions outside the menu element, typing in a header field, Tab walk header → menu → footer → close, Tab and Shift+Tab from an open sub-menu, Escape from the header, a finger tap on a footer button, bottom sheet order, no regions | A region rendered inside the menu element, a header key taken by typeahead, a Tab that leaves the menu open with focus outside it, or a footer tap swallowed by the press model fails. |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
+| FR1, FR4 | `DropdownMenu.test.tsx` pointer, bottom-sheet, adaptive, section, divider, and drill-in suites | Root pointer, nested pointer, root touch, drill-in | Collapsing presentation-specific parts or owners fails structure, target, or role assertions. | `audit:DropdownMenu/anatomy` |
+| FR2 | DropdownMenu target suites, source inspection, and theming target inventories | All six local targets | Removing, renaming, or assigning a current target to the wrong part fails evidence or inventory. | `audit:DropdownMenu/theming` |
+| FR3 | `DropdownMenuSelectable.test.tsx` plus BottomSheet, List, Indicator, Icon, and Divider owner tests | Trigger, touch actions, icons, checkbox, radio | A composed part loses its owner target or is documented as a new local target. | `audit:DropdownMenu/theming` |
+| Layer relationships | `DropdownMenu.test.tsx`, `DropdownMenuSubMenu.test.tsx`, and current layer/dismissal architecture records | Light dismiss, nested flyout, sheet dismissal | Documentation claims a shared owner where current source retains local behavior, or the reverse. | `audit:DropdownMenu/behavior` |
+| FR5 | `DropdownMenu.test.tsx` press model suite; the module record's own map | Finger slide across rows, outside release by mouse and finger, `touch-action`, root marker | A row acting on the press or the stray click, a lost `touch-action`, or a finger release that closes fails. | `audit:DropdownMenu/behavior` |
+| FR6 | `DropdownMenu.test.tsx` dismissal, closing and press model suites; `__tests__/MenuPress.a11y.chromium.spec.ts` in real Chromium | keyboard/pointer dismissal, Escape after press-open, press outside on a control, pointer pick, closed menu | Focus left on the body after a pointer pick, on the control focused before a press-open, or a ring after pointer input, fails. | `audit:DropdownMenu/behavior` |
+| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:DropdownMenu/theming` |
+| FR8 | `DropdownMenu.test.tsx` press model suite (trigger cases) | Press-open + drag-release, unsettled opening release, trigger toggle, held touch, tap | A menu that does not open on a mouse press, an unsettled release that acts, or a trigger that reopens in the same gesture fails. | `audit:DropdownMenu/behavior` |
+| FR9 | `DropdownMenu.test.tsx` custom trigger suite; `DropdownMenuSubMenu.test.tsx` custom-trigger Back row cases | Icon button, chip, list row; open, toggle, keyboard open, name; drill-in Back row | A rendered control missing `aria-haspopup`, `aria-expanded` or `aria-controls`, an unnamed menu, a lost keyboard open, or a "Back to Menu" row, fails. | `audit:DropdownMenu/anatomy` |
+| AR4 | `DropdownMenu.test.tsx` cases "has aria-haspopup and aria-expanded attributes", "keyboard open via Enter focuses the first enabled item", "walks into a mounted-open menu with ArrowDown from the focused trigger", "keyboard open via ArrowDown skips a disabled leading item", "ArrowUp on the trigger opens with the last row highlighted", and "a custom trigger opens from the keyboard and lands on the first row"; Space opening and `aria-controls` under the Menu Button accessibility contract (`internal/a11y-spec`, pending) bound to the anchored trigger | Button and `renderTrigger` controls; closed/open; Enter, Space, ArrowDown, ArrowUp open | The trigger loses its name, `aria-haspopup="menu"`, `aria-expanded` or `aria-controls`; a keyboard open lands focus somewhere other than the first (or, for ArrowUp, last) enabled row | `audit:DropdownMenu/accessibility` |
+| FR8, AR2 | `DropdownMenu.test.tsx` "DropdownMenuItem href" suite (pointer menu and bottom sheet) | Plain click, ⌘-click, Enter with modifiers, disabled link row | A row rendering an inner anchor, running `onClick` on a modified click, or a synthesized click dropping the modifiers fails. | `audit:DropdownMenu/behavior` |
+| FR12, AR3 | `DropdownMenuSubMenu.test.tsx` "drill-in on a phone" suite; `__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts` (real Chromium, coarse pointer) | Drill in, Back, Escape, ArrowLeft, nested level, scoped typeahead, forced presentations, close resets | A flyout opening on a coarse pointer, a missing Back row, sibling rows staying in the order, or focus not returning to the row fails. | `audit:DropdownMenu/behavior` |
+| FR10 | `DropdownMenuSubMenu.test.tsx` safe-triangle suite; `useMenuHover.test.tsx` `isPointInSafeTriangle` and click-guard suites | diagonal path toward the flyout, a pause inside it, path away, click-opened and hover-opened guard windows | A flyout that closes while the pointer is inside the triangle or paused in it, one that never closes after leaving it, or a changed guard-window rule, fails. | `audit:DropdownMenu/behavior` |
+| FR15 | `DropdownMenu.test.tsx` header and footer suite; `__tests__/MenuHeaderFooter.a11y.chromium.spec.ts` in real Chromium | dialog role, modality, name and trigger wiring; regions outside the menu element; typing in a header field; Tab walk header → menu → footer with wrap at both ends; Tab and Shift+Tab from an open sub-menu; hidden and hidden-wrapper controls; Escape from the header; a finger tap on a footer button; bottom sheet order; no regions | A region rendered inside the menu element, a popover with regions that is not a named modal dialog, a trigger still saying `aria-haspopup="menu"` with regions, a header key taken by typeahead, a Tab that leaves the dialog or closes it, focus stranded outside the dialog, or a footer tap swallowed by the press model fails. |
## Decision log
@@ -484,8 +493,8 @@ menu element, the menu never claims the control's keys or presses. Because
needs no inspection of its children to keep that true.
The menu becomes one Tab stop between the regions, so the popover reads as
-one Tab sequence: header, menu, footer. Leaving it past either end closes the
-menu, as Tab from the rows always has. Focus on open is unchanged. Rejected:
+one Tab sequence: header, menu, footer, inside the dialog of DEC-10. Focus on
+open is unchanged. Rejected:
letting the menu's handlers step aside for controls placed among the rows —
that makes invalid structure work instead of fixing it; and a caller-wrapped
items element, which leaves "nothing between the rows" to convention.
@@ -498,3 +507,20 @@ items element, which leaves "nothing between the rows" to convention.
The pointer trigger already plays the Menu Button's role, so it carries the pattern's required parts (AR4). ArrowDown and ArrowUp opening go beyond the adoption rule's required set and stay as a named exception because the component shipped them (FR12 keeps the wrap once the menu is open) and removing a working keyboard path would cost the users who have it. ContextMenu and NavMenu are not covered by this decision.
Rejected: dropping arrow-key opening to match the rule's default; adopting the pattern for every control that opens any layer.
+
+### DEC-10 — A popover with a header or footer is a modal dialog, and Tab wraps
+
+**Reference:** `component:DropdownMenu/DEC-10`
+**Decider:** `cixzhang`, 2026-10-13
+
+A popover that holds a menu and controls that are not menu items is not a
+menu: a trigger exposing `aria-haspopup="menu"` promises a menu, and the
+popover then holds a field or a button that is not one. With `header` or
+`footer`, the popover is therefore exposed as a named modal dialog with the
+menu inside it, the trigger says `aria-haspopup="dialog"`, and
+`aria-controls` names the popover that holds the dialog. Moving the
+menu role inward keeps every row a menu item and every other control outside
+the menu. Tab and Shift+Tab wrap within the dialog, as the APG Dialog
+pattern requires; Escape and a press outside close it. Without either prop
+the component is unchanged: a Menu Button whose Tab closes the menu. Rejected:
+closing on Tab past either end, which leaves a modal dialog by Tab.
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index ed40925e96..2479823d54 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -15,7 +15,7 @@ import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {useState} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {DropdownMenu} from './DropdownMenu';
+import {DropdownMenu, type DropdownMenuTriggerProps} from './DropdownMenu';
import {DropdownMenuItem} from './DropdownMenuItem';
import {DropdownMenuDivider} from './DropdownMenuDivider';
import {DropdownMenuGroup} from './DropdownMenuGroup';
@@ -3658,11 +3658,12 @@ describe('DropdownMenu header and footer', () => {
</button>,
],
])(
- 'treats a %s footer control as unreachable: Tab from the menu closes it',
+ 'treats a %s footer control as unreachable: Tab from the menu stays on the menu',
async (_label, control) => {
const {menu, hide} = await openHidden(null, control);
fireEvent.keyDown(menu, {key: 'Tab'});
- expect(hide).toHaveBeenCalled();
+ expect(menu).toHaveFocus();
+ expect(hide).not.toHaveBeenCalled();
},
);
@@ -3674,10 +3675,11 @@ describe('DropdownMenu header and footer', () => {
</div>,
);
fireEvent.keyDown(menu, {key: 'Tab'});
- expect(hide).toHaveBeenCalled();
+ expect(menu).toHaveFocus();
+ expect(hide).not.toHaveBeenCalled();
});
- it('treats a header control inside a display: none wrapper as unreachable: Shift+Tab from a row closes', async () => {
+ it('treats a header control inside a display: none wrapper as unreachable: Shift+Tab from a row stays', async () => {
const {menu, hide} = await openHidden(
<div style={{display: 'none'}}>
<input aria-label="Filter labels" />
@@ -3688,10 +3690,11 @@ describe('DropdownMenu header and footer', () => {
const row = screen.getByRole('menuitem', {name: 'Bug', hidden: true});
await waitFor(() => expect(row).toHaveFocus());
fireEvent.keyDown(row, {key: 'Tab', shiftKey: true});
- expect(hide).toHaveBeenCalled();
+ expect(row).toHaveFocus();
+ expect(hide).not.toHaveBeenCalled();
});
- it('Tab past the last visible footer control closes, ignoring a wrapped hidden one after it', async () => {
+ it('Tab past the last visible footer control wraps to the menu, ignoring a wrapped hidden one after it', async () => {
const {hide} = await openHidden(
null,
<>
@@ -3707,10 +3710,13 @@ describe('DropdownMenu header and footer', () => {
});
act(() => create.focus());
fireEvent.keyDown(create, {key: 'Tab'});
- expect(hide).toHaveBeenCalled();
+ expect(
+ screen.getByRole('menu', {name: 'Labels', hidden: true}),
+ ).toHaveFocus();
+ expect(hide).not.toHaveBeenCalled();
});
- it('Tab from an open sub-menu closes the menu when the footer control is in a hidden wrapper', async () => {
+ it('Tab from an open sub-menu returns to the menu when the footer control is in a hidden wrapper', async () => {
const {user, menu} = await openHidden(
null,
<div style={{display: 'none'}}>
@@ -3730,11 +3736,11 @@ describe('DropdownMenu header and footer', () => {
await waitFor(() => expect(folder).toHaveFocus());
fireEvent.keyDown(folder, {key: 'Tab'});
expect(subTrigger).toHaveAttribute('aria-expanded', 'false');
- // The flyout's own close also hides a popover, so check the root's.
- expect(menu.closest('[popover]')).not.toHaveAttribute('popover-open');
+ expect(menu).toHaveFocus();
+ expect(menu.closest('[popover]')).toHaveAttribute('popover-open');
});
- it('treats a hidden header control as unreachable: Shift+Tab from a row closes the menu', async () => {
+ it('treats a hidden header control as unreachable: Shift+Tab from a row stays on the row', async () => {
const {menu, hide} = await openHidden(
<input aria-label="Filter labels" hidden />,
null,
@@ -3743,10 +3749,11 @@ describe('DropdownMenu header and footer', () => {
const row = screen.getByRole('menuitem', {name: 'Bug', hidden: true});
await waitFor(() => expect(row).toHaveFocus());
fireEvent.keyDown(row, {key: 'Tab', shiftKey: true});
- expect(hide).toHaveBeenCalled();
+ expect(row).toHaveFocus();
+ expect(hide).not.toHaveBeenCalled();
});
- it('Tab past the last visible footer control closes, ignoring a hidden one after it', async () => {
+ it('Tab past the last visible footer control wraps to the menu, ignoring a hidden one after it', async () => {
const {hide} = await openHidden(
null,
<>
@@ -3762,10 +3769,13 @@ describe('DropdownMenu header and footer', () => {
});
act(() => create.focus());
fireEvent.keyDown(create, {key: 'Tab'});
- expect(hide).toHaveBeenCalled();
+ expect(
+ screen.getByRole('menu', {name: 'Labels', hidden: true}),
+ ).toHaveFocus();
+ expect(hide).not.toHaveBeenCalled();
});
- it('Tab from an open sub-menu closes the menu when the footer holds only hidden controls', async () => {
+ it('Tab from an open sub-menu returns to the menu when the footer holds only hidden controls', async () => {
const {user, menu} = await openHidden(
null,
<button type="button" hidden>
@@ -3785,8 +3795,8 @@ describe('DropdownMenu header and footer', () => {
await waitFor(() => expect(folder).toHaveFocus());
fireEvent.keyDown(folder, {key: 'Tab'});
expect(subTrigger).toHaveAttribute('aria-expanded', 'false');
- // The flyout's own close also hides a popover, so check the root's.
- expect(menu.closest('[popover]')).not.toHaveAttribute('popover-open');
+ expect(menu).toHaveFocus();
+ expect(menu.closest('[popover]')).toHaveAttribute('popover-open');
});
});
@@ -3846,7 +3856,7 @@ describe('DropdownMenu header and footer', () => {
});
});
- it('Tab past the last footer control closes the menu', async () => {
+ it('Tab past the last footer control wraps to the first header control', async () => {
await open();
const hide = vi.mocked(HTMLElement.prototype.hidePopover);
hide.mockClear();
@@ -3860,11 +3870,13 @@ describe('DropdownMenu header and footer', () => {
create.focus();
expect(create).toHaveFocus();
fireEvent.keyDown(create, {key: 'Tab'});
- expect(hide).toHaveBeenCalled();
- expect(screen.getByRole('button', {name: /Labels/})).toHaveFocus();
+ expect(
+ screen.getByRole('textbox', {name: 'Filter labels', hidden: true}),
+ ).toHaveFocus();
+ expect(hide).not.toHaveBeenCalled();
});
- it('Shift+Tab before the first header control closes the menu', async () => {
+ it('Shift+Tab before the first header control wraps to the last footer control', async () => {
await open();
const hide = vi.mocked(HTMLElement.prototype.hidePopover);
hide.mockClear();
@@ -3878,7 +3890,211 @@ describe('DropdownMenu header and footer', () => {
field.focus();
expect(field).toHaveFocus();
fireEvent.keyDown(field, {key: 'Tab', shiftKey: true});
- expect(hide).toHaveBeenCalled();
+ expect(
+ screen.getByRole('button', {name: 'Create label', hidden: true}),
+ ).toHaveFocus();
+ expect(hide).not.toHaveBeenCalled();
+ });
+
+ it('is a modal dialog named like the menu, holding the menu, and the trigger points at it', async () => {
+ const {menu} = await open();
+ const dialog = screen.getByRole('dialog', {name: 'Labels', hidden: true});
+ expect(dialog).toHaveAttribute('aria-modal', 'true');
+ expect(dialog).toContainElement(menu);
+ expect(dialog).toContainElement(
+ screen.getByRole('textbox', {name: 'Filter labels', hidden: true}),
+ );
+ const trigger = screen.getByRole('button', {name: /Labels/});
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ const controlled = document.getElementById(
+ trigger.getAttribute('aria-controls') ?? '',
+ );
+ expect(controlled).not.toBeNull();
+ expect(controlled).toContainElement(dialog);
+ expect(controlled).not.toContainElement(trigger);
+ });
+
+ it('a custom trigger with a header names the dialog and logs no unnamed-dialog warning', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ header={<input aria-label="Filter labels" />}
+ renderTrigger={props => (
+ <span {...props} role="button" tabIndex={0}>
+ Labels
+ </span>
+ )}>
+ <DropdownMenuItem label="Bug" />
+ </DropdownMenu>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Labels'});
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ await user.click(trigger);
+ expect(
+ screen.getByRole('dialog', {name: 'Labels', hidden: true}),
+ ).toHaveAttribute('aria-modal', 'true');
+ expect(
+ warn.mock.calls.some(args =>
+ String(args[0]).includes('unnamed dialog'),
+ ),
+ ).toBe(false);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it('an icon-only custom trigger with a header still gets a named dialog', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ header={<input aria-label="Filter labels" />}
+ renderTrigger={props => (
+ <button {...props} type="button">
+ <img alt="Labels" src="" />
+ </button>
+ )}>
+ <DropdownMenuItem label="Bug" />
+ </DropdownMenu>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Labels'});
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ await user.click(trigger);
+ expect(
+ screen.getByRole('dialog', {name: 'Labels', hidden: true}),
+ ).toHaveAttribute('aria-modal', 'true');
+ });
+
+ it.each([
+ [
+ 'its own <label>',
+ (props: DropdownMenuTriggerProps) => (
+ <>
+ <label htmlFor={props.id}>Labels</label>
+ <button {...props} type="button" />
+ </>
+ ),
+ ],
+ [
+ "an input button's value",
+ (props: DropdownMenuTriggerProps) => (
+ <input {...props} type="button" value="Labels" />
+ ),
+ ],
+ ])(
+ 'a custom trigger named by %s names the dialog like the menu',
+ async (_label, renderTrigger) => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ header={<input aria-label="Filter labels" />}
+ renderTrigger={renderTrigger}>
+ <DropdownMenuItem label="Bug" />
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ expect(
+ screen.getByRole('dialog', {name: 'Labels', hidden: true}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('menu', {name: 'Labels', hidden: true}),
+ ).toBeInTheDocument();
+ },
+ );
+
+ it('a custom trigger with no readable name still gets a dialog, named by the default label', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ footer={<button type="button">Create label</button>}
+ renderTrigger={props => (
+ <button {...props} type="button" data-testid="bare" />
+ )}>
+ <DropdownMenuItem label="Bug" />
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByTestId('bare'));
+ const dialog = screen.getByRole('dialog', {hidden: true});
+ expect(dialog).toHaveAttribute('aria-modal', 'true');
+ expect(dialog.getAttribute('aria-label')?.trim()).not.toBe('');
+ });
+
+ describe('with a radio group in the header', () => {
+ async function openWithRadios(checked: string | null) {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ button={{label: 'Labels'}}
+ header={
+ <fieldset>
+ {['Name', 'Date', 'Size'].map(option => (
+ <input
+ key={option}
+ type="radio"
+ name="sort"
+ aria-label={option}
+ defaultChecked={option === checked}
+ />
+ ))}
+ </fieldset>
+ }
+ footer={<button type="button">Create label</button>}>
+ <DropdownMenuItem label="Bug" />
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Labels/}));
+ const menu = screen.getByRole('menu', {name: 'Labels', hidden: true});
+ await waitFor(() => expect(menu).toHaveFocus());
+ const radio = (name: string) =>
+ screen.getByRole('radio', {name, hidden: true});
+ const create = screen.getByRole('button', {
+ name: 'Create label',
+ hidden: true,
+ });
+ return {menu, radio, create};
+ }
+
+ it('Shift+Tab from the menu lands on the checked radio, and Tab leaves the group in one step', async () => {
+ const {menu, radio} = await openWithRadios('Date');
+ fireEvent.keyDown(menu, {key: 'Tab', shiftKey: true});
+ expect(radio('Date')).toHaveFocus();
+ fireEvent.keyDown(radio('Date'), {key: 'Tab'});
+ expect(menu).toHaveFocus();
+ });
+
+ it('Tab wrapping past the footer lands on the checked radio', async () => {
+ const {radio, create} = await openWithRadios('Size');
+ act(() => create.focus());
+ fireEvent.keyDown(create, {key: 'Tab'});
+ expect(radio('Size')).toHaveFocus();
+ });
+
+ it('with none checked, the group is entered at its first radio forward and its last backward', async () => {
+ const {menu, radio, create} = await openWithRadios(null);
+ fireEvent.keyDown(menu, {key: 'Tab', shiftKey: true});
+ expect(radio('Size')).toHaveFocus();
+ act(() => create.focus());
+ fireEvent.keyDown(create, {key: 'Tab'});
+ expect(radio('Name')).toHaveFocus();
+ fireEvent.keyDown(radio('Name'), {key: 'Tab', shiftKey: true});
+ expect(create).toHaveFocus();
+ });
+ });
+
+ it('without a header or footer, there is no dialog and the trigger points at the menu', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem label="Item 1" />
+ </DropdownMenu>,
+ );
+ const trigger = screen.getByRole('button', {name: /Actions/});
+ await user.click(trigger);
+ const menu = screen.getByRole('menu', {name: 'Actions', hidden: true});
+ expect(screen.queryByRole('dialog', {hidden: true})).toBeNull();
+ expect(trigger).toHaveAttribute('aria-haspopup', 'menu');
+ expect(trigger).toHaveAttribute('aria-controls', menu.id);
});
it('leaves keys typed in the header to the field', async () => {
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 29b3bfe153..c4b2887775 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -114,6 +114,53 @@ const MENU_TRIGGER_OPEN_BACKGROUND = `linear-gradient(${colorVars['--color-overl
* aria-hidden subtrees) are not reachable, judged by the popover focus trap's
* own test so the two never disagree about where Tab can go.
*/
+/**
+ * Collapse each named radio group to the one Tab stop a browser gives it: the
+ * focused radio, else the checked one, else the first radio moving forward or
+ * the last moving backward. The stop takes the group's first position.
+ */
+function collapseRadioGroups(
+ elements: HTMLElement[],
+ active: Element | null,
+ isBackward: boolean,
+): HTMLElement[] {
+ const groups = new Map<string, HTMLInputElement[]>();
+ const groupKey = (el: HTMLElement): string | null =>
+ el instanceof HTMLInputElement &&
+ el.getAttribute('type') === 'radio' &&
+ el.name !== ''
+ ? `${el.form?.id ?? ''}\u0000${el.name}`
+ : null;
+ for (const el of elements) {
+ const key = groupKey(el);
+ if (key != null) {
+ const members = groups.get(key) ?? [];
+ members.push(el as HTMLInputElement);
+ groups.set(key, members);
+ }
+ }
+ const placed = new Set<string>();
+ const result: HTMLElement[] = [];
+ for (const el of elements) {
+ const key = groupKey(el);
+ if (key == null) {
+ result.push(el);
+ continue;
+ }
+ if (placed.has(key)) {
+ continue;
+ }
+ placed.add(key);
+ const members = groups.get(key) ?? [];
+ const stop =
+ members.find(radio => radio === active) ??
+ members.find(radio => radio.checked) ??
+ (isBackward ? members[members.length - 1] : members[0]);
+ result.push(stop);
+ }
+ return result;
+}
+
function tabbablesIn(region: HTMLElement | null): HTMLElement[] {
if (region == null) {
return [];
@@ -148,8 +195,9 @@ function isInsideHiddenWrapper(
}
/**
- * Move focus to a region control. Reports whether focus actually arrived, so a
- * caller can close the menu instead of stranding focus on the page.
+ * Move focus to a Tab stop in the dialog. Reports whether focus actually
+ * arrived, so a caller can fall back to the menu instead of stranding focus on
+ * the page.
*/
function focusRegionControl(element: HTMLElement): boolean {
element.focus();
@@ -551,6 +599,17 @@ function visibleText(element: Element): string {
for (const hidden of copy.querySelectorAll('[aria-hidden="true"]')) {
hidden.remove();
}
+ // An icon-only control is named by its image's alt, an inner aria-label, or
+ // an svg title rather than by text, so those count as its contents too.
+ for (const named of copy.querySelectorAll('img[alt], [aria-label]')) {
+ const name =
+ named.getAttribute(named.tagName === 'IMG' ? 'alt' : 'aria-label') ?? '';
+ named.replaceWith(copy.ownerDocument.createTextNode(` ${name} `));
+ }
+ for (const svg of copy.querySelectorAll('svg')) {
+ const title = svg.querySelector('title')?.textContent ?? '';
+ svg.replaceWith(copy.ownerDocument.createTextNode(` ${title} `));
+ }
return (copy.textContent ?? '').replace(/\s+/g, ' ').trim();
}
@@ -580,6 +639,24 @@ function readAccessibleName(element: HTMLElement | null): string | undefined {
if (label) {
return label;
}
+ // A form control is named by its own <label>s; an input button by its value.
+ const labels =
+ 'labels' in element
+ ? Array.from((element as HTMLInputElement).labels ?? [])
+ : [];
+ const labelText = labels.map(visibleText).join(' ').trim();
+ if (labelText !== '') {
+ return labelText;
+ }
+ if (
+ element instanceof HTMLInputElement &&
+ ['button', 'submit', 'reset'].includes(element.getAttribute('type') ?? '')
+ ) {
+ const value = element.value.trim();
+ if (value !== '') {
+ return value;
+ }
+ }
const text = visibleText(element);
if (text !== '') {
return text;
@@ -962,6 +1039,16 @@ function DropdownMenuPopover({
// ArrowUp opens with the LAST enabled row highlighted.
const focusLastOnOpenRef = useRef(false);
+ // Synchronizes the dialog's name from the custom trigger's DOM, an external
+ // system React does not own: the rendered control's accessible name is only
+ // readable once it mounts. With a header or footer the dialog is named like
+ // the menu, so that name is needed before the first open, not only at it.
+ useIsomorphicLayoutEffect(() => {
+ if (renderTrigger != null && hasRegions && triggerName == null) {
+ setTriggerName(readAccessibleName(buttonRef.current));
+ }
+ }, [renderTrigger, hasRegions, triggerName]);
+
const handleLayerShow = useCallback(() => {
acceptedOpenRef.current = true;
resetFocusReturn();
@@ -978,15 +1065,38 @@ function DropdownMenuPopover({
}
}, [isControlled, onClick, onOpenChange, renderTrigger, resetFocusReturn]);
+ // The menu's name: the dialog around it with a header or footer, and the
+ // Back row of a drilled-in view ("Back to <this>"), both read it.
+ // The design system's button names the menu by its label. A custom trigger
+ // names it by reference (or the caller's `aria-label` does), so that name
+ // is read off the control as the menu opens.
+ const callerMenuLabel = rest['aria-label'];
+ const menuLabel =
+ renderTrigger != null
+ ? typeof callerMenuLabel === 'string' && callerMenuLabel.trim() !== ''
+ ? callerMenuLabel
+ : triggerName
+ : typeof button.label === 'string'
+ ? button.label
+ : undefined;
+
const popover = usePopover({
onHide: handleLayerHide,
onShow: handleLayerShow,
hasLightDismiss: true,
hasCloseButton: false,
hasAutoFocus: false,
- // The popup's own role="menu" is the exposed semantics; wrapping it in a
- // modal dialog would announce an unnamed dialog around the menu.
- role: 'none',
+ // Without a header or footer the popup's own role="menu" is the exposed
+ // semantics; a dialog around it would announce an extra container. With
+ // either, the popover holds controls that are not menu items, so it is a
+ // modal dialog named like the menu, with the menu inside it. A custom
+ // trigger's name is read off the control once it mounts; until then, or
+ // when the control exposes no readable name, the dialog takes the default
+ // menu label, so it is never unnamed and never loses its role.
+ role: hasRegions ? 'dialog' : 'none',
+ dialogLabel: hasRegions
+ ? (menuLabel ?? t(DEFAULT_BUTTON_I18N_KEY))
+ : undefined,
});
const closeMenu = useCallback(() => {
@@ -1085,6 +1195,55 @@ function DropdownMenuPopover({
});
}, [popover.isOpen, focusFirst, focusLast, listRef]);
+ // With a header or footer the popover is a modal dialog: Tab and Shift+Tab
+ // walk the header's controls, the menu as one stop, then the footer's
+ // controls, and wrap at either end. The key is handled here in full, so the
+ // popover's own focus trap, which listens on the document, never reads it a
+ // second time.
+ const moveDialogTab = useCallback(
+ (e: React.KeyboardEvent, isFromFlyout = false) => {
+ const menu = listRef.current;
+ if (menu == null) {
+ return;
+ }
+ e.preventDefault();
+ e.stopPropagation();
+ // A named radio group is one stop, as the browser's own Tab order has it.
+ const cycle = collapseRadioGroups(
+ [
+ ...tabbablesIn(headerRef.current),
+ menu,
+ ...tabbablesIn(footerRef.current),
+ ],
+ document.activeElement,
+ e.shiftKey,
+ );
+ if (cycle.length === 1) {
+ // Nothing else to reach: focus stays in the menu. From a flyout that
+ // has just closed itself, that is the menu's own stop.
+ if (isFromFlyout) {
+ menu.focus();
+ }
+ return;
+ }
+ const active = document.activeElement;
+ const menuIndex = cycle.indexOf(menu);
+ // A row, or a row of an open flyout, counts as the menu's stop.
+ let index = menu.contains(active)
+ ? menuIndex
+ : cycle.findIndex(el => el === active || el.contains(active));
+ if (index < 0) {
+ index = menuIndex;
+ }
+ const step = e.shiftKey ? -1 : 1;
+ const next = cycle[(index + step + cycle.length) % cycle.length];
+ if (!focusRegionControl(next)) {
+ menu.focus();
+ }
+ },
+ [listRef],
+ );
+
// Extend useListFocus with Enter/Space activation + typeahead
const listKeyDown = useCallback(
(e: React.KeyboardEvent) => {
@@ -1095,18 +1254,7 @@ function DropdownMenuPopover({
// itself as the key bubbled up, and the root moves focus on as Tab
// from one of its own rows would.
if (e.key === 'Tab' && hasRegions) {
- const region = e.shiftKey ? headerRef.current : footerRef.current;
- const tabbables = tabbablesIn(region);
- e.stopPropagation();
- const target = e.shiftKey
- ? tabbables[tabbables.length - 1]
- : tabbables[0];
- if (target != null) {
- e.preventDefault();
- }
- if (target == null || !focusRegionControl(target)) {
- closeMenu();
- }
+ moveDialogTab(e, true);
}
return;
}
@@ -1128,30 +1276,15 @@ function DropdownMenuPopover({
}
return;
}
- // APG menu-button pattern: Tab closes the menu. Menu items are
- // tabIndex={-1} so the focus trap has nothing trappable and Tab would
- // otherwise leak into the page while the menu stayed open (menus-5).
- // Do NOT preventDefault — closing restores focus to the trigger, and the
- // browser's default Tab then continues from there to the next element.
- // A header or footer with something Tab can reach in that direction
- // takes the Tab instead, and the menu stays open.
+ // With a header or footer the popover is a dialog and Tab wraps inside
+ // it. Without either, the APG menu-button pattern: Tab closes the menu.
+ // Menu items are tabIndex={-1} so the focus trap has nothing trappable
+ // and Tab would otherwise leak into the page while the menu stayed open
+ // (menus-5). Do NOT preventDefault — closing restores focus to the
+ // trigger, and the browser's default Tab then continues from there.
if (e.key === 'Tab') {
- const region = e.shiftKey ? headerRef.current : footerRef.current;
- const tabbables = tabbablesIn(region);
- if (tabbables.length > 0) {
- // From a row, the browser's Shift+Tab would stop on the menu element
- // itself — the row's ancestor and a Tab stop — before reaching the
- // header. The menu is one stop, so go straight to the header.
- if (e.shiftKey && e.target !== listRef.current) {
- e.preventDefault();
- // The popover's focus trap listens on the document and would read
- // this same Shift+Tab against the field just focused — the trap's
- // first element — and wrap to the footer. This key is handled.
- e.stopPropagation();
- if (!focusRegionControl(tabbables[tabbables.length - 1])) {
- closeMenu();
- }
- }
+ if (hasRegions) {
+ moveDialogTab(e);
return;
}
closeMenu();
@@ -1164,33 +1297,24 @@ function DropdownMenuPopover({
}
listNavKeyDown(e);
},
- [listNavKeyDown, closeMenu, typeahead, ownsEvent, listRef, hasRegions],
+ [
+ listNavKeyDown,
+ closeMenu,
+ typeahead,
+ ownsEvent,
+ hasRegions,
+ moveDialogTab,
+ ],
);
- // Tab past the last control of the footer, or Shift+Tab before the first
- // control of the header, leaves the menu as Tab from its rows does: the
- // menu closes, focus returns to the trigger, and the browser's own Tab
- // continues from there. Between the regions, Tab moves through the menu
- // as one stop.
+ // Tab from a header or footer control moves through the same dialog cycle.
const handleRegionKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
- if (e.key !== 'Tab') {
- return;
- }
- const tabbables = tabbablesIn(e.currentTarget);
- const isHeader = e.currentTarget === headerRef.current;
- const exit = isHeader
- ? e.shiftKey
- ? tabbables[0]
- : undefined
- : e.shiftKey
- ? undefined
- : tabbables[tabbables.length - 1];
- if (exit != null && exit === document.activeElement) {
- closeMenu();
+ if (e.key === 'Tab') {
+ moveDialogTab(e);
}
},
- [closeMenu],
+ [moveDialogTab],
);
const openAndFocus = useCallback(
@@ -1389,20 +1513,6 @@ function DropdownMenuPopover({
// The drill-in view stack for sub-menus on a phone.
const {drillIn, wrapContent} = useMenuDrillIn(isOpen);
- // The name a drilled-in view's Back row returns to: the menu's own name.
- // The design system's button names the menu by its label. A custom trigger
- // names it by reference (or the caller's `aria-label` does), so that name
- // is read off the control as the menu opens.
- const callerMenuLabel = rest['aria-label'];
- const menuLabel =
- renderTrigger != null
- ? typeof callerMenuLabel === 'string' && callerMenuLabel.trim() !== ''
- ? callerMenuLabel
- : triggerName
- : typeof button.label === 'string'
- ? button.label
- : undefined;
-
const resolvedMaxHeight = menuMaxHeight == null ? null : `${menuMaxHeight}px`;
// Context for compound items
const contextValue = useMemo<DropdownMenuContextValue>(
@@ -1463,9 +1573,9 @@ function DropdownMenuPopover({
// keeps the browser from drawing one after pointer input (see
// handleLayerHide), so its focus needs no bookkeeping here.
onFocus: () => {},
- 'aria-haspopup': 'menu',
+ 'aria-haspopup': hasRegions ? 'dialog' : 'menu',
'aria-expanded': isOpen,
- 'aria-controls': menuId,
+ 'aria-controls': hasRegions ? popover.id : menuId,
};
return (
@@ -1513,9 +1623,9 @@ function DropdownMenuPopover({
button.onFocus?.(event);
onFocusReturnTargetFocus();
}}
- aria-haspopup="menu"
+ aria-haspopup={hasRegions ? 'dialog' : 'menu'}
aria-expanded={isOpen}
- aria-controls={menuId}
+ aria-controls={hasRegions ? popover.id : menuId}
data-testid={testId}
/>
)}
diff --git a/packages/core/src/DropdownMenu/__tests__/MenuHeaderFooter.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/MenuHeaderFooter.a11y.chromium.spec.ts
index a6a51b5900..c95d5a3073 100644
--- a/packages/core/src/DropdownMenu/__tests__/MenuHeaderFooter.a11y.chromium.spec.ts
+++ b/packages/core/src/DropdownMenu/__tests__/MenuHeaderFooter.a11y.chromium.spec.ts
@@ -31,8 +31,8 @@ test.afterAll(async () => {
const STORY = 'core-dropdownmenu--header-and-footer';
// The trigger button only: the sub-menu row inside the menu also carries
-// aria-haspopup="menu".
-const TRIGGER = '#storybook-root button[aria-haspopup="menu"]';
+// aria-haspopup. With a header and footer the trigger opens a dialog.
+const TRIGGER = '#storybook-root button[aria-haspopup="dialog"]';
async function openMenu(page: Page) {
await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);
@@ -76,7 +76,7 @@ test('typing into the header field filters without moving to a row', async ({
await expect(page.getByRole('menuitem')).toHaveText(['Design', 'Move to']);
});
-test('Tab walks header, menu, footer, then closes to the trigger', async ({
+test('Tab walks header, menu, footer, and wraps at both ends', async ({
page,
}) => {
const menu = await openMenu(page);
@@ -97,9 +97,44 @@ test('Tab walks header, menu, footer, then closes to the trigger', async ({
await expect(page.getByTestId('created')).toHaveText('1');
await expect(menu).toBeVisible();
+ // Past the footer's last control, Tab wraps to the header; before the
+ // header's first, Shift+Tab wraps to the footer. The dialog stays open.
await page.keyboard.press('Tab');
- await expect(menu).toBeHidden();
- await expect(page.locator(TRIGGER)).toHaveAttribute('aria-expanded', 'false');
+ await expect(field).toBeFocused();
+ await expect(menu).toBeVisible();
+ await page.keyboard.press('Shift+Tab');
+ await expect(create).toBeFocused();
+ await expect(menu).toBeVisible();
+ await expect(page.locator(TRIGGER)).toHaveAttribute('aria-expanded', 'true');
+});
+
+test('the popover is a modal dialog around the menu, and the trigger points at it', async ({
+ page,
+}) => {
+ const menu = await openMenu(page);
+ const dialog = page.getByRole('dialog', {name: 'Labels'});
+ await expect(dialog).toBeVisible();
+ await expect(dialog).toHaveAttribute('aria-modal', 'true');
+ await expect(
+ dialog.getByRole('menu', {name: 'Labels', exact: true}),
+ ).toBeVisible();
+ await expect(
+ dialog.getByRole('textbox', {name: 'Filter labels'}),
+ ).toBeVisible();
+ await expect(
+ dialog.getByRole('button', {name: 'Create label'}),
+ ).toBeVisible();
+ const trigger = page.locator(TRIGGER);
+ await expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ const controlsDialog = await trigger.evaluate(el => {
+ const target = document.getElementById(
+ el.getAttribute('aria-controls') ?? '',
+ );
+ const dialogEl = document.querySelector('[role="dialog"]');
+ return target != null && dialogEl != null && target.contains(dialogEl);
+ });
+ expect(controlsDialog).toBe(true);
+ await expect(menu).toBeFocused();
});
test('Shift+Tab from a row goes straight to the header', async ({page}) => {