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';
|
|
|
|
|
|
|
|
const DEBOUNCE_SCROLL_HANDLER_MS = 300;
|
2020-05-29 22:34:54 +02:00
|
|
|
|
|
|
|
type Props = {
|
|
|
|
children: any,
|
2020-07-25 11:03:22 +02:00
|
|
|
lastUpdateDate?: any,
|
2020-08-24 19:35:21 +02:00
|
|
|
skipWait?: boolean,
|
2020-05-29 22:34:54 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
export default function WaitUntilOnPage(props: Props) {
|
|
|
|
const ref = React.useRef();
|
|
|
|
const [shouldRender, setShouldRender] = React.useState(false);
|
|
|
|
|
2020-07-25 11:03:22 +02:00
|
|
|
React.useEffect(() => {
|
|
|
|
setShouldRender(false);
|
|
|
|
}, [props.lastUpdateDate]);
|
|
|
|
|
2020-05-29 22:34:54 +02:00
|
|
|
React.useEffect(() => {
|
2020-07-25 09:06:25 +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 (
|
|
|
|
bounding.top >= 0 &&
|
|
|
|
bounding.left >= 0 &&
|
|
|
|
// $FlowFixMe
|
|
|
|
bounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
|
|
|
|
// $FlowFixMe
|
|
|
|
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight)
|
|
|
|
) {
|
|
|
|
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]);
|
|
|
|
|
2020-08-24 19:35:21 +02:00
|
|
|
return <div ref={ref}>{(props.skipWait || shouldRender) && props.children}</div>;
|
2020-05-29 22:34:54 +02:00
|
|
|
}
|