An open source design system that's fully customizable and agent ready
TypeScript
feat(DropdownMenuSubMenu): forward host attributes, DOM handlers and a ref to the trigger row (#7318)
Christopher Chedeau3bc1f204abb2
diff --git a/.changeset/dropdown-menu-submenu-row-host-props.md b/.changeset/dropdown-menu-submenu-row-host-props.mdnew file mode 100644index 0000000000..af36414f75--- /dev/null+++ b/.changeset/dropdown-menu-submenu-row-host-props.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] `DropdownMenuSubMenu` passes host attributes, DOM event handlers and a `ref` to its trigger row, as `DropdownMenuItem` does: a sub-menu row can carry `aria-keyshortcuts`, a `data-*` mark or an `id`, and a caller can reach the row element. The row keeps its own role, tab stop and popup state; a caller's `onClick`, `onKeyDown`, `onPointerMove`, `onMouseEnter` and `onMouseLeave` run after the row's own handling, except for an event the row consumes: the keys that open the flyout (the open arrow, Enter and Space) and a click on a disabled row. A caller's `id` names the row the flyout is labelled by.++@vjeuxdiff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjsindex fb2bb71b51..61d8e3cb98 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). 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.',+ '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. Host attributes and DOM event handlers (aria-*, data-*, id) reach the trigger row, the element carrying role="menuitem" and aria-haspopup="menu"; a caller\'s handlers run after the row\'s own, except for the keys that open the flyout (the open arrow, Enter, Space) and a click on a disabled row. For data-driven menus, give a menu item a nested `items` array instead of using this component directly.',playground: {defaults: {label: 'Move to'},},@@ -73,6 +73,12 @@ export const docs = {description:'StyleX styles for the trigger row. Must be a stylex.create() value: not an inline style object like style={{}}.',},+ {+ name: 'ref',+ type: 'React.Ref<HTMLElement>',+ description:+ 'Ref forwarded to the trigger row, the element carrying role="menuitem" and aria-haspopup="menu".',+ },],};@@ -95,5 +101,6 @@ export const docsDense = {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',+ ref: 'ref to the trigger row (role="menuitem")',},};diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsxindex 3647b8c0d7..172fe62448 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx@@ -7,7 +7,7 @@*/import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';-import {useState} from 'react';+import {createRef, useState} from 'react';import {render, screen, waitFor, fireEvent, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';import * as stylex from '@stylexjs/stylex';@@ -439,6 +439,151 @@ describe('DropdownMenuSubMenu', () => {});});+describe('DropdownMenuSubMenu host attributes', () => {+ async function openRoot(user: ReturnType<typeof userEvent.setup>) {+ await user.click(screen.getByRole('button', {name: /Actions/}));+ // A pointer open focuses the menu in a frame; let it land first.+ await waitFor(() => {+ expect(+ screen.getByRole('menu', {name: 'Actions', hidden: true}),+ ).toHaveFocus();+ });+ return screen.getByRole('menuitem', {name: /Move to/, hidden: true});+ }++ it('aria-*, data-* and id reach the trigger row, and the flyout stays labelled by it', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuSubMenu+ label="Move to"+ aria-keyshortcuts="M"+ data-row="move"+ id="move-row">+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ const trigger = await openRoot(user);+ expect(trigger).toHaveAttribute('aria-keyshortcuts', 'M');+ expect(trigger).toHaveAttribute('data-row', 'move');+ expect(trigger).toHaveAttribute('id', 'move-row');+ expect(trigger).toHaveAttribute('aria-haspopup', 'menu');+ await user.click(trigger);+ await waitFor(() =>+ expect(trigger).toHaveAttribute('aria-expanded', 'true'),+ );+ expect(+ screen.getByRole('menu', {name: 'Move to', hidden: true}),+ ).toHaveAttribute('aria-labelledby', 'move-row');+ });++ it('a ref reaches the trigger row', async () => {+ const user = userEvent.setup();+ const ref = createRef<HTMLElement>();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuSubMenu label="Move to" ref={ref}>+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ const trigger = await openRoot(user);+ expect(ref.current).toBe(trigger);+ });++ it("a caller's handlers run after the row's own, and the row still opens and takes the hover focus", async () => {+ const user = userEvent.setup();+ const onKeyDown = vi.fn();+ const onClick = vi.fn();+ const onPointerMove = vi.fn();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuItem label="Rename" onClick={() => {}} />+ <DropdownMenuSubMenu+ label="Move to"+ onKeyDown={onKeyDown}+ onClick={onClick}+ onPointerMove={onPointerMove}>+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ const trigger = await openRoot(user);+ fireEvent.pointerMove(trigger, {pointerType: 'mouse'});+ expect(trigger).toHaveFocus();+ expect(onPointerMove).toHaveBeenCalledTimes(1);+ // A key the row does not consume reaches the caller.+ fireEvent.keyDown(trigger, {key: 'm'});+ expect(onKeyDown).toHaveBeenCalledTimes(1);+ await user.keyboard('{ArrowRight}');+ await waitFor(() =>+ expect(trigger).toHaveAttribute('aria-expanded', 'true'),+ );+ fireEvent.click(trigger, {detail: 1});+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it('a stable callback ref is not re-run as the flyout opens and closes', async () => {+ const user = userEvent.setup();+ const ref = vi.fn<(el: HTMLElement | null) => void>();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuSubMenu label="Move to" ref={ref}>+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ const trigger = await openRoot(user);+ expect(ref).toHaveBeenLastCalledWith(trigger);+ ref.mockClear();+ await user.click(trigger);+ await waitFor(() =>+ expect(trigger).toHaveAttribute('aria-expanded', 'true'),+ );+ await user.keyboard('{Escape}');+ await waitFor(() =>+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),+ );+ expect(ref).not.toHaveBeenCalled();+ });++ it("a disabled row does not pass a click on to the caller's onClick", async () => {+ const user = userEvent.setup();+ const onClick = vi.fn();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuSubMenu label="Move to" isDisabled onClick={onClick}>+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ const trigger = await openRoot(user);+ // A programmatic or assistive-technology activation.+ act(() => trigger.click());+ expect(onClick).not.toHaveBeenCalled();+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });++ it('the row keeps its own popup state and tab stop', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuSubMenu+ label="Move to"+ aria-haspopup="listbox"+ aria-expanded={true}>+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ const trigger = await openRoot(user);+ expect(trigger).toHaveAttribute('aria-haspopup', 'menu');+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(trigger).toHaveAttribute('tabindex', '-1');+ });+});+describe('DropdownMenu data-driven submenus', () => {it('renders a submenu when an item declares nested items', async () => {const user = userEvent.setup();diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsxindex 96eb51610c..dcd1443bb6 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx@@ -14,8 +14,9 @@* 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+ * (label / icon / description / isDisabled, host attributes, DOM handlers and+ * a ref on the row) 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`@@ -82,7 +83,8 @@ import {typographyVars,typeScaleVars,} from '../theme/tokens.stylex';-import {mergeProps, rtlStyles} from '../utils';+import {composeEventHandlers, mergeProps, rtlStyles} from '../utils';+import {useMergedRefs} from '../hooks/useMergedRefs';import {themeProps} from '../utils/themeProps';import type {BaseProps} from '../BaseProps';import {@@ -243,9 +245,9 @@ const drillInStyles = stylex.create({export type DropdownMenuSubMenuPresentation ='flyout' | 'drill-in' | 'adaptive';-interface DropdownMenuSubMenuBaseProps extends Pick<+interface DropdownMenuSubMenuBaseProps extends Omit<BaseProps,- 'xstyle' | 'className' | 'style'+ 'role' | 'tabIndex'> {/** Icon to display before the label on the trigger row. */icon?: ReactNode | IconType;@@ -285,6 +287,11 @@ interface DropdownMenuSubMenuBaseProps extends Pick<'data-testid'?: string;/** Test id for the flyout menu. */menuDataTestId?: string;+ /**+ * Ref forwarded to the trigger row — the element carrying `role="menuitem"`+ * and `aria-haspopup="menu"`.+ */+ ref?: React.Ref<HTMLElement>;}export interface DropdownMenuSubMenuProps extends DropdownMenuSubMenuBaseProps {@@ -338,6 +345,15 @@ export function DropdownMenuSubMenu(style,'data-testid': testId,menuDataTestId,+ ref,+ id: idProp,+ onMouseEnter,+ onMouseLeave,+ onPointerMove,+ onClick,+ onKeyDown,+ // Host attributes and DOM handlers for the trigger row.+ ...rest} = props;const t = useTranslator();@@ -346,7 +362,9 @@ export function DropdownMenuSubMenu(const canOpen = !isDisabled;const contentId = useId();- const triggerId = useId();+ const generatedTriggerId = useId();+ // A caller's `id` names the row; the flyout stays labelled by it.+ const triggerId = idProp ?? generatedTriggerId;const triggerRef = useRef<HTMLDivElement | null>(null);// Drill-in: the root keeps a view stack; this row pushes its@@ -529,17 +547,26 @@ export function DropdownMenuSubMenu(// Single ref for the trigger row: store it for focus management AND wire it// as the flyout's positioning anchor (CSS anchor positioning).+ // Depends on the layer's anchor ref alone, which is stable: the layer+ // object changes with its open state, and a new callback here would re-run a+ // caller's ref as the flyout opens.+ const layerRef = layer.ref;const setTriggerEl = useCallback((el: HTMLDivElement | null) => {triggerRef.current = el;- layer.ref(el);+ layerRef(el);},- [layer],+ [layerRef],);+ // The caller's ref reaches the same row.+ const triggerRowRef = useMergedRefs<HTMLElement>(setTriggerEl, ref);const handleTriggerClick = useCallback((event: React.MouseEvent) => {if (isDisabled) {+ // As a disabled DropdownMenuItem does: the click is spent, so a+ // caller's onClick composed after this one does not run.+ event.preventDefault();return;}if (isDrillIn) {@@ -576,6 +603,18 @@ export function DropdownMenuSubMenu(],);+ // The row's toggle runs first, then a caller's `onClick`. Item reports the+ // click as a generic element event; its root is the row's HTMLElement.+ const handleRowClick = useCallback(+ (event: React.MouseEvent) => {+ composeEventHandlers<React.MouseEvent<HTMLElement>>(+ handleTriggerClick,+ onClick,+ )(event as React.MouseEvent<HTMLElement>);+ },+ [handleTriggerClick, onClick],+ );+const handleTriggerKeyDown = useCallback((e: React.KeyboardEvent) => {if (isDisabled) {@@ -757,7 +796,11 @@ export function DropdownMenuSubMenu(return (<><Item- ref={el => setTriggerEl(el as HTMLDivElement | null)}+ // Host attributes and handlers first: the row's role, tab stop, popup+ // state and wiring are set after them, and its own handlers run+ // before the caller's.+ {...rest}+ ref={triggerRowRef}id={triggerId}role="menuitem"tabIndex={isDisabled ? undefined : -1}@@ -766,9 +809,15 @@ export function DropdownMenuSubMenu(aria-controls={isOpen ? contentId : undefined}aria-disabled={isDisabled || undefined}data-testid={testId}- onMouseEnter={triggerProps.onMouseEnter}- onMouseLeave={triggerProps.onMouseLeave}- onPointerMove={handlePointerMove}+ onMouseEnter={composeEventHandlers(+ triggerProps.onMouseEnter,+ onMouseEnter,+ )}+ onMouseLeave={composeEventHandlers(+ triggerProps.onMouseLeave,+ onMouseLeave,+ )}+ onPointerMove={composeEventHandlers(handlePointerMove, onPointerMove)}startContent={icon? renderIconSlot(icon, {size: 'sm', color: 'secondary'})@@ -777,8 +826,8 @@ export function DropdownMenuSubMenu(label={label}description={description}endContent={endAffordance}- onClick={handleTriggerClick}- onKeyDown={handleTriggerKeyDown}+ onClick={handleRowClick}+ onKeyDown={composeEventHandlers(handleTriggerKeyDown, onKeyDown)}isDisabled={isDisabled}xstyle={[triggerStyles.root,