UNPKG

@wordpress/components

Version:
246 lines (211 loc) 9.2 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.Modal = void 0; var _element = require("@wordpress/element"); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _classnames = _interopRequireDefault(require("classnames")); var _compose = require("@wordpress/compose"); var _i18n = require("@wordpress/i18n"); var _icons = require("@wordpress/icons"); var _dom = require("@wordpress/dom"); var ariaHelper = _interopRequireWildcard(require("./aria-helper")); var _button = _interopRequireDefault(require("../button")); var _styleProvider = _interopRequireDefault(require("../style-provider")); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * External dependencies */ /** * WordPress dependencies */ /** * Internal dependencies */ // Used to count the number of open modals. let openModalCount = 0; function UnforwardedModal(props, forwardedRef) { const { bodyOpenClassName = 'modal-open', role = 'dialog', title = null, focusOnMount = true, shouldCloseOnEsc = true, shouldCloseOnClickOutside = true, isDismissible = true, /* Accessibility. */ aria = { labelledby: undefined, describedby: undefined }, onRequestClose, icon, closeButtonLabel, children, style, overlayClassName, className, contentLabel, onKeyDown, isFullScreen = false, __experimentalHideHeader = false } = props; const ref = (0, _element.useRef)(); const instanceId = (0, _compose.useInstanceId)(Modal); const headingId = title ? `components-modal-header-${instanceId}` : aria.labelledby; const focusOnMountRef = (0, _compose.useFocusOnMount)(focusOnMount); const constrainedTabbingRef = (0, _compose.useConstrainedTabbing)(); const focusReturnRef = (0, _compose.useFocusReturn)(); const focusOutsideProps = (0, _compose.__experimentalUseFocusOutside)(onRequestClose); const contentRef = (0, _element.useRef)(null); const childrenContainerRef = (0, _element.useRef)(null); const [hasScrolledContent, setHasScrolledContent] = (0, _element.useState)(false); const [hasScrollableContent, setHasScrollableContent] = (0, _element.useState)(false); // Determines whether the Modal content is scrollable and updates the state. const isContentScrollable = (0, _element.useCallback)(() => { if (!contentRef.current) { return; } const closestScrollContainer = (0, _dom.getScrollContainer)(contentRef.current); if (contentRef.current === closestScrollContainer) { setHasScrollableContent(true); } else { setHasScrollableContent(false); } }, [contentRef]); (0, _element.useEffect)(() => { openModalCount++; if (openModalCount === 1) { ariaHelper.hideApp(ref.current); document.body.classList.add(bodyOpenClassName); } return () => { openModalCount--; if (openModalCount === 0) { document.body.classList.remove(bodyOpenClassName); ariaHelper.showApp(); } }; }, [bodyOpenClassName]); // Calls the isContentScrollable callback when the Modal children container resizes. (0, _element.useLayoutEffect)(() => { if (!window.ResizeObserver || !childrenContainerRef.current) { return; } const resizeObserver = new ResizeObserver(isContentScrollable); resizeObserver.observe(childrenContainerRef.current); isContentScrollable(); return () => { resizeObserver.disconnect(); }; }, [isContentScrollable, childrenContainerRef]); function handleEscapeKeyDown(event) { if ( // Ignore keydowns from IMEs event.nativeEvent.isComposing || // Workaround for Mac Safari where the final Enter/Backspace of an IME composition // is `isComposing=false`, even though it's technically still part of the composition. // These can only be detected by keyCode. event.keyCode === 229) { return; } if (shouldCloseOnEsc && event.code === 'Escape' && !event.defaultPrevented) { event.preventDefault(); if (onRequestClose) { onRequestClose(event); } } } const onContentContainerScroll = (0, _element.useCallback)(e => { var _e$currentTarget$scro, _e$currentTarget; const scrollY = (_e$currentTarget$scro = e === null || e === void 0 ? void 0 : (_e$currentTarget = e.currentTarget) === null || _e$currentTarget === void 0 ? void 0 : _e$currentTarget.scrollTop) !== null && _e$currentTarget$scro !== void 0 ? _e$currentTarget$scro : -1; if (!hasScrolledContent && scrollY > 0) { setHasScrolledContent(true); } else if (hasScrolledContent && scrollY <= 0) { setHasScrolledContent(false); } }, [hasScrolledContent]); return (0, _element.createPortal)( // eslint-disable-next-line jsx-a11y/no-static-element-interactions (0, _element.createElement)("div", { ref: (0, _compose.useMergeRefs)([ref, forwardedRef]), className: (0, _classnames.default)('components-modal__screen-overlay', overlayClassName), onKeyDown: handleEscapeKeyDown }, (0, _element.createElement)(_styleProvider.default, { document: document }, (0, _element.createElement)("div", (0, _extends2.default)({ className: (0, _classnames.default)('components-modal__frame', className, { 'is-full-screen': isFullScreen }), style: style, ref: (0, _compose.useMergeRefs)([constrainedTabbingRef, focusReturnRef, focusOnMountRef]), role: role, "aria-label": contentLabel, "aria-labelledby": contentLabel ? undefined : headingId, "aria-describedby": aria.describedby, tabIndex: -1 }, shouldCloseOnClickOutside ? focusOutsideProps : {}, { onKeyDown: onKeyDown }), (0, _element.createElement)("div", { className: (0, _classnames.default)('components-modal__content', { 'hide-header': __experimentalHideHeader, 'is-scrollable': hasScrollableContent, 'has-scrolled-content': hasScrolledContent }), role: "document", onScroll: onContentContainerScroll, ref: contentRef, "aria-label": hasScrollableContent ? (0, _i18n.__)('Scrollable section') : undefined, tabIndex: hasScrollableContent ? 0 : undefined }, !__experimentalHideHeader && (0, _element.createElement)("div", { className: "components-modal__header" }, (0, _element.createElement)("div", { className: "components-modal__header-heading-container" }, icon && (0, _element.createElement)("span", { className: "components-modal__icon-container", "aria-hidden": true }, icon), title && (0, _element.createElement)("h1", { id: headingId, className: "components-modal__header-heading" }, title)), isDismissible && (0, _element.createElement)(_button.default, { onClick: onRequestClose, icon: _icons.close, label: closeButtonLabel || (0, _i18n.__)('Close') })), (0, _element.createElement)("div", { ref: childrenContainerRef }, children))))), document.body); } /** * Modals give users information and choices related to a task they’re trying to * accomplish. They can contain critical information, require decisions, or * involve multiple tasks. * * ```jsx * import { Button, Modal } from '@wordpress/components'; * import { useState } from '@wordpress/element'; * * const MyModal = () => { * const [ isOpen, setOpen ] = useState( false ); * const openModal = () => setOpen( true ); * const closeModal = () => setOpen( false ); * * return ( * <> * <Button variant="secondary" onClick={ openModal }> * Open Modal * </Button> * { isOpen && ( * <Modal title="This is my modal" onRequestClose={ closeModal }> * <Button variant="secondary" onClick={ closeModal }> * My custom close button * </Button> * </Modal> * ) } * </> * ); * }; * ``` */ const Modal = (0, _element.forwardRef)(UnforwardedModal); exports.Modal = Modal; var _default = Modal; exports.default = _default; //# sourceMappingURL=index.js.map