2020-05-29 22:34:54 +02:00
|
|
|
// @flow
|
|
|
|
import React from 'react';
|
2020-07-25 09:06:25 +02:00
|
|
|
import debounce from 'util/debounce';
|
|
|
|
|
2021-06-15 09:17:08 +02:00
|
|
|
const DEBOUNCE_SCROLL_HANDLER_MS = 25;
|
2020-05-29 22:34:54 +02:00
|
|
|
|
|
|
|
type Props = {
|
|
|
|
children: any,
|
2020-08-24 19:35:21 +02:00
|
|
|
skipWait?: boolean,
|
2021-06-15 08:41:03 +02:00
|
|
|
placeholder?: any,
|
2020-05-29 22:34:54 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
export default function WaitUntilOnPage(props: Props) {
|
|
|
|
const ref = React.useRef();
|
|
|
|
const [shouldRender, setShouldRender] = React.useState(false);
|
|
|
|
|
|
|
|
React.useEffect(() => {
|
2021-06-15 08:41:03 +02:00
|
|
|
const handleDisplayingRef = debounce((e) => {
|
2020-05-29 22:34:54 +02:00
|
|
|
const element = ref && ref.current;
|
|
|
|
if (element) {
|
|
|
|
const bounding = element.getBoundingClientRect();
|
|
|
|
if (
|
2021-06-15 08:41:03 +02:00
|
|
|
bounding.bottom >= 0 &&
|
|
|
|
bounding.right >= 0 &&
|
2020-05-29 22:34:54 +02:00
|
|
|
// $FlowFixMe
|
2021-06-15 08:41:03 +02:00
|
|
|
bounding.top <= (window.innerHeight || document.documentElement.clientHeight) &&
|
2020-05-29 22:34:54 +02:00
|
|
|
// $FlowFixMe
|
2021-06-15 08:41:03 +02:00
|
|
|
bounding.left <= (window.innerWidth || document.documentElement.clientWidth)
|
2020-05-29 22:34:54 +02:00
|
|
|
) {
|
|
|
|
setShouldRender(true);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (element && !shouldRender) {
|
|
|
|
window.addEventListener('scroll', handleDisplayingRef);
|
2020-07-25 09:06:25 +02:00
|
|
|
return () => window.removeEventListener('scroll', handleDisplayingRef);
|
2020-05-29 22:34:54 +02:00
|
|
|
}
|
2020-07-25 09:06:25 +02:00
|
|
|
}, DEBOUNCE_SCROLL_HANDLER_MS);
|
2020-05-29 22:34:54 +02:00
|
|
|
|
|
|
|
if (ref) {
|
|
|
|
handleDisplayingRef();
|
|
|
|
}
|
|
|
|
}, [ref, setShouldRender, shouldRender]);
|
|
|
|
|
2021-06-15 08:41:03 +02:00
|
|
|
const render = props.skipWait || shouldRender;
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div ref={ref}>
|
|
|
|
{render && props.children}
|
|
|
|
{!render && props.placeholder !== undefined && props.placeholder}
|
|
|
|
</div>
|
|
|
|
);
|
2020-05-29 22:34:54 +02:00
|
|
|
}
|