import type { JSX, ValidComponent } from "solid-js"; import { createMotionComponent } from "./create-motion-component.tsx"; import type { MotionComponent, MotionCreateOptions, MotionNamespace, } from "./motion-component-types.ts"; // Custom components default to filtering Motion props at the wrapper boundary. const filteredComponentCache = new Map(); // Forwarded wrappers need their own cache because their prop contract is different. const forwardedComponentCache = new Map(); /** * Keep separate caches for the two public forwarding modes. * * `forwardMotionProps` changes the wrapper's prop-filtering contract, so a cached * component built for the filtered mode cannot be safely reused for the forwarded mode. */ function getComponentCache(options?: MotionCreateOptions): Map { return options?.forwardMotionProps ? forwardedComponentCache : filteredComponentCache; } /** * Return a stable Motion wrapper for one intrinsic tag or custom component. * * The wrapper factory itself is cheap, but repeated property reads like `motion.div` are * part of the public API surface. This cache keeps those reads stable and makes the Proxy * behave like a namespace of reusable components rather than a namespace of fresh factory * calls. */ function getCachedMotionComponent( component: T, options?: MotionCreateOptions, ): MotionComponent { const cache = getComponentCache(options); const cached = cache.get(component); if (cached) return cached as MotionComponent; const nextComponent = createMotionComponent(component, options); cache.set(component, nextComponent); return nextComponent; } /** * Exposes Motion's Solid component namespace through a cached Proxy. * * The cache matters because `motion.div` and `motion.create(Card)` should return stable * wrapper component identities. Recreating those factories on every property read would * make animation state harder to preserve and would drift away from Motion's established * API behavior. * * @example Primary member component API * ```tsx * * ``` * * @example Dynamic intrinsic creation * ```tsx * const MotionDialog = motion.create("dialog"); * ``` */ export const motion = new Proxy({} as MotionNamespace, { get(_, property: string) { if (property === "create") { // `motion.create(...)` is the explicit factory form for custom components or // dynamic intrinsic tags. return function create( component: T, options?: MotionCreateOptions, ): MotionComponent { return getCachedMotionComponent(component, options); }; } // Member access like `motion.div` is just shorthand for asking the cache for the // wrapper around a specific intrinsic element. return getCachedMotionComponent(property as keyof JSX.IntrinsicElements); }, });