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

View file

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