Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/solid-motion-experiments.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600import { 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<VoidFunction>();
/** * Serialize a target map into a stable identity string for completion bookkeeping. */ function serializeTarget(target: Record<string, string | number>): 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<typeof resolveStateOptions>, ): 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<typeof resolveStateOptions>, ): 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<typeof createSnapshot>): 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(); }, };}