An open source design system that's fully customizable and agent ready
TypeScript
feat(menu): compound-component mode for XDSDropdownMenu (#1372)
Cindy Zhang47e8956f6fed
diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsxindex faae7c6eb5..1f98ee9f5b 100644--- a/apps/storybook/stories/DropdownMenu.stories.tsx+++ b/apps/storybook/stories/DropdownMenu.stories.tsx@@ -1,6 +1,7 @@import type {Meta, StoryObj} from '@storybook/react';import {useState} from 'react';import {XDSDropdownMenu, XDSDropdownMenuItem} from '@xds/core/DropdownMenu';+import {XDSDivider} from '@xds/core/Divider';import {PencilIcon,TrashIcon,@@ -37,9 +38,6 @@ const meta: Meta<typeof XDSDropdownMenu> = {control: 'text',description: 'Custom menu width (number for px or CSS string)',},- children: {- description: 'Custom render function for items',- },'data-testid': {control: 'text',description: 'Test ID for testing frameworks',@@ -281,23 +279,28 @@ export const WithOnClick: Story = {},};-// Custom item rendering with XDSDropdownMenuItem+// Custom item rendering with compound modeexport const CustomItemRender: Story = {render: () => (- <XDSDropdownMenu- button={{label: 'Select User'}}- items={[- {label: 'Alice Johnson'},- {label: 'Bob Smith'},- {label: 'Carol Williams'},- ]}>- {item => (- <XDSDropdownMenuItem- icon={UserIcon}- label={item.label}- description={`${item.label.toLowerCase().replace(' ', '.')}@example.com`}- />- )}+ <XDSDropdownMenu button={{label: 'Select User'}} menuWidth={280}>+ <XDSDropdownMenuItem+ icon={UserIcon}+ label="Alice Johnson"+ description="[email protected]"+ onClick={() => console.log('Alice')}+ />+ <XDSDropdownMenuItem+ icon={UserIcon}+ label="Bob Smith"+ description="[email protected]"+ onClick={() => console.log('Bob')}+ />+ <XDSDropdownMenuItem+ icon={UserIcon}+ label="Carol Williams"+ description="[email protected]"+ onClick={() => console.log('Carol')}+ /></XDSDropdownMenu>),};@@ -370,3 +373,124 @@ export const NoChevron: Story = {/>),};++// Compound-component mode — JSX children with interactive items+export const CompoundBasic: Story = {+ render: () => (+ <XDSDropdownMenu button={{label: 'Actions'}}>+ <XDSDropdownMenuItem+ icon={PencilIcon}+ label="Edit"+ onClick={() => console.log('Edit')}+ />+ <XDSDropdownMenuItem+ icon={DocumentDuplicateIcon}+ label="Duplicate"+ onClick={() => console.log('Duplicate')}+ />+ <XDSDivider />+ <XDSDropdownMenuItem+ icon={TrashIcon}+ label="Delete"+ onClick={() => console.log('Delete')}+ />+ </XDSDropdownMenu>+ ),+};++// Compound mode with disabled items+export const CompoundWithDisabled: Story = {+ render: () => (+ <XDSDropdownMenu button={{label: 'File Actions'}}>+ <XDSDropdownMenuItem+ icon={PencilIcon}+ label="Edit"+ onClick={() => console.log('Edit')}+ />+ <XDSDropdownMenuItem+ icon={DocumentDuplicateIcon}+ label="Duplicate"+ onClick={() => console.log('Duplicate')}+ />+ <XDSDivider />+ <XDSDropdownMenuItem+ icon={TrashIcon}+ label="Delete (no permission)"+ isDisabled+ />+ </XDSDropdownMenu>+ ),+};++// Compound mode with conditional items+export const CompoundConditional: Story = {+ render: () => {+ const [canDelete, setCanDelete] = useState(false);+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: 16,+ alignItems: 'center',+ }}>+ <label style={{display: 'flex', gap: 8, alignItems: 'center'}}>+ <input+ type="checkbox"+ checked={canDelete}+ onChange={e => setCanDelete(e.target.checked)}+ />+ Show delete option+ </label>+ <XDSDropdownMenu button={{label: 'Actions'}}>+ <XDSDropdownMenuItem+ icon={PencilIcon}+ label="Edit"+ onClick={() => console.log('Edit')}+ />+ <XDSDropdownMenuItem+ icon={ShareIcon}+ label="Share"+ onClick={() => console.log('Share')}+ />+ {canDelete && (+ <>+ <XDSDivider />+ <XDSDropdownMenuItem+ icon={TrashIcon}+ label="Delete"+ onClick={() => console.log('Delete')}+ />+ </>+ )}+ </XDSDropdownMenu>+ </div>+ );+ },+};++// Compound mode with descriptions+export const CompoundWithDescriptions: Story = {+ render: () => (+ <XDSDropdownMenu button={{label: 'Select User'}} menuWidth={280}>+ <XDSDropdownMenuItem+ icon={UserIcon}+ label="Alice Johnson"+ description="[email protected]"+ onClick={() => console.log('Alice')}+ />+ <XDSDropdownMenuItem+ icon={UserIcon}+ label="Bob Smith"+ description="[email protected]"+ onClick={() => console.log('Bob')}+ />+ <XDSDropdownMenuItem+ icon={UserIcon}+ label="Carol Williams"+ description="[email protected]"+ onClick={() => console.log('Carol')}+ />+ </XDSDropdownMenu>+ ),+};diff --git a/packages/core/src/DropdownMenu/XDSDropdownMenu.test.tsx b/packages/core/src/DropdownMenu/XDSDropdownMenu.test.tsxindex b702f839af..7405411d30 100644--- a/packages/core/src/DropdownMenu/XDSDropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/XDSDropdownMenu.test.tsx@@ -11,6 +11,8 @@ import {describe, it, expect, vi, beforeEach} from 'vitest';import {render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {XDSDropdownMenu} from './XDSDropdownMenu';+import {XDSDropdownMenuItem} from './XDSDropdownMenuItem';+import {XDSDivider} from '../Divider';// Mock showPopover and hidePopover methods since they're not implemented in jsdombeforeEach(() => {@@ -334,23 +336,6 @@ describe('XDSDropdownMenu button customization', () => {});});-describe('XDSDropdownMenu custom render', () => {- it('supports custom item rendering via children prop', () => {- render(- <XDSDropdownMenu- button={{label: 'Actions'}}- items={[{label: 'Edit'}, {label: 'Delete'}]}>- {item => (- <span data-testid={`custom-${item.label}`}>{item.label}!</span>- )}- </XDSDropdownMenu>,- );-- expect(screen.getByTestId('custom-Edit')).toBeInTheDocument();- expect(screen.getByTestId('custom-Delete')).toBeInTheDocument();- });-});-describe('XDSDropdownMenu icon-only mode', () => {it('renders icon-only button when icon is set without children', () => {render(@@ -403,3 +388,98 @@ describe('XDSDropdownMenu hasChevron', () => {expect(endContentWrapper).toBeNull();});});++describe('XDSDropdownMenu compound mode', () => {+ it('renders JSX children as menu items', () => {+ render(+ <XDSDropdownMenu button={{label: 'Actions'}}>+ <XDSDropdownMenuItem label="Edit" onClick={() => {}} />+ <XDSDropdownMenuItem label="Delete" onClick={() => {}} />+ </XDSDropdownMenu>,+ );+ expect(+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('menuitem', {name: 'Delete', hidden: true}),+ ).toBeInTheDocument();+ });++ it('calls onClick when compound item is clicked', async () => {+ const user = userEvent.setup();+ const handleClick = vi.fn();+ render(+ <XDSDropdownMenu button={{label: 'Actions'}}>+ <XDSDropdownMenuItem label="Edit" onClick={handleClick} />+ </XDSDropdownMenu>,+ );++ await user.click(+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),+ );+ expect(handleClick).toHaveBeenCalledTimes(1);+ });++ it('does not call onClick when compound item is disabled', async () => {+ const user = userEvent.setup();+ const handleClick = vi.fn();+ render(+ <XDSDropdownMenu button={{label: 'Actions'}}>+ <XDSDropdownMenuItem label="Edit" onClick={handleClick} isDisabled />+ </XDSDropdownMenu>,+ );++ await user.click(+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),+ );+ expect(handleClick).not.toHaveBeenCalled();+ });++ it('renders dividers between compound items', () => {+ render(+ <XDSDropdownMenu button={{label: 'Actions'}}>+ <XDSDropdownMenuItem label="Edit" onClick={() => {}} />+ <XDSDivider />+ <XDSDropdownMenuItem label="Delete" onClick={() => {}} />+ </XDSDropdownMenu>,+ );++ expect(+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('menuitem', {name: 'Delete', hidden: true}),+ ).toBeInTheDocument();+ expect(screen.getByRole('separator', {hidden: true})).toBeInTheDocument();+ });++ it('has aria-disabled on disabled compound items', () => {+ render(+ <XDSDropdownMenu button={{label: 'Actions'}}>+ <XDSDropdownMenuItem label="Edit" onClick={() => {}} isDisabled />+ </XDSDropdownMenu>,+ );+ expect(+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),+ ).toHaveAttribute('aria-disabled', 'true');+ });++ it('supports mixed static and dynamic compound children', () => {+ const showExtra = true;+ render(+ <XDSDropdownMenu button={{label: 'Actions'}}>+ <XDSDropdownMenuItem label="Always" onClick={() => {}} />+ {showExtra && (+ <XDSDropdownMenuItem label="Conditional" onClick={() => {}} />+ )}+ </XDSDropdownMenu>,+ );++ expect(+ screen.getByRole('menuitem', {name: 'Always', hidden: true}),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('menuitem', {name: 'Conditional', hidden: true}),+ ).toBeInTheDocument();+ });+});diff --git a/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx b/packages/core/src/DropdownMenu/XDSDropdownMenu.tsxindex 379bee092f..b2f3098e27 100644--- a/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx@@ -2,10 +2,16 @@/*** @file XDSDropdownMenu.tsx- * @input Uses React, StyleX, useXDSPopover, XDSButton, XDSIcon+ * @input Uses React, StyleX, useXDSPopover, XDSButton, XDSIcon, useListFocus* @output Exports XDSDropdownMenu component* @position Core implementation; consumed by index.ts*+ * Supports two modes with a single keyboard/focus path:+ * - **Data-driven**: pass `items` array (converted to components internally)+ * - **Compound-component**: pass JSX children directly+ *+ * Both modes use useListFocus for DOM-based keyboard navigation.+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/DropdownMenu/DropdownMenu.doc.mjs* - /packages/core/src/DropdownMenu/XDSDropdownMenu.test.tsx@@ -27,45 +33,28 @@ import {XDSButton, type XDSButtonProps} from '../Button';import {XDSIcon} from '../Icon';import type {XDSIconType} from '../Icon';-import {XDSDivider} from '../Divider';-import {XDSDropdownMenuItem} from './XDSDropdownMenuItem';+import {renderXDSDropdownItems} from './renderXDSDropdownItems';+import {+ XDSDropdownMenuContext,+ type XDSDropdownMenuContextValue,+} from './XDSDropdownMenuContext';+import {useListFocus} from '../hooks/useListFocus';import {layerAnimations} from '../Layer/layerAnimations.stylex';import {- colorVars,spacingVars,radiusVars,durationVars,easeVars,- typographyVars,- typeScaleVars,} from '../theme/tokens.stylex';import {xdsClassName, mergeProps} from '../utils';--/**- * Size-aware item padding.- * sm triggers → tighter vertical padding (4px block, 8px inline)- * md/lg triggers → standard padding (8px all around, inherited from base item style)- *- * Note: menuSize is passed to xdsClassName on the item wrapper so themes- * can target `.xds-dropdown-menu-item[data-size="sm"]` etc.- */-const itemSizeStyles = stylex.create({- sm: {- paddingBlock: spacingVars['--spacing-1'],- paddingInline: spacingVars['--spacing-2'],- },- md: {- // Uses base item padding (--spacing-2 all around)- },- lg: {- // Uses base item padding (--spacing-2 all around)- },-});+import type {XDSBaseProps} from '../XDSBaseProps';const styles = stylex.create({- // Dropdown containerdropdown: {boxSizing: 'border-box',+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-0-5'],maxHeight: '300px',overflowY: 'auto','--dropdown-radius': radiusVars['--radius-container'],@@ -77,240 +66,74 @@ const styles = stylex.create({transitionDuration: durationVars['--duration-fast'],transitionTimingFunction: easeVars['--ease-standard'],},-- // Popover container (for anchor positioning)popover: {minWidth: 'anchor-size(width)',},-- // Gap between button and popoverpopoverGap: {marginBlockStart: spacingVars['--spacing-1'],marginBlockEnd: spacingVars['--spacing-1'],},-- // Custom width popoverpopoverCustomWidth: (width: string | number) => ({minWidth: typeof width === 'number' ? `${width}px` : width,}),-- // Section heading label (replaces divider for named sections)- sectionHeading: {- paddingBlock: spacingVars['--spacing-1'],- paddingInline: spacingVars['--spacing-2'],- fontFamily: typographyVars['--font-family-body'],- fontSize: typeScaleVars['--text-supporting-size'],- lineHeight: typeScaleVars['--text-supporting-leading'],- color: colorVars['--color-text-secondary'],- userSelect: 'none',- },-- // Divider- divider: {- marginBlock: spacingVars['--spacing-1'],- },-- // Individual item- item: {- boxSizing: 'border-box',- display: 'flex',- alignItems: 'center',- gap: spacingVars['--spacing-2'],- width: '100%',- padding: spacingVars['--spacing-2'],- borderRadius:- 'max(0px, calc(var(--dropdown-radius) - var(--dropdown-padding)))',- fontFamily: typographyVars['--font-family-body'],- fontSize: typeScaleVars['--text-label-size'],- color: colorVars['--color-text-primary'],- backgroundColor: 'transparent',- border: 'none',- cursor: 'pointer',- textAlign: 'left',- outline: 'none',- },- itemHighlighted: {- backgroundColor: colorVars['--color-overlay-hover'],- },- itemDisabled: {- opacity: 0.5,- cursor: 'not-allowed',- },});// =============================================================================// Types// =============================================================================-/**- * A menu item in the dropdown- */export interface XDSDropdownMenuItemData {- /**- * Display label for the item.- */label: string;-- /**- * Callback when item is selected.- */onClick?: () => void;-- /**- * Whether the item is disabled.- * @default false- */isDisabled?: boolean;-- /**- * Icon to display before the label.- */icon?: XDSIconType;}-/**- * A divider between items- */export interface XDSDropdownMenuDivider {type: 'divider';}-/**- * A section/group of items with optional title- */export interface XDSDropdownMenuSection {type: 'section';title?: string;items: XDSDropdownMenuItemData[];}-/**- * Union of all menu option types- */export type XDSDropdownMenuOption =| XDSDropdownMenuItemData| XDSDropdownMenuDivider| XDSDropdownMenuSection;-// =============================================================================-// Type guards and utilities-// =============================================================================--function isItemData(- option: XDSDropdownMenuOption,-): option is XDSDropdownMenuItemData {- return !('type' in option);-}--function isDivider(- option: XDSDropdownMenuOption,-): option is XDSDropdownMenuDivider {- return 'type' in option && option.type === 'divider';-}--function isSection(- option: XDSDropdownMenuOption,-): option is XDSDropdownMenuSection {- return 'type' in option && option.type === 'section';-}--/**- * Get all selectable items from options (flattening sections)- */-function getSelectableItems(- options: XDSDropdownMenuOption[],-): XDSDropdownMenuItemData[] {- const items: XDSDropdownMenuItemData[] = [];-- for (const option of options) {- if (isItemData(option)) {- items.push(option);- } else if (isSection(option)) {- for (const item of option.items) {- items.push(item);- }- }- }-- return items;-}-// =============================================================================// Props// =============================================================================-/**- * Props for customizing the dropdown button.- * Extends XDSButtonProps but omits onClick since it's managed internally.- *- * Set `isIconOnly` to render as an icon-only button (square, with `label` as aria-label).- */export type XDSDropdownMenuButtonProps = Omit<XDSButtonProps, 'onClick'>;-export interface XDSDropdownMenuProps {- /**- * Props for customizing the trigger button.- * Uses XDSButton internally - supports label, variant, size, icon, etc.- */+interface XDSDropdownMenuBaseProps extends XDSBaseProps {button?: XDSDropdownMenuButtonProps;-- /**- * The items to display in the menu.- * Can be item objects, dividers, or sections.- */- items: XDSDropdownMenuOption[];-- /**- * Whether the menu is open (controlled mode).- * When omitted, the component manages its own open state.- * @default undefined- */isMenuOpen?: boolean;-- /**- * Callback fired when the menu visibility changes (controlled mode).- */onOpenChange?: (isOpen: boolean) => void;-- /**- * Width of the dropdown menu.- * By default matches the button width.- * Can be a number (pixels) or CSS string value.- */menuWidth?: number | string;-- /**- * Callback when the button is clicked.- */onClick?: () => void;-- /**- * Whether to show a chevron indicator on the trigger button.- * Automatically hidden for icon-only buttons (when `button.isIconOnly` is true).- * @default true- */hasChevron?: boolean;-- /**- * Custom render function for items.- * Only called for selectable items (not dividers/sections).- */- children?: (item: XDSDropdownMenuItemData) => ReactNode;-- /**- * Test ID for testing frameworks.- */'data-testid'?: string;}-// =============================================================================-// Default item renderer-// =============================================================================+interface XDSDropdownMenuDataProps extends XDSDropdownMenuBaseProps {+ items: XDSDropdownMenuOption[];+ children?: undefined;+}-function DefaultItem({item}: {item: XDSDropdownMenuItemData}) {- return <XDSDropdownMenuItem icon={item.icon} label={item.label} />;+interface XDSDropdownMenuCompoundProps extends XDSDropdownMenuBaseProps {+ items?: undefined;+ children: ReactNode;}+export type XDSDropdownMenuProps =+ | XDSDropdownMenuDataProps+ | XDSDropdownMenuCompoundProps;+// =============================================================================// XDSDropdownMenu// =============================================================================@@ -318,11 +141,15 @@ function DefaultItem({item}: {item: XDSDropdownMenuItemData}) {/*** A dropdown menu component that displays a list of actionable items.*- * Unlike XDSSelector, this component has no inherent selector state -- * it's purely for displaying a menu of clickable items.+ * Supports two modes:+ * - **Data-driven**: pass `items` for static menus with optional custom rendering+ * - **Compound-component**: pass JSX children for dynamic, stateful, or lazy-loaded menus+ *+ * Both modes share the same DOM-based keyboard navigation via useListFocus.** @example* ```+ * // Data-driven (great for static menus)* <XDSDropdownMenu* button={{ label: 'Actions' }}* items={[@@ -330,56 +157,66 @@ function DefaultItem({item}: {item: XDSDropdownMenuItemData}) {* { label: 'Delete', onClick: () => handleDelete() },* ]}* />+ *+ * // Compound-component (for dynamic/stateful items)+ * <XDSDropdownMenu button={{ label: 'Actions' }}>+ * <XDSDropdownMenuItem icon={PencilIcon} label="Edit" onClick={handleEdit} />+ * <XDSDivider />+ * <Suspense fallback={<XDSSkeleton />}>+ * <LazyLoadedItems />+ * </Suspense>+ * </XDSDropdownMenu>* ```*/export function XDSDropdownMenu({button = {label: 'Menu'},- items,isMenuOpen: controlledIsOpen,onOpenChange,menuWidth,onClick,hasChevron = true,- children,+ className,+ style,+ xstyle,'data-testid': testId,+ ...props}: XDSDropdownMenuProps) {- const menuId = useId();+ const items = ('items' in props ? props.items : undefined) ?? [];+ const children = props.children as ReactNode;- // Derive menu item density from button size+ const menuId = useId();const menuSize = button?.size ?? 'md';-const buttonRef = useRef<HTMLButtonElement>(null);- // Internal state for uncontrolled mode+ // Open stateconst [internalIsOpen, setInternalIsOpen] = useState(false);-- // Determine if controlled or uncontrolledconst isControlled = controlledIsOpen !== undefined;const isOpen = isControlled ? controlledIsOpen : internalIsOpen;- // Highlighted item for keyboard navigation- const [highlightedIndex, setHighlightedIndex] = useState(-1);-- // Flatten items for keyboard navigation- const selectableItems = useMemo(() => getSelectableItems(items), [items]);-- // Layer for dropdown positioning+ // Close menu + return focus to triggerconst handleLayerHide = useCallback(() => {if (isControlled) {onOpenChange?.(false);} else {setInternalIsOpen(false);}- setHighlightedIndex(-1);buttonRef.current?.focus();}, [isControlled, onOpenChange]);+ // Track whether to focus the first item when the menu opens+ const shouldFocusOnOpen = useRef(false);+const handleLayerShow = useCallback(() => {if (isControlled) {onOpenChange?.(true);} else {setInternalIsOpen(true);}+ if (shouldFocusOnOpen.current) {+ shouldFocusOnOpen.current = false;+ // focusFirst is called via openAndFocus below — defer to rAF+ // so the popover content is rendered before we query for items+ }}, [isControlled, onOpenChange]);const popover = useXDSPopover({@@ -390,7 +227,6 @@ export function XDSDropdownMenu({hasAutoFocus: false,});- // Sync layer with controlled stateReact.useEffect(() => {if (isControlled) {if (controlledIsOpen && !popover.isOpen) {@@ -401,6 +237,42 @@ export function XDSDropdownMenu({}}, [controlledIsOpen, isControlled, popover]);+ const closeMenu = useCallback(() => {+ popover.hide();+ }, [popover]);++ // Single keyboard navigation path for both modes+ const {+ listRef,+ handleKeyDown: listNavKeyDown,+ focusFirst,+ } = useListFocus({+ itemSelector: '[role="menuitem"]:not([aria-disabled="true"])',+ wrap: false,+ onEscape: closeMenu,+ });++ // Extend useListFocus with Enter/Space activation+ const listKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ const focused = document.activeElement as HTMLElement | null;+ if (focused?.getAttribute('role') === 'menuitem') {+ focused.click();+ }+ return;+ }+ listNavKeyDown(e);+ },+ [listNavKeyDown],+ );++ const openAndFocus = useCallback(() => {+ popover.show();+ requestAnimationFrame(() => focusFirst());+ }, [popover, focusFirst]);+const handleButtonClick = useCallback(() => {onClick?.();if (isControlled) {@@ -409,246 +281,97 @@ export function XDSDropdownMenu({if (popover.isOpen) {popover.hide();} else {- popover.show();+ openAndFocus();}}- }, [onClick, isControlled, onOpenChange, controlledIsOpen, popover]);-- const closeMenu = useCallback(() => {- popover.hide();- }, [popover]);-- // Generate item ID for accessibility- const getItemId = useCallback(- (index: number) => `${menuId}-item-${index}`,- [menuId],- );-- // Handle item click- const handleItemClick = useCallback(- (item: XDSDropdownMenuItemData) => {- if (item.isDisabled) return;- item.onClick?.();- closeMenu();- },- [closeMenu],- );-- // Handle item mouse enter- const handleItemMouseEnter = useCallback(- (item: XDSDropdownMenuItemData, index: number) => {- if (item.isDisabled) return;- setHighlightedIndex(index);- },- [],- );-- // Keyboard navigation- const handleKeyDown = useCallback(+ }, [+ onClick,+ isControlled,+ onOpenChange,+ controlledIsOpen,+ popover,+ openAndFocus,+ ]);++ const handleButtonKeyDown = useCallback((e: React.KeyboardEvent) => {if (!popover.isOpen) {if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {e.preventDefault();- popover.show();- setHighlightedIndex(0);+ openAndFocus();}- return;}-- switch (e.key) {- case 'ArrowDown':- e.preventDefault();- setHighlightedIndex(prev => {- let next = prev + 1;- // Skip disabled items- while (- next < selectableItems.length &&- selectableItems[next].isDisabled- ) {- next++;- }- return next < selectableItems.length ? next : prev;- });- break;- case 'ArrowUp':- e.preventDefault();- setHighlightedIndex(prev => {- let next = prev - 1;- // Skip disabled items- while (next >= 0 && selectableItems[next].isDisabled) {- next--;- }- return next >= 0 ? next : prev;- });- break;- case 'Home':- e.preventDefault();- {- let index = 0;- while (- index < selectableItems.length &&- selectableItems[index].isDisabled- ) {- index++;- }- setHighlightedIndex(index < selectableItems.length ? index : -1);- }- break;- case 'End':- e.preventDefault();- {- let index = selectableItems.length - 1;- while (index >= 0 && selectableItems[index].isDisabled) {- index--;- }- setHighlightedIndex(index >= 0 ? index : -1);- }- break;- case 'Escape':- e.preventDefault();- closeMenu();- break;- case 'Enter':- case ' ':- e.preventDefault();- if (- highlightedIndex >= 0 &&- highlightedIndex < selectableItems.length- ) {- handleItemClick(selectableItems[highlightedIndex]);- }- break;- }- },- [popover, selectableItems, highlightedIndex, closeMenu, handleItemClick],- );-- // Render an individual item- const renderItem = useCallback(- (item: XDSDropdownMenuItemData, flatIndex: number) => {- const isHighlighted = flatIndex === highlightedIndex;-- return (- <div- key={`${item.label}-${flatIndex}`}- id={getItemId(flatIndex)}- role="menuitem"- tabIndex={-1}- aria-disabled={item.isDisabled}- onClick={() => handleItemClick(item)}- onMouseEnter={() => handleItemMouseEnter(item, flatIndex)}- {...mergeProps(- xdsClassName('dropdown-menu-item', {size: menuSize}),- stylex.props(- styles.item,- itemSizeStyles[menuSize],- isHighlighted && styles.itemHighlighted,- item.isDisabled && styles.itemDisabled,- ),- )}>- {children ? children(item) : <DefaultItem item={item} />}- </div>- );+ // When open, key events go to the menu container via useListFocus},- [- children,- menuSize,- highlightedIndex,- getItemId,- handleItemClick,- handleItemMouseEnter,- ],+ [popover.isOpen, openAndFocus],);- // Render all options (handling sections/dividers)- const renderOptions = useCallback(() => {- let flatIndex = 0;- const elements: ReactNode[] = [];-- for (let i = 0; i < items.length; i++) {- const option = items[i];-- if (isDivider(option)) {- elements.push(- <XDSDivider key={`divider-${i}`} xstyle={styles.divider} />,- );- } else if (isSection(option)) {- const sectionItems: ReactNode[] = [];- for (const item of option.items) {- sectionItems.push(renderItem(item, flatIndex));- flatIndex++;- }- elements.push(- <div key={`section-${i}`} role="group" aria-label={option.title}>- {option.title && (- <div- key={`section-heading-${i}`}- {...stylex.props(styles.sectionHeading)}- aria-hidden="true">- {option.title}- </div>- )}- {sectionItems}- </div>,- );- } else if (isItemData(option)) {- elements.push(renderItem(option, flatIndex));- flatIndex++;- }- }-- return elements;- }, [items, renderItem]);-- // Icon-only: check the explicit isIconOnly prop on the button config.+ // Icon-onlyconst isIconOnly = button.isIconOnly === true;-- // Build endContent: use consumer's endContent if provided,- // otherwise inject chevron (unless icon-only or hasChevron=false)const resolvedEndContent =button.endContent ??(hasChevron && !isIconOnly ? (<XDSIcon icon="chevronDown" size="sm" color="inherit" />) : undefined);- // Determine popover xstyleconst popoverXstyle = menuWidth? styles.popoverCustomWidth(menuWidth): styles.popover;+ // Context for compound items+ const contextValue = useMemo<XDSDropdownMenuContextValue>(+ () => ({closeMenu, menuSize}),+ [closeMenu, menuSize],+ );++ // Resolve menu content: data-driven items become components+ const menuContent =+ props.items !== undefined ? renderXDSDropdownItems(items) : children;+return (<><XDSButton+ {...button}ref={el => {(buttonRef as React.MutableRefObject<HTMLButtonElement | null>).current = el;popover.triggerRef(el);+ // Forward consumer ref from button config+ const consumerRef = button.ref;+ if (typeof consumerRef === 'function') {+ consumerRef(el);+ } else if (consumerRef) {+ (+ consumerRef as React.MutableRefObject<HTMLButtonElement | null>+ ).current = el;+ }}}- {...button}+ tooltip={isOpen ? undefined : button.tooltip}endContent={resolvedEndContent}onClick={handleButtonClick}- onKeyDown={handleKeyDown}+ onKeyDown={handleButtonKeyDown}aria-haspopup="menu"aria-expanded={isOpen}aria-controls={menuId}- aria-activedescendant={- isOpen && highlightedIndex >= 0- ? getItemId(highlightedIndex)- : undefined- }data-testid={testId}/>{popover.render(<div+ ref={listRef as React.RefObject<HTMLDivElement>}id={menuId}role="menu"+ onKeyDown={listKeyDown}{...mergeProps(xdsClassName('dropdown-menu'),- stylex.props(styles.dropdown),+ stylex.props(styles.dropdown, xstyle),+ className,+ style,)}>- {renderOptions()}+ <XDSDropdownMenuContext.Provider value={contextValue}>+ {menuContent}+ </XDSDropdownMenuContext.Provider></div>,{placement: 'below',diff --git a/packages/core/src/DropdownMenu/XDSDropdownMenuContext.tsx b/packages/core/src/DropdownMenu/XDSDropdownMenuContext.tsxnew file mode 100644index 0000000000..e87aa6a696--- /dev/null+++ b/packages/core/src/DropdownMenu/XDSDropdownMenuContext.tsx@@ -0,0 +1,31 @@+'use client';++/**+ * @file XDSDropdownMenuContext.tsx+ * @output Exports context and hook for compound-component menu coordination+ * @position Internal; used by XDSDropdownMenu and XDSDropdownMenuItem+ *+ * Provides menu state (close callback, size) to compound children.+ * Keyboard navigation is handled by useListFocus on the menu container —+ * items don't need to register themselves.+ */++import {createContext, useContext} from 'react';++export interface XDSDropdownMenuContextValue {+ /** Close the menu and return focus to trigger */+ closeMenu: () => void;+ /** Menu size derived from button size */+ menuSize: 'sm' | 'md' | 'lg';+}++export const XDSDropdownMenuContext =+ createContext<XDSDropdownMenuContextValue | null>(null);++/**+ * Hook for compound menu items to access menu state.+ * Returns null outside of a DropdownMenu.+ */+export function useXDSDropdownMenuContext(): XDSDropdownMenuContextValue | null {+ return useContext(XDSDropdownMenuContext);+}diff --git a/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx b/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsxindex b7011cd100..c50759e787 100644--- a/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx+++ b/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx@@ -1,7 +1,12 @@+'use client';+/*** @file XDSDropdownMenuItem.tsx- * @output Exports XDSDropdownMenuItem component for custom item rendering- * @position Sub-component; used by XDSDropdownMenu and consumers for custom items+ * @output Exports XDSDropdownMenuItem component+ * @position Sub-component; used inside XDSDropdownMenu+ *+ * Interactive menu item with role="menuitem". Keyboard navigation+ * is handled by useListFocus on the parent menu container.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/DropdownMenu/DropdownMenu.doc.mjs@@ -10,22 +15,42 @@* - /apps/storybook/stories/DropdownMenu.stories.tsx*/-import type {ReactNode} from 'react';+import {useCallback, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {XDSIcon} from '../Icon';import type {XDSIconType} from '../Icon';import {XDSText} from '../Text';-import {spacingVars} from '../theme/tokens.stylex';+import {+ colorVars,+ spacingVars,+ typographyVars,+ typeScaleVars,+} from '../theme/tokens.stylex';import {xdsClassName, mergeProps} from '../utils';+import {useXDSDropdownMenuContext} from './XDSDropdownMenuContext';const styles = stylex.create({root: {+ boxSizing: 'border-box',display: 'flex',alignItems: 'center',gap: spacingVars['--spacing-2'],- flex: 1,- minWidth: 0,+ width: '100%',+ padding: spacingVars['--spacing-2'],+ borderRadius: `max(0px, calc(var(--dropdown-radius, ${spacingVars['--spacing-2']}) - var(--dropdown-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': colorVars['--color-overlay-hover'],+ },+ border: 'none',+ cursor: 'pointer',+ textAlign: 'left',+ outline: 'none',},content: {display: 'flex',@@ -33,70 +58,53 @@ const styles = stylex.create({flex: 1,minWidth: 0,},+ disabled: {+ opacity: 0.5,+ cursor: 'not-allowed',+ },+});++const itemSizeStyles = stylex.create({+ sm: {+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-2'],+ },+ md: {},+ lg: {},});export interface XDSDropdownMenuItemProps {- /**- * Icon to display before the label.- */+ /** Icon to display before the label. */icon?: XDSIconType;-- /**- * Primary label text.- */+ /** Primary label text. */label: ReactNode;-- /**- * Secondary description text displayed below the label.- */+ /** Secondary description text displayed below the label. */description?: ReactNode;-- /**- * Additional content to render after the label/description.- */+ /** Callback when the item is selected. */+ onClick?: () => void;+ /** Whether the item is disabled. @default false */+ isDisabled?: boolean;+ /** Additional content to render after the label/description. */children?: ReactNode;-- /**- * StyleX styles created via `stylex.create()`. Merged with the component's- * base styles inside a single `stylex.props()` call for optimal deduplication.- *- * @example- * ```- * const overrides = stylex.create({ root: { marginBottom: 8 } });- * <Component xstyle={overrides.root} />- * ```- */+ /** StyleX styles merged with the component's base styles. */xstyle?: StyleXStyles;- /**- * CSS class name(s) appended to the root element.- * If you're using StyleX, prefer `xstyle` for optimal style deduplication.- */+ /** CSS class name(s) appended to the root element. */className?: string;- /**- * Inline styles to apply to the root element. Spread after StyleX- * inline styles, so these values take priority.- */+ /** Inline styles applied to the root element. */style?: React.CSSProperties;}/**- * A helper component for rendering custom dropdown menu items with consistent styling.+ * An interactive dropdown menu item with icon, label, and optional description.*- * Use this inside the `children` render prop of XDSDropdownMenu to create- * custom item layouts while maintaining design system consistency.+ * Must be used inside XDSDropdownMenu. Keyboard navigation is provided+ * automatically by the parent via useListFocus.** @example* ```- * <XDSDropdownMenu- * button={{ label: 'Actions' }}- * items={actions}>- * {item => (- * <XDSDropdownMenuItem- * icon={item.icon}- * label={item.label}- * description={item.description}- * />- * )}+ * <XDSDropdownMenu button={{ label: 'Actions' }}>+ * <XDSDropdownMenuItem icon={PencilIcon} label="Edit" onClick={handleEdit} />+ * <XDSDropdownMenuItem label="Delete" onClick={handleDelete} isDisabled />* </XDSDropdownMenu>* ```*/@@ -104,16 +112,36 @@ export function XDSDropdownMenuItem({icon,label,description,+ onClick,+ isDisabled = false,children,xstyle,className,style,}: XDSDropdownMenuItemProps) {+ const ctx = useXDSDropdownMenuContext();+ const menuSize = ctx?.menuSize ?? 'md';++ const handleClick = useCallback(() => {+ if (isDisabled || !onClick) return;+ onClick();+ ctx?.closeMenu();+ }, [isDisabled, onClick, ctx]);+return (- <span+ <div+ role="menuitem"+ tabIndex={isDisabled ? undefined : -1}+ aria-disabled={isDisabled || undefined}+ onClick={handleClick}{...mergeProps(- xdsClassName('dropdown-menu-item'),- stylex.props(styles.root, xstyle),+ xdsClassName('dropdown-menu-item', {size: menuSize}),+ stylex.props(+ styles.root,+ itemSizeStyles[menuSize],+ isDisabled && styles.disabled,+ xstyle,+ ),className,style,)}>@@ -133,7 +161,7 @@ export function XDSDropdownMenuItem({)}</span>{children}- </span>+ </div>);}diff --git a/packages/core/src/DropdownMenu/renderXDSDropdownItems.tsx b/packages/core/src/DropdownMenu/renderXDSDropdownItems.tsxnew file mode 100644index 0000000000..a7c8aadc6a--- /dev/null+++ b/packages/core/src/DropdownMenu/renderXDSDropdownItems.tsx@@ -0,0 +1,86 @@+/**+ * @file renderXDSDropdownItems.tsx+ * @output Converts data-driven menu items into XDSDropdownMenuItem components+ * @position Utility; used by XDSDropdownMenu to unify data-driven and compound paths+ */++import {type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSDivider} from '../Divider';+import {XDSDropdownMenuItem} from './XDSDropdownMenuItem';+import {+ spacingVars,+ typographyVars,+ typeScaleVars,+ colorVars,+} from '../theme/tokens.stylex';+import type {+ XDSDropdownMenuOption,+ XDSDropdownMenuItemData,+} from './XDSDropdownMenu';++const styles = stylex.create({+ sectionHeading: {+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-2'],+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleVars['--text-supporting-size'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ color: colorVars['--color-text-secondary'],+ userSelect: 'none',+ },+ divider: {+ marginBlock: spacingVars['--spacing-1'],+ },+});++/**+ * Converts data-driven items into XDSDropdownMenuItem components,+ * so both modes share the same rendering and keyboard navigation path.+ */+export function renderXDSDropdownItems(+ items: XDSDropdownMenuOption[],+): 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(+ <XDSDivider key={`divider-${i}`} xstyle={styles.divider} />,+ );+ } else if ('type' in option && option.type === 'section') {+ elements.push(+ <div key={`section-${i}`} role="group" aria-label={option.title}>+ {option.title && (+ <div {...stylex.props(styles.sectionHeading)} aria-hidden="true">+ {option.title}+ </div>+ )}+ {option.items.map((item, j) => (+ <XDSDropdownMenuItem+ key={`${item.label}-${j}`}+ icon={item.icon}+ label={item.label}+ onClick={item.onClick}+ isDisabled={item.isDisabled}+ />+ ))}+ </div>,+ );+ } else if (!('type' in option)) {+ elements.push(+ <XDSDropdownMenuItem+ key={`${option.label}-${i}`}+ icon={option.icon}+ label={option.label}+ onClick={option.onClick}+ isDisabled={option.isDisabled}+ />,+ );+ }+ }++ return elements;+}diff --git a/packages/core/src/MoreMenu/XDSMoreMenu.test.tsx b/packages/core/src/MoreMenu/XDSMoreMenu.test.tsxindex c206b7e454..9c434706a6 100644--- a/packages/core/src/MoreMenu/XDSMoreMenu.test.tsx+++ b/packages/core/src/MoreMenu/XDSMoreMenu.test.tsx@@ -101,8 +101,8 @@ describe('XDSMoreMenu', () => {it('supports disabled state', () => {render(<XDSMoreMenu items={defaultItems} isDisabled />);const button = screen.getByRole('button', {name: 'More options'});- // MoreMenu uses tooltip when closed, so Button uses aria-disabled- // instead of native disabled to keep the button focusable for tooltip access+ // Button uses aria-disabled (not native disabled) to keep+ // the button focusable for tooltip accessexpect(button).toHaveAttribute('aria-disabled', 'true');});diff --git a/packages/core/src/MoreMenu/XDSMoreMenu.tsx b/packages/core/src/MoreMenu/XDSMoreMenu.tsxindex 4dc42bc939..3a7cdcc0f7 100644--- a/packages/core/src/MoreMenu/XDSMoreMenu.tsx+++ b/packages/core/src/MoreMenu/XDSMoreMenu.tsx@@ -2,12 +2,12 @@/*** @file XDSMoreMenu.tsx- * @input Uses React, StyleX, useXDSPopover, XDSButton, getIcon, XDSDropdownMenuItem, XDSDivider+ * @input Uses XDSDropdownMenu, getIcon* @output Exports XDSMoreMenu component and XDSMoreMenuProps type* @position Core implementation; consumed by index.ts*- * Overflow menu with a three-dot icon trigger. A convenience wrapper- * that composes XDSButton (icon-only) + useXDSPopover for the dropdown.+ * Overflow menu with a three-dot icon trigger. A thin wrapper around+ * XDSDropdownMenu with icon-only button defaults.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/MoreMenu/README.md@@ -16,166 +16,19 @@* - /apps/storybook/stories/MoreMenu.stories.tsx*/-import {- useCallback,- useId,- useMemo,- useRef,- useState,- type ReactNode,-} from 'react';-import * as stylex from '@stylexjs/stylex';-import {useXDSPopover} from '../Popover/useXDSPopover';-import {XDSButton, type XDSButtonVariant, type XDSButtonSize} from '../Button';+import {type ReactNode} from 'react';import {getIcon} from '../Icon/globalIconRegistry';-import {XDSDropdownMenuItem} from '../DropdownMenu/XDSDropdownMenuItem';-import {XDSDivider} from '../Divider';-import type {- XDSDropdownMenuOption,- XDSDropdownMenuItemData,- XDSDropdownMenuDivider,- XDSDropdownMenuSection,-} from '../DropdownMenu';-import {- colorVars,- spacingVars,- radiusVars,- durationVars,- easeVars,- typographyVars,- typeScaleVars,-} from '../theme/tokens.stylex';-import {xdsClassName, mergeProps} from '../utils';--// =============================================================================-// Styles-// =============================================================================--/**- * Size-aware item padding.- * sm triggers → tighter vertical padding (4px block, 8px inline)- * md/lg triggers → standard padding (8px all around, inherited from base item style)- */-const itemSizeStyles = stylex.create({- sm: {- paddingBlock: spacingVars['--spacing-1'],- paddingInline: spacingVars['--spacing-2'],- },- md: {- // Uses base item padding (--spacing-2 all around)- },- lg: {- // Uses base item padding (--spacing-2 all around)- },-});--const styles = stylex.create({- dropdown: {- boxSizing: 'border-box',- maxHeight: '300px',- overflowY: 'auto',- padding: spacingVars['--spacing-1'],- opacity: 1,- transitionProperty: 'opacity',- transitionDuration: durationVars['--duration-fast'],- transitionTimingFunction: easeVars['--ease-standard'],- },- popover: {- minWidth: '160px',- },- popoverGap: {- marginBlockStart: spacingVars['--spacing-1'],- marginBlockEnd: spacingVars['--spacing-1'],- },- sectionHeading: {- paddingBlock: spacingVars['--spacing-1'],- paddingInline: spacingVars['--spacing-2'],- fontFamily: typographyVars['--font-family-body'],- fontSize: typeScaleVars['--text-supporting-size'],- lineHeight: typeScaleVars['--text-supporting-leading'],- color: colorVars['--color-text-secondary'],- userSelect: 'none',- },- divider: {- marginBlock: spacingVars['--spacing-1'],- },- item: {- boxSizing: 'border-box',- display: 'flex',- alignItems: 'center',- gap: spacingVars['--spacing-2'],- width: '100%',- padding: spacingVars['--spacing-2'],- borderRadius: radiusVars['--radius-element'],- fontFamily: typographyVars['--font-family-body'],- fontSize: typeScaleVars['--text-label-size'],- color: colorVars['--color-text-primary'],- backgroundColor: 'transparent',- border: 'none',- cursor: 'pointer',- textAlign: 'left',- outline: 'none',- },- itemHighlighted: {- backgroundColor: colorVars['--color-overlay-hover'],- },- itemDisabled: {- opacity: 0.5,- cursor: 'not-allowed',- },-});--// =============================================================================-// Type guards and utilities-// =============================================================================--function isItemData(- option: XDSDropdownMenuOption,-): option is XDSDropdownMenuItemData {- return !('type' in option);-}--function isDivider(- option: XDSDropdownMenuOption,-): option is XDSDropdownMenuDivider {- return 'type' in option && option.type === 'divider';-}--function isSection(- option: XDSDropdownMenuOption,-): option is XDSDropdownMenuSection {- return 'type' in option && option.type === 'section';-}--function getSelectableItems(- options: XDSDropdownMenuOption[],-): XDSDropdownMenuItemData[] {- const items: XDSDropdownMenuItemData[] = [];- for (const option of options) {- if (isItemData(option)) {- items.push(option);- } else if (isSection(option)) {- for (const item of option.items) {- items.push(item);- }- }- }- return items;-}--// =============================================================================-// Props-// =============================================================================+import {XDSDropdownMenu} from '../DropdownMenu/XDSDropdownMenu';+import type {XDSDropdownMenuOption} from '../DropdownMenu';+import type {XDSButtonVariant, XDSButtonSize} from '../Button';export interface XDSMoreMenuProps {- /** Ref forwarded to the root element */+ /** Ref forwarded to the trigger button */ref?: React.Ref<HTMLButtonElement>;+/**- * Menu items — data array of actions, dividers, and sections.+ * Menu items \u2014 data array of actions, dividers, and sections.* Same type as XDSDropdownMenu's `items` prop.- *- * For advanced menu content that can't be expressed as data,- * compose XDSButton + useXDSPopover + XDSDropdownMenuItem directly.*/items: XDSDropdownMenuOption[];@@ -188,21 +41,18 @@ export interface XDSMoreMenuProps {/*** Visual style variant of the trigger button.- * Matches XDSButton variant values.* @default 'ghost'*/variant?: XDSButtonVariant;/*** Size of the trigger button.- * Matches XDSButton size values.* @default 'md'*/size?: XDSButtonSize;/*** Override the default three-dot icon.- * Accepts any ReactNode (same as XDSButton's `icon` prop).* @default Three horizontal dots from the icon registry ('moreHorizontal')*/icon?: ReactNode;@@ -213,41 +63,14 @@ export interface XDSMoreMenuProps {*/isDisabled?: boolean;- /**- * Custom render function for items.- * Passed through to render custom item content.- * Only called for selectable items (not dividers/sections).- */- children?: (item: XDSDropdownMenuItemData) => ReactNode;-- /**- * Test ID for testing frameworks.- */+ /** Test ID for testing frameworks. */'data-testid'?: string;}-// =============================================================================-// Default item renderer-// =============================================================================--function DefaultItem({item}: {item: XDSDropdownMenuItemData}) {- return <XDSDropdownMenuItem icon={item.icon} label={item.label} />;-}--// =============================================================================-// XDSMoreMenu-// =============================================================================-/*** Overflow menu with a three-dot icon trigger.*- * A convenience wrapper that composes an icon-only XDSButton with a- * dropdown menu. Eliminates the boilerplate of wiring up state management,- * positioning, and accessibility attributes for the common "more actions"- * pattern.- *- * For full control over trigger rendering or menu content, compose- * XDSButton + useXDSPopover + XDSDropdownMenuItem directly.+ * A convenience wrapper around XDSDropdownMenu with icon-only button defaults.** @example* ```@@ -266,261 +89,28 @@ export function XDSMoreMenu({size = 'md',icon,isDisabled = false,- children,'data-testid': testId,ref,}: XDSMoreMenuProps) {const moreIcon = getIcon('moreHorizontal');- const buttonRef = useRef<HTMLButtonElement | null>(null);- const menuId = useId();- const [highlightedIndex, setHighlightedIndex] = useState(-1);-- const selectableItems = useMemo(() => getSelectableItems(items), [items]);-- const handleLayerHide = useCallback(() => {- setHighlightedIndex(-1);- buttonRef.current?.focus();- }, []);-- const popover = useXDSPopover({- onHide: handleLayerHide,- hasLightDismiss: true,- hasCloseButton: false,- hasAutoFocus: false,- });-- const handleButtonClick = useCallback(() => {- if (popover.isOpen) {- popover.hide();- } else {- popover.show();- }- }, [popover]);-- const closeMenu = useCallback(() => {- popover.hide();- }, [popover]);-- const getItemId = useCallback(- (index: number) => `${menuId}-item-${index}`,- [menuId],- );-- const handleItemClick = useCallback(- (item: XDSDropdownMenuItemData) => {- if (item.isDisabled) return;- item.onClick?.();- closeMenu();- },- [closeMenu],- );-- const handleItemMouseEnter = useCallback(- (item: XDSDropdownMenuItemData, index: number) => {- if (item.isDisabled) return;- setHighlightedIndex(index);- },- [],- );-- const handleKeyDown = useCallback(- (e: React.KeyboardEvent) => {- if (!popover.isOpen) {- if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- popover.show();- setHighlightedIndex(0);- }- return;- }-- switch (e.key) {- case 'ArrowDown':- e.preventDefault();- setHighlightedIndex(prev => {- let next = prev + 1;- while (- next < selectableItems.length &&- selectableItems[next].isDisabled- ) {- next++;- }- return next < selectableItems.length ? next : prev;- });- break;- case 'ArrowUp':- e.preventDefault();- setHighlightedIndex(prev => {- let next = prev - 1;- while (next >= 0 && selectableItems[next].isDisabled) {- next--;- }- return next >= 0 ? next : prev;- });- break;- case 'Home':- e.preventDefault();- {- let index = 0;- while (- index < selectableItems.length &&- selectableItems[index].isDisabled- ) {- index++;- }- setHighlightedIndex(index < selectableItems.length ? index : -1);- }- break;- case 'End':- e.preventDefault();- {- let index = selectableItems.length - 1;- while (index >= 0 && selectableItems[index].isDisabled) {- index--;- }- setHighlightedIndex(index >= 0 ? index : -1);- }- break;- case 'Escape':- e.preventDefault();- closeMenu();- break;- case 'Enter':- case ' ':- e.preventDefault();- if (- highlightedIndex >= 0 &&- highlightedIndex < selectableItems.length- ) {- handleItemClick(selectableItems[highlightedIndex]);- }- break;- }- },- [popover, selectableItems, highlightedIndex, closeMenu, handleItemClick],- );-- const renderItem = useCallback(- (item: XDSDropdownMenuItemData, flatIndex: number) => {- const isHighlighted = flatIndex === highlightedIndex;-- return (- <div- key={`${item.label}-${flatIndex}`}- id={getItemId(flatIndex)}- role="menuitem"- tabIndex={-1}- aria-disabled={item.isDisabled}- onClick={() => handleItemClick(item)}- onMouseEnter={() => handleItemMouseEnter(item, flatIndex)}- {...stylex.props(- styles.item,- itemSizeStyles[size],- isHighlighted && styles.itemHighlighted,- item.isDisabled && styles.itemDisabled,- )}>- {children ? children(item) : <DefaultItem item={item} />}- </div>- );- },- [- children,- size,- highlightedIndex,- getItemId,- handleItemClick,- handleItemMouseEnter,- ],- );-- const renderOptions = useCallback(() => {- let flatIndex = 0;- const elements: ReactNode[] = [];-- for (let i = 0; i < items.length; i++) {- const option = items[i];-- if (isDivider(option)) {- elements.push(- <XDSDivider key={`divider-${i}`} xstyle={styles.divider} />,- );- } else if (isSection(option)) {- const sectionItems: ReactNode[] = [];- for (const item of option.items) {- sectionItems.push(renderItem(item, flatIndex));- flatIndex++;- }- elements.push(- <div key={`section-${i}`} role="group" aria-label={option.title}>- {option.title && (- <div- key={`section-heading-${i}`}- {...stylex.props(styles.sectionHeading)}- aria-hidden="true">- {option.title}- </div>- )}- {sectionItems}- </div>,- );- } else if (isItemData(option)) {- elements.push(renderItem(option, flatIndex));- flatIndex++;- }- }-- return elements;- }, [items, renderItem]);return (- <>- <XDSButton- ref={el => {- buttonRef.current = el;- popover.triggerRef(el);- if (typeof ref === 'function') {- ref(el);- } else if (ref) {- (ref as React.MutableRefObject<HTMLButtonElement | null>).current =- el;- }- }}- label={label}- icon={icon ?? moreIcon}- variant={variant}- size={size}- isDisabled={isDisabled}- tooltip={popover.isOpen ? undefined : label}- onClick={handleButtonClick}- onKeyDown={handleKeyDown}- aria-haspopup="menu"- aria-expanded={popover.isOpen}- aria-controls={menuId}- aria-activedescendant={- popover.isOpen && highlightedIndex >= 0- ? getItemId(highlightedIndex)- : undefined- }- data-testid={testId}- isIconOnly- />- {popover.render(- <div- id={menuId}- role="menu"- {...mergeProps(- xdsClassName('more-menu'),- stylex.props(styles.dropdown),- )}>- {renderOptions()}- </div>,- {- placement: 'below',- alignment: 'end',- xstyle: [styles.popover, styles.popoverGap],- },- )}- </>+ <XDSDropdownMenu+ className="xds-more-menu"+ button={{+ label,+ icon: icon ?? moreIcon,+ variant,+ size,+ isDisabled,+ tooltip: label,+ isIconOnly: true,+ ref,+ }}+ items={items}+ hasChevron={false}+ data-testid={testId}+ />);}