import React, { useCallback, useState } from "react"; import { useInView } from "react-intersection-observer"; type State = { lazyLoad: boolean; isSsr: boolean; isIntersectionObserverAvailable: boolean; inView?: boolean; loaded: boolean; }; const imageAddStrategy = ({ lazyLoad, isSsr, isIntersectionObserverAvailable, inView, loaded, }: State) => { if (!lazyLoad) { return true; } if (isSsr) { return false; } if (isIntersectionObserverAvailable) { return inView || loaded; } return true; }; const imageShowStrategy = ({ lazyLoad, isSsr, isIntersectionObserverAvailable, loaded, }: State) => { if (!lazyLoad) { return true; } if (isSsr) { return false; } if (isIntersectionObserverAvailable) { return loaded; } return true; }; type ImageData = { aspectRatio: number; base64?: string; height?: number; width: number; sizes?: string; src?: string; srcSet?: string; webpSrcSet?: string; bgColor?: string; alt?: string; title?: string; }; type ImageProps = { data: ImageData; className?: string; pictureClassName?: string; fadeInDuration?: number; intersectionTreshold?: number; intersectionThreshold?: number; intersectionMargin?: string; lazyLoad?: boolean; style?: React.CSSProperties; pictureStyle?: React.CSSProperties; explicitWidth?: boolean; }; const Image = function ({ className, fadeInDuration, intersectionTreshold, intersectionMargin, pictureClassName, lazyLoad = true, style, pictureStyle, explicitWidth, data, }: ImageProps) { const [loaded, setLoaded] = useState(false); const handleLoad = useCallback(() => { setLoaded(true); }, []); const [ref, inView] = useInView({ threshold: intersectionTreshold || 0, rootMargin: intersectionMargin || "0px 0px 0px 0px", triggerOnce: true, }); const isSsr = typeof window === "undefined"; const isIntersectionObserverAvailable = isSsr ? false : !!window.IntersectionObserver; const absolutePositioning: React.CSSProperties = { position: "absolute", left: 0, top: 0, bottom: 0, right: 0, }; const addImage = imageAddStrategy({ lazyLoad, isSsr, isIntersectionObserverAvailable, inView, loaded, }); const showImage = imageShowStrategy({ lazyLoad, isSsr, isIntersectionObserverAvailable, inView, loaded, }); const webpSource = data.webpSrcSet && ( ); const regularSource = data.srcSet && ( ); const placeholder = (
0 ? `opacity ${fadeInDuration || 500}ms ${fadeInDuration || 500}ms` : null, ...absolutePositioning, }} /> ); const { width, aspectRatio } = data; const height = data.height || width / aspectRatio; const sizer = ( ); return (
{sizer} {placeholder} {addImage && ( 0 ? `opacity ${fadeInDuration || 500}ms` : null, }} > {webpSource} {regularSource} {data.src && ( {data.alt} )} )}
); }; export default Image;