UNPKG

@atlaskit/popup

Version:

A popup displays brief content in an overlay.

66 lines (64 loc) 3 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.useFocusManager = void 0; var _react = require("react"); var _focusTrap = _interopRequireDefault(require("focus-trap")); var _noop = _interopRequireDefault(require("@atlaskit/ds-lib/noop")); var _layering = require("@atlaskit/layering"); var _platformFeatureFlags = require("@atlaskit/platform-feature-flags"); var _useAnimationFrame2 = require("./utils/use-animation-frame"); var useFocusManager = exports.useFocusManager = function useFocusManager(_ref) { var initialFocusRef = _ref.initialFocusRef, popupRef = _ref.popupRef, triggerRef = _ref.triggerRef, autoFocus = _ref.autoFocus, shouldCloseOnTab = _ref.shouldCloseOnTab, shouldDisableFocusTrap = _ref.shouldDisableFocusTrap, shouldReturnFocus = _ref.shouldReturnFocus, shouldRenderToParent = _ref.shouldRenderToParent; var _useAnimationFrame = (0, _useAnimationFrame2.useAnimationFrame)(), requestFrame = _useAnimationFrame.requestFrame, cancelAllFrames = _useAnimationFrame.cancelAllFrames; var _useLayering = (0, _layering.useLayering)(), currentLevel = _useLayering.currentLevel; (0, _react.useEffect)(function () { if (!popupRef || shouldCloseOnTab) { return _noop.default; } if (shouldDisableFocusTrap && (0, _platformFeatureFlags.fg)('platform_dst_popup-disable-focuslock')) { var isDropdown = popupRef.matches('[id^=ds--dropdown--]'); var popups = document.querySelectorAll("[data-ds--level=\"".concat(currentLevel - 1, "\"]")); if (!(popups[popups.length - 1] && !shouldRenderToParent && isDropdown)) { // Plucking trigger & popup content container from the tab order so that // when we Shift+Tab, the focus moves to the element before trigger requestFrame(function () { triggerRef === null || triggerRef === void 0 || triggerRef.setAttribute('tabindex', '-1'); if (popupRef && autoFocus) { popupRef.setAttribute('tabindex', '-1'); } (initialFocusRef || popupRef).focus(); }); return _noop.default; } } var trapConfig = { clickOutsideDeactivates: true, escapeDeactivates: (0, _platformFeatureFlags.fg)('platform_dst_nested_escape') ? false : true, initialFocus: initialFocusRef || popupRef, fallbackFocus: popupRef, returnFocusOnDeactivate: shouldReturnFocus }; var focusTrap = (0, _focusTrap.default)(popupRef, trapConfig); // Wait for the popup to reposition itself before we focus requestFrame(function () { focusTrap.activate(); }); return function () { cancelAllFrames(); focusTrap.deactivate(); }; }, [popupRef, triggerRef, autoFocus, initialFocusRef, shouldCloseOnTab, shouldDisableFocusTrap, requestFrame, cancelAllFrames, shouldReturnFocus, shouldRenderToParent, currentLevel]); };