Skip to content

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

TypeScript

feat(DropdownMenu): header and footer hold controls beside the menu, never inside it (#7344)

Cindy Zhang61639ee1e706
diff --git a/.changeset/dropdown-menu-header-footer.md b/.changeset/dropdown-menu-header-footer.md
new file mode 100644
index 0000000000..3f3fc55fde
--- /dev/null
+++ b/.changeset/dropdown-menu-header-footer.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `DropdownMenu` takes `header` and `footer`: content above and below the rows that sits in the popover beside the menu, never inside it. This is the place for a filter field or a "Create" button. The menu still holds only its rows, so it stays a valid menu to a screen reader. The controls keep their own keys and presses, and Tab walks header, menu, footer. The bottom sheet shows them above and below the actions.
+
+@cixzhang
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3f4d8de465..26cff3a341 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1194,6 +1194,17 @@ jobs:
--project chromium \
--output table-min-width-output
+ # A DropdownMenu header and footer sit beside the menu, outside its
+ # role="menu" element, and join one Tab sequence with it. Focus order,
+ # the popover's focus trap, the keyboard-only ring and a finger tap on a
+ # footer control only exist in a real engine.
+ - name: Run DropdownMenu header and footer contract
+ run: |
+ pnpm exec playwright test \
+ packages/core/src/DropdownMenu/__tests__/MenuHeaderFooter.a11y.chromium.spec.ts \
+ --project chromium \
+ --output menu-header-footer-output
+
# The RichTextEditor "Markdown parity" stories render one Markdown
# document with core Markdown and RichTextEditor and measure where each
# block lands; geometry, the read/edit switch and the scroll anchor only
diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsx
index 20049f0b94..57a3c53a41 100644
--- a/apps/storybook/stories/DropdownMenu.stories.tsx
+++ b/apps/storybook/stories/DropdownMenu.stories.tsx
@@ -15,6 +15,8 @@ import {
DropdownMenuRadioItem,
DropdownMenuSubMenu,
} from '@astryxdesign/core/DropdownMenu';
+import {Button} from '@astryxdesign/core/Button';
+import {TextInput} from '@astryxdesign/core/TextInput';
import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
import {
PencilIcon,
@@ -1427,3 +1429,53 @@ export const SubmenuAdaptiveFixture: Story = {
</div>
),
};
+
+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.
+ */
+export const HeaderAndFooter: Story = {
+ render: () => {
+ const [query, setQuery] = useState('');
+ const [created, setCreated] = useState(0);
+ const visible = LABELS.filter(label =>
+ label.toLowerCase().includes(query.trim().toLowerCase()),
+ );
+ return (
+ <>
+ <DropdownMenu
+ button={{label: 'Labels'}}
+ header={
+ <TextInput
+ label="Filter labels"
+ isLabelHidden
+ placeholder="Filter labels"
+ value={query}
+ onChange={setQuery}
+ />
+ }
+ footer={
+ <Button
+ label="Create label"
+ variant="ghost"
+ onClick={() => setCreated(count => count + 1)}
+ />
+ }>
+ {visible.map(label => (
+ <DropdownMenuItem key={label} label={label} onClick={() => {}} />
+ ))}
+ <DropdownMenuSubMenu label="Move to">
+ <DropdownMenuItem label="Archive" onClick={() => {}} />
+ <DropdownMenuItem label="Backlog" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+ <output data-testid="created">{created}</output>
+ </>
+ );
+ },
+};
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index b4de7ee905..745eadc897 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -227,6 +227,18 @@ export const docs = {
description:
'Maximum height in pixels for the popover presentation, for a menu that must fit its rows. Lifts the default 300px cap; the viewport still bounds it.',
},
+ {
+ 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.',
+ },
+ {
+ 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.',
+ },
{
name: 'placement',
type: "'above' | 'below' | 'start' | 'end'",
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
index ec60514578..177e8c6ed1 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md
+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
@@ -17,6 +17,7 @@ verified_by:
packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx,
packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts,
packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts,
+ packages/core/src/DropdownMenu/__tests__/MenuHeaderFooter.a11y.chromium.spec.ts,
packages/core/src/BottomSheet/BottomSheet.test.tsx,
packages/core/src/List/List.test.tsx,
packages/core/src/Indicator/Indicator.test.tsx,
@@ -85,35 +86,37 @@ Consumer migration instructions belong in consumer docs and release notes.
## Public concepts
Consumer props, item shapes, subcomponents, and presentation policy remain
-documented in `DropdownMenu.doc.mjs` and the subcomponent docs. Two component-local concepts are added, by DEC-2 and DEC-3; each keeps its
-released default.
+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. |
+| 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. |
## 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 |
+| 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 |
### Allowed variation
@@ -261,21 +264,22 @@ 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` |
-| 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` |
+| 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` |
+| 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. |
## Decision log
@@ -440,3 +444,24 @@ The value is a number of pixels. Rejected: an arbitrary CSS length (`50vh`,
`calc(...)`), which is product-shaped tuning on a shared component that
`spec:AST-002` does not admit, and which lets a caller write a cap the
viewport term cannot reason about.
+
+### DEC-8 — Controls beside the rows go in `header` and `footer`
+
+**Reference:** `component:DropdownMenu/DEC-8`
+**Decider:** `cixzhang`, 2026-10-11
+
+`role="menu"` admits only menu items, groups and separators. A filter field
+or a "Create" button placed among the rows makes the menu invalid to a screen
+reader, and makes the menu's key handling and press model fight the control.
+The control belongs beside the menu, not in it. `header` and `footer` place it
+there: in the same popover or sheet, outside the menu element. Outside the
+menu element, the menu never claims the control's keys or presses. Because
+`children` stay rows only, nothing can be placed between rows; the component
+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:
+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.
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 68a9f494ca..0dc8a73920 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -19,6 +19,7 @@ import {DropdownMenu} from './DropdownMenu';
import {DropdownMenuItem} from './DropdownMenuItem';
import {DropdownMenuDivider} from './DropdownMenuDivider';
import {DropdownMenuGroup} from './DropdownMenuGroup';
+import {DropdownMenuSubMenu} from './DropdownMenuSubMenu';
import {Divider} from '../Divider';
import {rtlStyles} from '../utils';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
@@ -3357,3 +3358,459 @@ describe('DropdownMenu keyboard', () => {
expect(onClick).toHaveBeenCalledTimes(1);
});
});
+
+describe('DropdownMenu header and footer', () => {
+ function LabelsMenu({onCreate}: {onCreate?: () => void}) {
+ return (
+ <DropdownMenu
+ button={{label: 'Labels'}}
+ header={<input aria-label="Filter labels" />}
+ footer={
+ <button type="button" onClick={onCreate}>
+ Create label
+ </button>
+ }>
+ <DropdownMenuItem label="Bug" />
+ <DropdownMenuItem label="Feature" />
+ </DropdownMenu>
+ );
+ }
+
+ async function open() {
+ const user = userEvent.setup();
+ render(<LabelsMenu />);
+ await user.click(screen.getByRole('button', {name: /Labels/}));
+ const menu = screen.getByRole('menu', {hidden: true});
+ // A pointer open focuses the menu itself; let that land first.
+ await waitFor(() => expect(menu).toHaveFocus());
+ return {user, menu};
+ }
+
+ it('renders the regions in the popover, outside the role="menu" element', async () => {
+ const {menu} = await open();
+ const field = screen.getByRole('textbox', {
+ name: 'Filter labels',
+ hidden: true,
+ });
+ const create = screen.getByRole('button', {
+ name: 'Create label',
+ hidden: true,
+ });
+ // The menu holds only its rows.
+ expect(menu).not.toContainElement(field);
+ expect(menu).not.toContainElement(create);
+ expect(
+ Array.from(menu.querySelectorAll('[role]')).map(el =>
+ el.getAttribute('role'),
+ ),
+ ).toEqual(['menuitem', 'menuitem']);
+ // Header before the menu, footer after it, in one popover.
+ const popoverEl = menu.closest('[popover]');
+ expect(popoverEl).toContainElement(field);
+ expect(popoverEl).toContainElement(create);
+ expect(
+ field.compareDocumentPosition(menu) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ menu.compareDocumentPosition(create) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it('makes the menu one Tab stop between the regions', async () => {
+ const {menu} = await open();
+ expect(menu).toHaveAttribute('tabindex', '0');
+ });
+
+ it('Tab from the menu moves on to the footer and keeps the menu open', async () => {
+ const {menu} = await open();
+ const hide = vi.mocked(HTMLElement.prototype.hidePopover);
+ hide.mockClear();
+ fireEvent.keyDown(menu, {key: 'Tab'});
+ expect(hide).not.toHaveBeenCalled();
+ fireEvent.keyDown(menu, {key: 'Tab', shiftKey: true});
+ expect(hide).not.toHaveBeenCalled();
+ });
+
+ it('Shift+Tab from a row moves straight to the header and keeps the menu open', async () => {
+ const {menu} = await open();
+ const hide = vi.mocked(HTMLElement.prototype.hidePopover);
+ hide.mockClear();
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ const row = screen.getByRole('menuitem', {name: 'Bug', hidden: true});
+ await waitFor(() => expect(row).toHaveFocus());
+ fireEvent.keyDown(row, {key: 'Tab', shiftKey: true});
+ expect(
+ screen.getByRole('textbox', {name: 'Filter labels', hidden: true}),
+ ).toHaveFocus();
+ expect(hide).not.toHaveBeenCalled();
+ });
+
+ it('a pointer open draws no focus ring on the menu; keyboard focus on it does', async () => {
+ const {menu} = await open();
+ // Opened with a pointer: the menu is focused but must not ring.
+ const ringClasses = stylex
+ .props(focusOutlineStyles.focusVisible)
+ .className!.split(' ')
+ .filter(Boolean);
+ const hasRing = () => ringClasses.every(c => menu.classList.contains(c));
+ expect(menu).toHaveFocus();
+ expect(hasRing()).toBe(false);
+ // Keyboard: leave to the header and come back by Tab.
+ const field = screen.getByRole('textbox', {
+ name: 'Filter labels',
+ hidden: true,
+ });
+ fireEvent.keyDown(document, {key: 'Tab', shiftKey: true});
+ act(() => field.focus());
+ fireEvent.keyDown(document, {key: 'Tab'});
+ act(() => menu.focus());
+ await waitFor(() => expect(hasRing()).toBe(true));
+ });
+
+ describe('with only hidden controls in a region', () => {
+ async function openHidden(
+ header: React.ReactNode,
+ footer: React.ReactNode,
+ ) {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ button={{label: 'Labels'}}
+ header={header}
+ footer={footer}>
+ <DropdownMenuItem label="Bug" />
+ <DropdownMenuSubMenu label="Move to">
+ <DropdownMenuItem label="Folder A" />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ const trigger = screen.getByRole('button', {name: /Labels/});
+ await user.click(trigger);
+ const menu = screen.getByRole('menu', {name: 'Labels', hidden: true});
+ await waitFor(() => expect(menu).toHaveFocus());
+ const hide = vi.mocked(HTMLElement.prototype.hidePopover);
+ hide.mockClear();
+ return {user, trigger, menu, hide};
+ }
+
+ it.each([
+ [
+ 'hidden',
+ <button key="h" type="button" hidden>
+ Gone
+ </button>,
+ ],
+ [
+ 'display: none',
+ <button key="d" type="button" style={{display: 'none'}}>
+ Gone
+ </button>,
+ ],
+ [
+ 'visibility: hidden',
+ <button key="v" type="button" style={{visibility: 'hidden'}}>
+ Gone
+ </button>,
+ ],
+ ])(
+ 'treats a %s footer control as unreachable: Tab from the menu closes it',
+ async (_label, control) => {
+ const {menu, hide} = await openHidden(null, control);
+ fireEvent.keyDown(menu, {key: 'Tab'});
+ expect(hide).toHaveBeenCalled();
+ },
+ );
+
+ it('treats a footer control inside a display: none wrapper as unreachable', async () => {
+ const {menu, hide} = await openHidden(
+ null,
+ <div style={{display: 'none'}}>
+ <button type="button">Create label</button>
+ </div>,
+ );
+ fireEvent.keyDown(menu, {key: 'Tab'});
+ expect(hide).toHaveBeenCalled();
+ });
+
+ it('treats a header control inside a display: none wrapper as unreachable: Shift+Tab from a row closes', async () => {
+ const {menu, hide} = await openHidden(
+ <div style={{display: 'none'}}>
+ <input aria-label="Filter labels" />
+ </div>,
+ null,
+ );
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ const row = screen.getByRole('menuitem', {name: 'Bug', hidden: true});
+ await waitFor(() => expect(row).toHaveFocus());
+ fireEvent.keyDown(row, {key: 'Tab', shiftKey: true});
+ expect(hide).toHaveBeenCalled();
+ });
+
+ it('Tab past the last visible footer control closes, ignoring a wrapped hidden one after it', async () => {
+ const {hide} = await openHidden(
+ null,
+ <>
+ <button type="button">Create label</button>
+ <div style={{display: 'none'}}>
+ <button type="button">Gone</button>
+ </div>
+ </>,
+ );
+ const create = screen.getByRole('button', {
+ name: 'Create label',
+ hidden: true,
+ });
+ act(() => create.focus());
+ fireEvent.keyDown(create, {key: 'Tab'});
+ expect(hide).toHaveBeenCalled();
+ });
+
+ it('Tab from an open sub-menu closes the menu when the footer control is in a hidden wrapper', async () => {
+ const {user, menu} = await openHidden(
+ null,
+ <div style={{display: 'none'}}>
+ <button type="button">Create label</button>
+ </div>,
+ );
+ const subTrigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ act(() => subTrigger.focus());
+ await user.keyboard('{ArrowRight}');
+ const folder = screen.getByRole('menuitem', {
+ name: 'Folder A',
+ hidden: true,
+ });
+ 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');
+ });
+
+ it('treats a hidden header control as unreachable: Shift+Tab from a row closes the menu', async () => {
+ const {menu, hide} = await openHidden(
+ <input aria-label="Filter labels" hidden />,
+ null,
+ );
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ const row = screen.getByRole('menuitem', {name: 'Bug', hidden: true});
+ await waitFor(() => expect(row).toHaveFocus());
+ fireEvent.keyDown(row, {key: 'Tab', shiftKey: true});
+ expect(hide).toHaveBeenCalled();
+ });
+
+ it('Tab past the last visible footer control closes, ignoring a hidden one after it', async () => {
+ const {hide} = await openHidden(
+ null,
+ <>
+ <button type="button">Create label</button>
+ <button type="button" style={{display: 'none'}}>
+ Gone
+ </button>
+ </>,
+ );
+ const create = screen.getByRole('button', {
+ name: 'Create label',
+ hidden: true,
+ });
+ act(() => create.focus());
+ fireEvent.keyDown(create, {key: 'Tab'});
+ expect(hide).toHaveBeenCalled();
+ });
+
+ it('Tab from an open sub-menu closes the menu when the footer holds only hidden controls', async () => {
+ const {user, menu} = await openHidden(
+ null,
+ <button type="button" hidden>
+ Gone
+ </button>,
+ );
+ const subTrigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ act(() => subTrigger.focus());
+ await user.keyboard('{ArrowRight}');
+ const folder = screen.getByRole('menuitem', {
+ name: 'Folder A',
+ hidden: true,
+ });
+ 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');
+ });
+ });
+
+ describe('with a sub-menu open', () => {
+ async function openFlyout() {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ button={{label: 'Labels'}}
+ header={<input aria-label="Filter labels" />}
+ footer={<button type="button">Create label</button>}>
+ <DropdownMenuItem label="Bug" />
+ <DropdownMenuSubMenu label="Move to">
+ <DropdownMenuItem label="Folder A" />
+ <DropdownMenuItem label="Folder B" />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Labels/}));
+ const root = screen.getByRole('menu', {name: 'Labels', hidden: true});
+ await waitFor(() => expect(root).toHaveFocus());
+ const subTrigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ act(() => subTrigger.focus());
+ await user.keyboard('{ArrowRight}');
+ await waitFor(() =>
+ expect(subTrigger).toHaveAttribute('aria-expanded', 'true'),
+ );
+ const folder = screen.getByRole('menuitem', {
+ name: 'Folder A',
+ hidden: true,
+ });
+ await waitFor(() => expect(folder).toHaveFocus());
+ const hide = vi.mocked(HTMLElement.prototype.hidePopover);
+ return {root, subTrigger, folder, hide};
+ }
+
+ it('Tab from a flyout row closes the flyout and moves to the footer', async () => {
+ const {root, subTrigger, folder} = await openFlyout();
+ fireEvent.keyDown(folder, {key: 'Tab'});
+ expect(subTrigger).toHaveAttribute('aria-expanded', 'false');
+ expect(
+ screen.getByRole('button', {name: 'Create label', hidden: true}),
+ ).toHaveFocus();
+ expect(root.closest('[popover]')).toHaveAttribute('popover-open');
+ });
+
+ it('Shift+Tab from a flyout row closes the flyout and moves to the header', async () => {
+ const {subTrigger, folder} = await openFlyout();
+ fireEvent.keyDown(folder, {key: 'Tab', shiftKey: true});
+ expect(subTrigger).toHaveAttribute('aria-expanded', 'false');
+ expect(
+ screen.getByRole('textbox', {name: 'Filter labels', hidden: true}),
+ ).toHaveFocus();
+ });
+ });
+
+ it('Tab past the last footer control closes the menu', async () => {
+ await open();
+ const hide = vi.mocked(HTMLElement.prototype.hidePopover);
+ hide.mockClear();
+ const create = screen.getByRole('button', {
+ name: 'Create label',
+ hidden: true,
+ });
+ create.focus();
+ fireEvent.keyDown(create, {key: 'Tab', shiftKey: true});
+ expect(hide).not.toHaveBeenCalled();
+ create.focus();
+ expect(create).toHaveFocus();
+ fireEvent.keyDown(create, {key: 'Tab'});
+ expect(hide).toHaveBeenCalled();
+ expect(screen.getByRole('button', {name: /Labels/})).toHaveFocus();
+ });
+
+ it('Shift+Tab before the first header control closes the menu', async () => {
+ await open();
+ const hide = vi.mocked(HTMLElement.prototype.hidePopover);
+ hide.mockClear();
+ const field = screen.getByRole('textbox', {
+ name: 'Filter labels',
+ hidden: true,
+ });
+ field.focus();
+ fireEvent.keyDown(field, {key: 'Tab'});
+ expect(hide).not.toHaveBeenCalled();
+ field.focus();
+ expect(field).toHaveFocus();
+ fireEvent.keyDown(field, {key: 'Tab', shiftKey: true});
+ expect(hide).toHaveBeenCalled();
+ });
+
+ it('leaves keys typed in the header to the field', async () => {
+ const {user} = await open();
+ const field = screen.getByRole('textbox', {
+ name: 'Filter labels',
+ hidden: true,
+ });
+ await user.click(field);
+ await user.keyboard('bug');
+ expect(field).toHaveValue('bug');
+ expect(field).toHaveFocus();
+ });
+
+ it('a footer button acts on its own click and the menu stays open', async () => {
+ const user = userEvent.setup();
+ const onCreate = vi.fn();
+ render(<LabelsMenu onCreate={onCreate} />);
+ const trigger = screen.getByRole('button', {name: /Labels/});
+ await user.click(trigger);
+ await user.click(
+ screen.getByRole('button', {name: 'Create label', hidden: true}),
+ );
+ expect(onCreate).toHaveBeenCalledTimes(1);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('without a header or footer, Tab still closes and the menu stays out of the Tab order', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem label="Item 1" />
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const menu = screen.getByRole('menu', {hidden: true});
+ expect(menu).toHaveAttribute('tabindex', '-1');
+ expect(menu.parentElement?.closest('[role="menu"]')).toBeNull();
+ fireEvent.keyDown(menu, {key: 'Tab'});
+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();
+ });
+
+ it('a false or empty region renders no wrapper', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}} header={false} footer="">
+ <DropdownMenuItem label="Item 1" />
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const menu = screen.getByRole('menu', {hidden: true});
+ expect(menu).toHaveAttribute('tabindex', '-1');
+ });
+
+ it('renders the regions above and below the actions in the bottom sheet', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ button={{label: 'Labels'}}
+ presentation="bottom-sheet"
+ header={<input aria-label="Filter labels" />}
+ footer={<button type="button">Create label</button>}
+ items={[{label: 'Bug'}, {label: 'Feature'}]}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: /Labels/}));
+ const sheet = screen.getByRole('dialog', {name: 'Labels'});
+ const field = screen.getByRole('textbox', {name: 'Filter labels'});
+ const bug = screen.getByRole('button', {name: 'Bug'});
+ const create = screen.getByRole('button', {name: 'Create label'});
+ expect(sheet).toContainElement(field);
+ expect(sheet).toContainElement(create);
+ expect(
+ field.compareDocumentPosition(bug) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ bug.compareDocumentPosition(create) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index e17991ca6d..3720c10503 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -69,6 +69,8 @@ import type {MenuPressPointerType} from '../hooks/menuPressGesture';
import {useTypeahead} from '../hooks/useTypeahead';
import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';
import {useMenuOverflow} from './useMenuOverflow';
+import {MenuRegionsContext} from './menuRegionsContext';
+import {getFocusableElements} from '../hooks/useFocusTrap';
import {useDevWarning} from '../hooks/useDevWarning';
import {useMenuDrillIn} from './useMenuDrillIn';
import {resolveMenuWidth} from './menuWidth';
@@ -88,10 +90,13 @@ import {
durationVars,
easeVars,
} from '../theme/tokens.stylex';
-import {mergeProps, rtlStyles} from '../utils';
+import {isRenderable, mergeProps, rtlStyles} from '../utils';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
-import {useInteractionModalityTracking} from '../utils/interactionModality';
+import {
+ getInteractionModality,
+ useInteractionModalityTracking,
+} from '../utils/interactionModality';
import {useTranslator} from '../i18n';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
@@ -102,6 +107,54 @@ const MENU_MAX_BLOCK_SIZE = `min(${MENU_BLOCK_CAP}, ${layerViewportInset.maxBloc
const MENU_MAX_BLOCK_SIZE_FALLBACK = `min(${MENU_BLOCK_CAP}, ${layerViewportInset.maxBlockSizeFallback})`;
const MENU_TRIGGER_OPEN_BACKGROUND = `linear-gradient(${colorVars['--color-overlay-pressed']}, ${colorVars['--color-overlay-pressed']})`;
+/**
+ * The elements Tab reaches inside a header or footer region, in order. Hidden
+ * controls (`hidden`, `display: none`, `visibility: hidden`, inert or
+ * 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.
+ */
+function tabbablesIn(region: HTMLElement | null): HTMLElement[] {
+ if (region == null) {
+ return [];
+ }
+ return getFocusableElements(region).filter(
+ element => element.tabIndex >= 0 && !isInsideHiddenWrapper(element, region),
+ );
+}
+
+/**
+ * Whether a `display: none` ancestor between the element and its region hides
+ * it — a control in a wrapper hidden at some widths, say. The trap's test reads
+ * only the element's own display.
+ */
+function isInsideHiddenWrapper(
+ element: HTMLElement,
+ region: HTMLElement,
+): boolean {
+ if (typeof window === 'undefined' || !window.getComputedStyle) {
+ return false;
+ }
+ for (
+ let node = element.parentElement;
+ node != null && node !== region.parentElement;
+ node = node.parentElement
+ ) {
+ if (window.getComputedStyle(node).display === 'none') {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * 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.
+ */
+function focusRegionControl(element: HTMLElement): boolean {
+ element.focus();
+ return element.ownerDocument.activeElement === element;
+}
+
const styles = stylex.create({
triggerOpen: {
backgroundImage: MENU_TRIGGER_OPEN_BACKGROUND,
@@ -148,6 +201,27 @@ const styles = stylex.create({
overflowX: 'hidden',
overscrollBehavior: 'contain',
},
+ // With a header or footer, the regions and the menu share one column under
+ // the menu's block cap: the regions keep their height and the menu shrinks
+ // and scrolls between them.
+ regionsFrame: {
+ boxSizing: 'border-box',
+ display: 'flex',
+ flexDirection: 'column',
+ maxHeight: stylex.firstThatWorks(
+ MENU_MAX_BLOCK_SIZE,
+ MENU_MAX_BLOCK_SIZE_FALLBACK,
+ ),
+ },
+ menuInFrame: {
+ flexGrow: 1,
+ flexShrink: 1,
+ minBlockSize: 0,
+ },
+ region: {
+ flexShrink: 0,
+ padding: spacingVars['--spacing-1'],
+ },
// Scroll ownership by the browser's own signal. A menu whose rows fit keeps
// every one-finger move: a slide over its rows stays a slide. One that
// scrolls lets the browser pan it vertically and cancel the press when it
@@ -216,6 +290,12 @@ const bottomSheetStyles = stylex.create({
viewHeading: {
outline: 'none',
},
+ // Caller content above or below the action list, inset to the list's
+ // content edge.
+ region: {
+ paddingInline: spacingVars['--spacing-3'],
+ paddingBlock: spacingVars['--spacing-2'],
+ },
});
// =============================================================================
@@ -371,6 +451,17 @@ interface DropdownMenuBaseProps extends BaseProps {
* @default 'start'
*/
alignment?: LayerAlignment;
+ /**
+ * Content above the menu's rows and outside the menu itself — a filter
+ * field, a toggle. The menu holds only its rows, so a control that is not
+ * a row goes here or in `footer`, never among the rows.
+ */
+ header?: ReactNode;
+ /**
+ * Content below the menu's rows and outside the menu itself — a "Create"
+ * button. See `header`.
+ */
+ footer?: ReactNode;
'data-testid'?: string;
}
@@ -508,6 +599,8 @@ function DropdownMenuBottomSheet({
menuMaxHeight: _menuMaxHeight,
placement: _placement,
alignment: _alignment,
+ header,
+ footer,
className,
style,
xstyle,
@@ -718,11 +811,17 @@ function DropdownMenuBottomSheet({
{currentTitle}
</Heading>
</div>
+ {isRenderable(header) && (
+ <div {...stylex.props(bottomSheetStyles.region)}>{header}</div>
+ )}
<MenuBottomSheetActionList
items={currentItems}
onSelect={handleSelect}
onOpenSubmenu={item => setSubmenuPath(path => [...path, item])}
/>
+ {isRenderable(footer) && (
+ <div {...stylex.props(bottomSheetStyles.region)}>{footer}</div>
+ )}
</div>
</MenuBottomSheet>
</>
@@ -741,6 +840,8 @@ function DropdownMenuPopover({
placement = 'below',
alignment = 'start',
presentation: _presentation,
+ header,
+ footer,
className,
style,
xstyle,
@@ -786,6 +887,16 @@ function DropdownMenuPopover({
resetFocusReturn,
} = useFocusReturnVisibility();
const contentRef = useRef<HTMLDivElement | null>(null);
+ const headerRef = useRef<HTMLDivElement | null>(null);
+ const footerRef = useRef<HTMLDivElement | null>(null);
+ const hasRegions = useMemo(
+ () => isRenderable(header) || isRenderable(footer),
+ [header, footer],
+ );
+ // Whether the menu element itself took focus from the keyboard. A pointer
+ // open focuses it programmatically, and pointer history must not paint the
+ // keyboard ring (architecture:interaction-modality INV1).
+ const [isMenuKeyboardFocused, setIsMenuKeyboardFocused] = useState(false);
// The press model is mounted below (it needs the popover); the hide path
// above it ends the gesture in flight through this ref.
const cancelMenuPressRef = useRef<() => void>(() => {});
@@ -966,6 +1077,23 @@ function DropdownMenuPopover({
// A submenu flyout renders inline inside this menu; its key events bubble
// up here. Let that level own them — only handle events from this level.
if (!ownsEvent(e)) {
+ // Except Tab with a header or footer: each open flyout has closed
+ // 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();
+ }
+ }
return;
}
if (e.key === 'Enter' || e.key === ' ') {
@@ -991,7 +1119,27 @@ function DropdownMenuPopover({
// 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.
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();
+ }
+ }
+ return;
+ }
closeMenu();
return;
}
@@ -1002,7 +1150,33 @@ function DropdownMenuPopover({
}
listNavKeyDown(e);
},
- [listNavKeyDown, closeMenu, typeahead, ownsEvent],
+ [listNavKeyDown, closeMenu, typeahead, ownsEvent, listRef, hasRegions],
+ );
+
+ // 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.
+ 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();
+ }
+ },
+ [closeMenu],
);
const openAndFocus = useCallback(
@@ -1215,6 +1389,38 @@ function DropdownMenuPopover({
);
const hasOverflow = useMenuOverflow(listRef, menuContent, popover.isOpen);
+ // The header and footer sit beside the menu inside the popover, never inside
+ // the role="menu" element: a menu holds only its rows.
+ const renderWithRegions = (menu: ReactNode): ReactNode =>
+ hasRegions ? (
+ <div
+ {...stylex.props(
+ styles.regionsFrame,
+ resolvedMaxHeight != null &&
+ dynamicStyles.menuMaxHeight(resolvedMaxHeight),
+ )}>
+ {isRenderable(header) && (
+ <div
+ ref={headerRef}
+ onKeyDown={handleRegionKeyDown}
+ {...stylex.props(styles.region)}>
+ {header}
+ </div>
+ )}
+ {menu}
+ {isRenderable(footer) && (
+ <div
+ ref={footerRef}
+ onKeyDown={handleRegionKeyDown}
+ {...stylex.props(styles.region)}>
+ {footer}
+ </div>
+ )}
+ </div>
+ ) : (
+ menu
+ );
+
const triggerProps: DropdownMenuTriggerProps = {
ref: el => {
buttonRef.current = el;
@@ -1286,52 +1492,75 @@ function DropdownMenuPopover({
/>
)}
{popover.render(
- <div
- {...rest}
- ref={el => {
- listRef.current = el;
- contentRef.current =
- el?.closest<HTMLDivElement>('[popover]') ?? null;
- }}
- id={menuId}
- role="menu"
- // Pointer opens focus the container so arrows, typeahead, Escape and
- // Tab remain owned by the menu without pre-highlighting an item.
- // An overflowing menu joins the Tab order so its scrollable region is
- // keyboard-accessible; Tab still dismisses through listKeyDown.
- tabIndex={hasOverflow ? 0 : -1}
- // Give the menu an accessible name from its trigger's label, so
- // screen readers announce e.g. "Actions menu" rather than an unnamed
- // menu (menus-13). A custom trigger names it by reference.
- aria-label={
- renderTrigger != null
- ? (rest['aria-label'] as string | undefined)
- : button.label
- }
- aria-labelledby={
- renderTrigger != null && rest['aria-label'] == null
- ? triggerId
- : (rest['aria-labelledby'] as string | undefined)
- }
- onKeyDown={listKeyDown}
- {...menuPress.menuProps}
- {...mergeProps(
- themeProps('dropdown-menu'),
- stylex.props(
- styles.dropdown,
- resolvedMaxHeight != null &&
- dynamicStyles.menuMaxHeight(resolvedMaxHeight),
- hasOverflow ? styles.touchPanYPinchZoom : styles.touchPinchZoom,
- hasOverflow && styles.scrollable,
- xstyle,
- ),
- className,
- style,
- )}>
- <DropdownMenuContext value={contextValue}>
- {menuContent}
- </DropdownMenuContext>
- </div>,
+ renderWithRegions(
+ <div
+ {...rest}
+ ref={el => {
+ listRef.current = el;
+ contentRef.current =
+ el?.closest<HTMLDivElement>('[popover]') ?? null;
+ }}
+ id={menuId}
+ role="menu"
+ // Pointer opens focus the container so arrows, typeahead, Escape and
+ // Tab remain owned by the menu without pre-highlighting an item.
+ // An overflowing menu joins the Tab order so its scrollable region is
+ // keyboard-accessible; Tab still dismisses through listKeyDown. With
+ // a header or footer the menu is one Tab stop between them.
+ tabIndex={hasOverflow || hasRegions ? 0 : -1}
+ // Give the menu an accessible name from its trigger's label, so
+ // screen readers announce e.g. "Actions menu" rather than an unnamed
+ // menu (menus-13). A custom trigger names it by reference.
+ aria-label={
+ renderTrigger != null
+ ? (rest['aria-label'] as string | undefined)
+ : button.label
+ }
+ aria-labelledby={
+ renderTrigger != null && rest['aria-label'] == null
+ ? triggerId
+ : (rest['aria-labelledby'] as string | undefined)
+ }
+ onKeyDown={listKeyDown}
+ onFocus={event => {
+ (
+ rest.onFocus as
+ React.FocusEventHandler<HTMLDivElement> | undefined
+ )?.(event);
+ if (event.target === event.currentTarget) {
+ setIsMenuKeyboardFocused(
+ getInteractionModality() === 'keyboard',
+ );
+ }
+ }}
+ {...menuPress.menuProps}
+ {...mergeProps(
+ themeProps('dropdown-menu'),
+ stylex.props(
+ styles.dropdown,
+ resolvedMaxHeight != null &&
+ dynamicStyles.menuMaxHeight(resolvedMaxHeight),
+ hasOverflow ? styles.touchPanYPinchZoom : styles.touchPinchZoom,
+ hasOverflow && styles.scrollable,
+ hasRegions && styles.menuInFrame,
+ // Between a header and a footer the menu is a Tab stop, so
+ // keyboard focus on it must be visible (the base style removes
+ // the ring for the pointer-open focus target).
+ hasRegions &&
+ isMenuKeyboardFocused &&
+ focusOutlineStyles.focusVisible,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ <MenuRegionsContext value={hasRegions}>
+ <DropdownMenuContext value={contextValue}>
+ {menuContent}
+ </DropdownMenuContext>
+ </MenuRegionsContext>
+ </div>,
+ ),
{
placement,
alignment,
diff --git a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs
index efbf99ee2a..b02ddfbaf1 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs
@@ -29,12 +29,14 @@ export const docs = {
{
name: 'value',
type: 'boolean',
- description: 'Whether the item is checked. Controlled; pair with onChange.',
+ description:
+ 'Whether the item is checked. Controlled; pair with onChange.',
},
{
name: 'onChange',
type: '(checked: boolean) => void',
- description: 'Callback fired with the next checked state when the item is toggled.',
+ description:
+ 'Callback fired with the next checked state when the item is toggled.',
},
{
name: 'isDisabled',
@@ -88,7 +90,8 @@ export const docsDense = {
name: 'DropdownMenuCheckboxItem',
isHiddenFromOverview: true,
displayName: 'Dropdown Menu Checkbox Item',
- description: 'checkable menu item (menuitemcheckbox); independent boolean toggle',
+ description:
+ 'checkable menu item (menuitemcheckbox); independent boolean toggle',
propDescriptions: {
label: 'primary label text',
description: 'secondary text below label',
diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioGroup.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuRadioGroup.doc.mjs
index 83254cf30a..fef9014eb8 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuRadioGroup.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioGroup.doc.mjs
@@ -78,7 +78,8 @@ export const docsZh = {
propDescriptions: {
value: '组中当前选中的值。尚无选中项时传 undefined。',
onChange: '所选值变化时触发的回调。',
- label: '组的无障碍名称,作为 aria-label 应用,以便屏幕阅读器将单选项作为命名集合朗读,例如“Sort by”。必需。当名称已作为可见元素存在时,可改用 aria-labelledby(通过基础属性)。',
+ label:
+ '组的无障碍名称,作为 aria-label 应用,以便屏幕阅读器将单选项作为命名集合朗读,例如“Sort by”。必需。当名称已作为可见元素存在时,可改用 aria-labelledby(通过基础属性)。',
hasCloseOnSelect: '选择某值是否关闭菜单。默认关闭。',
children: '组成该组的 DropdownMenuRadioItem。',
},
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
index 7a9fb4b987..ba8a9c868d 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
@@ -50,6 +50,7 @@
*/
import React, {
+ use,
useCallback,
useEffect,
useId,
@@ -63,6 +64,7 @@ import {createPortal} from 'react-dom';
import * as stylex from '@stylexjs/stylex';
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {Spinner} from '../Spinner';
+import {MenuRegionsContext} from './menuRegionsContext';
import {Item} from '../Item';
import {useLayer} from '../Layer/useLayer';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
@@ -356,6 +358,7 @@ export function DropdownMenuSubMenu(
const t = useTranslator();
const menuCtx = useDropdownMenuContext();
+ const rootHasRegions = use(MenuRegionsContext);
const menuSize = menuCtx?.menuSize ?? 'md';
const canOpen = !isDisabled;
@@ -655,6 +658,13 @@ export function DropdownMenuSubMenu(
// stopPropagation needed — each level self-filters.
const handleContentKeyDown = useCallback(
(e: React.KeyboardEvent) => {
+ // In a menu with a header or footer, Tab leaves the whole flyout stack:
+ // every open level closes as the key bubbles past it — this one's own
+ // rows or a deeper level's — and the root menu moves focus to a region.
+ if (e.key === 'Tab' && rootHasRegions) {
+ close({focusTrigger: false});
+ return;
+ }
if (!ownsEvent(e)) {
return;
}
@@ -702,7 +712,7 @@ export function DropdownMenuSubMenu(
}
listNavKeyDown(e);
},
- [ownsEvent, close, listNavKeyDown, typeahead, menuRef],
+ [ownsEvent, close, listNavKeyDown, typeahead, menuRef, rootHasRegions],
);
// Re-provide the menu context so nested items behave exactly like top-level
diff --git a/packages/core/src/DropdownMenu/__tests__/MenuHeaderFooter.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/MenuHeaderFooter.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..a6a51b5900
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/MenuHeaderFooter.a11y.chromium.spec.ts
@@ -0,0 +1,195 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MenuHeaderFooter.a11y.chromium.spec.ts
+ * @input The `Core/DropdownMenu` HeaderAndFooter story in a built Storybook
+ * and real keyboard and mouse input.
+ * @output Real-engine proof that a menu's header and footer sit beside the
+ * menu rather than inside it, keep their own keys and presses, and join one
+ * Tab sequence with the menu.
+ * @position Run with `pnpm test:a11y-contract`.
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+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"]';
+
+async function openMenu(page: Page) {
+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);
+ await page.locator(TRIGGER).click();
+ const menu = page.getByRole('menu', {name: 'Labels', exact: true});
+ await expect(menu).toBeVisible();
+ // A pointer open focuses the menu itself; let that land first.
+ await expect(menu).toBeFocused();
+ return menu;
+}
+
+test('the menu holds only its rows; the field and button sit beside it', async ({
+ page,
+}) => {
+ const menu = await openMenu(page);
+ // The menu holds menu items, plus the sub-menu row's own nested menu.
+ const roles = await menu.evaluate(el =>
+ Array.from(el.querySelectorAll('[role]')).map(n => n.getAttribute('role')),
+ );
+ expect(roles.every(r => r === 'menuitem' || r === 'menu')).toBe(true);
+ expect(roles).toContain('menuitem');
+ await expect(menu.getByRole('textbox', {name: 'Filter labels'})).toHaveCount(
+ 0,
+ );
+ await expect(menu.getByRole('button', {name: 'Create label'})).toHaveCount(0);
+ await expect(
+ page.getByRole('textbox', {name: 'Filter labels'}),
+ ).toBeVisible();
+ await expect(page.getByRole('button', {name: 'Create label'})).toBeVisible();
+});
+
+test('typing into the header field filters without moving to a row', async ({
+ page,
+}) => {
+ await openMenu(page);
+ const field = page.getByRole('textbox', {name: 'Filter labels'});
+ await field.click();
+ await page.keyboard.type('de');
+ await expect(field).toHaveValue('de');
+ await expect(field).toBeFocused();
+ await expect(page.getByRole('menuitem')).toHaveText(['Design', 'Move to']);
+});
+
+test('Tab walks header, menu, footer, then closes to the trigger', async ({
+ page,
+}) => {
+ const menu = await openMenu(page);
+ const field = page.getByRole('textbox', {name: 'Filter labels'});
+ const create = page.getByRole('button', {name: 'Create label'});
+
+ await page.keyboard.press('Shift+Tab');
+ await expect(field).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(menu).toBeFocused();
+ await page.keyboard.press('ArrowDown');
+ await expect(page.getByRole('menuitem', {name: 'Bug'})).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(create).toBeFocused();
+ await expect(menu).toBeVisible();
+
+ await page.keyboard.press('Enter');
+ await expect(page.getByTestId('created')).toHaveText('1');
+ await expect(menu).toBeVisible();
+
+ await page.keyboard.press('Tab');
+ await expect(menu).toBeHidden();
+ await expect(page.locator(TRIGGER)).toHaveAttribute('aria-expanded', 'false');
+});
+
+test('Shift+Tab from a row goes straight to the header', async ({page}) => {
+ const menu = await openMenu(page);
+ await page.keyboard.press('ArrowDown');
+ await expect(page.getByRole('menuitem', {name: 'Bug'})).toBeFocused();
+ await page.keyboard.press('Shift+Tab');
+ await expect(
+ page.getByRole('textbox', {name: 'Filter labels'}),
+ ).toBeFocused();
+ await expect(menu).toBeVisible();
+});
+
+test('a mouse open draws no keyboard focus ring on the menu', async ({
+ page,
+}) => {
+ const menu = await openMenu(page);
+ const outlineStyle = await menu.evaluate(
+ el => getComputedStyle(el).outlineStyle,
+ );
+ expect(outlineStyle).toBe('none');
+});
+
+test('keyboard focus on the menu between the regions is visible', async ({
+ page,
+}) => {
+ const menu = await openMenu(page);
+ await page.keyboard.press('Shift+Tab');
+ await page.keyboard.press('Tab');
+ await expect(menu).toBeFocused();
+ const outline = await menu.evaluate(el => {
+ const style = getComputedStyle(el);
+ return {style: style.outlineStyle, width: parseFloat(style.outlineWidth)};
+ });
+ expect(outline.style).not.toBe('none');
+ expect(outline.width).toBeGreaterThan(0);
+});
+
+test('Tab and Shift+Tab from an open sub-menu close it and reach a region', async ({
+ page,
+}) => {
+ const menu = await openMenu(page);
+ const subTrigger = page.getByRole('menuitem', {name: 'Move to'});
+ await page.keyboard.press('End');
+ await expect(subTrigger).toBeFocused();
+ await page.keyboard.press('ArrowRight');
+ await expect(page.getByRole('menuitem', {name: 'Archive'})).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(page.getByRole('button', {name: 'Create label'})).toBeFocused();
+ await expect(subTrigger).toHaveAttribute('aria-expanded', 'false');
+ await expect(menu).toBeVisible();
+
+ await page.keyboard.press('Shift+Tab');
+ await expect(menu).toBeFocused();
+ await page.keyboard.press('End');
+ await page.keyboard.press('ArrowRight');
+ await expect(page.getByRole('menuitem', {name: 'Archive'})).toBeFocused();
+ await page.keyboard.press('Shift+Tab');
+ await expect(
+ page.getByRole('textbox', {name: 'Filter labels'}),
+ ).toBeFocused();
+ await expect(subTrigger).toHaveAttribute('aria-expanded', 'false');
+});
+
+test('Escape in the header closes the menu and returns focus to the trigger', async ({
+ page,
+}) => {
+ const menu = await openMenu(page);
+ await page.getByRole('textbox', {name: 'Filter labels'}).click();
+ await page.keyboard.press('Escape');
+ await expect(menu).toBeHidden();
+ await expect(page.locator(TRIGGER)).toBeFocused();
+});
+
+test('a finger tap on the footer button acts and the menu stays open', async ({
+ browser,
+}) => {
+ const context = await browser.newContext({hasTouch: true, isMobile: true});
+ const page = await context.newPage();
+ try {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`,
+ );
+ await page.locator(TRIGGER).tap();
+ const menu = page.getByRole('menu', {name: 'Labels', exact: true});
+ await expect(menu).toBeVisible();
+ await page.getByRole('button', {name: 'Create label'}).tap();
+ await expect(page.getByTestId('created')).toHaveText('1');
+ await expect(menu).toBeVisible();
+ } finally {
+ await context.close();
+ }
+});
diff --git a/packages/core/src/DropdownMenu/menuRegionsContext.ts b/packages/core/src/DropdownMenu/menuRegionsContext.ts
new file mode 100644
index 0000000000..f9159f7ec6
--- /dev/null
+++ b/packages/core/src/DropdownMenu/menuRegionsContext.ts
@@ -0,0 +1,17 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+'use client';
+/**
+ * @file menuRegionsContext.ts
+ * @input DropdownMenu's `header` and `footer` props
+ * @output `MenuRegionsContext`: whether the root menu has a header or footer
+ * @position Internal; not exported from the package. A sub-menu flyout reads it
+ * to close itself on Tab, so the root menu can move focus to a region.
+ *
+ * A plain context rather than a layer-scoped one on purpose: each sub-menu
+ * flyout is its own layer, and it must still see the root's value. A nested
+ * DropdownMenu provides its own value, so it never inherits an outer one.
+ */
+import {createContext} from 'react';
+
+export const MenuRegionsContext = createContext(false);
+MenuRegionsContext.displayName = 'MenuRegionsContext';
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index 8e89f16ac9..a39dd143c9 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -91,8 +91,12 @@ function isVisiblyFocusable(el: HTMLElement): boolean {
/**
* Get all focusable elements within a container.
+ *
+ * Exported for menus that place their own Tab stops inside a trapped layer
+ * (DropdownMenu's header and footer), so they judge reachability exactly as
+ * the trap does. Not re-exported from the package's `hooks` entry.
*/
-function getFocusableElements(container: HTMLElement): HTMLElement[] {
+export function getFocusableElements(container: HTMLElement): HTMLElement[] {
return Array.from(
container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
).filter(isVisiblyFocusable);