https://dev.kronoz.win/r/marzneshin.git
1import React from "react";
2
3type PossibleRef<T> = React.Ref<T> | undefined;
4
5/**
6 * Set a given ref to a given value
7 * This utility takes care of different types of refs: callback refs and RefObject(s)
8 */
9function setRef<T>(ref: PossibleRef<T>, value: T) {
10 if (typeof ref === "function") {
11 ref(value);
12 } else if (ref !== null && ref !== undefined) {
13 (ref as React.MutableRefObject<T>).current = value;
14 }
15}
16
17/**
18 * A utility to compose multiple refs together
19 * Accepts callback refs and RefObject(s)
20 */
21function composeRefs<T>(...refs: PossibleRef<T>[]) {
22 return (node: T) => {
23 refs.forEach((ref) => setRef(ref, node));
24 };
25}
26
27/**
28 * A custom hook that composes multiple refs
29 * Accepts callback refs and RefObject(s)
30 */
31function useComposedRefs<T>(...refs: PossibleRef<T>[]) {
32 return React.useCallback((node: T) => {
33 refs.forEach((ref) => setRef(ref, node));
34 }, [refs]);
35}
36
37export { composeRefs, useComposedRefs };