dropdownMenuItem.tsx 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import {Fragment, useEffect, useRef, useState} from 'react';
  2. import {useHover, useKeyboard} from '@react-aria/interactions';
  3. import {useMenuItem} from '@react-aria/menu';
  4. import {mergeProps} from '@react-aria/utils';
  5. import {TreeState} from '@react-stately/tree';
  6. import {Node} from '@react-types/shared';
  7. import {LocationDescriptor} from 'history';
  8. import Link from 'sentry/components/links/link';
  9. import MenuListItem, {
  10. InnerWrap as MenuListItemInnerWrap,
  11. MenuListItemProps,
  12. } from 'sentry/components/menuListItem';
  13. import {IconChevron} from 'sentry/icons';
  14. import usePrevious from 'sentry/utils/usePrevious';
  15. export type MenuItemProps = MenuListItemProps & {
  16. /**
  17. * Item key. Must be unique across the entire menu, including sub-menus.
  18. */
  19. key: string;
  20. /**
  21. * Sub-items that are nested inside this item. By default, sub-items are
  22. * rendered collectively as menu sections inside the current menu. If
  23. * `isSubmenu` is true, then they will be rendered together in a sub-menu.
  24. */
  25. children?: MenuItemProps[];
  26. /**
  27. * Hide item from the dropdown menu. Note: this will also remove the item
  28. * from the selection manager.
  29. */
  30. hidden?: boolean;
  31. /*
  32. * Whether this menu item is a trigger for a nested sub-menu. Only works
  33. * when `children` is also defined.
  34. */
  35. isSubmenu?: boolean;
  36. /**
  37. * Function to call when user selects/clicks/taps on the menu item. The
  38. * item's key is passed as an argument.
  39. */
  40. onAction?: (key: MenuItemProps['key']) => void;
  41. /**
  42. * Whether to show a line divider below this menu item
  43. */
  44. showDividers?: boolean;
  45. /**
  46. * Passed as the `menuTitle` prop onto the associated sub-menu (applicable
  47. * if `children` is defined and `isSubmenu` is true)
  48. */
  49. submenuTitle?: string;
  50. /**
  51. * Destination if this menu item is a link. See also: `isExternalLink`.
  52. */
  53. to?: LocationDescriptor;
  54. };
  55. type Props = {
  56. /**
  57. * Whether to close the menu when an item has been clicked/selected
  58. */
  59. closeOnSelect: boolean;
  60. /**
  61. * Whether this is the last node in the collection
  62. */
  63. isLastNode: boolean;
  64. /**
  65. * Node representation (from @react-aria) of the item
  66. */
  67. node: Node<MenuItemProps>;
  68. /**
  69. * Used to close the menu when needed (e.g. when the item is
  70. * clicked/selected)
  71. */
  72. onClose: () => void;
  73. /**
  74. * Tree state (from @react-stately) inherited from parent menu
  75. */
  76. state: TreeState<MenuItemProps>;
  77. /**
  78. * Whether this is a trigger button (displayed as a normal menu item) for a
  79. * submenu
  80. */
  81. isSubmenuTrigger?: boolean;
  82. /**
  83. * Tag name for item wrapper
  84. */
  85. renderAs?: React.ElementType;
  86. /**
  87. * If isSubmenuTrigger is true, then replace the internal ref object with
  88. * this ref
  89. */
  90. submenuTriggerRef?: React.RefObject<HTMLLIElement>;
  91. };
  92. /**
  93. * A menu item with a label, optional details, leading and trailing elements.
  94. * Can also be used as a trigger button for a submenu. See:
  95. * https://react-spectrum.adobe.com/react-aria/useMenu.html
  96. */
  97. const MenuItem = ({
  98. node,
  99. isLastNode,
  100. state,
  101. onClose,
  102. closeOnSelect,
  103. isSubmenuTrigger = false,
  104. submenuTriggerRef,
  105. renderAs = 'li' as React.ElementType,
  106. ...submenuTriggerProps
  107. }: Props) => {
  108. const ourRef = useRef(null);
  109. const isDisabled = state.disabledKeys.has(node.key);
  110. const isFocused = state.selectionManager.focusedKey === node.key;
  111. const {key, onAction, to, label, showDividers, ...itemProps} = node.value;
  112. const {size} = node.props;
  113. const ref = submenuTriggerRef ?? ourRef;
  114. const actionHandler = () => {
  115. if (to) {
  116. return;
  117. }
  118. if (isSubmenuTrigger) {
  119. state.selectionManager.select(node.key);
  120. return;
  121. }
  122. onAction?.(key);
  123. };
  124. // Open submenu on hover
  125. const [isHovering, setIsHovering] = useState(false);
  126. const {hoverProps} = useHover({onHoverChange: setIsHovering});
  127. const prevIsHovering = usePrevious(isHovering);
  128. const prevIsFocused = usePrevious(isFocused);
  129. useEffect(() => {
  130. if (isHovering === prevIsHovering && isFocused === prevIsFocused) {
  131. return;
  132. }
  133. if (isHovering && isFocused) {
  134. if (isSubmenuTrigger) {
  135. state.selectionManager.select(node.key);
  136. return;
  137. }
  138. state.selectionManager.clearSelection();
  139. }
  140. }, [
  141. isHovering,
  142. isFocused,
  143. prevIsHovering,
  144. prevIsFocused,
  145. isSubmenuTrigger,
  146. node.key,
  147. state.selectionManager,
  148. ]);
  149. // Open submenu on arrow right key press
  150. const {keyboardProps} = useKeyboard({
  151. onKeyDown: e => {
  152. if (e.key === 'Enter' && to) {
  153. const mouseEvent = new MouseEvent('click', {
  154. ctrlKey: e.ctrlKey,
  155. metaKey: e.metaKey,
  156. });
  157. ref.current?.querySelector(`${MenuListItemInnerWrap}`)?.dispatchEvent(mouseEvent);
  158. onClose();
  159. return;
  160. }
  161. if (e.key === 'ArrowRight' && isSubmenuTrigger) {
  162. state.selectionManager.select(node.key);
  163. return;
  164. }
  165. e.continuePropagation();
  166. },
  167. });
  168. // Manage interactive events & create aria attributes
  169. const {menuItemProps, labelProps, descriptionProps} = useMenuItem(
  170. {
  171. key: node.key,
  172. onAction: actionHandler,
  173. closeOnSelect: to ? false : closeOnSelect,
  174. onClose,
  175. isDisabled,
  176. },
  177. state,
  178. ref
  179. );
  180. // Merged menu item props, class names are combined, event handlers chained,
  181. // etc. See: https://react-spectrum.adobe.com/react-aria/mergeProps.html
  182. const props = mergeProps(submenuTriggerProps, menuItemProps, hoverProps, keyboardProps);
  183. const itemLabel = node.rendered ?? label;
  184. const showDivider = showDividers && !isLastNode;
  185. const innerWrapProps = {as: to ? Link : 'div', to};
  186. return (
  187. <MenuListItem
  188. ref={ref}
  189. as={renderAs}
  190. data-test-id={key}
  191. label={itemLabel}
  192. disabled={isDisabled}
  193. isFocused={isFocused}
  194. showDivider={showDivider}
  195. innerWrapProps={innerWrapProps}
  196. labelProps={labelProps}
  197. detailsProps={descriptionProps}
  198. size={size}
  199. {...props}
  200. {...itemProps}
  201. {...(isSubmenuTrigger && {
  202. role: 'menuitemradio',
  203. trailingItems: (
  204. <Fragment>
  205. {itemProps.trailingItems}
  206. <IconChevron size="xs" direction="right" aria-hidden="true" />
  207. </Fragment>
  208. ),
  209. })}
  210. />
  211. );
  212. };
  213. export default MenuItem;