@nextui-org/use-image
Version:
React hook for progressing image loading
91 lines (89 loc) • 3.1 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
shouldShowFallbackImage: () => shouldShowFallbackImage,
useImage: () => useImage
});
module.exports = __toCommonJS(src_exports);
var import_react = require("react");
var import_react_utils = require("@nextui-org/react-utils");
var import_use_safe_layout_effect = require("@nextui-org/use-safe-layout-effect");
function useImage(props = {}) {
const { onLoad, onError, ignoreFallback } = props;
const isHydrated = (0, import_react_utils.useIsHydrated)();
const imageRef = (0, import_react.useRef)(isHydrated ? new Image() : null);
const [status, setStatus] = (0, import_react.useState)("pending");
(0, import_react.useEffect)(() => {
if (!imageRef.current)
return;
imageRef.current.onload = (event) => {
flush();
setStatus("loaded");
onLoad == null ? void 0 : onLoad(event);
};
imageRef.current.onerror = (error) => {
flush();
setStatus("failed");
onError == null ? void 0 : onError(error);
};
}, [imageRef.current]);
const flush = () => {
if (imageRef.current) {
imageRef.current.onload = null;
imageRef.current.onerror = null;
imageRef.current = null;
}
};
(0, import_use_safe_layout_effect.useSafeLayoutEffect)(() => {
if (isHydrated) {
setStatus(setImageAndGetInitialStatus(props, imageRef));
}
}, [isHydrated]);
return ignoreFallback ? "loaded" : status;
}
function setImageAndGetInitialStatus(props, imageRef) {
const { loading, src, srcSet, crossOrigin, sizes, ignoreFallback } = props;
if (!src)
return "pending";
if (ignoreFallback)
return "loaded";
const img = new Image();
img.src = src;
if (crossOrigin)
img.crossOrigin = crossOrigin;
if (srcSet)
img.srcset = srcSet;
if (sizes)
img.sizes = sizes;
if (loading)
img.loading = loading;
imageRef.current = img;
if (img.complete && img.naturalWidth) {
return "loaded";
}
return "loading";
}
var shouldShowFallbackImage = (status, fallbackStrategy) => status !== "loaded" && fallbackStrategy === "beforeLoadOrError" || status === "failed" && fallbackStrategy === "onError";
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
shouldShowFallbackImage,
useImage
});