UNPKG

@blueprintjs/core

Version:

Core styles & components

487 lines 25.8 kB
"use strict"; /* * Copyright 2024 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Overlay2 = exports.OVERLAY2_DEFAULT_PROPS = void 0; const tslib_1 = require("tslib"); const classnames_1 = tslib_1.__importDefault(require("classnames")); const React = tslib_1.__importStar(require("react")); const react_transition_group_1 = require("react-transition-group"); const common_1 = require("../../common"); const errors_1 = require("../../common/errors"); const props_1 = require("../../common/props"); const utils_1 = require("../../common/utils"); const domUtils_1 = require("../../common/utils/domUtils"); const useOverlayStack_1 = require("../../hooks/overlays/useOverlayStack"); const usePrevious_1 = require("../../hooks/usePrevious"); const overlayUtils_1 = require("../overlay/overlayUtils"); const portal_1 = require("../portal/portal"); exports.OVERLAY2_DEFAULT_PROPS = { autoFocus: true, backdropProps: {}, canEscapeKeyClose: true, canOutsideClickClose: true, enforceFocus: true, hasBackdrop: true, isOpen: false, lazy: (0, domUtils_1.hasDOMEnvironment)(), shouldReturnFocusOnClose: true, transitionDuration: 300, transitionName: common_1.Classes.OVERLAY, usePortal: true, }; /** * Overlay2 component. * * @see https://blueprintjs.com/docs/#core/components/overlay2 */ exports.Overlay2 = React.forwardRef((props, forwardedRef) => { var _a, _b; const { autoFocus, backdropClassName, backdropProps, canEscapeKeyClose, canOutsideClickClose, childRef, childRefs, children, className, enforceFocus, hasBackdrop, isOpen, lazy, onClose, onClosed, onClosing, onOpened, onOpening, portalClassName, portalContainer, shouldReturnFocusOnClose, transitionDuration, transitionName, usePortal, } = props; useOverlay2Validation(props); const { closeOverlay, getLastOpened, getThisOverlayAndDescendants, openOverlay } = (0, useOverlayStack_1.useOverlayStack)(); const [isAutoFocusing, setIsAutoFocusing] = React.useState(false); const [hasEverOpened, setHasEverOpened] = React.useState(false); const lastActiveElementBeforeOpened = React.useRef(null); /** Ref for container element, containing all children and the backdrop */ const containerElement = React.useRef(null); /** Ref for backdrop element */ const backdropElement = React.useRef(null); /* An empty, keyboard-focusable div at the beginning of the Overlay content */ const startFocusTrapElement = React.useRef(null); /* An empty, keyboard-focusable div at the end of the Overlay content */ const endFocusTrapElement = React.useRef(null); /** * Locally-generated DOM ref for a singleton child element. * This is only used iff the user does not specify the `childRef` or `childRefs` props. */ const localChildRef = React.useRef(null); const bringFocusInsideOverlay = React.useCallback(() => { // always delay focus manipulation to just before repaint to prevent scroll jumping return requestAnimationFrame(() => { var _a; // container element may be undefined between component mounting and Portal rendering // activeElement may be undefined in some rare cases in IE const container = (0, utils_1.getRef)(containerElement); const activeElement = (0, utils_1.getActiveElement)(container); if (container == null || activeElement == null) { return; } // Overlay2 is guaranteed to be mounted here const isFocusOutsideModal = !container.contains(activeElement); if (isFocusOutsideModal) { (_a = (0, utils_1.getRef)(startFocusTrapElement)) === null || _a === void 0 ? void 0 : _a.focus({ preventScroll: true }); setIsAutoFocusing(false); } }); }, []); /** Unique ID for this overlay in the global stack */ const id = useOverlay2ID(); // N.B. use `null` here and not simply `undefined` because `useImperativeHandle` will set `null` on unmount, // and we need the following code to be resilient to that value. const instance = React.useRef(null); /** * When multiple `enforceFocus` Overlays are open, this event handler is only active for the most * recently opened one to avoid Overlays competing with each other for focus. */ const handleDocumentFocus = React.useCallback((e) => { // get the actual target even in the Shadow DOM // see https://github.com/palantir/blueprint/issues/4220 const eventTarget = e.composed ? e.composedPath()[0] : e.target; const container = (0, utils_1.getRef)(containerElement); if (container != null && eventTarget instanceof Node && !container.contains(eventTarget)) { // prevent default focus behavior (sometimes auto-scrolls the page) e.preventDefault(); e.stopImmediatePropagation(); bringFocusInsideOverlay(); } }, [bringFocusInsideOverlay]); // N.B. this listener is only kept attached when `isOpen={true}` and `canOutsideClickClose={true}` const handleDocumentMousedown = React.useCallback((e) => { // get the actual target even in the Shadow DOM // see https://github.com/palantir/blueprint/issues/4220 const eventTarget = (e.composed ? e.composedPath()[0] : e.target); const thisOverlayAndDescendants = getThisOverlayAndDescendants(id); const isClickInThisOverlayOrDescendant = thisOverlayAndDescendants.some(({ containerElement: containerRef }) => { // `elem` is the container of backdrop & content, so clicking directly on that container // should not count as being "inside" the overlay. const elem = (0, utils_1.getRef)(containerRef); return (elem === null || elem === void 0 ? void 0 : elem.contains(eventTarget)) && !elem.isSameNode(eventTarget); }); if (!isClickInThisOverlayOrDescendant) { // casting to any because this is a native event onClose === null || onClose === void 0 ? void 0 : onClose(e); } }, [getThisOverlayAndDescendants, id, onClose]); // send this instance's imperative handle to the the forwarded ref as well as our local ref const ref = React.useMemo(() => (0, common_1.mergeRefs)(forwardedRef, instance), [forwardedRef]); React.useImperativeHandle(ref, () => ({ bringFocusInsideOverlay, containerElement, handleDocumentFocus, handleDocumentMousedown, id, props: { autoFocus, enforceFocus, hasBackdrop, usePortal, }, }), [ autoFocus, bringFocusInsideOverlay, enforceFocus, handleDocumentFocus, handleDocumentMousedown, hasBackdrop, id, usePortal, ]); const handleContainerKeyDown = React.useCallback((e) => { if (e.key === "Escape" && canEscapeKeyClose) { onClose === null || onClose === void 0 ? void 0 : onClose(e); // prevent other overlays from closing e.stopPropagation(); // prevent browser-specific escape key behavior (Safari exits fullscreen) e.preventDefault(); } }, [canEscapeKeyClose, onClose]); const overlayWillOpen = React.useCallback(() => { if (instance.current == null) { return; } const lastOpenedOverlay = getLastOpened(); if ((lastOpenedOverlay === null || lastOpenedOverlay === void 0 ? void 0 : lastOpenedOverlay.handleDocumentFocus) !== undefined) { document.removeEventListener("focus", lastOpenedOverlay.handleDocumentFocus, /* useCapture */ true); } openOverlay(instance.current); if (autoFocus) { setIsAutoFocusing(true); bringFocusInsideOverlay(); } (0, utils_1.setRef)(lastActiveElementBeforeOpened, (0, utils_1.getActiveElement)((0, utils_1.getRef)(containerElement))); }, [autoFocus, bringFocusInsideOverlay, getLastOpened, openOverlay]); const overlayWillClose = React.useCallback(() => { var _a; document.removeEventListener("focus", handleDocumentFocus, /* useCapture */ true); document.removeEventListener("mousedown", handleDocumentMousedown); // N.B. `instance.current` may be null at this point if we are cleaning up an open overlay during the unmount phase // (this is common, for example, with context menu's singleton `showContextMenu` / `hideContextMenu` imperative APIs). closeOverlay(id); const lastOpenedOverlay = getLastOpened(); if (lastOpenedOverlay !== undefined) { // Only bring focus back to last overlay if it had autoFocus _and_ enforceFocus enabled. // If `autoFocus={false}`, it's likely that the overlay never received focus in the first place, // so it would be surprising for us to send it there. See https://github.com/palantir/blueprint/issues/4921 if (lastOpenedOverlay.props.autoFocus && lastOpenedOverlay.props.enforceFocus) { (_a = lastOpenedOverlay.bringFocusInsideOverlay) === null || _a === void 0 ? void 0 : _a.call(lastOpenedOverlay); if (lastOpenedOverlay.handleDocumentFocus !== undefined) { document.addEventListener("focus", lastOpenedOverlay.handleDocumentFocus, /* useCapture */ true); } } } }, [closeOverlay, getLastOpened, handleDocumentFocus, handleDocumentMousedown, id]); const prevIsOpen = (_a = (0, usePrevious_1.usePrevious)(isOpen)) !== null && _a !== void 0 ? _a : false; React.useEffect(() => { if (isOpen) { setHasEverOpened(true); } if (!prevIsOpen && isOpen) { // just opened overlayWillOpen(); } if (prevIsOpen && !isOpen) { // just closed overlayWillClose(); } }, [isOpen, overlayWillOpen, overlayWillClose, prevIsOpen]); // Important: clean up old document-level event listeners if their memoized values change (this is rare, but // may happen, for example, if a user forgets to use `React.useCallback` in the `props.onClose` value). // Otherwise, we will lose the reference to those values and create a memory leak since we won't be able // to successfully detach them inside overlayWillClose. React.useEffect(() => { if (!isOpen || !(canOutsideClickClose && !hasBackdrop)) { return; } document.addEventListener("mousedown", handleDocumentMousedown); return () => { document.removeEventListener("mousedown", handleDocumentMousedown); }; }, [handleDocumentMousedown, isOpen, canOutsideClickClose, hasBackdrop]); React.useEffect(() => { if (!isOpen || !enforceFocus) { return; } // Focus events do not bubble, but setting useCapture allows us to listen in and execute // our handler before all others document.addEventListener("focus", handleDocumentFocus, /* useCapture */ true); return () => { document.removeEventListener("focus", handleDocumentFocus, /* useCapture */ true); }; }, [handleDocumentFocus, enforceFocus, isOpen]); const overlayWillCloseRef = React.useRef(overlayWillClose); overlayWillCloseRef.current = overlayWillClose; React.useEffect(() => { // run cleanup code once on unmount, ensuring we call the most recent overlayWillClose callback // by storing in a ref and keeping up to date return () => { overlayWillCloseRef.current(); }; }, []); const handleTransitionExited = React.useCallback((node) => { const lastActiveElement = (0, utils_1.getRef)(lastActiveElementBeforeOpened); if (shouldReturnFocusOnClose && lastActiveElement instanceof HTMLElement) { lastActiveElement.focus(); } onClosed === null || onClosed === void 0 ? void 0 : onClosed(node); }, [onClosed, shouldReturnFocusOnClose]); // N.B. CSSTransition requires this callback to be defined, even if it's unused. const handleTransitionAddEnd = React.useCallback(() => { // no-op }, []); /** * Gets the relevant DOM ref for a child element using the `childRef` or `childRefs` props (if possible). * This ref is necessary for `CSSTransition` to work in React 18 without relying on `ReactDOM.findDOMNode`. * * Returns `undefined` if the user did not specify either of those props. In those cases, we use the ref we * have locally generated and expect that the user _did not_ specify their own `ref` on the child element * (it will get clobbered / overriden). * * @see https://reactcommunity.org/react-transition-group/css-transition */ const getUserChildRef = React.useCallback((child) => { if (childRef != null) { return childRef; } else if (childRefs != null) { const key = child.key; if (key == null) { if (!(0, utils_1.isNodeEnv)("production")) { console.error(errors_1.OVERLAY_CHILD_REQUIRES_KEY); } return undefined; } return childRefs[key]; } return undefined; }, [childRef, childRefs]); const maybeRenderChild = React.useCallback((child) => { if (child == null || (0, utils_1.isEmptyString)(child)) { return null; } // decorate the child with a few injected props const userChildRef = getUserChildRef(child); const childProps = (0, utils_1.isReactElement)(child) ? child.props : {}; // if the child is a string, number, or fragment, it will be wrapped in a <span> element const decoratedChild = (0, utils_1.ensureElement)(child, "span", { className: (0, classnames_1.default)(childProps.className, common_1.Classes.OVERLAY_CONTENT), // IMPORTANT: only inject our ref if the user didn't specify childRef or childRefs already. Otherwise, // we risk clobbering the user's ref (which we cannot inspect here while cloning/decorating the child). ref: userChildRef === undefined ? localChildRef : undefined, tabIndex: enforceFocus || autoFocus ? 0 : undefined, }); const resolvedChildRef = userChildRef !== null && userChildRef !== void 0 ? userChildRef : localChildRef; return (React.createElement(react_transition_group_1.CSSTransition, { addEndListener: handleTransitionAddEnd, classNames: transitionName, // HACKHACK: CSSTransition types are slightly incompatible with React types here. // React prefers `| null` but not `| undefined` for the ref value, while // CSSTransition _demands_ that `| undefined` be part of the element type. nodeRef: resolvedChildRef, onEntered: getLifecycleCallbackWithChildRef(onOpened, resolvedChildRef), onEntering: getLifecycleCallbackWithChildRef(onOpening, resolvedChildRef), onExited: getLifecycleCallbackWithChildRef(handleTransitionExited, resolvedChildRef), onExiting: getLifecycleCallbackWithChildRef(onClosing, resolvedChildRef), timeout: transitionDuration }, decoratedChild)); }, [ autoFocus, enforceFocus, getUserChildRef, handleTransitionAddEnd, handleTransitionExited, onClosing, onOpened, onOpening, transitionDuration, transitionName, ]); const handleBackdropMouseDown = React.useCallback((e) => { var _a; if (canOutsideClickClose) { onClose === null || onClose === void 0 ? void 0 : onClose(e); } if (enforceFocus) { bringFocusInsideOverlay(); } (_a = backdropProps === null || backdropProps === void 0 ? void 0 : backdropProps.onMouseDown) === null || _a === void 0 ? void 0 : _a.call(backdropProps, e); }, [backdropProps, bringFocusInsideOverlay, canOutsideClickClose, enforceFocus, onClose]); const renderDummyElement = React.useCallback((key, dummyElementProps) => (React.createElement(react_transition_group_1.CSSTransition, { addEndListener: handleTransitionAddEnd, classNames: transitionName, key: key, nodeRef: dummyElementProps.ref, timeout: transitionDuration, unmountOnExit: true }, React.createElement("div", { tabIndex: 0, ...dummyElementProps }))), [handleTransitionAddEnd, transitionDuration, transitionName]); /** * Ensures repeatedly pressing shift+tab keeps focus inside the Overlay. Moves focus to * the `endFocusTrapElement` or the first keyboard-focusable element in the Overlay (excluding * the `startFocusTrapElement`), depending on whether the element losing focus is inside the * Overlay. */ const handleStartFocusTrapElementFocus = React.useCallback((e) => { if (!enforceFocus || isAutoFocusing) { return; } // e.relatedTarget will not be defined if this was a programmatic focus event, as is the // case when we call this.bringFocusInsideOverlay() after a user clicked on the backdrop. // Otherwise, we're handling a user interaction, and we should wrap around to the last // element in this transition group. const container = (0, utils_1.getRef)(containerElement); const endFocusTrap = (0, utils_1.getRef)(endFocusTrapElement); if (e.relatedTarget != null && (container === null || container === void 0 ? void 0 : container.contains(e.relatedTarget)) && e.relatedTarget !== endFocusTrap) { endFocusTrap === null || endFocusTrap === void 0 ? void 0 : endFocusTrap.focus({ preventScroll: true }); } }, [enforceFocus, isAutoFocusing]); /** * Wrap around to the end of the dialog if `enforceFocus` is enabled. */ const handleStartFocusTrapElementKeyDown = React.useCallback((e) => { var _a; if (!enforceFocus) { return; } if (e.shiftKey && e.key === "Tab") { const lastFocusableElement = (0, overlayUtils_1.getKeyboardFocusableElements)(containerElement).pop(); if (lastFocusableElement != null) { lastFocusableElement.focus(); } else { (_a = (0, utils_1.getRef)(endFocusTrapElement)) === null || _a === void 0 ? void 0 : _a.focus({ preventScroll: true }); } } }, [enforceFocus]); /** * Ensures repeatedly pressing tab keeps focus inside the Overlay. Moves focus to the * `startFocusTrapElement` or the last keyboard-focusable element in the Overlay (excluding the * `startFocusTrapElement`), depending on whether the element losing focus is inside the * Overlay. */ const handleEndFocusTrapElementFocus = React.useCallback((e) => { var _a; // No need for this.props.enforceFocus check here because this element is only rendered // when that prop is true. // During user interactions, e.relatedTarget will be defined, and we should wrap around to the // "start focus trap" element. // Otherwise, we're handling a programmatic focus event, which can only happen after a user // presses shift+tab from the first focusable element in the overlay. const startFocusTrap = (0, utils_1.getRef)(startFocusTrapElement); if (e.relatedTarget != null && ((_a = (0, utils_1.getRef)(containerElement)) === null || _a === void 0 ? void 0 : _a.contains(e.relatedTarget)) && e.relatedTarget !== startFocusTrap) { const firstFocusableElement = (0, overlayUtils_1.getKeyboardFocusableElements)(containerElement).shift(); // ensure we don't re-focus an already active element by comparing against e.relatedTarget if (!isAutoFocusing && firstFocusableElement != null && firstFocusableElement !== e.relatedTarget) { firstFocusableElement.focus(); } else { startFocusTrap === null || startFocusTrap === void 0 ? void 0 : startFocusTrap.focus({ preventScroll: true }); } } else { const lastFocusableElement = (0, overlayUtils_1.getKeyboardFocusableElements)(containerElement).pop(); if (lastFocusableElement != null) { lastFocusableElement.focus(); } else { // Keeps focus within Overlay even if there are no keyboard-focusable children startFocusTrap === null || startFocusTrap === void 0 ? void 0 : startFocusTrap.focus({ preventScroll: true }); } } }, [isAutoFocusing]); const maybeBackdrop = React.useMemo(() => hasBackdrop && isOpen ? (React.createElement(react_transition_group_1.CSSTransition, { classNames: transitionName, key: "__backdrop", nodeRef: backdropElement, timeout: transitionDuration, addEndListener: handleTransitionAddEnd }, React.createElement("div", { ...backdropProps, className: (0, classnames_1.default)(common_1.Classes.OVERLAY_BACKDROP, backdropClassName, backdropProps === null || backdropProps === void 0 ? void 0 : backdropProps.className), onMouseDown: handleBackdropMouseDown, ref: backdropElement }))) : null, [ backdropClassName, backdropProps, handleBackdropMouseDown, handleTransitionAddEnd, hasBackdrop, isOpen, transitionDuration, transitionName, ]); // no reason to render anything at all if we're being truly lazy if (lazy && !hasEverOpened) { return null; } // TransitionGroup types require single array of children; does not support nested arrays. // So we must collapse backdrop and children into one array, and every item must be wrapped in a // Transition element (no ReactText allowed). const childrenWithTransitions = isOpen ? (_b = React.Children.map(children, maybeRenderChild)) !== null && _b !== void 0 ? _b : [] : []; // const maybeBackdrop = maybeRenderBackdrop(); if (maybeBackdrop !== null) { childrenWithTransitions.unshift(maybeBackdrop); } if (isOpen && (autoFocus || enforceFocus) && childrenWithTransitions.length > 0) { childrenWithTransitions.unshift(renderDummyElement("__start", { className: common_1.Classes.OVERLAY_START_FOCUS_TRAP, onFocus: handleStartFocusTrapElementFocus, onKeyDown: handleStartFocusTrapElementKeyDown, ref: startFocusTrapElement, })); if (enforceFocus) { childrenWithTransitions.push(renderDummyElement("__end", { className: common_1.Classes.OVERLAY_END_FOCUS_TRAP, onFocus: handleEndFocusTrapElementFocus, ref: endFocusTrapElement, })); } } const transitionGroup = (React.createElement("div", { "aria-live": "polite", className: (0, classnames_1.default)(common_1.Classes.OVERLAY, { [common_1.Classes.OVERLAY_OPEN]: isOpen, [common_1.Classes.OVERLAY_INLINE]: !usePortal, }, className), onKeyDown: handleContainerKeyDown, ref: containerElement }, React.createElement(react_transition_group_1.TransitionGroup, { appear: true, component: null }, childrenWithTransitions))); if (usePortal) { return (React.createElement(portal_1.Portal, { className: portalClassName, container: portalContainer }, transitionGroup)); } else { return transitionGroup; } }); // eslint-disable-next-line @typescript-eslint/no-deprecated exports.Overlay2.defaultProps = exports.OVERLAY2_DEFAULT_PROPS; exports.Overlay2.displayName = `${props_1.DISPLAYNAME_PREFIX}.Overlay2`; function useOverlay2Validation({ childRef, childRefs, children }) { const numChildren = React.Children.count(children); React.useEffect(() => { if ((0, utils_1.isNodeEnv)("production")) { return; } if (childRef != null && childRefs != null) { console.error(errors_1.OVERLAY_CHILD_REF_AND_REFS_MUTEX); } if (numChildren > 1 && childRefs == null) { console.error(errors_1.OVERLAY_WITH_MULTIPLE_CHILDREN_REQUIRES_CHILD_REFS); } }, [childRef, childRefs, numChildren]); } /** * Generates a unique ID for a given Overlay which persists across the component's lifecycle. */ function useOverlay2ID() { const id = React.useId(); return `${exports.Overlay2.displayName}-${id}`; } // N.B. the `onExiting` callback is not provided with the `node` argument as suggested in CSSTransition types since // we are using the `nodeRef` prop, so we must inject it dynamically. function getLifecycleCallbackWithChildRef(callback, childRef) { return () => { if ((childRef === null || childRef === void 0 ? void 0 : childRef.current) != null) { callback === null || callback === void 0 ? void 0 : callback(childRef.current); } }; } //# sourceMappingURL=overlay2.js.map