dropdownMenu.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import {Fragment, useMemo, useRef} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import {FocusScope} from '@react-aria/focus';
  5. import {useKeyboard} from '@react-aria/interactions';
  6. import {AriaMenuOptions, useMenu} from '@react-aria/menu';
  7. import {AriaPositionProps, OverlayProps} from '@react-aria/overlays';
  8. import {useSeparator} from '@react-aria/separator';
  9. import {mergeProps} from '@react-aria/utils';
  10. import {useTreeState} from '@react-stately/tree';
  11. import {Node} from '@react-types/shared';
  12. import MenuControl from 'sentry/components/dropdownMenuControl';
  13. import MenuItem, {MenuItemProps} from 'sentry/components/dropdownMenuItem';
  14. import MenuSection from 'sentry/components/dropdownMenuSection';
  15. import {Overlay, PositionWrapper} from 'sentry/components/overlay';
  16. import space from 'sentry/styles/space';
  17. type Props = {
  18. /**
  19. * If this is a submenu, it will in some cases need to close the root menu
  20. * (e.g. when a submenu item is clicked).
  21. */
  22. closeRootMenu: () => void;
  23. /**
  24. * Whether this is a submenu
  25. */
  26. isSubmenu: boolean;
  27. overlayPositionProps: React.HTMLAttributes<HTMLDivElement>;
  28. /**
  29. * If this is a submenu, it will in some cases need to close itself (e.g.
  30. * when the user presses the arrow left key)
  31. */
  32. closeCurrentSubmenu?: () => void;
  33. /**
  34. * Whether the menu should close when an item has been clicked/selected
  35. */
  36. closeOnSelect?: boolean;
  37. /*
  38. * Title to display on top of the menu
  39. */
  40. menuTitle?: string;
  41. onClose?: () => void;
  42. size?: MenuItemProps['size'];
  43. /**
  44. * Current width of the trigger element. This is used as the menu's minimum
  45. * width.
  46. */
  47. triggerWidth?: number;
  48. } & AriaMenuOptions<MenuItemProps> &
  49. Partial<OverlayProps> &
  50. Partial<AriaPositionProps>;
  51. function DropdownMenu({
  52. closeOnSelect = true,
  53. triggerWidth,
  54. size,
  55. isSubmenu,
  56. menuTitle,
  57. closeRootMenu,
  58. closeCurrentSubmenu,
  59. overlayPositionProps,
  60. ...props
  61. }: Props) {
  62. const state = useTreeState<MenuItemProps>({...props, selectionMode: 'single'});
  63. const stateCollection = useMemo(() => [...state.collection], [state.collection]);
  64. // Implement focus states, keyboard navigation, aria-label,...
  65. const menuRef = useRef(null);
  66. const {menuProps} = useMenu({...props, selectionMode: 'single'}, state, menuRef);
  67. const {separatorProps} = useSeparator({elementType: 'li'});
  68. // If this is a submenu, pressing arrow left should close it (but not the
  69. // root menu).
  70. const {keyboardProps} = useKeyboard({
  71. onKeyDown: e => {
  72. if (isSubmenu && e.key === 'ArrowLeft') {
  73. closeCurrentSubmenu?.();
  74. return;
  75. }
  76. e.continuePropagation();
  77. },
  78. });
  79. /**
  80. * Whether this menu/submenu is the current focused one, which in a nested,
  81. * tree-like menu system should be the leaf submenu. This information is
  82. * used for controlling keyboard events. See ``modifiedMenuProps` below.
  83. */
  84. const hasFocus = useMemo(() => {
  85. // A submenu is a leaf when it does not contain any expanded submenu. This
  86. // logically follows from the tree-like structure and single-selection
  87. // nature of menus.
  88. const isLeafSubmenu = !stateCollection.some(node => {
  89. const isSection = node.hasChildNodes && !node.value.isSubmenu;
  90. // A submenu with key [key] is expanded if
  91. // state.selectionManager.isSelected([key]) = true
  92. return isSection
  93. ? [...node.childNodes].some(child =>
  94. state.selectionManager.isSelected(`${child.key}`)
  95. )
  96. : state.selectionManager.isSelected(`${node.key}`);
  97. });
  98. return isLeafSubmenu;
  99. }, [stateCollection, state.selectionManager]);
  100. // Menu props from useMenu, modified to disable keyboard events if the
  101. // current menu does not have focus.
  102. const modifiedMenuProps = useMemo(
  103. () => ({
  104. ...menuProps,
  105. ...(!hasFocus && {
  106. onKeyUp: () => null,
  107. onKeyDown: () => null,
  108. }),
  109. }),
  110. [menuProps, hasFocus]
  111. );
  112. // Render a single menu item
  113. const renderItem = (node: Node<MenuItemProps>, isLastNode: boolean) => {
  114. return (
  115. <MenuItem
  116. node={node}
  117. isLastNode={isLastNode}
  118. state={state}
  119. onClose={closeRootMenu}
  120. closeOnSelect={closeOnSelect}
  121. />
  122. );
  123. };
  124. // Render a submenu whose trigger button is a menu item
  125. const renderItemWithSubmenu = (node: Node<MenuItemProps>, isLastNode: boolean) => {
  126. const trigger = submenuTriggerProps => (
  127. <MenuItem
  128. renderAs="div"
  129. node={node}
  130. isLastNode={isLastNode}
  131. state={state}
  132. isSubmenuTrigger
  133. {...submenuTriggerProps}
  134. />
  135. );
  136. return (
  137. <MenuControl
  138. items={node.value.children as MenuItemProps[]}
  139. trigger={trigger}
  140. menuTitle={node.value.submenuTitle}
  141. position="right-start"
  142. offset={-4}
  143. closeOnSelect={closeOnSelect}
  144. isOpen={state.selectionManager.isSelected(node.key)}
  145. size={size}
  146. isSubmenu
  147. closeRootMenu={closeRootMenu}
  148. closeCurrentSubmenu={() => state.selectionManager.clearSelection()}
  149. renderWrapAs="li"
  150. />
  151. );
  152. };
  153. // Render a collection of menu items
  154. const renderCollection = (collection: Node<MenuItemProps>[]) =>
  155. collection.map((node, i) => {
  156. const isLastNode = collection.length - 1 === i;
  157. const showSeparator =
  158. !isLastNode && (node.type === 'section' || collection[i + 1]?.type === 'section');
  159. let itemToRender: React.ReactNode;
  160. if (node.type === 'section') {
  161. itemToRender = (
  162. <MenuSection node={node}>{renderCollection([...node.childNodes])}</MenuSection>
  163. );
  164. } else {
  165. itemToRender = node.value.isSubmenu
  166. ? renderItemWithSubmenu(node, isLastNode)
  167. : renderItem(node, isLastNode);
  168. }
  169. return (
  170. <Fragment key={node.key}>
  171. {itemToRender}
  172. {showSeparator && <Separator {...separatorProps} />}
  173. </Fragment>
  174. );
  175. });
  176. const theme = useTheme();
  177. return (
  178. <FocusScope restoreFocus autoFocus>
  179. <PositionWrapper zIndex={theme.zIndex.dropdown} {...overlayPositionProps}>
  180. <StyledOverlay>
  181. <MenuWrap
  182. ref={menuRef}
  183. {...mergeProps(modifiedMenuProps, keyboardProps)}
  184. style={{
  185. maxHeight: overlayPositionProps.style?.maxHeight,
  186. minWidth: triggerWidth,
  187. }}
  188. >
  189. {menuTitle && <MenuTitle>{menuTitle}</MenuTitle>}
  190. {renderCollection(stateCollection)}
  191. </MenuWrap>
  192. </StyledOverlay>
  193. </PositionWrapper>
  194. </FocusScope>
  195. );
  196. }
  197. export default DropdownMenu;
  198. const StyledOverlay = styled(Overlay)`
  199. max-width: 24rem;
  200. @media only screen and (max-width: calc(24rem + ${space(2)} * 2)) {
  201. max-width: calc(100vw - ${space(2)} * 2);
  202. }
  203. `;
  204. const MenuWrap = styled('ul')`
  205. margin: 0;
  206. padding: ${space(0.5)} 0;
  207. font-size: ${p => p.theme.fontSizeMedium};
  208. &:focus {
  209. outline: none;
  210. }
  211. `;
  212. const MenuTitle = styled('div')`
  213. font-weight: 600;
  214. font-size: ${p => p.theme.fontSizeSmall};
  215. color: ${p => p.theme.headingColor};
  216. white-space: nowrap;
  217. padding: ${space(0.25)} ${space(1.5)} ${space(0.75)};
  218. margin-bottom: ${space(0.5)};
  219. border-bottom: solid 1px ${p => p.theme.innerBorder};
  220. `;
  221. const Separator = styled('li')`
  222. list-style-type: none;
  223. border-top: solid 1px ${p => p.theme.innerBorder};
  224. margin: ${space(0.5)} ${space(1.5)};
  225. `;