import { computed, nextTick, ref, watch, type Ref } from "vue"; /** Phase markers drive source keyframes; Reka Presence still owns exit unmounting. */ export function useOverlayAnimation( open: Ref, element?: Ref, floating = false, ) { const entering = ref(open.value); watch( open, (value) => { entering.value = value; }, { flush: "sync" }, ); function onAnimationEnd(event: AnimationEvent) { if (event.target !== event.currentTarget || !open.value) return; const names = getComputedStyle(event.currentTarget as HTMLElement) .animationName.split(",") .map((s) => s.trim()); if (names.includes(event.animationName)) entering.value = false; } if (element) watch( [element, open], ([el], _, onCleanup) => { if (!el) return; let stale = false; const wrapper = el.parentElement; const check = () => { if (stale || !open.value || !entering.value) return; // Floating UI briefly suppresses animation while measuring. Wait for placement. if ( floating && wrapper?.hasAttribute("data-reka-popper-content-wrapper") && /translate\(0(?:px)?,\s*-200%\)/.test(wrapper.style.transform) ) return; const animation = getComputedStyle(el).animationName; if (!animation || animation === "none") entering.value = false; }; const observer = new MutationObserver(check); observer.observe(el, { attributes: true, attributeFilter: ["data-reduce-motion", "class", "style"], }); // Reduced motion can change on a theme/portal ancestor while an entrance // runs. A cancelled animation has no animationend to clear its marker. for ( let ancestor = el.parentElement; ancestor; ancestor = ancestor.parentElement ) observer.observe(ancestor, { attributes: true, attributeFilter: ["data-reduce-motion", "class", "style"], }); el.addEventListener("animationcancel", check); const media = el.ownerDocument.defaultView?.matchMedia?.( "(prefers-reduced-motion: reduce)", ); media?.addEventListener("change", check); void nextTick(check); onCleanup(() => { stale = true; observer.disconnect(); el.removeEventListener("animationcancel", check); media?.removeEventListener("change", check); }); }, { flush: "post" }, ); return { entering, exiting: computed(() => !open.value), onAnimationEnd }; }