UNPKG

@wordpress/components

Version:
226 lines (225 loc) • 9.17 kB
import clsx from "clsx"; import { createPortal, forwardRef, useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from "@wordpress/element"; import { useConstrainedTabbing, useFocusOnMount, useFocusReturn, useInstanceId, useMergeRefs, useRefEffect } from "@wordpress/compose"; import { __ } from "@wordpress/i18n"; import { close } from "@wordpress/icons"; import { focus, getScrollContainer } from "@wordpress/dom"; import { withIgnoreIMEEvents } from "@wordpress/keycodes"; import * as ariaHelper from "./aria-helper.mjs"; import Button from "../button/index.mjs"; import StyleProvider from "../style-provider/index.mjs"; import { Spacer } from "../spacer/index.mjs"; import { useModalExitAnimation } from "./use-modal-exit-animation.mjs"; import { ModalContext } from "./context.mjs"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; // packages/components/src/modal/index.tsx const bodyOpenClasses = /* @__PURE__ */ new Map(); function UnforwardedModal(props, forwardedRef) { const { bodyOpenClassName = "modal-open", role = "dialog", title = null, focusOnMount = true, shouldCloseOnEsc = true, shouldCloseOnClickOutside = true, isDismissible = true, aria = { labelledby: void 0, describedby: void 0 }, onRequestClose, icon, closeButtonLabel, children, style, overlayClassName: overlayClassnameProp, className, contentLabel, onKeyDown, isFullScreen = false, size, headerActions = null, __experimentalHideHeader = false } = props; const ref = useRef(null); const instanceId = useInstanceId(Modal); const headingId = title ? `components-modal-header-${instanceId}` : aria.labelledby; const dialogLabel = contentLabel ?? (__experimentalHideHeader && title ? title : void 0); const shouldFocusContent = focusOnMount === "firstContentElement"; const focusOnMountRef = useFocusOnMount(shouldFocusContent ? false : focusOnMount); const constrainedTabbingRef = useConstrainedTabbing(); const focusReturnRef = useFocusReturn(); const contentRef = useRef(null); const childrenContainerRef = useRef(null); const focusContentRef = useRefEffect((node) => { if (!shouldFocusContent || node.contains(node.ownerDocument.activeElement)) return; const timerId = setTimeout(() => { const childrenContainer = childrenContainerRef.current; (childrenContainer && focus.tabbable.find(childrenContainer)[0] || focus.tabbable.find(node)[0] || node).focus({ preventScroll: true }); }, 0); return () => clearTimeout(timerId); }, [shouldFocusContent]); const [hasScrolledContent, setHasScrolledContent] = useState(false); const [hasScrollableContent, setHasScrollableContent] = useState(false); let sizeClass; if (isFullScreen || size === "fill") sizeClass = "is-full-screen"; else if (size) sizeClass = `has-size-${size}`; const isContentScrollable = useCallback(() => { if (!contentRef.current) return; const closestScrollContainer = getScrollContainer(contentRef.current); if (contentRef.current === closestScrollContainer) setHasScrollableContent(true); else setHasScrollableContent(false); }, [contentRef]); useEffect(() => { const modalElement = ref.current; ariaHelper.modalize(modalElement); return () => ariaHelper.unmodalize(modalElement); }, []); const onRequestCloseRef = useRef(void 0); useEffect(() => { onRequestCloseRef.current = onRequestClose; }, [onRequestClose]); const dismissers = useContext(ModalContext); const [nestedDismissers] = useState(() => /* @__PURE__ */ new Set()); useEffect(() => { dismissers.add(onRequestCloseRef); for (const dismisser of dismissers) if (dismisser !== onRequestCloseRef) dismisser.current?.(); return () => { for (const dismisser of nestedDismissers) dismisser.current?.(); dismissers.delete(onRequestCloseRef); }; }, [dismissers, nestedDismissers]); useEffect(() => { const theClass = bodyOpenClassName; const oneMore = 1 + (bodyOpenClasses.get(theClass) ?? 0); bodyOpenClasses.set(theClass, oneMore); document.body.classList.add(bodyOpenClassName); return () => { const oneLess = bodyOpenClasses.get(theClass) - 1; if (oneLess === 0) { document.body.classList.remove(theClass); bodyOpenClasses.delete(theClass); } else bodyOpenClasses.set(theClass, oneLess); }; }, [bodyOpenClassName]); const { closeModal, frameRef, overlayClassname } = useModalExitAnimation(); 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 (shouldCloseOnEsc && (event.code === "Escape" || event.key === "Escape") && !event.defaultPrevented) { event.preventDefault(); event.stopPropagation(); closeModal().then(() => onRequestClose(event)); } } const onContentContainerScroll = useCallback((e) => { const scrollY = e?.currentTarget?.scrollTop ?? -1; if (!hasScrolledContent && scrollY > 0) setHasScrolledContent(true); else if (hasScrolledContent && scrollY <= 0) setHasScrolledContent(false); }, [hasScrolledContent]); let pressTarget = null; const modal = /* @__PURE__ */ jsx("div", { ref: useMergeRefs([ref, forwardedRef]), className: clsx("components-modal__screen-overlay", overlayClassname, overlayClassnameProp), onKeyDown: withIgnoreIMEEvents(handleEscapeKeyDown), ...shouldCloseOnClickOutside ? { onPointerDown: (event) => { if (event.target === event.currentTarget) { pressTarget = event.target; event.preventDefault(); } }, onPointerUp: ({ target, button }) => { const isSameTarget = target === pressTarget; pressTarget = null; if (button === 0 && isSameTarget) closeModal().then(() => onRequestClose()); } } : {}, children: /* @__PURE__ */ jsx(StyleProvider, { document, children: /* @__PURE__ */ jsx("div", { className: clsx("components-modal__frame", sizeClass, className), style, ref: useMergeRefs([ frameRef, constrainedTabbingRef, focusReturnRef, shouldFocusContent ? focusContentRef : focusOnMountRef ]), role, "aria-label": dialogLabel, "aria-labelledby": dialogLabel ? void 0 : headingId, "aria-describedby": aria.describedby, tabIndex: -1, onKeyDown, children: /* @__PURE__ */ jsxs("div", { className: clsx("components-modal__content", { "hide-header": __experimentalHideHeader, "is-scrollable": hasScrollableContent, "has-scrolled-content": hasScrolledContent }), role: "document", onScroll: onContentContainerScroll, ref: contentRef, "aria-label": hasScrollableContent ? __("Scrollable section") : void 0, tabIndex: hasScrollableContent ? 0 : void 0, children: [!__experimentalHideHeader && /* @__PURE__ */ jsxs("div", { className: "components-modal__header", children: [ /* @__PURE__ */ jsxs("div", { className: "components-modal__header-heading-container", children: [icon && /* @__PURE__ */ jsx("span", { className: "components-modal__icon-container", "aria-hidden": true, children: icon }), title && /* @__PURE__ */ jsx("h1", { id: headingId, className: "components-modal__header-heading", children: title })] }), headerActions, isDismissible && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Spacer, { marginBottom: 0, marginLeft: 2 }), /* @__PURE__ */ jsx(Button, { size: "compact", onClick: (event) => closeModal().then(() => onRequestClose(event)), icon: close, label: closeButtonLabel || __("Close") })] }) ] }), /* @__PURE__ */ jsx("div", { ref: childrenContainerRef, className: "components-modal__children-container", children })] }) }) }) }); return createPortal(/* @__PURE__ */ jsx(ModalContext.Provider, { value: nestedDismissers, children: modal }), 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 = forwardRef(UnforwardedModal); Modal.displayName = "Modal"; export { Modal, Modal as default }; //# sourceMappingURL=index.mjs.map