dropdownMenuItem.tsx 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 ref = submenuTriggerRef ?? ourRef;
  113. const actionHandler = () => {
  114. if (to) {
  115. return;
  116. }
  117. if (isSubmenuTrigger) {
  118. state.selectionManager.select(node.key);
  119. return;
  120. }
  121. onAction?.(key);
  122. };
  123. // Open submenu on hover
  124. const [isHovering, setIsHovering] = useState(false);
  125. const {hoverProps} = useHover({onHoverChange: setIsHovering});
  126. const prevIsHovering = usePrevious(isHovering);
  127. const prevIsFocused = usePrevious(isFocused);
  128. useEffect(() => {
  129. if (isHovering === prevIsHovering && isFocused === prevIsFocused) {
  130. return;
  131. }
  132. if (isHovering && isFocused) {
  133. if (isSubmenuTrigger) {
  134. state.selectionManager.select(node.key);
  135. return;
  136. }
  137. state.selectionManager.clearSelection();
  138. }
  139. }, [
  140. isHovering,
  141. isFocused,
  142. prevIsHovering,
  143. prevIsFocused,
  144. isSubmenuTrigger,
  145. node.key,
  146. state.selectionManager,
  147. ]);
  148. // Open submenu on arrow right key press
  149. const {keyboardProps} = useKeyboard({
  150. onKeyDown: e => {
  151. if (e.key === 'Enter' && to) {
  152. const mouseEvent = new MouseEvent('click', {
  153. ctrlKey: e.ctrlKey,
  154. metaKey: e.metaKey,
  155. });
  156. ref.current?.querySelector(`${MenuListItemInnerWrap}`)?.dispatchEvent(mouseEvent);
  157. onClose();
  158. return;
  159. }
  160. if (e.key === 'ArrowRight' && isSubmenuTrigger) {
  161. state.selectionManager.select(node.key);
  162. return;
  163. }
  164. e.continuePropagation();
  165. },
  166. });
  167. // Manage interactive events & create aria attributes
  168. const {menuItemProps, labelProps, descriptionProps} = useMenuItem(
  169. {
  170. key: node.key,
  171. onAction: actionHandler,
  172. closeOnSelect: to ? false : closeOnSelect,
  173. onClose,
  174. isDisabled,
  175. },
  176. state,
  177. ref
  178. );
  179. // Merged menu item props, class names are combined, event handlers chained,
  180. // etc. See: https://react-spectrum.adobe.com/react-aria/mergeProps.html
  181. const props = mergeProps(submenuTriggerProps, menuItemProps, hoverProps, keyboardProps);
  182. const itemLabel = node.rendered ?? label;
  183. const showDivider = showDividers && !isLastNode;
  184. const innerWrapProps = {as: to ? Link : 'div', to};
  185. return (
  186. <MenuListItem
  187. ref={ref}
  188. as={renderAs}
  189. data-test-id={key}
  190. label={itemLabel}
  191. isDisabled={isDisabled}
  192. isFocused={isFocused}
  193. showDivider={showDivider}
  194. innerWrapProps={innerWrapProps}
  195. labelProps={labelProps}
  196. detailsProps={descriptionProps}
  197. {...props}
  198. {...itemProps}
  199. {...(isSubmenuTrigger && {
  200. role: 'menuitemradio',
  201. trailingItems: (
  202. <Fragment>
  203. {itemProps.trailingItems}
  204. <IconChevron size="xs" direction="right" aria-hidden="true" />
  205. </Fragment>
  206. ),
  207. })}
  208. />
  209. );
  210. };
  211. export default MenuItem;