dropdownMenuV2.tsx 9.0 KB

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