import { cloneElement, isValidElement, type CSSProperties, type ReactElement, type ReactNode } from 'react'; import { Menu as MuiMenu, MenuItem as MuiMenuItem, Divider, ListSubheader, ListItemIcon, ListItemText, Typography, type MenuProps } from '@mui/material'; import clsx from 'clsx'; import './rds-menu.scss' function getColor(color: string): string { switch (color) { case 'primary': return 'var(--rds-primary-main)'; case 'success': return 'var(--rds-success-main)'; case 'danger': return 'var(--rds-error-main)'; case 'info': return 'var(--rds-info-main)'; case 'warning': return 'var(--rds-warning-main)'; default: return color || ''; } } /** Map menu size → RdsAvatar size so avatars stay compact alongside menu icons. */ const menuToAvatarSize = { small: 'smallest', medium: 'smallest', large: 'small', } as const; type MenuSize = keyof typeof menuToAvatarSize; type AvatarSize = (typeof menuToAvatarSize)[MenuSize]; function isRdsAvatarElement(element: ReactElement): boolean { const type = element.type as { displayName?: string; name?: string }; return type?.displayName === 'RdsAvatar' || type?.name === 'RdsAvatar'; } function renderMenuIcon( icon: ReactNode, menuSize: MenuSize | undefined, itemColor?: string, ): ReactNode { if (!isValidElement(icon) || (typeof icon.type !== 'function' && typeof icon.type !== 'object')) { return icon; } const existingProps = (icon as ReactElement<{ style?: CSSProperties; size?: AvatarSize }>).props; const avatarSize = menuSize ? menuToAvatarSize[menuSize] : undefined; return cloneElement(icon as ReactElement<{ style?: CSSProperties; size?: AvatarSize; displayStyle?: string; showName?: boolean; showDesignation?: boolean }>, { ...existingProps, ...(isRdsAvatarElement(icon) ? { ...(avatarSize ? { size: avatarSize } : {}), showName: false, showDesignation: false, // Compact avatar chrome (no with-name wrapper) for menu list rows displayStyle: 'icon-only' as 'with-name', } : {}), style: { ...(existingProps?.style ?? {}), ...(itemColor ? { color: getColor(itemColor), fill: getColor(itemColor), } : {}), }, }); } export interface RdsMenuItem { id: string | number; label?: string; icon?: ReactNode; onClick?: () => void; disabled?: boolean; divider?: boolean; shortcut?: string; header?: string; color?: 'primary' | 'success' | 'danger' | 'info' | 'warning' | string; } export interface RdsMenuProps extends Omit { items: RdsMenuItem[]; size?: 'small' | 'medium' | 'large'; children?: ReactNode; } const RdsMenu = ({ items, size, children, ...props }: RdsMenuProps) => { const dense = size === 'small'; const menuClassName = clsx('rds-menu', size && `rds-menu--${size}`, props.className); const menuListClassName = 'rds-menu__list'; return ( {children ? children : items.map((item) => { if (item.header) { return ( {item.header} ); } if (item.divider) { return ; } return ( {item.icon && ( {renderMenuIcon(item.icon, size, item.color)} )} ); })} ); }; RdsMenu.displayName = 'RdsMenu'; export default RdsMenu;