Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/solid-motion-experiments.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316import type { Ref } from "@solid-primitives/refs";import type { Accessor, JSX, ValidComponent } from "solid-js";import { mergeRefs } from "@solid-primitives/refs";import { Dynamic } from "solid-js/web";
import { solid1Adapter } from "../adapter/solid1.ts";import { resolveMaybeAccessor } from "../motion/resolve-motion-prop.ts";import { splitMotionProps } from "../motion/split-motion-props.ts";import { trackPresenceKey } from "../presence/_presence-key-registry.ts";import { usePresenceContext } from "../presence/presence-context.tsx";
import { createMotionState } from "./create-motion-state.ts";import { resolveInitialStyles } from "./_motion-state-options.ts";
import type { MotionComponent, MotionComponentProps, MotionCreateOptions,} from "./motion-component-types.ts";import type { MotionStateOptions } from "./create-motion-state.ts";import type { SolidMotionAdapter } from "../adapter/types.ts";import type { PresenceContextValue } from "../presence/presence-context.tsx";
/** * Wrapper-local control props that never belong to the rendered host. * * These keys are split before Motion props so later reads can still distinguish between wrapper * behavior like `as` switching and actual animation configuration. */export const LOCAL_PROP_KEYS = ["as", "forwardMotionProps"] as const;
/** * Shared empty prop bag for the "filter Motion props out" branch. * * Returning one frozen object here keeps the forwarded-prop merge stable when a custom component * should not receive Motion-owned props at all. */export const EMPTY_PROPS = Object.freeze(Object.create(null)) as Record<string, never>;
/** * Only `false` has cross-boundary meaning for inherited presence initial state. * * A presence boundary can suppress descendant entry animations by providing * `initial={false}`. The boundary should not manufacture a truthy `initial` target for * descendants, because real entry targets still belong to the motion component itself. */function resolveInheritedInitial( localInitial: MotionStateOptions["initial"] | undefined, inheritedInitial: boolean | undefined,): MotionStateOptions["initial"] | undefined { if (localInitial !== undefined) return localInitial;
return inheritedInitial === false ? false : undefined;}
/** * Copy one defined MotionState option into the next snapshot. * * The wrapper assembles a plain object snapshot for MotionState on each tracked pass. This * helper keeps the bridge easy to scan by separating "which option wins" from "omit * undefined keys so MotionState sees a clean sparse object". */function assignStateOption<K extends keyof MotionStateOptions>( target: MotionStateOptions, key: K, value: MotionStateOptions[K] | undefined,): void { if (value === undefined) return;
Object.assign(target, { [key]: value } as Pick<MotionStateOptions, K>);}
/** * Build the sparse option snapshot that MotionState owns for the current reactive pass. * * The wrapper still decides two boundary-level rules before handing control to MotionState: * * ```text * local motion props * + inherited presence initial/custom * -> sparse MotionStateOptions snapshot * -> MotionState resolves active lane and renderer output * ``` * * Everything after this snapshot belongs to MotionState. Keeping the translation here makes the * Solid wrapper responsible only for boundary concerns: inherited presence data, prop splitting, * and DOM ref ownership. */function createStateOptionsSnapshot( motionProps: MotionStateOptions, presence: Pick<PresenceContextValue, "initial" | "custom"> | undefined,): MotionStateOptions { const stateOpts = Object.create(null) as MotionStateOptions; const initial = resolveInheritedInitial(motionProps.initial, presence?.initial); const custom = motionProps.custom ?? presence?.custom;
assignStateOption(stateOpts, "initial", initial); assignStateOption(stateOpts, "style", motionProps.style); assignStateOption(stateOpts, "animate", motionProps.animate); assignStateOption(stateOpts, "exit", motionProps.exit); assignStateOption(stateOpts, "variants", motionProps.variants); assignStateOption(stateOpts, "custom", custom); assignStateOption(stateOpts, "transition", motionProps.transition); assignStateOption(stateOpts, "presenceKey", motionProps.presenceKey); assignStateOption(stateOpts, "layout", motionProps.layout); assignStateOption(stateOpts, "layoutDependency", motionProps.layoutDependency); assignStateOption(stateOpts, "layoutId", motionProps.layoutId); assignStateOption(stateOpts, "layoutRoot", motionProps.layoutRoot); assignStateOption(stateOpts, "layoutScroll", motionProps.layoutScroll); assignStateOption(stateOpts, "layoutAnchor", motionProps.layoutAnchor); assignStateOption( stateOpts, "onLayoutAnimationStart", motionProps.onLayoutAnimationStart, ); assignStateOption( stateOpts, "onLayoutAnimationComplete", motionProps.onLayoutAnimationComplete, ); assignStateOption(stateOpts, "whileFocus", motionProps.whileFocus); assignStateOption(stateOpts, "whileHover", motionProps.whileHover); assignStateOption(stateOpts, "whileInView", motionProps.whileInView); assignStateOption(stateOpts, "whilePress", motionProps.whilePress); assignStateOption(stateOpts, "whileTap", motionProps.whileTap);
return stateOpts;}
/** * Creates a Motion component for one intrinsic tag or custom Solid component. * * The factory keeps the public Motion shape that callers expect from other Motion * integrations, while replacing the internals with Solid-native mechanics: * split reactive props lazily, render with `Dynamic`, and reserve explicit seams for a * later visual-element runtime. * * The current scaffold deliberately does not clone children for `asChild`. Vue and React * can build that feature around a VNode or element-cloning model that Solid does not * share. The Solid version keeps that boundary explicit until a render-prop or other * Solid-native design is chosen. * * @example Common HTML element * ```tsx * const MotionDiv = createMotionComponent("div"); * ``` * * @example Custom component with filtered Motion props * ```tsx * const MotionCard = createMotionComponent(Card); * ``` */export function createMotionComponent<T extends ValidComponent>( baseComponent: T, options: MotionCreateOptions = {}, adapter: SolidMotionAdapter = solid1Adapter,): MotionComponent<T> { return function MotionComponent(rawProps: MotionComponentProps<T>) { const state = createMotionState(); const presence = usePresenceContext(adapter); const presenceId = Symbol("motion-presence");
let latestOptions = Object.create(null) as MotionStateOptions; let unregisterPresence: VoidFunction | undefined; let stopExitCompletion: VoidFunction | undefined; let hasDisposedMotionState = false;
// Split wrapper-local controls away first so the remaining prop bag stays reactive. const [local, forwardedProps] = adapter.splitProps(rawProps, LOCAL_PROP_KEYS);
// Motion props and DOM props need different lifecycles: Motion is observed in // tracked effects later, while DOM props are forwarded straight to Dynamic. const [motionProps, domProps] = splitMotionProps(forwardedProps, adapter);
const componentToRender = () => local.as ?? baseComponent; const shouldForwardMotionProps = () => local.forwardMotionProps ?? options.forwardMotionProps ?? false;
// The wrapper re-snapshots Motion options on each tracked pass because MotionState owns a // plain object contract, not Solid's proxy-backed prop graph. function getStateOptions(): MotionStateOptions { return createStateOptionsSnapshot(motionProps, presence); }
// This is the "fully let go of Motion" path. It tears down three separate relationships: // the async exit-complete listener, the current presence registration, and the MotionState // itself. Keeping that grouped in one helper makes retained-exit and normal unmount cleanup // share the exact same terminal behavior. function disposeMotionState(): void { if (hasDisposedMotionState) return;
hasDisposedMotionState = true; stopExitCompletion?.(); stopExitCompletion = undefined;
unregisterPresence?.(); unregisterPresence = undefined;
state.destroy(); }
// Presence boundaries only need an identity plus two imperative hooks. They do not need to // know about DOM refs, Solid props, or the internal renderer. This narrow handle is the seam // that lets `PresenceChild` drive exit after the component owner has already started disposing. const handle = { id: presenceId, get presenceKey(): string | number | undefined { return motionProps.presenceKey; }, startExit(): void { // This path must not rely on Solid tracking. It can run after this // component's owner has already started cleaning up. // Reapply the latest option snapshot first so exit resolves against the last known variants, // custom payload, and transition config instead of whatever partial cleanup state remains. state.updateOptions(latestOptions); state.setIsPresent(false); }, dispose(): void { disposeMotionState(); }, };
const [element, setElement] = adapter.createSignal<HTMLElement | SVGElement | undefined>(); const ref = mergeRefs(rawProps.ref as Ref<unknown>, (value: unknown) => { // The local ref stays signal-backed so Motion can react if the rendered host node // ever changes, while mergeRefs preserves the caller's original Solid ref contract. if (value instanceof HTMLElement || value instanceof SVGElement) { setElement(value); } else { setElement(undefined); } });
adapter.onClientMount(() => { stopExitCompletion = state.onExitComplete(() => { // Exit completion settles asynchronously after Motion finishes animating. By that time // there may be no current Solid owner, so re-reading context here is not reliable. // Keep the latest boundary reference from the tracked effect below and forward through it. presence?.onExitComplete?.(presenceId); });
adapter.createTrackedEffect(() => { /** * Read the Solid-facing lifecycle inputs that can change MotionState on this pass. * * Grouping these values makes the tracked effect read top-to-bottom as: * 1. observe Solid state * 2. sync presence registration * 3. sync MotionState * 4. sync host mount state */ const isPresent = presence ? resolveMaybeAccessor(presence.isPresent) : true; const shouldRegisterPresence = ( presence?.register !== undefined && motionProps.exit !== undefined ); const currentElement = element(); const stateOptions = getStateOptions(); latestOptions = stateOptions;
if (shouldRegisterPresence && !unregisterPresence) { // Exit-aware descendants only participate when both sides exist: a surrounding presence // boundary to aggregate completion, and a local `exit` lane that can actually animate. unregisterPresence = presence?.register?.(handle); } else if (!shouldRegisterPresence && unregisterPresence) { unregisterPresence(); unregisterPresence = undefined; }
// Presence becomes a first-class MotionState input here. Exit is now activated by // logical absence, even though retained rendering and exit completion land later. state.updateOptions(stateOptions); state.setIsPresent(isPresent);
if (currentElement) { state.mount(currentElement); } else if (!unregisterPresence) { // A retained exiting descendant can temporarily lose its Solid owner before the parent // boundary is ready to destroy MotionState. Skip `unmount()` while presence still owns it. state.unmount(); } });
adapter.onDispose(() => { // Motion subscriptions and animations are external resources, so they need an // explicit owner-scoped cleanup instead of relying on garbage collection. const shouldRetain = presence?.retainOnOwnerDispose?.(presenceId) ?? false; if (shouldRetain) { // Do not unregister and do not destroy. The retained PresenceChild // will call handle.dispose() after exit completion. return; }
disposeMotionState(); }); });
const props = adapter.mergeProps( domProps, // This style path stays pure so SSR and hydration can serialize the same first-frame // values without waiting for Motion to mount and attach its renderer. () => ({ style: resolveInitialStyles(getStateOptions()) }), // Custom components should not receive Motion-only props unless explicitly opted in. () => (shouldForwardMotionProps() ? motionProps : EMPTY_PROPS), { ref }, );
const renderedChild = ( <Dynamic component={componentToRender() as ValidComponent} {...props} /> );
return trackPresenceKey(renderedChild, motionProps.presenceKey); };}