@carbon/ibm-products
Version:
Carbon for IBM Products
63 lines (61 loc) • 1.85 kB
JavaScript
/**
* Copyright IBM Corp. 2020, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { pkg } from "../../settings.js";
import { useIsomorphicEffect } from "../../global/js/hooks/useIsomorphicEffect.js";
import { useCallback, useState } from "react";
//#region src/components/Tearsheet/usePresence.ts
/**
* Copyright IBM Corp. 2025
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const usePresence = (ref, isOpen) => {
const [exitState, setExitState] = useState(isOpen ? "idle" : "finished");
const isExiting = exitState === "active";
if (!isOpen && exitState === "idle") setExitState("active");
if (isOpen && exitState !== "idle") setExitState("idle");
const handleAnimationEnd = useCallback(() => {
setExitState("finished");
}, []);
useIsomorphicEffect(() => {
if (!ref.current || !isExiting) return;
if (!("getAnimations" in ref.current)) {
handleAnimationEnd();
return;
}
const animations = ref.current.getAnimations({ subtree: true }).filter((animation) => animation instanceof CSSAnimation && animation.animationName.startsWith(`${pkg.prefix}`));
if (!animations.length) {
handleAnimationEnd();
return;
}
let cancelled = false;
Promise.all(animations.map((animation) => animation.finished)).finally(() => {
if (cancelled) return;
handleAnimationEnd();
});
return () => {
cancelled = true;
};
}, [
ref,
isExiting,
handleAnimationEnd
]);
return {
/**
* Indicates whether the ref object is supposed to be mounted
*/
isPresent: isOpen || exitState !== "finished",
/**
* Indicates whether the ref object is currently exiting
*/
isExiting
};
};
//#endregion
export { usePresence };