/** * Enter animation for floating elements (fade + scale, 120ms). * * The animation class is removed on animationend: a retained `transform` * (even identity scale) makes the element the containing block for nested * absolutely-positioned popups, which breaks floating-ui positioning of * submenus rendered inside it. */ import type { Action } from 'svelte/action'; const ENTER_CLASS = 'popup-enter'; const PENDING_CLASS = 'popup-enter-pending'; const KEYFRAMES_NAME = 'popup-enter'; type GetAnchor = () => Element | undefined; const start = (popup: HTMLElement) => { popup.classList.add(ENTER_CLASS); popup.addEventListener('animationend', (event) => { if (event.target === popup && event.animationName === KEYFRAMES_NAME) { popup.classList.remove(ENTER_CLASS); popup.classList.remove(PENDING_CLASS); popup.style.transformOrigin = ''; } }); }; // Safety cap so a popup that never gets inline positioning still reveals. const POSITION_TIMEOUT_FRAMES = 20; const startAnchored = (popup: HTMLElement, getAnchor: GetAnchor) => { // Stay hidden until floating-ui has actually positioned the element // (Floating sets inline top/left once resolved), then anchor the scale // origin to the trigger's center and animate. PENDING is left on until // animationend: removing it in the same tick as adding the animation class // lets the browser paint one frame at the underlying opacity (1) before // the keyframes engage, which reads as a pre-animation flash. popup.classList.add(PENDING_CLASS); let frames = 0; const reveal = () => { frames += 1; const positioned = popup.style.top !== '' && popup.style.left !== ''; if (!positioned && frames < POSITION_TIMEOUT_FRAMES) { requestAnimationFrame(reveal); return; } const anchorRect = getAnchor()?.getBoundingClientRect(); const popupRect = popup.getBoundingClientRect(); if (anchorRect && popupRect.width > 0) { const originX = anchorRect.left + anchorRect.width / 2 - popupRect.left; const originY = anchorRect.top + anchorRect.height / 2 - popupRect.top; popup.style.transformOrigin = `${originX}px ${originY}px`; } start(popup); }; requestAnimationFrame(reveal); }; /** * Animate this element in. With an anchor getter, the scale origin is * measured from the anchor; without one, set a static origin at the call * site (e.g. Tailwind `origin-top-right`). */ export const popupEnter: Action = ( node, getAnchor ) => { if (getAnchor) { startAnchored(node, getAnchor); } else { start(node); } }; /** * Variant for floating elements rendered by a component we can't put an * action on (e.g. Floating). Place on an empty `display: contents` marker * inside the floating element; animates the marker's parent. */ export const popupEnterParent: Action = ( marker, getAnchor ) => { const popup = marker.parentElement; if (popup) { startAnchored(popup, getAnchor ?? (() => undefined)); } };