import type { MotionTargetMap, MotionTargetValue, } from "./_motion-state-options.ts"; import type { Transition } from "motion-dom"; import { animateSingleValue, motionValue, styleEffect, svgEffect, } from "motion-dom"; import { resolveTargetRecord } from "./_motion-state-options.ts"; import { noop } from "../utils/_noop.ts"; export type MotionValueInstance = ReturnType>; /** * Mutable MotionValue table currently connected to the DOM effect. */ export type RenderedMotionValues = Record; /** * Upstream per-value animation handle returned by `animateSingleValue()`. */ export type ValueAnimationControl = ReturnType; /** * Listener used by MotionState to observe aggregate animation settlement. */ export type MotionAnimationStateListener = (isAnimating: boolean) => void; /** * Narrow the upstream animation result to the branch that exposes async settlement hooks. * * `animateSingleValue()` can either return a real animation control or settle immediately for * values that do not need frame-based interpolation. The renderer has to support both cases, * because higher layers still need correct `isAnimating` bookkeeping when Motion decides a * target can complete synchronously. */ function isAnimationControl(value: ValueAnimationControl): value is NonNullable { return value !== undefined && value !== null && typeof value.then === "function"; } /** * Minimal renderer contract owned by MotionState. * * This stays intentionally small because it is still the scalar bridge. MotionState decides * which targets win; the renderer only reflects those targets into MotionValues and DOM effects. */ export interface MotionRenderer { /** * Reports whether any scalar animation started by this renderer is still in flight. * * MotionState uses this to distinguish "the exit lane is active" from "the exit work * has actually settled". That difference becomes important once retained presence needs * to know when a child is safe to remove. */ readonly isAnimating: boolean; /** * Reconcile the current scalar style and animated targets for the attached host. * * `styleTarget` is the non-animated base layer. `animateTarget` is the current winning animated * output chosen by MotionState. `seedTarget` is optional layout input: when present, it gives * the temporary visual start that should be applied before animating toward `animateTarget`. * * The important nuance is that `seedTarget` does not replace `animateTarget`. It only changes * where the animation starts from on this update pass. The resting owner is still the matching * key in `animateTarget`. */ update( styleTarget: MotionTargetMap, animateTarget: MotionTargetMap, transition?: Transition, seedTarget?: MotionTargetMap, ): void; /** * Subscribe to changes in whether the renderer still has active animations. * * The listener is called immediately with the current state so higher layers can attach * after mount without waiting for the next animation edge. */ subscribeAnimationState(listener: MotionAnimationStateListener): VoidFunction; /** * Stop DOM effects, active animations, and per-value subscriptions owned by this renderer. */ destroy(): void; } /** * Choose the correct `motion-dom` DOM effect for the attached host. */ function createRenderer( element: HTMLElement | SVGElement, values: RenderedMotionValues, ): VoidFunction { // Motion uses different DOM writers for HTML and SVG, but both consume the same // motion-value map that this helper maintains. return element instanceof SVGElement ? svgEffect(element, values) : styleEffect(element, values); } /** * Create the scalar renderer used by MotionState. * * The renderer owns per-key MotionValues, DOM effect subscriptions, and animation handles for * one mounted element. * * This module deliberately does not decide animation priority, presence rules, or layout timing. * Those policies live in MotionState. The renderer's job is narrower: keep one persistent * MotionValue per scalar key, reflect ownership changes between style and animate layers, and * expose one honest `isAnimating` signal to the state layer above it. */ export function createMotionValueRenderer(element: HTMLElement | SVGElement): MotionRenderer { const renderedValues = Object.create(null) as RenderedMotionValues; const activeAnimations = new Map(); // The renderer needs to distinguish "same resting target" from "same whole update" so layout // handoffs can restart from a new seed without reanimating unchanged keys unnecessarily. const lastAnimatedTargets = new Map(); const animationStateListeners = new Set(); let cancelRender: VoidFunction = noop; // Rebuild the DOM effect only when the rendered key set changes, not on every value update. let renderSignature = ""; let isAnimating = false; /** * Notify listeners only when the aggregate animation flag changes. */ function notifyAnimationState(): void { const nextIsAnimating = activeAnimations.size > 0; if (nextIsAnimating === isAnimating) return; isAnimating = nextIsAnimating; for (const listener of animationStateListeners) { listener(isAnimating); } } /** * Reuse one MotionValue per key so DOM effects stay attached across updates. */ function ensureValue(key: string, fallback: MotionTargetValue): MotionValueInstance { const existing = renderedValues[key]; if (existing) return existing; const nextValue = motionValue(fallback); renderedValues[key] = nextValue; return nextValue; } /** * Recreate the upstream DOM effect only when the set of rendered keys changes. * * Changing a MotionValue's contents does not require rebuilding `styleEffect()` or * `svgEffect()`. Those effects subscribe to the MotionValues themselves. Rebuilding only when * keys appear or disappear avoids unnecessary subscription churn during ordinary target updates. */ function syncRenderer(): void { const nextSignature = Object.keys(renderedValues).sort().join("|"); if (nextSignature === renderSignature) return; cancelRender(); cancelRender = nextSignature.length === 0 ? noop : createRenderer(element, renderedValues); renderSignature = nextSignature; } /** * Drop values that no longer belong to either the style layer or the active animated target. * * A key can disappear because MotionState changed lanes, because a layout handoff finished and * no longer needs a transform key, or because the user simply stopped providing that value. * The renderer has to remove every resource tied to that key so stale MotionValues do not keep * writing to the DOM behind the current state. */ function pruneRemovedKeys(nextKeys: Set): void { for (const key of Object.keys(renderedValues)) { if (nextKeys.has(key)) continue; const renderedValue = renderedValues[key]; // One removed key owns three renderer resources: an animation handle, a remembered target, // and the MotionValue feeding the DOM effect. activeAnimations.get(key)?.stop(); activeAnimations.delete(key); lastAnimatedTargets.delete(key); renderedValue?.destroy(); delete renderedValues[key]; } notifyAnimationState(); } /** * Apply non-animated values directly, but leave overlapping keys to the animated lane. * * The style layer is the stable fallback underneath animation. If both layers mention the same * key, the animated layer wins for that pass so the MotionValue can stay the single writer for * the DOM output of that key. */ function applyStyleTargets( styleTargets: MotionTargetMap, animateTargets: MotionTargetMap, ): void { for (const [key, value] of Object.entries(styleTargets)) { const renderedValue = ensureValue(key, value); if (Object.hasOwn(animateTargets, key)) continue; // If the animated layer no longer owns this key, stop its animation and let static style // become the only writer again. activeAnimations.get(key)?.stop(); activeAnimations.delete(key); lastAnimatedTargets.delete(key); renderedValue.set(value); } notifyAnimationState(); } /** * Animate each active scalar key toward the latest resolved target. * * The surrounding MotionState already picked the winning targets. This helper updates one * MotionValue per key and keeps aggregate animation state accurate for higher-level callbacks. * * Two edge cases matter here: * - a layout handoff may keep the same resting target but still need work because the visual * start changed through `seedTargets` * - Motion may decide a new target settles immediately and return no thenable control at all * * Both cases need to leave `lastAnimatedTargets` and `isAnimating` in a truthful state. */ function applyAnimateTargets( animateTargets: MotionTargetMap, transition?: Transition, seedTargets: MotionTargetMap = Object.create(null) as MotionTargetMap, ): void { for (const [key, value] of Object.entries(animateTargets)) { const hasSeed = Object.hasOwn(seedTargets, key); // A layout handoff may keep the same final target while changing only the visual start. if (!hasSeed && lastAnimatedTargets.get(key) === value) continue; const renderedValue = ensureValue(key, value); if (hasSeed) { const seededValue = seedTargets[key]; if (seededValue === undefined) continue; // Step 1: temporarily force the old visual position or size. renderedValue.set(seededValue); } // Step 2: replace any older animation for this key with the latest target. activeAnimations.get(key)?.stop(); const nextAnimation = animateSingleValue(renderedValue, value, transition); if (isAnimationControl(nextAnimation)) { // Long-lived animations participate in aggregate `isAnimating` bookkeeping until the // exact control we started here settles or gets replaced by a newer update. activeAnimations.set(key, nextAnimation); notifyAnimationState(); nextAnimation.then( () => { if (activeAnimations.get(key) !== nextAnimation) return; activeAnimations.delete(key); notifyAnimationState(); }, () => { if (activeAnimations.get(key) !== nextAnimation) return; activeAnimations.delete(key); notifyAnimationState(); }, ); } else { // Some transitions settle synchronously. In that branch the DOM value is already at the // new target, so the key should not count as animating after this pass. activeAnimations.delete(key); notifyAnimationState(); } lastAnimatedTargets.set(key, value); } } return { get isAnimating(): boolean { return isAnimating; }, update( styleTarget: MotionTargetMap, animateTarget: MotionTargetMap, transition?: Transition, seedTarget: MotionTargetMap = Object.create(null) as MotionTargetMap, ): void { // The renderer resolves the incoming records again at its own boundary so callers do not // need to know which target shapes are currently accepted internally. const styleTargets = resolveTargetRecord(styleTarget); const animateTargets = resolveTargetRecord(animateTarget); const nextKeys = new Set([ ...Object.keys(styleTargets), ...Object.keys(animateTargets), ]); // Keep the update order stable so a key never briefly has two competing writers in the // same pass: remove stale keys, restore static owners, retarget animations, then rebuild // DOM subscriptions only if the key set changed. pruneRemovedKeys(nextKeys); applyStyleTargets(styleTargets, animateTargets); applyAnimateTargets(animateTargets, transition, seedTarget); syncRenderer(); }, subscribeAnimationState(listener: MotionAnimationStateListener): VoidFunction { animationStateListeners.add(listener); listener(isAnimating); return () => animationStateListeners.delete(listener); }, destroy(): void { cancelRender(); for (const control of activeAnimations.values()) { control.stop(); } activeAnimations.clear(); notifyAnimationState(); lastAnimatedTargets.clear(); animationStateListeners.clear(); for (const [key, renderedValue] of Object.entries(renderedValues)) { renderedValue.destroy(); delete renderedValues[key]; } renderSignature = ""; cancelRender = noop; }, }; }