@shopify/hydrogen-react 2024.4.1 → 2024.4.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.
- package/README.md +2 -2
- package/dist/browser-dev/Image.mjs.map +1 -1
- package/dist/browser-dev/RichText.components.mjs +57 -0
- package/dist/browser-dev/RichText.components.mjs.map +1 -0
- package/dist/browser-dev/RichText.mjs +160 -0
- package/dist/browser-dev/RichText.mjs.map +1 -0
- package/dist/browser-dev/ShopifyProvider.mjs +2 -1
- package/dist/browser-dev/ShopifyProvider.mjs.map +1 -1
- package/dist/browser-dev/index.mjs +2 -0
- package/dist/browser-dev/index.mjs.map +1 -1
- package/dist/browser-dev/parse-metafield.mjs +1 -0
- package/dist/browser-dev/parse-metafield.mjs.map +1 -1
- package/dist/browser-dev/storefront-client.mjs +1 -1
- package/dist/browser-dev/storefront-client.mjs.map +1 -1
- package/dist/browser-dev/useShopifyCookies.mjs +8 -4
- package/dist/browser-dev/useShopifyCookies.mjs.map +1 -1
- package/dist/browser-prod/Image.mjs.map +1 -1
- package/dist/browser-prod/RichText.components.mjs +57 -0
- package/dist/browser-prod/RichText.components.mjs.map +1 -0
- package/dist/browser-prod/RichText.mjs +160 -0
- package/dist/browser-prod/RichText.mjs.map +1 -0
- package/dist/browser-prod/ShopifyProvider.mjs +2 -1
- package/dist/browser-prod/ShopifyProvider.mjs.map +1 -1
- package/dist/browser-prod/index.mjs +2 -0
- package/dist/browser-prod/index.mjs.map +1 -1
- package/dist/browser-prod/parse-metafield.mjs +1 -0
- package/dist/browser-prod/parse-metafield.mjs.map +1 -1
- package/dist/browser-prod/storefront-client.mjs +1 -1
- package/dist/browser-prod/storefront-client.mjs.map +1 -1
- package/dist/browser-prod/useShopifyCookies.mjs +8 -4
- package/dist/browser-prod/useShopifyCookies.mjs.map +1 -1
- package/dist/node-dev/Image.js.map +1 -1
- package/dist/node-dev/Image.mjs.map +1 -1
- package/dist/node-dev/RichText.components.js +57 -0
- package/dist/node-dev/RichText.components.js.map +1 -0
- package/dist/node-dev/RichText.components.mjs +57 -0
- package/dist/node-dev/RichText.components.mjs.map +1 -0
- package/dist/node-dev/RichText.js +160 -0
- package/dist/node-dev/RichText.js.map +1 -0
- package/dist/node-dev/RichText.mjs +160 -0
- package/dist/node-dev/RichText.mjs.map +1 -0
- package/dist/node-dev/ShopifyProvider.js +2 -1
- package/dist/node-dev/ShopifyProvider.js.map +1 -1
- package/dist/node-dev/ShopifyProvider.mjs +2 -1
- package/dist/node-dev/ShopifyProvider.mjs.map +1 -1
- package/dist/node-dev/index.js +2 -0
- package/dist/node-dev/index.js.map +1 -1
- package/dist/node-dev/index.mjs +2 -0
- package/dist/node-dev/index.mjs.map +1 -1
- package/dist/node-dev/parse-metafield.js +1 -0
- package/dist/node-dev/parse-metafield.js.map +1 -1
- package/dist/node-dev/parse-metafield.mjs +1 -0
- package/dist/node-dev/parse-metafield.mjs.map +1 -1
- package/dist/node-dev/storefront-client.js +1 -1
- package/dist/node-dev/storefront-client.js.map +1 -1
- package/dist/node-dev/storefront-client.mjs +1 -1
- package/dist/node-dev/storefront-client.mjs.map +1 -1
- package/dist/node-dev/useShopifyCookies.js +8 -4
- package/dist/node-dev/useShopifyCookies.js.map +1 -1
- package/dist/node-dev/useShopifyCookies.mjs +8 -4
- package/dist/node-dev/useShopifyCookies.mjs.map +1 -1
- package/dist/node-prod/Image.js.map +1 -1
- package/dist/node-prod/Image.mjs.map +1 -1
- package/dist/node-prod/RichText.components.js +57 -0
- package/dist/node-prod/RichText.components.js.map +1 -0
- package/dist/node-prod/RichText.components.mjs +57 -0
- package/dist/node-prod/RichText.components.mjs.map +1 -0
- package/dist/node-prod/RichText.js +160 -0
- package/dist/node-prod/RichText.js.map +1 -0
- package/dist/node-prod/RichText.mjs +160 -0
- package/dist/node-prod/RichText.mjs.map +1 -0
- package/dist/node-prod/ShopifyProvider.js +2 -1
- package/dist/node-prod/ShopifyProvider.js.map +1 -1
- package/dist/node-prod/ShopifyProvider.mjs +2 -1
- package/dist/node-prod/ShopifyProvider.mjs.map +1 -1
- package/dist/node-prod/index.js +2 -0
- package/dist/node-prod/index.js.map +1 -1
- package/dist/node-prod/index.mjs +2 -0
- package/dist/node-prod/index.mjs.map +1 -1
- package/dist/node-prod/parse-metafield.js +1 -0
- package/dist/node-prod/parse-metafield.js.map +1 -1
- package/dist/node-prod/parse-metafield.mjs +1 -0
- package/dist/node-prod/parse-metafield.mjs.map +1 -1
- package/dist/node-prod/storefront-client.js +1 -1
- package/dist/node-prod/storefront-client.js.map +1 -1
- package/dist/node-prod/storefront-client.mjs +1 -1
- package/dist/node-prod/storefront-client.mjs.map +1 -1
- package/dist/node-prod/useShopifyCookies.js +8 -4
- package/dist/node-prod/useShopifyCookies.js.map +1 -1
- package/dist/node-prod/useShopifyCookies.mjs +8 -4
- package/dist/node-prod/useShopifyCookies.mjs.map +1 -1
- package/dist/types/Image.d.ts +1 -1
- package/dist/types/RichText.components.d.ts +76 -0
- package/dist/types/RichText.d.ts +14 -0
- package/dist/types/RichText.test.helpers.d.ts +9 -0
- package/dist/types/RichText.types.d.ts +36 -0
- package/dist/types/index.d.cts +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/parse-metafield.d.ts +8 -1
- package/dist/umd/hydrogen-react.dev.js +217 -6
- package/dist/umd/hydrogen-react.dev.js.map +1 -1
- package/dist/umd/hydrogen-react.prod.js +18 -17
- package/dist/umd/hydrogen-react.prod.js.map +1 -1
- package/package.json +2 -3
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
Hydrogen React is an unopinionated and performant library of Shopify-specific commerce components, hooks, and utilities. Bring the best parts of Hydrogen to more React frameworks, like Next.js and Gatsby, and accelerate headless development using Shopify’s pre-built React components including Cart, Shop Pay, and Shopify Analytics.
|
|
6
6
|
|
|
7
|
-
📚 [Overview](https://shopify.dev/custom-storefronts/hydrogen-react) | 🛠️ [Docs](https://shopify.dev/docs/api/hydrogen-react) | 🛍️ [Custom Storefronts at Shopify](https://shopify.dev/custom-storefronts) | 🗣 [
|
|
7
|
+
📚 [Overview](https://shopify.dev/custom-storefronts/hydrogen-react) | 🛠️ [Docs](https://shopify.dev/docs/api/hydrogen-react) | 🛍️ [Custom Storefronts at Shopify](https://shopify.dev/custom-storefronts) | 🗣 [Discussions](https://github.com/Shopify/hydrogen/discussions) | 📝 [Changelog](https://github.com/Shopify/hydrogen/blob/main/packages/hydrogen-react/CHANGELOG.md)
|
|
8
8
|
|
|
9
9
|
**IMPORTANT:** Refer to how this package is [versioned](../../README.md#versioning).
|
|
10
10
|
|
|
@@ -78,6 +78,6 @@ For example, in VSCode do the following:
|
|
|
78
78
|
|
|
79
79
|
## Contributing
|
|
80
80
|
|
|
81
|
-
We love contributions! Contributing works best when you first confirm that something needs to be changed or fixed; please open an issue
|
|
81
|
+
We love contributions! Contributing works best when you first confirm that something needs to be changed or fixed; please open an issue or start a discussion!
|
|
82
82
|
|
|
83
83
|
PRs are welcome! Be sure to read the [CONTRIBUTING.md](../../CONTRIBUTING.md) for an overview and guidelines to help your PR succeed.
|
|
@@ -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-04/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 * Hydrgen’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:\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,QAA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M,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-04/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],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,YAAW,KAAK,CAAC,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;"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { jsx } from "react/jsx-runtime";
|
|
2
|
+
import { createElement } from "react";
|
|
3
|
+
const RichTextComponents = {
|
|
4
|
+
root: Root,
|
|
5
|
+
heading: Heading,
|
|
6
|
+
paragraph: Paragraph,
|
|
7
|
+
text: Text,
|
|
8
|
+
link: RichTextLink,
|
|
9
|
+
list: List,
|
|
10
|
+
"list-item": ListItem
|
|
11
|
+
};
|
|
12
|
+
function Root({
|
|
13
|
+
node
|
|
14
|
+
}) {
|
|
15
|
+
return /* @__PURE__ */ jsx("div", { children: node.children });
|
|
16
|
+
}
|
|
17
|
+
function Heading({
|
|
18
|
+
node
|
|
19
|
+
}) {
|
|
20
|
+
return createElement(`h${node.level ?? "1"}`, null, node.children);
|
|
21
|
+
}
|
|
22
|
+
function Paragraph({
|
|
23
|
+
node
|
|
24
|
+
}) {
|
|
25
|
+
return /* @__PURE__ */ jsx("p", { children: node.children });
|
|
26
|
+
}
|
|
27
|
+
function Text({
|
|
28
|
+
node
|
|
29
|
+
}) {
|
|
30
|
+
if (node.bold && node.italic)
|
|
31
|
+
return /* @__PURE__ */ jsx("em", { children: /* @__PURE__ */ jsx("strong", { children: node.value }) });
|
|
32
|
+
if (node.bold)
|
|
33
|
+
return /* @__PURE__ */ jsx("strong", { children: node.value });
|
|
34
|
+
if (node.italic)
|
|
35
|
+
return /* @__PURE__ */ jsx("em", { children: node.value });
|
|
36
|
+
return node.value;
|
|
37
|
+
}
|
|
38
|
+
function RichTextLink({
|
|
39
|
+
node
|
|
40
|
+
}) {
|
|
41
|
+
return /* @__PURE__ */ jsx("a", { href: node.url, title: node.title, target: node.target, children: node.children });
|
|
42
|
+
}
|
|
43
|
+
function List({
|
|
44
|
+
node
|
|
45
|
+
}) {
|
|
46
|
+
const List2 = node.listType === "unordered" ? "ul" : "ol";
|
|
47
|
+
return /* @__PURE__ */ jsx(List2, { children: node.children });
|
|
48
|
+
}
|
|
49
|
+
function ListItem({
|
|
50
|
+
node
|
|
51
|
+
}) {
|
|
52
|
+
return /* @__PURE__ */ jsx("li", { children: node.children });
|
|
53
|
+
}
|
|
54
|
+
export {
|
|
55
|
+
RichTextComponents
|
|
56
|
+
};
|
|
57
|
+
//# sourceMappingURL=RichText.components.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RichText.components.mjs","sources":["../../src/RichText.components.tsx"],"sourcesContent":["import {createElement, type ReactNode} from 'react';\n\nexport type CustomComponents = {\n /** The root node of the rich text. Defaults to `<div>` */\n root?: typeof Root;\n /** Customize the headings. Each heading has a `level` property from 1-6. Defaults to `<h1>` to `<h6>` */\n heading?: typeof Heading;\n /** Customize paragraphs. Defaults to `<p>` */\n paragraph?: typeof Paragraph;\n /** Customize how text nodes. They can either be bold or italic. Defaults to `<em>`, `<strong>` or text. */\n text?: typeof Text;\n /** Customize links. Defaults to a React Router `<Link>` component in Hydrogen and a `<a>` in Hydrogen React. */\n link?: typeof RichTextLink;\n /** Customize lists. They can be either ordered or unordered. Defaults to `<ol>` or `<ul>` */\n list?: typeof List;\n /** Customize list items. Defaults to `<li>`. */\n listItem?: typeof ListItem;\n};\n\nexport const RichTextComponents = {\n root: Root,\n heading: Heading,\n paragraph: Paragraph,\n text: Text,\n link: RichTextLink,\n list: List,\n 'list-item': ListItem,\n};\n\nfunction Root({\n node,\n}: {\n node: {\n type: 'root';\n children?: ReactNode[];\n };\n}): ReactNode {\n return <div>{node.children}</div>;\n}\n\nfunction Heading({\n node,\n}: {\n node: {\n type: 'heading';\n level: number;\n children?: ReactNode[];\n };\n}): ReactNode {\n return createElement(`h${node.level ?? '1'}`, null, node.children);\n}\n\nfunction Paragraph({\n node,\n}: {\n node: {\n type: 'paragraph';\n children?: ReactNode[];\n };\n}): ReactNode {\n return <p>{node.children}</p>;\n}\n\nfunction Text({\n node,\n}: {\n node: {\n type: 'text';\n italic?: boolean;\n bold?: boolean;\n value?: string;\n };\n}): ReactNode {\n if (node.bold && node.italic)\n return (\n <em>\n <strong>{node.value}</strong>\n </em>\n );\n\n if (node.bold) return <strong>{node.value}</strong>;\n if (node.italic) return <em>{node.value}</em>;\n\n return node.value;\n}\n\nfunction RichTextLink({\n node,\n}: {\n node: {\n type: 'link';\n url: string;\n title?: string;\n target?: string;\n children?: ReactNode[];\n };\n}): ReactNode {\n return (\n <a href={node.url} title={node.title} target={node.target}>\n {node.children}\n </a>\n );\n}\n\nfunction List({\n node,\n}: {\n node: {\n type: 'list';\n listType: 'unordered' | 'ordered';\n children?: ReactNode[];\n };\n}): ReactNode {\n const List = node.listType === 'unordered' ? 'ul' : 'ol';\n return <List>{node.children}</List>;\n}\n\nfunction ListItem({\n node,\n}: {\n node: {\n type: 'list-item';\n children?: ReactNode[];\n };\n}): ReactNode {\n return <li>{node.children}</li>;\n}\n"],"names":["List"],"mappings":";;AAmBO,MAAM,qBAAqB;AAAA,EAChC,MAAM;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,aAAa;AACf;AAEA,SAAS,KAAK;AAAA,EACZ;AACF,GAKc;AACL,SAAA,oBAAC,OAAK,EAAA,UAAA,KAAK,SAAS,CAAA;AAC7B;AAEA,SAAS,QAAQ;AAAA,EACf;AACF,GAMc;AACL,SAAA,cAAc,IAAI,KAAK,SAAS,GAAG,IAAI,MAAM,KAAK,QAAQ;AACnE;AAEA,SAAS,UAAU;AAAA,EACjB;AACF,GAKc;AACL,SAAA,oBAAC,KAAG,EAAA,UAAA,KAAK,SAAS,CAAA;AAC3B;AAEA,SAAS,KAAK;AAAA,EACZ;AACF,GAOc;AACR,MAAA,KAAK,QAAQ,KAAK;AACpB,+BACG,MACC,EAAA,UAAA,oBAAC,UAAQ,EAAA,UAAA,KAAK,MAAM,CAAA,EACtB,CAAA;AAGJ,MAAI,KAAK;AAAa,WAAA,oBAAC,UAAQ,EAAA,UAAA,KAAK,MAAM,CAAA;AAC1C,MAAI,KAAK;AAAe,WAAA,oBAAC,MAAI,EAAA,UAAA,KAAK,MAAM,CAAA;AAExC,SAAO,KAAK;AACd;AAEA,SAAS,aAAa;AAAA,EACpB;AACF,GAQc;AACZ,SACG,oBAAA,KAAA,EAAE,MAAM,KAAK,KAAK,OAAO,KAAK,OAAO,QAAQ,KAAK,QAChD,UAAA,KAAK,SACR,CAAA;AAEJ;AAEA,SAAS,KAAK;AAAA,EACZ;AACF,GAMc;AACZ,QAAMA,QAAO,KAAK,aAAa,cAAc,OAAO;AACpD,SAAQA,oBAAAA,OAAA,EAAM,UAAA,KAAK,SAAS,CAAA;AAC9B;AAEA,SAAS,SAAS;AAAA,EAChB;AACF,GAKc;AACL,SAAA,oBAAC,MAAI,EAAA,UAAA,KAAK,SAAS,CAAA;AAC5B;"}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useMemo, createElement, Fragment } from "react";
|
|
3
|
+
import { RichTextComponents } from "./RichText.components.mjs";
|
|
4
|
+
function RichText({
|
|
5
|
+
as,
|
|
6
|
+
data,
|
|
7
|
+
plain,
|
|
8
|
+
components,
|
|
9
|
+
...passthroughProps
|
|
10
|
+
}) {
|
|
11
|
+
try {
|
|
12
|
+
const Wrapper = as ?? "div";
|
|
13
|
+
const parsedData = useMemo(
|
|
14
|
+
() => JSON.parse(data),
|
|
15
|
+
[data]
|
|
16
|
+
);
|
|
17
|
+
return /* @__PURE__ */ jsx(Wrapper, { ...passthroughProps, children: plain ? richTextToString(parsedData) : serializeRichTextASTNode(components, parsedData) });
|
|
18
|
+
} catch (e) {
|
|
19
|
+
throw new Error(
|
|
20
|
+
"[h2:error:RichText] Parsing error. Make sure to pass a JSON string of rich text metafield",
|
|
21
|
+
{
|
|
22
|
+
cause: e
|
|
23
|
+
}
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function serializeRichTextASTNode(components = {}, node, index = 0) {
|
|
28
|
+
let children;
|
|
29
|
+
if ("children" in node) {
|
|
30
|
+
children = node.children.map(
|
|
31
|
+
(child, childIndex) => serializeRichTextASTNode(components, child, childIndex)
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
const Component = components[node.type === "list-item" ? "listItem" : node.type] ?? RichTextComponents[node.type];
|
|
35
|
+
switch (node.type) {
|
|
36
|
+
case "root":
|
|
37
|
+
return createElement(
|
|
38
|
+
Component,
|
|
39
|
+
{
|
|
40
|
+
key: index,
|
|
41
|
+
node: {
|
|
42
|
+
type: "root",
|
|
43
|
+
children
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
);
|
|
47
|
+
case "heading":
|
|
48
|
+
return createElement(
|
|
49
|
+
Component,
|
|
50
|
+
{
|
|
51
|
+
key: index,
|
|
52
|
+
node: {
|
|
53
|
+
type: "heading",
|
|
54
|
+
level: node.level,
|
|
55
|
+
children
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
);
|
|
59
|
+
case "paragraph":
|
|
60
|
+
return createElement(
|
|
61
|
+
Component,
|
|
62
|
+
{
|
|
63
|
+
key: index,
|
|
64
|
+
node: {
|
|
65
|
+
type: "paragraph",
|
|
66
|
+
children
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
);
|
|
70
|
+
case "text": {
|
|
71
|
+
const elements = (node.value ?? "").split("\n").flatMap((value, subindex) => {
|
|
72
|
+
const key = `${index}-${value}-${subindex}`;
|
|
73
|
+
const textElement = createElement(
|
|
74
|
+
Component,
|
|
75
|
+
{
|
|
76
|
+
key,
|
|
77
|
+
node: {
|
|
78
|
+
type: "text",
|
|
79
|
+
italic: node.italic,
|
|
80
|
+
bold: node.bold,
|
|
81
|
+
value
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
);
|
|
85
|
+
return subindex === 0 ? textElement : [createElement("br", { key: `${key}-br` }), textElement];
|
|
86
|
+
});
|
|
87
|
+
return elements.length > 1 ? createElement(Fragment, { key: index }, elements) : elements[0];
|
|
88
|
+
}
|
|
89
|
+
case "link":
|
|
90
|
+
return createElement(
|
|
91
|
+
Component,
|
|
92
|
+
{
|
|
93
|
+
key: index,
|
|
94
|
+
node: {
|
|
95
|
+
type: "link",
|
|
96
|
+
url: node.url,
|
|
97
|
+
title: node.title,
|
|
98
|
+
target: node.target,
|
|
99
|
+
children
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
);
|
|
103
|
+
case "list":
|
|
104
|
+
return createElement(
|
|
105
|
+
Component,
|
|
106
|
+
{
|
|
107
|
+
key: index,
|
|
108
|
+
node: {
|
|
109
|
+
type: "list",
|
|
110
|
+
listType: node.listType,
|
|
111
|
+
children
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
);
|
|
115
|
+
case "list-item":
|
|
116
|
+
return createElement(
|
|
117
|
+
Component,
|
|
118
|
+
{
|
|
119
|
+
key: index,
|
|
120
|
+
node: {
|
|
121
|
+
type: "list-item",
|
|
122
|
+
children
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function richTextToString(node, result = []) {
|
|
129
|
+
switch (node.type) {
|
|
130
|
+
case "root":
|
|
131
|
+
node.children.forEach((child) => richTextToString(child, result));
|
|
132
|
+
break;
|
|
133
|
+
case "heading":
|
|
134
|
+
case "paragraph":
|
|
135
|
+
node.children.forEach((child) => richTextToString(child, result));
|
|
136
|
+
result.push(" ");
|
|
137
|
+
break;
|
|
138
|
+
case "text":
|
|
139
|
+
result.push(node.value || "");
|
|
140
|
+
break;
|
|
141
|
+
case "link":
|
|
142
|
+
node.children.forEach((child) => richTextToString(child, result));
|
|
143
|
+
break;
|
|
144
|
+
case "list":
|
|
145
|
+
node.children.forEach((item) => {
|
|
146
|
+
if (item.children) {
|
|
147
|
+
item.children.forEach((child) => richTextToString(child, result));
|
|
148
|
+
}
|
|
149
|
+
result.push(" ");
|
|
150
|
+
});
|
|
151
|
+
break;
|
|
152
|
+
default:
|
|
153
|
+
throw new Error(`Unknown node encountered ${node.type}`);
|
|
154
|
+
}
|
|
155
|
+
return result.join("").trim();
|
|
156
|
+
}
|
|
157
|
+
export {
|
|
158
|
+
RichText
|
|
159
|
+
};
|
|
160
|
+
//# sourceMappingURL=RichText.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RichText.mjs","sources":["../../src/RichText.tsx"],"sourcesContent":["import {createElement, Fragment, type ReactNode, useMemo} from 'react';\nimport type {RichTextASTNode} from './RichText.types.js';\nimport {\n type CustomComponents,\n RichTextComponents,\n} from './RichText.components.js';\n\nexport interface RichTextPropsBase<ComponentGeneric extends React.ElementType> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `div`. */\n as?: ComponentGeneric;\n /** The JSON string that correspond to the Storefront API's [RichText format](https://shopify.dev/docs/apps/custom-data/metafields/types#rich-text-formatting). */\n data: string;\n /** Customize how rich text components are rendered */\n components?: CustomComponents;\n /** Remove rich text formatting and render plain text */\n plain?: boolean;\n}\n\nexport function RichText<ComponentGeneric extends React.ElementType = 'div'>({\n as,\n data,\n plain,\n components,\n ...passthroughProps\n}: RichTextProps<ComponentGeneric>): JSX.Element {\n try {\n const Wrapper = as ?? 'div';\n const parsedData = useMemo(\n () => JSON.parse(data) as RichTextASTNode,\n [data],\n );\n\n return (\n <Wrapper {...passthroughProps}>\n {plain\n ? richTextToString(parsedData)\n : serializeRichTextASTNode(components, parsedData)}\n </Wrapper>\n );\n } catch (e) {\n throw new Error(\n '[h2:error:RichText] Parsing error. Make sure to pass a JSON string of rich text metafield',\n {\n cause: e,\n },\n );\n }\n}\n\n// This article helps understand the typing here https://www.benmvp.com/blog/polymorphic-react-components-typescript/ Ben is the best :)\nexport type RichTextProps<ComponentGeneric extends React.ElementType> =\n RichTextPropsBase<ComponentGeneric> &\n Omit<\n React.ComponentPropsWithoutRef<ComponentGeneric>,\n keyof RichTextPropsBase<ComponentGeneric>\n >;\n\nfunction serializeRichTextASTNode(\n components: CustomComponents = {},\n node: RichTextASTNode,\n index = 0,\n): ReactNode {\n let children;\n if ('children' in node) {\n children = node.children.map((child, childIndex) =>\n serializeRichTextASTNode(components, child, childIndex),\n );\n }\n\n const Component =\n components[node.type === 'list-item' ? 'listItem' : node.type] ??\n RichTextComponents[node.type];\n\n switch (node.type) {\n case 'root':\n return createElement(\n Component as Exclude<CustomComponents['root'], undefined>,\n {\n key: index,\n node: {\n type: 'root',\n children,\n },\n },\n );\n case 'heading':\n return createElement(\n Component as Exclude<CustomComponents['heading'], undefined>,\n {\n key: index,\n node: {\n type: 'heading',\n level: node.level,\n children,\n },\n },\n );\n case 'paragraph':\n return createElement(\n Component as Exclude<CustomComponents['paragraph'], undefined>,\n {\n key: index,\n node: {\n type: 'paragraph',\n children,\n },\n },\n );\n case 'text': {\n const elements = (node.value ?? '')\n .split('\\n')\n .flatMap((value, subindex) => {\n const key = `${index}-${value}-${subindex}`;\n const textElement = createElement(\n Component as Exclude<CustomComponents['text'], undefined>,\n {\n key,\n node: {\n type: 'text',\n italic: node.italic,\n bold: node.bold,\n value,\n },\n },\n );\n\n // Add a `<br>` before each substring except the first one\n return subindex === 0\n ? textElement\n : [createElement('br', {key: `${key}-br`}), textElement];\n });\n\n return elements.length > 1\n ? createElement(Fragment, {key: index}, elements)\n : elements[0];\n }\n case 'link':\n return createElement(\n Component as Exclude<CustomComponents['link'], undefined>,\n {\n key: index,\n node: {\n type: 'link',\n url: node.url,\n title: node.title,\n target: node.target,\n children,\n },\n },\n );\n case 'list':\n return createElement(\n Component as Exclude<CustomComponents['list'], undefined>,\n {\n key: index,\n node: {\n type: 'list',\n listType: node.listType,\n children,\n },\n },\n );\n case 'list-item':\n return createElement(\n Component as Exclude<CustomComponents['listItem'], undefined>,\n {\n key: index,\n node: {\n type: 'list-item',\n children,\n },\n },\n );\n }\n}\n\nfunction richTextToString(\n node: RichTextASTNode,\n result: string[] = [],\n): string {\n switch (node.type) {\n case 'root':\n node.children.forEach((child) => richTextToString(child, result));\n break;\n case 'heading':\n case 'paragraph':\n node.children.forEach((child) => richTextToString(child, result));\n result.push(' ');\n break;\n case 'text':\n result.push(node.value || '');\n break;\n case 'link':\n node.children.forEach((child) => richTextToString(child, result));\n break;\n case 'list':\n node.children.forEach((item) => {\n if (item.children) {\n item.children.forEach((child) => richTextToString(child, result));\n }\n result.push(' ');\n });\n break;\n default:\n throw new Error(`Unknown node encountered ${node.type}`);\n }\n\n return result.join('').trim();\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport type RichTextPropsForDocs<AsType extends React.ElementType = 'div'> =\n RichTextPropsBase<AsType>;\n"],"names":[],"mappings":";;;AAkBO,SAAS,SAA6D;AAAA,EAC3E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAAiD;AAC3C,MAAA;AACF,UAAM,UAAU,MAAM;AACtB,UAAM,aAAa;AAAA,MACjB,MAAM,KAAK,MAAM,IAAI;AAAA,MACrB,CAAC,IAAI;AAAA,IAAA;AAIL,WAAA,oBAAC,SAAS,EAAA,GAAG,kBACV,UAAA,QACG,iBAAiB,UAAU,IAC3B,yBAAyB,YAAY,UAAU,EACrD,CAAA;AAAA,WAEK,GAAG;AACV,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,QACE,OAAO;AAAA,MACT;AAAA,IAAA;AAAA,EAEJ;AACF;AAUA,SAAS,yBACP,aAA+B,CAAA,GAC/B,MACA,QAAQ,GACG;AACP,MAAA;AACJ,MAAI,cAAc,MAAM;AACtB,eAAW,KAAK,SAAS;AAAA,MAAI,CAAC,OAAO,eACnC,yBAAyB,YAAY,OAAO,UAAU;AAAA,IAAA;AAAA,EAE1D;AAEM,QAAA,YACJ,WAAW,KAAK,SAAS,cAAc,aAAa,KAAK,IAAI,KAC7D,mBAAmB,KAAK,IAAI;AAE9B,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACI,aAAA;AAAA,QACL;AAAA,QACA;AAAA,UACE,KAAK;AAAA,UACL,MAAM;AAAA,YACJ,MAAM;AAAA,YACN;AAAA,UACF;AAAA,QACF;AAAA,MAAA;AAAA,IAEJ,KAAK;AACI,aAAA;AAAA,QACL;AAAA,QACA;AAAA,UACE,KAAK;AAAA,UACL,MAAM;AAAA,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,UACE,KAAK;AAAA,UACL,MAAM;AAAA,YACJ,MAAM;AAAA,YACN;AAAA,UACF;AAAA,QACF;AAAA,MAAA;AAAA,EAEN;AACF;AAEA,SAAS,iBACP,MACA,SAAmB,IACX;AACR,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,WAAK,SAAS,QAAQ,CAAC,UAAU,iBAAiB,OAAO,MAAM,CAAC;AAChE;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AACH,WAAK,SAAS,QAAQ,CAAC,UAAU,iBAAiB,OAAO,MAAM,CAAC;AAChE,aAAO,KAAK,GAAG;AACf;AAAA,IACF,KAAK;AACI,aAAA,KAAK,KAAK,SAAS,EAAE;AAC5B;AAAA,IACF,KAAK;AACH,WAAK,SAAS,QAAQ,CAAC,UAAU,iBAAiB,OAAO,MAAM,CAAC;AAChE;AAAA,IACF,KAAK;AACE,WAAA,SAAS,QAAQ,CAAC,SAAS;AAC9B,YAAI,KAAK,UAAU;AACjB,eAAK,SAAS,QAAQ,CAAC,UAAU,iBAAiB,OAAO,MAAM,CAAC;AAAA,QAClE;AACA,eAAO,KAAK,GAAG;AAAA,MAAA,CAChB;AACD;AAAA,IACF;AACE,YAAM,IAAI,MAAM,4BAA4B,KAAK,IAAI,EAAE;AAAA,EAC3D;AAEA,SAAO,OAAO,KAAK,EAAE,EAAE,KAAK;AAC9B;"}
|
|
@@ -37,7 +37,8 @@ function ShopifyProvider({
|
|
|
37
37
|
}
|
|
38
38
|
const finalConfig = useMemo(() => {
|
|
39
39
|
function getShopifyDomain(overrideProps) {
|
|
40
|
-
|
|
40
|
+
const domain = (overrideProps == null ? void 0 : overrideProps.storeDomain) ?? shopifyConfig.storeDomain;
|
|
41
|
+
return domain.includes("://") ? domain : `https://${domain}`;
|
|
41
42
|
}
|
|
42
43
|
return {
|
|
43
44
|
...shopifyConfig,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShopifyProvider.mjs","sources":["../../src/ShopifyProvider.tsx"],"sourcesContent":["import {createContext, useContext, useMemo, type ReactNode} from 'react';\nimport type {LanguageCode, CountryCode} from './storefront-api-types.js';\nimport {SFAPI_VERSION} from './storefront-api-constants.js';\nimport {getPublicTokenHeadersRaw} from './storefront-client.js';\n\nexport const defaultShopifyContext: ShopifyContextValue = {\n storeDomain: 'test',\n storefrontToken: 'abc123',\n storefrontApiVersion: SFAPI_VERSION,\n countryIsoCode: 'US',\n languageIsoCode: 'EN',\n getStorefrontApiUrl() {\n return '';\n },\n getPublicTokenHeaders() {\n return {};\n },\n getShopifyDomain() {\n return '';\n },\n};\n\nconst ShopifyContext = createContext<ShopifyContextValue>(\n defaultShopifyContext,\n);\n\n/**\n * The `<ShopifyProvider/>` component enables use of the `useShop()` hook. The component should wrap your app.\n */\nexport function ShopifyProvider({\n children,\n ...shopifyConfig\n}: ShopifyProviderProps): JSX.Element {\n if (\n !shopifyConfig.countryIsoCode ||\n !shopifyConfig.languageIsoCode ||\n !shopifyConfig.storeDomain ||\n !shopifyConfig.storefrontToken ||\n !shopifyConfig.storefrontApiVersion\n ) {\n throw new Error(\n `Please provide the necessary props to '<ShopifyProvider/>'`,\n );\n }\n\n if (shopifyConfig.storefrontApiVersion !== SFAPI_VERSION) {\n console.warn(\n `<ShopifyProvider/>: This version of Hydrogen React is built for Shopify's Storefront API version ${SFAPI_VERSION}, but it looks like you're using version ${shopifyConfig.storefrontApiVersion}. There may be issues or bugs if you use a mismatched version of Hydrogen React and the Storefront API.`,\n );\n }\n\n const finalConfig = useMemo<ShopifyContextValue>(() => {\n function getShopifyDomain(overrideProps?: {storeDomain?: string}): string {\n
|
|
1
|
+
{"version":3,"file":"ShopifyProvider.mjs","sources":["../../src/ShopifyProvider.tsx"],"sourcesContent":["import {createContext, useContext, useMemo, type ReactNode} from 'react';\nimport type {LanguageCode, CountryCode} from './storefront-api-types.js';\nimport {SFAPI_VERSION} from './storefront-api-constants.js';\nimport {getPublicTokenHeadersRaw} from './storefront-client.js';\n\nexport const defaultShopifyContext: ShopifyContextValue = {\n storeDomain: 'test',\n storefrontToken: 'abc123',\n storefrontApiVersion: SFAPI_VERSION,\n countryIsoCode: 'US',\n languageIsoCode: 'EN',\n getStorefrontApiUrl() {\n return '';\n },\n getPublicTokenHeaders() {\n return {};\n },\n getShopifyDomain() {\n return '';\n },\n};\n\nconst ShopifyContext = createContext<ShopifyContextValue>(\n defaultShopifyContext,\n);\n\n/**\n * The `<ShopifyProvider/>` component enables use of the `useShop()` hook. The component should wrap your app.\n */\nexport function ShopifyProvider({\n children,\n ...shopifyConfig\n}: ShopifyProviderProps): JSX.Element {\n if (\n !shopifyConfig.countryIsoCode ||\n !shopifyConfig.languageIsoCode ||\n !shopifyConfig.storeDomain ||\n !shopifyConfig.storefrontToken ||\n !shopifyConfig.storefrontApiVersion\n ) {\n throw new Error(\n `Please provide the necessary props to '<ShopifyProvider/>'`,\n );\n }\n\n if (shopifyConfig.storefrontApiVersion !== SFAPI_VERSION) {\n console.warn(\n `<ShopifyProvider/>: This version of Hydrogen React is built for Shopify's Storefront API version ${SFAPI_VERSION}, but it looks like you're using version ${shopifyConfig.storefrontApiVersion}. There may be issues or bugs if you use a mismatched version of Hydrogen React and the Storefront API.`,\n );\n }\n\n const finalConfig = useMemo<ShopifyContextValue>(() => {\n function getShopifyDomain(overrideProps?: {storeDomain?: string}): string {\n const domain = overrideProps?.storeDomain ?? shopifyConfig.storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n }\n\n return {\n ...shopifyConfig,\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n return getPublicTokenHeadersRaw(\n overrideProps.contentType,\n shopifyConfig.storefrontApiVersion,\n overrideProps.storefrontToken ?? shopifyConfig.storefrontToken,\n );\n },\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl = getShopifyDomain({\n storeDomain: overrideProps?.storeDomain ?? shopifyConfig.storeDomain,\n });\n return `${finalDomainUrl}${\n finalDomainUrl.endsWith('/') ? '' : '/'\n }api/${\n overrideProps?.storefrontApiVersion ??\n shopifyConfig.storefrontApiVersion\n }/graphql.json`;\n },\n };\n }, [shopifyConfig]);\n\n return (\n <ShopifyContext.Provider value={finalConfig}>\n {children}\n </ShopifyContext.Provider>\n );\n}\n\n/**\n * Provides access to the `shopifyConfig` prop of `<ShopifyProvider/>`. Must be a descendent of `<ShopifyProvider/>`.\n */\nexport function useShop(): ShopifyContextValue {\n const shopContext = useContext(ShopifyContext);\n if (!shopContext) {\n throw new Error(`'useShop()' must be a descendent of <ShopifyProvider/>`);\n }\n return shopContext;\n}\n\nexport interface ShopifyProviderBase {\n /** The globally-unique identifier for the Shop */\n storefrontId?: string;\n /** The full domain of your Shopify storefront URL (eg: the complete string of `{subdomain}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API public access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * The code designating a country, which generally follows ISO 3166-1 alpha-2 guidelines. If a territory doesn't have a country code value in the `CountryCode` enum, it might be considered a subdivision of another country. For example, the territories associated with Spain are represented by the country code `ES`, and the territories associated with the United States of America are represented by the country code `US`.\n */\n countryIsoCode: CountryCode;\n /**\n * `ISO 369` language codes supported by Shopify.\n */\n languageIsoCode: LanguageCode;\n}\n\n/**\n * Shopify-specific values that are used in various Hydrogen React components and hooks.\n */\nexport interface ShopifyProviderProps extends ShopifyProviderBase {\n /** React children to render. */\n children?: ReactNode;\n}\n\nexport interface ShopifyContextValue\n extends ShopifyProviderBase,\n ShopifyContextReturn {}\n\ntype ShopifyContextReturn = {\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (props?: GetStorefrontApiUrlProps) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This uses the public Storefront API token.\n *\n * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `storefrontToken`\n *\n */\n getPublicTokenHeaders: (\n props: GetPublicTokenHeadersProps,\n ) => Record<string, string>;\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (props?: GetShopifyDomainProps) => string;\n};\n\ntype GetStorefrontApiUrlProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen-UI was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion?: string;\n};\n\ntype GetPublicTokenHeadersProps = {\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n */\n contentType: 'json' | 'graphql';\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n storefrontToken?: string;\n};\n\ntype GetShopifyDomainProps = {storeDomain?: string};\n"],"names":[],"mappings":";;;;AAKO,MAAM,wBAA6C;AAAA,EACxD,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,sBAAsB;AAAA,EACtB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,sBAAsB;AACb,WAAA;AAAA,EACT;AAAA,EACA,wBAAwB;AACtB,WAAO;EACT;AAAA,EACA,mBAAmB;AACV,WAAA;AAAA,EACT;AACF;AAEA,MAAM,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parse-metafield.mjs";
|
|
23
23
|
import { ProductPrice } from "./ProductPrice.mjs";
|
|
24
24
|
import { ProductProvider, useProduct } from "./ProductProvider.mjs";
|
|
25
|
+
import { RichText } from "./RichText.mjs";
|
|
25
26
|
import { ShopifyProvider, useShop } from "./ShopifyProvider.mjs";
|
|
26
27
|
import { ShopPayButton } from "./ShopPayButton.mjs";
|
|
27
28
|
import { createStorefrontClient } from "./storefront-client.mjs";
|
|
@@ -47,6 +48,7 @@ export {
|
|
|
47
48
|
Money,
|
|
48
49
|
ProductPrice,
|
|
49
50
|
ProductProvider,
|
|
51
|
+
RichText,
|
|
50
52
|
SHOPIFY_S,
|
|
51
53
|
SHOPIFY_STOREFRONT_ID_HEADER,
|
|
52
54
|
SHOPIFY_STOREFRONT_S_HEADER,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-metafield.mjs","sources":["../../src/parse-metafield.ts"],"sourcesContent":["import type {\n Collection,\n GenericFile,\n Metafield as MetafieldBaseType,\n MoneyV2,\n Page,\n Product,\n ProductVariant,\n} from './storefront-api-types.js';\nimport type {PartialDeep, Simplify} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\n/**\n * A function that uses `metafield.type` to parse the Metafield's `value` or `reference` or `references` (depending on the `metafield.type`) and places the result in `metafield.parsedValue`\n *\n * TypeScript developers can use the type `ParsedMetafields` from this package to get the returned object's type correct. For example:\n *\n * ```\n * parseMetafield<ParsedMetafields['boolean']>({type: 'boolean', value: 'false'}\n * ```\n */\nexport function parseMetafield<ReturnGeneric>(\n metafield: PartialDeep<MetafieldBaseType, {recurseIntoArrays: true}>,\n): ReturnGeneric {\n if (!metafield.type) {\n const noTypeError = `parseMetafield(): The 'type' field is required in order to parse the Metafield.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noTypeError);\n } else {\n console.error(`${noTypeError} Returning 'parsedValue' of 'null'`);\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n\n switch (metafield.type) {\n case 'boolean':\n return {\n ...metafield,\n parsedValue: metafield.value === 'true',\n } as ReturnGeneric;\n\n case 'collection_reference':\n case 'file_reference':\n case 'page_reference':\n case 'product_reference':\n case 'variant_reference':\n return {\n ...metafield,\n parsedValue: metafield.reference,\n } as ReturnGeneric;\n\n case 'color':\n case 'multi_line_text_field':\n case 'single_line_text_field':\n case 'url':\n return {\n ...metafield,\n parsedValue: metafield.value,\n } as ReturnGeneric;\n\n // TODO: 'money' should probably be parsed even further to like `useMoney()`, but that logic needs to be extracted first so it's not a hook\n case 'dimension':\n case 'money':\n case 'json':\n case 'rating':\n case 'volume':\n case 'weight':\n case 'list.color':\n case 'list.dimension':\n case 'list.number_integer':\n case 'list.number_decimal':\n case 'list.rating':\n case 'list.single_line_text_field':\n case 'list.url':\n case 'list.volume':\n case 'list.weight': {\n let parsedValue = null;\n try {\n parsedValue = parseJSON(metafield.value ?? '');\n } catch (err) {\n const parseError = `parseMetafield(): attempted to JSON.parse the 'metafield.value' property, but failed.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(parseError);\n } else {\n console.error(`${parseError} Returning 'null' for 'parsedValue'`);\n }\n parsedValue = null;\n }\n return {\n ...metafield,\n parsedValue,\n } as ReturnGeneric;\n }\n\n case 'date':\n case 'date_time':\n return {\n ...metafield,\n parsedValue: new Date(metafield.value ?? ''),\n } as ReturnGeneric;\n\n case 'list.date':\n case 'list.date_time': {\n const jsonParseValue = parseJSON(metafield?.value ?? '') as string[];\n return {\n ...metafield,\n parsedValue: jsonParseValue.map((dateString) => new Date(dateString)),\n } as ReturnGeneric;\n }\n\n case 'number_decimal':\n case 'number_integer':\n return {\n ...metafield,\n parsedValue: Number(metafield.value),\n } as ReturnGeneric;\n\n case 'list.collection_reference':\n case 'list.file_reference':\n case 'list.page_reference':\n case 'list.product_reference':\n case 'list.variant_reference':\n return {\n ...metafield,\n parsedValue: flattenConnection(metafield.references ?? undefined),\n } as ReturnGeneric;\n\n default: {\n const typeNotFoundError = `parseMetafield(): the 'metafield.type' you passed in is not supported. Your type: \"${metafield.type}\". If you believe this is an error, please open an issue on GitHub.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(typeNotFoundError);\n } else {\n console.error(\n `${typeNotFoundError} Returning 'parsedValue' of 'null'`,\n );\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n }\n}\n\n/**\n * Parses a JSON string while preventing prototype injection attacks.\n */\nexport function parseJSON(json: string): unknown {\n if (String(json).includes('__proto__')) {\n return JSON.parse(json, (k, v) => {\n if (k !== '__proto__') return v as unknown;\n }) as unknown;\n }\n return JSON.parse(json) as unknown;\n}\n\n// taken from https://shopify.dev/apps/metafields/types\nexport const allMetafieldTypesArray = [\n 'boolean',\n 'collection_reference',\n 'color',\n 'date',\n 'date_time',\n 'dimension',\n 'file_reference',\n 'json',\n 'money',\n 'multi_line_text_field',\n 'number_decimal',\n 'number_integer',\n 'page_reference',\n 'product_reference',\n 'rating',\n 'single_line_text_field',\n 'url',\n 'variant_reference',\n 'volume',\n 'weight',\n // list metafields\n 'list.collection_reference',\n 'list.color',\n 'list.date',\n 'list.date_time',\n 'list.dimension',\n 'list.file_reference',\n 'list.number_integer',\n 'list.number_decimal',\n 'list.page_reference',\n 'list.product_reference',\n 'list.rating',\n 'list.single_line_text_field',\n 'list.url',\n 'list.variant_reference',\n 'list.volume',\n 'list.weight',\n] as const;\n\n/** A union of all the supported `metafield.type`s */\nexport type MetafieldTypeTypes = (typeof allMetafieldTypesArray)[number];\n\n/**\n * A mapping of a Metafield's `type` to the TypeScript type that is returned from `parseMetafield()`\n * For example, when using `parseMetafield()`, the type will be correctly returned when used like the following:\n *\n * ```\n * const parsedMetafield = parseMetafield<ParsedMetafields['boolean']>(metafield);`\n * ```\n * `parsedMetafield.parsedValue`'s type is now `boolean`\n */\nexport type ParsedMetafields<ExtraTypeGeneric = void> = {\n /** A Metafield that's been parsed, with a `parsedValue` of `boolean` */\n boolean: Simplify<BooleanParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Collection` object (as defined by the Storefront API) */\n collection_reference: Simplify<CollectionParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n color: Simplify<ColorParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date_time: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n dimension: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `GenericFile` object (as defined by the Storefront API) */\n file_reference: Simplify<FileRefParsedMetafield>;\n /**\n * A Metafield that's been parsed, with a `parsedValue` of type `unknown`, unless you pass in the type as a generic. For example:\n *\n * ```\n * ParsedMetafields<MyJsonType>['json']\n * ```\n */\n json: Simplify<JsonParsedMetafield<ExtraTypeGeneric>>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Money` */\n money: Simplify<MoneyParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n multi_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_decimal: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_integer: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Page` object (as defined by the Storefront API) */\n page_reference: Simplify<PageParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Product` object (as defined by the Storefront API) */\n product_reference: Simplify<ProductParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Rating` */\n rating: Simplify<RatingParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n single_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n url: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `ProductVariant` object (as defined by the Storefront API) */\n variant_reference: Simplify<VariantParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n volume: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n weight: Simplify<MeasurementParsedMetafield>;\n // list metafields\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Collection` objects (as defined by the Storefront API) */\n 'list.collection_reference': Simplify<CollectionListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.color': Simplify<ColorListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date_time': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement` objects */\n 'list.dimension': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `GenericFile` objects (as defined by the Storefront API) */\n 'list.file_reference': Simplify<FileListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_integer': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_decimal': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Page` objects (as defined by the Storefront API) */\n 'list.page_reference': Simplify<PageListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Product` objects (as defined by the Storefront API) */\n 'list.product_reference': Simplify<ProductListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Rating`s */\n 'list.rating': Simplify<RatingListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.single_line_text_field': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.url': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `ProductVariant` objects (as defined by the Storefront API) */\n 'list.variant_reference': Simplify<VariantListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.volume': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.weight': Simplify<MeasurementListParsedMetafield>;\n};\n\ninterface ParsedBase extends MetafieldBaseType {\n type: MetafieldTypeTypes;\n parsedValue: unknown;\n}\n\ninterface BooleanParsedMetafield extends ParsedBase {\n type: 'boolean';\n parsedValue: boolean | null;\n}\ntype CollectionParsedRefMetafield = MetafieldBaseType & {\n type: 'collection_reference';\n parsedValue: Collection | null;\n};\ntype ColorParsedMetafield = MetafieldBaseType & {\n type: 'color';\n parsedValue: string | null;\n};\ntype DatesParsedMetafield = MetafieldBaseType & {\n type: 'date' | 'date_time';\n parsedValue: Date | null;\n};\n\ntype MeasurementParsedMetafield = MetafieldBaseType & {\n type: 'dimension' | 'weight' | 'volume';\n parsedValue: Measurement | null;\n};\n\ntype FileRefParsedMetafield = MetafieldBaseType & {\n type: 'file_reference';\n parsedValue: GenericFile | null;\n};\n\ntype JsonParsedMetafield<JsonTypeGeneric = void> = MetafieldBaseType & {\n type: 'json';\n parsedValue: JsonTypeGeneric extends void ? unknown : JsonTypeGeneric | null;\n};\n\ntype MoneyParsedMetafield = MetafieldBaseType & {\n type: 'money';\n parsedValue: MoneyV2 | null;\n};\n\ntype TextParsedMetafield = MetafieldBaseType & {\n type: 'single_line_text_field' | 'multi_line_text_field' | 'url';\n parsedValue: string | null;\n};\n\ntype NumberParsedMetafield = MetafieldBaseType & {\n type: 'number_decimal' | 'number_integer';\n parsedValue: number | null;\n};\n\ntype PageParsedRefMetafield = MetafieldBaseType & {\n type: 'page_reference';\n parsedValue: Page | null;\n};\n\ntype ProductParsedRefMetafield = MetafieldBaseType & {\n type: 'product_reference';\n parsedValue: Product | null;\n};\n\ntype RatingParsedMetafield = MetafieldBaseType & {\n type: 'rating';\n parsedValue: Rating | null;\n};\n\ntype VariantParsedRefMetafield = MetafieldBaseType & {\n type: 'variant_reference';\n parsedValue: ProductVariant | null;\n};\n\ntype CollectionListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.collection_reference';\n parsedValue: Array<Collection> | null;\n};\n\ntype ColorListParsedMetafield = MetafieldBaseType & {\n type: 'list.color';\n parsedValue: Array<string> | null;\n};\n\ntype DatesListParsedMetafield = MetafieldBaseType & {\n type: 'list.date' | 'list.date_time';\n parsedValue: Array<Date> | null;\n};\n\ntype MeasurementListParsedMetafield = MetafieldBaseType & {\n type: 'list.dimension' | 'list.weight' | 'list.volume';\n parsedValue: Array<Measurement> | null;\n};\n\ntype FileListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.file_reference';\n parsedValue: Array<GenericFile> | null;\n};\n\ntype TextListParsedMetafield = MetafieldBaseType & {\n type: 'list.single_line_text_field' | 'list.url';\n parsedValue: Array<string> | null;\n};\n\ntype NumberListParsedMetafield = MetafieldBaseType & {\n type: 'list.number_decimal' | 'list.number_integer';\n parsedValue: Array<number> | null;\n};\n\ntype PageListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.page_reference';\n parsedValue: Array<Page> | null;\n};\n\ntype ProductListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.product_reference';\n parsedValue: Array<Product> | null;\n};\n\ntype RatingListParsedMetafield = MetafieldBaseType & {\n type: 'list.rating';\n parsedValue: Array<Rating> | null;\n};\n\ntype VariantListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.variant_reference';\n parsedValue: Array<ProductVariant> | null;\n};\n\nexport type Measurement = {\n unit: string;\n value: number;\n};\n\nexport interface Rating {\n value: number;\n scale_min: number;\n scale_max: number;\n}\n"],"names":[],"mappings":";AAqBO,SAAS,eACd,WACe;AACX,MAAA,CAAC,UAAU,MAAM;AACnB,UAAM,cAAc;AACE;AACd,YAAA,IAAI,MAAM,WAAW;AAAA,IAO7B;AAAA,EACF;AAEA,UAAQ,UAAU,MAAM;AAAA,IACtB,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU,UAAU;AAAA,MAAA;AAAA,IAGrC,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU;AAAA,MAAA;AAAA,IAG3B,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU;AAAA,MAAA;AAAA,IAI3B,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK,eAAe;AAClB,UAAI,cAAc;AACd,UAAA;AACY,sBAAA,UAAU,UAAU,SAAS,EAAE;AAAA,eACtC,KAAK;AACZ,cAAM,aAAa;AACG;AACd,gBAAA,IAAI,MAAM,UAAU;AAAA,QAG5B;AAAA,MAEF;AACO,aAAA;AAAA,QACL,GAAG;AAAA,QACH;AAAA,MAAA;AAAA,IAEJ;AAAA,IAEA,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,IAAI,KAAK,UAAU,SAAS,EAAE;AAAA,MAAA;AAAA,IAG/C,KAAK;AAAA,IACL,KAAK,kBAAkB;AACrB,YAAM,iBAAiB,WAAU,uCAAW,UAAS,EAAE;AAChD,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,eAAe,IAAI,CAAC,eAAe,IAAI,KAAK,UAAU,CAAC;AAAA,MAAA;AAAA,IAExE;AAAA,IAEA,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,OAAO,UAAU,KAAK;AAAA,MAAA;AAAA,IAGvC,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,kBAAkB,UAAU,cAAc,MAAS;AAAA,MAAA;AAAA,IAGpE,SAAS;AACD,YAAA,oBAAoB,sFAAsF,UAAU,IAAI;AACxG;AACd,cAAA,IAAI,MAAM,iBAAiB;AAAA,MASnC;AAAA,IACF;AAAA,EACF;AACF;AAKO,SAAS,UAAU,MAAuB;AAC/C,MAAI,OAAO,IAAI,EAAE,SAAS,WAAW,GAAG;AACtC,WAAO,KAAK,MAAM,MAAM,CAAC,GAAG,MAAM;AAChC,UAAI,MAAM;AAAoB,eAAA;AAAA,IAAA,CAC/B;AAAA,EACH;AACO,SAAA,KAAK,MAAM,IAAI;AACxB;"}
|
|
1
|
+
{"version":3,"file":"parse-metafield.mjs","sources":["../../src/parse-metafield.ts"],"sourcesContent":["import type {\n Collection,\n GenericFile,\n Metafield as MetafieldBaseType,\n MoneyV2,\n Page,\n Product,\n ProductVariant,\n} from './storefront-api-types.js';\nimport type {PartialDeep, Simplify} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\nimport {RootASTNode as RichTextRootASTNode} from './RichText.types.js';\n\n/**\n * A function that uses `metafield.type` to parse the Metafield's `value` or `reference` or `references` (depending on the `metafield.type`) and places the result in `metafield.parsedValue`\n *\n * TypeScript developers can use the type `ParsedMetafields` from this package to get the returned object's type correct. For example:\n *\n * ```\n * parseMetafield<ParsedMetafields['boolean']>({type: 'boolean', value: 'false'}\n * ```\n */\nexport function parseMetafield<ReturnGeneric>(\n metafield: PartialDeep<MetafieldBaseType, {recurseIntoArrays: true}>,\n): ReturnGeneric {\n if (!metafield.type) {\n const noTypeError = `parseMetafield(): The 'type' field is required in order to parse the Metafield.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noTypeError);\n } else {\n console.error(`${noTypeError} Returning 'parsedValue' of 'null'`);\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n\n switch (metafield.type) {\n case 'boolean':\n return {\n ...metafield,\n parsedValue: metafield.value === 'true',\n } as ReturnGeneric;\n\n case 'collection_reference':\n case 'file_reference':\n case 'page_reference':\n case 'product_reference':\n case 'variant_reference':\n return {\n ...metafield,\n parsedValue: metafield.reference,\n } as ReturnGeneric;\n\n case 'color':\n case 'multi_line_text_field':\n case 'single_line_text_field':\n case 'url':\n return {\n ...metafield,\n parsedValue: metafield.value,\n } as ReturnGeneric;\n\n // TODO: 'money' should probably be parsed even further to like `useMoney()`, but that logic needs to be extracted first so it's not a hook\n case 'dimension':\n case 'money':\n case 'json':\n case 'rating':\n case 'volume':\n case 'weight':\n case 'rich_text_field':\n case 'list.color':\n case 'list.dimension':\n case 'list.number_integer':\n case 'list.number_decimal':\n case 'list.rating':\n case 'list.single_line_text_field':\n case 'list.url':\n case 'list.volume':\n case 'list.weight': {\n let parsedValue = null;\n try {\n parsedValue = parseJSON(metafield.value ?? '');\n } catch (err) {\n const parseError = `parseMetafield(): attempted to JSON.parse the 'metafield.value' property, but failed.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(parseError);\n } else {\n console.error(`${parseError} Returning 'null' for 'parsedValue'`);\n }\n parsedValue = null;\n }\n return {\n ...metafield,\n parsedValue,\n } as ReturnGeneric;\n }\n\n case 'date':\n case 'date_time':\n return {\n ...metafield,\n parsedValue: new Date(metafield.value ?? ''),\n } as ReturnGeneric;\n\n case 'list.date':\n case 'list.date_time': {\n const jsonParseValue = parseJSON(metafield?.value ?? '') as string[];\n return {\n ...metafield,\n parsedValue: jsonParseValue.map((dateString) => new Date(dateString)),\n } as ReturnGeneric;\n }\n\n case 'number_decimal':\n case 'number_integer':\n return {\n ...metafield,\n parsedValue: Number(metafield.value),\n } as ReturnGeneric;\n\n case 'list.collection_reference':\n case 'list.file_reference':\n case 'list.page_reference':\n case 'list.product_reference':\n case 'list.variant_reference':\n return {\n ...metafield,\n parsedValue: flattenConnection(metafield.references ?? undefined),\n } as ReturnGeneric;\n\n default: {\n const typeNotFoundError = `parseMetafield(): the 'metafield.type' you passed in is not supported. Your type: \"${metafield.type}\". If you believe this is an error, please open an issue on GitHub.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(typeNotFoundError);\n } else {\n console.error(\n `${typeNotFoundError} Returning 'parsedValue' of 'null'`,\n );\n return {\n ...metafield,\n parsedValue: null,\n } as ReturnGeneric;\n }\n }\n }\n}\n\n/**\n * Parses a JSON string while preventing prototype injection attacks.\n */\nexport function parseJSON(json: string): unknown {\n if (String(json).includes('__proto__')) {\n return JSON.parse(json, (k, v) => {\n if (k !== '__proto__') return v as unknown;\n }) as unknown;\n }\n return JSON.parse(json) as unknown;\n}\n\n// taken from https://shopify.dev/apps/metafields/types\nexport const allMetafieldTypesArray = [\n 'boolean',\n 'collection_reference',\n 'color',\n 'date',\n 'date_time',\n 'dimension',\n 'file_reference',\n 'json',\n 'money',\n 'rich_text_field',\n 'multi_line_text_field',\n 'number_decimal',\n 'number_integer',\n 'page_reference',\n 'product_reference',\n 'rating',\n 'single_line_text_field',\n 'url',\n 'variant_reference',\n 'volume',\n 'weight',\n // list metafields\n 'list.collection_reference',\n 'list.color',\n 'list.date',\n 'list.date_time',\n 'list.dimension',\n 'list.file_reference',\n 'list.number_integer',\n 'list.number_decimal',\n 'list.page_reference',\n 'list.product_reference',\n 'list.rating',\n 'list.single_line_text_field',\n 'list.url',\n 'list.variant_reference',\n 'list.volume',\n 'list.weight',\n] as const;\n\n/** A union of all the supported `metafield.type`s */\nexport type MetafieldTypeTypes = (typeof allMetafieldTypesArray)[number];\n\n/**\n * A mapping of a Metafield's `type` to the TypeScript type that is returned from `parseMetafield()`\n * For example, when using `parseMetafield()`, the type will be correctly returned when used like the following:\n *\n * ```\n * const parsedMetafield = parseMetafield<ParsedMetafields['boolean']>(metafield);`\n * ```\n * `parsedMetafield.parsedValue`'s type is now `boolean`\n */\nexport type ParsedMetafields<ExtraTypeGeneric = void> = {\n /** A Metafield that's been parsed, with a `parsedValue` of `boolean` */\n boolean: Simplify<BooleanParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Collection` object (as defined by the Storefront API) */\n collection_reference: Simplify<CollectionParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n color: Simplify<ColorParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Date` */\n date_time: Simplify<DatesParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n dimension: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `GenericFile` object (as defined by the Storefront API) */\n file_reference: Simplify<FileRefParsedMetafield>;\n /**\n * A Metafield that's been parsed, with a `parsedValue` of type `unknown`, unless you pass in the type as a generic. For example:\n *\n * ```\n * ParsedMetafields<MyJsonType>['json']\n * ```\n */\n json: Simplify<JsonParsedMetafield<ExtraTypeGeneric>>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Money` */\n money: Simplify<MoneyParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n multi_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_decimal: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `number` */\n number_integer: Simplify<NumberParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Page` object (as defined by the Storefront API) */\n page_reference: Simplify<PageParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `Product` object (as defined by the Storefront API) */\n product_reference: Simplify<ProductParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Rating` */\n rating: Simplify<RatingParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Rating` */\n rich_text_field: Simplify<RichTextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n single_line_text_field: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `string` */\n url: Simplify<TextParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of a `ProductVariant` object (as defined by the Storefront API) */\n variant_reference: Simplify<VariantParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n volume: Simplify<MeasurementParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of type `Measurement` */\n weight: Simplify<MeasurementParsedMetafield>;\n // list metafields\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Collection` objects (as defined by the Storefront API) */\n 'list.collection_reference': Simplify<CollectionListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.color': Simplify<ColorListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of Date objects */\n 'list.date_time': Simplify<DatesListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement` objects */\n 'list.dimension': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `GenericFile` objects (as defined by the Storefront API) */\n 'list.file_reference': Simplify<FileListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_integer': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of numbers */\n 'list.number_decimal': Simplify<NumberListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Page` objects (as defined by the Storefront API) */\n 'list.page_reference': Simplify<PageListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Product` objects (as defined by the Storefront API) */\n 'list.product_reference': Simplify<ProductListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Rating`s */\n 'list.rating': Simplify<RatingListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.single_line_text_field': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of strings */\n 'list.url': Simplify<TextListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `ProductVariant` objects (as defined by the Storefront API) */\n 'list.variant_reference': Simplify<VariantListParsedRefMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.volume': Simplify<MeasurementListParsedMetafield>;\n /** A Metafield that's been parsed, with a `parsedValue` of an array of `Measurement`s */\n 'list.weight': Simplify<MeasurementListParsedMetafield>;\n};\n\ninterface ParsedBase extends MetafieldBaseType {\n type: MetafieldTypeTypes;\n parsedValue: unknown;\n}\n\ninterface BooleanParsedMetafield extends ParsedBase {\n type: 'boolean';\n parsedValue: boolean | null;\n}\ntype CollectionParsedRefMetafield = MetafieldBaseType & {\n type: 'collection_reference';\n parsedValue: Collection | null;\n};\ntype ColorParsedMetafield = MetafieldBaseType & {\n type: 'color';\n parsedValue: string | null;\n};\ntype DatesParsedMetafield = MetafieldBaseType & {\n type: 'date' | 'date_time';\n parsedValue: Date | null;\n};\n\ntype MeasurementParsedMetafield = MetafieldBaseType & {\n type: 'dimension' | 'weight' | 'volume';\n parsedValue: Measurement | null;\n};\n\ntype FileRefParsedMetafield = MetafieldBaseType & {\n type: 'file_reference';\n parsedValue: GenericFile | null;\n};\n\ntype JsonParsedMetafield<JsonTypeGeneric = void> = MetafieldBaseType & {\n type: 'json';\n parsedValue: JsonTypeGeneric extends void ? unknown : JsonTypeGeneric | null;\n};\n\ntype MoneyParsedMetafield = MetafieldBaseType & {\n type: 'money';\n parsedValue: MoneyV2 | null;\n};\n\ntype TextParsedMetafield = MetafieldBaseType & {\n type: 'single_line_text_field' | 'multi_line_text_field' | 'url';\n parsedValue: string | null;\n};\n\ntype NumberParsedMetafield = MetafieldBaseType & {\n type: 'number_decimal' | 'number_integer';\n parsedValue: number | null;\n};\n\ntype PageParsedRefMetafield = MetafieldBaseType & {\n type: 'page_reference';\n parsedValue: Page | null;\n};\n\ntype ProductParsedRefMetafield = MetafieldBaseType & {\n type: 'product_reference';\n parsedValue: Product | null;\n};\n\ntype RatingParsedMetafield = MetafieldBaseType & {\n type: 'rating';\n parsedValue: Rating | null;\n};\n\ntype RichTextParsedMetafield = MetafieldBaseType & {\n type: 'rich_text_field';\n parsedValue: RichTextRootASTNode | null;\n};\n\ntype VariantParsedRefMetafield = MetafieldBaseType & {\n type: 'variant_reference';\n parsedValue: ProductVariant | null;\n};\n\ntype CollectionListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.collection_reference';\n parsedValue: Array<Collection> | null;\n};\n\ntype ColorListParsedMetafield = MetafieldBaseType & {\n type: 'list.color';\n parsedValue: Array<string> | null;\n};\n\ntype DatesListParsedMetafield = MetafieldBaseType & {\n type: 'list.date' | 'list.date_time';\n parsedValue: Array<Date> | null;\n};\n\ntype MeasurementListParsedMetafield = MetafieldBaseType & {\n type: 'list.dimension' | 'list.weight' | 'list.volume';\n parsedValue: Array<Measurement> | null;\n};\n\ntype FileListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.file_reference';\n parsedValue: Array<GenericFile> | null;\n};\n\ntype TextListParsedMetafield = MetafieldBaseType & {\n type: 'list.single_line_text_field' | 'list.url';\n parsedValue: Array<string> | null;\n};\n\ntype NumberListParsedMetafield = MetafieldBaseType & {\n type: 'list.number_decimal' | 'list.number_integer';\n parsedValue: Array<number> | null;\n};\n\ntype PageListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.page_reference';\n parsedValue: Array<Page> | null;\n};\n\ntype ProductListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.product_reference';\n parsedValue: Array<Product> | null;\n};\n\ntype RatingListParsedMetafield = MetafieldBaseType & {\n type: 'list.rating';\n parsedValue: Array<Rating> | null;\n};\n\ntype VariantListParsedRefMetafield = MetafieldBaseType & {\n type: 'list.variant_reference';\n parsedValue: Array<ProductVariant> | null;\n};\n\nexport type Measurement = {\n unit: string;\n value: number;\n};\n\nexport interface Rating {\n value: number;\n scale_min: number;\n scale_max: number;\n}\n"],"names":[],"mappings":";AAsBO,SAAS,eACd,WACe;AACX,MAAA,CAAC,UAAU,MAAM;AACnB,UAAM,cAAc;AACE;AACd,YAAA,IAAI,MAAM,WAAW;AAAA,IAO7B;AAAA,EACF;AAEA,UAAQ,UAAU,MAAM;AAAA,IACtB,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU,UAAU;AAAA,MAAA;AAAA,IAGrC,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU;AAAA,MAAA;AAAA,IAG3B,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACI,aAAA;AAAA,QACL,GAAG;AAAA,QACH,aAAa,UAAU;AAAA,MAAA;AAAA,IAI3B,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK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;AAAA,EACH;AACO,SAAA,KAAK,MAAM,IAAI;AACxB;"}
|
|
@@ -20,7 +20,7 @@ function createStorefrontClient({
|
|
|
20
20
|
if (storefrontApiVersion !== SFAPI_VERSION) {
|
|
21
21
|
warnOnce(
|
|
22
22
|
`The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.
|
|
23
|
-
You may run into unexpected errors if these versions don't match. Received
|
|
23
|
+
You may run into unexpected errors if these versions don't match. Received version: "${storefrontApiVersion}"; expected version "${SFAPI_VERSION}"`
|
|
24
24
|
);
|
|
25
25
|
}
|
|
26
26
|
if (!privateStorefrontToken && !globalThis.document && !isMockShop(storeDomain)) {
|