@shopify/hydrogen-react 2024.7.1 → 2024.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/browser-dev/Image.mjs +29 -11
  2. package/dist/browser-dev/Image.mjs.map +1 -1
  3. package/dist/browser-dev/ProductPrice.mjs +30 -10
  4. package/dist/browser-dev/ProductPrice.mjs.map +1 -1
  5. package/dist/browser-dev/analytics.mjs +8 -0
  6. package/dist/browser-dev/analytics.mjs.map +1 -1
  7. package/dist/browser-dev/useMoney.mjs +43 -29
  8. package/dist/browser-dev/useMoney.mjs.map +1 -1
  9. package/dist/browser-prod/Image.mjs +29 -11
  10. package/dist/browser-prod/Image.mjs.map +1 -1
  11. package/dist/browser-prod/ProductPrice.mjs +30 -10
  12. package/dist/browser-prod/ProductPrice.mjs.map +1 -1
  13. package/dist/browser-prod/analytics.mjs +8 -0
  14. package/dist/browser-prod/analytics.mjs.map +1 -1
  15. package/dist/browser-prod/useMoney.mjs +43 -29
  16. package/dist/browser-prod/useMoney.mjs.map +1 -1
  17. package/dist/node-dev/Image.js +29 -11
  18. package/dist/node-dev/Image.js.map +1 -1
  19. package/dist/node-dev/Image.mjs +29 -11
  20. package/dist/node-dev/Image.mjs.map +1 -1
  21. package/dist/node-dev/ProductPrice.js +30 -10
  22. package/dist/node-dev/ProductPrice.js.map +1 -1
  23. package/dist/node-dev/ProductPrice.mjs +30 -10
  24. package/dist/node-dev/ProductPrice.mjs.map +1 -1
  25. package/dist/node-dev/analytics.js +8 -0
  26. package/dist/node-dev/analytics.js.map +1 -1
  27. package/dist/node-dev/analytics.mjs +8 -0
  28. package/dist/node-dev/analytics.mjs.map +1 -1
  29. package/dist/node-dev/useMoney.js +43 -29
  30. package/dist/node-dev/useMoney.js.map +1 -1
  31. package/dist/node-dev/useMoney.mjs +43 -29
  32. package/dist/node-dev/useMoney.mjs.map +1 -1
  33. package/dist/node-prod/Image.js +29 -11
  34. package/dist/node-prod/Image.js.map +1 -1
  35. package/dist/node-prod/Image.mjs +29 -11
  36. package/dist/node-prod/Image.mjs.map +1 -1
  37. package/dist/node-prod/ProductPrice.js +30 -10
  38. package/dist/node-prod/ProductPrice.js.map +1 -1
  39. package/dist/node-prod/ProductPrice.mjs +30 -10
  40. package/dist/node-prod/ProductPrice.mjs.map +1 -1
  41. package/dist/node-prod/analytics.js +8 -0
  42. package/dist/node-prod/analytics.js.map +1 -1
  43. package/dist/node-prod/analytics.mjs +8 -0
  44. package/dist/node-prod/analytics.mjs.map +1 -1
  45. package/dist/node-prod/useMoney.js +43 -29
  46. package/dist/node-prod/useMoney.js.map +1 -1
  47. package/dist/node-prod/useMoney.mjs +43 -29
  48. package/dist/node-prod/useMoney.mjs.map +1 -1
  49. package/dist/types/Image.d.ts +4 -1
  50. package/dist/umd/hydrogen-react.dev.js +110 -50
  51. package/dist/umd/hydrogen-react.dev.js.map +1 -1
  52. package/dist/umd/hydrogen-react.prod.js +17 -17
  53. package/dist/umd/hydrogen-react.prod.js.map +1 -1
  54. package/package.json +2 -2
@@ -108,7 +108,8 @@ const Image = React.forwardRef(
108
108
  normalizedProps,
109
109
  passthroughProps,
110
110
  ref,
111
- width
111
+ width,
112
+ data
112
113
  }
113
114
  );
114
115
  } else {
@@ -125,7 +126,8 @@ const Image = React.forwardRef(
125
126
  passthroughProps,
126
127
  placeholderWidth,
127
128
  ref,
128
- sizes
129
+ sizes,
130
+ data
129
131
  }
130
132
  );
131
133
  }
