dropdownMenuControl.tsx 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import {useCallback, useEffect, useRef, 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 {AriaPositionProps, OverlayProps} from '@react-aria/overlays';
  6. import {useResizeObserver} from '@react-aria/utils';
  7. import {Item, Section} from '@react-stately/collections';
  8. import {useMenuTriggerState} from '@react-stately/menu';
  9. import {MenuTriggerProps} from '@react-types/menu';
  10. import DropdownButton, {DropdownButtonProps} from 'sentry/components/dropdownButton';
  11. import {MenuItemProps} from 'sentry/components/dropdownMenuItem';
  12. import Menu from 'sentry/components/dropdownMenuV2';
  13. type TriggerProps = {
  14. props: Omit<React.HTMLAttributes<Element>, 'children'> & {
  15. onClick?: (e: MouseEvent) => void;
  16. };
  17. ref: React.RefObject<HTMLButtonElement>;
  18. };
  19. type Props = {
  20. /**
  21. * Items to display inside the dropdown menu. If the item has a `children`
  22. * prop, it will be rendered as a menu section. If it has a `children` prop
  23. * and its `isSubmenu` prop is true, it will be rendered as a submenu.
  24. */
  25. items: MenuItemProps[];
  26. /**
  27. * Pass class name to the outer wrap
  28. */
  29. className?: string;
  30. /**
  31. * If this is a submenu, it will in some cases need to close itself (e.g.
  32. * when the user presses the arrow left key)
  33. */
  34. closeCurrentSubmenu?: () => void;
  35. /**
  36. * If this is a submenu, it will in some cases need to close the root menu
  37. * (e.g. when a submenu item is clicked).
  38. */
  39. closeRootMenu?: () => void;
  40. /**
  41. * Whether the trigger is disabled.
  42. */
  43. isDisabled?: boolean;
  44. /**
  45. * Whether this is a submenu.
  46. */
  47. isSubmenu?: boolean;
  48. /**
  49. * Title for the current menu.
  50. */
  51. menuTitle?: string;
  52. /**
  53. * Tag name for the outer wrap, defaults to `div`
  54. */
  55. renderWrapAs?: React.ElementType;
  56. /**
  57. * Optionally replace the trigger button with a different component. Note
  58. * that the replacement must have the `props` and `ref` (supplied in
  59. * TriggerProps) forwarded its outer wrap, otherwise the accessibility
  60. * features won't work correctly.
  61. */
  62. trigger?: (props: TriggerProps) => React.ReactNode;
  63. /**
  64. * By default, the menu trigger will be rendered as a button, with
  65. * triggerLabel as the button label.
  66. */
  67. triggerLabel?: React.ReactNode;
  68. /**
  69. * If using the default button trigger (i.e. the custom `trigger` prop has
  70. * not been provided), then `triggerProps` will be passed on to the button
  71. * component.
  72. */
  73. triggerProps?: DropdownButtonProps;
  74. } & Partial<MenuTriggerProps> &
  75. Partial<AriaMenuOptions<MenuItemProps>> &
  76. Partial<OverlayProps> &
  77. Partial<AriaPositionProps>;
  78. /**
  79. * A menu component that renders both the trigger button and the dropdown
  80. * menu. See: https://react-spectrum.adobe.com/react-aria/useMenuTrigger.html
  81. */
  82. function MenuControl({
  83. items,
  84. trigger,
  85. triggerLabel,
  86. triggerProps = {},
  87. isDisabled: disabledProp,
  88. isSubmenu = false,
  89. closeRootMenu,
  90. closeCurrentSubmenu,
  91. renderWrapAs = 'div',
  92. className,
  93. ...props
  94. }: Props) {
  95. const ref = useRef<HTMLButtonElement>(null);
  96. const isDisabled = disabledProp ?? (!items || items.length === 0);
  97. // Control the menu open state. See:
  98. // https://react-spectrum.adobe.com/react-aria/useMenuTrigger.html
  99. const state = useMenuTriggerState(props);
  100. const {menuTriggerProps, menuProps} = useMenuTrigger(
  101. {type: 'menu', isDisabled},
  102. state,
  103. ref
  104. );
  105. const {buttonProps} = useButton(
  106. {
  107. isDisabled,
  108. ...menuTriggerProps,
  109. ...(isSubmenu && {
  110. onKeyUp: e => e.continuePropagation(),
  111. onKeyDown: e => e.continuePropagation(),
  112. onPress: () => null,
  113. onPressStart: () => null,
  114. onPressEnd: () => null,
  115. }),
  116. },
  117. ref
  118. );
  119. // Calculate the current trigger element's width. This will be used as
  120. // the min width for the menu.
  121. const [triggerWidth, setTriggerWidth] = useState<number>();
  122. // Update triggerWidth when its size changes using useResizeObserver
  123. const updateTriggerWidth = useCallback(async () => {
  124. // Wait until the trigger element finishes rendering, otherwise
  125. // ResizeObserver might throw an infinite loop error.
  126. await new Promise(resolve => window.setTimeout(resolve));
  127. const newTriggerWidth = ref.current?.offsetWidth;
  128. !isSubmenu && newTriggerWidth && setTriggerWidth(newTriggerWidth);
  129. }, [isSubmenu]);
  130. useResizeObserver({ref, onResize: updateTriggerWidth});
  131. // If ResizeObserver is not available, manually update the width
  132. // when any of [trigger, triggerLabel, triggerProps] changes.
  133. useEffect(() => {
  134. if (typeof window.ResizeObserver !== 'undefined') {
  135. return;
  136. }
  137. updateTriggerWidth();
  138. }, [updateTriggerWidth]);
  139. // Recursively remove hidden items, including those nested in submenus
  140. function removeHiddenItems(source) {
  141. return source
  142. .filter(item => !item.hidden)
  143. .map(item => ({
  144. ...item,
  145. ...(item.children ? {children: removeHiddenItems(item.children)} : {}),
  146. }));
  147. }
  148. function renderTrigger() {
  149. if (trigger) {
  150. return trigger({
  151. props: {
  152. ...triggerProps,
  153. ...buttonProps,
  154. isOpen: state.isOpen,
  155. },
  156. ref,
  157. });
  158. }
  159. return (
  160. <DropdownButton ref={ref} isOpen={state.isOpen} {...triggerProps} {...buttonProps}>
  161. {triggerLabel}
  162. </DropdownButton>
  163. );
  164. }
  165. function renderMenu() {
  166. if (!state.isOpen) {
  167. return null;
  168. }
  169. return (
  170. <Menu
  171. {...props}
  172. {...menuProps}
  173. triggerRef={ref}
  174. triggerWidth={triggerWidth}
  175. isSubmenu={isSubmenu}
  176. isDismissable={!isSubmenu && props.isDismissable}
  177. shouldCloseOnBlur={!isSubmenu && props.shouldCloseOnBlur}
  178. closeRootMenu={closeRootMenu ?? state.close}
  179. closeCurrentSubmenu={closeCurrentSubmenu}
  180. items={removeHiddenItems(items)}
  181. >
  182. {(item: MenuItemProps) => {
  183. if (item.children && item.children.length > 0 && !item.isSubmenu) {
  184. return (
  185. <Section key={item.key} title={item.label} items={item.children}>
  186. {sectionItem => <Item {...sectionItem}>{sectionItem.label}</Item>}
  187. </Section>
  188. );
  189. }
  190. return <Item {...item}>{item.label}</Item>;
  191. }}
  192. </Menu>
  193. );
  194. }
  195. return (
  196. <MenuControlWrap className={className} as={renderWrapAs} role="presentation">
  197. {renderTrigger()}
  198. {renderMenu()}
  199. </MenuControlWrap>
  200. );
  201. }
  202. export default MenuControl;
  203. const MenuControlWrap = styled('div')`
  204. list-style-type: none;
  205. `;