dropdownMenu.tsx 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. /**
  42. * Minimum menu width
  43. */
  44. minWidth?: number;
  45. onClose?: () => void;
  46. size?: MenuItemProps['size'];
  47. } & AriaMenuOptions<MenuItemProps> &
  48. Partial<OverlayProps> &
  49. Partial<AriaPositionProps>;
  50. function DropdownMenu({
  51. closeOnSelect = true,
  52. minWidth,
  53. size,
  54. isSubmenu,
  55. menuTitle,
  56. closeRootMenu,
  57. closeCurrentSubmenu,
  58. overlayPositionProps,
  59. ...props
  60. }: Props) {
  61. const state = useTreeState<MenuItemProps>({...props, selectionMode: 'single'});
  62. const stateCollection = useMemo(() => [...state.collection], [state.collection]);
  63. // Implement focus states, keyboard navigation, aria-label,...
  64. const menuRef = useRef(null);
  65. const {menuProps} = useMenu({...props, selectionMode: 'single'}, state, menuRef);
  66. const {separatorProps} = useSeparator({elementType: 'li'});
  67. // If this is a submenu, pressing arrow left should close it (but not the
  68. // root menu).
  69. const {keyboardProps} = useKeyboard({
  70. onKeyDown: e => {
  71. if (isSubmenu && e.key === 'ArrowLeft') {
  72. closeCurrentSubmenu?.();
  73. return;
  74. }
  75. e.continuePropagation();
  76. },
  77. });
  78. /**
  79. * Whether this menu/submenu is the current focused one, which in a nested,
  80. * tree-like menu system should be the leaf submenu. This information is
  81. * used for controlling keyboard events. See ``modifiedMenuProps` below.
  82. */
  83. const hasFocus = useMemo(() => {
  84. // A submenu is a leaf when it does not contain any expanded submenu. This
  85. // logically follows from the tree-like structure and single-selection
  86. // nature of menus.
  87. const isLeafSubmenu = !stateCollection.some(node => {
  88. const isSection = node.hasChildNodes && !node.value.isSubmenu;
  89. // A submenu with key [key] is expanded if
  90. // state.selectionManager.isSelected([key]) = true
  91. return isSection
  92. ? [...node.childNodes].some(child =>
  93. state.selectionManager.isSelected(`${child.key}`)
  94. )
  95. : state.selectionManager.isSelected(`${node.key}`);
  96. });
  97. return isLeafSubmenu;
  98. }, [stateCollection, state.selectionManager]);
  99. // Menu props from useMenu, modified to disable keyboard events if the
  100. // current menu does not have focus.
  101. const modifiedMenuProps = useMemo(
  102. () => ({
  103. ...menuProps,
  104. ...(!hasFocus && {
  105. onKeyUp: () => null,
  106. onKeyDown: () => null,
  107. }),
  108. }),
  109. [menuProps, hasFocus]
  110. );
  111. const showDividers = stateCollection.some(item => !!item.props.details);
  112. // Render a single menu item
  113. const renderItem = (node: Node<MenuItemProps>, isLastNode: boolean) => {
  114. return (
  115. <MenuItem
  116. node={node}
  117. state={state}
  118. onClose={closeRootMenu}
  119. closeOnSelect={closeOnSelect}
  120. showDivider={showDividers && !isLastNode}
  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. state={state}
  131. isSubmenuTrigger
  132. showDivider={showDividers && !isLastNode}
  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,
  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. `;