GoScrobble/web/node_modules/react-overlays/esm/useWaitForDOMRef.js

38 lines
1.1 KiB
JavaScript
Raw Normal View History

2022-04-25 02:47:15 +00:00
import ownerDocument from 'dom-helpers/ownerDocument';
import { useState, useEffect } from 'react';
export var resolveContainerRef = function resolveContainerRef(ref) {
var _ref;
if (typeof document === 'undefined') return null;
if (ref == null) return ownerDocument().body;
if (typeof ref === 'function') ref = ref();
if (ref && 'current' in ref) ref = ref.current;
if ((_ref = ref) != null && _ref.nodeType) return ref || null;
return null;
};
export default function useWaitForDOMRef(ref, onResolved) {
var _useState = useState(function () {
return resolveContainerRef(ref);
}),
resolvedRef = _useState[0],
setRef = _useState[1];
if (!resolvedRef) {
var earlyRef = resolveContainerRef(ref);
if (earlyRef) setRef(earlyRef);
}
useEffect(function () {
if (onResolved && resolvedRef) {
onResolved(resolvedRef);
}
}, [onResolved, resolvedRef]);
useEffect(function () {
var nextRef = resolveContainerRef(ref);
if (nextRef !== resolvedRef) {
setRef(nextRef);
}
}, [ref, resolvedRef]);
return resolvedRef;
}