Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/solid-motion-experiments.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643import type { HTMLRenderState, MotionNodeOptions, ResolvedValues, Target, TargetAndTransition, TargetResolver, Transition, VariantLabels, Variants,} from "motion-dom";
import { buildHTMLStyles, isVariantLabel, resolveVariantFromProps,} from "motion-dom";import { isObject } from "motion-utils";
import type { MaybeAccessor } from "../motion/resolve-motion-prop.ts";import { resolveMaybeAccessor } from "../motion/resolve-motion-prop.ts";import { merge } from "../utils/_merge.ts";
/** * Names the target lanes MotionState can activate and resolve. * * The state object needs a stable vocabulary for "which target currently owns output" * before gestures, presence, and layout are fully implemented. Keeping these names in one * module makes it easier to share the same rules between the pre-mount initial-style path * and the mounted runtime path. * * @example Baseline animate lane * ```ts * const lane: MotionStateTargetKey = "animate"; * ``` * * @example Presence-driven exit lane * ```ts * const lane: MotionStateTargetKey = "exit"; * ``` */export type MotionStateTargetKey = | "animate" | "exit" | "whileFocus" | "whileHover" | "whileInView" | "whilePress" | "whileTap";
/** * Describes one Motion target definition that the current Solid runtime can resolve. * * This reuses Motion's own public animation-definition vocabulary instead of maintaining a * parallel local shape. The only Solid-specific wrapper lives one level up, where callers * may still provide these values through zero-argument accessors. */export type MotionStateTargetDefinition = | VariantLabels | TargetAndTransition | TargetResolver;
/** * Describes the pre-mount initial state contract for MotionState. * * Motion uses `false` as a special value that means "skip an entry state and start from the * animate target". Keeping that sentinel explicit makes the SSR and hydration path easier to * reason about than leaving it buried in `unknown`. */export type MotionStateInitialDefinition = false | MotionStateTargetDefinition;
/** * Captures the Motion-facing inputs that a Solid wrapper hands to MotionState. * * This interface is wider than the currently implemented features on purpose. The state * object should own option normalization and target selection now, even if layout, * presence, and gestures still resolve to inert lanes or reserved fields. * * @example Direct animate target * ```ts * const options: MotionStateOptions = { * style: { opacity: 0.5 }, * animate: { opacity: 1, x: 24 }, * }; * ``` * * @example Variant label with custom payload * ```ts * const options: MotionStateOptions = { * animate: "open", * variants: { * open: (custom) => ({ x: Number(custom) }), * }, * custom: 48, * }; * ``` */export interface MotionStateOptions { /** * Immediate non-animated style values that act as the base layer under animated lanes. */ style?: MaybeAccessor<Target>;
/** * Initial visual state used during SSR and the first client render before Motion starts. */ initial?: MaybeAccessor<MotionStateInitialDefinition>;
/** * The default active animation target when no higher-priority lane is enabled. */ animate?: MaybeAccessor<MotionStateTargetDefinition>;
/** * Exit target reserved for future presence-driven activation. */ exit?: MaybeAccessor<MotionStateTargetDefinition>;
/** * Variant table used when lanes reference string labels. */ variants?: MaybeAccessor<Variants>;
/** * Arbitrary payload forwarded to variant resolver functions. */ custom?: MaybeAccessor<unknown>;
/** * Reserved transition config for the later animation-state layer. */ transition?: MaybeAccessor<Transition>;
/** * Reserved identity escape hatch for retained-presence workflows. */ presenceKey?: MaybeAccessor<unknown>;
/** * Opts the component into the current layout-measurement path. */ layout?: MaybeAccessor<MotionNodeOptions["layout"]>;
/** * Explicit invalidation hint for the first layout-measurement pass. * * Milestone 0 layout work is dependency-first rather than observer-driven. The wrapper can * update this value when surrounding layout state changes, and MotionState can treat that as * a signal that any cached box data is stale. */ layoutDependency?: MaybeAccessor<MotionNodeOptions["layoutDependency"]>;
/** * Reserved shared-layout identity for later grouped layout work. */ layoutId?: MaybeAccessor<MotionNodeOptions["layoutId"]>;
/** * Reserved root-scoping flag for later layout tree coordination. */ layoutRoot?: MaybeAccessor<MotionNodeOptions["layoutRoot"]>;
/** * Reserved scroll-compensation flag for later layout measurement work. */ layoutScroll?: MaybeAccessor<MotionNodeOptions["layoutScroll"]>;
/** * Reserved anchor target for later shared-layout positioning. */ layoutAnchor?: MaybeAccessor<MotionNodeOptions["layoutAnchor"]>;
/** * Layout animation lifecycle start callback. */ onLayoutAnimationStart?: MotionNodeOptions["onLayoutAnimationStart"];
/** * Layout animation lifecycle completion callback. */ onLayoutAnimationComplete?: MotionNodeOptions["onLayoutAnimationComplete"];
/** * Focus-driven target lane. */ whileFocus?: MaybeAccessor<MotionStateTargetDefinition>;
/** * Hover-driven target lane. */ whileHover?: MaybeAccessor<MotionStateTargetDefinition>;
/** * Viewport-driven target lane. */ whileInView?: MaybeAccessor<MotionStateTargetDefinition>;
/** * Press-driven target lane. */ whilePress?: MaybeAccessor<MotionStateTargetDefinition>;
/** * Tap-driven target lane. */ whileTap?: MaybeAccessor<MotionStateTargetDefinition>;}
/** * Narrow scalar value vocabulary supported by the current renderer. * * Milestone 0 only animates scalar CSS and SVG values. Complex objects and arrays stay outside * this type on purpose so the renderer never pretends it can interpolate value shapes it does * not yet understand. */export type MotionTargetValue = number | string;
/** * Plain record of the scalar target values currently owned by one resolved lane. */export type MotionTargetMap = Record<string, MotionTargetValue>;
/** * Fully resolved option bag owned by MotionState for one render pass. * * The wrapper-facing `MotionStateOptions` type still allows Solid accessors. This internal shape * is the next step after unwrapping those accessors, before target priority and variant lookup * choose the winning animated lane. */export type ResolvedStateOptions = { style: Target | undefined; initial: MotionStateInitialDefinition | undefined; animate: MotionStateTargetDefinition | undefined; exit: MotionStateTargetDefinition | undefined; variants: Variants | undefined; custom: unknown; transition: Transition | undefined; presenceKey: unknown; layout: MotionNodeOptions["layout"] | undefined; layoutDependency: MotionNodeOptions["layoutDependency"] | undefined; layoutId: MotionNodeOptions["layoutId"] | undefined; layoutRoot: MotionNodeOptions["layoutRoot"] | undefined; layoutScroll: MotionNodeOptions["layoutScroll"] | undefined; layoutAnchor: MotionNodeOptions["layoutAnchor"] | undefined; onLayoutAnimationStart: MotionNodeOptions["onLayoutAnimationStart"] | undefined; onLayoutAnimationComplete: MotionNodeOptions["onLayoutAnimationComplete"] | undefined; whileFocus: MotionStateTargetDefinition | undefined; whileHover: MotionStateTargetDefinition | undefined; whileInView: MotionStateTargetDefinition | undefined; whilePress: MotionStateTargetDefinition | undefined; whileTap: MotionStateTargetDefinition | undefined;};
/** * One resolved renderer snapshot for the current MotionState pass. */export type ResolvedStateSnapshot = { styleTarget: MotionTargetMap; animateTarget: MotionTargetMap; activeTarget: MotionStateTargetKey | undefined;};
/** * Shared empty target record for branches that resolve to no scalar output. * * MotionState compares and merges target maps frequently. Reusing one frozen null-prototype * object for the empty case keeps those branches explicit without allocating throwaway records. */export const EMPTY_TARGETS = Object.freeze(Object.create(null)) as MotionTargetMap;
/** * Shared empty serialized style record for SSR and hydration paths with no output styles. */export const EMPTY_STYLE = Object.freeze(Object.create(null)) as MotionTargetMap;
/** * Default lane activation table for a newly created MotionState. * * `animate` starts enabled so ordinary components immediately use their primary target. The * other lanes stay off until features like presence or gestures explicitly activate them. */export const DEFAULT_ACTIVE_TARGETS = Object.freeze({ animate: true, exit: false, whileFocus: false, whileHover: false, whileInView: false, whilePress: false, whileTap: false,}) as Readonly<Record<MotionStateTargetKey, boolean>>;
/** * Priority order used when several lanes are active at once. * * Motion-dom manages a fuller animation-state machine and can resolve variants from lowest to * highest priority. MotionState only needs to know the one lane that wins right now, so it scans * in the opposite direction. `whilePress` sits ahead of tap for now because the Solid adapter * exposes it as a temporary local gesture lane. */export const MOTION_STATE_TARGET_PRIORITY: readonly MotionStateTargetKey[] = [ "exit", "whilePress", "whileTap", "whileHover", "whileFocus", "whileInView", "animate",];
/** * Accept only scalar value entries that the current renderer can write directly. */function isMotionTargetValue(value: unknown): value is MotionTargetValue { return typeof value === "number" || typeof value === "string";}
/** * Create the minimal render-state object that `motion-dom`'s HTML style builder expects. * * We only use this on the static pre-mount path. The mounted renderer already delegates DOM * writes to `styleEffect()` and `svgEffect()`, but SSR and hydration still need one pure * function that turns resolved Motion values into a concrete style object. */function createHtmlRenderState(): HTMLRenderState { return { transform: Object.create(null), transformOrigin: Object.create(null), style: Object.create(null), vars: Object.create(null), };}
/** * Build one static HTML style object using `motion-dom`'s own style serializer. * * The Solid wrapper still decides which values belong to the current entry snapshot, but it * should not reimplement transform ordering, transform-origin formatting, CSS variable output, * or unit normalization. Those rules already live in `buildHTMLStyles()`. */function buildStaticStyle(latestValues: MotionTargetMap): MotionTargetMap { if (Object.keys(latestValues).length === 0) { return EMPTY_STYLE; }
const renderState = createHtmlRenderState(); buildHTMLStyles(renderState, latestValues as ResolvedValues);
return merge(renderState.style, renderState.vars) as MotionTargetMap;}
/** * Snapshot the wrapper-owned options into a plain object under MotionState ownership. * * The wrapper can assemble options from Solid prop proxies. Copying the outer bag here * keeps MotionState's internal view explicit and stable without freezing the nested * values it still needs to resolve lazily. */export function cloneStateOptions(options: MotionStateOptions): MotionStateOptions { return merge(options) as MotionStateOptions;}
/** * Build the mutable active-lane table that MotionState toggles over time. */export function createActiveTargets(): Record<MotionStateTargetKey, boolean> { return merge(DEFAULT_ACTIVE_TARGETS) as Record< MotionStateTargetKey, boolean >;}
/** * Resolve one top-level Motion option without deciding how the value will be interpreted. * * For example, this turns `animate={() => "open"}` into the label `"open"`, but it does * not yet decide whether that label points to a variant or whether a higher-priority lane * should override it. */function resolveOptionValue<T>(value: MaybeAccessor<T> | undefined): T | undefined { if (typeof value !== "function") { return value; }
// Solid accessors are zero-argument functions. Motion variant resolvers are exported // three-argument callbacks. We only invoke the former here so the latter can flow intact // into motion-dom's own resolver path. return value.length === 0 ? resolveMaybeAccessor(value as () => T) : (value as T);}
/** * Convert a user-facing target object into the scalar subset the current renderer can use. * * This is intentionally narrower than Motion's full value model. The first Solid renderer * only serializes and animates scalar CSS/SVG values. Complex values stay reserved for the * later VisualElement-backed layer. */export function resolveTargetRecord(value: unknown): MotionTargetMap { if (typeof value === "function" && value.length === 0) { return resolveTargetRecord(resolveMaybeAccessor(value as () => unknown)); }
if (!isObject(value) || Array.isArray(value)) { return EMPTY_TARGETS; }
const nextTargets = Object.create(null) as MotionTargetMap;
for (const [key, entry] of Object.entries(value)) { if (isMotionTargetValue(entry)) { nextTargets[key] = entry; } }
return nextTargets;}
/** * Resolve the raw wrapper options into one normalized shape for the current pass. * * This is the handoff from Solid-facing input to MotionState-owned decision making. * After this step, later helpers no longer care whether a value came from a plain prop or from * a zero-argument Solid accessor. They only decide which lane wins and how that lane resolves. */export function resolveStateOptions(options: MotionStateOptions): ResolvedStateOptions { return { style: resolveOptionValue(options.style), initial: resolveOptionValue(options.initial), animate: resolveOptionValue(options.animate), exit: resolveOptionValue(options.exit), variants: resolveOptionValue(options.variants), custom: resolveOptionValue(options.custom), transition: resolveOptionValue(options.transition), presenceKey: resolveOptionValue(options.presenceKey), layout: resolveOptionValue(options.layout), layoutDependency: resolveOptionValue(options.layoutDependency), layoutId: resolveOptionValue(options.layoutId), layoutRoot: resolveOptionValue(options.layoutRoot), layoutScroll: resolveOptionValue(options.layoutScroll), layoutAnchor: resolveOptionValue(options.layoutAnchor), onLayoutAnimationStart: options.onLayoutAnimationStart, onLayoutAnimationComplete: options.onLayoutAnimationComplete, whileFocus: resolveOptionValue(options.whileFocus), whileHover: resolveOptionValue(options.whileHover), whileInView: resolveOptionValue(options.whileInView), whilePress: resolveOptionValue(options.whilePress), whileTap: resolveOptionValue(options.whileTap), };}
/** * Resolve a single variant definition into the scalar subset the current renderer can use. * * Motion-dom already knows how to unwrap function variants and variant labels from props. * We reuse that here with a minimal props-shaped object, while explicitly passing no * VisualElement because the current Solid runtime has not built that layer yet. */function resolveVariantTarget( definition: MotionStateTargetDefinition, options: ResolvedStateOptions,): MotionTargetMap { const variantProps = options.variants === undefined ? { custom: options.custom } : { variants: options.variants, custom: options.custom };
const resolvedDefinition = resolveVariantFromProps( variantProps, definition, options.custom, undefined, );
return resolveTargetRecord(resolvedDefinition);}
/** * Resolve an ordered list of variant labels into one scalar target record. * * Arrays like `["base", "active"]` are not a request to animate twice. They are a request to * merge several named targets into one resolved lane, with later labels overriding earlier ones. */function resolveVariantLabels( labels: readonly string[], options: ResolvedStateOptions,): MotionTargetMap { // Variant labels are merged left-to-right so later labels can override earlier ones. // That matches the common Motion expectation for arrays like ["base", "active"]. const nextTarget = Object.create(null) as MotionTargetMap; let hasTarget = false;
for (const label of labels) { const variantTarget = resolveVariantTarget(label, options);
if (Object.keys(variantTarget).length === 0) { continue; }
Object.assign(nextTarget, variantTarget); hasTarget = true; }
return hasTarget ? nextTarget : EMPTY_TARGETS;}
/** * Resolve the entry target that should seed SSR output and the first mounted frame. * * `false` and `undefined` both mean "there is no dedicated entry target here". The caller can * then decide whether that implies falling back to `animate`, keeping only base style, or doing * nothing at all. */function resolveInitialTarget(options: ResolvedStateOptions): MotionTargetMap { if (options.initial === false || options.initial === undefined) { return EMPTY_TARGETS; }
return resolveTargetSource(options.initial, options);}
/** * Resolve one target source, which may be a direct object target or one or more variant labels. * * This helper is intentionally the last place that knows about Motion's mixed target vocabulary. * Everything below it works with plain scalar target records, so callers can treat object * targets, variant labels, and variant resolver functions as one unified "target source" input. */export function resolveTargetSource( value: MotionStateTargetDefinition | undefined, options: ResolvedStateOptions,): MotionTargetMap { if (value === undefined) return EMPTY_TARGETS; if (isVariantLabel(value)) return resolveVariantLabels(Array.isArray(value) ? value : [value], options);
if (typeof value === "function") return resolveVariantTarget(value, options);
return resolveTargetRecord(value);}
/** * Pick the currently winning lane by scanning the active table from highest to lowest priority. */export function getActiveTarget( options: ResolvedStateOptions, activeTargets: Record<MotionStateTargetKey, boolean>,): MotionStateTargetKey | undefined { for (const key of MOTION_STATE_TARGET_PRIORITY) { if (!activeTargets[key]) continue; if (options[key] === undefined) continue;
return key; }
return undefined;}
/** * Resolve the style and animated targets that the mounted renderer should currently apply. * * On the first mounted pass, MotionState can ask this helper to fold `initial` into the * style layer. That keeps the runtime honest with the SSR and hydration frame by seeding the * renderer's MotionValues from the same entry state before the active lane animates. */export function createSnapshot( options: ResolvedStateOptions, activeTargets: Record<MotionStateTargetKey, boolean>, includeInitial: boolean = false,): ResolvedStateSnapshot { // Snapshot creation deliberately happens in two layers: // 1. build the non-animated style base, optionally seeded with the initial target // 2. resolve the single winning animated lane on top of that base // // Keeping those outputs separate matches how the renderer thinks: one stable style layer plus // one animated layer that may replace overlapping keys for the current pass. const activeTarget = getActiveTarget(options, activeTargets); const baseStyleTarget = resolveTargetRecord(options.style); const initialTarget = includeInitial ? resolveInitialTarget(options) : EMPTY_TARGETS; const isInitialTargetEmpty = Object.keys(initialTarget).length === 0; const styleTarget = isInitialTargetEmpty ? baseStyleTarget : merge(baseStyleTarget, initialTarget);
return { styleTarget, animateTarget: activeTarget ? resolveTargetSource(options[activeTarget], options) : EMPTY_TARGETS, activeTarget, };}
/** * Resolve the deterministic style object that should be serialized before Motion mounts. * * This is the SSR and hydration fence. It stays pure and only resolves values that can be * known during render. The mounted runtime can then take over without needing to guess what * HTML or hydration should have looked like. * * Rules implemented here: * - base `style` always contributes * - `initial={false}` serializes the animate target instead of an entry state * - `initial={...}` serializes the resolved initial target * - if `initial` is omitted, serialize the animate target when one exists * * @example Entry state on first paint * ```ts * resolveInitialStyles({ * style: { opacity: 1 }, * initial: { opacity: 0 }, * animate: { opacity: 1 }, * }); * ``` * * @example No entry animation, serialize animate state * ```ts * resolveInitialStyles({ * initial: false, * animate: { opacity: 1 }, * }); * ``` */export function resolveInitialStyles(options: MotionStateOptions): MotionTargetMap { const resolvedOptions = resolveStateOptions(options); const baseStyle = resolveTargetRecord(resolvedOptions.style); let initialTarget = EMPTY_TARGETS;
if (resolvedOptions.initial === false || resolvedOptions.initial === undefined) { initialTarget = resolveTargetSource(resolvedOptions.animate, resolvedOptions); } else { initialTarget = resolveInitialTarget(resolvedOptions); }
if (Object.keys(initialTarget).length === 0) { // Even when there is no dedicated entry target, keep the static style path aligned with // motion-dom's HTML serializer so CSS variables and transform-origin formatting stay // consistent with the mounted runtime. return buildStaticStyle(baseStyle); }
return buildStaticStyle( merge(baseStyle, initialTarget) as MotionTargetMap, );}