dropdownMenuV2.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import {Fragment, useEffect, useMemo, useRef, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import {FocusScope} from '@react-aria/focus';
  4. import {useKeyboard} from '@react-aria/interactions';
  5. import {AriaMenuOptions, useMenu} from '@react-aria/menu';
  6. import {
  7. AriaPositionProps,
  8. OverlayProps,
  9. PositionAria,
  10. useOverlay,
  11. useOverlayPosition,
  12. } from '@react-aria/overlays';
  13. import {useSeparator} from '@react-aria/separator';
  14. import {mergeProps} from '@react-aria/utils';
  15. import {useTreeState} from '@react-stately/tree';
  16. import {Node} from '@react-types/shared';
  17. import MenuControl from 'sentry/components/dropdownMenuControl';
  18. import MenuItem, {MenuItemProps} from 'sentry/components/dropdownMenuItem';
  19. import MenuSection from 'sentry/components/dropdownMenuSection';
  20. import space from 'sentry/styles/space';
  21. type Props = {
  22. /**
  23. * If this is a submenu, it will in some cases need to close the root menu
  24. * (e.g. when a submenu item is clicked).
  25. */
  26. closeRootMenu: () => void;
  27. /**
  28. * Whether this is a submenu
  29. */
  30. isSubmenu: boolean;
  31. /**
  32. * Ref object to the trigger element, needed for useOverlayPosition()
  33. */
  34. triggerRef: React.RefObject<HTMLButtonElement>;
  35. /**
  36. * If this is a submenu, it will in some cases need to close itself (e.g.
  37. * when the user presses the arrow left key)
  38. */
  39. closeCurrentSubmenu?: () => void;
  40. /**
  41. * Whether the menu should close when an item has been clicked/selected
  42. */
  43. closeOnSelect?: boolean;
  44. /*
  45. * Title to display on top of the menu
  46. */
  47. menuTitle?: string;
  48. onClose?: () => void;
  49. /**
  50. * Current width of the trigger element. This is used as the menu's minimum
  51. * width.
  52. */
  53. triggerWidth?: number;
  54. } & AriaMenuOptions<MenuItemProps> &
  55. Partial<OverlayProps> &
  56. Partial<AriaPositionProps>;
  57. function Menu({
  58. offset = 8,
  59. crossOffset = 0,
  60. containerPadding = 0,
  61. placement = 'bottom left',
  62. closeOnSelect = true,
  63. triggerRef,
  64. triggerWidth,
  65. isSubmenu,
  66. menuTitle,
  67. closeRootMenu,
  68. closeCurrentSubmenu,
  69. isDismissable = true,
  70. shouldCloseOnBlur = true,
  71. ...props
  72. }: Props) {
  73. const state = useTreeState<MenuItemProps>({...props, selectionMode: 'single'});
  74. const stateCollection = useMemo(() => [...state.collection], [state.collection]);
  75. // Implement focus states, keyboard navigation, aria-label,...
  76. const menuRef = useRef(null);
  77. const {menuProps} = useMenu({...props, selectionMode: 'single'}, state, menuRef);
  78. const {separatorProps} = useSeparator({elementType: 'li'});
  79. // If this is a submenu, pressing arrow left should close it (but not the
  80. // root menu).
  81. const {keyboardProps} = useKeyboard({
  82. onKeyDown: e => {
  83. if (isSubmenu && e.key === 'ArrowLeft') {
  84. closeCurrentSubmenu?.();
  85. return;
  86. }
  87. e.continuePropagation();
  88. },
  89. });
  90. // Close the menu on outside interaction, blur, or Esc key press, and
  91. // control its position relative to the trigger button. See:
  92. // https://react-spectrum.adobe.com/react-aria/useOverlay.html
  93. // https://react-spectrum.adobe.com/react-aria/useOverlayPosition.html
  94. const overlayRef = useRef(null);
  95. const {overlayProps} = useOverlay(
  96. {
  97. onClose: closeRootMenu,
  98. shouldCloseOnBlur,
  99. isDismissable,
  100. isOpen: true,
  101. shouldCloseOnInteractOutside: target =>
  102. target && triggerRef.current !== target && !triggerRef.current?.contains(target),
  103. },
  104. overlayRef
  105. );
  106. const {overlayProps: positionProps, placement: placementProp} = useOverlayPosition({
  107. targetRef: triggerRef,
  108. overlayRef,
  109. offset,
  110. crossOffset,
  111. placement,
  112. containerPadding,
  113. isOpen: true,
  114. // useOverlayPosition's algorithm doesn't work well for submenus on viewport
  115. // scroll. Changing the boundary element (document.body by default) seems to
  116. // fix this.
  117. boundaryElement: document.querySelector<HTMLElement>('.app') ?? undefined,
  118. });
  119. // Store whether this menu/submenu is the current focused one, which in a
  120. // nested, tree-like menu system should be the leaf submenu. This
  121. // information is used for controlling keyboard events. See:
  122. // modifiedMenuProps below.
  123. const [hasFocus, setHasFocus] = useState(true);
  124. useEffect(() => {
  125. // A submenu is a leaf when it does not contain any expanded submenu. This
  126. // logically follows from the tree-like structure and single-selection
  127. // nature of menus.
  128. const isLeafSubmenu = !stateCollection.some(node => {
  129. const isSection = node.hasChildNodes && !node.value.isSubmenu;
  130. // A submenu with key [key] is expanded if
  131. // state.selectionManager.isSelected([key]) = true
  132. return isSection
  133. ? [...node.childNodes].some(child =>
  134. state.selectionManager.isSelected(`${child.key}`)
  135. )
  136. : state.selectionManager.isSelected(`${node.key}`);
  137. });
  138. setHasFocus(isLeafSubmenu);
  139. }, [stateCollection, state.selectionManager]);
  140. // Menu props from useMenu, modified to disable keyboard events if the
  141. // current menu does not have focus.
  142. const modifiedMenuProps = {
  143. ...menuProps,
  144. ...(!hasFocus && {
  145. onKeyUp: () => null,
  146. onKeyDown: () => null,
  147. }),
  148. };
  149. // Render a single menu item
  150. const renderItem = (node: Node<MenuItemProps>, isLastNode: boolean) => {
  151. return (
  152. <MenuItem
  153. node={node}
  154. isLastNode={isLastNode}
  155. state={state}
  156. onClose={closeRootMenu}
  157. closeOnSelect={closeOnSelect}
  158. />
  159. );
  160. };
  161. // Render a submenu whose trigger button is a menu item
  162. const renderItemWithSubmenu = (node: Node<MenuItemProps>, isLastNode: boolean) => {
  163. const trigger = ({props: submenuTriggerProps, ref: submenuTriggerRef}) => (
  164. <MenuItem
  165. renderAs="div"
  166. node={node}
  167. isLastNode={isLastNode}
  168. state={state}
  169. isSubmenuTrigger
  170. submenuTriggerRef={submenuTriggerRef}
  171. {...submenuTriggerProps}
  172. />
  173. );
  174. return (
  175. <MenuControl
  176. items={node.value.children as MenuItemProps[]}
  177. trigger={trigger}
  178. menuTitle={node.value.submenuTitle}
  179. placement="right top"
  180. offset={-4}
  181. crossOffset={-8}
  182. closeOnSelect={closeOnSelect}
  183. isOpen={state.selectionManager.isSelected(node.key)}
  184. isSubmenu
  185. closeRootMenu={closeRootMenu}
  186. closeCurrentSubmenu={() => state.selectionManager.clearSelection()}
  187. renderWrapAs="li"
  188. />
  189. );
  190. };
  191. // Render a collection of menu items
  192. const renderCollection = (collection: Node<MenuItemProps>[]) =>
  193. collection.map((node, i) => {
  194. const isLastNode = collection.length - 1 === i;
  195. const showSeparator =
  196. !isLastNode && (node.type === 'section' || collection[i + 1]?.type === 'section');
  197. let itemToRender: React.ReactNode;
  198. if (node.type === 'section') {
  199. itemToRender = (
  200. <MenuSection node={node}>{renderCollection([...node.childNodes])}</MenuSection>
  201. );
  202. } else {
  203. itemToRender = node.value.isSubmenu
  204. ? renderItemWithSubmenu(node, isLastNode)
  205. : renderItem(node, isLastNode);
  206. }
  207. return (
  208. <Fragment key={node.key}>
  209. {itemToRender}
  210. {showSeparator && <Separator {...separatorProps} />}
  211. </Fragment>
  212. );
  213. });
  214. return (
  215. <FocusScope restoreFocus autoFocus>
  216. <Overlay
  217. ref={overlayRef}
  218. placementProp={placementProp}
  219. {...mergeProps(overlayProps, positionProps, keyboardProps)}
  220. >
  221. <MenuWrap
  222. ref={menuRef}
  223. {...modifiedMenuProps}
  224. style={{
  225. maxHeight: positionProps.style?.maxHeight,
  226. minWidth: triggerWidth,
  227. }}
  228. >
  229. {menuTitle && <MenuTitle>{menuTitle}</MenuTitle>}
  230. {renderCollection(stateCollection)}
  231. </MenuWrap>
  232. </Overlay>
  233. </FocusScope>
  234. );
  235. }
  236. export default Menu;
  237. const Overlay = styled('div')<{placementProp: PositionAria['placement']}>`
  238. max-width: 24rem;
  239. border-radius: ${p => p.theme.borderRadius};
  240. background: ${p => p.theme.backgroundElevated};
  241. box-shadow: 0 0 0 1px ${p => p.theme.translucentBorder}, ${p => p.theme.dropShadowHeavy};
  242. font-size: ${p => p.theme.fontSizeMedium};
  243. margin: ${space(1)} 0;
  244. ${p => p.placementProp === 'top' && `margin-bottom: 0;`}
  245. ${p => p.placementProp === 'bottom' && `margin-top: 0;`}
  246. /* Override z-index from useOverlayPosition */
  247. z-index: ${p => p.theme.zIndex.dropdown} !important;
  248. `;
  249. const MenuWrap = styled('ul')`
  250. margin: 0;
  251. padding: ${space(0.5)} 0;
  252. font-size: ${p => p.theme.fontSizeMedium};
  253. overflow-x: hidden;
  254. overflow-y: auto;
  255. &:focus {
  256. outline: none;
  257. }
  258. `;
  259. const MenuTitle = styled('div')`
  260. font-weight: 600;
  261. font-size: ${p => p.theme.fontSizeSmall};
  262. color: ${p => p.theme.headingColor};
  263. white-space: nowrap;
  264. padding: ${space(0.25)} ${space(1.5)} ${space(0.75)};
  265. margin-bottom: ${space(0.5)};
  266. border-bottom: solid 1px ${p => p.theme.innerBorder};
  267. `;
  268. const Separator = styled('li')`
  269. list-style-type: none;
  270. border-top: solid 1px ${p => p.theme.innerBorder};
  271. margin: ${space(0.5)} ${space(1.5)};
  272. `;