| 16 | * Merges multiple refs into one. Works with either callback or object refs. |
| 17 | */ |
| 18 | export function mergeRefs<T>( |
| 19 | ...refs: Array<Ref<T> | MutableRefObject<T> | null | undefined> |
| 20 | ): Ref<T> { |
| 21 | if (refs.length === 1 && refs[0]) { |
| 22 | return refs[0]; |
| 23 | } |
| 24 | |
| 25 | return (value: T | null) => { |
| 26 | let hasCleanup = false; |
| 27 | |
| 28 | const cleanups = refs.map(ref => { |
| 29 | const cleanup = setRef(ref, value); |
| 30 | hasCleanup ||= typeof cleanup == 'function'; |
| 31 | return cleanup; |
| 32 | }); |
| 33 | |
| 34 | if (hasCleanup) { |
| 35 | return () => { |
| 36 | cleanups.forEach((cleanup, i) => { |
| 37 | if (typeof cleanup === 'function') { |
| 38 | cleanup(); |
| 39 | } else { |
| 40 | setRef(refs[i], null); |
| 41 | } |
| 42 | }); |
| 43 | }; |
| 44 | } |
| 45 | }; |
| 46 | } |
| 47 | |
| 48 | function setRef<T>(ref: Ref<T> | MutableRefObject<T> | null | undefined, value: T) { |
| 49 | if (typeof ref === 'function') { |