item.tsx 6.1 KB

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