dropdownMenuControl.tsx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import {useCallback, useEffect, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import {useButton} from '@react-aria/button';
  4. import {AriaMenuOptions, useMenuTrigger} from '@react-aria/menu';
  5. import {useResizeObserver} from '@react-aria/utils';
  6. import {Item, Section} from '@react-stately/collections';
  7. import {MenuTriggerProps} from '@react-types/menu';
  8. import DropdownButton, {DropdownButtonProps} from 'sentry/components/dropdownButton';
  9. import DropdownMenu from 'sentry/components/dropdownMenu';
  10. import {MenuItemProps} from 'sentry/components/dropdownMenuItem';
  11. import {FormSize} from 'sentry/utils/theme';
  12. import useOverlay, {UseOverlayProps} from 'sentry/utils/useOverlay';
  13. /**
  14. * Recursively removes hidden items, including those nested in submenus
  15. */
  16. function removeHiddenItems(source: MenuItemProps[]): MenuItemProps[] {
  17. return source
  18. .filter(item => !item.hidden)
  19. .map(item => ({
  20. ...item,
  21. ...(item.children ? {children: removeHiddenItems(item.children)} : {}),
  22. }));
  23. }
  24. /**
  25. * Recursively finds and returns disabled items
  26. */
  27. function getDisabledKeys(source: MenuItemProps[]): MenuItemProps['key'][] {
  28. return source.reduce<string[]>((acc, cur) => {
  29. if (cur.disabled) {
  30. // If an item is disabled, then its children will be inaccessible, so we
  31. // can skip them and just return the parent item
  32. return acc.concat([cur.key]);
  33. }
  34. if (cur.children) {
  35. return acc.concat(getDisabledKeys(cur.children));
  36. }
  37. return acc;
  38. }, []);
  39. }
  40. interface Props
  41. extends Partial<MenuTriggerProps>,
  42. Partial<AriaMenuOptions<MenuItemProps>>,
  43. UseOverlayProps {
  44. /**
  45. * Items to display inside the dropdown menu. If the item has a `children`
  46. * prop, it will be rendered as a menu section. If it has a `children` prop
  47. * and its `isSubmenu` prop is true, it will be rendered as a submenu.
  48. */
  49. items: MenuItemProps[];
  50. /**
  51. * Pass class name to the outer wrap
  52. */
  53. className?: string;
  54. /**
  55. * If this is a submenu, it will in some cases need to close itself (e.g.
  56. * when the user presses the arrow left key)
  57. */
  58. closeCurrentSubmenu?: () => void;
  59. /**
  60. * If this is a submenu, it will in some cases need to close the root menu
  61. * (e.g. when a submenu item is clicked).
  62. */
  63. closeRootMenu?: () => void;
  64. /**
  65. * Whether the trigger is disabled.
  66. */
  67. isDisabled?: boolean;
  68. /**
  69. * Whether this is a submenu.
  70. */
  71. isSubmenu?: boolean;
  72. /**
  73. * Title for the current menu.
  74. */
  75. menuTitle?: string;
  76. /**
  77. * Minimum menu width, in pixels
  78. */
  79. minMenuWidth?: number;
  80. /**
  81. * Tag name for the outer wrap, defaults to `div`
  82. */
  83. renderWrapAs?: React.ElementType;
  84. /**
  85. * Affects the size of the trigger button and menu items.
  86. */
  87. size?: FormSize;
  88. /**
  89. * Optionally replace the trigger button with a different component. Note
  90. * that the replacement must have the `props` and `ref` (supplied in
  91. * TriggerProps) forwarded its outer wrap, otherwise the accessibility
  92. * features won't work correctly.
  93. */
  94. trigger?: (
  95. props: Omit<React.HTMLAttributes<Element>, 'children'> & {
  96. onClick?: (e: MouseEvent) => void;
  97. }
  98. ) => React.ReactNode;
  99. /**
  100. * By default, the menu trigger will be rendered as a button, with
  101. * triggerLabel as the button label.
  102. */
  103. triggerLabel?: React.ReactNode;
  104. /**
  105. * If using the default button trigger (i.e. the custom `trigger` prop has
  106. * not been provided), then `triggerProps` will be passed on to the button
  107. * component.
  108. */
  109. triggerProps?: DropdownButtonProps;
  110. }
  111. /**
  112. * A menu component that renders both the trigger button and the dropdown
  113. * menu. See: https://react-spectrum.adobe.com/react-aria/useMenuTrigger.html
  114. */
  115. function DropdownMenuControl({
  116. items,
  117. disabledKeys,
  118. trigger,
  119. triggerLabel,
  120. triggerProps = {},
  121. isDisabled: disabledProp,
  122. isOpen: isOpenProp,
  123. minMenuWidth,
  124. isSubmenu = false,
  125. closeRootMenu,
  126. closeCurrentSubmenu,
  127. renderWrapAs = 'div',
  128. size = 'md',
  129. className,
  130. // Overlay props
  131. offset = 8,
  132. position = 'bottom-start',
  133. isDismissable = true,
  134. shouldCloseOnBlur = true,
  135. ...props
  136. }: Props) {
  137. const isDisabled = disabledProp ?? (!items || items.length === 0);
  138. const {
  139. isOpen,
  140. state,
  141. triggerRef,
  142. triggerProps: overlayTriggerProps,
  143. overlayProps,
  144. } = useOverlay({
  145. onClose: closeRootMenu,
  146. isOpen: isOpenProp,
  147. offset,
  148. position,
  149. isDismissable: !isSubmenu && isDismissable,
  150. shouldCloseOnBlur: !isSubmenu && shouldCloseOnBlur,
  151. shouldCloseOnInteractOutside: target =>
  152. !isSubmenu &&
  153. target &&
  154. triggerRef.current !== target &&
  155. !triggerRef.current?.contains(target),
  156. });
  157. const {menuTriggerProps, menuProps} = useMenuTrigger(
  158. {type: 'menu', isDisabled},
  159. {...state, focusStrategy: 'first'},
  160. triggerRef
  161. );
  162. const {buttonProps} = useButton(
  163. {
  164. isDisabled,
  165. ...menuTriggerProps,
  166. ...(isSubmenu && {
  167. onKeyUp: e => e.continuePropagation(),
  168. onKeyDown: e => e.continuePropagation(),
  169. onPress: () => null,
  170. onPressStart: () => null,
  171. onPressEnd: () => null,
  172. }),
  173. },
  174. triggerRef
  175. );
  176. // Calculate the current trigger element's width. This will be used as
  177. // the min width for the menu.
  178. const [triggerWidth, setTriggerWidth] = useState<number>();
  179. // Update triggerWidth when its size changes using useResizeObserver
  180. const updateTriggerWidth = useCallback(async () => {
  181. // Wait until the trigger element finishes rendering, otherwise
  182. // ResizeObserver might throw an infinite loop error.
  183. await new Promise(resolve => window.setTimeout(resolve));
  184. const newTriggerWidth = triggerRef.current?.offsetWidth;
  185. !isSubmenu && newTriggerWidth && setTriggerWidth(newTriggerWidth);
  186. }, [isSubmenu, triggerRef]);
  187. useResizeObserver({ref: triggerRef, onResize: updateTriggerWidth});
  188. // If ResizeObserver is not available, manually update the width
  189. // when any of [trigger, triggerLabel, triggerProps] changes.
  190. useEffect(() => {
  191. if (typeof window.ResizeObserver !== 'undefined') {
  192. return;
  193. }
  194. updateTriggerWidth();
  195. }, [updateTriggerWidth]);
  196. function renderTrigger() {
  197. if (trigger) {
  198. return trigger({
  199. size,
  200. isOpen,
  201. ...triggerProps,
  202. ...overlayTriggerProps,
  203. ...buttonProps,
  204. });
  205. }
  206. return (
  207. <DropdownButton
  208. size={size}
  209. isOpen={isOpen}
  210. {...triggerProps}
  211. {...overlayTriggerProps}
  212. {...buttonProps}
  213. >
  214. {triggerLabel}
  215. </DropdownButton>
  216. );
  217. }
  218. const activeItems = useMemo(() => removeHiddenItems(items), [items]);
  219. const defaultDisabledKeys = useMemo(() => getDisabledKeys(activeItems), [activeItems]);
  220. function renderMenu() {
  221. if (!isOpen) {
  222. return null;
  223. }
  224. return (
  225. <DropdownMenu
  226. {...props}
  227. {...menuProps}
  228. size={size}
  229. isSubmenu={isSubmenu}
  230. minWidth={Math.max(minMenuWidth ?? 0, triggerWidth ?? 0)}
  231. closeRootMenu={closeRootMenu ?? state.close}
  232. closeCurrentSubmenu={closeCurrentSubmenu}
  233. disabledKeys={disabledKeys ?? defaultDisabledKeys}
  234. overlayPositionProps={overlayProps}
  235. items={activeItems}
  236. >
  237. {(item: MenuItemProps) => {
  238. if (item.children && item.children.length > 0 && !item.isSubmenu) {
  239. return (
  240. <Section key={item.key} title={item.label} items={item.children}>
  241. {sectionItem => (
  242. <Item size={size} {...sectionItem}>
  243. {sectionItem.label}
  244. </Item>
  245. )}
  246. </Section>
  247. );
  248. }
  249. return (
  250. <Item size={size} {...item}>
  251. {item.label}
  252. </Item>
  253. );
  254. }}
  255. </DropdownMenu>
  256. );
  257. }
  258. return (
  259. <MenuControlWrap className={className} as={renderWrapAs} role="presentation">
  260. {renderTrigger()}
  261. {renderMenu()}
  262. </MenuControlWrap>
  263. );
  264. }
  265. export default DropdownMenuControl;
  266. const MenuControlWrap = styled('div')`
  267. list-style-type: none;
  268. `;