@wordpress/components
Version:
UI components for WordPress.
47 lines (46 loc) • 1.87 kB
JavaScript
import { useReducedMotion } from "@wordpress/compose";
import { useCallback, useRef, useState } from "@wordpress/element";
import warning from "@wordpress/warning";
// packages/components/src/modal/use-modal-exit-animation.ts
const EXIT_ANIMATION_NAME = "components-modal__disappear-animation";
function useModalExitAnimation() {
const frameRef = useRef(null);
const [isAnimatingOut, setIsAnimatingOut] = useState(false);
const isReducedMotion = useReducedMotion();
const closeModal = useCallback(() => new Promise((closeModalResolve) => {
const frameEl = frameRef.current;
if (isReducedMotion) {
closeModalResolve();
return;
}
if (!frameEl) {
warning("wp.components.Modal: the Modal component can't be closed with an exit animation because of a missing reference to the modal frame element.");
closeModalResolve();
return;
}
const animationDuration = Number.parseFloat(frameEl.ownerDocument.defaultView?.getComputedStyle(frameEl).animationDuration || "0") * 1e3;
let handleAnimationEnd;
const startAnimation = () => new Promise((animationResolve) => {
handleAnimationEnd = (e) => {
if (e.animationName === EXIT_ANIMATION_NAME) animationResolve();
};
frameEl.addEventListener("animationend", handleAnimationEnd);
setIsAnimatingOut(true);
});
const animationTimeout = () => new Promise((timeoutResolve) => {
setTimeout(() => timeoutResolve(), animationDuration * 1.2);
});
Promise.race([startAnimation(), animationTimeout()]).then(() => {
if (handleAnimationEnd) frameEl.removeEventListener("animationend", handleAnimationEnd);
setIsAnimatingOut(false);
closeModalResolve();
});
}), [isReducedMotion]);
return {
overlayClassname: isAnimatingOut ? "is-animating-out" : void 0,
frameRef,
closeModal
};
}
export { useModalExitAnimation };
//# sourceMappingURL=use-modal-exit-animation.mjs.map