UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

137 lines 6.32 kB
"use strict"; "use client"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useAnimationsFinished = useAnimationsFinished; const react_1 = __importStar(require("react")); const react_dom_1 = __importDefault(require("react-dom")); const helpers_1 = require("../helpers"); const useEventCallback_1 = require("./useEventCallback"); /** * Returns a stable function that, when invoked, waits for all current CSS/Web Animations * on a target element (and its subtree) to finish before executing a callback. * * Why: * - Coordinate logic (unmount, focus restore, measuring) after exit / enter animations. * - Avoid `animationend` event bookkeeping across multiple animations / nested elements. * - Batch detection using `requestAnimationFrame` so freshly-applied animations are discoverable. * * Mechanics: * 1. Resolves the concrete `HTMLElement` (direct element or from ref) – early no-op if missing. * 2. If `getAnimations` is unsupported or animations are globally disabled (`AKSEL_NO_EXIT_ANIMATIONS`), * runs the callback immediately. * 3. Schedules a frame so style/animation changes applied this render are committed. * 4. Optionally schedules an additional frame (`waitForNextTick=true`) to catch animations that * start only after layout (e.g. when an `open` class triggers the animation). * 5. Captures all current animations, waits on their `.finished` promises (using `Promise.allSettled` * so rejections don't block), then `flushSync` executes the callback (ensures React state updates * inside run before the browser paints the next frame). * 6. If an `AbortSignal` aborts while waiting, it silently cancels execution. * * @param elementOrRef HTMLElement or ref to observe. * @param waitForNextTick If true, waits an extra frame to ensure enter animations are detectable. * @returns Stable function (identity preserved) accepting (fn, abortSignal?). */ function useAnimationsFinished(elementOrRef, waitForNextTick = false) { const rootFrameRef = react_1.default.useRef(null); const nestedFrameRef = react_1.default.useRef(null); const cancelScheduled = (0, react_1.useCallback)(() => { for (const ref of [rootFrameRef, nestedFrameRef]) { if (ref.current !== null) { cancelAnimationFrame(ref.current); ref.current = null; } } }, []); /* Unmount cleanup */ (0, react_1.useEffect)(() => { return () => cancelScheduled(); }, [cancelScheduled]); return (0, useEventCallback_1.useEventCallback)(( /** * A function to execute once all animations have finished. */ fnToExecute, /** * An optional [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that * can be used to abort `fnToExecute` before all the animations have finished. * @default null */ signal = null) => { // Cancel any in-flight scheduling from a previous invocation (next-frame debounce semantics) cancelScheduled(); const element = (0, helpers_1.resolveRef)(elementOrRef); if (element == null) { return; } // Fast path: no Web Animations API support OR animations globally disabled. if (typeof element.getAnimations !== "function" || // Flag hook for test envs. globalThis.AKSEL_NO_EXIT_ANIMATIONS) { fnToExecute(); return; } rootFrameRef.current = requestAnimationFrame(() => { function exec() { if (!element) { return; } // Collect animations present at this moment; we don't continuously observe // if new animations start after these settle, caller should invoke again. Promise.allSettled(element.getAnimations().map((anim) => anim.finished)).then(() => { if (signal === null || signal === void 0 ? void 0 : signal.aborted) { return; } // Ensure any state updates inside the callback are flushed synchronously, // guaranteeing that dependent logic observes the current // tree rather than a stale in-progress update. react_dom_1.default.flushSync(fnToExecute); }); } // Some animations (e.g. triggered by a class applied this same frame) only // become observable after an extra frame; opt-in via flag. if (waitForNextTick) { nestedFrameRef.current = requestAnimationFrame(exec); } else { exec(); } }); }); } //# sourceMappingURL=useAnimationsFinished.js.map