UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

74 lines 2.66 kB
import React, { useEffect } from "react"; import { ownerDocument } from "../util/owner.js"; export const coordsAreInside = ({ clientX, clientY }, { left, top, right, bottom }) => { if (clientX < left || clientY < top) return false; if (clientX > right || clientY > bottom) return false; return true; }; export function getCloseHandler(modalRef, header, onBeforeClose) { if (header && header.closeButton === false) return undefined; if (onBeforeClose) { return () => { var _a; return onBeforeClose() !== false && ((_a = modalRef.current) === null || _a === void 0 ? void 0 : _a.close()); }; } return () => { var _a; return (_a = modalRef.current) === null || _a === void 0 ? void 0 : _a.close(); }; } function useIsModalOpen(modalRef) { const [isOpen, setIsOpen] = React.useState(false); useEffect(() => { if (!modalRef) { return; } setIsOpen(modalRef.open); const observer = new MutationObserver(() => { setIsOpen(modalRef.open); }); observer.observe(modalRef, { attributes: true, attributeFilter: ["open"], }); return () => { observer.disconnect(); }; }, [modalRef]); return isOpen; } export const BODY_CLASS_LEGACY = "navds-modal__document-body"; function useBodyScrollLock(modalRef, portalNode, isNested) { React.useEffect(() => { if (isNested) { return; } // We check both to avoid running this twice when not using portal if (!modalRef.current || !portalNode) { return; } const ownerDoc = ownerDocument(modalRef.current); // In case `open` is true initially if (modalRef.current.open) { ownerDoc.body.classList.add(BODY_CLASS_LEGACY); } const observer = new MutationObserver(() => { var _a; if ((_a = modalRef.current) === null || _a === void 0 ? void 0 : _a.open) { ownerDoc.body.classList.add(BODY_CLASS_LEGACY); } else { ownerDoc.body.classList.remove(BODY_CLASS_LEGACY); } }); observer.observe(modalRef.current, { attributes: true, attributeFilter: ["open"], }); return () => { observer.disconnect(); // In case modal is unmounted before it's closed ownerDoc.body.classList.remove(BODY_CLASS_LEGACY); }; }, [modalRef, portalNode, isNested]); } export { useIsModalOpen, useBodyScrollLock }; //# sourceMappingURL=ModalUtils.js.map