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