4dc333de41
## Issue 6010: hyperchat send display issues with GIF profiles The FreezeFrameWrapper have no `src` to freeze due to the lazy loading. ## Fix Delay the freezing by making the lazy-load effect return a state to indicate when then `src` has been loaded. Since the lazy-loader will `unobserve` after loading, the state will never go back to false, so we don't need to handle the case of preventing `new FreezeFrameWrapper` from being called multiple times from it's effect.
57 lines
1.5 KiB
JavaScript
57 lines
1.5 KiB
JavaScript
// @flow
|
|
import type { ElementRef } from 'react';
|
|
import React, { useEffect } from 'react';
|
|
|
|
/**
|
|
* Helper React hook for lazy loading images
|
|
* @param elementRef - A React useRef instance to the element to lazy load.
|
|
* @param {Number} [threshold=0.5] - The percent visible in order for loading to begin.
|
|
* @param {Array<>} [deps=[]] - The dependencies this lazy-load is reliant on.
|
|
*/
|
|
export default function useLazyLoading(
|
|
elementRef: { current: ?ElementRef<any> },
|
|
threshold: number = 0.25,
|
|
deps: Array<any> = []
|
|
) {
|
|
const [srcLoaded, setSrcLoaded] = React.useState(false);
|
|
|
|
useEffect(() => {
|
|
if (!elementRef.current) {
|
|
return;
|
|
}
|
|
|
|
const lazyLoadingObserver = new IntersectionObserver(
|
|
(entries, observer) => {
|
|
entries.forEach((entry) => {
|
|
if (entry.intersectionRatio >= threshold) {
|
|
const { target } = entry;
|
|
|
|
observer.unobserve(target);
|
|
|
|
// useful for lazy loading img tags
|
|
if (target.dataset.src) {
|
|
// $FlowFixMe
|
|
target.src = target.dataset.src;
|
|
setSrcLoaded(true);
|
|
return;
|
|
}
|
|
|
|
// useful for lazy loading background images on divs
|
|
if (target.dataset.backgroundImage) {
|
|
target.style.backgroundImage = `url(${target.dataset.backgroundImage})`;
|
|
}
|
|
}
|
|
});
|
|
},
|
|
{
|
|
root: null,
|
|
rootMargin: '0px',
|
|
threshold,
|
|
}
|
|
);
|
|
|
|
lazyLoadingObserver.observe(elementRef.current);
|
|
}, deps);
|
|
|
|
return srcLoaded;
|
|
}
|