UNPKG

@atlaskit/dropdown-menu

Version:

A dropdown menu displays a list of actions or options to a user.

444 lines (425 loc) • 17.5 kB
/* dropdown-menu-top-layer.tsx generated by @compiled/babel-plugin v3.0.4 */ import _extends from "@babel/runtime/helpers/extends"; import "./dropdown-menu-top-layer.compiled.css"; import * as React from 'react'; import { ax, ix } from "@compiled/react/runtime"; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { flushSync } from 'react-dom'; import { bind } from 'bind-event-listener'; import Button from '@atlaskit/button/default/button'; import noop from '@atlaskit/ds-lib/noop'; import useControlledState from '@atlaskit/ds-lib/use-controlled'; import useFocus from '@atlaskit/ds-lib/use-focus-event'; import { useLayoutEffect } from '@atlaskit/ds-lib/use-layout-effect'; import ExpandIcon from '@atlaskit/icon/core/chevron-down'; import MenuGroup from '@atlaskit/menu/menu-group'; import { fg } from '@atlaskit/platform-feature-flags/fg'; import Spinner from '@atlaskit/spinner/spinner'; import { getAriaForTrigger } from '@atlaskit/top-layer/get-aria-for-trigger'; import { isAtCurrentMenuLevel } from '@atlaskit/top-layer/is-at-current-menu-level'; import { fromLegacyPlacement } from '@atlaskit/top-layer/placement-map/index'; import { PopoverSurface } from '@atlaskit/top-layer/popover-surface'; import { createPopoverCloseEvent } from '@atlaskit/top-layer/popover/create-close-event'; import { Popover } from '@atlaskit/top-layer/popover/popover'; import { useAnchoredPopover } from '@atlaskit/top-layer/use-anchored-popover'; import { useArrowNavigation } from '@atlaskit/top-layer/use-arrow-navigation/use-arrow-navigation'; import { useManualLightDismiss } from '@atlaskit/top-layer/use-manual-light-dismiss'; import { usePopoverId } from '@atlaskit/top-layer/use-popover-id'; import { DropdownTriggerContext } from './internal/context/dropdown-trigger-context'; import SelectionStore from './internal/context/selection-store'; const MAX_HEIGHT = `calc(100vh - 16px)`; const MAX_WIDTH = '800px'; // We want 8px horizontal gap between open menus. // Gap is measured starting from the end of the dropdown item - menu has 6px right padding + 8px gap = 14 const NESTED_MENU_OFFSET = 14; const styles = { spinnerContainer: "_1e0c1txw _1ul91lit _1bah1h6o _1q51v47k _y4tiv47k _85i5v47k _bozgv47k", newWrapper: "_1reo1wug _18m91wug _1e0c1txw _kqswpfqs _2lx21bp4", height: "_c71lk6is", width: "_p12f1c3h" }; const semanticStyles = { spinnerContainer: "_1q51covo _y4ticovo _85i5covo _bozgcovo" }; /** * Event types produced by trigger interactions. * * - `React.MouseEvent<Element>`: from the trigger's `onClick` handler * - `React.KeyboardEvent<Element>`: from the trigger's `onClick` when activated via keyboard * - `KeyboardEvent`: native event from the ArrowDown `bind(window, ...)` listener */ /** * The menu and its parent menus, innermost first. The last one is the root menu. */ function getMenuStack({ menu }) { var _menu$parentElement; const parentMenu = (_menu$parentElement = menu.parentElement) === null || _menu$parentElement === void 0 ? void 0 : _menu$parentElement.closest('[popover][role="menu"]'); if (!parentMenu) { return [menu]; } return [menu, ...getMenuStack({ menu: parentMenu })]; } /** * Asks each open menu to close for a Tab, so a Tab in a nested menu can ask every menu in its * stack, as the legacy path does. */ const menuTabCloseRequests = new WeakMap(); /** * A submenu trigger: `aria-haspopup` `menu` or `true`. */ const submenuTriggerSelector = '[aria-haspopup="menu"], [aria-haspopup="true"]'; /** * A group title (`GroupTitle`, or a `@atlaskit/menu` `HeadingItem`). */ const headingItemSelector = '[data-ds--menu--heading-item]'; /** * Loading indicator for the dropdown menu. */ function LoadingIndicator({ statusLabel = 'Loading', testId }) { return /*#__PURE__*/React.createElement("div", { role: "menuitem", className: ax([styles.spinnerContainer, fg('platform-semantic-spacing') && semanticStyles.spinnerContainer]) }, /*#__PURE__*/React.createElement(Spinner, { size: "small", label: statusLabel, testId: testId })); } /** * Top-layer implementation of DropdownMenu. * * Replaces the legacy `@atlaskit/popup` + `@atlaskit/portal` + `@atlaskit/layering` pipeline * with the native Popover API via `@atlaskit/top-layer`. * * What is no longer needed: * - Portal: top layer handles stacking natively * - FocusLock / react-focus-lock: `useManualLightDismiss` provides light dismiss * - z-index: top layer is always above everything * - FocusManager (ref registration): replaced by DOM-query-based `useArrowNavigation` * - handle-focus.tsx: replaced by `useArrowNavigation` * - Layering context: top layer nesting is handled by the browser * - Fallback placements / Popper: CSS Anchor Positioning handles positioning */ function DropdownMenuTopLayer({ children, defaultOpen = false, isLoading, isOpen: isOpenProp, onOpenChange = noop, placement = 'bottom-start', shouldFitContainer = false, spacing, statusLabel, testId, trigger, label, interactionName, menuLabel }) { var _ref2; const [isLocalOpen, setLocalIsOpen] = useControlledState(isOpenProp, () => defaultOpen); const [isNestedTrigger, setIsNestedTrigger] = useState(false); const triggerRef = useRef(null); const popoverRef = useRef(null); const setPopoverRef = useCallback(element => { popoverRef.current = element; // Leave untouched menus without a busy state; retain false once it has been set. if (isLoading !== undefined || element !== null && element !== void 0 && element.hasAttribute('aria-busy')) { element === null || element === void 0 ? void 0 : element.setAttribute('aria-busy', String(Boolean(isLoading))); } }, [isLoading]); const oldSpacing = (spacing === 'spacious' ? 'cozy' : spacing) || 'cozy'; const popoverId = usePopoverId(); const topLayerPlacement = useMemo(() => { return fromLegacyPlacement({ legacy: placement, // If the menu is nested, give it an offset so it doesn't overlap the edges of the previous menu offset: fg('platform-dst-new-menu') && isNestedTrigger ? [0, NESTED_MENU_OFFSET] : undefined }); }, [placement, isNestedTrigger]); // DropdownMenu has no `shouldFitViewport` equivalent, so neither axis ever // fits and `blockSize` stays `'content'` - `MenuGroup`'s `maxHeight` owns the // block axis. useAnchoredPopover({ anchorRef: triggerRef, popoverRef, placement: topLayerPlacement, isOpen: isLocalOpen, inlineSize: shouldFitContainer ? 'min-anchor' : 'content' }); // Close handling. Escape, Tab, Left arrow, an outside press and an item select // close through here; the trigger toggle closes in `handleTriggerClicked`. // With a controlled `isOpen`, it only asks: the menu hides when `isOpen` becomes `false`. // Focus return: // - Escape, Tab or a close from state: `Popover` returns focus to the element that had // focus when the menu opened (usually the trigger), as the menu hides // - Outside press: no focus return; focus stays where the user pressed // `returnFocusRef` is a no-op on this path. const closeMenu = useCallback(({ event }) => { setLocalIsOpen(false); onOpenChange({ isOpen: false, event }); }, [onOpenChange, setLocalIsOpen]); // Bridges the Popover close reason to the legacy `onOpenChange` event: a // `KeyboardEvent` for Escape, a `MouseEvent` for an outside press, and // `null` for a programmatic close (as `OnOpenChangeArgs` documents). const handleOnClose = useCallback(({ reason }) => { closeMenu({ event: reason === 'programmatic' ? null : createPopoverCloseEvent({ reason }) }); }, [closeMenu]); // A Tab in this menu or a nested one asks this menu to close, with a Tab `KeyboardEvent`, as the // legacy path does. useLayoutEffect(() => { const menu = popoverRef.current; if (!isLocalOpen || !menu) { return; } menuTabCloseRequests.set(menu, () => { closeMenu({ event: new KeyboardEvent('keydown', { key: 'Tab', bubbles: true }) }); }); return () => { menuTabCloseRequests.delete(menu); }; }, [closeMenu, isLocalOpen]); /** * **Ask first, close second** * * A `manual` popover, so the browser never closes it. An outside press or Escape asks through * `onOpenChange`, and the menu hides only when `isOpen` becomes `false`. A press on the trigger * does not ask: the trigger's click toggles the menu, as on the legacy path. A press in a nested * menu is inside this menu (it renders in place). * See `@atlaskit/top-layer` `notes/decisions/wrappers-ask-first-close.md`. */ const triggerRefs = useMemo(() => [triggerRef], []); useManualLightDismiss({ isOpen: isLocalOpen, popoverRef, additionalInsideElementRefs: triggerRefs, onClose: handleOnClose }); const handleNestedClose = useCallback(() => { closeMenu({ event: new KeyboardEvent('keydown', { key: 'ArrowLeft', bubbles: true }) }); }, [closeMenu]); // Trigger click handling. const handleTriggerClicked = useCallback(event => { const nextIsOpen = !isLocalOpen; setLocalIsOpen(nextIsOpen); // Extract the native DOM event for onOpenChange const nativeEvent = 'nativeEvent' in event ? event.nativeEvent : event; onOpenChange({ isOpen: nextIsOpen, event: nativeEvent }); }, [isLocalOpen, setLocalIsOpen, onOpenChange]); const { isFocused, bindFocus } = useFocus(); // When trigger is focused, open dropdown on ArrowDown (top-level only). // Per WAI-ARIA, ArrowDown opens a menu from a menubar/button trigger, // but inside a vertical submenu, ArrowDown navigates between siblings // and ArrowRight opens nested menus instead. useEffect(() => { var _triggerRef$current; const isNestedTriggerLocal = Boolean((_triggerRef$current = triggerRef.current) === null || _triggerRef$current === void 0 ? void 0 : _triggerRef$current.closest('[role="menu"]')); setIsNestedTrigger(isNestedTriggerLocal); if (!isFocused || isLocalOpen) { return; } // Do not open on ArrowDown if this trigger is inside a parent menu. // Nested menus should only be opened via ArrowRight or Enter. return bind(window, { type: 'keydown', listener: function openOnKeyDown(e) { if (e.key === 'ArrowDown' && !isNestedTriggerLocal) { e.preventDefault(); handleTriggerClicked(e); } } }); }, [isFocused, isLocalOpen, handleTriggerClicked]); const handleNestedOpen = useCallback(({ trigger }) => { if (!trigger.matches(submenuTriggerSelector)) { return; } trigger.click(); }, []); const handleTabClose = useCallback(() => { const currentMenu = popoverRef.current; if (!currentMenu) { return; } const menuStack = getMenuStack({ menu: currentMenu }); // Ask every menu in the stack, innermost first. In one `flushSync`, so the menus that accept // hide before the browser performs the Tab default action. flushSync(() => { menuStack.forEach(menu => { var _menuTabCloseRequests; return (_menuTabCloseRequests = menuTabCloseRequests.get(menu)) === null || _menuTabCloseRequests === void 0 ? void 0 : _menuTabCloseRequests(); }); }); }, []); useArrowNavigation({ containerRef: popoverRef, onClose: handleTabClose, onNestedOpen: handleNestedOpen, onNestedClose: handleNestedClose, isEnabled: isLocalOpen, filter: isAtCurrentMenuLevel }); // Close on menu item click, as the WAI-ARIA APG menu pattern describes: activating an item // closes the menu. Checkbox and radio items, and submenu triggers, keep it open. Any other // item closes it, also an item that opens a popup (the popup must open outside the menu, or // in a modal). A click on an item of a nested menu also bubbles here, so every menu in the // stack closes and focus returns to the root trigger (only Escape and Left arrow go back one // level). const handleMenuClick = useCallback(e => { var _e$target$closest, _e$target; if (!(e.target instanceof Element)) { return; } const menuItem = (_e$target$closest = (_e$target = e.target).closest) === null || _e$target$closest === void 0 ? void 0 : _e$target$closest.call(_e$target, '[role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"]'); if (!menuItem) { return; } // A group title has `role="menuitem"` (see `GroupTitle`), but it is not an item. The legacy // menu closes only for its registered items. if (menuItem.matches(headingItemSelector)) { return; } const isCheckboxOrRadio = menuItem.getAttribute('role') === 'menuitemcheckbox' || menuItem.getAttribute('role') === 'menuitemradio'; if (!isCheckboxOrRadio && !menuItem.matches(submenuTriggerSelector)) { var _popoverRef$current; // APG menu button: choosing an item focuses the trigger. Do it now, in the click. React // applies the item's change before the menu hides, so an item that this click disables, // removes or moves has lost focus by then, and `Popover` does not move lost focus. // Focus that the item's handler moved elsewhere stays. const trigger = triggerRef.current; const activeElement = trigger === null || trigger === void 0 ? void 0 : trigger.ownerDocument.activeElement; if (trigger !== null && trigger !== void 0 && trigger.isConnected && (activeElement === trigger.ownerDocument.body || (_popoverRef$current = popoverRef.current) !== null && _popoverRef$current !== void 0 && _popoverRef$current.contains(activeElement !== null && activeElement !== void 0 ? activeElement : null))) { trigger.focus({ preventScroll: true }); } closeMenu({ event: e.nativeEvent }); } }, [closeMenu]); const ariaAttributes = getAriaForTrigger({ role: 'menu', isOpen: isLocalOpen, popoverId }); /** * Custom trigger consumers historically receive a callback ref, * and their code assumes it is one. * Using this wrapper for compatibility... */ const setTriggerRef = useCallback(node => { triggerRef.current = node; }, []); const renderTrigger = () => { if (typeof trigger === 'function') { return /*#__PURE__*/React.createElement(DropdownTriggerContext.Provider, { value: true }, trigger({ ...ariaAttributes, onFocus: bindFocus.onFocus, onBlur: bindFocus.onBlur, triggerRef: setTriggerRef, isSelected: isLocalOpen, onClick: handleTriggerClicked, testId: testId && `${testId}--trigger` })); } return /*#__PURE__*/React.createElement(Button, _extends({ onFocus: bindFocus.onFocus, onBlur: bindFocus.onBlur, ref: setTriggerRef }, ariaAttributes, { isSelected: isLocalOpen, iconAfter: iconProps => /*#__PURE__*/React.createElement(ExpandIcon, _extends({}, iconProps, { size: "small" })), onClick: handleTriggerClicked, testId: testId && `${testId}--trigger`, "aria-label": label, interactionName: interactionName }), trigger); }; if (fg('platform-dst-new-menu')) { var _ref; return /*#__PURE__*/React.createElement(SelectionStore, null, renderTrigger(), /*#__PURE__*/React.createElement(Popover, { ref: popoverRef, id: popoverId, role: "menu", label: (_ref = menuLabel !== null && menuLabel !== void 0 ? menuLabel : label) !== null && _ref !== void 0 ? _ref : typeof trigger === 'string' ? trigger : 'Menu', isOpen: isLocalOpen, mode: "manual", onClose: handleOnClose, shouldAnimate: true, placement: topLayerPlacement, testId: testId && `${testId}--content` }, /*#__PURE__*/React.createElement(PopoverSurface, null, /*#__PURE__*/React.createElement("div", { onClick: handleMenuClick, "data-testid": testId && `${testId}--menu-wrapper--menu-group`, className: ax([styles.newWrapper, styles.height, !shouldFitContainer && ""]) }, isLoading ? /*#__PURE__*/React.createElement(LoadingIndicator, { statusLabel: statusLabel, testId: testId && `${testId}--menu-wrapper--loading-indicator` }) : children)))); } return /*#__PURE__*/React.createElement(SelectionStore, null, renderTrigger(), /*#__PURE__*/React.createElement(Popover, { ref: setPopoverRef, id: popoverId, role: "menu", label: (_ref2 = menuLabel !== null && menuLabel !== void 0 ? menuLabel : label) !== null && _ref2 !== void 0 ? _ref2 : typeof trigger === 'string' ? trigger : 'Menu', isOpen: isLocalOpen, mode: "manual", onClose: handleOnClose, shouldAnimate: true, placement: topLayerPlacement, testId: testId && `${testId}--content` }, /*#__PURE__*/React.createElement(PopoverSurface, null, /*#__PURE__*/React.createElement(MenuGroup, { maxHeight: MAX_HEIGHT, maxWidth: shouldFitContainer ? undefined : MAX_WIDTH, onClick: handleMenuClick, spacing: oldSpacing, testId: testId && `${testId}--menu-wrapper--menu-group` }, isLoading ? /*#__PURE__*/React.createElement(LoadingIndicator, { statusLabel: statusLabel, testId: testId && `${testId}--menu-wrapper--loading-indicator` }) : children)))); } export default DropdownMenuTopLayer;