Skip to content

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

TypeScript

feat(DropdownMenuSubMenu): drill in on a phone instead of opening a flyout (#6682)

Christopher Chedeau6197cfb51b13
diff --git a/.changeset/menu-submenu-drill-in.md b/.changeset/menu-submenu-drill-in.md
new file mode 100644
index 0000000000..da813b4bc5
--- /dev/null
+++ b/.changeset/menu-submenu-drill-in.md
@@ -0,0 +1,13 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DropdownMenuSubMenu drills in on a phone instead of opening a flyout.
+
+When a coarse pointer opened the menu, a sub-menu row replaces the menu's rows
+with its own and a "Back to <parent>" row, in the same box; Back, Escape or
+ArrowLeft return to the row. Works in compound and data mode, inside
+`DropdownMenu` and `ContextMenu`; `presentation` (`flyout` | `drill-in` |
+`adaptive`) overrides the policy.
+
+@vjeux
diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsx
index c3b73547f8..b78206c369 100644
--- a/apps/storybook/stories/DropdownMenu.stories.tsx
+++ b/apps/storybook/stories/DropdownMenu.stories.tsx
@@ -1344,3 +1344,53 @@ export const LinkRows: Story = {
},
},
};
+
+export const SubmenuDrillIn: Story = {
+ name: 'Submenu / drill-in on a phone',
+ parameters: {
+ viewport: {defaultViewport: 'mobile1'},
+ docs: {
+ description: {
+ story:
+ 'On a phone (a coarse pointer, decided when the menu opened) a sub-menu row drills in: its rows replace the menu\'s rows in the same box, led by a "Back to <parent>" row; Back, Escape or ArrowLeft return to the row. `presentation="drill-in"` forces it, `"flyout"` keeps the flyout; the default `"adaptive"` follows the pointer.',
+ },
+ },
+ },
+ render: () => (
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem icon={PencilIcon} label="Rename" onClick={() => {}} />
+ <DropdownMenuSubMenu
+ icon={FolderPlusIcon}
+ label="Move to"
+ presentation="drill-in">
+ <DropdownMenuItem label="Folder A" onClick={() => {}} />
+ <DropdownMenuItem label="Folder B" onClick={() => {}} />
+ <DropdownMenuSubMenu icon={ArchiveBoxIcon} label="Archive">
+ <DropdownMenuItem label="2025" onClick={() => {}} />
+ <DropdownMenuItem label="2024" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenuSubMenu>
+ <DropdownMenuItem icon={TrashIcon} label="Delete" onClick={() => {}} />
+ </DropdownMenu>
+ ),
+};
+
+export const SubmenuAdaptiveFixture: Story = {
+ name: 'Submenu / adaptive fixture',
+ parameters: {docs: {disable: true}},
+ render: () => (
+ <div data-testid="drill-in-fixture" style={{padding: 16}}>
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem icon={PencilIcon} label="Rename" onClick={() => {}} />
+ <DropdownMenuSubMenu icon={FolderPlusIcon} label="Move to">
+ <DropdownMenuItem label="Folder A" onClick={() => {}} />
+ <DropdownMenuItem label="Folder B" onClick={() => {}} />
+ <DropdownMenuSubMenu icon={ArchiveBoxIcon} label="Archive">
+ <DropdownMenuItem label="2025" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenuSubMenu>
+ <DropdownMenuItem icon={TrashIcon} label="Delete" onClick={() => {}} />
+ </DropdownMenu>
+ </div>
+ ),
+};
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 36d7c6c1f3..77d272107e 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -435,6 +435,10 @@
"defaultMessage": "Back",
"description": "Button label that returns from a nested action list to its parent inside a DropdownMenu bottom sheet. Imperative navigation action."
},
+ "@astryx.dropdownMenu.backTo": {
+ "defaultMessage": "Back to {parent}",
+ "description": "Menu row that returns from a drilled-in sub-menu to the menu it came from. {parent} is that menu's name (e.g. \"Back to Actions\"). Imperative navigation action."
+ },
"@astryx.lightbox.close": {
"defaultMessage": "Close",
"description": "\"Close\" = shut/dismiss (not \"nearby\"). Screen-reader-only label on the X button that dismisses a Lightbox."
diff --git a/packages/core/src/ContextMenu/ContextMenu.spec.md b/packages/core/src/ContextMenu/ContextMenu.spec.md
index f97923891c..c506aeb816 100644
--- a/packages/core/src/ContextMenu/ContextMenu.spec.md
+++ b/packages/core/src/ContextMenu/ContextMenu.spec.md
@@ -9,7 +9,7 @@ superseded_by: null
approved_by: null
approved_at: null
owners: [cixzhang]
-review_triggers: [theming, public-api, behavior, accessibility]
+review_triggers: [accessibility, behavior, public-api, theming]
verified_by:
[
packages/core/src/ContextMenu/ContextMenu.test.tsx,
@@ -89,6 +89,7 @@ Consumer props, content modes, and presentation policy remain documented in
| FR4 | Compound `menuContent` remains a caller-supplied pointer-menu interior and may also render inside the touch frame; the data-driven touch path instead converts the same item data to List and ListItem presentation. | Current source and tests | Verified current branches; no behavior change |
| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the stray click never acts, and `touch-action` follows overflow. Right-click, Shift+F10, long-press invocation and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `ContextMenu.test.tsx` press model suite | Proposed; verified in jsdom |
| FR6 | With `triggerAs="span"` the Trigger area MUST be an inline element that owns a box, so the cursor anchor measures from the trigger's own rect on every invocation path. Every invocation path (right-click, Shift+F10, long-press) and the `context-menu` target's placement are unchanged. | `component:ContextMenu/DEC-1` | Accepted; verified in jsdom |
+| FR7 | Sub-menu rows follow `component:DropdownMenu` FR12 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. | `component:DropdownMenu/DEC-2` | Proposed; verified in jsdom |
### Allowed variation
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index eacaaf42d3..b36315c945 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -63,6 +63,7 @@ import {
activateMenuItem,
} from '../DropdownMenu/menuItemRoles';
import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow';
+import {useMenuDrillIn} from '../DropdownMenu/useMenuDrillIn';
import {useListFocus} from '../hooks/useListFocus';
import {useMenuPress} from '../hooks/useMenuPress';
import {useTypeahead} from '../hooks/useTypeahead';
@@ -595,13 +596,17 @@ export function ContextMenu({
? styles.popoverCustomWidth(menuWidth)
: styles.popover;
+ // The drill-in view stack for sub-menus on a phone; the bottom sheet has
+ // its own drill-in.
+ const {drillIn, wrapContent} = useMenuDrillIn(isOpen && !usesBottomSheet);
const contextValue = useMemo<DropdownMenuContextValue>(
- () => ({closeMenu, menuSize: size}),
- [closeMenu, size],
+ () => ({closeMenu, menuSize: size, drillIn, menuLabel: label}),
+ [closeMenu, size, drillIn, label],
);
- const resolvedMenuContent =
- itemsProp !== undefined ? renderDropdownItems(items) : menuContent;
+ const resolvedMenuContent = wrapContent(
+ itemsProp !== undefined ? renderDropdownItems(items) : menuContent,
+ );
const hasOverflow = useMenuOverflow(
listRef,
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index 824105da33..9dea8ed1be 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -258,7 +258,7 @@ export const docs = {
name: 'children',
type: 'ReactNode',
description:
- 'Compound-mode menu content: DropdownMenuItem, DropdownMenuDivider, DropdownMenuSubMenu, and the selectable items. Mutually exclusive with `items`.',
+ 'Compound-mode menu content: DropdownMenuItem, DropdownMenuDivider, DropdownMenuSubMenu (a flyout on a laptop, a drilled-in view with a Back row on a phone), and the selectable items. Mutually exclusive with `items`.',
},
],
components: [{name: 'DropdownMenuItem'}],
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
index 964b274d3b..09d5fc69d5 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md
+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
@@ -15,6 +15,7 @@ verified_by:
packages/core/src/DropdownMenu/DropdownMenu.test.tsx,
packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx,
packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx,
+ packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts,
packages/core/src/BottomSheet/BottomSheet.test.tsx,
packages/core/src/List/List.test.tsx,
packages/core/src/Indicator/Indicator.test.tsx,
@@ -93,20 +94,22 @@ released default.
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
-| FR1 | Every current render contains a Trigger button. Pointer presentation renders a Pointer menu surface with pointer-owned rows and optional pointer headings, dividers, indicators, and nested flyouts. Touch presentation renders a Touch sheet frame containing a Touch menu surface, Touch heading, Touch action list, and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR2 | The six current local targets are `dropdown-menu`, `dropdown-menu-item`, `dropdown-menu-radio`, `dropdown-menu-section-heading`, `dropdown-menu-divider`, and `dropdown-menu-indicator-icon`; every target remains on its current painted element. | Current source, docs, and tests | Verified current inventory; no target change |
-| FR3 | Button owns the Trigger button, BottomSheet owns the Touch sheet frame, List owns the Touch action list and Touch action rows, Indicator owns checkbox chrome, and Icon owns ordinary rendered icons. | Current source and owner docs | Verified current delegation; no ownership change |
-| FR4 | The same `dropdown-menu` target reaches the alternative Pointer menu surface and Touch menu surface. Pointer action rows retain `dropdown-menu-item`; touch action rows instead use List's `list-item` target. | Current source and tests | Verified modality split; no target change |
-| FR5 | Both menu surfaces carry `data-astryx-menu-press` and follow `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the browser's stray click never acts, and the Pointer menu surface declares `touch-action` by overflow. Trigger opening and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom and real Chromium |
-| FR6 | When the pointer menu closes, focus returns to the Trigger button with a visible ring only when the menu was driven by keyboard; a press outside that landed on a focusable control keeps focus there. | `architecture:interaction-modality` INV1; proposed in this change; `DropdownMenu.test.tsx` closing suite | Proposed; verified in jsdom, pending owner review |
-| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
-| FR8 | The Trigger button opens the pointer menu on a mouse press-down and on a finger held for the long-press delay, with the module's settle rule on the opening release; pressing the trigger of an open menu closes it without reopening in the same gesture; a tap and the keyboard open as before (`module:DropdownMenu/useMenuPress` proposed FR8, FR9). | Proposed `module:DropdownMenu/useMenuPress/DEC-4`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom, pending owner review |
-| Trigger source | `button` (Button props) or `renderTrigger` (render prop) | Which control the menu hangs off. `trigger` receives `DropdownMenuTriggerProps` — the press model, keyboard opens, toggle click and ARIA wiring — and names the menu. | Both presentations | `button` | `component:DropdownMenu` | stable | Both given: `trigger` wins and a dev warning fires. |
-| FR9 | With `renderTrigger`, the rendered control MUST carry `aria-haspopup`, `aria-expanded`, `aria-controls` and the `id` the menu's `aria-labelledby` points at, and MUST receive the same press-model, keyboard-open and toggle-click handlers as the Button path; the menu is named by that control. `button` and `trigger` are mutually exclusive: both given, `trigger` wins and a dev warning fires, in both presentations. | `component:DropdownMenu/DEC-2` | Proposed; verified in jsdom; owner to confirm DEC-2 |
-| Row destination | `href` (+ `target`, `rel`) on an action item | The row's act is navigation: the row itself is the link (`family:navigation-destinations`). | Pointer action row and Touch action row, compound and data mode | none (an action row) | `component:DropdownMenu` | stable | Blocked schemes follow the family rule; a disabled row has none. |
-| FR10 | An action row with `href` MUST render as one anchor carrying `role="menuitem"` (the pointer menu) or the touch sheet's link row, routed through `LinkProvider`; a plain click MUST run `onClick`, then close the menu (`hasCloseOnSelect`), then let the browser navigate; a modified click or middle click MUST be left to the browser and MUST NOT run `onClick`; Enter and Space MUST activate through a synthesized click that carries the key's modifiers. A disabled link row has no `href`. | `component:DropdownMenu/DEC-2`; `family:navigation-destinations` | Proposed; verified in jsdom; owner to confirm DEC-1 |
+| ID | Candidate invariant | Basis | Draft review state |
+| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
+| FR1 | Every current render contains a Trigger button. Pointer presentation renders a Pointer menu surface with pointer-owned rows and optional pointer headings, dividers, indicators, and nested flyouts. Touch presentation renders a Touch sheet frame containing a Touch menu surface, Touch heading, Touch action list, and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
+| FR2 | The six current local targets are `dropdown-menu`, `dropdown-menu-item`, `dropdown-menu-radio`, `dropdown-menu-section-heading`, `dropdown-menu-divider`, and `dropdown-menu-indicator-icon`; every target remains on its current painted element. | Current source, docs, and tests | Verified current inventory; no target change |
+| FR3 | Button owns the Trigger button, BottomSheet owns the Touch sheet frame, List owns the Touch action list and Touch action rows, Indicator owns checkbox chrome, and Icon owns ordinary rendered icons. | Current source and owner docs | Verified current delegation; no ownership change |
+| FR4 | The same `dropdown-menu` target reaches the alternative Pointer menu surface and Touch menu surface. Pointer action rows retain `dropdown-menu-item`; touch action rows instead use List's `list-item` target. | Current source and tests | Verified modality split; no target change |
+| FR5 | Both menu surfaces carry `data-astryx-menu-press` and follow `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the browser's stray click never acts, and the Pointer menu surface declares `touch-action` by overflow. Trigger opening and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom and real Chromium |
+| FR6 | When the pointer menu closes, focus returns to the Trigger button with a visible ring only when the menu was driven by keyboard; a press outside that landed on a focusable control keeps focus there. | `architecture:interaction-modality` INV1; proposed in this change; `DropdownMenu.test.tsx` closing suite | Proposed; verified in jsdom, pending owner review |
+| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
+| FR8 | The Trigger button opens the pointer menu on a mouse press-down and on a finger held for the long-press delay, with the module's settle rule on the opening release; pressing the trigger of an open menu closes it without reopening in the same gesture; a tap and the keyboard open as before (`module:DropdownMenu/useMenuPress` proposed FR8, FR9). | Proposed `module:DropdownMenu/useMenuPress/DEC-4`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom, pending owner review |
+| Trigger source | `button` (Button props) or `renderTrigger` (render prop) | Which control the menu hangs off. `trigger` receives `DropdownMenuTriggerProps` — the press model, keyboard opens, toggle click and ARIA wiring — and names the menu. | Both presentations | `button` | `component:DropdownMenu` | stable | Both given: `trigger` wins and a dev warning fires. |
+| FR9 | With `renderTrigger`, the rendered control MUST carry `aria-haspopup`, `aria-expanded`, `aria-controls` and the `id` the menu's `aria-labelledby` points at, and MUST receive the same press-model, keyboard-open and toggle-click handlers as the Button path; the menu is named by that control. `button` and `trigger` are mutually exclusive: both given, `trigger` wins and a dev warning fires, in both presentations. | `component:DropdownMenu/DEC-2` | Proposed; verified in jsdom; owner to confirm DEC-2 |
+| Row destination | `href` (+ `target`, `rel`) on an action item | The row's act is navigation: the row itself is the link (`family:navigation-destinations`). | Pointer action row and Touch action row, compound and data mode | none (an action row) | `component:DropdownMenu` | stable | Blocked schemes follow the family rule; a disabled row has none. |
+| FR10 | An action row with `href` MUST render as one anchor carrying `role="menuitem"` (the pointer menu) or the touch sheet's link row, routed through `LinkProvider`; a plain click MUST run `onClick`, then close the menu (`hasCloseOnSelect`), then let the browser navigate; a modified click or middle click MUST be left to the browser and MUST NOT run `onClick`; Enter and Space MUST activate through a synthesized click that carries the key's modifiers. A disabled link row has no `href`. | `component:DropdownMenu/DEC-2`; `family:navigation-destinations` | Proposed; verified in jsdom; owner to confirm DEC-1 |
+| Sub-menu presentation | `presentation` on a sub-menu row: `flyout`, `drill-in`, `adaptive` | Whether a sub-menu opens beside its row or replaces the menu's rows with its own and a Back row, in the same box. `adaptive` drills in when a coarse pointer opened the menu. | Pointer presentation, compound and data mode | `adaptive` | `component:DropdownMenu` | stable | An unknown value reads as `adaptive`. |
+| FR11 | When a compact touch display opened the pointer menu (`COMPACT_TOUCH_PRESENTATION_QUERY`, the same query the root presentation uses for its bottom sheet, sampled once as it opens) an `adaptive` sub-menu row MUST drill in: its rows and a leading Back row named "Back to <parent>" replace the menu's rows in the same Pointer menu surface, no flyout opens, the drilled list is a `menu` named by the row's label, and Back, Escape and ArrowLeft MUST return to the row with focus on it; a pick inside closes the whole menu. Roving focus and typeahead scope to the shown rows; sibling rows and dividers need no knowledge of it. `presentation="flyout"` keeps the flyout; `"drill-in"` drills in on any pointer. | `component:DropdownMenu/DEC-2`; `architecture:interaction-modality` | Proposed; verified in jsdom and Chromium (coarse pointer); owner to confirm DEC-5 |
### Allowed variation
@@ -135,6 +138,7 @@ released default.
- **ORD2 — Link row activation.** modified click → the browser alone; else
`onClick` → close (`hasCloseOnSelect`) → the browser navigates.
+ | Drilled-in sub-menu | The Pointer menu surface shows a Back row then the sub-menu's rows; the parent rows are hidden, not unmounted. | Depth; which pointer opened the menu; a forced `presentation`. |
- No other presentation-resolution, open-state, positioning, or styling
precedence rule is introduced.
@@ -253,19 +257,20 @@ than adding a DropdownMenu-owned heading target.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
-| FR1, FR4 | `DropdownMenu.test.tsx` pointer, bottom-sheet, adaptive, section, divider, and drill-in suites | Root pointer, nested pointer, root touch, drill-in | Collapsing presentation-specific parts or owners fails structure, target, or role assertions. | `audit:DropdownMenu/anatomy` |
-| FR2 | DropdownMenu target suites, source inspection, and theming target inventories | All six local targets | Removing, renaming, or assigning a current target to the wrong part fails evidence or inventory. | `audit:DropdownMenu/theming` |
-| FR3 | `DropdownMenuSelectable.test.tsx` plus BottomSheet, List, Indicator, Icon, and Divider owner tests | Trigger, touch actions, icons, checkbox, radio | A composed part loses its owner target or is documented as a new local target. | `audit:DropdownMenu/theming` |
-| Layer relationships | `DropdownMenu.test.tsx`, `DropdownMenuSubMenu.test.tsx`, and current layer/dismissal architecture records | Light dismiss, nested flyout, sheet dismissal | Documentation claims a shared owner where current source retains local behavior, or the reverse. | `audit:DropdownMenu/behavior` |
-| FR5 | `DropdownMenu.test.tsx` press model suite; the module record's own map | Finger slide across rows, outside release by mouse and finger, `touch-action`, root marker | A row acting on the press or the stray click, a lost `touch-action`, or a finger release that closes fails. | `audit:DropdownMenu/behavior` |
-| FR6 | `DropdownMenu.test.tsx` dismissal and closing suites | keyboard dismissal, pointer dismissal, press outside on a control, pointer pick, closed menu | Focus left on the body after a pointer pick, or a ring after pointer input, fails. | `audit:DropdownMenu/behavior` |
-| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:DropdownMenu/theming` |
-| FR8 | `DropdownMenu.test.tsx` press model suite (trigger cases) | Press-open + drag-release, unsettled opening release, trigger toggle, held touch, tap | A menu that does not open on a mouse press, an unsettled release that acts, or a trigger that reopens in the same gesture fails. | `audit:DropdownMenu/behavior` |
-| FR9 | `DropdownMenu.test.tsx` custom trigger suite | Icon button, chip, list row; open, toggle, keyboard open, name | A rendered control missing `aria-haspopup`, `aria-expanded` or `aria-controls`, an unnamed menu, or a lost keyboard open, fails. | `audit:DropdownMenu/anatomy` |
-| FR8, AR2 | `DropdownMenu.test.tsx` "DropdownMenuItem href" suite (pointer menu and bottom sheet) | Plain click, ⌘-click, Enter with modifiers, disabled link row | A row rendering an inner anchor, running `onClick` on a modified click, or a synthesized click dropping the modifiers fails. | `audit:DropdownMenu/behavior` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
+| FR1, FR4 | `DropdownMenu.test.tsx` pointer, bottom-sheet, adaptive, section, divider, and drill-in suites | Root pointer, nested pointer, root touch, drill-in | Collapsing presentation-specific parts or owners fails structure, target, or role assertions. | `audit:DropdownMenu/anatomy` |
+| FR2 | DropdownMenu target suites, source inspection, and theming target inventories | All six local targets | Removing, renaming, or assigning a current target to the wrong part fails evidence or inventory. | `audit:DropdownMenu/theming` |
+| FR3 | `DropdownMenuSelectable.test.tsx` plus BottomSheet, List, Indicator, Icon, and Divider owner tests | Trigger, touch actions, icons, checkbox, radio | A composed part loses its owner target or is documented as a new local target. | `audit:DropdownMenu/theming` |
+| Layer relationships | `DropdownMenu.test.tsx`, `DropdownMenuSubMenu.test.tsx`, and current layer/dismissal architecture records | Light dismiss, nested flyout, sheet dismissal | Documentation claims a shared owner where current source retains local behavior, or the reverse. | `audit:DropdownMenu/behavior` |
+| FR5 | `DropdownMenu.test.tsx` press model suite; the module record's own map | Finger slide across rows, outside release by mouse and finger, `touch-action`, root marker | A row acting on the press or the stray click, a lost `touch-action`, or a finger release that closes fails. | `audit:DropdownMenu/behavior` |
+| FR6 | `DropdownMenu.test.tsx` dismissal and closing suites | keyboard dismissal, pointer dismissal, press outside on a control, pointer pick, closed menu | Focus left on the body after a pointer pick, or a ring after pointer input, fails. | `audit:DropdownMenu/behavior` |
+| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:DropdownMenu/theming` |
+| FR8 | `DropdownMenu.test.tsx` press model suite (trigger cases) | Press-open + drag-release, unsettled opening release, trigger toggle, held touch, tap | A menu that does not open on a mouse press, an unsettled release that acts, or a trigger that reopens in the same gesture fails. | `audit:DropdownMenu/behavior` |
+| FR9 | `DropdownMenu.test.tsx` custom trigger suite | Icon button, chip, list row; open, toggle, keyboard open, name | A rendered control missing `aria-haspopup`, `aria-expanded` or `aria-controls`, an unnamed menu, or a lost keyboard open, fails. | `audit:DropdownMenu/anatomy` |
+| FR8, AR2 | `DropdownMenu.test.tsx` "DropdownMenuItem href" suite (pointer menu and bottom sheet) | Plain click, ⌘-click, Enter with modifiers, disabled link row | A row rendering an inner anchor, running `onClick` on a modified click, or a synthesized click dropping the modifiers fails. | `audit:DropdownMenu/behavior` |
+| FR12, AR3 | `DropdownMenuSubMenu.test.tsx` "drill-in on a phone" suite; `__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts` (real Chromium, coarse pointer) | Drill in, Back, Escape, ArrowLeft, nested level, scoped typeahead, forced presentations, close resets | A flyout opening on a coarse pointer, a missing Back row, sibling rows staying in the order, or focus not returning to the row fails. | `audit:DropdownMenu/behavior` |
## Decision log
@@ -303,6 +308,8 @@ viewport term cannot reason about.
### DEC-3 — Any control can open a menu
+### DEC-4 — Sub-menus drill in on a phone
+
**Reference:** `component:DropdownMenu/DEC-3`
**Decider:** `cixzhang`, 2026-10-02
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index c243eb1fa9..d387c0e70e 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -17,7 +17,10 @@
* Both modes use useListFocus for DOM-based keyboard navigation.
*
* The trigger is the design system's Button (`button`) or any control the
- * caller renders (`trigger`).
+ * caller renders (`renderTrigger`).
+ *
+ * A sub-menu drills in on a phone through the view stack useMenuDrillIn
+ * keeps; the root shows the drilled view in place of its rows.
*
* Initial focus on open follows the input modality: a keyboard open
* (Enter / Space / ArrowDown on the trigger) focuses the first enabled item
@@ -67,6 +70,7 @@ import {useTypeahead} from '../hooks/useTypeahead';
import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';
import {useMenuOverflow} from './useMenuOverflow';
import {useDevWarning} from '../hooks/useDevWarning';
+import {useMenuDrillIn} from './useMenuDrillIn';
import {resolveMenuWidth} from './menuWidth';
import {
useAdaptivePresentation,
@@ -1145,16 +1149,23 @@ function DropdownMenuPopover({
? styles.popoverCentered
: styles.popoverAligned;
const isSidePlacement = placement === 'start' || placement === 'end';
+
+ // The drill-in view stack for sub-menus on a phone.
+ const {drillIn, wrapContent} = useMenuDrillIn(isOpen);
+ // The name a drilled-in view's Back row returns to.
+ const menuLabel = typeof button.label === 'string' ? button.label : undefined;
+
const resolvedMaxHeight = menuMaxHeight == null ? null : `${menuMaxHeight}px`;
// Context for compound items
const contextValue = useMemo<DropdownMenuContextValue>(
- () => ({closeMenu, menuSize}),
- [closeMenu, menuSize],
+ () => ({closeMenu, menuSize, drillIn, menuLabel}),
+ [closeMenu, menuSize, drillIn, menuLabel],
);
// Resolve menu content: data-driven items become components
- const menuContent =
- props.items !== undefined ? renderDropdownItems(items) : children;
+ const menuContent = wrapContent(
+ props.items !== undefined ? renderDropdownItems(items) : children,
+ );
const hasOverflow = useMenuOverflow(listRef, menuContent, popover.isOpen);
const triggerProps: DropdownMenuTriggerProps = {
diff --git a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx b/packages/core/src/DropdownMenu/DropdownMenuContext.tsx
index d08bfbeba9..c287f2dce8 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuContext.tsx
@@ -6,7 +6,8 @@
* @file DropdownMenuContext.tsx
* @input Layer-scoped React context
* @output Exports context and hook for compound-component menu coordination
- * @position Internal; used by DropdownMenu and DropdownMenuItem
+ * @position Internal; used by DropdownMenu, DropdownMenuItem and the
+ * drill-in stack (useMenuDrillIn, DropdownMenuSubMenu)
*
* Provides menu state (close callback, size) to compound children.
* Keyboard navigation is handled by useListFocus on the menu container —
@@ -19,11 +20,49 @@ import {createLayerScopedContext} from '../Layer/layerScopedContext';
/** Menu size, derived from the trigger button size. */
export type DropdownMenuSize = 'sm' | 'md' | 'lg';
+/**
+ * The drill-in view stack a menu root keeps for its sub-menus.
+ * On a phone a sub-menu row pushes its view and the root shows that view in
+ * place of its own rows; Back, Escape and ArrowLeft pop it. Sibling rows and
+ * dividers need no knowledge of it: they are simply hidden while a view shows.
+ *
+ * Internal. The public surface for this behavior is `presentation` alone;
+ * this is a view-stack controller, and exporting it would make internal
+ * machinery permanent API that nothing requires a caller to touch. A product
+ * that later needs to drive the stack earns a deliberate component or hook
+ * then, with its own contract.
+ * @internal
+ */
+export interface DropdownMenuDrillIn {
+ /**
+ * Whether the menu opened on a compact touch display — decided once, when
+ * the menu opened, on the same query the root presentation uses for its
+ * bottom sheet. An `adaptive` sub-menu drills in exactly then, so one
+ * component carries one meaning of "adaptive".
+ */
+ isCompactTouch: boolean;
+ /** The pushed view ids, outermost first; the last one is the view shown. */
+ 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. */
+ push: (viewId: string) => void;
+ /** Return to the rows the shown view replaced. */
+ pop: () => void;
+}
+
export interface DropdownMenuContextValue {
/** Close the menu; keyboard dismissal returns focus to the trigger. */
closeMenu: () => void;
/** Menu size derived from button size */
menuSize: DropdownMenuSize;
+ /** The drill-in view stack; absent in a menu that cannot drill in. */
+ drillIn?: DropdownMenuDrillIn;
+ /**
+ * The name of this menu level, when known as text: a drilled-in view's Back
+ * row reads "Back to <this>".
+ */
+ menuLabel?: string;
}
export const DropdownMenuContext =
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs
index e0f1768a1b..fb2bb71b51 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs
@@ -8,7 +8,7 @@ export const docs = {
displayName: 'Dropdown Menu Submenu',
isHiddenFromOverview: true,
description:
- 'A single menu row that reveals a nested flyout of its own items. The row adopts DropdownMenuItem semantics (label / icon / description / isDisabled); its children become the flyout content. Opens inline-end with viewport auto-flip; Right/Enter/Space opens and focuses the first item, Left/Escape closes and returns focus to the trigger (Right/Left swap in RTL). For data-driven menus, give a menu item a nested `items` array instead of using this component directly.',
+ 'A single menu row that reveals a nested flyout of its own items. The row adopts DropdownMenuItem semantics (label / icon / description / isDisabled); its children become the flyout content. Opens inline-end with viewport auto-flip; Right/Enter/Space opens and focuses the first item, Left/Escape closes and returns focus to the trigger (Right/Left swap in RTL). On a phone (a coarse pointer, decided when the menu opened) the row drills in instead: its rows replace the menu\'s rows in the same box, led by a Back row named "Back to <parent>", and Back, Escape or ArrowLeft return to the row. For data-driven menus, give a menu item a nested `items` array instead of using this component directly.',
playground: {
defaults: {label: 'Move to'},
},
@@ -47,7 +47,7 @@ export const docs = {
type: 'boolean',
default: 'false',
description:
- 'Show a spinner in place of the caret, e.g. while a lazy submenu\'s children are loading.',
+ "Show a spinner in place of the caret, e.g. while a lazy submenu's children are loading.",
},
{
name: 'menuWidth',
@@ -60,6 +60,13 @@ export const docs = {
type: '(isOpen: boolean) => void',
description: 'Called when the flyout opens or closes.',
},
+ {
+ name: 'presentation',
+ type: "'flyout' | 'drill-in' | 'adaptive'",
+ description:
+ "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: 'xstyle',
type: 'StyleXStyles',
@@ -74,7 +81,7 @@ export const docsDense = {
isHiddenFromOverview: true,
displayName: 'Dropdown Menu Submenu',
description:
- 'menu row that reveals a nested flyout of its own children/items (single component, not Sub/SubTrigger/SubContent)',
+ 'menu row that reveals a nested flyout of its own children/items (single component, not Sub/SubTrigger/SubContent); drills in on a phone',
propDescriptions: {
label: 'primary label text for the trigger row',
icon: 'icon before label',
@@ -85,6 +92,8 @@ export const docsDense = {
menuWidth:
'minimum flyout width, capped to the viewport (default: content, min 160px)',
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",
xstyle: 'StyleX styles for the trigger row',
},
};
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
index a0d697125f..b936042001 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
@@ -6,7 +6,7 @@
* @output Unit tests for DropdownMenuSubMenu (#3829)
*/
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {useState} from 'react';
import {render, screen, waitFor, fireEvent, act} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -14,6 +14,7 @@ import * as stylex from '@stylexjs/stylex';
import {DropdownMenu} from './DropdownMenu';
import {DropdownMenuItem} from './DropdownMenuItem';
import {DropdownMenuSubMenu} from './DropdownMenuSubMenu';
+import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
import {rtlStyles} from '../utils';
beforeEach(() => {
@@ -953,3 +954,219 @@ describe('DropdownMenuSubMenu press model', () => {
expect(root).toHaveAttribute('aria-expanded', 'false');
});
});
+
+describe('DropdownMenuSubMenu drill-in on a phone', () => {
+ const originalMatchMedia = window.matchMedia;
+
+ // The drill-in resolves on the same query the root presentation uses for
+ // its bottom sheet, so one component carries one meaning of "adaptive".
+ function stubCompactTouch(matches: boolean) {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ matches: 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);
+ });
+
+ function PhoneMenu({onMove}: {onMove?: (folder: string) => void} = {}) {
+ return (
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem label="Rename" onClick={() => {}} />
+ <DropdownMenuSubMenu label="Move to">
+ <DropdownMenuItem label="Folder A" onClick={() => onMove?.('a')} />
+ <DropdownMenuSubMenu label="Archive">
+ <DropdownMenuItem label="2025" onClick={() => onMove?.('2025')} />
+ </DropdownMenuSubMenu>
+ </DropdownMenuSubMenu>
+ <DropdownMenuItem label="Delete" onClick={() => {}} />
+ </DropdownMenu>
+ );
+ }
+
+ // The popover is not open for jsdom's accessibility tree, so every query
+ // passes `hidden`; the rows a drilled-in view replaced sit under a `hidden`
+ // wrapper, which is what "shown" means here.
+ const h = {hidden: true} as const;
+ const isShown = (el: HTMLElement) => el.closest('[hidden]') == null;
+ const visibleRows = () =>
+ screen
+ .getAllByRole('menuitem', h)
+ .filter(isShown)
+ .map(el => el.textContent);
+ const shownRow = (name: string) =>
+ screen.getAllByRole('menuitem', {name, ...h}).find(isShown)!;
+ const shownMenu = (name: string) =>
+ screen.getAllByRole('menu', {name, ...h}).find(isShown)!;
+
+ it('on a phone a sub-menu drills in, is named by its row, and Back returns', async () => {
+ stubCompactTouch(true);
+ const user = userEvent.setup();
+ const onMove = vi.fn();
+ render(<PhoneMenu onMove={onMove} />);
+ const trigger = screen.getByRole('button', {name: /Actions/});
+ await user.click(trigger);
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'true'),
+ );
+ const rootMenu = shownMenu('Actions');
+
+ const moveTo = shownRow('Move to');
+ expect(moveTo).toHaveAttribute('aria-haspopup', 'menu');
+ expect(moveTo).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.click(moveTo, {detail: 1});
+
+ // The list is replaced in place: the sibling rows are gone from view, the
+ // drilled list is named by its row and leads with a Back row.
+ const drilled = await waitFor(() => shownMenu('Move to'));
+ expect(rootMenu).toContainElement(drilled);
+ expect(visibleRows()).toEqual(['Back to Actions', 'Folder A', 'Archive']);
+ // The sibling row is still mounted (its state stays live) but hidden.
+ expect(screen.getByRole('menuitem', {name: 'Rename', ...h})).not.toBe(
+ undefined,
+ );
+ expect(isShown(screen.getByRole('menuitem', {name: 'Rename', ...h}))).toBe(
+ false,
+ );
+ // No flyout beside the menu: the drilled list has no popover of its own.
+ expect(drilled.closest('[popover]')).toBe(rootMenu.closest('[popover]'));
+
+ // Back returns to the sub-menu row.
+ fireEvent.click(shownRow('Back to Actions'), {
+ detail: 1,
+ });
+ await waitFor(() => expect(shownRow('Move to')).toHaveFocus());
+ expect(visibleRows()).toEqual(['Rename', 'Move to', 'Delete']);
+
+ // Escape and ArrowLeft pop too, and a second level names its parent.
+ fireEvent.keyDown(shownRow('Move to'), {
+ key: 'Enter',
+ });
+ await waitFor(() => shownMenu('Move to'));
+ // A keyboard drill-in lands on the first row after Back.
+ expect(shownRow('Folder A')).toHaveFocus();
+ fireEvent.keyDown(shownRow('Archive'), {
+ key: 'Enter',
+ });
+ await waitFor(() => shownMenu('Archive'));
+ expect(visibleRows()).toEqual(['Back to Move to', '2025']);
+ expect(shownRow('2025')).toHaveFocus();
+
+ fireEvent.keyDown(document.activeElement!, {key: 'ArrowLeft'});
+ await waitFor(() => expect(shownRow('Archive')).toHaveFocus());
+ expect(visibleRows()).toEqual(['Back to Actions', 'Folder A', 'Archive']);
+ fireEvent.keyDown(document.activeElement!, {key: 'Escape'});
+ await waitFor(() => expect(shownRow('Move to')).toHaveFocus());
+ // One Escape popped one level; the menu is still open.
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // A pick inside a drilled list acts and closes the whole menu.
+ fireEvent.click(shownRow('Move to'), {
+ detail: 1,
+ });
+ await waitFor(() => shownMenu('Move to'));
+ fireEvent.click(shownRow('Folder A'), {
+ detail: 1,
+ });
+ expect(onMove).toHaveBeenCalledWith('a');
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),
+ );
+ });
+
+ it('typeahead and arrows scope to the drilled rows', async () => {
+ stubCompactTouch(true);
+ const user = userEvent.setup();
+ render(<PhoneMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ fireEvent.keyDown(await waitFor(() => shownRow('Move to')), {
+ key: 'Enter',
+ });
+ const drilled = await waitFor(() => shownMenu('Move to'));
+ const folderA = shownRow('Folder A');
+ expect(folderA).toHaveFocus();
+ // "d" matches Delete at the root, which is not shown: nothing moves.
+ fireEvent.keyDown(folderA, {key: 'd'});
+ expect(folderA).toHaveFocus();
+ // Arrows, Home and End walk the drilled list only, Back included; the
+ // hidden parent rows are not in the order.
+ fireEvent.keyDown(folderA, {key: 'ArrowUp'});
+ expect(shownRow('Back to Actions')).toHaveFocus();
+ fireEvent.keyDown(document.activeElement!, {key: 'End'});
+ expect(shownRow('Archive')).toHaveFocus();
+ fireEvent.keyDown(document.activeElement!, {key: 'Home'});
+ expect(shownRow('Back to Actions')).toHaveFocus();
+ expect(drilled).toBeInTheDocument();
+ });
+
+ it('presentation="flyout" keeps the flyout on a phone and "drill-in" drills on a laptop', async () => {
+ stubCompactTouch(true);
+ const user = userEvent.setup();
+ const {unmount} = render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuSubMenu label="Move to" presentation="flyout">
+ <DropdownMenuItem label="Folder A" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ fireEvent.click(await waitFor(() => shownRow('Move to')), {
+ detail: 1,
+ });
+ // The flyout renders in a popover of its own beside the row.
+ const flyout = await waitFor(() => shownMenu('Move to'));
+ expect(flyout.closest('[popover]')).not.toBe(
+ shownMenu('Actions').closest('[popover]'),
+ );
+ expect(screen.queryByRole('menuitem', {name: /^Back to/, ...h})).toBeNull();
+ unmount();
+
+ stubCompactTouch(false);
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuSubMenu label="Move to" presentation="drill-in">
+ <DropdownMenuItem label="Folder A" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ fireEvent.click(await waitFor(() => shownRow('Move to')), {
+ detail: 1,
+ });
+ await waitFor(() => shownRow('Back to Actions'));
+ });
+
+ it('closing the menu resets the drilled view', async () => {
+ stubCompactTouch(true);
+ const user = userEvent.setup();
+ render(<PhoneMenu />);
+ const trigger = screen.getByRole('button', {name: /Actions/});
+ await user.click(trigger);
+ fireEvent.click(await waitFor(() => shownRow('Move to')), {
+ detail: 1,
+ });
+ await waitFor(() => shownMenu('Move to'));
+ fireEvent.keyDown(document.activeElement!, {key: 'Escape'});
+ await waitFor(() => expect(shownRow('Move to')).toHaveFocus());
+ fireEvent.keyDown(document.activeElement!, {key: 'Escape'});
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),
+ );
+ await user.click(trigger);
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'true'),
+ );
+ expect(visibleRows()).toEqual(['Rename', 'Move to', 'Delete']);
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
index a5c9d21aa5..f1123d0733 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
@@ -8,7 +8,8 @@
* useTypeahead, the shared viewport-safe menu-width resolver, Item, Icon,
* Spinner, and DropdownMenu context + item roles
* @output Exports DropdownMenuSubMenu — a single menu row that reveals a nested
- * flyout menu of its own children/items.
+ * 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.
* @position Sub-component; place inside a DropdownMenu (or ContextMenu)
* alongside plain items.
*
@@ -28,6 +29,14 @@
* Enter / Space opens the flyout and focuses its first item; Left (Right in
* RTL) / Escape closes it and returns focus to the trigger row.
*
+ * Drill-in (the phone presentation): the root menu keeps a view stack
+ * (useMenuDrillIn) and this row pushes its view onto it; the root shows the
+ * view — a Back row named "Back to <parent>", then these rows — in place of
+ * its own, portalled into the root's host so the row stays mounted and its
+ * rows stay live. Back, Escape and ArrowLeft pop the view and return focus to
+ * the row. The list keeps this level's own roving focus, typeahead and press
+ * model, so nothing beside the row needs to know.
+ *
* Prior art: legacy internal XDS `XDSDropdownSubMenuItem` (APG menubar-
* navigation submenu). This re-expresses the same contract on Astryx primitives.
*
@@ -41,6 +50,7 @@
import React, {
useCallback,
+ useEffect,
useId,
useMemo,
useRef,
@@ -48,6 +58,7 @@ import React, {
type PointerEvent,
type ReactNode,
} from 'react';
+import {createPortal} from 'react-dom';
import * as stylex from '@stylexjs/stylex';
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {Spinner} from '../Spinner';
@@ -56,7 +67,7 @@ import {useLayer} from '../Layer/useLayer';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {useListFocus} from '../hooks/useListFocus';
import {useMenuHover} from '../hooks/useMenuHover';
-import {useMenuPress} from '../hooks/useMenuPress';
+import {isMenuPressActivation, useMenuPress} from '../hooks/useMenuPress';
import {useTypeahead} from '../hooks/useTypeahead';
import {useMenuOverflow} from './useMenuOverflow';
import {resolveMenuWidth} from './menuWidth';
@@ -85,6 +96,8 @@ import {
type DropdownMenuContextValue,
} from './DropdownMenuContext';
import {focusMenuItemOnHover} from './menuItemHover';
+import {DropdownMenuItem} from './DropdownMenuItem';
+import {useTranslator} from '../i18n';
const MENU_VIEWPORT_GUTTER = spacingVars['--spacing-4'];
// `useLayer` adds 4px of anchor clearance. An 8px collision margin resolves
@@ -210,6 +223,25 @@ const flyoutStyles = stylex.create({
}),
});
+// The drilled-in list shows in place of the parent rows, inside the parent's
+// own box: no surface, shadow or cap of its own.
+const drillInStyles = stylex.create({
+ list: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-0-5'],
+ outline: 'none',
+ WebkitTouchCallout: 'none',
+ userSelect: 'none',
+ },
+ hidden: {
+ display: 'none',
+ },
+});
+
+export type DropdownMenuSubMenuPresentation =
+ 'flyout' | 'drill-in' | 'adaptive';
+
interface DropdownMenuSubMenuBaseProps extends Pick<
BaseProps,
'xstyle' | 'className' | 'style'
@@ -239,6 +271,15 @@ interface DropdownMenuSubMenuBaseProps extends Pick<
menuWidth?: number | string;
/** Called when the flyout opens or closes. */
onOpenChange?: (isOpen: boolean) => void;
+ /**
+ * 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
+ * `(pointer: coarse)` device, decided when the menu opened — and flies out
+ * otherwise. Drill-in needs a `DropdownMenu` or `ContextMenu` root.
+ * 'adaptive'
+ */
+ presentation?: DropdownMenuSubMenuPresentation;
/** Test id for the trigger row. */
'data-testid'?: string;
/** Test id for the flyout menu. */
@@ -289,6 +330,7 @@ export function DropdownMenuSubMenu(
hasSpinner = false,
menuWidth,
onOpenChange,
+ presentation = 'adaptive',
children,
xstyle,
className,
@@ -297,6 +339,7 @@ export function DropdownMenuSubMenu(
menuDataTestId,
} = props;
+ const t = useTranslator();
const menuCtx = useDropdownMenuContext();
const menuSize = menuCtx?.menuSize ?? 'md';
const canOpen = !isDisabled;
@@ -305,17 +348,39 @@ export function DropdownMenuSubMenu(
const triggerId = useId();
const triggerRef = useRef<HTMLDivElement | null>(null);
- const [isOpen, setIsOpen] = useState(false);
+ // Drill-in: the root keeps a view stack; this row pushes its
+ // view and the root shows it in place of its rows. Decided from the root's
+ // pointer kind at open time, or forced by `presentation`.
+ const drillIn = menuCtx?.drillIn;
+ const activeDrillIn =
+ drillIn != null &&
+ (presentation === 'drill-in' ||
+ (presentation === 'adaptive' && drillIn.isCompactTouch))
+ ? drillIn
+ : null;
+ const isDrillIn = activeDrillIn != null;
+ const viewId = useId();
+ const isOnStack = activeDrillIn?.viewStack.includes(viewId) === true;
+ const isTopView = isOnStack && activeDrillIn?.viewStack.at(-1) === viewId;
+ const stringLabel = typeof label === 'string' ? label : undefined;
+ const parentLabel = menuCtx?.menuLabel;
+ const backLabel =
+ parentLabel != null
+ ? t('@astryx.dropdownMenu.backTo', {parent: parentLabel})
+ : t('@astryx.dropdownMenu.back');
+
+ const [isFlyoutOpen, setIsFlyoutOpen] = useState(false);
+ const isOpen = isDrillIn ? isOnStack : isFlyoutOpen;
const layer = useLayer({
mode: 'context',
lightDismiss: false,
onShow: useCallback(() => {
- setIsOpen(true);
+ setIsFlyoutOpen(true);
onOpenChange?.(true);
}, [onOpenChange]),
onHide: useCallback(() => {
- setIsOpen(false);
+ setIsFlyoutOpen(false);
onOpenChange?.(false);
}, [onOpenChange]),
});
@@ -346,7 +411,8 @@ export function DropdownMenuSubMenu(
wrap: false,
onEscape: () => close({focusTrigger: true}),
});
- const hasOverflow = useMenuOverflow(menuRef, children, isOpen);
+ // A drilled-in list scrolls with the root menu, not on its own.
+ const hasOverflow = useMenuOverflow(menuRef, children, isOpen && !isDrillIn);
const typeahead = useTypeahead({
getItemLabels: () => getItems().map(el => el.textContent),
@@ -362,20 +428,35 @@ export function DropdownMenuSubMenu(
// either surface closes after a delay. Hover-open does not steal focus.
// Hover intent and the shared hover→click guard only: this level owns its own
// click handling, roving focus and typeahead. popover="manual", so the
- // invoker wiring other consumers need does not apply.
+ // invoker wiring other consumers need does not apply. A drill-in row has no
+ // hover: a finger drives it, and a press opens it.
const {triggerProps, contentProps, confirmHoverOpen} =
useMenuHover<HTMLDivElement>({
show: showLayer,
hide: hideLayer,
- isOpen,
- isEnabled: canOpen,
+ isOpen: isFlyoutOpen,
+ isEnabled: canOpen && !isDrillIn,
});
+ // 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.
+ const pendingViewFocusRef = useRef<'first' | 'container' | null>(null);
+ const pendingTriggerFocusRef = useRef(false);
+
const open = useCallback(
(options?: {focusFirst?: boolean}) => {
if (!canOpen) {
return;
}
+ if (activeDrillIn != null) {
+ pendingViewFocusRef.current = options?.focusFirst
+ ? 'first'
+ : 'container';
+ activeDrillIn.push(viewId);
+ onOpenChange?.(true);
+ return;
+ }
layer.show();
if (options?.focusFirst) {
// Synchronous by design — see the focus note in useMenuHover. A
@@ -386,19 +467,57 @@ export function DropdownMenuSubMenu(
}
}
},
- [canOpen, layer, focusFirst, menuRef],
+ [canOpen, activeDrillIn, viewId, onOpenChange, layer, focusFirst, menuRef],
);
const close = useCallback(
(options?: {focusTrigger?: boolean}) => {
+ if (activeDrillIn != null) {
+ if (isOnStack) {
+ pendingTriggerFocusRef.current = options?.focusTrigger !== false;
+ activeDrillIn.pop();
+ onOpenChange?.(false);
+ }
+ return;
+ }
layer.hide();
if (options?.focusTrigger !== false) {
triggerRef.current?.focus();
}
},
- [layer],
+ [activeDrillIn, isOnStack, onOpenChange, layer],
);
+ // The pushed view has just shown (its rows are in the host and visible):
+ // land focus as the open asked.
+ useEffect(() => {
+ if (!isTopView || activeDrillIn?.host == null) {
+ return;
+ }
+ const mode = pendingViewFocusRef.current;
+ if (mode == null) {
+ return;
+ }
+ pendingViewFocusRef.current = null;
+ const items = getItems();
+ // Back is the first row; a keyboard open lands on the first row after it.
+ const target = mode === 'first' ? (items[1] ?? items[0]) : null;
+ if (target != null) {
+ target.focus({preventScroll: true});
+ } else {
+ menuRef.current?.focus({preventScroll: true});
+ }
+ }, [isTopView, activeDrillIn?.host, getItems, menuRef]);
+
+ // The view was popped: the row is visible again, focus returns to it.
+ useEffect(() => {
+ if (isOnStack || !pendingTriggerFocusRef.current) {
+ return;
+ }
+ pendingTriggerFocusRef.current = false;
+ triggerRef.current?.focus({preventScroll: true});
+ }, [isOnStack]);
+
// Single ref for the trigger row: store it for focus management AND wire it
// as the flyout's positioning anchor (CSS anchor positioning).
const setTriggerEl = useCallback(
@@ -409,23 +528,44 @@ export function DropdownMenuSubMenu(
[layer],
);
- const handleTriggerClick = useCallback(() => {
- if (isDisabled) {
- return;
- }
- // Toggles, except for the click that follows a hover-open (#3121).
- if (isOpen) {
- if (confirmHoverOpen()) {
- if (!focusFirst()) {
- menuRef.current?.focus();
- }
+ const handleTriggerClick = useCallback(
+ (event: React.MouseEvent) => {
+ if (isDisabled) {
return;
}
- close({focusTrigger: true});
- } else {
- open({focusFirst: true});
- }
- }, [isDisabled, isOpen, open, close, confirmHoverOpen, focusFirst, menuRef]);
+ if (isDrillIn) {
+ // A keyboard activation (a synthesized click, `detail` 0, outside the
+ // press model) lands on the first row; a pointer's drill-in — a real
+ // click, or the press model's own activation, which is also `detail`
+ // 0 — lights nothing until the pointer moves.
+ const isPointer = event.detail > 0 || isMenuPressActivation();
+ open({focusFirst: !isPointer});
+ return;
+ }
+ // Toggles, except for the click that follows a hover-open (#3121).
+ if (isFlyoutOpen) {
+ if (confirmHoverOpen()) {
+ if (!focusFirst()) {
+ menuRef.current?.focus();
+ }
+ return;
+ }
+ close({focusTrigger: true});
+ } else {
+ open({focusFirst: true});
+ }
+ },
+ [
+ isDisabled,
+ isDrillIn,
+ isFlyoutOpen,
+ open,
+ close,
+ confirmHoverOpen,
+ focusFirst,
+ menuRef,
+ ],
+ );
const handleTriggerKeyDown = useCallback(
(e: React.KeyboardEvent) => {
@@ -523,7 +663,9 @@ export function DropdownMenuSubMenu(
// flyout: close this level (without stealing focus back to the trigger) and
// propagate up via the parent menu's closeMenu. Because every level
// re-provides the context, this chains from the deepest flyout all the way to
- // the root DropdownMenu (whose closeMenu hides the popover).
+ // the root DropdownMenu (whose closeMenu hides the popover). The drill-in
+ // stack passes through untouched — the root owns it — and this level's label
+ // names the Back row of a view drilled in from here.
const nestedMenuContext = useMemo<DropdownMenuContextValue>(
() => ({
menuSize,
@@ -531,8 +673,10 @@ export function DropdownMenuSubMenu(
close({focusTrigger: false});
menuCtx?.closeMenu();
},
+ drillIn,
+ menuLabel: stringLabel,
}),
- [menuSize, close, menuCtx],
+ [menuSize, close, menuCtx, drillIn, stringLabel],
);
// The press model for this flyout: the row under a release acts, the
@@ -569,6 +713,27 @@ export function DropdownMenuSubMenu(
: flyoutStyles.popoverCustomWidth(resolvedMenuWidth.value)
: flyoutStyles.popover;
+ const nestedContent = (
+ <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}
+ </DropdownMenuContext>
+ );
+
return (
<>
<Item
@@ -607,44 +772,68 @@ export function DropdownMenuSubMenu(
style,
})}
/>
- {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.touchPanY : flyoutStyles.touchNone,
- hasOverflow && flyoutStyles.scrollable,
- ),
- )}>
- <DropdownMenuContext value={nestedMenuContext}>
- {children}
- </DropdownMenuContext>
- </div>,
- {
- placement: 'end',
- alignment: 'start',
- offset: spacingVars['--spacing-1'],
- xstyle: [
- flyoutStyles.popoverViewport,
- popoverXstyle,
- layerAnimations.end,
- ],
- },
- )}
+ {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.touchPanY : flyoutStyles.touchNone,
+ 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__/DropdownMenuDrillIn.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..9a4f4224c9
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts
@@ -0,0 +1,174 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuDrillIn.a11y.chromium.spec.ts
+ * @input Built Storybook adaptive sub-menu fixture and real Chromium, once
+ * emulating a phone (coarse pointer, touch) and once a laptop (fine pointer)
+ * @output Evidence for component:DropdownMenu FR12 / AR3: on a coarse pointer
+ * an adaptive sub-menu drills in — the rows are replaced in the same menu
+ * box, the drilled list is named by its row, Back / Escape return focus to
+ * the row — and on a fine pointer the same sub-menu flies out.
+ * @position Browser proof behind the jsdom drill-in suite; the pointer decision
+ * (`(pointer: coarse)` at open time) is what jsdom cannot exercise.
+ */
+
+import {devices, expect, test, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+const storyId = 'core-dropdownmenu--submenu-adaptive-fixture';
+
+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('drill-in-fixture')).toBeVisible();
+}
+
+/** The rows a person can see: not under a hidden wrapper, not in a closed popover. */
+function shownRows(page: Page) {
+ return page.locator('[role="menuitem"]:visible');
+}
+
+test.describe('on a phone (coarse pointer)', () => {
+ // The phone's context options only: `defaultBrowserType` would force a new
+ // worker, which a describe-level `use` may not do.
+ const {defaultBrowserType: _browser, ...phone} = devices['Pixel 7'];
+ test.use(phone);
+
+ test('an adaptive sub-menu drills in, is named by its row, and Back / Escape return to the row', async ({
+ page,
+ }) => {
+ await mount(page);
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(true);
+
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ await trigger.tap();
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const rootMenu = page.getByRole('menu', {name: 'Actions'});
+ await expect(rootMenu).toBeVisible();
+ await expect(shownRows(page)).toHaveText(['Rename', 'Move to', 'Delete']);
+ const popoversBefore = await page.locator('[popover]:popover-open').count();
+
+ // Drill in with a finger.
+ const moveTo = page.getByRole('menuitem', {name: 'Move to'});
+ await expect(moveTo).toHaveAttribute('aria-haspopup', 'menu');
+ await moveTo.tap();
+
+ const drilled = page.getByRole('menu', {name: 'Move to'});
+ await expect(drilled).toBeVisible();
+ // Same box: the drilled list sits inside the root menu, no new popover.
+ expect(
+ await drilled.evaluate(
+ (el, rootName) =>
+ el.closest('[popover]') ===
+ document
+ .querySelector(`[role="menu"][aria-label="${rootName}"]`)
+ ?.closest('[popover]'),
+ 'Actions',
+ ),
+ ).toBe(true);
+ expect(await page.locator('[popover]:popover-open').count()).toBe(
+ popoversBefore,
+ );
+ await expect(shownRows(page)).toHaveText([
+ 'Back to Actions',
+ 'Folder A',
+ 'Folder B',
+ 'Archive',
+ ]);
+ await expect(page.getByRole('menuitem', {name: 'Rename'})).toBeHidden();
+ // The parent rows have left the accessibility tree while the view shows.
+ expect(
+ await page.evaluate(
+ () =>
+ document
+ .querySelector('[role="menuitem"][aria-haspopup="menu"]')
+ ?.closest('[hidden]') instanceof HTMLElement,
+ ),
+ ).toBe(true);
+
+ // A pointer drill-in lights nothing; the drilled list owns focus.
+ expect(
+ await page.evaluate(() => document.activeElement?.getAttribute('role')),
+ ).toBe('menu');
+
+ // Escape pops one level and lands on the row; the menu stays open.
+ await page.keyboard.press('Escape');
+ await expect(moveTo).toBeFocused();
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await expect(shownRows(page)).toHaveText(['Rename', 'Move to', 'Delete']);
+
+ // Keyboard drill-in lands on the first row after Back; a second level
+ // names its parent; ArrowLeft pops it.
+ await page.keyboard.press('Enter');
+ await expect(drilled).toBeVisible();
+ await expect(page.getByRole('menuitem', {name: 'Folder A'})).toBeFocused();
+ await page.getByRole('menuitem', {name: 'Archive'}).focus();
+ await page.keyboard.press('Enter');
+ await expect(page.getByRole('menu', {name: 'Archive'})).toBeVisible();
+ await expect(shownRows(page)).toHaveText(['Back to Move to', '2025']);
+ await expect(page.getByRole('menuitem', {name: '2025'})).toBeFocused();
+ await page.keyboard.press('ArrowLeft');
+ await expect(page.getByRole('menuitem', {name: 'Archive'})).toBeFocused();
+ await expect(shownRows(page)).toHaveText([
+ 'Back to Actions',
+ 'Folder A',
+ 'Folder B',
+ 'Archive',
+ ]);
+
+ // Back returns to the row with a finger too.
+ await page.getByRole('menuitem', {name: 'Back to Actions'}).tap();
+ await expect(moveTo).toBeFocused();
+ await expect(shownRows(page)).toHaveText(['Rename', 'Move to', 'Delete']);
+
+ // A pick inside a drilled view closes the whole menu.
+ await moveTo.tap();
+ await page.getByRole('menuitem', {name: 'Folder A'}).tap();
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+});
+
+test.describe('on a laptop (fine pointer)', () => {
+ test('the same adaptive sub-menu flies out beside its row', async ({
+ page,
+ }) => {
+ await mount(page);
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ await trigger.click();
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const popoversBefore = await page.locator('[popover]:popover-open').count();
+
+ const moveTo = page.getByRole('menuitem', {name: 'Move to'});
+ await moveTo.click();
+ const flyout = page.getByRole('menu', {name: 'Move to'});
+ await expect(flyout).toBeVisible();
+ // A popover of its own, beside the row; the parent rows stay shown.
+ expect(await page.locator('[popover]:popover-open').count()).toBe(
+ popoversBefore + 1,
+ );
+ await expect(page.getByRole('menuitem', {name: 'Rename'})).toBeVisible();
+ await expect(page.getByRole('menuitem', {name: /^Back to/})).toHaveCount(0);
+ await expect(page.getByRole('menuitem', {name: 'Folder A'})).toBeFocused();
+ });
+});
diff --git a/packages/core/src/DropdownMenu/index.ts b/packages/core/src/DropdownMenu/index.ts
index 21254d9cf6..777e86497a 100644
--- a/packages/core/src/DropdownMenu/index.ts
+++ b/packages/core/src/DropdownMenu/index.ts
@@ -54,10 +54,12 @@ export {
} from './DropdownMenuRadioItem';
// Submenu — a single menu row that reveals a nested flyout of its own
-// children/items. Data mode via DropdownMenuItemData.items.
+// children/items, or drills in on a phone. Data mode via
+// DropdownMenuItemData.items.
export {
DropdownMenuSubMenu,
type DropdownMenuSubMenuProps,
+ type DropdownMenuSubMenuPresentation,
} from './DropdownMenuSubMenu';
// Menu-coordination context — public so consumers can build custom menu items
diff --git a/packages/core/src/DropdownMenu/useMenuDrillIn.tsx b/packages/core/src/DropdownMenu/useMenuDrillIn.tsx
new file mode 100644
index 0000000000..ee8ef97b27
--- /dev/null
+++ b/packages/core/src/DropdownMenu/useMenuDrillIn.tsx
@@ -0,0 +1,128 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useMenuDrillIn.tsx
+ * @input React, StyleX, the shared SSR-safe media-query check
+ * @output Exports useMenuDrillIn — the view stack a menu root keeps so its
+ * sub-menus can drill in — and the coarse-pointer query.
+ * @position Internal; mounted by DropdownMenu and ContextMenu, read by
+ * DropdownMenuSubMenu through DropdownMenuContext.
+ *
+ * On a phone a flyout beside a phone-width menu has no room, so a sub-menu
+ * row replaces the list with its own rows and a Back row in the same menu
+ * box. The root owns the stack: `wrapContent` renders the root's rows inside
+ * a wrapper that hides while a view shows, followed by the host element the
+ * shown view portals its rows into. The sub-menu row stays mounted (hidden)
+ * while its view shows, so its rows stay live and Back can return focus to
+ * it without bookkeeping. Whether a finger drove the menu is decided once,
+ * when it opens, so a menu never changes shape under a pointer.
+ */
+
+import {useCallback, useMemo, useState, type ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {DropdownMenuDrillIn} from './DropdownMenuContext';
+import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
+
+/**
+ * The same query the root presentation uses to decide the bottom sheet, so
+ * one component carries one meaning of "adaptive". A bare `(pointer: coarse)`
+ * would disagree with it on a large touch tablet: the menu would stay an
+ * anchored popover while its sub-menus replaced rows in place, a combination
+ * nobody designed.
+ */
+function matchesCompactTouch(): boolean {
+ return (
+ typeof window !== 'undefined' &&
+ typeof window.matchMedia === 'function' &&
+ window.matchMedia(COMPACT_TOUCH_PRESENTATION_QUERY).matches
+ );
+}
+
+const styles = stylex.create({
+ // The wrappers add no box of their own, so the menu's flex gap still runs
+ // between the rows exactly as it does without them.
+ tree: {
+ display: 'contents',
+ },
+ treeHidden: {
+ display: 'none',
+ },
+});
+
+export interface UseMenuDrillInReturn {
+ /** The context value for `DropdownMenuContext.drillIn`. */
+ drillIn: DropdownMenuDrillIn;
+ /** Whether a view is shown in place of the root's rows. */
+ isDrilled: boolean;
+ /**
+ * Wrap the root's rows: hidden while a view shows, followed by the host the
+ * view renders into.
+ */
+ wrapContent: (content: ReactNode) => ReactNode;
+}
+
+/**
+ * The drill-in view stack for a menu root.
+ *
+ * @param isOpen - whether the menu is open; the pointer kind is sampled when it
+ * opens and the stack empties when it closes.
+ */
+export function useMenuDrillIn(isOpen: boolean): UseMenuDrillInReturn {
+ const [isCompactTouch, setIsCompactTouch] = useState(false);
+ const [viewStack, setViewStack] = useState<ReadonlyArray<string>>([]);
+ const [host, setHost] = useState<HTMLElement | null>(null);
+ // Derived from the open transition during render (the documented pattern
+ // for state that follows a prop): the pointer kind is sampled as the menu
+ // opens, and closing forgets the drilled view so the next open starts at
+ // the root.
+ const [wasOpen, setWasOpen] = useState(isOpen);
+ if (wasOpen !== isOpen) {
+ setWasOpen(isOpen);
+ if (isOpen) {
+ setIsCompactTouch(matchesCompactTouch());
+ } else if (viewStack.length > 0) {
+ setViewStack([]);
+ }
+ }
+
+ const push = useCallback((viewId: string) => {
+ setViewStack(stack =>
+ stack.includes(viewId) ? stack : [...stack, viewId],
+ );
+ }, []);
+ const pop = useCallback(() => {
+ setViewStack(stack => (stack.length === 0 ? stack : stack.slice(0, -1)));
+ }, []);
+
+ const drillIn = useMemo<DropdownMenuDrillIn>(
+ () => ({isCompactTouch, viewStack, host, push, pop}),
+ [isCompactTouch, viewStack, host, push, pop],
+ );
+
+ const isDrilled = viewStack.length > 0;
+
+ // The wrappers render always, not only once a view shows: a tree that
+ // changed shape at push time would remount the sub-menu row, and with it the
+ // view id it just pushed. They own no box (`display: contents`), so the
+ // menu's layout is unchanged.
+ const wrapContent = useCallback(
+ (content: ReactNode): ReactNode => {
+ return (
+ <>
+ <div
+ hidden={isDrilled}
+ inert={isDrilled}
+ {...stylex.props(styles.tree, isDrilled && styles.treeHidden)}>
+ {content}
+ </div>
+ <div ref={setHost} {...stylex.props(styles.tree)} />
+ </>
+ );
+ },
+ [isDrilled],
+ );
+
+ return {drillIn, isDrilled, wrapContent};
+}
diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.ts
index 7cca9766ed..c72c5808c1 100644
--- a/packages/core/src/hooks/useListFocus.ts
+++ b/packages/core/src/hooks/useListFocus.ts
@@ -177,6 +177,17 @@ const TEXT_INPUT_TYPES = new Set([
'number',
]);
+/**
+ * Whether `el` sits under a `hidden` or `inert` ancestor that is itself inside
+ * `listEl` (the list's own state is not consulted). Such a row cannot take
+ * focus — a drilled-in menu hides the rows a view replaced — so it
+ * leaves the roving order and the typeahead.
+ */
+function isHiddenWithin(el: HTMLElement, listEl: HTMLElement): boolean {
+ const hidden = el.parentElement?.closest<HTMLElement>('[hidden],[inert]');
+ return hidden != null && hidden !== listEl && listEl.contains(hidden);
+}
+
/**
* The nearest `contenteditable` root for `el`, or null when `el` is not inside
* an editable region. Prefers the browser's `isContentEditable` property and
@@ -342,7 +353,7 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
}
const matched = Array.from(
listEl.querySelectorAll<HTMLElement>(itemSelector),
- );
+ ).filter(el => !isHiddenWithin(el, listEl));
// When a boundary is set, keep only items that belong to THIS list level —
// i.e. whose nearest boundary ancestor is our own container. This excludes
// items inside nested lists (e.g. inline submenu flyouts) that would