Skip to content

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

TypeScript

feat(DropdownMenuSubMenu): header and footer around a sub-menu's rows (#7530)

Christopher Chedeaub7860bcbb0b8
diff --git a/.changeset/dropdown-menu-submenu-regions.md b/.changeset/dropdown-menu-submenu-regions.md
new file mode 100644
index 0000000000..465b02170d
--- /dev/null
+++ b/.changeset/dropdown-menu-submenu-regions.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `DropdownMenuSubMenu` takes `header` and `footer`, as the root `DropdownMenu` does: a field that filters a sub-menu's rows, or a door below them, sits beside the sub-menu's menu rather than inside it. With either, the sub-menu's surface (the flyout, or the drilled-in view on a phone) is a modal dialog named by its row: the row says `aria-haspopup="dialog"`, Tab and Shift+Tab walk the header, the rows and the footer and wrap, Escape returns to the row, and a pointer leaving the flyout closes it only once focus leaves too. A `ContextMenu` does not show a sub-menu's `header` or `footer`. Without them nothing changes.
+
+@vjeux
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1b7b182c23..de085467f2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1383,6 +1383,17 @@ jobs:
--project chromium \
--output menu-header-footer-output
+ # A sub-menu with a header or footer is a modal dialog beside the root's
+ # menu, outside every role="menu" element. Its Tab order, a header radio
+ # group the browser moves focus in after the pointer leaves, the
+ # press-drag pick and the phone drill-in only exist in a real engine.
+ - name: Run DropdownMenu sub-menu header and footer contract
+ run: |
+ pnpm exec playwright test \
+ packages/core/src/DropdownMenu/__tests__/SubMenuHeaderFooter.a11y.chromium.spec.ts \
+ --project chromium \
+ --output submenu-header-footer-output
+
# A pointer that crosses from a Tooltip's trigger onto the tooltip in one
# step must not lose it (WCAG 1.4.13 hoverable). The defect is in the
# order the engine dispatches mouseout and mouseleave on that step, which
diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsx
index 5126f0a85a..93639a6f58 100644
--- a/apps/storybook/stories/DropdownMenu.stories.tsx
+++ b/apps/storybook/stories/DropdownMenu.stories.tsx
@@ -16,6 +16,7 @@ import {
DropdownMenuSubMenu,
} from '@astryxdesign/core/DropdownMenu';
import {Button} from '@astryxdesign/core/Button';
+import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';
import {TextInput} from '@astryxdesign/core/TextInput';
import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
import {
@@ -1537,3 +1538,119 @@ export const HeaderAndFooter: Story = {
);
},
};
+
+/**
+ * A sub-menu with its own filter field and "Create" button: the Labels level
+ * of a session menu. Its surface (the flyout, or the drilled-in view on a
+ * phone) is a modal dialog named by its row, beside the menu rather than
+ * inside it: Tab walks field, rows, button and wraps; Escape returns to the
+ * row. The picks are checkbox rows, so the sub-menu stays open while several
+ * are chosen.
+ */
+export const SubMenuHeaderAndFooter: Story = {
+ name: 'Submenu / header and footer',
+ render: () => {
+ const [query, setQuery] = useState('');
+ const [picked, setPicked] = useState<ReadonlyArray<string>>(['Bug']);
+ const [created, setCreated] = useState(0);
+ const visible = LABELS.filter(label =>
+ label.toLowerCase().includes(query.trim().toLowerCase()),
+ );
+ return (
+ <div data-testid="submenu-regions-fixture" style={{padding: 16}}>
+ <DropdownMenu button={{label: 'Session'}}>
+ <DropdownMenuItem
+ icon={PencilIcon}
+ label="Rename"
+ onClick={() => {}}
+ />
+ <DropdownMenuSubMenu
+ 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 => (
+ <DropdownMenuCheckboxItem
+ key={label}
+ label={label}
+ value={picked.includes(label)}
+ onChange={isChecked =>
+ setPicked(current =>
+ isChecked
+ ? [...current, label]
+ : current.filter(item => item !== label),
+ )
+ }
+ />
+ ))}
+ </DropdownMenuSubMenu>
+ <DropdownMenuItem
+ icon={TrashIcon}
+ label="Delete"
+ onClick={() => {}}
+ />
+ </DropdownMenu>
+ <output data-testid="picked">{picked.join(', ')}</output>
+ <output data-testid="created">{created}</output>
+ </div>
+ );
+ },
+};
+
+/**
+ * A sub-menu whose header holds a choice rather than a field: whether the
+ * picked labels must all match. The radio group keeps its own arrow keys, and
+ * a flyout the pointer has left stays open while focus is inside it, so the
+ * choice can still be changed from the keyboard.
+ */
+export const SubMenuHeaderChoice: Story = {
+ name: 'Submenu / header with a choice',
+ render: () => {
+ const [match, setMatch] = useState('any');
+ const [picked, setPicked] = useState<ReadonlyArray<string>>(['Bug']);
+ return (
+ <div data-testid="submenu-choice-fixture" style={{padding: 16}}>
+ <DropdownMenu button={{label: 'Filters'}}>
+ <DropdownMenuItem label="Reset" onClick={() => {}} />
+ <DropdownMenuSubMenu
+ label="Labels"
+ header={
+ <RadioList label="Match" value={match} onChange={setMatch}>
+ <RadioListItem label="Any label" value="any" />
+ <RadioListItem label="All labels" value="all" />
+ </RadioList>
+ }>
+ {LABELS.map(label => (
+ <DropdownMenuCheckboxItem
+ key={label}
+ label={label}
+ value={picked.includes(label)}
+ onChange={isChecked =>
+ setPicked(current =>
+ isChecked
+ ? [...current, label]
+ : current.filter(item => item !== label),
+ )
+ }
+ />
+ ))}
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+ <output data-testid="match">{match}</output>
+ </div>
+ );
+ },
+};
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index c9f242739b..ecf94122a4 100644
--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx
@@ -24,6 +24,7 @@ import {
ContextMenuRadioItem,
} from './index';
import {DropdownMenuItem} from '../DropdownMenu/DropdownMenuItem';
+import {DropdownMenuSubMenu} from '../DropdownMenu/DropdownMenuSubMenu';
import {Divider} from '../Divider';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {warmMenuBottomSheet} from '../DropdownMenu/__tests__/warmMenuBottomSheet';
@@ -706,6 +707,46 @@ describe('ContextMenu dividers', () => {
});
describe('ContextMenu compound mode', () => {
+ it('shows a sub-menu with a header or footer as its rows alone, and says why in development', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ render(
+ <ContextMenu
+ menuContent={
+ <>
+ <DropdownMenuItem label="Rename" onClick={() => {}} />
+ <DropdownMenuSubMenu
+ label="Labels"
+ header={<input aria-label="Filter labels" />}
+ footer={<button type="button">Create label</button>}>
+ <DropdownMenuItem label="Bug" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </>
+ }>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+ const row = screen.getByRole('menuitem', {name: /Labels/, hidden: true});
+ // No region can sit outside this menu, so none renders inside it.
+ expect(row).toHaveAttribute('aria-haspopup', 'menu');
+ fireEvent.click(row, {detail: 1});
+ await waitFor(() => expect(row).toHaveAttribute('aria-expanded', 'true'));
+ expect(screen.queryByRole('dialog', {hidden: true})).toBeNull();
+ expect(
+ screen.queryByRole('textbox', {name: 'Filter labels', hidden: true}),
+ ).toBeNull();
+ expect(
+ screen.getByRole('menuitem', {name: 'Bug', hidden: true}),
+ ).toBeInTheDocument();
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('DropdownMenuSubMenu: header and footer'),
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
it('renders menuContent as menu items', () => {
render(
<ContextMenu
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
index b44b795958..84fc7347d6 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md
+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
@@ -86,7 +86,7 @@ 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. Three component-local concepts are added, by DEC-2, DEC-3 and DEC-8; each
+documented in `DropdownMenu.doc.mjs` and the subcomponent docs. Four component-local concepts are added, by DEC-2, DEC-3, DEC-8 and proposed DEC-13; each
keeps its released default.
| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
@@ -94,6 +94,7 @@ keeps its released default.
| 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. |
+| Sub-menu regions | `header`, `footer` on a sub-menu: any React node | Content above and below a sub-menu's rows, beside its menu inside its own surface; with either, that surface is a modal dialog named by the row (proposed FR20). | Popover presentation | none | `component:DropdownMenu` | proposed | A false or empty value renders no region. |
## Behavioral and layout contract
@@ -119,6 +120,7 @@ keeps its released default.
| 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 |
| FR16 | `DropdownMenuCheckboxItem` MUST expose one `menuitemcheckbox` row whose `aria-checked` equals its controlled value; enabled activation reports `!value`, stays open by default, and composes consumer click and pointer-move handlers with owned activation and hover focus. Disabled activation calls no consumer activation handler. | Released subcomponent API; `architecture:public-component-api/INV5–INV8`; `DropdownMenuSelectable.test.tsx` | Verified current behavior; consumer handlers are preserved |
| FR17 | Disabled menu rows SHOULD remain keyboard-discoverable while activation stays blocked. Current shared `useListFocus` deliberately skips every `aria-disabled` row, including checkbox items. | WAI-ARIA Menu pattern; current shared navigation source/tests | Objective mismatch; shared mechanism remains undecided in OQ1 |
+| FR20 | With `header` or `footer` on a sub-menu (`DropdownMenuSubMenu`), its surface is a modal dialog named by its row (AR7), holding the header, the sub-menu's `role="menu"` (rows only), then the footer. It sits in a host `DropdownMenu` renders beside its menu, never inside a menu; under a root with no such host (`ContextMenu`) the sub-menu shows its rows alone. On a fine pointer the dialog is the flyout; on a compact touch display, the drilled-in view, which replaces the root's menu and regions until popped. A region keeps its own keys and presses. The rows are one Tab stop: Tab and Shift+Tab walk the header's controls, the rows, then the footer's, and wrap; from a deeper flyout, that flyout closes and the walk goes on from the rows. An open lands as for any sub-menu (FR11, FR12), not on a region. Escape in the dialog, outside an IME composition and unless a control there handled it, returns focus to the row and leaves the root open. A pointer leaving the flyout keeps it open until focus leaves, and it closes with the flyout holding its row. Without either prop nothing changes. | Proposed DEC-13; FR15; AR5 | Proposed; verified in jsdom and Chromium, pending owner review |
### Allowed variation
@@ -200,13 +202,20 @@ visibility helper.
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.
-
- **AR6 — Checkbox rows remain one control.** The row owns
`menuitemcheckbox`, its accessible name, checked state, focus, and activation;
Indicator's checkbox marker is decorative. Disabled activation is inert.
Current shared navigation skips disabled rows instead of making them
discoverable as the WAI-ARIA Menu pattern recommends; FR17 and OQ1 retain that
gap without inventing a component-local focus path.
+- **AR7 (proposed) — A sub-menu with a header or footer adopts the same APG
+ Dialog (Modal) parts for its own surface** (`spec:AST-020/FR15`):
+ `role="dialog"`, `aria-modal="true"`, and an accessible name, its row's;
+ focus moves into the dialog on open, to the sub-menu's first row or its
+ menu as FR11 and FR12 already state; Tab and Shift+Tab cycle within it
+ (FR20); Escape closes it and focus returns to the row. The sub-menu's menu
+ inside keeps AR3. The row keeps `aria-expanded`; its `aria-haspopup` says
+ `dialog` and its `aria-controls` names the dialog.
## Design relationships
@@ -324,6 +333,7 @@ than adding a DropdownMenu-owned heading target.
| 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. |
| FR16 | `DropdownMenuSelectable.test.tsx`, source inspection, scoped `pr-a11y` over the `a11y/Checkbox pattern` stories, and owned Storybook states | checked, unchecked, disabled, caller click/pointer handlers, marker size and ownership | A dropped consumer handler, wrong checked state, nested semantic checkbox, disabled activation, or menu that closes by default fails. | `audit:DropdownMenuCheckboxItem/behavior` |
| FR17, AR6 | Shared navigation source and DropdownMenu keyboard tests | disabled checkbox row first, middle, and last | Current tests prove the shared hook skips the row; no keyboard-discoverability proof exists until OQ1 is settled. | `audit:DropdownMenuCheckboxItem/accessibility` |
+| FR20, AR7 | `DropdownMenuSubMenu.test.tsx` "header and footer" suite; `ContextMenu.test.tsx` rows-alone case; `__tests__/SubMenuHeaderFooter.a11y.chromium.spec.ts` in real Chromium (fine pointer, coarse pointer) | flyout and phone view; dialog role, name, row wiring; regions outside menus; Tab walk and wrap from a field, row, deeper flyout; field keys, presses; Escape, IME and handled Escapes; keyboard open; pointer leaving, focus in then out; parent closing a nested flyout; view tracking its regions; ContextMenu rows alone | A region inside a menu element, a surface with regions that is not a named modal dialog, a row still saying `aria-haspopup="menu"`, a field key taken by the menu, a Tab that leaves or closes the dialog, a flyout closed under focus by a pointer leaving, a flyout outliving its parent, or the root menu beside a view, fails. | `audit:DropdownMenu/behavior` |
## Decision log
@@ -541,3 +551,24 @@ 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.
+
+### DEC-13 (proposed) — A sub-menu's header and footer make its surface a dialog beside the menu
+
+**Reference:** `component:DropdownMenu/DEC-13`
+**Decider:** proposed by `vjeux`, 2026-10-14; pending owner review
+
+A filter field above a sub-menu's rows, or a door below them, is a control
+that is not a menu item, so DEC-8 and DEC-10 apply to the sub-menu's own
+surface as they apply to the root's: the sub-menu's menu holds only its rows,
+and the surface around it is a named modal dialog whose Tab order wraps. A
+flyout renders inside the menu that holds its row, so a dialog there would
+still sit inside that menu; the `DropdownMenu` therefore renders a host beside its menu,
+inside its popover, and a sub-menu with regions renders its surface there (the
+flyout layer, or the drilled-in view, which then takes the root menu's place).
+Rendered there, a flyout no longer hides with the flyout that holds its row,
+so it closes with it. The pointer leaving that flyout does not close it while
+focus is inside, because what was typed into its field would go with it.
+Rejected: regions inside the flyout beside the sub-menu's menu,
+which puts them inside the parent menu; a separate DropdownMenu for the level,
+which loses the row, the drill-in and the single press model; and closing the
+flyout when the pointer leaves it as any flyout does.
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 1a474d1167..875bf11824 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -61,7 +61,10 @@ import {
import {
DropdownMenuContext,
DropdownMenuRootOpenContext,
+ DropdownMenuSurfaceContext,
type DropdownMenuContextValue,
+ type DropdownMenuSurfaceHost,
+ type DropdownMenuSurfaceValue,
} from './DropdownMenuContext';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {useListFocus} from '../hooks/useListFocus';
@@ -112,6 +115,14 @@ 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']})`;
+// A sub-menu's drilled-in view with a header or footer renders in the surface
+// host that follows the menu, as the frame marked
+// `data-astryx-submenu-regions="view"` (hidden while a deeper view shows).
+// While one shows, the menu and its header and footer step aside. The rule
+// reads that from the DOM, so no state mirrors which view shows.
+const STEPS_ASIDE_FOR_VIEW =
+ ':has(~ * > [data-astryx-submenu-regions="view"]:not([hidden]))';
+
const styles = stylex.create({
triggerOpen: {
backgroundImage: MENU_TRIGGER_OPEN_BACKGROUND,
@@ -125,7 +136,12 @@ const styles = stylex.create({
},
dropdown: {
boxSizing: 'border-box',
- display: 'flex',
+ display: {
+ default: 'flex',
+ // A sub-menu's drilled-in view with a header or footer shows in its
+ // place (see `stepsAsideForView`).
+ [STEPS_ASIDE_FOR_VIEW]: 'none',
+ },
flexDirection: 'column',
gap: spacingVars['--spacing-0-5'],
// Pointer opens focus this container so subsequent arrow keys and Escape
@@ -175,6 +191,22 @@ const styles = stylex.create({
flexShrink: 1,
minBlockSize: 0,
},
+ // Where a sub-menu with a header or footer renders its surface: beside the
+ // menu, never inside it. It owns no box, so the popover's layout is
+ // unchanged.
+ surfaceHost: {
+ display: 'contents',
+ },
+ // While a sub-menu's drilled-in view with its own header or footer shows
+ // in the surface host, the header and footer step aside for it, as the menu
+ // does (see `dropdown`). Derived from the DOM by the rule itself: the view
+ // is the frame in the host that is not hidden.
+ stepsAsideForView: {
+ display: {
+ default: null,
+ [STEPS_ASIDE_FOR_VIEW]: 'none',
+ },
+ },
region: {
flexShrink: 0,
padding: spacingVars['--spacing-1'],
@@ -1455,12 +1487,39 @@ function DropdownMenuPopover({
// The drill-in view stack for sub-menus on a phone.
const {drillIn, wrapContent} = useMenuDrillIn(isOpen);
+ // The surface host is owned through a ref. State keeps only a key that
+ // changes whenever a host element attaches, the host included when it
+ // moves (a header or footer coming or going), so sub-menus re-render into
+ // the element that is mounted.
+ const surfaceHostRef = useRef<HTMLDivElement | null>(null);
+ const [surfaceHostKey, setSurfaceHostKey] = useState(0);
+ const attachSurfaceHost = useCallback((node: HTMLDivElement | null) => {
+ surfaceHostRef.current = node;
+ if (node != null) {
+ setSurfaceHostKey(key => key + 1);
+ }
+ }, []);
+ const surfaceHost = useMemo<DropdownMenuSurfaceHost>(
+ () => ({
+ getElement: () => (surfaceHostKey > 0 ? surfaceHostRef.current : null),
+ }),
+ [surfaceHostKey],
+ );
const resolvedMaxHeight = menuMaxHeight == null ? null : `${menuMaxHeight}px`;
// Context for compound items
const contextValue = useMemo<DropdownMenuContextValue>(
() => ({closeMenu, menuSize, drillIn, menuLabel}),
[closeMenu, menuSize, drillIn, menuLabel],
);
+ // What a sub-menu with a header or footer needs, on an internal context.
+ const surfaceValue = useMemo<DropdownMenuSurfaceValue>(
+ () => ({
+ host: surfaceHost,
+ ownerId: menuId,
+ menuMaxHeight: resolvedMaxHeight ?? undefined,
+ }),
+ [surfaceHost, menuId, resolvedMaxHeight],
+ );
// Resolve menu content: data-driven items become components
const menuContent = wrapContent(
@@ -1469,7 +1528,13 @@ 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.
+ // the role="menu" element: a menu holds only its rows. The surface host
+ // follows the menu, so a sub-menu with a header or footer renders beside the
+ // menu too; while such a sub-menu's drilled-in view shows there, the menu and
+ // the regions step aside (STEPS_ASIDE_FOR_VIEW).
+ const surfaceHostElement = (
+ <div ref={attachSurfaceHost} {...stylex.props(styles.surfaceHost)} />
+ );
const renderWithRegions = (menu: ReactNode): ReactNode =>
hasRegions ? (
<div
@@ -1482,7 +1547,7 @@ function DropdownMenuPopover({
<div
ref={headerRef}
onKeyDown={handleRegionKeyDown}
- {...stylex.props(styles.region)}>
+ {...stylex.props(styles.region, styles.stepsAsideForView)}>
{header}
</div>
)}
@@ -1491,13 +1556,17 @@ function DropdownMenuPopover({
<div
ref={footerRef}
onKeyDown={handleRegionKeyDown}
- {...stylex.props(styles.region)}>
+ {...stylex.props(styles.region, styles.stepsAsideForView)}>
{footer}
</div>
)}
+ {surfaceHostElement}
</div>
) : (
- menu
+ <>
+ {menu}
+ {surfaceHostElement}
+ </>
);
const triggerProps: DropdownMenuTriggerProps = {
@@ -1636,9 +1705,11 @@ function DropdownMenuPopover({
)}>
<MenuRegionsContext value={hasRegions}>
<DropdownMenuContext value={contextValue}>
- <DropdownMenuRootOpenContext value={isOpen}>
- {menuContent}
- </DropdownMenuRootOpenContext>
+ <DropdownMenuSurfaceContext value={surfaceValue}>
+ <DropdownMenuRootOpenContext value={isOpen}>
+ {menuContent}
+ </DropdownMenuRootOpenContext>
+ </DropdownMenuSurfaceContext>
</DropdownMenuContext>
</MenuRegionsContext>
</div>,
diff --git a/packages/core/src/DropdownMenu/DropdownMenuContext.public.test.ts b/packages/core/src/DropdownMenu/DropdownMenuContext.public.test.ts
new file mode 100644
index 0000000000..9ecc080081
--- /dev/null
+++ b/packages/core/src/DropdownMenu/DropdownMenuContext.public.test.ts
@@ -0,0 +1,22 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuContext.public.test.ts
+ * @input The DropdownMenu barrel and its public `DropdownMenuContextValue`
+ * @output Guards that the menu context keeps its members and that the internal
+ * surface context a sub-menu with a header or footer reads is not exported
+ * @position Public API test guarding @astryxdesign/core/DropdownMenu
+ */
+
+import {describe, expect, expectTypeOf, it} from 'vitest';
+import * as dropdownMenu from './index';
+import type {DropdownMenuContextValue} from './index';
+
+describe('DropdownMenu public context', () => {
+ it('keeps its members and exports no surface context', () => {
+ expectTypeOf<keyof DropdownMenuContextValue>().toEqualTypeOf<
+ 'closeMenu' | 'menuSize' | 'drillIn' | 'menuLabel'
+ >();
+ expect('DropdownMenuSurfaceContext' in dropdownMenu).toBe(false);
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx b/packages/core/src/DropdownMenu/DropdownMenuContext.tsx
index 0a2f9c69fd..ca3bd3bba3 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuContext.tsx
@@ -45,7 +45,10 @@ export interface DropdownMenuDrillIn {
viewStack: ReadonlyArray<string>;
/** The element a shown view renders its rows into (a portal target). */
host: HTMLElement | null;
- /** Show a sub-menu's view in place of the current rows. */
+ /**
+ * Show a sub-menu's view in place of the current rows. A view with a header
+ * or footer renders into the root's surface host instead of `host`.
+ */
push: (viewId: string) => void;
/** Return to the rows the shown view replaced. */
pop: () => void;
@@ -65,6 +68,41 @@ export interface DropdownMenuContextValue {
menuLabel?: string;
}
+/**
+ * The root's surface host. The root owns the element through a ref; this
+ * object is new whenever a new element attaches, so a sub-menu re-renders
+ * into it.
+ */
+export interface DropdownMenuSurfaceHost {
+ /** The host element, or `null` before it attaches. */
+ getElement: () => HTMLElement | null;
+}
+
+/** What a sub-menu with a header or footer needs from the root. Internal. */
+export interface DropdownMenuSurfaceValue {
+ /**
+ * An element inside the root's popover but outside every `role="menu"`
+ * element, where such a sub-menu renders its surface (its flyout layer, or
+ * its drilled-in view, while which the root's menu and regions step aside).
+ */
+ host: DropdownMenuSurfaceHost;
+ /**
+ * The root menu's `id`, which a sub-menu's menu in the host names so the
+ * press model counts it, and only it, as nested in the root.
+ */
+ ownerId: string;
+ /** The root's resolved `menuMaxHeight`, which a drilled-in view caps at. */
+ menuMaxHeight?: string;
+}
+
+/**
+ * The root's surface; `null` under a root with none (ContextMenu). Internal,
+ * off the public menu context, and layer-scoped, so each flyout re-provides it.
+ */
+export const DropdownMenuSurfaceContext =
+ createLayerScopedContext<DropdownMenuSurfaceValue | null>(null);
+DropdownMenuSurfaceContext.displayName = 'DropdownMenuSurfaceContext';
+
/**
* Whether the root menu of this layer tree is open; internal companion to
* `DropdownMenuContext`, on its own unexported context so the public
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs
index 61d8e3cb98..a0b03cbb57 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs
@@ -67,6 +67,18 @@ export const docs = {
"How the sub-menu shows its rows. 'flyout' opens them beside the row; 'drill-in' replaces the menu's rows with them and a Back row, in the same box; 'adaptive' drills in when a finger opened the menu (a coarse pointer, decided when the menu opened) and flies out otherwise.",
default: "'adaptive'",
},
+ {
+ name: 'header',
+ type: 'ReactNode',
+ description:
+ 'Content above the sub-menu\'s rows and outside its menu, a field that filters them, say. It keeps its own keys and presses. With a header or footer the sub-menu\'s surface (the flyout, or the drilled-in view on a phone) is a modal dialog named by the row, beside the menu rather than inside it: the row says aria-haspopup="dialog", Tab and Shift+Tab move through the header, the rows and the footer and wrap, Escape returns to the row, and a pointer leaving the flyout closes it only once focus leaves too. A ContextMenu does not show it.',
+ },
+ {
+ name: 'footer',
+ type: 'ReactNode',
+ description:
+ "Content below the sub-menu's rows and outside its menu, a door to where the options are managed, say. Same rules as header.",
+ },
{
name: 'xstyle',
type: 'StyleXStyles',
@@ -77,7 +89,7 @@ export const docs = {
name: 'ref',
type: 'React.Ref<HTMLElement>',
description:
- 'Ref forwarded to the trigger row, the element carrying role="menuitem" and aria-haspopup="menu".',
+ 'Ref forwarded to the trigger row, the element carrying role="menuitem" and aria-haspopup="menu" ("dialog" with a header or footer).',
},
],
};
@@ -100,6 +112,9 @@ export const docsDense = {
onOpenChange: 'called when flyout opens/closes',
presentation:
"'flyout' beside the row | 'drill-in' replaces the rows + Back row | 'adaptive' (default) drills in on a coarse pointer",
+ header:
+ 'content above the rows, outside the menu; surface becomes a modal dialog named by the row (Tab wraps, Escape returns to the row)',
+ footer: 'content below the rows, outside the menu; same rules as header',
xstyle: 'StyleX styles for the trigger row',
ref: 'ref to the trigger row (role="menuitem")',
},
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
index f890c351bd..a60bd05294 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
@@ -6,7 +6,15 @@
* @output Unit tests for DropdownMenuSubMenu (#3829)
*/
-import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ beforeEach,
+ afterEach,
+} from 'vitest';
import {createRef, useState} from 'react';
import {render, screen, waitFor, fireEvent, act} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -14,7 +22,9 @@ import * as stylex from '@stylexjs/stylex';
import {DropdownMenu} from './DropdownMenu';
import {DropdownMenuItem} from './DropdownMenuItem';
import {DropdownMenuSubMenu} from './DropdownMenuSubMenu';
+import {warmMenuBottomSheet} from './__tests__/warmMenuBottomSheet';
import {IconButton} from '../IconButton';
+import {RadioList, RadioListItem} from '../RadioList';
import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
import {rtlStyles} from '../utils';
@@ -1679,3 +1689,615 @@ describe('DropdownMenuSubMenu light dismiss of the root menu (#6893)', () => {
}
});
});
+
+describe('DropdownMenuSubMenu header and footer', () => {
+ const h = {hidden: true} as const;
+ // The touch sheet is loaded lazily; resolve it once so the sheets below
+ // render synchronously.
+ beforeAll(warmMenuBottomSheet, 20000);
+ // The bottom sheet is a native dialog, which jsdom does not open.
+ beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.removeAttribute('open');
+ });
+ });
+ // Hidden by an attribute, or stepped aside by a style rule (the root's menu
+ // while a view with regions shows). The walk stops at the popover, whose
+ // own open state jsdom does not compute.
+ const isShown = (el: HTMLElement) => {
+ for (
+ let node: HTMLElement | null = el;
+ node != null && !node.hasAttribute('popover');
+ node = node.parentElement
+ ) {
+ if (node.hidden || window.getComputedStyle(node).display === 'none') {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ function LabelsMenu({
+ onCreate,
+ onPick,
+ rootHeader,
+ menuMaxHeight,
+ header = <input aria-label="Filter labels" />,
+ }: {
+ onCreate?: () => void;
+ onPick?: (label: string) => void;
+ rootHeader?: React.ReactNode;
+ menuMaxHeight?: number;
+ header?: React.ReactNode;
+ } = {}) {
+ return (
+ <DropdownMenu
+ button={{label: 'Session'}}
+ header={rootHeader}
+ menuMaxHeight={menuMaxHeight}>
+ <DropdownMenuItem label="Rename" onClick={() => {}} />
+ <DropdownMenuSubMenu
+ label="Labels"
+ header={header}
+ footer={
+ <button type="button" onClick={onCreate}>
+ Create label
+ </button>
+ }>
+ <DropdownMenuItem label="Bug" onClick={() => onPick?.('Bug')} />
+ <DropdownMenuSubMenu label="More">
+ <DropdownMenuItem label="Later" onClick={() => onPick?.('Later')} />
+ </DropdownMenuSubMenu>
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+ );
+ }
+
+ async function openLabels(props?: Parameters<typeof LabelsMenu>[0]) {
+ const user = userEvent.setup();
+ render(<LabelsMenu {...props} />);
+ const trigger = screen.getByRole('button', {name: /Session/});
+ await user.click(trigger);
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'true'),
+ );
+ const rootMenu = screen.getByRole('menu', {name: 'Session', ...h});
+ // A pointer open focuses the root menu itself; let that land first.
+ await waitFor(() => expect(rootMenu).toHaveFocus());
+ const row = screen.getByRole('menuitem', {name: /Labels/, ...h});
+ fireEvent.click(row, {detail: 1});
+ const dialog = await screen.findByRole('dialog', {name: /Labels/, ...h});
+ return {user, trigger, rootMenu, row, dialog};
+ }
+
+ const field = () =>
+ screen.getByRole('textbox', {name: 'Filter labels', ...h});
+ const create = () => screen.getByRole('button', {name: 'Create label', ...h});
+ const labelsMenu = () => screen.getByRole('menu', {name: /Labels/, ...h});
+
+ it('holds the header, the rows and the footer in a dialog named by the row, outside every menu', async () => {
+ const {rootMenu, row, dialog} = await openLabels();
+ expect(dialog).toHaveAttribute('aria-modal', 'true');
+ expect(row).toHaveAttribute('aria-haspopup', 'dialog');
+ expect(row).toHaveAttribute('aria-controls', dialog.id);
+ const menu = labelsMenu();
+ for (const part of [field(), menu, create()]) {
+ expect(dialog).toContainElement(part);
+ }
+ // The sub-menu's menu holds only its rows, and the dialog sits beside the
+ // root's menu, not inside it.
+ expect(menu).not.toContainElement(field());
+ expect(menu).not.toContainElement(create());
+ expect(rootMenu).not.toContainElement(dialog);
+ expect(rootMenu.closest('[popover]')).toContainElement(dialog);
+ expect(
+ field().compareDocumentPosition(menu) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ menu.compareDocumentPosition(create()) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it('makes the rows one Tab stop, and Tab and Shift+Tab walk the regions and wrap', async () => {
+ const {row} = await openLabels();
+ const menu = labelsMenu();
+ expect(menu).toHaveAttribute('tabindex', '0');
+ // A pointer open lands on the first row.
+ const bug = screen.getByRole('menuitem', {name: 'Bug', ...h});
+ await waitFor(() => expect(bug).toHaveFocus());
+
+ fireEvent.keyDown(bug, {key: 'Tab'});
+ expect(create()).toHaveFocus();
+ fireEvent.keyDown(create(), {key: 'Tab'});
+ expect(field()).toHaveFocus();
+ fireEvent.keyDown(field(), {key: 'Tab'});
+ expect(menu).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'Tab', shiftKey: true});
+ expect(field()).toHaveFocus();
+ fireEvent.keyDown(field(), {key: 'Tab', shiftKey: true});
+ expect(create()).toHaveFocus();
+ expect(row).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('keeps arrows and letters in the field; Escape there returns to the row and leaves the menu open', async () => {
+ const {trigger, row} = await openLabels();
+ act(() => field().focus());
+ fireEvent.keyDown(field(), {key: 'ArrowLeft'});
+ fireEvent.keyDown(field(), {key: 'b'});
+ expect(field()).toHaveFocus();
+ expect(row).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.keyDown(field(), {key: 'Escape'});
+ await waitFor(() => expect(row).toHaveAttribute('aria-expanded', 'false'));
+ expect(row).toHaveFocus();
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('an Escape a control in the region already handled closes only that control: a menu in the header, a field that clears itself', async () => {
+ // A field that clears itself on Escape claims the key.
+ function ClearingField() {
+ const [query, setQuery] = useState('bu');
+ return (
+ <input
+ aria-label="Filter labels"
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ onKeyDown={e => {
+ if (e.key === 'Escape' && query !== '') {
+ e.preventDefault();
+ setQuery('');
+ }
+ }}
+ />
+ );
+ }
+ const {user, trigger, row} = await openLabels({
+ header: (
+ <>
+ <ClearingField />
+ <DropdownMenu button={{label: 'Sort'}}>
+ <DropdownMenuItem label="By name" onClick={() => {}} />
+ </DropdownMenu>
+ </>
+ ),
+ });
+
+ // The header's own menu takes the first Escape and closes; the sub-menu
+ // and the root menu stay open.
+ const sort = screen.getByRole('button', {name: /Sort/, ...h});
+ await user.click(sort);
+ await waitFor(() => expect(sort).toHaveAttribute('aria-expanded', 'true'));
+ const sortMenu = screen.getByRole('menu', {name: /Sort/, ...h});
+ await waitFor(() => expect(sortMenu).toHaveFocus());
+ fireEvent.keyDown(sortMenu, {key: 'Escape'});
+ await waitFor(() => expect(sort).toHaveAttribute('aria-expanded', 'false'));
+ expect(row).toHaveAttribute('aria-expanded', 'true');
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // A field that clears itself on Escape keeps that Escape too.
+ act(() => field().focus());
+ fireEvent.keyDown(field(), {key: 'Escape'});
+ expect(field()).toHaveValue('');
+ expect(field()).toHaveFocus();
+ expect(row).toHaveAttribute('aria-expanded', 'true');
+
+ // The next Escape, which nothing in the region claims, returns to the row.
+ fireEvent.keyDown(field(), {key: 'Escape'});
+ await waitFor(() => expect(row).toHaveAttribute('aria-expanded', 'false'));
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('an Escape that ends an IME composition in the field closes nothing', async () => {
+ const {trigger, row} = await openLabels();
+ act(() => field().focus());
+ fireEvent.keyDown(field(), {key: 'Escape', isComposing: true});
+ fireEvent.keyDown(field(), {key: 'Escape', keyCode: 229});
+ expect(row).toHaveAttribute('aria-expanded', 'true');
+ expect(field()).toHaveFocus();
+ // The next Escape, outside the composition, returns to the row.
+ fireEvent.keyDown(field(), {key: 'Escape'});
+ await waitFor(() => expect(row).toHaveAttribute('aria-expanded', 'false'));
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('a keyboard open lands on the first row, not the field', async () => {
+ const user = userEvent.setup();
+ render(<LabelsMenu />);
+ const trigger = screen.getByRole('button', {name: /Session/});
+ await user.click(trigger);
+ const row = screen.getByRole('menuitem', {name: /Labels/, ...h});
+ act(() => row.focus());
+ fireEvent.keyDown(row, {key: 'ArrowRight'});
+ await waitFor(() =>
+ expect(screen.getByRole('menuitem', {name: 'Bug', ...h})).toHaveFocus(),
+ );
+ });
+
+ it('a press in a region acts on nothing in the menus and keeps both open', async () => {
+ const onCreate = vi.fn();
+ const onPick = vi.fn();
+ const {trigger, row} = await openLabels({onCreate, onPick});
+ fireEvent.pointerDown(field(), {pointerType: 'mouse', button: 0});
+ fireEvent.pointerUp(field(), {pointerType: 'mouse', button: 0});
+ fireEvent.click(field());
+ fireEvent.click(create());
+ expect(onCreate).toHaveBeenCalledTimes(1);
+ expect(onPick).not.toHaveBeenCalled();
+ expect(row).toHaveAttribute('aria-expanded', 'true');
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('Tab from a deeper flyout closes it and walks on from the rows', async () => {
+ await openLabels();
+ const more = screen.getByRole('menuitem', {name: /More/, ...h});
+ act(() => more.focus());
+ fireEvent.keyDown(more, {key: 'ArrowRight'});
+ const later = await waitFor(() => {
+ const el = screen.getByRole('menuitem', {name: 'Later', ...h});
+ expect(el).toHaveFocus();
+ return el;
+ });
+ fireEvent.keyDown(later, {key: 'Tab'});
+ await waitFor(() => expect(more).toHaveAttribute('aria-expanded', 'false'));
+ expect(create()).toHaveFocus();
+ });
+
+ // Opens the Labels flyout by hover (timers faked), puts focus on `focusIn`,
+ // and moves the pointer off until the hide delay has run out: the flyout
+ // stays open while focus is inside.
+ function hoverOpenAndLeave(
+ focusIn: () => HTMLElement,
+ header?: React.ReactNode,
+ ) {
+ render(<LabelsMenu header={header} />);
+ fireEvent.click(screen.getByRole('button', {name: /Session/}));
+ const row = screen.getByRole('menuitem', {name: /Labels/, ...h});
+ fireEvent.mouseEnter(row);
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ act(() => focusIn().focus());
+ fireEvent.mouseLeave(screen.getByRole('dialog', {name: /Labels/, ...h}));
+ fireEvent.mouseLeave(row);
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(row).toHaveAttribute('aria-expanded', 'true');
+ return row;
+ }
+
+ it('a flyout the pointer left stays open while focus moves inside it, and closes once focus leaves it', async () => {
+ vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']});
+ try {
+ const row = hoverOpenAndLeave(field);
+ await act(async () => create().focus());
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+ expect(row).toHaveAttribute('aria-expanded', 'true');
+ // Focus leaving closes it, with no further pointer movement, once the
+ // move has completed.
+ await act(async () =>
+ screen.getByRole('menuitem', {name: 'Rename', ...h}).focus(),
+ );
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+ expect(row).toHaveAttribute('aria-expanded', 'false');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('a flyout the pointer left stays open while the browser moves focus between its header controls, as an arrow in a radio group does', async () => {
+ vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']});
+ try {
+ const radio = (name: string) => screen.getByRole('radio', {name, ...h});
+ const row = hoverOpenAndLeave(
+ () => radio('Any label'),
+ <RadioList label="Match" value="any" onChange={() => {}}>
+ <RadioListItem label="Any label" value="any" />
+ <RadioListItem label="All labels" value="all" />
+ </RadioList>,
+ );
+ // The browser's own move, in its order: the blur, a microtask
+ // checkpoint, then the focus on the next radio.
+ fireEvent.focusOut(radio('Any label'));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ act(() => radio('All labels').focus());
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+ expect(row).toHaveAttribute('aria-expanded', 'true');
+ expect(radio('All labels')).toHaveFocus();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('a flyout with regions stays in the popover when the root header comes or goes, which moves the host', async () => {
+ const user = userEvent.setup();
+ const {rerender} = render(<LabelsMenu />);
+ const trigger = screen.getByRole('button', {name: /Session/});
+ await user.click(trigger);
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'true'),
+ );
+ const rootMenu = screen.getByRole('menu', {name: 'Session', ...h});
+ fireEvent.click(screen.getByRole('menuitem', {name: /Labels/, ...h}), {
+ detail: 1,
+ });
+ await screen.findByRole('dialog', {name: /Labels/, ...h});
+ const popover = rootMenu.closest<HTMLElement>('[popover]');
+ // The host moves into the regions frame and back out; the flyout follows
+ // the host that is mounted, never a detached one.
+ for (const rootHeader of [
+ <input key="search" aria-label="Search actions" />,
+ undefined,
+ ]) {
+ rerender(<LabelsMenu rootHeader={rootHeader} />);
+ const dialog = await screen.findByRole('dialog', {name: /Labels/, ...h});
+ expect(popover).toContainElement(dialog);
+ }
+ });
+
+ it('a nested flyout with regions closes with the flyout that holds its row', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Session'}}>
+ <DropdownMenuSubMenu
+ label="Labels"
+ header={<input aria-label="Filter labels" />}>
+ <DropdownMenuItem label="Bug" onClick={() => {}} />
+ <DropdownMenuSubMenu
+ label="More"
+ header={<input aria-label="Filter more" />}>
+ <DropdownMenuItem label="Later" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Session/}));
+ const labelsRow = screen.getByRole('menuitem', {name: /Labels/, ...h});
+ fireEvent.click(labelsRow, {detail: 1});
+ await screen.findByRole('dialog', {name: /Labels/, ...h});
+ const moreRow = screen.getByRole('menuitem', {name: /More/, ...h});
+ fireEvent.click(moreRow, {detail: 1});
+ const moreDialog = await screen.findByRole('dialog', {name: /More/, ...h});
+ const morePopover = moreDialog.closest<HTMLElement>('[popover]');
+ expect(morePopover).toHaveAttribute('popover-open', '');
+ // Escape in the outer flyout's field closes that flyout, and the nested
+ // one, which renders beside the root's menu, with it.
+ act(() => field().focus());
+ fireEvent.keyDown(field(), {key: 'Escape'});
+ await waitFor(() =>
+ expect(labelsRow).toHaveAttribute('aria-expanded', 'false'),
+ );
+ await waitFor(() =>
+ expect(morePopover).not.toHaveAttribute('popover-open'),
+ );
+ });
+
+ it('a menu placed in a region keeps its own press: a mouse release outside it closes it and acts on nothing', async () => {
+ const user = userEvent.setup();
+ const onBug = vi.fn();
+ const onNewest = vi.fn();
+ render(
+ <DropdownMenu button={{label: 'Session'}}>
+ <DropdownMenuItem label="Rename" onClick={() => {}} />
+ <DropdownMenuSubMenu
+ label="Labels"
+ header={
+ <DropdownMenu button={{label: 'Sort'}}>
+ <DropdownMenuItem label="Newest" onClick={onNewest} />
+ </DropdownMenu>
+ }>
+ <DropdownMenuItem label="Bug" onClick={onBug} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Session/}));
+ fireEvent.click(screen.getByRole('menuitem', {name: /Labels/, ...h}), {
+ detail: 1,
+ });
+ await screen.findByRole('dialog', {name: /Labels/, ...h});
+ const sort = screen.getByRole('button', {name: /Sort/, ...h});
+ await user.click(sort);
+ await waitFor(() => expect(sort).toHaveAttribute('aria-expanded', 'true'));
+ const newest = screen.getByRole('menuitem', {name: 'Newest', ...h});
+ const bug = screen.getByRole('menuitem', {name: 'Bug', ...h});
+ fireEvent.pointerDown(newest, {
+ pointerType: 'mouse',
+ pointerId: 1,
+ button: 0,
+ });
+ fireEvent.pointerMove(bug, {pointerType: 'mouse', pointerId: 1});
+ fireEvent.pointerUp(bug, {pointerType: 'mouse', pointerId: 1, button: 0});
+ expect(onBug).not.toHaveBeenCalled();
+ expect(onNewest).not.toHaveBeenCalled();
+ await waitFor(() => expect(sort).toHaveAttribute('aria-expanded', 'false'));
+ });
+
+ it('a press from a menu row released on a row of the flyout acts on it, as in any flyout', async () => {
+ const onPick = vi.fn();
+ const {trigger} = await openLabels({onPick});
+ const rename = screen.getByRole('menuitem', {name: 'Rename', ...h});
+ const bug = screen.getByRole('menuitem', {name: 'Bug', ...h});
+ fireEvent.pointerDown(rename, {
+ pointerType: 'mouse',
+ pointerId: 1,
+ button: 0,
+ });
+ fireEvent.pointerMove(bug, {pointerType: 'mouse', pointerId: 1});
+ fireEvent.pointerUp(bug, {pointerType: 'mouse', pointerId: 1, button: 0});
+ expect(onPick).toHaveBeenCalledWith('Bug');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it("a mouse press from a menu row released on the flyout's field acts on nothing and closes, as outside the menu", async () => {
+ const onPick = vi.fn();
+ const {trigger} = await openLabels({onPick});
+ const rename = screen.getByRole('menuitem', {name: 'Rename', ...h});
+ fireEvent.pointerDown(rename, {
+ pointerType: 'mouse',
+ pointerId: 1,
+ button: 0,
+ });
+ fireEvent.pointerMove(field(), {pointerType: 'mouse', pointerId: 1});
+ fireEvent.pointerUp(field(), {
+ pointerType: 'mouse',
+ pointerId: 1,
+ button: 0,
+ });
+ expect(onPick).not.toHaveBeenCalled();
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('without a header or footer the sub-menu is a plain flyout menu', async () => {
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const row = screen.getByRole('menuitem', {name: /Move to/, ...h});
+ fireEvent.click(row, {detail: 1});
+ await waitFor(() => expect(row).toHaveAttribute('aria-expanded', 'true'));
+ expect(row).toHaveAttribute('aria-haspopup', 'menu');
+ expect(screen.queryByRole('dialog', h)).toBeNull();
+ });
+
+ describe('on a phone', () => {
+ const originalMatchMedia = window.matchMedia;
+ beforeEach(() => {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ matches: query === COMPACT_TOUCH_PRESENTATION_QUERY,
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+ });
+ afterEach(() => {
+ vi.stubGlobal('matchMedia', originalMatchMedia);
+ });
+
+ it('the drilled-in view holds the regions beside its menu while the root steps aside, and Escape in its field returns', async () => {
+ const {rootMenu, row, dialog} = await openLabels({
+ rootHeader: <input aria-label="Search actions" />,
+ });
+ const rootField = screen.getByRole('textbox', {
+ name: 'Search actions',
+ ...h,
+ });
+ expect(isShown(dialog)).toBe(true);
+ expect(dialog).toHaveAttribute('aria-modal', 'true');
+ expect(row).toHaveAttribute('aria-haspopup', 'dialog');
+ // The view sits beside the root's menu, which steps aside with its own
+ // header; the view leads with a Back row.
+ expect(rootMenu).not.toContainElement(dialog);
+ expect(isShown(rootMenu)).toBe(false);
+ expect(isShown(rootField)).toBe(false);
+ expect(dialog.closest('[popover]')).toBe(rootMenu.closest('[popover]'));
+ const viewRows = Array.from(
+ labelsMenu().querySelectorAll('[role="menuitem"]'),
+ )
+ .filter(el => isShown(el as HTMLElement))
+ .map(el => el.textContent);
+ expect(viewRows[0]).toBe('Back to Session');
+ for (const part of [field(), labelsMenu(), create()]) {
+ expect(dialog).toContainElement(part);
+ }
+
+ // Escape in the field returns to the row; the root comes back.
+ act(() => field().focus());
+ fireEvent.keyDown(field(), {key: 'Escape'});
+ await waitFor(() => expect(row).toHaveFocus());
+ expect(isShown(rootMenu)).toBe(true);
+ expect(isShown(rootField)).toBe(true);
+ });
+
+ it('a shown view follows its header or footer as it comes and goes: beside the root menu with one, inside it without', async () => {
+ function TogglingLabels() {
+ const [hasHeader, setHasHeader] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setHasHeader(v => !v)}>
+ Toggle filter
+ </button>
+ <DropdownMenu button={{label: 'Session'}}>
+ <DropdownMenuItem label="Rename" onClick={() => {}} />
+ <DropdownMenuSubMenu
+ label="Labels"
+ header={
+ hasHeader ? <input aria-label="Filter labels" /> : undefined
+ }>
+ <DropdownMenuItem label="Bug" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+ </>
+ );
+ }
+ const user = userEvent.setup();
+ render(<TogglingLabels />);
+ await user.click(screen.getByRole('button', {name: /Session/}));
+ const rootMenu = screen.getByRole('menu', {name: 'Session', ...h});
+ fireEvent.click(screen.getByRole('menuitem', {name: /Labels/, ...h}), {
+ detail: 1,
+ });
+ await screen.findByRole('dialog', {name: /Labels/, ...h});
+ expect(isShown(rootMenu)).toBe(false);
+ const toggle = screen.getByRole('button', {name: 'Toggle filter'});
+ const bugIsShown = () =>
+ isShown(screen.getByRole('menuitem', {name: 'Bug', ...h}));
+
+ // The header goes: the view drills in inside the root's menu, which
+ // shows again with the view's rows.
+ fireEvent.click(toggle);
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', {name: /Labels/, ...h})).toBeNull(),
+ );
+ expect(isShown(rootMenu)).toBe(true);
+ expect(bugIsShown()).toBe(true);
+
+ // It comes back: the view moves beside the root's menu, which steps
+ // aside again.
+ fireEvent.click(toggle);
+ const dialog = await screen.findByRole('dialog', {
+ name: /Labels/,
+ ...h,
+ });
+ expect(isShown(dialog)).toBe(true);
+ expect(isShown(rootMenu)).toBe(false);
+ expect(bugIsShown()).toBe(true);
+ });
+
+ it("a drilled-in view with a header or footer caps at the root's menuMaxHeight, as the plain view does", async () => {
+ const {dialog} = await openLabels({menuMaxHeight: 560});
+ expect(dialog.getAttribute('style')).toContain('min(560px');
+ });
+
+ it('Tab in the drilled-in view wraps through its own regions', async () => {
+ await openLabels();
+ act(() => field().focus());
+ fireEvent.keyDown(field(), {key: 'Tab'});
+ expect(labelsMenu()).toHaveFocus();
+ fireEvent.keyDown(labelsMenu(), {key: 'Tab'});
+ expect(create()).toHaveFocus();
+ fireEvent.keyDown(create(), {key: 'Tab'});
+ expect(field()).toHaveFocus();
+ });
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
index 87edca09ef..ff96fd59a7 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
@@ -9,7 +9,9 @@
* Spinner, and DropdownMenu context + item roles
* @output Exports DropdownMenuSubMenu — a single menu row that reveals a nested
* menu of its own children/items: a flyout beside the row, or, on a phone,
- * a drilled-in view in place of the parent rows.
+ * a drilled-in view in place of the parent rows. With a header or footer,
+ * that surface is a modal dialog rendered into the root's surface host,
+ * beside every menu element.
* @position Sub-component; place inside a DropdownMenu (or ContextMenu)
* alongside plain items.
*
@@ -65,12 +67,17 @@ import * as stylex from '@stylexjs/stylex';
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {Spinner} from '../Spinner';
import {MenuRegionsContext} from './menuRegionsContext';
+import {moveRegionsTab} from './menuRegionStops';
import {Item} from '../Item';
import {useLayer} from '../Layer/useLayer';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {useListFocus} from '../hooks/useListFocus';
import {useMenuHover} from '../hooks/useMenuHover';
-import {isMenuPressActivation, useMenuPress} from '../hooks/useMenuPress';
+import {
+ isMenuPressActivation,
+ MENU_PRESS_SURFACE_ATTR,
+ useMenuPress,
+} from '../hooks/useMenuPress';
import {useTypeahead} from '../hooks/useTypeahead';
import {useMenuOverflow} from './useMenuOverflow';
import {resolveMenuWidth} from './menuWidth';
@@ -85,8 +92,17 @@ import {
typographyVars,
typeScaleVars,
} from '../theme/tokens.stylex';
-import {composeEventHandlers, mergeProps, rtlStyles} from '../utils';
+import {
+ composeEventHandlers,
+ isImeKeyEvent,
+ isRenderable,
+ mergeProps,
+ rtlStyles,
+} from '../utils';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {getInteractionModality} from '../utils/interactionModality';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useDevWarning} from '../hooks/useDevWarning';
import {themeProps} from '../utils/themeProps';
import type {BaseProps} from '../BaseProps';
import {
@@ -98,6 +114,7 @@ import {
import {
DropdownMenuContext,
DropdownMenuRootOpenContext,
+ DropdownMenuSurfaceContext,
useDropdownMenuContext,
useDropdownMenuRootOpen,
type DropdownMenuContextValue,
@@ -244,6 +261,70 @@ const drillInStyles = stylex.create({
},
});
+// With a header or footer the sub-menu's surface is a frame holding the
+// header, the sub-menu's own role="menu" element and the footer, in one column
+// under the flyout's block cap: the regions keep their height and the rows
+// shrink and scroll between them.
+// A drilled-in view with a header or footer takes the root menu's place, so
+// it caps where the root does when the root's `menuMaxHeight` lifts the 300px
+// cap; the viewport still bounds it.
+const dynamicRegionStyles = stylex.create({
+ viewMaxHeight: (maxHeight: string) => ({
+ maxHeight: `min(${maxHeight}, ${layerViewportInset.maxBlockSize})`,
+ }),
+});
+
+const regionStyles = stylex.create({
+ frame: {
+ boxSizing: 'border-box',
+ display: 'flex',
+ flexDirection: 'column',
+ maxHeight: stylex.firstThatWorks(
+ MENU_MAX_BLOCK_SIZE,
+ MENU_MAX_BLOCK_SIZE_FALLBACK,
+ ),
+ '--_dropdown-menu-radius': radiusVars['--radius-container'],
+ '--_dropdown-menu-padding': spacingVars['--spacing-1'],
+ borderRadius: 'var(--_dropdown-menu-radius)',
+ },
+ // The flyout paints its own surface; a drilled-in view sits inside the
+ // root's.
+ flyoutSurface: {
+ // Each constant inside calc(), as for the plain flyout: a bare pair would
+ // ship as var(--<hash>, <fallback>) with the hash defined nowhere.
+ maxInlineSize: stylex.firstThatWorks(
+ `calc(${layerViewportInset.maxInlineSize})`,
+ `calc(${layerViewportInset.maxInlineSizeFallback})`,
+ ),
+ backgroundColor: colorVars['--color-background-popover'],
+ boxShadow: shadowVars['--shadow-low'],
+ opacity: 1,
+ transitionProperty: 'opacity',
+ transitionDuration: durationVars['--duration-fast'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ menu: {
+ boxSizing: 'border-box',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-0-5'],
+ flexGrow: 1,
+ flexShrink: 1,
+ minBlockSize: 0,
+ padding: spacingVars['--spacing-1'],
+ outline: 'none',
+ WebkitTouchCallout: 'none',
+ userSelect: 'none',
+ },
+ region: {
+ flexShrink: 0,
+ padding: spacingVars['--spacing-1'],
+ },
+ hidden: {
+ display: 'none',
+ },
+});
+
export type DropdownMenuSubMenuPresentation =
'flyout' | 'drill-in' | 'adaptive';
@@ -285,13 +366,30 @@ interface DropdownMenuSubMenuBaseProps extends Omit<
* 'adaptive'
*/
presentation?: DropdownMenuSubMenuPresentation;
+ /**
+ * Content above the sub-menu's rows: a field that filters them, say. Like
+ * the root menu's `header`, it sits beside the sub-menu's `role="menu"`
+ * element, never inside it, and keeps its own keys and presses. With a
+ * header or footer the sub-menu's surface (the flyout, or the drilled-in
+ * view on a phone) is a modal dialog named by the row: the row says
+ * `aria-haspopup="dialog"`, Tab and Shift+Tab walk the header's controls,
+ * the rows as one stop and the footer's controls and wrap, and Escape
+ * returns to the row. A pointer leaving the flyout does not close it while
+ * focus is inside. A `ContextMenu` does not show it.
+ */
+ header?: ReactNode;
+ /**
+ * Content below the sub-menu's rows: a door to where the options are
+ * managed, say. Same rules as `header`.
+ */
+ footer?: ReactNode;
/** Test id for the trigger row. */
'data-testid'?: string;
/** Test id for the flyout menu. */
menuDataTestId?: string;
/**
* Ref forwarded to the trigger row — the element carrying `role="menuitem"`
- * and `aria-haspopup="menu"`.
+ * and `aria-haspopup="menu"` (`"dialog"` with a header or footer).
*/
ref?: React.Ref<HTMLElement>;
}
@@ -309,6 +407,49 @@ export interface DropdownMenuSubMenuProps extends DropdownMenuSubMenuBaseProps {
children: ReactNode;
}
+/**
+ * Close every open flyout with a header or footer whose row sits in `menu`.
+ * Such a flyout renders beside the root's menu, not inside the flyout that
+ * holds its row, so hiding that flyout does not hide it. Each closes through
+ * the popover API, as DropdownMenu closes its flyouts when it hides, so its
+ * layer's toggle handling resets its state and reports the close; its own
+ * nested flyouts close the same way, innermost first.
+ */
+function hideRegionedFlyoutsIn(menu: HTMLElement | null): void {
+ if (menu == null) {
+ return;
+ }
+ const doc = menu.ownerDocument;
+ const rows = menu.querySelectorAll<HTMLElement>(
+ '[aria-expanded="true"][aria-controls]',
+ );
+ for (const row of [...rows].reverse()) {
+ const frame = doc.getElementById(row.getAttribute('aria-controls') ?? '');
+ if (frame?.getAttribute('data-astryx-submenu-regions') !== 'flyout') {
+ continue;
+ }
+ const flyout = frame.closest<HTMLElement>('[popover]');
+ if (flyout == null) {
+ continue;
+ }
+ if (typeof flyout.hidePopover === 'function') {
+ if (flyout.matches(':popover-open')) {
+ flyout.hidePopover();
+ }
+ } else if (flyout.style.display === 'block') {
+ // Without the popover API the layer toggles `display`; mirror it and
+ // tell its reconciler, as DropdownMenu's own sweep does.
+ flyout.style.display = 'none';
+ const toggle = new Event('toggle', {bubbles: false});
+ Object.defineProperty(toggle, 'newState', {
+ value: 'closed',
+ configurable: true,
+ });
+ flyout.dispatchEvent(toggle);
+ }
+ }
+}
+
/**
* A single menu row that reveals a nested flyout of its own items. The row
* adopts DropdownMenuItem semantics (label / icon / description / isDisabled);
@@ -341,6 +482,8 @@ export function DropdownMenuSubMenu(
menuWidth,
onOpenChange,
presentation = 'adaptive',
+ header,
+ footer,
children,
xstyle,
className,
@@ -360,9 +503,29 @@ export function DropdownMenuSubMenu(
const t = useTranslator();
const menuCtx = useDropdownMenuContext();
+ const rootSurface = use(DropdownMenuSurfaceContext);
const rootHasRegions = use(MenuRegionsContext);
const menuSize = menuCtx?.menuSize ?? 'md';
const canOpen = !isDisabled;
+ // With a header or footer the sub-menu's surface holds controls that are not
+ // menu items, so it is a modal dialog around the sub-menu's menu, rendered
+ // into the root's surface host: outside every menu element. A root that
+ // renders no host (no surface context, as in ContextMenu) has nowhere
+ // outside its menu to put them, so the sub-menu shows its rows alone there.
+ const wantsRegions = isRenderable(header) || isRenderable(footer);
+ const rootHostsSurfaces = rootSurface != null;
+ const hasRegions = wantsRegions && rootHostsSurfaces;
+ const surfaceHost = rootSurface?.host.getElement() ?? null;
+ useDevWarning(
+ 'DropdownMenuSubMenu',
+ 'header and footer show only inside a DropdownMenu; this menu has no place outside its rows for them, so they are not rendered.',
+ wantsRegions && !rootHostsSurfaces,
+ );
+ const frameId = useId();
+ const frameRef = useRef<HTMLDivElement | null>(null);
+ const headerRef = useRef<HTMLDivElement | null>(null);
+ const footerRef = useRef<HTMLDivElement | null>(null);
+ const [isMenuKeyboardFocused, setIsMenuKeyboardFocused] = useState(false);
const contentId = useId();
const generatedTriggerId = useId();
@@ -394,17 +557,32 @@ export function DropdownMenuSubMenu(
const [isFlyoutOpen, setIsFlyoutOpen] = useState(false);
const isOpen = isDrillIn ? isOnStack : isFlyoutOpen;
+ // Whether focus is anywhere in this flyout's frame, a level nested in it
+ // included: React brings a nested level's focus events back here through
+ // its portal, where the DOM would not.
+ const isFocusInFrameRef = useRef(false);
+ // A pointer that left while focus was inside: the flyout closes once focus
+ // leaves too.
+ const closeWhenFocusLeavesRef = useRef(false);
const layer = useLayer({
mode: 'context',
lightDismiss: false,
onShow: useCallback(() => {
+ closeWhenFocusLeavesRef.current = false;
setIsFlyoutOpen(true);
onOpenChange?.(true);
}, [onOpenChange]),
onHide: useCallback(() => {
+ closeWhenFocusLeavesRef.current = false;
+ // Whatever closed this flyout, a flyout with a header or footer opened
+ // from one of its rows closes with it: that flyout renders beside the
+ // root's menu, not inside this one, so hiding this one leaves it shown.
+ hideRegionedFlyoutsIn(
+ triggerRef.current?.ownerDocument.getElementById(contentId) ?? null,
+ );
setIsFlyoutOpen(false);
onOpenChange?.(false);
- }, [onOpenChange]),
+ }, [onOpenChange, contentId]),
});
const showLayer = useCallback(() => {
@@ -413,8 +591,49 @@ export function DropdownMenuSubMenu(
}
}, [canOpen, layer]);
const hideLayer = useCallback(() => {
+ // A pointer leaving a flyout with a header or footer does not close it
+ // while focus is inside: what was typed into its field stays.
+ if (hasRegions && isFocusInFrameRef.current) {
+ closeWhenFocusLeavesRef.current = true;
+ return;
+ }
layer.hide();
- }, [layer]);
+ }, [layer, hasRegions]);
+ const handleFrameFocus = useCallback(() => {
+ isFocusInFrameRef.current = true;
+ }, []);
+ const handleFrameBlur = useCallback(
+ (event: React.FocusEvent<HTMLElement>) => {
+ isFocusInFrameRef.current = false;
+ if (!closeWhenFocusLeavesRef.current) {
+ return;
+ }
+ // Focus moving to another control in the frame keeps it open.
+ const next = event.relatedTarget;
+ if (next instanceof Node && event.currentTarget.contains(next)) {
+ return;
+ }
+ // Focus moving into a level nested in this one (React brings that
+ // focus event back through its portal), or moved by the browser itself
+ // (an arrow key in a native radio group, whose focus event follows a
+ // microtask checkpoint), arrives after this blur: decide in a task of
+ // its own, once the move has completed.
+ setTimeout(() => {
+ if (
+ !isFocusInFrameRef.current &&
+ closeWhenFocusLeavesRef.current &&
+ triggerRef.current?.isConnected === true
+ ) {
+ closeWhenFocusLeavesRef.current = false;
+ layer.hide();
+ }
+ }, 0);
+ },
+ [layer],
+ );
+ const handleFramePointerEnter = useCallback(() => {
+ closeWhenFocusLeavesRef.current = false;
+ }, []);
// Dedicated roving-focus + typeahead for this flyout level. The boundary
// selector scopes item collection and key handling to this flyout's own
@@ -435,8 +654,13 @@ export function DropdownMenuSubMenu(
hasPaging: true,
onEscape: () => close({focusTrigger: true}),
});
- // A drilled-in list scrolls with the root menu, not on its own.
- const hasOverflow = useMenuOverflow(menuRef, children, isOpen && !isDrillIn);
+ // A drilled-in list scrolls with the root menu, not on its own, unless it
+ // has a header or footer: then its rows scroll between them.
+ const hasOverflow = useMenuOverflow(
+ menuRef,
+ children,
+ isOpen && (!isDrillIn || hasRegions),
+ );
const typeahead = useTypeahead({
getItemLabels: () => getItems().map(el => el.textContent),
@@ -465,10 +689,10 @@ export function DropdownMenuSubMenu(
isOpen: isFlyoutOpen,
isEnabled: canOpen && !isDrillIn && isRootMenuOpen,
// The safe triangle toward the flyout's near edge is built from the
- // flyout this component renders, not the hook's own list ref.
- flyoutRef: menuRef,
+ // flyout this component renders, not the hook's own list ref: the
+ // frame, with a header or footer.
+ flyoutRef: hasRegions ? frameRef : menuRef,
});
-
// Where focus lands once a pushed view shows: the first row after Back for
// a keyboard open, the list itself for a pointer open; and the row itself
// once its view is popped.
@@ -664,12 +888,29 @@ 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 (e.key === 'Tab') {
+ // With its own header or footer this level is a dialog: Tab walks
+ // its regions and its rows as one stop, and wraps. A deeper level
+ // has closed itself as the key bubbled up, and the walk continues
+ // from this level's rows.
+ if (hasRegions) {
+ moveRegionsTab(
+ e,
+ menuRef.current,
+ headerRef.current,
+ footerRef.current,
+ !ownsEvent(e),
+ );
+ return;
+ }
+ // In a menu with a header or footer above this level, Tab leaves the
+ // flyout stack: every open level closes as the key bubbles past it,
+ // this one's own rows or a deeper level's, and the level with the
+ // regions moves focus on.
+ if (rootHasRegions) {
+ close({focusTrigger: false});
+ return;
+ }
}
if (!ownsEvent(e)) {
return;
@@ -718,7 +959,46 @@ export function DropdownMenuSubMenu(
}
listNavKeyDown(e);
},
- [ownsEvent, close, listNavKeyDown, typeahead, menuRef, rootHasRegions],
+ [
+ ownsEvent,
+ close,
+ listNavKeyDown,
+ typeahead,
+ menuRef,
+ rootHasRegions,
+ hasRegions,
+ ],
+ );
+
+ // A region keeps its own keys: arrows move a field's caret and letters type.
+ // Tab moves on through the dialog's stops, and Escape returns to the row as
+ // it does from the rows.
+ const handleRegionKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLDivElement>) => {
+ if (e.key === 'Tab') {
+ moveRegionsTab(
+ e,
+ menuRef.current,
+ headerRef.current,
+ footerRef.current,
+ );
+ return;
+ }
+ // An Escape that ends an IME composition belongs to the field, and one a
+ // control in the region already handled (a menu it opened closing, a
+ // field clearing itself) belongs to that control: either closes nothing
+ // here, so one Escape affects one surface.
+ if (
+ e.key === 'Escape' &&
+ !e.defaultPrevented &&
+ !isImeKeyEvent(e.nativeEvent)
+ ) {
+ e.preventDefault();
+ e.stopPropagation();
+ close({focusTrigger: true});
+ }
+ },
+ [menuRef, close],
);
// Re-provide the menu context so nested items behave exactly like top-level
@@ -776,35 +1056,133 @@ export function DropdownMenuSubMenu(
: flyoutStyles.popoverCustomWidth(resolvedMenuWidth.value)
: flyoutStyles.popover;
+ // The flyout is a layer of its own, where layer-scoped contexts reset:
+ // nested rows get this level's menu context and the root's surface again.
const nestedRows = (
<DropdownMenuContext value={nestedMenuContext}>
- {isDrillIn && (
- <DropdownMenuItem
- icon={
- <Icon
- icon="chevronLeft"
- size="sm"
- color="secondary"
- xstyle={rtlStyles.mirror}
- />
- }
- label={backLabel}
- hasCloseOnSelect={false}
- onClick={() => close({focusTrigger: true})}
- />
- )}
- {children}
+ <DropdownMenuSurfaceContext value={rootSurface}>
+ {isDrillIn && (
+ <DropdownMenuItem
+ icon={
+ <Icon
+ icon="chevronLeft"
+ size="sm"
+ color="secondary"
+ xstyle={rtlStyles.mirror}
+ />
+ }
+ label={backLabel}
+ hasCloseOnSelect={false}
+ onClick={() => close({focusTrigger: true})}
+ />
+ )}
+ {children}
+ </DropdownMenuSurfaceContext>
</DropdownMenuContext>
);
+ // A level with its own header or footer tells the levels below it, so Tab
+ // from a deeper flyout closes that flyout and this level walks on.
+ //
// Nested rows live in this level's flyout, a layer of their own where the
- // layer-scoped signal resets; re-provide it so their pending hover intent
- // dies with the root menu too.
+ // layer-scoped signal resets; re-provide it, as whether every level above
+ // them is open, so their pending hover intent dies with the root menu or
+ // with this level: a hover-open that fired after this level closed would
+ // leave a flyout with a header or footer shown beside the root's menu.
const nestedContent = (
- <DropdownMenuRootOpenContext value={isRootMenuOpen}>
- {nestedRows}
+ <DropdownMenuRootOpenContext value={isRootMenuOpen && isOpen}>
+ {hasRegions ? (
+ <MenuRegionsContext value={true}>{nestedRows}</MenuRegionsContext>
+ ) : (
+ nestedRows
+ )}
</DropdownMenuRootOpenContext>
);
+ // The menu of a sub-menu with a header or footer renders beside the root's
+ // menu, outside its DOM: it names the root so the press model counts it as
+ // nested there, as a flyout inside the root's menu is. Only this menu does:
+ // a picker placed in its header or footer stays its own press root.
+ const surfaceOwnerProps =
+ hasRegions && rootSurface != null
+ ? {[MENU_PRESS_SURFACE_ATTR]: rootSurface.ownerId}
+ : undefined;
+
+ // With a header or footer, the dialog that holds them and the sub-menu's
+ // menu. A drilled-in view is named as its list is, by the row's label; the
+ // flyout by the row.
+ const renderRegionsFrame = (
+ menuElement: ReactNode,
+ frameProps: React.HTMLAttributes<HTMLDivElement>,
+ surface: 'flyout' | 'view',
+ ): ReactNode => (
+ <div
+ ref={frameRef}
+ id={frameId}
+ role="dialog"
+ aria-modal="true"
+ // Read by the root's step-aside rule (a shown view) and by the flyout
+ // that holds this row when it closes (an open flyout).
+ data-astryx-submenu-regions={surface}
+ {...frameProps}
+ {...(surface === 'flyout'
+ ? {
+ onFocus: handleFrameFocus,
+ onBlur: handleFrameBlur,
+ onPointerEnter: handleFramePointerEnter,
+ }
+ : undefined)}
+ {...(surface === 'flyout'
+ ? // The flyout's frame paints its surface, so the menu target rides
+ // on it; a drilled-in view sits inside the root's surface.
+ mergeProps(
+ themeProps('dropdown-menu'),
+ stylex.props(regionStyles.frame, regionStyles.flyoutSurface),
+ )
+ : stylex.props(
+ regionStyles.frame,
+ rootSurface?.menuMaxHeight != null &&
+ dynamicRegionStyles.viewMaxHeight(rootSurface.menuMaxHeight),
+ frameProps.hidden === true && regionStyles.hidden,
+ ))}>
+ {isRenderable(header) && (
+ <div
+ ref={headerRef}
+ onKeyDown={handleRegionKeyDown}
+ {...stylex.props(regionStyles.region)}>
+ {header}
+ </div>
+ )}
+ {menuElement}
+ {isRenderable(footer) && (
+ <div
+ ref={footerRef}
+ onKeyDown={handleRegionKeyDown}
+ {...stylex.props(regionStyles.region)}>
+ {footer}
+ </div>
+ )}
+ </div>
+ );
+ // A flyout with a header or footer renders into the root's surface host,
+ // beside the root's menu rather than inside it; any other flyout renders
+ // in place, inside the menu that holds its row.
+ const renderFlyout = (flyout: ReactNode): ReactNode =>
+ hasRegions && surfaceHost != null
+ ? createPortal(flyout, surfaceHost)
+ : flyout;
+ // Between a header and a footer the rows are one Tab stop, so keyboard focus
+ // on the menu element shows the ring the base style otherwise removes.
+ const handleMenuFocus = (event: React.FocusEvent<HTMLDivElement>) => {
+ if (hasRegions && event.target === event.currentTarget) {
+ setIsMenuKeyboardFocused(getInteractionModality() === 'keyboard');
+ }
+ };
+ const handleMenuBlur = (event: React.FocusEvent<HTMLDivElement>) => {
+ if (hasRegions && event.target === event.currentTarget) {
+ setIsMenuKeyboardFocused(false);
+ }
+ };
+
return (
<>
<Item
@@ -816,9 +1194,9 @@ export function DropdownMenuSubMenu(
id={triggerId}
role="menuitem"
tabIndex={isDisabled ? undefined : -1}
- aria-haspopup="menu"
+ aria-haspopup={hasRegions ? 'dialog' : 'menu'}
aria-expanded={isOpen}
- aria-controls={isOpen ? contentId : undefined}
+ aria-controls={isOpen ? (hasRegions ? frameId : contentId) : undefined}
aria-disabled={isDisabled || undefined}
data-testid={testId}
onMouseEnter={composeEventHandlers(
@@ -856,66 +1234,145 @@ export function DropdownMenuSubMenu(
{activeDrillIn != null
? isOnStack &&
activeDrillIn.host != null &&
- createPortal(
- <div
- ref={menuRef}
- id={contentId}
- role="menu"
- tabIndex={-1}
- // The drilled-in list is named by its row's label.
- aria-label={stringLabel}
- aria-labelledby={stringLabel == null ? triggerId : undefined}
- // A deeper view shows in its place; this one waits, hidden.
- hidden={!isTopView}
- inert={!isTopView}
- onKeyDown={handleContentKeyDown}
- data-testid={menuDataTestId}
- {...menuPress.menuProps}
- {...stylex.props(
- drillInStyles.list,
- !isTopView && drillInStyles.hidden,
- )}>
- {nestedContent}
- </div>,
- activeDrillIn.host,
- )
- : layer.render(
- <div
- ref={menuRef}
- id={contentId}
- role="menu"
- // Focusable as a fallback target so an empty/loading flyout can own
- // arrow/Escape keys. An overflowing flyout joins the Tab order so its
- // scrollable region is keyboard-accessible.
- tabIndex={hasOverflow ? 0 : -1}
- aria-labelledby={triggerId}
- onKeyDown={handleContentKeyDown}
- onMouseEnter={contentProps.onMouseEnter}
- onMouseLeave={contentProps.onMouseLeave}
- data-testid={menuDataTestId}
- {...menuPress.menuProps}
- {...mergeProps(
- themeProps('dropdown-menu'),
- stylex.props(
- flyoutStyles.menu,
- hasOverflow
- ? flyoutStyles.touchPanYPinchZoom
- : flyoutStyles.touchPinchZoom,
- hasOverflow && flyoutStyles.scrollable,
+ (hasRegions
+ ? // A view with a header or footer renders beside the root's menu,
+ // in its surface host, while the root steps its menu aside.
+ createPortal(
+ renderRegionsFrame(
+ <div
+ ref={menuRef}
+ id={contentId}
+ role="menu"
+ tabIndex={0}
+ aria-label={stringLabel}
+ aria-labelledby={
+ stringLabel == null ? triggerId : undefined
+ }
+ onKeyDown={handleContentKeyDown}
+ onFocus={handleMenuFocus}
+ onBlur={handleMenuBlur}
+ data-testid={menuDataTestId}
+ {...menuPress.menuProps}
+ {...surfaceOwnerProps}
+ {...stylex.props(
+ regionStyles.menu,
+ hasOverflow && flyoutStyles.scrollable,
+ hasOverflow
+ ? flyoutStyles.touchPanYPinchZoom
+ : flyoutStyles.touchPinchZoom,
+ isMenuKeyboardFocused && focusOutlineStyles.focusVisible,
+ )}>
+ {nestedContent}
+ </div>,
+ {
+ 'aria-label': stringLabel,
+ 'aria-labelledby':
+ stringLabel == null ? triggerId : undefined,
+ // A deeper view shows in its place; this one waits, hidden.
+ hidden: !isTopView,
+ inert: !isTopView,
+ },
+ 'view',
),
- )}>
- {nestedContent}
- </div>,
- {
- placement: 'end',
- alignment: 'start',
- offset: spacingVars['--spacing-1'],
- xstyle: [
- flyoutStyles.popoverViewport,
- popoverXstyle,
- layerAnimations.end,
- ],
- },
+ surfaceHost ?? activeDrillIn.host,
+ )
+ : createPortal(
+ <div
+ ref={menuRef}
+ id={contentId}
+ role="menu"
+ tabIndex={-1}
+ // The drilled-in list is named by its row's label.
+ aria-label={stringLabel}
+ aria-labelledby={stringLabel == null ? triggerId : undefined}
+ // A deeper view shows in its place; this one waits, hidden.
+ hidden={!isTopView}
+ inert={!isTopView}
+ onKeyDown={handleContentKeyDown}
+ data-testid={menuDataTestId}
+ {...menuPress.menuProps}
+ {...stylex.props(
+ drillInStyles.list,
+ !isTopView && drillInStyles.hidden,
+ )}>
+ {nestedContent}
+ </div>,
+ activeDrillIn.host,
+ ))
+ : renderFlyout(
+ layer.render(
+ hasRegions ? (
+ renderRegionsFrame(
+ <div
+ ref={menuRef}
+ id={contentId}
+ role="menu"
+ // One Tab stop between the regions.
+ tabIndex={0}
+ aria-labelledby={triggerId}
+ onKeyDown={handleContentKeyDown}
+ onFocus={handleMenuFocus}
+ onBlur={handleMenuBlur}
+ data-testid={menuDataTestId}
+ {...menuPress.menuProps}
+ {...surfaceOwnerProps}
+ {...stylex.props(
+ regionStyles.menu,
+ hasOverflow
+ ? flyoutStyles.touchPanYPinchZoom
+ : flyoutStyles.touchPinchZoom,
+ hasOverflow && flyoutStyles.scrollable,
+ isMenuKeyboardFocused && focusOutlineStyles.focusVisible,
+ )}>
+ {nestedContent}
+ </div>,
+ {
+ 'aria-labelledby': triggerId,
+ // Hovering the regions is hovering the flyout.
+ onMouseEnter: contentProps.onMouseEnter,
+ onMouseLeave: contentProps.onMouseLeave,
+ },
+ 'flyout',
+ )
+ ) : (
+ <div
+ ref={menuRef}
+ id={contentId}
+ role="menu"
+ // Focusable as a fallback target so an empty/loading flyout can own
+ // arrow/Escape keys. An overflowing flyout joins the Tab order so its
+ // scrollable region is keyboard-accessible.
+ tabIndex={hasOverflow ? 0 : -1}
+ aria-labelledby={triggerId}
+ onKeyDown={handleContentKeyDown}
+ onMouseEnter={contentProps.onMouseEnter}
+ onMouseLeave={contentProps.onMouseLeave}
+ data-testid={menuDataTestId}
+ {...menuPress.menuProps}
+ {...mergeProps(
+ themeProps('dropdown-menu'),
+ stylex.props(
+ flyoutStyles.menu,
+ hasOverflow
+ ? flyoutStyles.touchPanYPinchZoom
+ : flyoutStyles.touchPinchZoom,
+ hasOverflow && flyoutStyles.scrollable,
+ ),
+ )}>
+ {nestedContent}
+ </div>
+ ),
+ {
+ placement: 'end',
+ alignment: 'start',
+ offset: spacingVars['--spacing-1'],
+ xstyle: [
+ flyoutStyles.popoverViewport,
+ popoverXstyle,
+ layerAnimations.end,
+ ],
+ },
+ ),
)}
</>
);
diff --git a/packages/core/src/DropdownMenu/__tests__/SubMenuHeaderFooter.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/SubMenuHeaderFooter.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..767655973c
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/SubMenuHeaderFooter.a11y.chromium.spec.ts
@@ -0,0 +1,267 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SubMenuHeaderFooter.a11y.chromium.spec.ts
+ * @input The built Storybook "Submenu / header and footer" story (a Labels
+ * sub-menu with a filter field above its checkbox rows and a "Create label"
+ * button below them) and real Chromium, once as a laptop (fine pointer) and
+ * once as a phone (coarse pointer, touch).
+ * @output Evidence for component:DropdownMenu FR20: a sub-menu's header and
+ * footer sit with its rows in a modal dialog named by its row, beside every
+ * menu element rather than inside one; the row says it opens a dialog; Tab
+ * and Shift+Tab walk field, rows and button and wrap; typing filters the
+ * rows and Escape returns to the row; a pick keeps the sub-menu open. On a
+ * phone the drilled-in view holds the same regions while the root menu
+ * steps aside. On the "Submenu / header with a choice" story, a flyout the
+ * pointer has left stays open while an arrow moves the header's radio choice.
+ * @position Browser proof behind the jsdom suite: the accessibility tree, real
+ * Tab order and the pointer decision are what jsdom cannot exercise.
+ */
+
+import {devices, expect, test, type Locator, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+const storyId = 'core-dropdownmenu--sub-menu-header-and-footer';
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function mount(page: Page) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story`,
+ );
+ await expect(page.getByTestId('submenu-regions-fixture')).toBeVisible();
+}
+
+/** Whether the element sits inside any role="menu" element. */
+async function isInsideAMenu(page: Page, testName: string): Promise<boolean> {
+ return page
+ .getByRole('dialog', {name: testName})
+ .evaluate(el => el.parentElement?.closest('[role="menu"]') != null);
+}
+
+async function bounds(locator: Locator) {
+ const rect = await locator.boundingBox();
+ if (rect == null) {
+ throw new Error('no rendered bounds');
+ }
+ return rect;
+}
+
+test.describe('on a laptop (fine pointer)', () => {
+ test('the sub-menu opens a dialog beside the menu, named by its row, holding field, rows and button', async ({
+ page,
+ }) => {
+ await mount(page);
+ await page.getByRole('button', {name: 'Session'}).click();
+ const row = page.getByRole('menuitem', {name: 'Labels'});
+ await expect(row).toHaveAttribute('aria-haspopup', 'dialog');
+ await row.click();
+
+ const dialog = page.getByRole('dialog', {name: 'Labels'});
+ await expect(dialog).toBeVisible();
+ await expect(dialog).toHaveAttribute('aria-modal', 'true');
+ await expect(row).toHaveAttribute(
+ 'aria-controls',
+ (await dialog.getAttribute('id')) ?? '',
+ );
+ expect(await isInsideAMenu(page, 'Labels')).toBe(false);
+ // The sub-menu's own menu holds only its rows.
+ const menu = dialog.getByRole('menu', {name: 'Labels'});
+ expect(
+ await menu.evaluate(el =>
+ Array.from(el.querySelectorAll('[role]')).map(child =>
+ child.getAttribute('role'),
+ ),
+ ),
+ ).toEqual(Array(5).fill('menuitemcheckbox'));
+ await expect(
+ dialog.getByRole('textbox', {name: 'Filter labels'}),
+ ).toBeVisible();
+ await expect(
+ dialog.getByRole('button', {name: 'Create label'}),
+ ).toBeVisible();
+ });
+
+ test('Tab and Shift+Tab walk field, rows and button and wrap; typing filters; Escape returns to the row', async ({
+ page,
+ }) => {
+ await mount(page);
+ const trigger = page.getByRole('button', {name: 'Session'});
+ await trigger.focus();
+ await page.keyboard.press('Enter');
+ // A keyboard open lands on the first row; let it land before moving on.
+ await expect(page.getByRole('menuitem', {name: 'Rename'})).toBeFocused();
+ const row = page.getByRole('menuitem', {name: 'Labels'});
+ await page.keyboard.press('ArrowDown');
+ await expect(row).toBeFocused();
+ await page.keyboard.press('ArrowRight');
+
+ const dialog = page.getByRole('dialog', {name: 'Labels'});
+ const field = dialog.getByRole('textbox', {name: 'Filter labels'});
+ const create = dialog.getByRole('button', {name: 'Create label'});
+ const menu = dialog.getByRole('menu', {name: 'Labels'});
+ // A keyboard open lands on the first row, not the field.
+ await expect(
+ dialog.getByRole('menuitemcheckbox', {name: 'Bug'}),
+ ).toBeFocused();
+
+ await page.keyboard.press('Tab');
+ await expect(create).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(field).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(menu).toBeFocused();
+ await page.keyboard.press('Shift+Tab');
+ await expect(field).toBeFocused();
+ await page.keyboard.press('Shift+Tab');
+ await expect(create).toBeFocused();
+ await expect(dialog).toBeVisible();
+
+ // The field keeps its keys: letters type and filter the rows, and the
+ // arrow that closes a sub-menu from a row moves the caret instead.
+ await field.focus();
+ await page.keyboard.type('doc');
+ await page.keyboard.press('ArrowLeft');
+ await expect(field).toHaveValue('doc');
+ await expect(dialog.getByRole('menuitemcheckbox')).toHaveText([
+ 'Documentation',
+ ]);
+
+ await page.keyboard.press('Escape');
+ await expect(dialog).toBeHidden();
+ await expect(row).toBeFocused();
+ await expect(page.getByRole('menu', {name: 'Session'})).toBeVisible();
+ });
+
+ test('a pick keeps the sub-menu open; the button acts without closing anything', async ({
+ page,
+ }) => {
+ await mount(page);
+ await page.getByRole('button', {name: 'Session'}).click();
+ await page.getByRole('menuitem', {name: 'Labels'}).click();
+ const dialog = page.getByRole('dialog', {name: 'Labels'});
+ await dialog.getByRole('menuitemcheckbox', {name: 'Feature'}).click();
+ await expect(page.getByTestId('picked')).toHaveText('Bug, Feature');
+ await expect(dialog).toBeVisible();
+ await dialog.getByRole('button', {name: 'Create label'}).click();
+ await expect(page.getByTestId('created')).toHaveText('1');
+ await expect(dialog).toBeVisible();
+ });
+});
+
+test.describe('the press model', () => {
+ test('a press on the row, dragged into the flyout and released on a row, picks it', async ({
+ page,
+ }) => {
+ await mount(page);
+ await page.getByRole('button', {name: 'Session'}).click();
+ const row = page.getByRole('menuitem', {name: 'Labels'});
+ await row.hover();
+ const dialog = page.getByRole('dialog', {name: 'Labels'});
+ await expect(dialog).toBeVisible();
+ const feature = dialog.getByRole('menuitemcheckbox', {name: 'Feature'});
+ const [from, to] = await Promise.all([row, feature].map(bounds));
+ await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(from.x + from.width - 4, from.y + from.height / 2, {
+ steps: 4,
+ });
+ await page.mouse.move(to.x + to.width / 2, to.y + to.height / 2, {
+ steps: 8,
+ });
+ await page.mouse.up();
+ await expect(page.getByTestId('picked')).toHaveText('Bug, Feature');
+ // A checkbox pick keeps the sub-menu, and the menu, open.
+ await expect(dialog).toBeVisible();
+ });
+});
+
+test.describe('on a phone (coarse pointer)', () => {
+ const {defaultBrowserType: _browser, ...phone} = devices['Pixel 7'];
+ test.use(phone);
+
+ test('the drilled-in view holds field, rows and button beside the root menu, which steps aside', async ({
+ page,
+ }) => {
+ await mount(page);
+ const trigger = page.getByRole('button', {name: 'Session'});
+ await trigger.tap();
+ const rootMenu = page.getByRole('menu', {name: 'Session'});
+ await expect(rootMenu).toBeVisible();
+ await page.getByRole('menuitem', {name: 'Labels'}).tap();
+
+ const dialog = page.getByRole('dialog', {name: 'Labels'});
+ await expect(dialog).toBeVisible();
+ await expect(rootMenu).toBeHidden();
+ expect(await isInsideAMenu(page, 'Labels')).toBe(false);
+ // Same popover: the view replaces the root's rows in place.
+ expect(
+ await dialog.evaluate(
+ el =>
+ el.closest('[popover]') ===
+ document
+ .querySelector('[role="menu"][aria-label="Session"]')
+ ?.closest('[popover]'),
+ ),
+ ).toBe(true);
+ await expect(
+ dialog.getByRole('menuitem', {name: 'Back to Session'}),
+ ).toBeVisible();
+ await expect(
+ dialog.getByRole('textbox', {name: 'Filter labels'}),
+ ).toBeVisible();
+ await expect(
+ dialog.getByRole('button', {name: 'Create label'}),
+ ).toBeVisible();
+
+ await dialog.getByRole('menuitem', {name: 'Back to Session'}).tap();
+ await expect(dialog).toBeHidden();
+ await expect(rootMenu).toBeVisible();
+ });
+});
+
+test.describe('a header with a choice', () => {
+ test('a flyout the pointer has left stays open while an arrow moves the choice in its header', async ({
+ page,
+ }) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-dropdownmenu--sub-menu-header-choice&viewMode=story`,
+ );
+ await expect(page.getByTestId('submenu-choice-fixture')).toBeVisible();
+ await page.getByRole('button', {name: 'Filters'}).click();
+ const row = page.getByRole('menuitem', {name: 'Labels'});
+ await row.hover();
+ const dialog = page.getByRole('dialog', {name: 'Labels'});
+ await expect(dialog).toBeVisible();
+ const anyLabel = dialog.getByRole('radio', {name: 'Any label'});
+ const allLabels = dialog.getByRole('radio', {name: 'All labels'});
+ await anyLabel.click();
+ await expect(anyLabel).toBeFocused();
+
+ // The pointer leaves the flyout and the menu, and its hide delay runs out
+ // with focus still inside.
+ const viewport = page.viewportSize() ?? {width: 1280, height: 720};
+ await page.mouse.move(viewport.width - 8, viewport.height - 8, {steps: 4});
+ await page.waitForTimeout(500);
+ await expect(dialog).toBeVisible();
+
+ // The browser moves focus and the choice for the arrow itself.
+ await page.keyboard.press('ArrowDown');
+ await expect(allLabels).toBeFocused();
+ await expect(allLabels).toBeChecked();
+ await expect(page.getByTestId('match')).toHaveText('all');
+ await expect(dialog).toBeVisible();
+ });
+});
diff --git a/packages/core/src/DropdownMenu/menuRegionStops.ts b/packages/core/src/DropdownMenu/menuRegionStops.ts
index 5dd7d2ace5..438c4dcc24 100644
--- a/packages/core/src/DropdownMenu/menuRegionStops.ts
+++ b/packages/core/src/DropdownMenu/menuRegionStops.ts
@@ -8,8 +8,8 @@
* @output `tabbablesIn`, `focusRegionControl`, `moveRegionsTab`: the Tab stops
* of a header or footer region and the walk through a menu with regions,
* with a named radio group as one stop
- * @position Internal; DropdownMenu's walk through its header and footer, in a
- * module of its own so another menu level with regions can share it.
+ * @position Internal; used by DropdownMenu (the root menu's header and footer)
+ * and DropdownMenuSubMenu (a sub-menu's header and footer).
*
* A menu with a header or footer is a dialog: Tab and Shift+Tab walk the
* header's controls, the menu as one stop, then the footer's controls, and
diff --git a/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md b/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md
index 756a67458b..7bb64d1e8b 100644
--- a/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md
+++ b/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md
@@ -163,6 +163,14 @@ Consumer migration instructions belong in consumer docs and release notes.
claimed by the innermost root carrying `data-astryx-menu-press` (a flyout
before its parent); the outermost root decides what counts as "inside the
menu" for the release.
+- **ORD1a (proposed) — A menu beside the root.** A root carrying
+ `data-astryx-menu-press-surface`, which names another root's `id`, is nested
+ in that root for ORD1, as a flyout inside the root's DOM is: a release on
+ its rows is inside the menu. Only the menu of a sub-menu with a header or
+ footer, which the root renders beside itself (`component:DropdownMenu`
+ FR20), carries it. Anything else beside the root, a header field or a picker
+ placed in a region say, is outside the menu, as the root's own regions are,
+ and a picker there stays its own root. Pending owner review.
- **ORD2 — Release resolution.** Enabled row under the point → `act`; inside
the menu or on the trigger with no row → `settle` (stray click swallowed,
menu stays); outside → `settle` with `dismiss` only for a mouse.
@@ -238,6 +246,7 @@ owned by the item components.
| FR4 (scroll) | `MenuPress.a11y.chromium.spec.ts` (real Chromium) | Chromium touch pan in an overflowing menu; touch-action by overflow; finger slide and its stray click | Not provable in jsdom; a pan that acts on a row, or a slide that acts on the press row, fails |
| FR4 (pinch) | `MenuPinchZoom.a11y.chromium.spec.ts` (real Chromium, phone emulation) | two-finger pinch over a menu whose rows fit, over one that scrolls, and over a picker listbox | Not provable in jsdom; a pinch that leaves the page at scale 1, or acts on a row, fails |
| FR8, FR9 (proposed) | `menuPressGesture.test.ts` trigger states; `useMenuPress.test.tsx` trigger suite; `DropdownMenu.test.tsx` press-open cases | mouse opens at once, finger tap, held finger, settle before/after, cancel; press-open + drag-release, unsettled 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 |
+| ORD1a (proposed) | `DropdownMenuSubMenu.test.tsx` press cases; `SubMenuHeaderFooter.a11y.chromium.spec.ts` press-drag case | a mouse press on a menu row released on a row of a sub-menu rendered beside the menu; the same press released on that sub-menu's header field | A release on such a row that acts on nothing or closes the menu, or a release on its header field that acts, fails. |
## Decision log
diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts
index bc28f2fb72..91375393b5 100644
--- a/packages/core/src/hooks/useMenuPress.ts
+++ b/packages/core/src/hooks/useMenuPress.ts
@@ -36,7 +36,9 @@
*
* The menu root is marked `data-astryx-menu-press` so a nested flyout (a DOM
* descendant of its parent menu) can tell which level owns a press, and so a
- * surface can be recognised as carrying this model.
+ * surface can be recognised as carrying this model. A menu the root renders
+ * beside itself names the root with `data-astryx-menu-press-surface` and counts
+ * as nested in it.
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
@@ -60,6 +62,14 @@ import {useLongPress, type UseLongPressHandlers} from './useLongPress';
/** Marks a menu root that carries this press model. */
export const MENU_PRESS_MARKER = 'data-astryx-menu-press';
const MENU_PRESS_ROOT_SELECTOR = `[${MENU_PRESS_MARKER}]`;
+/**
+ * Carried by a menu root that another root renders beside itself rather than
+ * inside it, naming that root's `id`: the menu of a sub-menu with a header or
+ * footer, in a dialog beside the root's menu, is nested in that root for the
+ * press model, as a flyout inside the root's DOM is. Nothing else beside the
+ * root carries it, so a picker placed in a header or footer stays its own root.
+ */
+export const MENU_PRESS_SURFACE_ATTR = 'data-astryx-menu-press-surface';
/** How long after a tracked release the browser's click is still swallowed. */
export const MENU_PRESS_STRAY_CLICK_MS = 400;
@@ -246,16 +256,44 @@ function isRowFocusable(row: HTMLElement): boolean {
function getOutermostRoot(menu: HTMLElement): HTMLElement {
let root = menu;
for (;;) {
- const parent = root.parentElement?.closest<HTMLElement>(
- MENU_PRESS_ROOT_SELECTOR,
- );
- if (parent == null) {
+ const parent =
+ root.parentElement?.closest<HTMLElement>(MENU_PRESS_ROOT_SELECTOR) ??
+ getSurfaceOwner(root);
+ if (parent == null || parent === root) {
return root;
}
root = parent;
}
}
+/**
+ * The menu root that renders `menu` beside itself, if any (see
+ * `MENU_PRESS_SURFACE_ATTR`). Read off the menu itself, never an ancestor, so
+ * a root placed in a region of that surface is not adopted.
+ */
+function getSurfaceOwner(menu: HTMLElement): HTMLElement | null {
+ const ownerId = menu.getAttribute(MENU_PRESS_SURFACE_ATTR);
+ if (!ownerId) {
+ return null;
+ }
+ const owner = menu.ownerDocument.getElementById(ownerId);
+ return owner?.matches(MENU_PRESS_ROOT_SELECTOR) === true ? owner : null;
+}
+
+/**
+ * Whether `element` is inside the menu tree whose outermost root is `root`:
+ * inside the root itself, or inside a menu nested in it through a surface
+ * the root renders beside itself. Anything else in such a surface (a header
+ * field, say) is outside the menu, as the root's own regions are.
+ */
+function isInMenuTree(element: Element, root: HTMLElement): boolean {
+ if (root.contains(element)) {
+ return true;
+ }
+ const owner = element.closest<HTMLElement>(MENU_PRESS_ROOT_SELECTOR);
+ return owner != null && getOutermostRoot(owner) === root;
+}
+
interface ResolvedPoint {
row: HTMLElement | null;
isInMenu: boolean;
@@ -332,14 +370,14 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
}
const root = menu == null ? null : getOutermostRoot(menu);
const isInMenu =
- root != null && element != null && root.contains(element);
+ root != null && element != null && isInMenuTree(element, root);
const trigger = triggerRef?.current ?? null;
const isOnTrigger =
trigger != null && element != null && trigger.contains(element);
let row: HTMLElement | null = null;
if (isInMenu && element != null) {
row = element.closest<HTMLElement>(itemSelector);
- if (row != null && !root.contains(row)) {
+ if (row != null && !isInMenuTree(row, root)) {
row = null;
}
}