@@ -142,13 +144,17 @@ const FixedWidthImage = React.forwardRef(
142
144
  loading,
143
145
  normalizedProps,
144
146
  passthroughProps,
145
- width
147
+ width,
148
+ data
146
149
  }, ref) => {
147
150
  const fixed = React.useMemo(() => {
148
151
  const intWidth = getNormalizedFixedUnit(width);
149
152
  const intHeight = getNormalizedFixedUnit(height);
150
153
  const fixedAspectRatio = aspectRatio ? aspectRatio : unitsMatch(normalizedProps.width, normalizedProps.height) ? [intWidth, intHeight].join("/") : normalizedProps.aspectRatio ? normalizedProps.aspectRatio : void 0;
151
- const sizesArray = imageWidths === void 0 ? void 0 : generateSizes(imageWidths, fixedAspectRatio, crop);
154
+ const sizesArray = imageWidths === void 0 ? void 0 : generateSizes(imageWidths, fixedAspectRatio, crop, {
155
+ width: (data == null ? void 0 : data.width) ?? void 0,
156
+ height: (data == null ? void 0 : data.height) ?? void 0
157
+ });
152
158
  const fixedHeight = intHeight ? intHeight : fixedAspectRatio && intWidth ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1) : void 0;
153
159
  const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);
154
160
  const src = loader({
@@ -167,6 +173,7 @@ const FixedWidthImage = React.forwardRef(
167
173
  }, [
168
174
  aspectRatio,
169
175
  crop,
176
+ data,
170
177
  height,
171
178
  imageWidths,
172
179
  loader,
@@ -203,10 +210,14 @@ const FluidImage = React.forwardRef(
203
210
  normalizedProps,
204
211
  passthroughProps,
205
212
  placeholderWidth,
206
- sizes
213
+ sizes,
214
+ data
207
215
  }, ref) => {
208
216
  const fluid = React.useMemo(() => {
209
- const sizesArray = imageWidths === void 0 ? void 0 : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);
217
+ const sizesArray = imageWidths === void 0 ? void 0 : generateSizes(imageWidths, normalizedProps.aspectRatio, crop, {
218
+ width: (data == null ? void 0 : data.width) ?? void 0,
219
+ height: (data == null ? void 0 : data.height) ?? void 0
220
+ });
210
221
  const placeholderHeight = normalizedProps.aspectRatio && placeholderWidth ? placeholderWidth * (parseAspectRatio(normalizedProps.aspectRatio) ?? 1) : void 0;
211
222
  const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);
212
223
  const src = loader({
@@ -220,7 +231,7 @@ const FluidImage = React.forwardRef(
220
231
  srcSet,
221
232
  src
222
233
  };
223
- }, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);
234
+ }, [crop, data, imageWidths, loader, normalizedProps, placeholderWidth]);
224
235
  return /* @__PURE__ */ jsx(
225
236
  "img",
226
237
  {
@@ -290,7 +301,7 @@ function getNormalizedFixedUnit(value) {
290
301
  }
291
302
  function isFixedWidth(width) {
292
303
  const fixedEndings = /\d(px|em|rem)$/;
293
- return typeof width === "number" || typeof width === "string" && fixedEndings.test(width);
304
+ return typeof width === "number" || fixedEndings.test(width);
294
305
  }
295
306
  function generateSrcSet(src, sizesArray, loader = shopifyLoader) {
296
307
  if (!src) {
@@ -325,17 +336,24 @@ function parseAspectRatio(aspectRatio) {
325
336
  const [width, height] = aspectRatio.split("/");
326
337
  return 1 / (Number(width) / Number(height));
327
338
  }
328
- function generateSizes(imageWidths, aspectRatio, crop = "center") {
339
+ function generateSizes(imageWidths, aspectRatio, crop = "center", sourceDimensions) {
329
340
  if (!imageWidths)
330
341
  return;
331
- const sizes = imageWidths.map((width) => {
342
+ return imageWidths.map((width) => {
332
343
  return {
333
344
  width,
334
345
  height: aspectRatio ? width * (parseAspectRatio(aspectRatio) ?? 1) : void 0,
335
346
  crop
336
347
  };
348
+ }).filter(({ width, height }) => {
349
+ if ((sourceDimensions == null ? void 0 : sourceDimensions.width) && width > sourceDimensions.width) {
350
+ return false;
351
+ }
352
+ if ((sourceDimensions == null ? void 0 : sourceDimensions.height) && height && height > sourceDimensions.height) {
353
+ return false;
354
+ }
355
+ return true;
337
356
  });
338
- return sizes;
339
357
  }
340
358
  export {
341
359
  IMAGE_FRAGMENT,
@@ -1 +1 @@
1
- {"version":3,"file":"Image.mjs","sources":["../../src/Image.tsx"],"sourcesContent":["/* eslint-disable eslint-comments/disable-enable-pair */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable hydrogen/prefer-image-component */\nimport * as React from 'react';\nimport type {PartialDeep} from 'type-fest';\nimport type {Image as ImageType} from './storefront-api-types.js';\n\n/*\n * An optional prop you can use to change the\n * default srcSet generation behaviour\n */\ntype SrcSetOptions = {\n /** The number of sizes to generate */\n intervals: number;\n /** The smallest image size */\n startingWidth: number;\n /** The increment by which to increase for each size, in pixels */\n incrementSize: number;\n /** The size used for placeholder fallback images */\n placeholderWidth: number;\n};\n\ntype NormalizedProps = {\n alt: string;\n aspectRatio: string | undefined;\n height: string;\n src: string | undefined;\n width: string;\n};\n\nexport type LoaderParams = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: number;\n /** The URL param that controls height */\n height?: number;\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\n\nexport type Loader = (params: LoaderParams) => string;\n\n/*\n * @TODO: Expand to include focal point support; and/or switch this to be an SF API type\n */\ntype Crop = 'center' | 'top' | 'bottom' | 'left' | 'right';\n\nexport type HydrogenImageProps = React.ComponentPropsWithRef<'img'> &\n HydrogenImageBaseProps;\n\ntype HydrogenImageBaseProps = {\n /** The aspect ratio of the image, in the format of `width/height`.\n *\n * @example\n * ```\n * <Image data={productImage} aspectRatio=\"4/5\" />\n * ```\n */\n aspectRatio?: string;\n /** The crop position of the image.\n *\n * @remarks\n * In the event that AspectRatio is set, without specifying a crop,\n * the Shopify CDN won't return the expected image.\n *\n * @defaultValue `center`\n */\n crop?: Crop;\n /** Data mapping to the [Storefront API `Image`](https://shopify.dev/docs/api/storefront/2024-07/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrogen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loading = 'lazy',\n sizes,\n src,\n srcSetOptions = {\n intervals: 15,\n startingWidth: 200,\n incrementSize: 200,\n placeholderWidth: 100,\n },\n width = '100%',\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n};\n\nconst FixedWidthImage = React.forwardRef<\n HTMLImageElement,\n FixedWidthImageProps\n>(\n (\n {\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n width,\n },\n ref,\n ) => {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all of the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop);\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [\n aspectRatio,\n crop,\n height,\n imageWidths,\n loader,\n normalizedProps,\n width,\n ]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fixed.height}\n loading={loading}\n src={fixed.src}\n srcSet={fixed.srcSet}\n width={fixed.width}\n style={{\n aspectRatio: fixed.aspectRatio,\n ...passthroughProps.style,\n }}\n {...passthroughProps}\n />\n );\n },\n);\n\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n};\n\nconst FluidImage = React.forwardRef<HTMLImageElement, FluidImageProps>(\n (\n {\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n sizes,\n },\n ref,\n ) => {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n },\n);\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href;\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return (\n typeof width === 'number' ||\n (typeof width === 'string' && fixedEndings.test(width))\n );\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n const sizes = imageWidths.map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n });\n return sizes;\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\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YAAY;AACpC,WAAA;AAAA,EACT;AAEA,SAAO,WACJ;AAAA,IACC,CAAC,MAAM,MACL,GAAG,OAAO;AAAA,MACR;AAAA,MACA,OAAO,KAAK;AAAA,MACZ,QAAQ,KAAK;AAAA,MACb,MAAM,KAAK;AAAA,IAAA,CACZ,CAAC,IAAI,WAAW,WAAW,IAAI,GAAG,IAAI,CAAC,MAAM,GAAG,KAAK,SAAS,CAAC,GAAG;AAAA,EAAA,EAEtE,KAAK,IAAI;AACd;AAUO,SAAS,oBACd,QAAyB,QACzB,WACA,eACA,eACU;AACV,QAAM,aAAa,MAAM;AAAA,IACvB,EAAC,QAAQ,UAAS;AAAA,IAClB,CAAC,GAAG,MAAM,IAAI,gBAAgB;AAAA,EAAA;AAGhC,QAAM,QAAQ,MAAM;AAAA,IAClB,EAAC,QAAQ,EAAC;AAAA,IACV,CAAC,GAAG,OAAO,IAAI,MAAM,uBAAuB,KAAK,KAAK;AAAA,EAAA;AAGjD,SAAA,aAAa,KAAK,IAAI,QAAQ;AACvC;AASO,SAAS,iBAAiB,aAA0C;AACzE,MAAI,CAAC;AAAa;AAClB,QAAM,CAAC,OAAO,MAAM,IAAI,YAAY,MAAM,GAAG;AAC7C,SAAO,KAAK,OAAO,KAAK,IAAI,OAAO,MAAM;AAC3C;AAGO,SAAS,cACd,aACA,aACA,OAAa,UAOD;AACZ,MAAI,CAAC;AAAa;AAClB,QAAM,QAAQ,YAAY,IAAI,CAAC,UAAkB;AACxC,WAAA;AAAA,MACL;AAAA,MACA,QAAQ,cACJ,SAAS,iBAAiB,WAAW,KAAK,KAC1C;AAAA,MACJ;AAAA,IAAA;AAAA,EACF,CACD;AACM,SAAA;AAQT;"}
1
+ {"version":3,"file":"Image.mjs","sources":["../../src/Image.tsx"],"sourcesContent":["/* eslint-disable eslint-comments/disable-enable-pair */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable hydrogen/prefer-image-component */\nimport * as React from 'react';\nimport type {PartialDeep} from 'type-fest';\nimport type {Image as ImageType} from './storefront-api-types.js';\n\n/*\n * An optional prop you can use to change the\n * default srcSet generation behaviour\n */\ntype SrcSetOptions = {\n /** The number of sizes to generate */\n intervals: number;\n /** The smallest image size */\n startingWidth: number;\n /** The increment by which to increase for each size, in pixels */\n incrementSize: number;\n /** The size used for placeholder fallback images */\n placeholderWidth: number;\n};\n\ntype NormalizedProps = {\n alt: string;\n aspectRatio: string | undefined;\n height: string;\n src: string | undefined;\n width: string;\n};\n\nexport type LoaderParams = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: number;\n /** The URL param that controls height */\n height?: number;\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\n\nexport type Loader = (params: LoaderParams) => string;\n\n/*\n * @TODO: Expand to include focal point support; and/or switch this to be an SF API type\n */\ntype Crop = 'center' | 'top' | 'bottom' | 'left' | 'right';\n\nexport type HydrogenImageProps = React.ComponentPropsWithRef<'img'> &\n HydrogenImageBaseProps;\n\ntype HydrogenImageBaseProps = {\n /** The aspect ratio of the image, in the format of `width/height`.\n *\n * @example\n * ```\n * <Image data={productImage} aspectRatio=\"4/5\" />\n * ```\n */\n aspectRatio?: string;\n /** The crop position of the image.\n *\n * @remarks\n * In the event that AspectRatio is set, without specifying a crop,\n * the Shopify CDN won't return the expected image.\n *\n * @defaultValue `center`\n */\n crop?: Crop;\n /** Data mapping to the [Storefront API `Image`](https://shopify.dev/docs/api/storefront/2024-07/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrogen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loading = 'lazy',\n sizes,\n src,\n srcSetOptions = {\n intervals: 15,\n startingWidth: 200,\n incrementSize: 200,\n placeholderWidth: 100,\n },\n width = '100%',\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n data={data}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n data={data}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> &\n Pick<HydrogenImageBaseProps, 'data'> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n };\n\nconst FixedWidthImage = React.forwardRef<\n HTMLImageElement,\n FixedWidthImageProps\n>(\n (\n {\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n width,\n data,\n },\n ref,\n ) => {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop, {\n width: data?.width ?? undefined,\n height: data?.height ?? undefined,\n });\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [\n aspectRatio,\n crop,\n data,\n height,\n imageWidths,\n loader,\n normalizedProps,\n width,\n ]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fixed.height}\n loading={loading}\n src={fixed.src}\n srcSet={fixed.srcSet}\n width={fixed.width}\n style={{\n aspectRatio: fixed.aspectRatio,\n ...passthroughProps.style,\n }}\n {...passthroughProps}\n />\n );\n },\n);\n\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> &\n Pick<HydrogenImageBaseProps, 'data'> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n };\n\nconst FluidImage = React.forwardRef<HTMLImageElement, FluidImageProps>(\n (\n {\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n sizes,\n data,\n },\n ref,\n ) => {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop, {\n width: data?.width ?? undefined,\n height: data?.height ?? undefined,\n });\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, data, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n },\n);\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href;\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return typeof width === 'number' || fixedEndings.test(width);\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n sourceDimensions?: {width?: number; height?: number},\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n return imageWidths\n .map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n })\n .filter(({width, height}) => {\n if (sourceDimensions?.width && width > sourceDimensions.width) {\n return false;\n }\n\n if (\n sourceDimensions?.height &&\n height &&\n height > sourceDimensions.height\n ) {\n return false;\n }\n\n return true;\n });\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n"],"names":[],"mappings":";;AA6GO,MAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2CvB,MAAM,QAAQ,MAAM;AAAA,EACzB,CACE;AAAA,IACE;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP;AAAA,IACA,WAAW;AAAA,IACX,SAAS;AAAA,IACT,SAAS;AAAA,IACT,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,MACd,WAAW;AAAA,MACX,eAAe;AAAA,MACf,eAAe;AAAA,MACf,kBAAkB;AAAA,IACpB;AAAA,IACA,QAAQ;AAAA,IACR,GAAG;AAAA,KAEL,QACG;AAIG,UAAA,iBAAiB,MAAM,QAAQ,MAAM;AAEzC,YAAM,aACJ,6BAAM,WAAS,6BAAM,UAAS,6BAAM,QAAQ;AAE9C,YAAM,cACJ,6BAAM,WAAS,6BAAM,UAAS,6BAAM,SAAS;AAExC,aAAA;AAAA,QACL,OAAO;AAAA,QACP,QAAQ;AAAA,QACR,YAAY,QAAQ,WAAW,WAAW,UAAU,CAAC;AAAA,MAAA;AAAA,IACvD,GACC,CA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uBAAuB,KAAK,KAAK;AAAA,EAAA;AAGjD,SAAA,aAAa,KAAK,IAAI,QAAQ;AACvC;AASO,SAAS,iBAAiB,aAA0C;AACzE,MAAI,CAAC;AAAa;AAClB,QAAM,CAAC,OAAO,MAAM,IAAI,YAAY,MAAM,GAAG;AAC7C,SAAO,KAAK,OAAO,KAAK,IAAI,OAAO,MAAM;AAC3C;AAGO,SAAS,cACd,aACA,aACA,OAAa,UACb,kBAOY;AACZ,MAAI,CAAC;AAAa;AACX,SAAA,YACJ,IAAI,CAAC,UAAkB;AACf,WAAA;AAAA,MACL;AAAA,MACA,QAAQ,cACJ,SAAS,iBAAiB,WAAW,KAAK,KAC1C;AAAA,MACJ;AAAA,IAAA;AAAA,EAEH,CAAA,EACA,OAAO,CAAC,EAAC,OAAO,aAAY;AAC3B,SAAI,qDAAkB,UAAS,QAAQ,iBAAiB,OAAO;AACtD,aAAA;AAAA,IACT;AAEA,SACE,qDAAkB,WAClB,UACA,SAAS,iBAAiB,QAC1B;AACO,aAAA;AAAA,IACT;AAEO,WAAA;AAAA,EAAA,CACR;AAQL;"}
@@ -2,7 +2,7 @@ import { jsx } from "react/jsx-runtime";
2
2
  import { Money } from "./Money.mjs";
3
3
  import { flattenConnection } from "./flatten-connection.mjs";
4
4
  function ProductPrice(props) {
5
- var _a, _b, _c, _d, _e, _f;
5
+ var _a, _b, _c, _d, _e, _f, _g;
6
6
  const {
7
7
  priceType = "regular",
8
8
  variantId,
@@ -18,28 +18,48 @@ function ProductPrice(props) {
18
18
  const variant = variantId ? flattenConnection((product == null ? void 0 : product.variants) ?? {}).find(
19
19
  (variant2) => (variant2 == null ? void 0 : variant2.id) === variantId
20
20
  ) ?? null : null;
21
+ const variantPriceProperty = valueType === "max" ? "maxVariantPrice" : "minVariantPrice";
21
22
  if (priceType === "compareAt") {
22
23
  if (variantId && variant) {
23
- if (((_a = variant.compareAtPriceV2) == null ? void 0 : _a.amount) === ((_b = variant.priceV2) == null ? void 0 : _b.amount)) {
24
- return null;
24
+ if (variant.compareAtPriceV2) {
25
+ console.error(
26
+ "<ProductPrice> `compareAtPriceV2` is deprecated. Use `compareAtPrice` instead."
27
+ );
25
28
  }
26
- price = variant.compareAtPriceV2;
27
- } else if (valueType === "max") {
28
- price = (_c = product == null ? void 0 : product.compareAtPriceRange) == null ? void 0 : _c.maxVariantPrice;
29
+ price = variant.compareAtPrice ?? variant.compareAtPriceV2;
30
+ } else {
31
+ price = (_a = product == null ? void 0 : product.compareAtPriceRange) == null ? void 0 : _a[variantPriceProperty];
32
+ }
33
+ let priceAsNumber;
34
+ if (variantId && variant) {
35
+ priceAsNumber = parseFloat(
36
+ ((_b = variant.price) == null ? void 0 : _b.amount) ?? ((_c = variant.priceV2) == null ? void 0 : _c.amount) ?? "0"
37
+ );
29
38
  } else {
30
- price = (_d = product == null ? void 0 : product.compareAtPriceRange) == null ? void 0 : _d.minVariantPrice;
39
+ priceAsNumber = parseFloat(
40
+ ((_e = (_d = product == null ? void 0 : product.priceRange) == null ? void 0 : _d[variantPriceProperty]) == null ? void 0 : _e.amount) ?? "0"
41
+ );
42
+ }
43
+ const compareAtPriceAsNumber = parseFloat((price == null ? void 0 : price.amount) ?? "0");
44
+ if (priceAsNumber >= compareAtPriceAsNumber) {
45
+ return null;
31
46
  }
32
47
  } else {
33
48
  if (variantId && variant) {
34
- price = variant.priceV2;
49
+ if (variant.priceV2) {
50
+ console.error(
51
+ "<ProductPrice> `priceV2` is deprecated. Use `price` instead."
52
+ );
53
+ }
54
+ price = variant.price ?? variant.priceV2;
35
55
  if (valueType === "unit") {
36
56
  price = variant.unitPrice;
37
57
  measurement = variant.unitPriceMeasurement;
38
58
  }
39
59
  } else if (valueType === "max") {
40
- price = (_e = product.priceRange) == null ? void 0 : _e.maxVariantPrice;
60
+ price = (_f = product.priceRange) == null ? void 0 : _f.maxVariantPrice;
41
61
  } else {
42
- price = (_f = product.priceRange) == null ? void 0 : _f.minVariantPrice;
62
+ price = (_g = product.priceRange) == null ? void 0 : _g.minVariantPrice;
43
63
  }
44
64
  }
45
65
  if (!price) {
@@ -1 +1 @@
1
- {"version":3,"file":"ProductPrice.mjs","sources":["../../src/ProductPrice.tsx"],"sourcesContent":["import type {\n MoneyV2,\n UnitPriceMeasurement,\n Product,\n} from './storefront-api-types.js';\nimport {Money, type MoneyProps, type MoneyPropsBase} from './Money.js';\nimport type {PartialDeep} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\nexport interface ProductPriceProps {\n /** A Storefront API [Product object](https://shopify.dev/api/storefront/reference/products/product). */\n data: PartialDeep<Product, {recurseIntoArrays: true}>;\n /** The type of price. Valid values: `regular` (default) or `compareAt`. */\n priceType?: 'regular' | 'compareAt';\n /** The type of value. Valid values: `min` (default), `max` or `unit`. */\n valueType?: 'max' | 'min' | 'unit';\n /** The ID of the variant. */\n variantId?: string;\n}\n\n/**\n * The `ProductPrice` component renders a `Money` component with the product\n * [`priceRange`](https://shopify.dev/api/storefront/reference/products/productpricerange)'s `maxVariantPrice` or `minVariantPrice`, for either the regular price or compare at price range.\n */\nexport function ProductPrice<\n ComponentGeneric extends React.ElementType = 'div',\n>(\n props: ProductPriceProps &\n Omit<MoneyProps<ComponentGeneric>, 'data' | 'measurement'>,\n): JSX.Element | null {\n const {\n priceType = 'regular',\n variantId,\n valueType = 'min',\n data: product,\n ...passthroughProps\n } = props;\n\n if (product == null) {\n throw new Error(`<ProductPrice/> requires a product as the 'data' prop`);\n }\n\n let price: Partial<MoneyV2> | undefined | null;\n let measurement: Partial<UnitPriceMeasurement> | undefined | null;\n\n const variant = variantId\n ? flattenConnection(product?.variants ?? {}).find(\n (variant) => variant?.id === variantId,\n ) ?? null\n : null;\n\n if (priceType === 'compareAt') {\n if (variantId && variant) {\n if (variant.compareAtPriceV2?.amount === variant.priceV2?.amount) {\n return null;\n }\n price = variant.compareAtPriceV2;\n } else if (valueType === 'max') {\n price = product?.compareAtPriceRange?.maxVariantPrice;\n } else {\n price = product?.compareAtPriceRange?.minVariantPrice;\n }\n } else {\n if (variantId && variant) {\n price = variant.priceV2;\n if (valueType === 'unit') {\n price = variant.unitPrice;\n measurement = variant.unitPriceMeasurement;\n }\n } else if (valueType === 'max') {\n price = product.priceRange?.maxVariantPrice;\n } else {\n price = product.priceRange?.minVariantPrice;\n }\n }\n\n if (!price) {\n return null;\n }\n\n if (measurement) {\n return (\n <Money {...passthroughProps} data={price} measurement={measurement} />\n );\n }\n\n return <Money {...passthroughProps} data={price} />;\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface ProductPricePropsForDocs<\n AsType extends React.ElementType = 'div',\n> extends Omit<MoneyPropsBase<AsType>, 'data' | 'measurement'>,\n ProductPriceProps {}\n"],"names":["variant"],"mappings":";;;AAwBO,SAAS,aAGd,OAEoB;;AACd,QAAA;AAAA,IACJ,YAAY;AAAA,IACZ;AAAA,IACA,YAAY;AAAA,IACZ,MAAM;AAAA,IACN,GAAG;AAAA,EACD,IAAA;AAEJ,MAAI,WAAW,MAAM;AACb,UAAA,IAAI,MAAM,uDAAuD;AAAA,EACzE;AAEI,MAAA;AACA,MAAA;AAEJ,QAAM,UAAU,YACZ,mBAAkB,mCAAS,aAAY,CAAE,CAAA,EAAE;AAAA,IACzC,CAACA,cAAYA,qCAAS,QAAO;AAAA,EAAA,KAC1B,OACL;AAEJ,MAAI,cAAc,aAAa;AAC7B,QAAI,aAAa,SAAS;AACxB,YAAI,aAAQ,qBAAR,mBAA0B,cAAW,aAAQ,YAAR,mBAAiB,SAAQ;AACzD,eAAA;AAAA,MACT;AACA,cAAQ,QAAQ;AAAA,IAAA,WACP,cAAc,OAAO;AAC9B,eAAQ,wCAAS,wBAAT,mBAA8B;AAAA,IAAA,OACjC;AACL,eAAQ,wCAAS,wBAAT,mBAA8B;AAAA,IACxC;AAAA,EAAA,OACK;AACL,QAAI,aAAa,SAAS;AACxB,cAAQ,QAAQ;AAChB,UAAI,cAAc,QAAQ;AACxB,gBAAQ,QAAQ;AAChB,sBAAc,QAAQ;AAAA,MACxB;AAAA,IAAA,WACS,cAAc,OAAO;AAC9B,eAAQ,aAAQ,eAAR,mBAAoB;AAAA,IAAA,OACvB;AACL,eAAQ,aAAQ,eAAR,mBAAoB;AAAA,IAC9B;AAAA,EACF;AAEA,MAAI,CAAC,OAAO;AACH,WAAA;AAAA,EACT;AAEA,MAAI,aAAa;AACf,+BACG,OAAO,EAAA,GAAG,kBAAkB,MAAM,OAAO,YAA0B,CAAA;AAAA,EAExE;AAEA,SAAQ,oBAAA,OAAA,EAAO,GAAG,kBAAkB,MAAM,MAAO,CAAA;AACnD;"}
1
+ {"version":3,"file":"ProductPrice.mjs","sources":["../../src/ProductPrice.tsx"],"sourcesContent":["import type {\n MoneyV2,\n UnitPriceMeasurement,\n Product,\n} from './storefront-api-types.js';\nimport {Money, type MoneyProps, type MoneyPropsBase} from './Money.js';\nimport type {PartialDeep} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\nexport interface ProductPriceProps {\n /** A Storefront API [Product object](https://shopify.dev/api/storefront/reference/products/product). */\n data: PartialDeep<Product, {recurseIntoArrays: true}>;\n /** The type of price. Valid values: `regular` (default) or `compareAt`. */\n priceType?: 'regular' | 'compareAt';\n /** The type of value. Valid values: `min` (default), `max` or `unit`. */\n valueType?: 'max' | 'min' | 'unit';\n /** The ID of the variant. */\n variantId?: string;\n}\n\n/**\n * The `ProductPrice` component renders a `Money` component with the product\n * [`priceRange`](https://shopify.dev/api/storefront/reference/products/productpricerange)'s `maxVariantPrice` or `minVariantPrice`, for either the regular price or compare at price range.\n */\nexport function ProductPrice<\n ComponentGeneric extends React.ElementType = 'div',\n>(\n props: ProductPriceProps &\n Omit<MoneyProps<ComponentGeneric>, 'data' | 'measurement'>,\n): JSX.Element | null {\n const {\n priceType = 'regular',\n variantId,\n valueType = 'min',\n data: product,\n ...passthroughProps\n } = props;\n\n if (product == null) {\n throw new Error(`<ProductPrice/> requires a product as the 'data' prop`);\n }\n\n let price: Partial<MoneyV2> | undefined | null;\n let measurement: Partial<UnitPriceMeasurement> | undefined | null;\n\n const variant = variantId\n ? flattenConnection(product?.variants ?? {}).find(\n (variant) => variant?.id === variantId,\n ) ?? null\n : null;\n\n /**\n * @deprecated (Next major release) Stop using compareAtPriceV2 and priceV2\n */\n const variantPriceProperty =\n valueType === 'max' ? 'maxVariantPrice' : 'minVariantPrice';\n\n if (priceType === 'compareAt') {\n if (variantId && variant) {\n if (variant.compareAtPriceV2) {\n console.error(\n '<ProductPrice> `compareAtPriceV2` is deprecated. Use `compareAtPrice` instead.',\n );\n }\n\n price = variant.compareAtPrice ?? variant.compareAtPriceV2;\n } else {\n price = product?.compareAtPriceRange?.[variantPriceProperty];\n }\n\n let priceAsNumber: number;\n if (variantId && variant) {\n priceAsNumber = parseFloat(\n variant.price?.amount ?? variant.priceV2?.amount ?? '0',\n );\n } else {\n priceAsNumber = parseFloat(\n product?.priceRange?.[variantPriceProperty]?.amount ?? '0',\n );\n }\n\n const compareAtPriceAsNumber = parseFloat(price?.amount ?? '0');\n\n if (priceAsNumber >= compareAtPriceAsNumber) {\n return null;\n }\n } else {\n if (variantId && variant) {\n if (variant.priceV2) {\n console.error(\n '<ProductPrice> `priceV2` is deprecated. Use `price` instead.',\n );\n }\n\n price = variant.price ?? variant.priceV2;\n if (valueType === 'unit') {\n price = variant.unitPrice;\n measurement = variant.unitPriceMeasurement;\n }\n } else if (valueType === 'max') {\n price = product.priceRange?.maxVariantPrice;\n } else {\n price = product.priceRange?.minVariantPrice;\n }\n }\n\n if (!price) {\n return null;\n }\n\n if (measurement) {\n return (\n <Money {...passthroughProps} data={price} measurement={measurement} />\n );\n }\n\n return <Money {...passthroughProps} data={price} />;\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface ProductPricePropsForDocs<\n AsType extends React.ElementType = 'div',\n> extends Omit<MoneyPropsBase<AsType>, 'data' | 'measurement'>,\n ProductPriceProps {}\n"],"names":["variant"],"mappings":";;;AAwBO,SAAS,aAGd,OAEoB;;AACd,QAAA;A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eAAQ,aAAQ,eAAR,mBAAoB;AAAA,IAC9B;AAAA,EACF;AAEA,MAAI,CAAC,OAAO;AACH,WAAA;AAAA,EACT;AAEA,MAAI,aAAa;AACf,+BACG,OAAO,EAAA,GAAG,kBAAkB,MAAM,OAAO,YAA0B,CAAA;AAAA,EAExE;AAEA,SAAQ,oBAAA,OAAA,EAAO,GAAG,kBAAkB,MAAM,MAAO,CAAA;AACnD;"}
@@ -37,8 +37,16 @@ function sendShopifyAnalytics(event, shopDomain) {
37
37
  return Promise.resolve();
38
38
  }
39
39
  }
40
+ function isLighthouseUserAgent() {
41
+ if (typeof window === "undefined" || !window.navigator)
42
+ return false;
43
+ return /Chrome-Lighthouse/.test(window.navigator.userAgent);
44
+ }
40
45
  const ERROR_MESSAGE = "sendShopifyAnalytics request is unsuccessful";
41
46
  function sendToShopify(events, shopDomain) {
47
+ if (isLighthouseUserAgent()) {
48
+ return Promise.resolve();
49
+ }
42
50
  const eventsToBeSent = {
43
51
  events,
44
52
  metadata: {
@@ -1 +1 @@
1
- {"version":3,"file":"analytics.mjs","sources":["../../src/analytics.ts"],"sourcesContent":["import {SHOPIFY_S, SHOPIFY_Y} from './cart-constants.js';\nimport type {\n ClientBrowserParameters,\n ShopifyAddToCartPayload,\n ShopifyAnalytics,\n ShopifyPageViewPayload,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {AnalyticsEventName} from './analytics-constants.js';\nimport {errorIfServer} from './analytics-utils.js';\nimport {getShopifyCookies} from './cookies-utils.js';\n\nimport {pageView as trekkiePageView} from './analytics-schema-trekkie-storefront-page-view.js';\nimport {\n pageView as customerPageView,\n pageView2 as customerPageView2,\n collectionView as customerCollectionView,\n productView as customerProductView,\n searchView as customerSearchView,\n addToCart as customerAddToCart,\n} from './analytics-schema-custom-storefront-customer-tracking.js';\n\n/**\n * Set user and session cookies and refresh the expiry time\n * @param event - The analytics event.\n * @param shopDomain - The Online Store domain to sent Shopify analytics under the same\n * top level domain.\n */\nexport function sendShopifyAnalytics(\n event: ShopifyAnalytics,\n shopDomain?: string,\n): Promise<void> {\n const {eventName, payload} = event;\n if (!payload.hasUserConsent) return Promise.resolve();\n\n let events: ShopifyMonorailEvent[] = [];\n const pageViewPayload = payload as ShopifyPageViewPayload;\n\n if (eventName === AnalyticsEventName.PAGE_VIEW) {\n events = events.concat(\n trekkiePageView(pageViewPayload),\n customerPageView(pageViewPayload),\n );\n } else if (eventName === AnalyticsEventName.ADD_TO_CART) {\n events = events.concat(\n customerAddToCart(payload as ShopifyAddToCartPayload),\n );\n } else if (eventName === AnalyticsEventName.PAGE_VIEW_2) {\n events = events.concat(\n trekkiePageView(pageViewPayload),\n customerPageView2(pageViewPayload),\n );\n } else if (eventName === AnalyticsEventName.COLLECTION_VIEW) {\n events = events.concat(customerCollectionView(pageViewPayload));\n } else if (eventName === AnalyticsEventName.PRODUCT_VIEW) {\n events = events.concat(customerProductView(pageViewPayload));\n } else if (eventName === AnalyticsEventName.SEARCH_VIEW) {\n events = events.concat(customerSearchView(pageViewPayload));\n }\n\n if (events.length) {\n return sendToShopify(events, shopDomain);\n } else {\n return Promise.resolve();\n }\n}\n\ntype MonorailResponse = {\n status: number;\n message: string;\n};\n\nconst ERROR_MESSAGE = 'sendShopifyAnalytics request is unsuccessful';\n\nfunction sendToShopify(\n events: ShopifyMonorailEvent[],\n shopDomain?: string,\n): Promise<void> {\n const eventsToBeSent = {\n events,\n metadata: {\n event_sent_at_ms: Date.now(),\n },\n };\n\n try {\n return fetch(\n shopDomain\n ? `https://${shopDomain}/.well-known/shopify/monorail/unstable/produce_batch`\n : 'https://monorail-edge.shopifysvc.com/unstable/produce_batch',\n {\n method: 'post',\n headers: {\n 'content-type': 'text/plain',\n },\n body: JSON.stringify(eventsToBeSent),\n },\n )\n .then((response) => {\n if (!response.ok) {\n throw new Error('Response failed');\n }\n return response.text();\n })\n .then((data) => {\n if (data) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const jsonResponse = JSON.parse(data);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n jsonResponse.result.forEach((eventResponse: MonorailResponse) => {\n if (eventResponse.status !== 200) {\n console.error(ERROR_MESSAGE, '\\n\\n', eventResponse.message);\n }\n });\n }\n })\n .catch((err) => {\n console.error(ERROR_MESSAGE, err);\n if (__HYDROGEN_DEV__) {\n throw new Error(ERROR_MESSAGE);\n }\n });\n } catch (error) {\n // Do nothing\n return Promise.resolve();\n }\n}\n\nexport function getClientBrowserParameters(): ClientBrowserParameters {\n if (errorIfServer('getClientBrowserParameters')) {\n return {\n uniqueToken: '',\n visitToken: '',\n url: '',\n path: '',\n search: '',\n referrer: '',\n title: '',\n userAgent: '',\n navigationType: '',\n navigationApi: '',\n };\n }\n\n const [navigationType, navigationApi] = getNavigationType();\n const cookies = getShopifyCookies(document.cookie);\n\n return {\n uniqueToken: cookies[SHOPIFY_Y],\n visitToken: cookies[SHOPIFY_S],\n url: location.href,\n path: location.pathname,\n search: location.search,\n referrer: document.referrer,\n title: document.title,\n userAgent: navigator.userAgent,\n navigationType,\n navigationApi,\n };\n}\n\nfunction getNavigationTypeExperimental(): string | undefined {\n try {\n const navigationEntries =\n performance?.getEntriesByType &&\n performance?.getEntriesByType('navigation');\n\n if (navigationEntries && navigationEntries[0]) {\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming\n const rawType = (\n window.performance.getEntriesByType(\n 'navigation',\n )[0] as PerformanceNavigationTiming\n )['type'];\n const navType = rawType && rawType.toString();\n\n return navType;\n }\n } catch (err) {\n // Do nothing\n }\n return undefined;\n}\n\nfunction getNavigationTypeLegacy(): string | undefined {\n try {\n if (\n PerformanceNavigation &&\n performance?.navigation?.type !== null &&\n performance?.navigation?.type !== undefined\n ) {\n // https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation\n const rawType = performance.navigation.type;\n switch (rawType) {\n case PerformanceNavigation.TYPE_NAVIGATE:\n return 'navigate';\n break;\n case PerformanceNavigation.TYPE_RELOAD:\n return 'reload';\n break;\n case PerformanceNavigation.TYPE_BACK_FORWARD:\n return 'back_forward';\n break;\n default:\n return `unknown: ${rawType}`;\n }\n }\n } catch (err) {\n // do nothing\n }\n return undefined;\n}\n\nfunction getNavigationType(): [string, string] {\n try {\n let navApi = 'PerformanceNavigationTiming';\n let navType = getNavigationTypeExperimental();\n if (!navType) {\n navType = getNavigationTypeLegacy();\n navApi = 'performance.navigation';\n }\n if (navType) {\n return [navType, navApi];\n } else {\n return ['unknown', 'unknown'];\n }\n } catch (err) {\n // do nothing\n }\n return ['error', 'error'];\n}\n"],"names":["trekkiePageView","customerPageView","customerAddToCart","customerPageView2","customerCollectionView","customerProductView","customerSearchView"],"mappings":";;;;;;AA4BgB,SAAA,qBACd,OACA,YACe;AACT,QAAA,EAAC,WAAW,QAAW,IAAA;AAC7B,MAAI,CAAC,QAAQ;AAAgB,WAAO,QAAQ;AAE5C,MAAI,SAAiC,CAAA;AACrC,QAAM,kBAAkB;AAEpB,MAAA,cAAc,mBAAmB,WAAW;AAC9C,aAAS,OAAO;AAAA,MACdA,SAAgB,eAAe;AAAA,MAC/BC,WAAiB,eAAe;AAAA,IAAA;AAAA,EAClC,WACS,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO;AAAA,MACdC,UAAkB,OAAkC;AAAA,IAAA;AAAA,EACtD,WACS,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO;AAAA,MACdF,SAAgB,eAAe;AAAA,MAC/BG,UAAkB,eAAe;AAAA,IAAA;AAAA,EACnC,WACS,cAAc,mBAAmB,iBAAiB;AAC3D,aAAS,OAAO,OAAOC,eAAuB,eAAe,CAAC;AAAA,EAAA,WACrD,cAAc,mBAAmB,cAAc;AACxD,aAAS,OAAO,OAAOC,YAAoB,eAAe,CAAC;AAAA,EAAA,WAClD,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO,OAAOC,WAAmB,eAAe,CAAC;AAAA,EAC5D;AAEA,MAAI,OAAO,Q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,CAAC,SAAS,MAAM;AAAA,IAAA,OAClB;AACE,aAAA,CAAC,WAAW,SAAS;AAAA,IAC9B;AAAA,WACO,KAAK;AAAA,EAEd;AACO,SAAA,CAAC,SAAS,OAAO;AAC1B;"}
1
+ {"version":3,"file":"analytics.mjs","sources":["../../src/analytics.ts"],"sourcesContent":["import {SHOPIFY_S, SHOPIFY_Y} from './cart-constants.js';\nimport type {\n ClientBrowserParameters,\n ShopifyAddToCartPayload,\n ShopifyAnalytics,\n ShopifyPageViewPayload,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {AnalyticsEventName} from './analytics-constants.js';\nimport {errorIfServer} from './analytics-utils.js';\nimport {getShopifyCookies} from './cookies-utils.js';\n\nimport {pageView as trekkiePageView} from './analytics-schema-trekkie-storefront-page-view.js';\nimport {\n pageView as customerPageView,\n pageView2 as customerPageView2,\n collectionView as customerCollectionView,\n productView as customerProductView,\n searchView as customerSearchView,\n addToCart as customerAddToCart,\n} from './analytics-schema-custom-storefront-customer-tracking.js';\n\n/**\n * Set user and session cookies and refresh the expiry time\n * @param event - The analytics event.\n * @param shopDomain - The Online Store domain to sent Shopify analytics under the same\n * top level domain.\n */\nexport function sendShopifyAnalytics(\n event: ShopifyAnalytics,\n shopDomain?: string,\n): Promise<void> {\n const {eventName, payload} = event;\n if (!payload.hasUserConsent) return Promise.resolve();\n\n let events: ShopifyMonorailEvent[] = [];\n const pageViewPayload = payload as ShopifyPageViewPayload;\n\n if (eventName === AnalyticsEventName.PAGE_VIEW) {\n events = events.concat(\n trekkiePageView(pageViewPayload),\n customerPageView(pageViewPayload),\n );\n } else if (eventName === AnalyticsEventName.ADD_TO_CART) {\n events = events.concat(\n customerAddToCart(payload as ShopifyAddToCartPayload),\n );\n } else if (eventName === AnalyticsEventName.PAGE_VIEW_2) {\n events = events.concat(\n trekkiePageView(pageViewPayload),\n customerPageView2(pageViewPayload),\n );\n } else if (eventName === AnalyticsEventName.COLLECTION_VIEW) {\n events = events.concat(customerCollectionView(pageViewPayload));\n } else if (eventName === AnalyticsEventName.PRODUCT_VIEW) {\n events = events.concat(customerProductView(pageViewPayload));\n } else if (eventName === AnalyticsEventName.SEARCH_VIEW) {\n events = events.concat(customerSearchView(pageViewPayload));\n }\n\n if (events.length) {\n return sendToShopify(events, shopDomain);\n } else {\n return Promise.resolve();\n }\n}\n\n// Shopify monorail return invalid agent for Lighthouse userAgents\nfunction isLighthouseUserAgent(): boolean {\n if (typeof window === 'undefined' || !window.navigator) return false;\n return /Chrome-Lighthouse/.test(window.navigator.userAgent);\n}\n\ntype MonorailResponse = {\n status: number;\n message: string;\n};\n\nconst ERROR_MESSAGE = 'sendShopifyAnalytics request is unsuccessful';\n\nfunction sendToShopify(\n events: ShopifyMonorailEvent[],\n shopDomain?: string,\n): Promise<void> {\n if (isLighthouseUserAgent()) {\n return Promise.resolve();\n }\n\n const eventsToBeSent = {\n events,\n metadata: {\n event_sent_at_ms: Date.now(),\n },\n };\n\n try {\n return fetch(\n shopDomain\n ? `https://${shopDomain}/.well-known/shopify/monorail/unstable/produce_batch`\n : 'https://monorail-edge.shopifysvc.com/unstable/produce_batch',\n {\n method: 'post',\n headers: {\n 'content-type': 'text/plain',\n },\n body: JSON.stringify(eventsToBeSent),\n },\n )\n .then((response) => {\n if (!response.ok) {\n throw new Error('Response failed');\n }\n return response.text();\n })\n .then((data) => {\n if (data) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const jsonResponse = JSON.parse(data);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n jsonResponse.result.forEach((eventResponse: MonorailResponse) => {\n if (eventResponse.status !== 200) {\n console.error(ERROR_MESSAGE, '\\n\\n', eventResponse.message);\n }\n });\n }\n })\n .catch((err) => {\n console.error(ERROR_MESSAGE, err);\n if (__HYDROGEN_DEV__) {\n throw new Error(ERROR_MESSAGE);\n }\n });\n } catch (error) {\n // Do nothing\n return Promise.resolve();\n }\n}\n\nexport function getClientBrowserParameters(): ClientBrowserParameters {\n if (errorIfServer('getClientBrowserParameters')) {\n return {\n uniqueToken: '',\n visitToken: '',\n url: '',\n path: '',\n search: '',\n referrer: '',\n title: '',\n userAgent: '',\n navigationType: '',\n navigationApi: '',\n };\n }\n\n const [navigationType, navigationApi] = getNavigationType();\n const cookies = getShopifyCookies(document.cookie);\n\n return {\n uniqueToken: cookies[SHOPIFY_Y],\n visitToken: cookies[SHOPIFY_S],\n url: location.href,\n path: location.pathname,\n search: location.search,\n referrer: document.referrer,\n title: document.title,\n userAgent: navigator.userAgent,\n navigationType,\n navigationApi,\n };\n}\n\nfunction getNavigationTypeExperimental(): string | undefined {\n try {\n const navigationEntries =\n performance?.getEntriesByType &&\n performance?.getEntriesByType('navigation');\n\n if (navigationEntries && navigationEntries[0]) {\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming\n const rawType = (\n window.performance.getEntriesByType(\n 'navigation',\n )[0] as PerformanceNavigationTiming\n )['type'];\n const navType = rawType && rawType.toString();\n\n return navType;\n }\n } catch (err) {\n // Do nothing\n }\n return undefined;\n}\n\nfunction getNavigationTypeLegacy(): string | undefined {\n try {\n if (\n PerformanceNavigation &&\n performance?.navigation?.type !== null &&\n performance?.navigation?.type !== undefined\n ) {\n // https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation\n const rawType = performance.navigation.type;\n switch (rawType) {\n case PerformanceNavigation.TYPE_NAVIGATE:\n return 'navigate';\n break;\n case PerformanceNavigation.TYPE_RELOAD:\n return 'reload';\n break;\n case PerformanceNavigation.TYPE_BACK_FORWARD:\n return 'back_forward';\n break;\n default:\n return `unknown: ${rawType}`;\n }\n }\n } catch (err) {\n // do nothing\n }\n return undefined;\n}\n\nfunction getNavigationType(): [string, string] {\n try {\n let navApi = 'PerformanceNavigationTiming';\n let navType = getNavigationTypeExperimental();\n if (!navType) {\n navType = getNavigationTypeLegacy();\n navApi = 'performance.navigation';\n }\n if (navType) {\n return [navType, navApi];\n } else {\n return ['unknown', 'unknown'];\n }\n } catch (err) {\n // do nothing\n }\n return ['error', 'error'];\n}\n"],"names":["trekkiePageView","customerPageView","customerAddToCart","customerPageView2","customerCollectionView","customerProductView","customerSearchView"],"mappings":";;;;;;AA4BgB,SAAA,qBACd,OACA,YACe;AACT,QAAA,EAAC,WAAW,QAAW,IAAA;AAC7B,MAAI,CAAC,QAAQ;AAAgB,WAAO,QAAQ;AAE5C,MAAI,SAAiC,CAAA;AACrC,QAAM,kBAAkB;AAEpB,MAAA,cAAc,mBAAmB,WAAW;AAC9C,aAAS,OAAO;AAAA,MACdA,SAAgB,eAAe;AAAA,MAC/BC,WAAiB,eAAe;AAAA,IAAA;AAAA,EAClC,WACS,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO;AAAA,MACdC,UAAkB,OAAkC;AAAA,IAAA;AAAA,EACtD,WACS,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO;AAAA,MACdF,SAAgB,eAAe;AAAA,MAC/BG,UAAkB,eAAe;AAAA,IAAA;AAAA,EACnC,WACS,cAAc,mBAAmB,iBAAiB;AAC3D,aAAS,OAAO,OAAOC,eAAuB,eAAe,CAAC;AAAA,EAAA,WACrD,cAAc,mBAAmB,cAAc;AACxD,aAAS,OAAO,OAAOC,YAAoB,eAAe,CAAC;AAAA,EAAA,WAClD,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO,OAAOC,WAAmB,eAAe,CAAC;AAAA,EAC5D;AAEA,MAAI,OAAO,QAAQ;AACV,WAAA,cAAc,QAAQ,UAAU;AAAA,EAAA,OAClC;AACL,WAAO,QAAQ;EACjB;AACF;AAGA,SAAS,wBAAiC;AACxC,MAAI,OAAO,WAAW,eAAe,CAAC,OAAO;AAAkB,WAAA;AAC/D,SAAO,oBAAoB,KAAK,OAAO,UAAU,SAAS;AAC5D;AAOA,MAAM,gBAAgB;AAEtB,SAAS,cACP,QACA,YACe;AACf,MAAI,yBAAyB;AAC3B,WAAO,QAAQ;EACjB;AAEA,QAAM,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B;"}
@@ -9,32 +9,40 @@ function useMoney(money) {
9
9
  );
10
10
  }
11
11
  const amount = parseFloat(money.amount);
12
- const options = useMemo(
13
- () => ({
12
+ const {
13
+ defaultFormatter,
14
+ nameFormatter,
15
+ narrowSymbolFormatter,
16
+ withoutTrailingZerosFormatter,
17
+ withoutCurrencyFormatter,
18
+ withoutTrailingZerosOrCurrencyFormatter
19
+ } = useMemo(() => {
20
+ const options = {
14
21
  style: "currency",
15
22
  currency: money.currencyCode
16
- }),
17
- [money.currencyCode]
18
- );
19
- const defaultFormatter = useLazyFormatter(locale, options);
20
- const nameFormatter = useLazyFormatter(locale, {
21
- ...options,
22
- currencyDisplay: "name"
23
- });
24
- const narrowSymbolFormatter = useLazyFormatter(locale, {
25
- ...options,
26
- currencyDisplay: "narrowSymbol"
27
- });
28
- const withoutTrailingZerosFormatter = useLazyFormatter(locale, {
29
- ...options,
30
- minimumFractionDigits: 0,
31
- maximumFractionDigits: 0
32
- });
33
- const withoutCurrencyFormatter = useLazyFormatter(locale);
34
- const withoutTrailingZerosOrCurrencyFormatter = useLazyFormatter(locale, {
35
- minimumFractionDigits: 0,
36
- maximumFractionDigits: 0
37
- });
23
+ };
24
+ return {
25
+ defaultFormatter: getLazyFormatter(locale, options),
26
+ nameFormatter: getLazyFormatter(locale, {
27
+ ...options,
28
+ currencyDisplay: "name"
29
+ }),
30
+ narrowSymbolFormatter: getLazyFormatter(locale, {
31
+ ...options,
32
+ currencyDisplay: "narrowSymbol"
33
+ }),
34
+ withoutTrailingZerosFormatter: getLazyFormatter(locale, {
35
+ ...options,
36
+ minimumFractionDigits: 0,
37
+ maximumFractionDigits: 0
38
+ }),
39
+ withoutCurrencyFormatter: getLazyFormatter(locale),
40
+ withoutTrailingZerosOrCurrencyFormatter: getLazyFormatter(locale, {
41
+ minimumFractionDigits: 0,
42
+ maximumFractionDigits: 0
43
+ })
44
+ };
45
+ }, [money.currencyCode, locale]);
38
46
  const isPartCurrency = (part) => part.type === "currency";
39
47
  const lazyFormatters = useMemo(
40
48
  () => ({
@@ -87,11 +95,17 @@ function useMoney(money) {
87
95
  [lazyFormatters]
88
96
  );
89
97
  }
90
- function useLazyFormatter(locale, options) {
91
- return useMemo(() => {
92
- let memoized;
93
- return () => memoized ?? (memoized = new Intl.NumberFormat(locale, options));
94
- }, [locale, options]);
98
+ const formatterCache = /* @__PURE__ */ new Map();
99
+ function getLazyFormatter(locale, options) {
100
+ const key = JSON.stringify([locale, options]);
101
+ return function() {
102
+ let formatter = formatterCache.get(key);
103
+ if (!formatter) {
104
+ formatter = new Intl.NumberFormat(locale, options);
105
+ formatterCache.set(key, formatter);
106
+ }
107
+ return formatter;
108
+ };
95
109
  }
96
110
  export {
97
111
  useMoney
@@ -1 +1 @@
1
- {"version":3,"file":"useMoney.mjs","sources":["../../src/useMoney.tsx"],"sourcesContent":["import {useMemo} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {CurrencyCode, MoneyV2} from './storefront-api-types.js';\n\nexport type UseMoneyValue = {\n /**\n * The currency code from the `MoneyV2` object.\n */\n currencyCode: CurrencyCode;\n /**\n * The name for the currency code, returned by `Intl.NumberFormat`.\n */\n currencyName?: string;\n /**\n * The currency symbol returned by `Intl.NumberFormat`.\n */\n currencySymbol?: string;\n /**\n * The currency narrow symbol returned by `Intl.NumberFormat`.\n */\n currencyNarrowSymbol?: string;\n /**\n * The localized amount, without any currency symbols or non-number types from the `Intl.NumberFormat.formatToParts` parts.\n */\n amount: string;\n /**\n * All parts returned by `Intl.NumberFormat.formatToParts`.\n */\n parts: Intl.NumberFormatPart[];\n /**\n * A string returned by `new Intl.NumberFormat` for the amount and currency code,\n * using the `locale` value in the [`LocalizationProvider` component](https://shopify.dev/api/hydrogen/components/localization/localizationprovider).\n */\n localizedString: string;\n /**\n * The `MoneyV2` object provided as an argument to the hook.\n */\n original: MoneyV2;\n /**\n * A string with trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `$640`.\n * `$640.42` remains `$640.42`.\n */\n withoutTrailingZeros: string;\n /**\n * A string without currency and without trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `640`.\n * `$640.42` turns into `640.42`.\n */\n withoutTrailingZerosAndCurrency: string;\n};\n\n/**\n * The `useMoney` hook takes a [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2) and returns a\n * default-formatted string of the amount with the correct currency indicator, along with some of the parts provided by\n * [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat).\n * Uses `locale` from `ShopifyProvider`\n * &nbsp;\n * @see {@link https://shopify.dev/api/hydrogen/hooks/usemoney}\n * @example initialize the money object\n * ```ts\n * const money = useMoney({\n * amount: '100.00',\n * currencyCode: 'USD'\n * })\n * ```\n * &nbsp;\n *\n * @example basic usage, outputs: $100.00\n * ```ts\n * money.localizedString\n * ```\n * &nbsp;\n *\n * @example without currency, outputs: 100.00\n * ```ts\n * money.amount\n * ```\n * &nbsp;\n *\n * @example without trailing zeros, outputs: $100\n * ```ts\n * money.withoutTrailingZeros\n * ```\n * &nbsp;\n *\n * @example currency name, outputs: US dollars\n * ```ts\n * money.currencyCode\n * ```\n * &nbsp;\n *\n * @example currency symbol, outputs: $\n * ```ts\n * money.currencySymbol\n * ```\n * &nbsp;\n *\n * @example without currency and without trailing zeros, outputs: 100\n * ```ts\n * money.withoutTrailingZerosAndCurrency\n * ```\n */\nexport function useMoney(money: MoneyV2): UseMoneyValue {\n const {countryIsoCode, languageIsoCode} = useShop();\n const locale = languageIsoCode.includes('_')\n ? languageIsoCode.replace('_', '-')\n : `${languageIsoCode}-${countryIsoCode}`;\n\n if (!locale) {\n throw new Error(\n `useMoney(): Unable to get 'locale' from 'useShop()', which means that 'locale' was not passed to '<ShopifyProvider/>'. 'locale' is required for 'useMoney()' to work`,\n );\n }\n\n const amount = parseFloat(money.amount);\n\n const options = useMemo(\n () => ({\n style: 'currency' as const,\n currency: money.currencyCode,\n }),\n [money.currencyCode],\n );\n\n const defaultFormatter = useLazyFormatter(locale, options);\n\n const nameFormatter = useLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'name',\n });\n\n const narrowSymbolFormatter = useLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'narrowSymbol',\n });\n\n const withoutTrailingZerosFormatter = useLazyFormatter(locale, {\n ...options,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n });\n\n const withoutCurrencyFormatter = useLazyFormatter(locale);\n\n const withoutTrailingZerosOrCurrencyFormatter = useLazyFormatter(locale, {\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n });\n\n const isPartCurrency = (part: Intl.NumberFormatPart): boolean =>\n part.type === 'currency';\n\n // By wrapping these properties in functions, we only\n // create formatters if they are going to be used.\n const lazyFormatters = useMemo(\n () => ({\n original: () => money,\n currencyCode: () => money.currencyCode,\n\n localizedString: () => defaultFormatter().format(amount),\n\n parts: () => defaultFormatter().formatToParts(amount),\n\n withoutTrailingZeros: () =>\n amount % 1 === 0\n ? withoutTrailingZerosFormatter().format(amount)\n : defaultFormatter().format(amount),\n\n withoutTrailingZerosAndCurrency: () =>\n amount % 1 === 0\n ? withoutTrailingZerosOrCurrencyFormatter().format(amount)\n : withoutCurrencyFormatter().format(amount),\n\n currencyName: () =>\n nameFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"US dollars\"\n\n currencySymbol: () =>\n defaultFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"USD\"\n\n currencyNarrowSymbol: () =>\n narrowSymbolFormatter().formatToParts(amount).find(isPartCurrency)\n ?.value ?? '', // e.g. \"$\"\n\n amount: () =>\n defaultFormatter()\n .formatToParts(amount)\n .filter((part) =>\n ['decimal', 'fraction', 'group', 'integer', 'literal'].includes(\n part.type,\n ),\n )\n .map((part) => part.value)\n .join(''),\n }),\n [\n money,\n amount,\n nameFormatter,\n defaultFormatter,\n narrowSymbolFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n ],\n );\n\n // Call functions automatically when the properties are accessed\n // to keep these functions as an implementation detail.\n return useMemo(\n () =>\n new Proxy(lazyFormatters as unknown as UseMoneyValue, {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n get: (target, key) => Reflect.get(target, key)?.call(null),\n }),\n [lazyFormatters],\n );\n}\n\nfunction useLazyFormatter(\n locale: string,\n options?: Intl.NumberFormatOptions,\n): () => Intl.NumberFormat {\n return useMemo(() => {\n let memoized: Intl.NumberFormat;\n return () => (memoized ??= new Intl.NumberFormat(locale, options));\n }, [locale, options]);\n}\n"],"names":[],"mappings":";;AAuGO,SAAS,SAAS,OAA+B;AACtD,QAAM,EAAC,gBAAgB,gBAAe,IAAI,QAAQ;AAClD,QAAM,SAAS,gBAAgB,SAAS,GAAG,IACvC,gBAAgB,QAAQ,KAAK,GAAG,IAChC,GAAG,eAAe,IAAI,cAAc;AAExC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAEM,QAAA,SAAS,WAAW,MAAM,MAAM;AAEtC,QAAM,UAAU;AAAA,IACd,OAAO;AAAA,MACL,OAAO;AAAA,MACP,UAAU,MAAM;AAAA,IAAA;AAAA,IAElB,CAAC,MAAM,YAAY;AAAA,EAAA;AAGf,QAAA,mBAAmB,iBAAiB,QAAQ,OAAO;AAEnD,QAAA,gBAAgB,iBAAiB,QAAQ;AAAA,IAC7C,GAAG;AAAA,IACH,iBAAiB;AAAA,EAAA,CAClB;AAEK,QAAA,wBAAwB,iBAAiB,QAAQ;AAAA,IACrD,GAAG;AAAA,IACH,iBAAiB;AAAA,EAAA,CAClB;AAEK,QAAA,gCAAgC,iBAAiB,QAAQ;AAAA,IAC7D,GAAG;AAAA,IAC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A,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EAAA;AAKK,SAAA;AAAA,IACL,MACE,IAAI,MAAM,gBAA4C;AAAA;AAAA,MAEpD,KAAK,CAAC,QAAQ;;AAAQ,6BAAQ,IAAI,QAAQ,GAAG,MAAvB,mBAA0B,KAAK;AAAA;AAAA,IAAI,CAC1D;AAAA,IACH,CAAC,cAAc;AAAA,EAAA;AAEnB;AAEA,SAAS,iBACP,QACA,SACyB;AACzB,SAAO,QAAQ,MAAM;AACf,QAAA;AACJ,WAAO,MAAO,wBAAa,IAAI,KAAK,aAAa,QAAQ,OAAO;AAAA,EAAA,GAC/D,CAAC,QAAQ,OAAO,CAAC;AACtB;"}
1
+ {"version":3,"file":"useMoney.mjs","sources":["../../src/useMoney.tsx"],"sourcesContent":["import {useMemo} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {CurrencyCode, MoneyV2} from './storefront-api-types.js';\n\nexport type UseMoneyValue = {\n /**\n * The currency code from the `MoneyV2` object.\n */\n currencyCode: CurrencyCode;\n /**\n * The name for the currency code, returned by `Intl.NumberFormat`.\n */\n currencyName?: string;\n /**\n * The currency symbol returned by `Intl.NumberFormat`.\n */\n currencySymbol?: string;\n /**\n * The currency narrow symbol returned by `Intl.NumberFormat`.\n */\n currencyNarrowSymbol?: string;\n /**\n * The localized amount, without any currency symbols or non-number types from the `Intl.NumberFormat.formatToParts` parts.\n */\n amount: string;\n /**\n * All parts returned by `Intl.NumberFormat.formatToParts`.\n */\n parts: Intl.NumberFormatPart[];\n /**\n * A string returned by `new Intl.NumberFormat` for the amount and currency code,\n * using the `locale` value in the [`LocalizationProvider` component](https://shopify.dev/api/hydrogen/components/localization/localizationprovider).\n */\n localizedString: string;\n /**\n * The `MoneyV2` object provided as an argument to the hook.\n */\n original: MoneyV2;\n /**\n * A string with trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `$640`.\n * `$640.42` remains `$640.42`.\n */\n withoutTrailingZeros: string;\n /**\n * A string without currency and without trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `640`.\n * `$640.42` turns into `640.42`.\n */\n withoutTrailingZerosAndCurrency: string;\n};\n\n/**\n * The `useMoney` hook takes a [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2) and returns a\n * default-formatted string of the amount with the correct currency indicator, along with some of the parts provided by\n * [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat).\n * Uses `locale` from `ShopifyProvider`\n * &nbsp;\n * @see {@link https://shopify.dev/api/hydrogen/hooks/usemoney}\n * @example initialize the money object\n * ```ts\n * const money = useMoney({\n * amount: '100.00',\n * currencyCode: 'USD'\n * })\n * ```\n * &nbsp;\n *\n * @example basic usage, outputs: $100.00\n * ```ts\n * money.localizedString\n * ```\n * &nbsp;\n *\n * @example without currency, outputs: 100.00\n * ```ts\n * money.amount\n * ```\n * &nbsp;\n *\n * @example without trailing zeros, outputs: $100\n * ```ts\n * money.withoutTrailingZeros\n * ```\n * &nbsp;\n *\n * @example currency name, outputs: US dollars\n * ```ts\n * money.currencyCode\n * ```\n * &nbsp;\n *\n * @example currency symbol, outputs: $\n * ```ts\n * money.currencySymbol\n * ```\n * &nbsp;\n *\n * @example without currency and without trailing zeros, outputs: 100\n * ```ts\n * money.withoutTrailingZerosAndCurrency\n * ```\n */\nexport function useMoney(money: MoneyV2): UseMoneyValue {\n const {countryIsoCode, languageIsoCode} = useShop();\n const locale = languageIsoCode.includes('_')\n ? languageIsoCode.replace('_', '-')\n : `${languageIsoCode}-${countryIsoCode}`;\n\n if (!locale) {\n throw new Error(\n `useMoney(): Unable to get 'locale' from 'useShop()', which means that 'locale' was not passed to '<ShopifyProvider/>'. 'locale' is required for 'useMoney()' to work`,\n );\n }\n\n const amount = parseFloat(money.amount);\n\n const {\n defaultFormatter,\n nameFormatter,\n narrowSymbolFormatter,\n withoutTrailingZerosFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n } = useMemo(() => {\n const options = {\n style: 'currency' as const,\n currency: money.currencyCode,\n };\n\n return {\n defaultFormatter: getLazyFormatter(locale, options),\n nameFormatter: getLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'name',\n }),\n narrowSymbolFormatter: getLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'narrowSymbol',\n }),\n withoutTrailingZerosFormatter: getLazyFormatter(locale, {\n ...options,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n }),\n withoutCurrencyFormatter: getLazyFormatter(locale),\n withoutTrailingZerosOrCurrencyFormatter: getLazyFormatter(locale, {\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n }),\n };\n }, [money.currencyCode, locale]);\n\n const isPartCurrency = (part: Intl.NumberFormatPart): boolean =>\n part.type === 'currency';\n\n // By wrapping these properties in functions, we only\n // create formatters if they are going to be used.\n const lazyFormatters = useMemo(\n () => ({\n original: () => money,\n currencyCode: () => money.currencyCode,\n\n localizedString: () => defaultFormatter().format(amount),\n\n parts: () => defaultFormatter().formatToParts(amount),\n\n withoutTrailingZeros: () =>\n amount % 1 === 0\n ? withoutTrailingZerosFormatter().format(amount)\n : defaultFormatter().format(amount),\n\n withoutTrailingZerosAndCurrency: () =>\n amount % 1 === 0\n ? withoutTrailingZerosOrCurrencyFormatter().format(amount)\n : withoutCurrencyFormatter().format(amount),\n\n currencyName: () =>\n nameFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"US dollars\"\n\n currencySymbol: () =>\n defaultFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"USD\"\n\n currencyNarrowSymbol: () =>\n narrowSymbolFormatter().formatToParts(amount).find(isPartCurrency)\n ?.value ?? '', // e.g. \"$\"\n\n amount: () =>\n defaultFormatter()\n .formatToParts(amount)\n .filter((part) =>\n ['decimal', 'fraction', 'group', 'integer', 'literal'].includes(\n part.type,\n ),\n )\n .map((part) => part.value)\n .join(''),\n }),\n [\n money,\n amount,\n nameFormatter,\n defaultFormatter,\n narrowSymbolFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n ],\n );\n\n // Call functions automatically when the properties are accessed\n // to keep these functions as an implementation detail.\n return useMemo(\n () =>\n new Proxy(lazyFormatters as unknown as UseMoneyValue, {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n get: (target, key) => Reflect.get(target, key)?.call(null),\n }),\n [lazyFormatters],\n );\n}\n\nconst formatterCache = new Map<string, Intl.NumberFormat>();\n\nfunction getLazyFormatter(\n locale: string,\n options?: Intl.NumberFormatOptions,\n): () => Intl.NumberFormat {\n const key = JSON.stringify([locale, options]);\n\n return function (): Intl.NumberFormat {\n let formatter = formatterCache.get(key);\n if (!formatter) {\n formatter = new Intl.NumberFormat(locale, options);\n formatterCache.set(key, formatter);\n }\n return formatter;\n };\n}\n"],"names":[],"mappings":";;AAuGO,SAAS,SAAS,OAA+B;AACtD,QAAM,EAAC,gBAAgB,gBAAe,IAAI,QAAQ;AAClD,QAAM,SAAS,gBAAgB,SAAS,GAAG,IACvC,gBAAgB,QAAQ,KAAK,GAAG,IAChC,GAAG,eAAe,IAAI,cAAc;AAExC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAEM,QAAA,SAAS,WAAW,MAAM,MAAM;AAEhC,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,QAAQ,MAAM;AAChB,UAAM,UAAU;AAAA,MACd,OAAO;AAAA,MACP,UAAU,MAAM;AAAA,IAAA;AAGX,WAAA;AAAA,MACL,kBAAkB,iBAAiB,QAAQ,OAAO;AAAA,MA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