@heroui/use-image
Version:
React hook for progressing image loading
79 lines (78 loc) • 2.04 kB
JavaScript
// src/index.ts
import { useRef, useState, useCallback } from "react";
import { useIsHydrated } from "@heroui/react-utils";
import { useSafeLayoutEffect } from "@heroui/use-safe-layout-effect";
function useImage(props = {}) {
const {
onLoad,
onError,
ignoreFallback,
src,
crossOrigin,
srcSet,
sizes,
loading,
shouldBypassImageLoad = false
} = props;
const isHydrated = useIsHydrated();
const imageRef = useRef(null);
const [status, setStatus] = useState("pending");
const flush = useCallback(() => {
if (imageRef.current) {
imageRef.current.onload = null;
imageRef.current.onerror = null;
imageRef.current = null;
}
}, []);
const load = useCallback(() => {
if (!src) return "pending";
if (ignoreFallback || shouldBypassImageLoad) return "loaded";
flush();
const img = new Image();
img.onload = (event) => {
flush();
setStatus("loaded");
onLoad == null ? void 0 : onLoad(event);
};
img.onerror = (error) => {
flush();
setStatus("failed");
onError == null ? void 0 : onError(error);
};
if (crossOrigin) img.crossOrigin = crossOrigin;
if (srcSet) img.srcset = srcSet;
if (sizes) img.sizes = sizes;
if (loading) img.loading = loading;
img.src = src;
imageRef.current = img;
if (img.complete) {
if (img.naturalWidth && img.naturalHeight) {
return "loaded";
}
return "failed";
}
return "loading";
}, [
src,
crossOrigin,
srcSet,
sizes,
onLoad,
onError,
ignoreFallback,
loading,
shouldBypassImageLoad,
flush
]);
useSafeLayoutEffect(() => {
if (isHydrated) {
setStatus(load());
}
}, [isHydrated, load]);
return ignoreFallback ? "loaded" : status;
}
var shouldShowFallbackImage = (status, fallbackStrategy) => status !== "loaded" && fallbackStrategy === "beforeLoadOrError" || status === "failed" && fallbackStrategy === "onError";
export {
shouldShowFallbackImage,
useImage
};