import { cloneStateOptions, createActiveTargets, createSnapshot, resolveStateOptions, } from "./_motion-state-options.ts"; import { createMotionValueRenderer } from "./_motion-value-renderer.ts"; import type { MotionRenderer } from "./_motion-value-renderer.ts"; import type { MotionTargetMap, MotionStateOptions, MotionStateTargetKey, } from "./_motion-state-options.ts"; import { noop } from "../utils/_noop.ts"; import { merge } from "../utils/_merge.ts"; export type { MotionStateOptions, MotionStateTargetKey } from "./_motion-state-options.ts"; /** * Snapshot of one rendered element's client box. * * The layout path stores these plain numbers so MotionState can compare old and new layout * without carrying live `DOMRect` objects through the rest of the runtime. */ export type LayoutBox = { left: number; top: number; width: number; height: number; }; /** * One resolved layout handoff for the current render pass. * * `seedTarget` is the temporary inverse transform that visually keeps the element in its old * position or size. `animateTarget` is the resting transform that Motion animates back to. * `signature` lets MotionState treat repeated reactive passes as the same layout animation. * * The important nuance is that this object is not a generic layout model. It is only the * transient handoff data needed between measurement and renderer update for the current * Milestone 0 FLIP path. */ export type LayoutAnimation = { seedTarget: MotionTargetMap; animateTarget: MotionTargetMap; signature: string; }; /** * Read the current client box from the mounted host element. */ function measureLayoutBox(element: HTMLElement | SVGElement): LayoutBox { const rect = element.getBoundingClientRect(); return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, }; } /** * Report whether two layout snapshots differ in a way that matters for the FLIP path. */ function hasLayoutChange(previous: LayoutBox, next: LayoutBox): boolean { return previous.left !== next.left || previous.top !== next.top || previous.width !== next.width || previous.height !== next.height; } /** * Convert two measured boxes into the transform targets needed for the current layout MVP. * * The DOM has already committed the new layout when this runs. This helper derives the inverse * transform that makes the new box still look like the old box, then pairs it with the resting * identity transform that Motion should animate toward. * * This helper only produces transform keys. It does not mutate the DOM, start animations, or * decide when the layout path should run. Those concerns stay separate so the measurement logic * can remain a pure translation from boxes to target records. */ function resolveLayoutAnimation( previous: LayoutBox, next: LayoutBox, layoutMode: MotionStateOptions["layout"], ): LayoutAnimation | undefined { if (layoutMode === undefined || layoutMode === false) return undefined; if (!hasLayoutChange(previous, next)) return undefined; const includePosition = layoutMode !== "size"; const includeSize = layoutMode !== "position"; const seedTarget = Object.create(null) as MotionTargetMap; const animateTarget = Object.create(null) as MotionTargetMap; if (includePosition) { // The element already occupies `next`. Offsetting by previous - next makes the first // animated frame still appear at the old visual position. const deltaX = previous.left - next.left; const deltaY = previous.top - next.top; if (deltaX !== 0) { seedTarget.x = deltaX; animateTarget.x = 0; } if (deltaY !== 0) { seedTarget.y = deltaY; animateTarget.y = 0; } } if (includeSize && next.width !== 0 && next.height !== 0) { // Scale uses ratios instead of deltas because the resting target is identity: `1`. const deltaScaleX = previous.width / next.width; const deltaScaleY = previous.height / next.height; if (deltaScaleX !== 1) { seedTarget.scaleX = deltaScaleX; animateTarget.scaleX = 1; } if (deltaScaleY !== 1) { seedTarget.scaleY = deltaScaleY; animateTarget.scaleY = 1; } } if (Object.keys(seedTarget).length === 0) { return undefined; } return { seedTarget, animateTarget, // Sorting keeps the signature stable even when object insertion order differs. signature: JSON.stringify(Object.entries(seedTarget).sort(([left], [right]) => left.localeCompare(right) )), }; } /** * Stable per-component runtime state for one Solid Motion wrapper. * * This object owns the stateful boundary between Solid and Motion. The wrapper only hands * it host lifecycle events and raw Motion options. MotionState then resolves the currently * active lane and keeps the renderer in sync. */ export interface MotionState { /** * Tracks which DOM host this Motion state currently owns. */ readonly element: HTMLElement | SVGElement | undefined; /** * Reports which target lane currently owns animation output. * * This is useful even before gestures and presence are fully wired because it keeps the * priority decision inside MotionState, where later exit and gesture features will also * live. */ readonly activeTarget: MotionStateTargetKey | undefined; /** * Exposes the last option bag the state received from the wrapper. */ readonly options: MotionStateOptions; /** * Tracks whether the surrounding presence boundary still considers this state present. */ readonly isPresent: boolean; /** * Tells callers whether a real DOM host is currently attached. */ readonly isMounted: boolean; /** * Subscribe to exit completion for the currently active exit cycle. * * Presence needs a state-level signal that means more than "the exit lane is selected". * This callback only fires after the current exit target has no in-flight scalar animation * work left, or immediately if the exit target resolves without animation. */ onExitComplete(listener: VoidFunction): VoidFunction; /** * Attach a concrete DOM host to this state. * * MotionState is stable across the component lifetime, but the rendered host node can * still change when `as` changes or a custom component swaps its root. `mount()` lets the * state recreate only the DOM-bound renderer while preserving resolved options and active * target state. */ mount(element: HTMLElement | SVGElement): void; /** * Detach the current DOM host without forgetting options or active lanes. * * This is different from `destroy()`: unmounting keeps the logical MotionState alive so a * later host can remount and receive the same resolved target snapshot. */ unmount(): void; /** * Reconcile the latest Solid-facing options into MotionState. * * The state object is where top-level accessor resolution, variant-label lookup, and * target-priority selection now live. The wrapper should only hand over the raw Motion * options it observes from Solid. */ updateOptions(options: MotionStateOptions): void; /** * Update MotionState's logical presence. * * For now this only toggles the exit lane on and off. The important part is that presence * now has a dedicated state seam instead of leaking in as ad hoc lane mutation from the * wrapper. */ setIsPresent(isPresent: boolean): void; /** * Enable or disable one target lane. * * `animate` starts enabled by default. The other lanes are dormant until a feature such as * presence or gestures turns them on. That keeps the feature plumbing centered in the * state object even before those features exist. */ setActive(name: MotionStateTargetKey, isActive: boolean): void; /** * Fully dispose MotionState and the DOM renderer it owns. */ destroy(): void; } /** * Create the per-component MotionState runtime. * * MotionState is the bridge between Solid's reactive prop layer and Motion's DOM-writing * renderer. The wrapper forwards raw options and host lifecycle changes; MotionState resolves * active targets, manages renderer lifetime, and layers in layout and presence bookkeeping. * * Read the flow left to right: * * ```text * Solid props ─► updateOptions() ─► resolve active lane ─► renderer.update(style, animate) * ref ─► mount()/unmount() ──────────────────────► renderer lifetime * ``` * * The renderer knows how to write scalar MotionValues to one host element. MotionState knows when * that renderer should exist, which targets currently own output, and which completion signals * matter to features like presence and layout. * * @example Mount and update a state object * ```ts * const state = createMotionState(); * state.mount(element); * state.updateOptions({ animate: { opacity: 1 } }); * ``` * * @example Promote exit over animate * ```ts * const state = createMotionState(); * state.updateOptions({ animate: { opacity: 1 }, exit: { opacity: 0 } }); * state.setActive("exit", true); * ``` */ export function createMotionState(): MotionState { let currentElement: HTMLElement | SVGElement | undefined; let currentRenderer: MotionRenderer | undefined; let currentActiveTarget: MotionStateTargetKey | undefined; // Exit and layout callbacks are cycle-based, not frame-based. These signatures let repeated // reactive passes recognize that they still belong to the same in-flight cycle. let pendingExitSignature: string | undefined; let completedExitSignature: string | undefined; let pendingLayoutSignature: string | undefined; let completedLayoutSignature: string | undefined; let currentIsPresent = true; let hasAppliedInitialMount = false; // Milestone 0 layout is explicit-invalidation based. These two values provide the old box // and the dependency edge that tell us when a new layout bridge should start. let lastLayoutDependency: unknown; let lastLayoutBox: LayoutBox | undefined; let currentOptions = cloneStateOptions({}); let currentActiveTargets = createActiveTargets(); let cancelRendererSubscription: VoidFunction = noop; const exitCompleteListeners = new Set(); /** * Serialize a target map into a stable identity string for completion bookkeeping. */ function serializeTarget(target: Record): string { const entries = Object.entries(target).sort(([left], [right]) => left.localeCompare(right) ); return JSON.stringify(entries); } /** * Fan out exit completion to all current listeners. */ function notifyExitComplete(): void { for (const listener of exitCompleteListeners) { listener(); } } /** * Deliver the current layout-complete callback. */ function notifyLayoutComplete(): void { const resolvedOptions = resolveStateOptions(currentOptions); resolvedOptions.onLayoutAnimationComplete?.(); } /** * Finalize the current exit cycle once the renderer reports that animation work has settled. */ function settleExitIfReady(): void { if (!pendingExitSignature) return; if (currentRenderer?.isAnimating) return; completedExitSignature = pendingExitSignature; pendingExitSignature = undefined; notifyExitComplete(); } /** * Finalize the current layout cycle once the renderer reports that animation work has settled. */ function settleLayoutIfReady(): void { if (!pendingLayoutSignature) return; if (currentRenderer?.isAnimating) return; completedLayoutSignature = pendingLayoutSignature; pendingLayoutSignature = undefined; notifyLayoutComplete(); } /** * Bind MotionState's completion bookkeeping to the current renderer instance. */ function bindRenderer(renderer: MotionRenderer): void { cancelRendererSubscription(); cancelRendererSubscription = renderer.subscribeAnimationState(() => { settleExitIfReady(); settleLayoutIfReady(); }); } /** * Tear down only the DOM-bound renderer bridge. * * MotionState keeps its logical options and active lanes across host swaps and retained exit. * This helper isolates the smaller cleanup step where only the element-bound renderer and its * animation-state subscription need to go away. */ function resetRenderer(): void { cancelRendererSubscription(); cancelRendererSubscription = noop; currentRenderer?.destroy(); currentRenderer = undefined; } /** * Resolve the current FLIP handoff if layout is enabled and the dependency invalidated. * * The dependency gate is important here. Milestone 0 layout is not observer-driven, so Motion * should only compare the previously cached box with the newly committed box when the caller has * explicitly said that surrounding layout state changed. * * Read this as a bridge between two committed layouts: * 1. reuse the previously cached box as the old visual state * 2. measure the current element as the new visual state * 3. derive the inverse transform that lets the renderer animate between them */ function resolveLayoutHandoff( resolvedOptions: ReturnType, ): LayoutAnimation | undefined { if (!currentElement) return undefined; if (resolvedOptions.layout === undefined || resolvedOptions.layout === false) { return undefined; } const nextLayoutBox = measureLayoutBox(currentElement); const didLayoutDependencyChange = !Object.is( lastLayoutDependency, resolvedOptions.layoutDependency, ); const layoutAnimation = lastLayoutBox && didLayoutDependencyChange ? resolveLayoutAnimation( lastLayoutBox, nextLayoutBox, resolvedOptions.layout, ) : undefined; lastLayoutBox = nextLayoutBox; lastLayoutDependency = resolvedOptions.layoutDependency; return layoutAnimation; } /** * Record a newly started layout cycle and fire its start callback once. */ function trackLayoutCycle( layoutAnimation: LayoutAnimation | undefined, resolvedOptions: ReturnType, ): void { if (!layoutAnimation) return; if (layoutAnimation.signature === completedLayoutSignature) return; if (layoutAnimation.signature === pendingLayoutSignature) return; pendingLayoutSignature = layoutAnimation.signature; resolvedOptions.onLayoutAnimationStart?.(); } /** * Record the currently active exit cycle, if any. * * Exit bookkeeping lives on the resolved target rather than on presence toggles alone because * repeated reactive passes can rebuild the same exit lane many times before the renderer settles. */ function trackExitCycle(snapshot: ReturnType): void { if (snapshot.activeTarget !== "exit") { // A non-exit pass should not keep stale exit completion state alive. pendingExitSignature = undefined; return; } const nextExitSignature = serializeTarget(snapshot.animateTarget); if (nextExitSignature === completedExitSignature) return; if (nextExitSignature === pendingExitSignature) return; pendingExitSignature = nextExitSignature; } /** * Resolve the latest Motion snapshot and synchronize the mounted renderer. * * This is the point where MotionState collapses several logical inputs into one renderer update: * resolved props decide the winning lane, layout may augment that lane with a FLIP handoff, and * the renderer receives one concrete style/animate payload for the current committed element. */ function syncRenderer(): void { const resolvedOptions = resolveStateOptions(currentOptions); const snapshot = createSnapshot( resolvedOptions, currentActiveTargets, !hasAppliedInitialMount, ); currentActiveTarget = snapshot.activeTarget; if (!currentElement) { // Without a host element there is no DOM bridge to keep alive, but completion bookkeeping // may still need to flush if animation work already settled before the element disappeared. resetRenderer(); settleExitIfReady(); return; } if (!currentRenderer) { currentRenderer = createMotionValueRenderer(currentElement); bindRenderer(currentRenderer); } const layoutAnimation = resolveLayoutHandoff(resolvedOptions); // Layout augments the winning lane instead of replacing it. Exit still wins outright. const animateTarget = layoutAnimation && snapshot.activeTarget !== "exit" ? merge(snapshot.animateTarget, layoutAnimation.animateTarget) : snapshot.animateTarget; currentRenderer.update( snapshot.styleTarget, animateTarget, resolvedOptions.transition, // The renderer applies this inverse transform first, then animates back to rest. layoutAnimation?.seedTarget, ); hasAppliedInitialMount = true; // Cycle tracking comes after the renderer update because these signatures describe the work // we just handed off, not merely the latest resolved inputs in userland. trackLayoutCycle(layoutAnimation, resolvedOptions); trackExitCycle(snapshot); settleLayoutIfReady(); settleExitIfReady(); } return { get element(): HTMLElement | SVGElement | undefined { return currentElement; }, get activeTarget(): MotionStateTargetKey | undefined { return currentActiveTarget; }, get options(): MotionStateOptions { return currentOptions; }, get isPresent(): boolean { return currentIsPresent; }, get isMounted(): boolean { return currentElement !== undefined; }, onExitComplete(listener: VoidFunction): VoidFunction { exitCompleteListeners.add(listener); return () => { exitCompleteListeners.delete(listener); }; }, mount(element: HTMLElement | SVGElement): void { if (currentElement === element) return; // The logical MotionState survives host swaps, but the DOM-side renderer does not. resetRenderer(); currentElement = element; syncRenderer(); }, unmount(): void { if (!currentElement) return; // Unmount only drops the DOM bridge. Options and lane state stay alive for a later remount. resetRenderer(); currentElement = undefined; settleExitIfReady(); }, updateOptions(options: MotionStateOptions): void { // Copy the outer options bag so MotionState owns a stable plain object even when the // wrapper hands us values assembled from Solid's reactive prop proxies. currentOptions = cloneStateOptions(options); syncRenderer(); }, setIsPresent(isPresent: boolean): void { if (currentIsPresent === isPresent) return; currentIsPresent = isPresent; if (isPresent) { // Re-entry starts a fresh logical presence cycle. pendingExitSignature = undefined; completedExitSignature = undefined; } currentActiveTargets.exit = !isPresent; syncRenderer(); }, setActive(name: MotionStateTargetKey, isActive: boolean): void { if (currentActiveTargets[name] === isActive) return; currentActiveTargets[name] = isActive; syncRenderer(); }, destroy(): void { resetRenderer(); currentElement = undefined; currentOptions = cloneStateOptions({}); currentActiveTargets = createActiveTargets(); currentActiveTarget = undefined; currentIsPresent = true; hasAppliedInitialMount = false; lastLayoutDependency = undefined; lastLayoutBox = undefined; pendingExitSignature = undefined; completedExitSignature = undefined; pendingLayoutSignature = undefined; completedLayoutSignature = undefined; exitCompleteListeners.clear(); }, }; }