framer-motion
Version:
A simple and powerful JavaScript animation library
66 lines (63 loc) • 2.2 kB
JavaScript
"use client";
import { useRef, useCallback } from 'react';
import { isRefObject } from '../../utils/is-ref-object.mjs';
/**
* Set a given ref to a given value
* This utility takes care of different types of refs: callback refs and RefObject(s)
* Returns a cleanup function if the ref callback returns one (React 19 feature)
*/
function setRef(ref, value) {
if (typeof ref === "function") {
return ref(value);
}
else if (isRefObject(ref)) {
ref.current = value;
}
}
/**
* Creates a ref function that, when called, hydrates the provided
* external ref and VisualElement.
*/
function useMotionRef(visualState, visualElement, externalRef) {
// Store the cleanup function from external ref if it returns one
const externalRefCleanupRef = useRef(null);
return useCallback((instance) => {
if (instance) {
visualState.onMount && visualState.onMount(instance);
}
if (visualElement) {
if (instance) {
visualElement.mount(instance);
}
else {
visualElement.unmount();
}
}
if (externalRef) {
if (instance) {
// Mount: call the external ref and store any cleanup function
const cleanup = setRef(externalRef, instance);
if (typeof cleanup === "function") {
externalRefCleanupRef.current = cleanup;
}
}
else {
// Unmount: call stored cleanup function if available, otherwise call ref with null
if (externalRefCleanupRef.current) {
externalRefCleanupRef.current();
externalRefCleanupRef.current = null;
}
else {
// Fallback to React <19 behavior for refs that don't return cleanup
setRef(externalRef, instance);
}
}
}
},
/**
* Include all dependencies to ensure the callback updates correctly
*/
[]);
}
export { useMotionRef };
//# sourceMappingURL=use-motion-ref.mjs.map