WaitUntilOnPage: add option to load when approaching viewport

This commit is contained in:
infinite-persistence 2021-07-05 11:54:55 +08:00
parent 9745d6df3e
commit bb8fb038ca
No known key found for this signature in database
GPG key ID: B9C3252EDC3D0AA0
2 changed files with 26 additions and 17 deletions

View file

@ -8,31 +8,40 @@ type Props = {
children: any,
skipWait?: boolean,
placeholder?: any,
yOffset?: number,
};
export default function WaitUntilOnPage(props: Props) {
const { yOffset } = props;
const ref = React.useRef();
const [shouldRender, setShouldRender] = React.useState(false);
const shouldElementRender = React.useCallback((ref) => {
const shouldElementRender = React.useCallback(
(ref) => {
const element = ref && ref.current;
if (element) {
const bounding = element.getBoundingClientRect();
if (
// $FlowFixMe
const windowH = window.innerHeight || document.documentElement.clientHeight;
// $FlowFixMe
const windowW = window.innerWidth || document.documentElement.clientWidth;
const isApproachingViewport = yOffset && bounding.top < windowH + yOffset;
const isInViewport = // also covers "element is larger than viewport".
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;
}
bounding.top <= windowH &&
bounding.left <= windowW;
return isInViewport || isApproachingViewport;
}
return false;
}, []);
},
[yOffset]
);
// Handles "element is already in viewport when mounted".
React.useEffect(() => {

View file

@ -63,7 +63,7 @@ function HomePage(props: Props) {
{index === 0 && <>{claimTiles}</>}
{index !== 0 && (
<WaitUntilOnPage name={title} placeholder={tilePlaceholder}>
<WaitUntilOnPage name={title} placeholder={tilePlaceholder} yOffset={800}>
{claimTiles}
</WaitUntilOnPage>
)}