lbry-desktop/ui/component/common/wait-until-on-page.jsx
infiinte-persistence 1383b19817 WaitUntilOnPage: Debounce to fix false positives.
There are cases where `WaitUntilOnPage` will incorrectly render, such as at the beginning if the upper components hasn't expanded to full size, so `WaitUntilOnPage` would be briefly visible.

Added a 300ms debounce to fix this, which would also improve scrolling performance a bit by doing less. Hopefully 300ms is enough for the upper components to inflate to full size.
2020-07-29 17:56:38 -04:00

45 lines
1.2 KiB
JavaScript

// @flow
import React from 'react';
import debounce from 'util/debounce';
const DEBOUNCE_SCROLL_HANDLER_MS = 300;
type Props = {
children: any,
};
export default function WaitUntilOnPage(props: Props) {
const ref = React.useRef();
const [shouldRender, setShouldRender] = React.useState(false);
React.useEffect(() => {
const handleDisplayingRef = debounce(e => {
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);
return () => window.removeEventListener('scroll', handleDisplayingRef);
}
}, DEBOUNCE_SCROLL_HANDLER_MS);
if (ref) {
handleDisplayingRef();
}
}, [ref, setShouldRender, shouldRender]);
return <div ref={ref}>{shouldRender && props.children}</div>;
}