UNPKG

@shopify/hydrogen-react

Version:

React components, hooks, and utilities for creating custom Shopify storefronts

100 lines (99 loc) 2.94 kB
"use strict"; Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } }); const imageSize = require("./image-size.js"); const jsxRuntime = require("react/jsx-runtime"); function Image({ data, width, height, loading, loader = imageSize.shopifyImageLoader, loaderOptions, widths, decoding = "async", ...rest }) { var _a, _b, _c, _d, _e, _f; if (!data.url) { const missingUrlError = `<Image/>: the 'data' prop requires the 'url' property. Image: ${(_a = data.id) != null ? _a : "no ID provided"}`; { console.error(missingUrlError); } return null; } const { width: imgElementWidth, height: imgElementHeight } = imageSize.getShopifyImageDimensions({ data, loaderOptions, elementProps: { width, height } }); let finalSrc = data.url; if (loader) { finalSrc = loader({ ...loaderOptions, src: data.url, width: imgElementWidth, height: imgElementHeight }); if (typeof finalSrc !== "string" || !finalSrc) { throw new Error(`<Image/>: 'loader' did not return a valid string. Image: ${(_b = data.id) != null ? _b : data.url}`); } } const maxWidth = width && imgElementWidth && width < imgElementWidth ? width : imgElementWidth; const finalSrcset = (_c = rest.srcSet) != null ? _c : internalImageSrcSet({ ...loaderOptions, widths, src: data.url, width: maxWidth, height: imgElementHeight, loader }); return /* @__PURE__ */ jsxRuntime.jsx("img", { id: (_d = data.id) != null ? _d : "", alt: (_f = (_e = data.altText) != null ? _e : rest.alt) != null ? _f : "", loading: loading != null ? loading : "lazy", ...rest, src: finalSrc, width: imgElementWidth != null ? imgElementWidth : void 0, height: imgElementHeight != null ? imgElementHeight : void 0, srcSet: finalSrcset, decoding }); } function internalImageSrcSet({ src, width, crop, scale, widths, loader, height }) { const hasCustomWidths = widths && Array.isArray(widths); if (hasCustomWidths && widths.some((size) => isNaN(size))) { throw new Error(`<Image/>: the 'widths' must be an array of numbers. Image: ${src}`); } let aspectRatio = 1; if (width && height) { aspectRatio = Number(height) / Number(width); } let setSizes = hasCustomWidths ? widths : imageSize.IMG_SRC_SET_SIZES; if (!hasCustomWidths && width && width < imageSize.IMG_SRC_SET_SIZES[imageSize.IMG_SRC_SET_SIZES.length - 1]) { setSizes = imageSize.IMG_SRC_SET_SIZES.filter((size) => size <= width); } const srcGenerator = loader ? loader : imageSize.addImageSizeParametersToUrl; return setSizes.map((size) => `${srcGenerator({ src, width: size, height: crop ? Number(size) * aspectRatio : void 0, crop, scale })} ${size}w`).join(", "); } exports.Image = Image; //# sourceMappingURL=Image.js.map