{"version":3,"file":"use-motion-ref.mjs","sources":["../../../../src/motion/utils/use-motion-ref.ts"],"sourcesContent":["\"use client\"\n\nimport * as React from \"react\"\nimport { useCallback, useRef } from \"react\"\nimport type { VisualElement } from \"../../render/VisualElement\"\nimport { isRefObject } from \"../../utils/is-ref-object\"\nimport { VisualState } from \"./use-visual-state\"\n\n/**\n * Set a given ref to a given value\n * This utility takes care of different types of refs: callback refs and RefObject(s)\n * Returns a cleanup function if the ref callback returns one (React 19 feature)\n */\nfunction setRef<T>(ref: React.Ref<T>, value: T): void | (() => void) {\n    if (typeof ref === \"function\") {\n        return ref(value)\n    } else if (isRefObject(ref)) {\n        ;(ref as any).current = value\n    }\n}\n\n/**\n * Creates a ref function that, when called, hydrates the provided\n * external ref and VisualElement.\n */\nexport function useMotionRef<Instance, RenderState>(\n    visualState: VisualState<Instance, RenderState>,\n    visualElement?: VisualElement<Instance> | null,\n    externalRef?: React.Ref<Instance>\n): React.Ref<Instance> {\n    // Store the cleanup function from external ref if it returns one\n    const externalRefCleanupRef = useRef<(() => void) | null>(null)\n\n    return useCallback(\n        (instance: Instance) => {\n            if (instance) {\n                visualState.onMount && visualState.onMount(instance)\n            }\n\n            if (visualElement) {\n                if (instance) {\n                    visualElement.mount(instance)\n                } else {\n                    visualElement.unmount()\n                }\n            }\n\n            if (externalRef) {\n                if (instance) {\n                    // Mount: call the external ref and store any cleanup function\n                    const cleanup = setRef(externalRef, instance)\n                    if (typeof cleanup === \"function\") {\n                        externalRefCleanupRef.current = cleanup\n                    }\n                } else {\n                    // Unmount: call stored cleanup function if available, otherwise call ref with null\n                    if (externalRefCleanupRef.current) {\n                        externalRefCleanupRef.current()\n                        externalRefCleanupRef.current = null\n                    } else {\n                        // Fallback to React <19 behavior for refs that don't return cleanup\n                        setRef(externalRef, instance)\n                    }\n                }\n            }\n        },\n        /**\n         * Include all dependencies to ensure the callback updates correctly\n         */\n        [visualElement, visualState, externalRef]\n    )\n}\n"],"names":[],"mappings":";;;;AAQA;;;;AAIG;AACH;AACI;AACI;;AACG;AACD;;AAEV;AAEA;;;AAGG;;;AAOC;AAEA;;;;;;AAQgB;;;;;;;;;;AAUA;AACI;;;;;AAIJ;;AAEI;;;;AAGA;;;;;AAKhB;;AAEG;AACH;AAER;;"}