mirror of
https://github.com/zoriya/v10.git
synced 2026-08-09 15:46:42 +00:00
55 lines
1.4 KiB
JavaScript
55 lines
1.4 KiB
JavaScript
"use client";
|
|
import { useCallback } from "react";
|
|
import { isFunction } from "@videojs/utils/predicate";
|
|
//#region src/utils/use-composed-refs.ts
|
|
/**
|
|
* Set a given ref to a given value.
|
|
*
|
|
* Handles both callback refs and RefObject(s).
|
|
*
|
|
* @returns Cleanup function if the ref callback returned one (React 19+)
|
|
*/
|
|
function setRef(ref, value) {
|
|
if (isFunction(ref)) return ref(value);
|
|
else if (ref !== null && ref !== void 0) ref.current = value;
|
|
}
|
|
/**
|
|
* Compose multiple refs into a single callback ref.
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* const composedRef = composeRefs(ref1, ref2, ref3);
|
|
* return <div ref={composedRef} />;
|
|
* ```
|
|
*/
|
|
function composeRefs(...refs) {
|
|
const flatRefs = refs.flat();
|
|
return (node) => {
|
|
const cleanups = flatRefs.map((ref) => setRef(ref, node));
|
|
if (cleanups.some(isFunction)) return () => {
|
|
for (let i = 0; i < cleanups.length; i++) {
|
|
const cleanup = cleanups[i];
|
|
if (isFunction(cleanup)) cleanup();
|
|
else setRef(flatRefs[i], null);
|
|
}
|
|
};
|
|
};
|
|
}
|
|
/**
|
|
* Hook that composes multiple refs into a single callback ref.
|
|
*
|
|
* Memoized for stable reference.
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* const composedRef = useComposedRefs(forwardedRef, localRef);
|
|
* return <div ref={composedRef} />;
|
|
* ```
|
|
*/
|
|
function useComposedRefs(...refs) {
|
|
return useCallback(composeRefs(...refs), [...refs]);
|
|
}
|
|
//#endregion
|
|
export { composeRefs, useComposedRefs };
|
|
|
|
//# sourceMappingURL=use-composed-refs.js.map
|