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-07-05 05:27:22 +02:00
|
|
|
const DEBOUNCE_SCROLL_HANDLER_MS = 50;
|
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);
|
|
|
|
|
2021-07-05 05:27:22 +02:00
|
|
|
const shouldElementRender = React.useCallback((ref) => {
|
|
|
|
const element = ref && ref.current;
|
|
|
|
if (element) {
|
|
|
|
const bounding = element.getBoundingClientRect();
|
|
|
|
if (
|
|
|
|
bounding.width > 0 &&
|
|
|
|
bounding.height > 0 &&
|
|
|
|
bounding.bottom >= 0 &&
|
|
|
|
bounding.right >= 0 &&
|
|
|
|
// $FlowFixMe
|
|
|
|
bounding.top <= (window.innerHeight || document.documentElement.clientHeight) &&
|
|
|
|
// $FlowFixMe
|
|
|
|
bounding.left <= (window.innerWidth || document.documentElement.clientWidth)
|
|
|
|
) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
// Handles "element is already in viewport when mounted".
|
2020-05-29 22:34:54 +02:00
|
|
|
React.useEffect(() => {
|
2021-07-05 05:27:22 +02:00
|
|
|
setTimeout(() => {
|
|
|
|
if (!shouldRender && shouldElementRender(ref)) {
|
|
|
|
setShouldRender(true);
|
2020-05-29 22:34:54 +02:00
|
|
|
}
|
2021-07-05 05:27:22 +02:00
|
|
|
}, 500);
|
|
|
|
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
2020-05-29 22:34:54 +02:00
|
|
|
|
2021-07-05 05:27:22 +02:00
|
|
|
// Handles "element scrolled into viewport".
|
|
|
|
React.useEffect(() => {
|
|
|
|
const handleDisplayingRef = debounce(() => {
|
|
|
|
if (shouldElementRender(ref)) {
|
|
|
|
setShouldRender(true);
|
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
|
|
|
|
2021-07-05 05:27:22 +02:00
|
|
|
if (ref && ref.current && !shouldRender) {
|
|
|
|
window.addEventListener('scroll', handleDisplayingRef);
|
|
|
|
return () => window.removeEventListener('scroll', handleDisplayingRef);
|
2020-05-29 22:34:54 +02:00
|
|
|
}
|
2021-07-05 05:27:22 +02:00
|
|
|
}, [ref, setShouldRender, shouldRender, shouldElementRender]);
|
2020-05-29 22:34:54 +02:00
|
|
|
|
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
|
|
|
}
|