Skip to content

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

TypeScript

feat(core): DropdownMenu submenus (DropdownMenuSubMenu) (#4498)

Cindy Zhang9c65e8b0d335
diff --git a/.changeset/dropdown-menu-submenus.md b/.changeset/dropdown-menu-submenus.md
new file mode 100644
index 0000000000..dd2fea5f0b
--- /dev/null
+++ b/.changeset/dropdown-menu-submenus.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DropdownMenu: add submenus via a single `DropdownMenuSubMenu` component (or a nested `items` array in data mode). The row adopts DropdownMenuItem semantics (label / icon / description / isDisabled) and its children — or an `items` array — become the flyout content. Flyouts open inline-end with auto-flip, hover-intent, and full keyboard support (Right/Enter/Space opens and focuses the first item; Left/Escape closes and returns focus to the trigger).
+@cixzhang
diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsx
index bdc3c910a7..e4b0ea2ab8 100644
--- a/apps/storybook/stories/DropdownMenu.stories.tsx
+++ b/apps/storybook/stories/DropdownMenu.stories.tsx
@@ -8,6 +8,7 @@ import {
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
+ DropdownMenuSubMenu,
} from '@astryxdesign/core/DropdownMenu';
import {Divider} from '@astryxdesign/core/Divider';
import {
@@ -657,3 +658,96 @@ export const LabSelectableSizes: Story = {
},
},
};
+
+export const Submenu: Story = {
+ render: () => (
+ <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={() => {}} />
+ <DropdownMenuItem label="Folder C" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ <DropdownMenuItem icon={TrashIcon} label="Delete" onClick={() => {}} />
+ </DropdownMenu>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'DropdownMenuSubMenu is a single menu row that reveals a nested flyout of its own children. Hover or Right arrow (Left in RTL) / Enter / Space opens it and moves focus to its first item; Left arrow / Escape closes it and returns focus to the trigger. The flyout opens inline-end by default and auto-flips at the viewport edge.',
+ },
+ },
+ },
+};
+
+export const NestedSubmenu: Story = {
+ render: () => (
+ <DropdownMenu button={{label: 'Share'}}>
+ <DropdownMenuItem icon={ShareIcon} label="Copy link" onClick={() => {}} />
+ <DropdownMenuSubMenu label="Share to">
+ <DropdownMenuItem label="Email" onClick={() => {}} />
+ <DropdownMenuSubMenu label="Team">
+ <DropdownMenuItem label="Design" onClick={() => {}} />
+ <DropdownMenuItem label="Engineering" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Submenus nest to arbitrary depth — each level owns its own roving focus and positioning layer.',
+ },
+ },
+ },
+};
+
+export const SubmenuAsyncSpinner: Story = {
+ render: () => (
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem label="Rename" onClick={() => {}} />
+ <DropdownMenuSubMenu label="Move to" hasSpinner>
+ <DropdownMenuItem label="Loading…" isDisabled onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A submenu row can show a spinner in place of the caret via `hasSpinner`, e.g. while a lazy submenu\u2019s children load.',
+ },
+ },
+ },
+};
+
+export const SubmenuDataDriven: Story = {
+ render: () => (
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ items={[
+ {label: 'Rename', onClick: () => {}},
+ {
+ label: 'Move to',
+ icon: FolderPlusIcon,
+ items: [
+ {label: 'Folder A', onClick: () => {}},
+ {label: 'Folder B', onClick: () => {}},
+ ],
+ },
+ {type: 'divider'},
+ {label: 'Delete', onClick: () => {}},
+ ]}
+ />
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Data-driven parity: give a menu item a nested `items` array and it becomes a submenu automatically — no separate item type.',
+ },
+ },
+ },
+};
diff --git a/internal/vibe-tests/src/interactive.ts b/internal/vibe-tests/src/interactive.ts
index 0762454263..36d648439c 100644
--- a/internal/vibe-tests/src/interactive.ts
+++ b/internal/vibe-tests/src/interactive.ts
@@ -546,7 +546,7 @@ import {
## Subcomponents
- \`DropdownMenuCheckboxItem\`: Checkable item
- \`DropdownMenuRadioGroup\` / \`DropdownMenuRadioItem\`: Radio items
-- \`DropdownMenuSub\` / \`DropdownMenuSubTrigger\` / \`DropdownMenuSubContent\`: Nested menus
+- \`DropdownMenuSubMenu\`: A menu row that reveals a nested flyout of its own children/items
`,
Command: `# Command
diff --git a/packages/cli/templates/blocks/components/DropdownMenu/DropdownMenuWithSubmenu.doc.mjs b/packages/cli/templates/blocks/components/DropdownMenu/DropdownMenuWithSubmenu.doc.mjs
new file mode 100644
index 0000000000..adb2bd5690
--- /dev/null
+++ b/packages/cli/templates/blocks/components/DropdownMenu/DropdownMenuWithSubmenu.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'DropdownMenu',
+ name: 'DropdownMenu — Submenu',
+ displayName: 'DropdownMenu — Submenu',
+ description:
+ 'Action menu with a nested submenu. Hover or Right arrow opens the flyout; Left arrow / Escape closes it. Use to group related destinations or secondary actions without crowding the top level.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['DropdownMenu', 'Layout', 'Text'],
+};
diff --git a/packages/cli/templates/blocks/components/DropdownMenu/DropdownMenuWithSubmenu.tsx b/packages/cli/templates/blocks/components/DropdownMenu/DropdownMenuWithSubmenu.tsx
new file mode 100644
index 0000000000..421e3eaad8
--- /dev/null
+++ b/packages/cli/templates/blocks/components/DropdownMenu/DropdownMenuWithSubmenu.tsx
@@ -0,0 +1,52 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {
+ DropdownMenu,
+ DropdownMenuItem,
+ DropdownMenuSubMenu,
+} from '@astryxdesign/core/DropdownMenu';
+import {VStack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+
+export default function DropdownMenuWithSubmenu() {
+ const [lastAction, setLastAction] = useState<string | null>(null);
+
+ return (
+ <VStack gap={3}>
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem
+ icon="pencil"
+ label="Rename"
+ onClick={() => setLastAction('Rename')}
+ />
+ <DropdownMenuSubMenu icon="folder" label="Move to">
+ <DropdownMenuItem
+ label="Projects"
+ onClick={() => setLastAction('Move to Projects')}
+ />
+ <DropdownMenuItem
+ label="Archive"
+ onClick={() => setLastAction('Move to Archive')}
+ />
+ <DropdownMenuItem
+ label="Trash"
+ onClick={() => setLastAction('Move to Trash')}
+ />
+ </DropdownMenuSubMenu>
+ <DropdownMenuItem
+ icon="trash"
+ label="Delete"
+ onClick={() => setLastAction('Delete')}
+ />
+ </DropdownMenu>
+ {lastAction && (
+ <Text type="supporting" color="secondary">
+ Last action: {lastAction}
+ </Text>
+ )}
+ </VStack>
+ );
+}
diff --git a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
index f468c0cd9f..66e78b321f 100644
--- a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
+++ b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
@@ -59,6 +59,7 @@ import {
import {
MENU_ITEM_ROLES,
MENU_ITEM_SELECTOR,
+ MENU_BOUNDARY_SELECTOR,
} from '../DropdownMenu/menuItemRoles';
import type {DropdownMenuOption} from '../DropdownMenu/DropdownMenu';
@@ -515,21 +516,15 @@ function BreadcrumbMenuTrigger({
handleKeyDown: listNavKeyDown,
focusFirst,
focusItem,
+ ownsEvent,
+ getItems: getMenuItems,
} = useListFocus<HTMLDivElement>({
itemSelector: MENU_ITEM_SELECTOR,
+ boundarySelector: MENU_BOUNDARY_SELECTOR,
wrap: false,
onEscape: closeMenu,
});
- const getMenuItems = useCallback(
- (): HTMLElement[] =>
- listRef.current
- ? Array.from(
- listRef.current.querySelectorAll<HTMLElement>(MENU_ITEM_SELECTOR),
- )
- : [],
- [listRef],
- );
const typeahead = useTypeahead({
getItemLabels: () => getMenuItems().map(el => el.textContent),
onMatch: focusItem,
@@ -542,6 +537,11 @@ function BreadcrumbMenuTrigger({
const listKeyDown = useCallback(
(e: React.KeyboardEvent) => {
+ // A submenu flyout renders inline inside this menu; its key events bubble
+ // up here. Let that level own them — only handle events from this level.
+ if (!ownsEvent(e)) {
+ return;
+ }
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
const focused = document.activeElement as HTMLElement | null;
@@ -564,7 +564,7 @@ function BreadcrumbMenuTrigger({
}
listNavKeyDown(e);
},
- [listNavKeyDown, closeMenu, typeahead],
+ [listNavKeyDown, closeMenu, typeahead, ownsEvent],
);
const openAndFocus = useCallback(() => {
diff --git a/packages/core/src/Breadcrumbs/Breadcrumbs.test.tsx b/packages/core/src/Breadcrumbs/Breadcrumbs.test.tsx
index 5f6e8630c6..d47ee89b2c 100644
--- a/packages/core/src/Breadcrumbs/Breadcrumbs.test.tsx
+++ b/packages/core/src/Breadcrumbs/Breadcrumbs.test.tsx
@@ -589,6 +589,57 @@ describe('BreadcrumbItem menu', () => {
).toHaveFocus();
});
+ it('renders a submenu from a nested items array and keyboard-reaches an item after it', async () => {
+ // Breadcrumb menus reuse the DropdownMenu item pipeline, so a nested
+ // `items` array becomes a submenu. The inline flyout must not pollute the
+ // breadcrumb menu's roving order — an item after the submenu row stays
+ // keyboard-reachable.
+ const onDelete = vi.fn();
+ render(
+ <Breadcrumbs>
+ <BreadcrumbItem
+ menu={[
+ {label: 'Rename', onClick: vi.fn()},
+ {
+ label: 'Move to',
+ items: [
+ {label: 'Folder A', onClick: vi.fn()},
+ {label: 'Folder B', onClick: vi.fn()},
+ ],
+ },
+ {type: 'divider'},
+ {label: 'Delete', onClick: onDelete},
+ ]}>
+ Teams
+ </BreadcrumbItem>
+ <BreadcrumbItem isCurrent>Overview</BreadcrumbItem>
+ </Breadcrumbs>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Teams'});
+ trigger.focus();
+ fireEvent.keyDown(trigger, {key: 'ArrowDown'});
+ // Two role="menu" exist (the breadcrumb menu + the inline submenu flyout);
+ // the breadcrumb menu is the first in DOM order.
+ const menu = screen.getAllByRole('menu', {hidden: true})[0];
+ const submenuTrigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ expect(submenuTrigger).toHaveAttribute('aria-haspopup', 'menu');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Rename', hidden: true}),
+ ).toHaveFocus();
+ });
+ // Rename → Move to → Delete, one step per press.
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ expect(submenuTrigger).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ expect(
+ screen.getByRole('menuitem', {name: 'Delete', hidden: true}),
+ ).toHaveFocus();
+ });
+
it('allows menu together with isCurrent (both aria-current and aria-haspopup)', () => {
render(
<Breadcrumbs>
diff --git a/packages/core/src/Breadcrumbs/index.ts b/packages/core/src/Breadcrumbs/index.ts
index e60e4a9077..8a620ef187 100644
--- a/packages/core/src/Breadcrumbs/index.ts
+++ b/packages/core/src/Breadcrumbs/index.ts
@@ -35,6 +35,10 @@ export {
DropdownMenuRadioItem as BreadcrumbMenuRadioItem,
type DropdownMenuRadioItemProps as BreadcrumbMenuRadioItemProps,
} from '../DropdownMenu/DropdownMenuRadioItem';
+export {
+ DropdownMenuSubMenu as BreadcrumbMenuSubMenu,
+ type DropdownMenuSubMenuProps as BreadcrumbMenuSubMenuProps,
+} from '../DropdownMenu/DropdownMenuSubMenu';
export type {
DropdownMenuOption as BreadcrumbMenuOption,
DropdownMenuItemData as BreadcrumbMenuItemData,
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index 656fafc31f..65faafdf0d 100644
--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx
@@ -803,4 +803,46 @@ describe('ContextMenu keyboard access for menuitemradio/menuitemcheckbox (#3829)
screen.getByRole('menuitemradio', {name: 'Oldest', hidden: true}),
).toHaveFocus();
});
+
+ it('renders a submenu from a nested items array and keyboard-reaches an item after it', () => {
+ // Same inline-flyout scoping the DropdownMenu fix covers: the submenu's
+ // items must not pollute the ContextMenu's roving order, and an item after
+ // the submenu row must stay keyboard-reachable.
+ const onDelete = vi.fn();
+ render(
+ <ContextMenu
+ items={[
+ {label: 'Cut', onClick: () => {}},
+ {
+ label: 'Move to',
+ items: [
+ {label: 'Folder A', onClick: () => {}},
+ {label: 'Folder B', onClick: () => {}},
+ ],
+ },
+ {type: 'divider'},
+ {label: 'Delete', onClick: onDelete},
+ ]}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+ // Two role="menu" exist (the context menu + the inline submenu flyout);
+ // the context menu is the first in DOM order.
+ const menu = screen.getAllByRole('menu', {hidden: true})[0];
+ // The submenu trigger renders as a menuitem with aria-haspopup.
+ const submenuTrigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ expect(submenuTrigger).toHaveAttribute('aria-haspopup', 'menu');
+ // Cut → Move to → Delete, one step per press (submenu items not swept in).
+ screen.getByRole('menuitem', {name: 'Cut', hidden: true}).focus();
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ expect(submenuTrigger).toHaveFocus();
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ expect(
+ screen.getByRole('menuitem', {name: 'Delete', hidden: true}),
+ ).toHaveFocus();
+ });
});
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index b8709534eb..8e83782ed3 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -49,6 +49,7 @@ import {
import {
MENU_ITEM_ROLES,
MENU_ITEM_SELECTOR,
+ MENU_BOUNDARY_SELECTOR,
} from '../DropdownMenu/menuItemRoles';
import {useListFocus} from '../hooks/useListFocus';
import {useTypeahead} from '../hooks/useTypeahead';
@@ -268,22 +269,18 @@ export function ContextMenu({
handleKeyDown: listNavKeyDown,
focusFirst,
focusItem,
+ ownsEvent,
+ getItems: getMenuItems,
} = useListFocus<HTMLDivElement>({
itemSelector: MENU_ITEM_SELECTOR,
+ boundarySelector: MENU_BOUNDARY_SELECTOR,
wrap: false,
onEscape: closeMenu,
});
- // First-character typeahead over the enabled menu items (menus-11).
- const getMenuItems = useCallback(
- (): HTMLElement[] =>
- listRef.current
- ? Array.from(
- listRef.current.querySelectorAll<HTMLElement>(MENU_ITEM_SELECTOR),
- )
- : [],
- [listRef],
- );
+ // First-character typeahead over the enabled menu items (menus-11). Reuses
+ // the hook's scoped item collection so an inline submenu flyout's items
+ // aren't swept in.
const typeahead = useTypeahead({
getItemLabels: () => getMenuItems().map(el => el.textContent),
onMatch: focusItem,
@@ -340,6 +337,11 @@ export function ContextMenu({
const listKeyDown = useCallback(
(e: React.KeyboardEvent) => {
+ // A submenu flyout renders inline inside this menu; its key events bubble
+ // up here. Let that level own them — only handle events from this level.
+ if (!ownsEvent(e)) {
+ return;
+ }
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
const focused = document.activeElement as HTMLElement | null;
@@ -357,7 +359,7 @@ export function ContextMenu({
}
listNavKeyDown(e);
},
- [listNavKeyDown, typeahead],
+ [listNavKeyDown, typeahead, ownsEvent],
);
// Place the zero-size cursor anchor at a point in the trigger's local
diff --git a/packages/core/src/ContextMenu/index.ts b/packages/core/src/ContextMenu/index.ts
index da92d7aef2..1e878bec72 100644
--- a/packages/core/src/ContextMenu/index.ts
+++ b/packages/core/src/ContextMenu/index.ts
@@ -35,3 +35,8 @@ export {
DropdownMenuRadioItem as ContextMenuRadioItem,
type DropdownMenuRadioItemProps as ContextMenuRadioItemProps,
} from '../DropdownMenu/DropdownMenuRadioItem';
+// Submenus work inside a ContextMenu too (nested flyout of items).
+export {
+ DropdownMenuSubMenu as ContextMenuSubMenu,
+ type DropdownMenuSubMenuProps as ContextMenuSubMenuProps,
+} from '../DropdownMenu/DropdownMenuSubMenu';
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 49ed2598b8..42541a730c 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -38,7 +38,11 @@ import {Icon} from '../Icon';
import type {IconType} from '../Icon';
import {renderDropdownItems} from './renderDropdownItems';
-import {MENU_ITEM_ROLES, MENU_ITEM_SELECTOR} from './menuItemRoles';
+import {
+ MENU_ITEM_ROLES,
+ MENU_ITEM_SELECTOR,
+ MENU_BOUNDARY_SELECTOR,
+} from './menuItemRoles';
import {
DropdownMenuContext,
type DropdownMenuContextValue,
@@ -100,6 +104,12 @@ export interface DropdownMenuItemData {
onClick?: () => void;
isDisabled?: boolean;
icon?: ReactNode | IconType;
+ /**
+ * Nested submenu entries. When present, this row becomes a submenu (a
+ * flyout revealing `items`) instead of a leaf action — no separate item
+ * "type" is needed. Data-mode parity for the compound DropdownMenuSubMenu API.
+ */
+ items?: DropdownMenuOption[];
}
export interface DropdownMenuDivider {
@@ -273,23 +283,18 @@ export function DropdownMenu({
handleKeyDown: listNavKeyDown,
focusFirst,
focusItem,
+ ownsEvent,
+ getItems: getMenuItems,
} = useListFocus<HTMLDivElement>({
itemSelector: MENU_ITEM_SELECTOR,
+ boundarySelector: MENU_BOUNDARY_SELECTOR,
wrap: false,
onEscape: closeMenu,
});
// First-character typeahead over the (enabled) menu items — jump to the next
- // item whose label starts with the typed text (menus-11).
- const getMenuItems = useCallback(
- (): HTMLElement[] =>
- listRef.current
- ? Array.from(
- listRef.current.querySelectorAll<HTMLElement>(MENU_ITEM_SELECTOR),
- )
- : [],
- [listRef],
- );
+ // item whose label starts with the typed text (menus-11). Reuses the hook's
+ // scoped item collection so an inline submenu flyout's items aren't swept in.
const typeahead = useTypeahead({
getItemLabels: () => getMenuItems().map(el => el.textContent),
onMatch: focusItem,
@@ -315,6 +320,11 @@ export function DropdownMenu({
// Extend useListFocus with Enter/Space activation + typeahead
const listKeyDown = useCallback(
(e: React.KeyboardEvent) => {
+ // A submenu flyout renders inline inside this menu; its key events bubble
+ // up here. Let that level own them — only handle events from this level.
+ if (!ownsEvent(e)) {
+ return;
+ }
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
const focused = document.activeElement as HTMLElement | null;
@@ -342,7 +352,7 @@ export function DropdownMenu({
}
listNavKeyDown(e);
},
- [listNavKeyDown, closeMenu, typeahead],
+ [listNavKeyDown, closeMenu, typeahead, ownsEvent],
);
const openAndFocus = useCallback(() => {
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs
new file mode 100644
index 0000000000..010c5d0ff5
--- /dev/null
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../docs-types').ComponentDoc} */
+
+export const docs = {
+ name: 'DropdownMenuSubMenu',
+ subComponentOf: 'DropdownMenu',
+ 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.',
+ playground: {
+ defaults: {label: 'Move to'},
+ },
+ props: [
+ {
+ name: 'label',
+ type: 'ReactNode',
+ description: 'Primary label text for the trigger row.',
+ },
+ {
+ name: 'icon',
+ type: 'IconType',
+ description:
+ 'Icon to display before the label. See `astryx docs icons` for valid semantic names.',
+ },
+ {
+ name: 'description',
+ type: 'ReactNode',
+ description: 'Secondary description text displayed below the label.',
+ },
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description:
+ 'The flyout menu items — the same components used at the top level (DropdownMenuItem, nested DropdownMenuSubMenu, selectable items).',
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ default: 'false',
+ description:
+ 'A disabled submenu renders its trigger row but never opens the flyout.',
+ },
+ {
+ name: 'hasSpinner',
+ type: 'boolean',
+ default: 'false',
+ description:
+ 'Show a spinner in place of the caret, e.g. while a lazy submenu’s children are loading.',
+ },
+ {
+ name: 'menuWidth',
+ type: 'number | string',
+ description: 'Fixed flyout width. Defaults to sizing to its content (min 160px).',
+ },
+ {
+ name: 'onOpenChange',
+ type: '(isOpen: boolean) => void',
+ description: 'Called when the flyout opens or closes.',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX styles for the trigger row. Must be a stylex.create() value: not an inline style object like style={{}}.',
+ },
+ ],
+};
+
+export const docsDense = {
+ name: 'DropdownMenuSubMenu',
+ 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)',
+ propDescriptions: {
+ label: 'primary label text for the trigger row',
+ icon: 'icon before label',
+ description: 'secondary text below label',
+ children: 'flyout menu items (same components as top level)',
+ isDisabled: 'renders trigger but never opens',
+ hasSpinner: 'spinner instead of caret for async children',
+ menuWidth: 'fixed flyout width (default: content, min 160px)',
+ onOpenChange: 'called when flyout opens/closes',
+ 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
new file mode 100644
index 0000000000..5089aa9958
--- /dev/null
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
@@ -0,0 +1,635 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuSubMenu.test.tsx
+ * @input vitest, @testing-library/react, DropdownMenu + DropdownMenuSubMenu
+ * @output Unit tests for DropdownMenuSubMenu (#3829)
+ */
+
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {useState} from 'react';
+import {render, screen, waitFor} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {DropdownMenu} from './DropdownMenu';
+import {DropdownMenuItem} from './DropdownMenuItem';
+import {DropdownMenuSubMenu} from './DropdownMenuSubMenu';
+
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ const originalMatches = HTMLElement.prototype.matches;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+function MoveMenu({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')} />
+ <DropdownMenuItem label="Folder B" onClick={() => onMove?.('b')} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+ );
+}
+
+describe('DropdownMenuSubMenu', () => {
+ it('renders the trigger with aria-haspopup and collapsed aria-expanded', async () => {
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ expect(trigger).toHaveAttribute('aria-haspopup', 'menu');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('opens the flyout on trigger click and exposes its items', async () => {
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await user.click(trigger);
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+ expect(
+ screen.getByRole('menuitem', {name: 'Folder A', hidden: true}),
+ ).toBeInTheDocument();
+ });
+
+ it('opens on ArrowRight and returns focus to the trigger on ArrowLeft', async () => {
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ // The menu focuses its first item (Rename) on open via rAF; wait for that
+ // to settle before moving focus to the submenu trigger, so the deferred
+ // focus can't steal it back mid-test.
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Rename', hidden: true}),
+ ).toHaveFocus();
+ });
+ trigger.focus();
+ await user.keyboard('{ArrowRight}');
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+ // Focus moved into the flyout's first item.
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Folder A', hidden: true}),
+ ).toHaveFocus();
+ });
+ await user.keyboard('{ArrowLeft}');
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(trigger).toHaveFocus();
+ });
+
+ it('names the flyout from its trigger via aria-labelledby', async () => {
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await user.click(trigger);
+ const flyout = await screen.findByRole('menu', {
+ name: /Move to/,
+ hidden: true,
+ });
+ expect(flyout).toHaveAttribute('aria-labelledby', trigger.id);
+ });
+
+ it('invokes the nested item handler on selection', async () => {
+ const user = userEvent.setup();
+ const onMove = vi.fn();
+ render(<MoveMenu onMove={onMove} />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ await user.click(
+ screen.getByRole('menuitem', {name: /Move to/, hidden: true}),
+ );
+ await user.click(
+ await screen.findByRole('menuitem', {name: 'Folder A', hidden: true}),
+ );
+ expect(onMove).toHaveBeenCalledWith('a');
+ });
+
+ it('closes the whole menu after selecting a nested item', async () => {
+ // Regression: the nested closeMenu only closed the flyout, leaving the
+ // root menu open. Selecting a leaf must dismiss the entire stack. The root
+ // menu's open state is reflected on its trigger button's aria-expanded.
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ const button = screen.getByRole('button', {name: /Actions/});
+ await user.click(button);
+ expect(button).toHaveAttribute('aria-expanded', 'true');
+ await user.click(
+ screen.getByRole('menuitem', {name: /Move to/, hidden: true}),
+ );
+ await user.click(
+ await screen.findByRole('menuitem', {name: 'Folder A', hidden: true}),
+ );
+ // The whole stack is dismissed — the root menu closed too.
+ await waitFor(() => {
+ expect(button).toHaveAttribute('aria-expanded', 'false');
+ });
+ });
+
+ it('activates a nested item with the Enter key and closes the menu', async () => {
+ const user = userEvent.setup();
+ const onMove = vi.fn();
+ render(<MoveMenu onMove={onMove} />);
+ const button = screen.getByRole('button', {name: /Actions/});
+ await user.click(button);
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ // Let the root menu's open-focus (Rename, via rAF) settle before moving
+ // focus to the submenu trigger, so it can't steal focus back mid-test.
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Rename', hidden: true}),
+ ).toHaveFocus();
+ });
+ trigger.focus();
+ await user.keyboard('{ArrowRight}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Folder A', hidden: true}),
+ ).toHaveFocus();
+ });
+ await user.keyboard('{Enter}');
+ expect(onMove).toHaveBeenCalledWith('a');
+ await waitFor(() => {
+ expect(button).toHaveAttribute('aria-expanded', 'false');
+ });
+ });
+
+ it('does not open a disabled submenu', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuSubMenu label="Move to" isDisabled>
+ <DropdownMenuItem label="Folder A" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('steps through every flyout item with ArrowDown without skipping', async () => {
+ // Regression: the flyout renders inline inside the parent menu's
+ // roving-focus container, so an unstopped ArrowDown bubbled to the parent
+ // and moved focus a second time — skipping the middle item.
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuSubMenu label="Move to">
+ <DropdownMenuItem label="Projects" onClick={() => {}} />
+ <DropdownMenuItem label="Archive" onClick={() => {}} />
+ <DropdownMenuItem label="Trash" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ trigger.focus();
+ await user.keyboard('{ArrowRight}');
+ // Opens and focuses the first item.
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Projects', hidden: true}),
+ ).toHaveFocus();
+ });
+ // ArrowDown lands on the MIDDLE item (previously skipped to Trash).
+ await user.keyboard('{ArrowDown}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Archive', hidden: true}),
+ ).toHaveFocus();
+ });
+ // ArrowDown again lands on the last item.
+ await user.keyboard('{ArrowDown}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Trash', hidden: true}),
+ ).toHaveFocus();
+ });
+ // ArrowUp returns to the middle item (no skip in reverse either).
+ await user.keyboard('{ArrowUp}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Archive', hidden: true}),
+ ).toHaveFocus();
+ });
+ });
+});
+
+describe('DropdownMenu data-driven submenus', () => {
+ it('renders a submenu when an item declares nested items', async () => {
+ const user = userEvent.setup();
+ const onMove = vi.fn();
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ items={[
+ {label: 'Rename', onClick: () => {}},
+ {
+ label: 'Move to',
+ items: [
+ {
+ label: 'Folder A',
+ onClick: () => {
+ onMove('a');
+ },
+ },
+ {
+ label: 'Folder B',
+ onClick: () => {
+ onMove('b');
+ },
+ },
+ ],
+ },
+ ]}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ expect(trigger).toHaveAttribute('aria-haspopup', 'menu');
+ await user.click(trigger);
+ await user.click(
+ await screen.findByRole('menuitem', {name: 'Folder B', hidden: true}),
+ );
+ expect(onMove).toHaveBeenCalledWith('b');
+ });
+
+ it('keyboard-reaches an item positioned after a submenu row', async () => {
+ // Regression: the submenu flyout renders inline inside the root menu, so
+ // the root's item query swept in the (hidden) flyout items. Arrow nav then
+ // stalled on those unfocusable items and never reached "Delete" below the
+ // submenu row.
+ const user = userEvent.setup();
+ const onDelete = vi.fn();
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ items={[
+ {label: 'Rename', onClick: () => {}},
+ {
+ label: 'Move to',
+ items: [
+ {label: 'Folder A', onClick: () => {}},
+ {label: 'Folder B', onClick: () => {}},
+ ],
+ },
+ {type: 'divider'},
+ {label: 'Delete', onClick: onDelete},
+ ]}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Rename', hidden: true}),
+ ).toHaveFocus();
+ });
+ // Rename → Move to → Delete (three ArrowDowns, no stalling on hidden
+ // flyout items).
+ await user.keyboard('{ArrowDown}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: /Move to/, hidden: true}),
+ ).toHaveFocus();
+ });
+ await user.keyboard('{ArrowDown}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Delete', hidden: true}),
+ ).toHaveFocus();
+ });
+ await user.keyboard('{Enter}');
+ expect(onDelete).toHaveBeenCalled();
+ });
+});
+
+describe('DropdownMenuSubMenu accessibility (WCAG 2.2 / APG)', () => {
+ // 2.1.2 No Keyboard Trap + APG submenu contract: Escape closes the current
+ // submenu and returns focus to its trigger, leaving the parent menu open.
+ it('closes only the submenu on Escape and restores focus to the trigger', async () => {
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ const button = screen.getByRole('button', {name: /Actions/});
+ await user.click(button);
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Rename', hidden: true}),
+ ).toHaveFocus();
+ });
+ trigger.focus();
+ await user.keyboard('{ArrowRight}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Folder A', hidden: true}),
+ ).toHaveFocus();
+ });
+ await user.keyboard('{Escape}');
+ // Submenu collapsed, focus back on the trigger…
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(trigger).toHaveFocus();
+ // …but the parent menu is still open (Escape didn't dismiss everything).
+ expect(button).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ // 2.1.1 Keyboard: type-ahead is operable inside the flyout.
+ it('supports first-character type-ahead within the flyout', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuSubMenu label="Move to">
+ <DropdownMenuItem label="Apple" onClick={() => {}} />
+ <DropdownMenuItem label="Banana" onClick={() => {}} />
+ <DropdownMenuItem label="Cherry" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ trigger.focus();
+ await user.keyboard('{ArrowRight}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Apple', hidden: true}),
+ ).toHaveFocus();
+ });
+ await user.keyboard('c');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Cherry', hidden: true}),
+ ).toHaveFocus();
+ });
+ });
+
+ // The core of the inline-flyout fix: a submenu nested inside a submenu must
+ // not double-handle arrow keys (each level self-scopes via boundarySelector),
+ // so navigation in the deepest flyout steps one item at a time.
+ it('navigates a two-level nested submenu without double-stepping', async () => {
+ const user = userEvent.setup();
+ const onPick = vi.fn();
+ render(
+ <DropdownMenu button={{label: 'Share'}}>
+ <DropdownMenuItem label="Copy link" onClick={() => {}} />
+ <DropdownMenuSubMenu label="Share to">
+ <DropdownMenuItem label="Email" onClick={() => {}} />
+ <DropdownMenuSubMenu label="Team">
+ <DropdownMenuItem
+ label="Design"
+ onClick={() => {
+ onPick('design');
+ }}
+ />
+ <DropdownMenuItem
+ label="Eng"
+ onClick={() => {
+ onPick('eng');
+ }}
+ />
+ <DropdownMenuItem
+ label="Data"
+ onClick={() => {
+ onPick('data');
+ }}
+ />
+ </DropdownMenuSubMenu>
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Share/}));
+ const shareTo = screen.getByRole('menuitem', {
+ name: /Share to/,
+ hidden: true,
+ });
+ // Let the root menu's open-focus (Copy link, via rAF) settle first so it
+ // can't steal focus back after we move to the submenu trigger.
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Copy link', hidden: true}),
+ ).toHaveFocus();
+ });
+ shareTo.focus();
+ await user.keyboard('{ArrowRight}');
+ // First flyout: focus on Email.
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Email', hidden: true}),
+ ).toHaveFocus();
+ });
+ // Down to the nested submenu trigger, then open it.
+ await user.keyboard('{ArrowDown}');
+ const teamTrigger = screen.getByRole('menuitem', {
+ name: /Team/,
+ hidden: true,
+ });
+ await waitFor(() => {
+ expect(teamTrigger).toHaveFocus();
+ });
+ await user.keyboard('{ArrowRight}');
+ // Deepest flyout: Design → Eng → Data, one step per press (no skipping).
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Design', hidden: true}),
+ ).toHaveFocus();
+ });
+ await user.keyboard('{ArrowDown}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Eng', hidden: true}),
+ ).toHaveFocus();
+ });
+ await user.keyboard('{ArrowDown}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Data', hidden: true}),
+ ).toHaveFocus();
+ });
+ await user.keyboard('{Enter}');
+ expect(onPick).toHaveBeenCalledWith('data');
+ });
+
+ // 1.4.13 Content on Hover or Focus: the flyout stays open while the pointer
+ // is over it (moving onto the flyout must not dismiss it).
+ it('keeps the flyout open while the pointer is over it', async () => {
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await user.click(trigger);
+ const flyout = await screen.findByRole('menu', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await user.hover(flyout);
+ await user.hover(
+ screen.getByRole('menuitem', {name: 'Folder A', hidden: true}),
+ );
+ // Still open after moving the pointer onto the flyout and its items.
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ // Async/loading submenu (hasSpinner): the flyout may contain no focusable
+ // items yet (only a disabled "Loading…" row). Opening it must still move
+ // keyboard ownership INTO the flyout — otherwise focus stays on the parent
+ // list, arrow keys rove the parent while the empty flyout stays open, and
+ // Enter re-triggers into a broken state.
+ it('moves focus into a loading (item-less) flyout so keyboard ownership transfers', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem label="Rename" onClick={() => {}} />
+ <DropdownMenuSubMenu label="Move to" hasSpinner>
+ <DropdownMenuItem label="Loading…" isDisabled onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ <DropdownMenuItem label="Delete" onClick={() => {}} />
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Rename', hidden: true}),
+ ).toHaveFocus();
+ });
+ trigger.focus();
+ await user.keyboard('{ArrowRight}');
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+ // The flyout has no focusable items, so focus lands on the flyout container
+ // itself — NOT on a parent item (Rename/Delete).
+ const flyout = screen.getByRole('menu', {name: /Move to/, hidden: true});
+ await waitFor(() => {
+ expect(flyout).toHaveFocus();
+ });
+ expect(
+ screen.getByRole('menuitem', {name: 'Rename', hidden: true}),
+ ).not.toHaveFocus();
+ expect(
+ screen.getByRole('menuitem', {name: 'Delete', hidden: true}),
+ ).not.toHaveFocus();
+ // Left/Escape from the loading flyout closes it and returns to the trigger.
+ await user.keyboard('{ArrowLeft}');
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(trigger).toHaveFocus();
+ });
+
+ it('roves to the first item once a loading flyout resolves', async () => {
+ // After children load, ArrowDown from the focused container moves onto the
+ // first real item (container reports index -1, so next = first).
+ const user = userEvent.setup();
+ function AsyncSubmenu() {
+ const [loaded, setLoaded] = useState(false);
+ return (
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuSubMenu
+ label="Move to"
+ hasSpinner={!loaded}
+ onOpenChange={open => {
+ if (open) {
+ setLoaded(true);
+ }
+ }}>
+ {loaded ? (
+ <>
+ <DropdownMenuItem label="Folder A" onClick={() => {}} />
+ <DropdownMenuItem label="Folder B" onClick={() => {}} />
+ </>
+ ) : (
+ <DropdownMenuItem
+ label="Loading…"
+ isDisabled
+ onClick={() => {}}
+ />
+ )}
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+ );
+ }
+ render(<AsyncSubmenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ trigger.focus();
+ await user.keyboard('{ArrowRight}');
+ // Children resolve on open; ArrowDown moves from the container to Folder A.
+ await user.keyboard('{ArrowDown}');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('menuitem', {name: 'Folder A', hidden: true}),
+ ).toHaveFocus();
+ });
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
new file mode 100644
index 0000000000..f56f309a99
--- /dev/null
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
@@ -0,0 +1,553 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file DropdownMenuSubMenu.tsx
+ * @input React, stylex, useLayer (context mode), useListFocus, useMenuHover,
+ * useTypeahead, Item, Icon, Spinner, DropdownMenu context + item roles.
+ * @output Exports DropdownMenuSubMenu — a single menu row that reveals a nested
+ * flyout menu of its own children/items.
+ * @position Sub-component; place inside a DropdownMenu (or ContextMenu)
+ * alongside plain items.
+ *
+ * One component, not three. The row itself adopts DropdownMenuItem semantics
+ * (label / icon / description / isDisabled) and its children become the
+ * flyout's content. This mirrors how SideNavItem / TreeListItem promote a
+ * normal row into a nested surface when given children, rather than the Radix
+ * Sub / SubTrigger / SubContent split. Data-driven menus never touch this
+ * component directly — renderDropdownItems renders it from a nested `items`
+ * array and passes the rendered children in.
+ *
+ * Built on existing primitives — no bespoke floating code:
+ * - Positioning: useLayer context mode opens the flyout inline-end with
+ * viewport auto-flip via CSS anchor positioning (RTL-correct by default).
+ * - Pointer: useMenuHover for open/close intent.
+ * - Keyboard: a per-level useListFocus + useTypeahead. Right (Left in RTL) /
+ * Enter / Space opens the flyout and focuses its first item; Left (Right in
+ * RTL) / Escape closes it and returns focus to the trigger row.
+ *
+ * Prior art: legacy internal XDS `XDSDropdownSubMenuItem` (APG menubar-
+ * navigation submenu). This re-expresses the same contract on Astryx primitives.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs
+ * - /packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
+ * - /packages/core/src/DropdownMenu/index.ts
+ * - /apps/storybook/stories/DropdownMenu.stories.tsx
+ * - /packages/cli/templates/blocks/components/DropdownMenu/ (showcase blocks)
+ */
+
+import React, {
+ useCallback,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Icon, renderIconSlot, type IconType} from '../Icon';
+import {Spinner} from '../Spinner';
+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 {useTypeahead} from '../hooks/useTypeahead';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ durationVars,
+ easeVars,
+ shadowVars,
+ typographyVars,
+ typeScaleVars,
+} from '../theme/tokens.stylex';
+import {mergeProps} from '../utils';
+import {themeProps} from '../utils/themeProps';
+import type {BaseProps} from '../BaseProps';
+import {
+ MENU_ITEM_ROLES,
+ MENU_ITEM_SELECTOR,
+ MENU_BOUNDARY_SELECTOR,
+} from './menuItemRoles';
+import {
+ DropdownMenuContext,
+ useDropdownMenuContext,
+ type DropdownMenuContextValue,
+} from './DropdownMenuContext';
+
+const triggerStyles = stylex.create({
+ root: {
+ boxSizing: 'border-box',
+ width: '100%',
+ paddingBlock: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-2'],
+ borderRadius: `max(0px, calc(var(--_dropdown-menu-radius, ${spacingVars['--spacing-2']}) - var(--_dropdown-menu-padding, ${spacingVars['--spacing-1']})))`,
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: typeScaleVars['--text-label-size'],
+ color: colorVars['--color-text-primary'],
+ backgroundColor: {
+ default: 'transparent',
+ ':focus': colorVars['--color-overlay-hover'],
+ },
+ ':hover': {
+ '@media (hover: hover)': {
+ backgroundColor: colorVars['--color-overlay-hover'],
+ },
+ },
+ border: 'none',
+ cursor: 'pointer',
+ textAlign: 'start',
+ outline: 'none',
+ },
+ // While the flyout is open, keep the trigger visibly active so the open
+ // branch reads as the current path even when focus has moved into the child.
+ open: {
+ backgroundColor: colorVars['--color-overlay-hover'],
+ },
+ disabled: {
+ opacity: 0.5,
+ cursor: 'not-allowed',
+ },
+ caret: {
+ display: 'flex',
+ alignItems: 'center',
+ },
+});
+
+const triggerSizeStyles = stylex.create({
+ sm: {
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-2'],
+ },
+ md: {
+ paddingBlock: spacingVars['--spacing-1-5'],
+ },
+ lg: {},
+});
+
+const flyoutStyles = stylex.create({
+ menu: {
+ boxSizing: 'border-box',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-0-5'],
+ maxHeight: '300px',
+ overflowY: 'auto',
+ '--_dropdown-menu-radius': radiusVars['--radius-container'],
+ '--_dropdown-menu-padding': spacingVars['--spacing-1'],
+ padding: spacingVars['--spacing-1'],
+ borderRadius: 'var(--_dropdown-menu-radius)',
+ backgroundColor: colorVars['--color-background-popover'],
+ boxShadow: shadowVars['--shadow-low'],
+ opacity: 1,
+ transitionProperty: 'opacity',
+ transitionDuration: durationVars['--duration-fast'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ popover: {
+ minWidth: '160px',
+ // Small inline gap so the flyout doesn't sit flush against the parent menu.
+ marginInlineStart: spacingVars['--spacing-1'],
+ marginInlineEnd: spacingVars['--spacing-1'],
+ },
+ popoverCustomWidth: (width: string | number) => ({
+ minWidth: typeof width === 'number' ? `${width}px` : width,
+ marginInlineStart: spacingVars['--spacing-1'],
+ marginInlineEnd: spacingVars['--spacing-1'],
+ }),
+});
+
+interface DropdownMenuSubMenuBaseProps extends Pick<
+ BaseProps,
+ 'xstyle' | 'className' | 'style'
+> {
+ /** Icon to display before the label on the trigger row. */
+ icon?: ReactNode | IconType;
+ /** Primary label text for the trigger row. */
+ label: ReactNode;
+ /** Secondary description text displayed below the label. */
+ description?: ReactNode;
+ /**
+ * Whether the submenu is disabled. A disabled submenu renders its trigger
+ * row but never opens the flyout.
+ * @default false
+ */
+ isDisabled?: boolean;
+ /**
+ * Show a spinner in place of the caret, e.g. while a lazy submenu's children
+ * are loading. Ported from the legacy `hasSpinner` async-submenu affordance.
+ * @default false
+ */
+ hasSpinner?: boolean;
+ /** Fixed flyout width. Defaults to sizing to its content (min 160px). */
+ menuWidth?: number | string;
+ /** Called when the flyout opens or closes. */
+ onOpenChange?: (isOpen: boolean) => void;
+ /** Test id for the trigger row. */
+ 'data-testid'?: string;
+ /** Test id for the flyout menu. */
+ menuDataTestId?: string;
+}
+
+export interface DropdownMenuSubMenuProps extends DropdownMenuSubMenuBaseProps {
+ /**
+ * The flyout's menu items — the same components used at the top level
+ * (`DropdownMenuItem`, `DropdownMenuSubMenu`, selectable items, etc.).
+ *
+ * Data-mode parity lives one level up: give a `DropdownMenu`/`ContextMenu`
+ * item a nested `items` array and it renders a `DropdownMenuSubMenu` with
+ * these children automatically — so the data path never has to reach into
+ * this component.
+ */
+ children: ReactNode;
+}
+
+/**
+ * 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. Place inside a DropdownMenu (or
+ * ContextMenu) alongside plain items.
+ *
+ * For data-driven menus, don't use this directly — give a menu item a nested
+ * `items` array and DropdownMenu/ContextMenu renders the submenu for you.
+ *
+ * @example
+ * ```
+ * <DropdownMenu button={{label: 'Actions'}}>
+ * <DropdownMenuItem label="Rename" onClick={rename} />
+ * <DropdownMenuSubMenu label="Move to" icon="folder">
+ * <DropdownMenuItem label="Folder A" onClick={() => move('a')} />
+ * <DropdownMenuItem label="Folder B" onClick={() => move('b')} />
+ * </DropdownMenuSubMenu>
+ * </DropdownMenu>
+ * ```
+ */
+export function DropdownMenuSubMenu(
+ props: DropdownMenuSubMenuProps,
+): ReactNode {
+ const {
+ icon,
+ label,
+ description,
+ isDisabled = false,
+ hasSpinner = false,
+ menuWidth,
+ onOpenChange,
+ children,
+ xstyle,
+ className,
+ style,
+ 'data-testid': testId,
+ menuDataTestId,
+ } = props;
+
+ const menuCtx = useDropdownMenuContext();
+ const menuSize = menuCtx?.menuSize ?? 'md';
+ const canOpen = !isDisabled;
+
+ const contentId = useId();
+ const triggerId = useId();
+ const triggerRef = useRef<HTMLDivElement | null>(null);
+
+ const [isOpen, setIsOpen] = useState(false);
+
+ const layer = useLayer({
+ mode: 'context',
+ lightDismiss: false,
+ onShow: useCallback(() => {
+ setIsOpen(true);
+ onOpenChange?.(true);
+ }, [onOpenChange]),
+ onHide: useCallback(() => {
+ setIsOpen(false);
+ onOpenChange?.(false);
+ }, [onOpenChange]),
+ });
+
+ const showLayer = useCallback(() => {
+ if (canOpen) {
+ layer.show();
+ }
+ }, [canOpen, layer]);
+ const hideLayer = useCallback(() => {
+ layer.hide();
+ }, [layer]);
+
+ // Dedicated roving-focus + typeahead for this flyout level. The boundary
+ // selector scopes item collection and key handling to this flyout's own
+ // `role="menu"` — so a submenu nested inside this one (also inline, also
+ // `role="menu"`) doesn't pollute this level's items or double-handle keys.
+ const {
+ listRef: menuRef,
+ handleKeyDown: listNavKeyDown,
+ focusFirst,
+ focusItem,
+ ownsEvent,
+ getItems,
+ } = useListFocus<HTMLDivElement>({
+ itemSelector: MENU_ITEM_SELECTOR,
+ boundarySelector: MENU_BOUNDARY_SELECTOR,
+ wrap: false,
+ onEscape: () => close({focusTrigger: true}),
+ });
+
+ const typeahead = useTypeahead({
+ getItemLabels: () => getItems().map(el => el.textContent),
+ onMatch: focusItem,
+ getCurrentIndex: () =>
+ getItems().findIndex(
+ el =>
+ el === document.activeElement || el.contains(document.activeElement),
+ ),
+ });
+
+ // Hover-intent: entering the trigger opens after a short delay; leaving
+ // either surface closes after a delay. Hover-open does not steal focus.
+ const {triggerProps, contentProps} = useMenuHover<HTMLDivElement>({
+ show: showLayer,
+ hide: hideLayer,
+ isOpen,
+ isEnabled: canOpen,
+ });
+
+ const open = useCallback(
+ (options?: {focusFirst?: boolean}) => {
+ if (!canOpen) {
+ return;
+ }
+ layer.show();
+ if (options?.focusFirst) {
+ requestAnimationFrame(() => {
+ // Move focus into the flyout. When it has no focusable items yet
+ // (e.g. an async submenu showing only a disabled "Loading…" row via
+ // hasSpinner), focusFirst() finds nothing — fall back to focusing the
+ // flyout container itself so keyboard ownership still transfers off
+ // the parent list. Otherwise the parent would keep focus, letting
+ // arrow keys rove the parent while the empty flyout stays open.
+ const focusedItem = focusFirst();
+ if (!focusedItem) {
+ menuRef.current?.focus();
+ }
+ });
+ }
+ },
+ [canOpen, layer, focusFirst, menuRef],
+ );
+
+ const close = useCallback(
+ (options?: {focusTrigger?: boolean}) => {
+ layer.hide();
+ if (options?.focusTrigger !== false) {
+ triggerRef.current?.focus();
+ }
+ },
+ [layer],
+ );
+
+ // 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(
+ (el: HTMLDivElement | null) => {
+ triggerRef.current = el;
+ layer.ref(el);
+ },
+ [layer],
+ );
+
+ const handleTriggerClick = useCallback(() => {
+ if (isDisabled) {
+ return;
+ }
+ // Click toggles the flyout, moving focus into it on open.
+ if (isOpen) {
+ close({focusTrigger: true});
+ } else {
+ open({focusFirst: true});
+ }
+ }, [isDisabled, isOpen, open, close]);
+
+ const handleTriggerKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (isDisabled) {
+ return;
+ }
+ const isRtl =
+ typeof window !== 'undefined' && triggerRef.current
+ ? window.getComputedStyle(triggerRef.current).direction === 'rtl'
+ : false;
+ const openKey = isRtl ? 'ArrowLeft' : 'ArrowRight';
+ if (e.key === openKey || e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ // The trigger row is a direct child of the parent menu (not a nested
+ // role="menu"), so the parent's key handler would otherwise also act on
+ // this event (e.g. Enter clicking the focused row). Stop it here — this
+ // level fully handles opening the flyout.
+ e.stopPropagation();
+ open({focusFirst: true});
+ }
+ },
+ [isDisabled, open],
+ );
+
+ // Enter/Space activate the focused row; typeahead jumps by first character;
+ // the close key (Left, or Right in RTL) returns focus to the trigger;
+ // arrows/Home/End defer to useListFocus (RTL-aware).
+ //
+ // The flyout renders inline (useLayer context mode is a native popover, not a
+ // portal), so a submenu nested inside this one bubbles its key events up to
+ // this handler. `ownsEvent` (from useListFocus, scoped by boundarySelector)
+ // tells us whether the event originated in THIS flyout or a deeper one; we
+ // only act on our own, letting the deeper level keep ownership. No manual
+ // stopPropagation needed — each level self-filters.
+ const handleContentKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (!ownsEvent(e)) {
+ return;
+ }
+ // Escape closes just this submenu and returns focus to its trigger (APG:
+ // Escape collapses the current level, not the whole stack). The root
+ // popover's focus-trap listens for Escape at the document level and bails
+ // when the event is already handled, so we mark it handled here (stop
+ // propagation + preventDefault) to keep the parent menu open.
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ close({focusTrigger: true});
+ return;
+ }
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ const focused = document.activeElement as HTMLElement | null;
+ if (
+ focused &&
+ MENU_ITEM_ROLES.has(focused.getAttribute('role') ?? '')
+ ) {
+ focused.click();
+ }
+ return;
+ }
+ const isRtl =
+ typeof window !== 'undefined' && menuRef.current
+ ? window.getComputedStyle(menuRef.current).direction === 'rtl'
+ : false;
+ const closeKey = isRtl ? 'ArrowRight' : 'ArrowLeft';
+ if (e.key === closeKey) {
+ e.preventDefault();
+ close({focusTrigger: true});
+ return;
+ }
+ if (typeahead.onKeyDown(e)) {
+ e.preventDefault();
+ return;
+ }
+ listNavKeyDown(e);
+ },
+ [ownsEvent, close, listNavKeyDown, typeahead, menuRef],
+ );
+
+ // Re-provide the menu context so nested items behave exactly like top-level
+ // ones. Selecting a leaf item must dismiss the WHOLE stack, not just this
+ // 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).
+ const nestedMenuContext = useMemo<DropdownMenuContextValue>(
+ () => ({
+ menuSize,
+ closeMenu: () => {
+ close({focusTrigger: false});
+ menuCtx?.closeMenu();
+ },
+ }),
+ [menuSize, close, menuCtx],
+ );
+
+ const endAffordance = hasSpinner ? (
+ <span {...stylex.props(triggerStyles.caret)}>
+ <Spinner size="sm" />
+ </span>
+ ) : (
+ <span {...stylex.props(triggerStyles.caret)}>
+ <Icon icon="chevronRight" size="sm" color="secondary" />
+ </span>
+ );
+
+ const popoverXstyle = menuWidth
+ ? flyoutStyles.popoverCustomWidth(menuWidth)
+ : flyoutStyles.popover;
+
+ return (
+ <>
+ <Item
+ ref={el => setTriggerEl(el as HTMLDivElement | null)}
+ id={triggerId}
+ role="menuitem"
+ tabIndex={isDisabled ? undefined : -1}
+ aria-haspopup="menu"
+ aria-expanded={isOpen}
+ aria-controls={isOpen ? contentId : undefined}
+ aria-disabled={isDisabled || undefined}
+ data-testid={testId}
+ onMouseEnter={triggerProps.onMouseEnter}
+ onMouseLeave={triggerProps.onMouseLeave}
+ startContent={
+ icon
+ ? renderIconSlot(icon, {size: 'sm', color: 'secondary'})
+ : undefined
+ }
+ label={label}
+ description={description}
+ endContent={endAffordance}
+ onClick={handleTriggerClick}
+ onKeyDown={handleTriggerKeyDown}
+ isDisabled={isDisabled}
+ xstyle={[
+ triggerStyles.root,
+ triggerSizeStyles[menuSize],
+ isOpen && triggerStyles.open,
+ isDisabled && triggerStyles.disabled,
+ xstyle,
+ ]}
+ {...mergeProps(themeProps('dropdown-menu-item', {size: menuSize}), {
+ className,
+ style,
+ })}
+ />
+ {layer.render(
+ <div
+ ref={menuRef}
+ id={contentId}
+ role="menu"
+ // Focusable as a fallback target so an empty/loading flyout (e.g.
+ // hasSpinner with only a disabled row) can still receive keyboard
+ // focus and own arrow/Escape keys instead of leaving focus on the
+ // parent list.
+ tabIndex={-1}
+ aria-labelledby={triggerId}
+ onKeyDown={handleContentKeyDown}
+ onMouseEnter={contentProps.onMouseEnter}
+ onMouseLeave={contentProps.onMouseLeave}
+ data-testid={menuDataTestId}
+ {...mergeProps(
+ themeProps('dropdown-menu'),
+ stylex.props(flyoutStyles.menu),
+ )}>
+ <DropdownMenuContext value={nestedMenuContext}>
+ {children}
+ </DropdownMenuContext>
+ </div>,
+ {
+ placement: 'end',
+ alignment: 'start',
+ xstyle: [popoverXstyle, layerAnimations.end],
+ },
+ )}
+ </>
+ );
+}
+
+DropdownMenuSubMenu.displayName = 'DropdownMenuSubMenu';
diff --git a/packages/core/src/DropdownMenu/index.ts b/packages/core/src/DropdownMenu/index.ts
index ca399caf90..4587aff0b4 100644
--- a/packages/core/src/DropdownMenu/index.ts
+++ b/packages/core/src/DropdownMenu/index.ts
@@ -6,6 +6,15 @@
* @file index.ts
* @output Exports DropdownMenu, DropdownMenuItem and related types
* @position Public API entry point
+ *
+ * SYNC: The item components below are re-exported (aliased) by the other menu
+ * surfaces that reuse the DropdownMenu item pipeline. When you add or remove an
+ * item component here, mirror it in:
+ * - /packages/core/src/ContextMenu/index.ts (ContextMenu* aliases)
+ * - /packages/core/src/Breadcrumbs/index.ts (BreadcrumbMenu* aliases)
+ * Those surfaces render menu items through the same renderDropdownItems +
+ * DropdownMenuContext + useListFocus path, so a new item type (e.g. a submenu)
+ * only shows up in their public API once it's aliased there too.
*/
export {
@@ -34,6 +43,13 @@ export {
type DropdownMenuRadioItemProps,
} from './DropdownMenuRadioItem';
+// Submenu — a single menu row that reveals a nested flyout of its own
+// children/items. Data mode via DropdownMenuItemData.items.
+export {
+ DropdownMenuSubMenu,
+ type DropdownMenuSubMenuProps,
+} from './DropdownMenuSubMenu';
+
// Menu-coordination context — public so consumers can build custom menu items
// that read the menu size / close the menu.
export {
diff --git a/packages/core/src/DropdownMenu/menuItemRoles.ts b/packages/core/src/DropdownMenu/menuItemRoles.ts
index 7c86772b06..1531de8cee 100644
--- a/packages/core/src/DropdownMenu/menuItemRoles.ts
+++ b/packages/core/src/DropdownMenu/menuItemRoles.ts
@@ -20,3 +20,12 @@ export const MENU_ITEM_ROLES: ReadonlySet<string> = new Set([
export const MENU_ITEM_SELECTOR: string = [...MENU_ITEM_ROLES]
.map(role => `[role="${role}"]:not([aria-disabled="true"])`)
.join(',');
+
+/**
+ * Boundary selector for a single menu level. A menu and its submenu flyouts
+ * both use `role="menu"`, and flyouts render inline (native popover, not a
+ * portal), so a nested menu's items and key events would otherwise be picked
+ * up by the parent. Pass this as `useListFocus`'s `boundarySelector` so each
+ * level scopes item collection and key handling to its own container.
+ */
+export const MENU_BOUNDARY_SELECTOR = '[role="menu"]';
diff --git a/packages/core/src/DropdownMenu/renderDropdownItems.tsx b/packages/core/src/DropdownMenu/renderDropdownItems.tsx
index e97ec7ddc0..8d82083084 100644
--- a/packages/core/src/DropdownMenu/renderDropdownItems.tsx
+++ b/packages/core/src/DropdownMenu/renderDropdownItems.tsx
@@ -10,6 +10,7 @@ import type {ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Divider} from '../Divider';
import {DropdownMenuItem} from './DropdownMenuItem';
+import {DropdownMenuSubMenu} from './DropdownMenuSubMenu';
import {
spacingVars,
typographyVars,
@@ -49,18 +50,14 @@ function getSectionKey(section: DropdownMenuSection, index: number): string {
* Converts data-driven items into DropdownMenuItem components,
* so both modes share the same rendering and keyboard navigation path.
*/
-export function renderDropdownItems(
- items: DropdownMenuOption[],
-): ReactNode {
+export function renderDropdownItems(items: DropdownMenuOption[]): ReactNode {
const elements: ReactNode[] = [];
for (let i = 0; i < items.length; i++) {
const option = items[i];
if ('type' in option && option.type === 'divider') {
- elements.push(
- <Divider key={`divider-${i}`} xstyle={styles.divider} />,
- );
+ elements.push(<Divider key={`divider-${i}`} xstyle={styles.divider} />);
} else if ('type' in option && option.type === 'section') {
elements.push(
<div
@@ -84,15 +81,32 @@ export function renderDropdownItems(
</div>,
);
} else if (!('type' in option)) {
- elements.push(
- <DropdownMenuItem
- key={getItemKey(option)}
- icon={option.icon}
- label={option.label}
- onClick={option.onClick}
- isDisabled={option.isDisabled}
- />,
- );
+ // A plain item that declares nested `items` becomes a submenu (data-mode
+ // parity with the compound DropdownMenuSubMenu API); otherwise it's a
+ // leaf. renderDropdownItems owns the recursion and hands the rendered
+ // children to DropdownMenuSubMenu — so DropdownMenuSubMenu never imports
+ // this module back (no import cycle).
+ if (option.items && option.items.length > 0) {
+ elements.push(
+ <DropdownMenuSubMenu
+ key={getItemKey(option)}
+ icon={option.icon}
+ label={option.label}
+ isDisabled={option.isDisabled}>
+ {renderDropdownItems(option.items)}
+ </DropdownMenuSubMenu>,
+ );
+ } else {
+ elements.push(
+ <DropdownMenuItem
+ key={getItemKey(option)}
+ icon={option.icon}
+ label={option.label}
+ onClick={option.onClick}
+ isDisabled={option.isDisabled}
+ />,
+ );
+ }
}
}
diff --git a/packages/core/src/hooks/useListFocus.doc.mjs b/packages/core/src/hooks/useListFocus.doc.mjs
index c8732554a3..8d78180a24 100644
--- a/packages/core/src/hooks/useListFocus.doc.mjs
+++ b/packages/core/src/hooks/useListFocus.doc.mjs
@@ -19,6 +19,13 @@ export const docs = {
default: "'[role=\"menuitem\"]'",
required: false,
},
+ {
+ name: 'options.boundarySelector',
+ type: 'string',
+ description:
+ "Selector identifying a list boundary, for lists that contain nested lists of the same kind (e.g. a menu with submenu flyouts). When set, item collection and key handling are scoped to this level's own container. Typically '[role=\"menu\"]'.",
+ required: false,
+ },
{
name: 'options.wrap',
type: 'boolean',
@@ -99,6 +106,18 @@ export const docs = {
type: '() => boolean',
description: 'Focus the last enabled item. Returns true when an item was focused.',
},
+ {
+ name: 'ownsEvent',
+ type: '(e: React.KeyboardEvent) => boolean',
+ description:
+ "Whether a key event belongs to this list level rather than a nested list sharing the same boundarySelector. Always true when no boundarySelector is set. Use to guard consumer-added key handling (Enter/Space, typeahead).",
+ },
+ {
+ name: 'getItems',
+ type: '() => HTMLElement[]',
+ description:
+ "This level's focusable items in DOM order (already scoped by boundarySelector). Build typeahead targets from this instead of re-querying.",
+ },
],
usage: {
description:
@@ -123,6 +142,7 @@ export const docsDense = {
paramDescriptions: {
options: 'config for list focus behavior. All fields optional.',
'options.itemSelector': 'selector for focusable items in list.',
+ 'options.boundarySelector': "boundary selector for lists that contain nested lists (e.g. submenu flyouts); scopes items + key handling to this level.",
'options.wrap': 'whether arrow navigation wraps around at ends.',
'options.onEscape': 'callback when Escape key pressed (e.g. close menu).',
'options.orientation': "navigation orientation. 'horizontal' uses ArrowLeft/ArrowRight, 'vertical' uses ArrowUp/ArrowDown, 'both' accepts all four arrows.",
@@ -138,6 +158,8 @@ export const docsDense = {
focusItem: 'focus specific item by index (clamped to valid range).',
focusFirst: 'focus first enabled item; returns true when focused.',
focusLast: 'focus last enabled item; returns true when focused.',
+ ownsEvent: 'whether a key event is this level\'s vs a nested list\'s (boundarySelector); always true without one.',
+ getItems: "this level's focusable items in DOM order, scoped by boundarySelector.",
},
usage: {
description:
diff --git a/packages/core/src/hooks/useListFocus.test.tsx b/packages/core/src/hooks/useListFocus.test.tsx
index b86a65b107..2b2b1c3bfd 100644
--- a/packages/core/src/hooks/useListFocus.test.tsx
+++ b/packages/core/src/hooks/useListFocus.test.tsx
@@ -11,6 +11,7 @@
*/
import {describe, it, expect} from 'vitest';
+import type {KeyboardEvent as ReactKeyboardEvent} from 'react';
import {render, screen, fireEvent} from '@testing-library/react';
import {useListFocus} from './useListFocus';
@@ -439,3 +440,88 @@ describe('useListFocus RTL auto-detection (WCAG 1.3.2)', () => {
expect(screen.getByTestId('Two')).toHaveFocus();
});
});
+
+// A menu whose second item contains a NESTED role="menu" (mirrors an inline
+// submenu flyout). Exercises boundarySelector: item scoping + event ownership.
+function NestedMenu() {
+ const {listRef, handleKeyDown, ownsEvent} = useListFocus<HTMLDivElement>({
+ boundarySelector: '[role="menu"]',
+ wrap: false,
+ });
+ return (
+ <div ref={listRef} role="menu" onKeyDown={handleKeyDown}>
+ <div role="menuitem" tabIndex={-1} data-testid="Outer1">
+ Outer1
+ </div>
+ <div role="menuitem" tabIndex={-1} data-testid="Outer2">
+ Outer2
+ {/* Nested submenu rendered inline (like a popover flyout). */}
+ <div role="menu" data-testid="inner-menu">
+ <div role="menuitem" tabIndex={-1} data-testid="Inner1">
+ Inner1
+ </div>
+ <div role="menuitem" tabIndex={-1} data-testid="Inner2">
+ Inner2
+ </div>
+ </div>
+ </div>
+ <div role="menuitem" tabIndex={-1} data-testid="Outer3">
+ Outer3
+ </div>
+ {/* Surface ownership for assertions. */}
+ <input
+ data-testid="probe-owns"
+ onKeyDown={e => {
+ e.currentTarget.setAttribute('data-owns', String(ownsEvent(e)));
+ }}
+ />
+ </div>
+ );
+}
+
+// Variant with the ownsEvent probe placed INSIDE the nested menu, so a key
+// event from it reports as not-owned by the outer list.
+function NestedMenuWithInnerProbe() {
+ const {listRef, handleKeyDown, ownsEvent} = useListFocus<HTMLDivElement>({
+ boundarySelector: '[role="menu"]',
+ wrap: false,
+ });
+ const report = (e: ReactKeyboardEvent<HTMLInputElement>) => {
+ e.currentTarget.setAttribute('data-owns', String(ownsEvent(e)));
+ };
+ return (
+ <div ref={listRef} role="menu" onKeyDown={handleKeyDown}>
+ <div role="menuitem" tabIndex={-1} data-testid="Outer1">
+ Outer1
+ </div>
+ <div role="menu" data-testid="inner-menu">
+ <input data-testid="inner-probe" onKeyDown={report} />
+ </div>
+ </div>
+ );
+}
+
+describe('useListFocus boundarySelector (nested lists)', () => {
+ it("ArrowDown skips over a nested list's items to the next own item", () => {
+ render(<NestedMenu />);
+ const menu = screen.getAllByRole('menu')[0];
+ screen.getByTestId('Outer2').focus();
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ // Lands on Outer3, not Inner1 (which is inside the nested menu).
+ expect(screen.getByTestId('Outer3')).toHaveFocus();
+ });
+
+ it('ownsEvent is true for an event originating at this level', () => {
+ render(<NestedMenu />);
+ const ownProbe = screen.getByTestId('probe-owns');
+ fireEvent.keyDown(ownProbe, {key: 'ArrowDown'});
+ expect(ownProbe).toHaveAttribute('data-owns', 'true');
+ });
+
+ it('ownsEvent is false for an event from inside a nested list', () => {
+ render(<NestedMenuWithInnerProbe />);
+ const innerProbe = screen.getByTestId('inner-probe');
+ fireEvent.keyDown(innerProbe, {key: 'ArrowDown'});
+ expect(innerProbe).toHaveAttribute('data-owns', 'false');
+ });
+});
diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.ts
index 4a091c5817..3c4fe4aea7 100644
--- a/packages/core/src/hooks/useListFocus.ts
+++ b/packages/core/src/hooks/useListFocus.ts
@@ -38,6 +38,25 @@ export interface UseListFocusOptions {
*/
itemSelector?: string;
+ /**
+ * Selector identifying a list boundary — used to scope a list that contains
+ * *nested* lists of the same kind (e.g. a menu with submenu flyouts).
+ *
+ * Overlays like submenu flyouts render inline (native popover, not a
+ * portal), so a nested list's items are DOM descendants of the parent list.
+ * Without scoping, the parent's `querySelectorAll` sweeps the nested items
+ * into its roving order (leaving hidden items `.focus()` can't land on), and
+ * key events from the nested list bubble into the parent's handler (moving
+ * focus twice). When set, `useListFocus`:
+ * - counts an item as its own only when the item's nearest
+ * `boundarySelector` ancestor is this list's container, and
+ * - ignores key events whose nearest `boundarySelector` ancestor is not
+ * this list's container (i.e. they originated in a nested list).
+ *
+ * Typically `'[role="menu"]'` for menus. Omit for flat lists.
+ */
+ boundarySelector?: string;
+
/**
* Whether arrow navigation wraps around at the ends.
* @default true
@@ -137,6 +156,23 @@ export interface UseListFocusReturn<T extends HTMLElement = HTMLElement> {
* Focus the last enabled item. Returns true when an item was focused.
*/
focusLast: () => boolean;
+
+ /**
+ * Whether a key event belongs to this list level (vs. a nested list that
+ * shares the same `boundarySelector`). Useful when a consumer wraps
+ * `handleKeyDown` with extra behavior (Enter/Space activation, typeahead)
+ * and must apply it only to events this level owns. Always true when no
+ * `boundarySelector` is configured.
+ */
+ ownsEvent: (e: React.KeyboardEvent) => boolean;
+
+ /**
+ * The current, in-DOM-order list of this level's focusable items (already
+ * scoped by `boundarySelector`). Exposed so consumers can build typeahead
+ * targets from the same source of truth as roving focus, rather than
+ * re-querying and re-filtering.
+ */
+ getItems: () => HTMLElement[];
}
// Text-editing inputs whose caret must not be hijacked by arrow navigation.
@@ -280,6 +316,7 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
): UseListFocusReturn<T> {
const {
itemSelector = '[role="menuitem"]',
+ boundarySelector,
wrap = true,
onEscape,
orientation = 'vertical',
@@ -308,13 +345,43 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
* Get all focusable items in the list.
*/
const getItems = useCallback((): HTMLElement[] => {
- if (!listRef.current) {
+ const listEl = listRef.current;
+ if (!listEl) {
return [];
}
- return Array.from(
- listRef.current.querySelectorAll<HTMLElement>(itemSelector),
+ const matched = Array.from(
+ listEl.querySelectorAll<HTMLElement>(itemSelector),
);
- }, [itemSelector]);
+ // 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
+ // otherwise be swept in by querySelectorAll.
+ if (!boundarySelector) {
+ return matched;
+ }
+ return matched.filter(el => el.closest(boundarySelector) === listEl);
+ }, [itemSelector, boundarySelector]);
+
+ /**
+ * Whether a key event belongs to this list level rather than a nested list.
+ * With a boundary set, an event that originated inside a nested boundary
+ * (e.g. a submenu flyout) has bubbled up to us and must be ignored so we
+ * don't double-handle navigation. Without a boundary, every event is ours.
+ */
+ const ownsEvent = useCallback(
+ (e: React.KeyboardEvent): boolean => {
+ const listEl = listRef.current;
+ if (!listEl || !boundarySelector) {
+ return true;
+ }
+ const target = e.target as HTMLElement | null;
+ if (!target) {
+ return true;
+ }
+ return target.closest(boundarySelector) === listEl;
+ },
+ [boundarySelector],
+ );
/**
* Find the next enabled item index from `start`, moving by `step`, optionally
@@ -482,6 +549,13 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
return;
}
+ // Ignore events that bubbled up from a nested list (e.g. a submenu
+ // flyout, which renders inline inside this container). That level owns
+ // and already handled them; re-handling here would move focus twice.
+ if (!ownsEvent(e)) {
+ return;
+ }
+
// Escape is handled regardless of orientation. Preserve the historical
// behavior of always consuming Escape here (preventDefault) so consumers
// that relied on it are unaffected.
@@ -569,6 +643,7 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
focusFirst,
focusLast,
onEscape,
+ ownsEvent,
],
);
@@ -579,5 +654,7 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
focusItem,
focusFirst,
focusLast,
+ ownsEvent,
+ getItems,
};
}