// Ref: https://github.com/gregberge/react-merge-refs/blob/812fefa4390884a4a2d1bc489d869bd088df8ff5/src/index.tsx
import type { MutableRefObject, LegacyRef, RefCallback } from "react";

export function mergeRefs<T = unknown>(
  refs: Array<MutableRefObject<T> | LegacyRef<T> | undefined>,
): RefCallback<T> {
  return value => {
    refs.forEach(ref => {
      if (typeof ref === "function") {
        ref(value);
      } else if (ref != null) {
        (ref as MutableRefObject<T | null>).current = value;
      }
    });
  };
}
