@shopify/hydrogen-react 2025.1.0 → 2025.1.2
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/dist/browser-dev/CartCheckoutButton.mjs.map +1 -1
- package/dist/browser-dev/Image.mjs.map +1 -1
- package/dist/browser-dev/ModelViewer.mjs.map +1 -1
- package/dist/browser-dev/analytics-schema-custom-storefront-customer-tracking.mjs +1 -2
- package/dist/browser-dev/analytics-schema-custom-storefront-customer-tracking.mjs.map +1 -1
- package/dist/browser-dev/analytics.mjs +0 -3
- package/dist/browser-dev/analytics.mjs.map +1 -1
- package/dist/browser-dev/cart-hooks.mjs.map +1 -1
- package/dist/browser-dev/flatten-connection.mjs.map +1 -1
- package/dist/browser-dev/getProductOptions.mjs +39 -27
- package/dist/browser-dev/getProductOptions.mjs.map +1 -1
- package/dist/browser-dev/optionValueDecoder.mjs.map +1 -1
- package/dist/browser-dev/packages/hydrogen-react/package.json.mjs +1 -1
- package/dist/browser-dev/useMoney.mjs.map +1 -1
- package/dist/browser-prod/CartCheckoutButton.mjs.map +1 -1
- package/dist/browser-prod/Image.mjs.map +1 -1
- package/dist/browser-prod/ModelViewer.mjs.map +1 -1
- package/dist/browser-prod/analytics-schema-custom-storefront-customer-tracking.mjs +1 -2
- package/dist/browser-prod/analytics-schema-custom-storefront-customer-tracking.mjs.map +1 -1
- package/dist/browser-prod/analytics.mjs +0 -3
- package/dist/browser-prod/analytics.mjs.map +1 -1
- package/dist/browser-prod/cart-hooks.mjs.map +1 -1
- package/dist/browser-prod/flatten-connection.mjs.map +1 -1
- package/dist/browser-prod/getProductOptions.mjs +39 -27
- package/dist/browser-prod/getProductOptions.mjs.map +1 -1
- package/dist/browser-prod/optionValueDecoder.mjs.map +1 -1
- package/dist/browser-prod/packages/hydrogen-react/package.json.mjs +1 -1
- package/dist/browser-prod/useMoney.mjs.map +1 -1
- package/dist/node-dev/CartCheckoutButton.js.map +1 -1
- package/dist/node-dev/CartCheckoutButton.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/ModelViewer.js.map +1 -1
- package/dist/node-dev/ModelViewer.mjs.map +1 -1
- package/dist/node-dev/analytics-schema-custom-storefront-customer-tracking.js +1 -2
- package/dist/node-dev/analytics-schema-custom-storefront-customer-tracking.js.map +1 -1
- package/dist/node-dev/analytics-schema-custom-storefront-customer-tracking.mjs +1 -2
- package/dist/node-dev/analytics-schema-custom-storefront-customer-tracking.mjs.map +1 -1
- package/dist/node-dev/analytics.js +0 -3
- package/dist/node-dev/analytics.js.map +1 -1
- package/dist/node-dev/analytics.mjs +0 -3
- package/dist/node-dev/analytics.mjs.map +1 -1
- package/dist/node-dev/cart-hooks.js.map +1 -1
- package/dist/node-dev/cart-hooks.mjs.map +1 -1
- package/dist/node-dev/flatten-connection.js.map +1 -1
- package/dist/node-dev/flatten-connection.mjs.map +1 -1
- package/dist/node-dev/getProductOptions.js +39 -27
- package/dist/node-dev/getProductOptions.js.map +1 -1
- package/dist/node-dev/getProductOptions.mjs +39 -27
- package/dist/node-dev/getProductOptions.mjs.map +1 -1
- package/dist/node-dev/optionValueDecoder.js.map +1 -1
- package/dist/node-dev/optionValueDecoder.mjs.map +1 -1
- package/dist/node-dev/packages/hydrogen-react/package.json.js +1 -1
- package/dist/node-dev/packages/hydrogen-react/package.json.mjs +1 -1
- package/dist/node-dev/useMoney.js.map +1 -1
- package/dist/node-dev/useMoney.mjs.map +1 -1
- package/dist/node-prod/CartCheckoutButton.js.map +1 -1
- package/dist/node-prod/CartCheckoutButton.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/ModelViewer.js.map +1 -1
- package/dist/node-prod/ModelViewer.mjs.map +1 -1
- package/dist/node-prod/analytics-schema-custom-storefront-customer-tracking.js +1 -2
- package/dist/node-prod/analytics-schema-custom-storefront-customer-tracking.js.map +1 -1
- package/dist/node-prod/analytics-schema-custom-storefront-customer-tracking.mjs +1 -2
- package/dist/node-prod/analytics-schema-custom-storefront-customer-tracking.mjs.map +1 -1
- package/dist/node-prod/analytics.js +0 -3
- package/dist/node-prod/analytics.js.map +1 -1
- package/dist/node-prod/analytics.mjs +0 -3
- package/dist/node-prod/analytics.mjs.map +1 -1
- package/dist/node-prod/cart-hooks.js.map +1 -1
- package/dist/node-prod/cart-hooks.mjs.map +1 -1
- package/dist/node-prod/flatten-connection.js.map +1 -1
- package/dist/node-prod/flatten-connection.mjs.map +1 -1
- package/dist/node-prod/getProductOptions.js +39 -27
- package/dist/node-prod/getProductOptions.js.map +1 -1
- package/dist/node-prod/getProductOptions.mjs +39 -27
- package/dist/node-prod/getProductOptions.mjs.map +1 -1
- package/dist/node-prod/optionValueDecoder.js.map +1 -1
- package/dist/node-prod/optionValueDecoder.mjs.map +1 -1
- package/dist/node-prod/packages/hydrogen-react/package.json.js +1 -1
- package/dist/node-prod/packages/hydrogen-react/package.json.mjs +1 -1
- package/dist/node-prod/useMoney.js.map +1 -1
- package/dist/node-prod/useMoney.mjs.map +1 -1
- package/dist/types/flatten-connection.d.ts +1 -1
- package/dist/umd/hydrogen-react.dev.js +41 -33
- package/dist/umd/hydrogen-react.dev.js.map +1 -1
- package/dist/umd/hydrogen-react.prod.js +7 -7
- package/dist/umd/hydrogen-react.prod.js.map +1 -1
- package/package.json +4 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CartCheckoutButton.mjs","sources":["../../src/CartCheckoutButton.tsx"],"sourcesContent":["import {ReactNode, useEffect, useState} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ntype ChildrenProps = {\n /** A `ReactNode` element. */\n children: ReactNode;\n};\ntype CartCheckoutButtonProps = Omit<BaseButtonProps<'button'>, 'onClick'> &\n ChildrenProps;\n\n/**\n * The `CartCheckoutButton` component renders a button that redirects to the checkout URL for the cart.\n * It must be a descendent of a `CartProvider` component.\n */\nexport function CartCheckoutButton(\n props: CartCheckoutButtonProps,\n): JSX.Element {\n const [requestedCheckout, setRequestedCheckout] = useState(false);\n const {status, checkoutUrl} = useCart();\n const {children, ...passthroughProps} = props;\n\n useEffect(() => {\n if (requestedCheckout && checkoutUrl && status === 'idle') {\n window.location.href = checkoutUrl;\n }\n }, [requestedCheckout, status, checkoutUrl]);\n\n return (\n <BaseButton\n {...passthroughProps}\n disabled={requestedCheckout || passthroughProps.disabled}\n onClick={(): void => setRequestedCheckout(true)}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documentation purposes, and it is not used in the code.\n// we ignore this issue because it makes the documentation look better than the equivalent `type` that it wants us to convert to\n// eslint-disable-next-line @typescript-eslint/no-empty-
|
|
1
|
+
{"version":3,"file":"CartCheckoutButton.mjs","sources":["../../src/CartCheckoutButton.tsx"],"sourcesContent":["import {ReactNode, useEffect, useState} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ntype ChildrenProps = {\n /** A `ReactNode` element. */\n children: ReactNode;\n};\ntype CartCheckoutButtonProps = Omit<BaseButtonProps<'button'>, 'onClick'> &\n ChildrenProps;\n\n/**\n * The `CartCheckoutButton` component renders a button that redirects to the checkout URL for the cart.\n * It must be a descendent of a `CartProvider` component.\n */\nexport function CartCheckoutButton(\n props: CartCheckoutButtonProps,\n): JSX.Element {\n const [requestedCheckout, setRequestedCheckout] = useState(false);\n const {status, checkoutUrl} = useCart();\n const {children, ...passthroughProps} = props;\n\n useEffect(() => {\n if (requestedCheckout && checkoutUrl && status === 'idle') {\n window.location.href = checkoutUrl;\n }\n }, [requestedCheckout, status, checkoutUrl]);\n\n return (\n <BaseButton\n {...passthroughProps}\n disabled={requestedCheckout || passthroughProps.disabled}\n onClick={(): void => setRequestedCheckout(true)}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documentation purposes, and it is not used in the code.\n// we ignore this issue because it makes the documentation look better than the equivalent `type` that it wants us to convert to\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface CartCheckoutButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends Omit<CustomBaseButtonProps<AsType>, 'onClick'> {}\n"],"names":[],"mappings":";;;;AAmBO,SAAS,mBACd,OACa;AACb,QAAM,CAAC,mBAAmB,oBAAoB,IAAI,SAAS,KAAK;AAChE,QAAM,EAAC,QAAQ,YAAW,IAAI,QAAQ;AACtC,QAAM,EAAC,UAAU,GAAG,iBAAA,IAAoB;AAExC,YAAU,MAAM;AACV,QAAA,qBAAqB,eAAe,WAAW,QAAQ;AACzD,aAAO,SAAS,OAAO;AAAA,IACzB;AAAA,EACC,GAAA,CAAC,mBAAmB,QAAQ,WAAW,CAAC;AAGzC,SAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACE,GAAG;AAAA,MACJ,UAAU,qBAAqB,iBAAiB;AAAA,MAChD,SAAS,MAAY,qBAAqB,IAAI;AAAA,MAE7C;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
@@ -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/2025-01/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrogen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loading = 'lazy',\n sizes,\n src,\n srcSetOptions = {\n intervals: 15,\n startingWidth: 200,\n incrementSize: 200,\n placeholderWidth: 100,\n },\n width = '100%',\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n data={data}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n data={data}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> &\n Pick<HydrogenImageBaseProps, 'data'> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n };\n\nconst FixedWidthImage = React.forwardRef<\n HTMLImageElement,\n FixedWidthImageProps\n>(\n (\n {\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n width,\n data,\n },\n ref,\n ) => {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop, {\n width: data?.width ?? undefined,\n height: data?.height ?? undefined,\n });\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [\n aspectRatio,\n crop,\n data,\n height,\n imageWidths,\n loader,\n normalizedProps,\n width,\n ]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fixed.height}\n loading={loading}\n src={fixed.src}\n srcSet={fixed.srcSet}\n width={fixed.width}\n style={{\n aspectRatio: fixed.aspectRatio,\n ...passthroughProps.style,\n }}\n {...passthroughProps}\n />\n );\n },\n);\n\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> &\n Pick<HydrogenImageBaseProps, 'data'> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n };\n\nconst FluidImage = React.forwardRef<HTMLImageElement, FluidImageProps>(\n (\n {\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n sizes,\n data,\n },\n ref,\n ) => {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop, {\n width: data?.width ?? undefined,\n height: data?.height ?? undefined,\n });\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, data, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n },\n);\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nconst PLACEHOLDER_DOMAIN = 'https://placeholder.shopify.com';\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src, PLACEHOLDER_DOMAIN);\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.replace(PLACEHOLDER_DOMAIN, '');\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return typeof width === 'number' || fixedEndings.test(width);\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n sourceDimensions?: {width?: number; height?: number},\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n return imageWidths\n .map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n })\n .filter(({width, height}) => {\n if (sourceDimensions?.width && width > sourceDimensions.width) {\n return false;\n }\n\n if (\n sourceDimensions?.height &&\n height &&\n height > sourceDimensions.height\n ) {\n return false;\n }\n\n return true;\n });\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n"],"names":[],"mappings":";;AA6GO,MAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2CvB,MAAM,QAAQ,MAAM;AAAA,EACzB,CACE;AAAA,IACE;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP;AAAA,IACA,WAAW;AAAA,IACX,SAAS;AAAA,IACT,SAAS;AAAA,IACT,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,MACd,WAAW;AAAA,MACX,eAAe;AAAA,MACf,eAAe;AAAA,MACf,kBAAkB;AAAA,IACpB;AAAA,IACA,QAAQ;AAAA,IACR,GAAG;AAAA,KAEL,QACG;AAIG,UAAA,iBAAiB,MAAM,QAAQ,MAAM;AAEzC,YAAM,aACJ,6BAAM,WAAS,6BAAM,UAAS,6BAAM,QAAQ;AAE9C,YAAM,cACJ,6BAAM,WAAS,6BAAM,UAAS,6BAAM,SAAS;AAExC,aAAA;AAAA,QACL,OAAO;AAAA,QACP,QAAQ;AAAA,QACR,YAAY,QAAQ,WAAW,WAAW,UAAU,CAAC;AAAA,MAAA;AAAA,IACvD,GACC,CAAC,IAAI,CAAC;AAMH,UAAA,kBAAkB,MAAM,QAAQ,MAAM;AAC1C,YAAM,aAA8B,SAAS;AAC7C,YAAM,aAAa,kBAAkB,WAAW,SAAU,CAAA;AAC1D,YAAM,SAAS,GAAG,WAAW,MAAM,GAAG,WAAW,IAAI;AAE/C,YAAA,aAAa,WAAW,UAAa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M,IAAI,YAAY,MAAM,GAAG;AAC7C,SAAO,KAAK,OAAO,KAAK,IAAI,OAAO,MAAM;AAC3C;AAGO,SAAS,cACd,aACA,aACA,OAAa,UACb,kBAOY;AACZ,MAAI,CAAC;AAAa;AACX,SAAA,YACJ,IAAI,CAAC,UAAkB;AACf,WAAA;AAAA,MACL;AAAA,MACA,QAAQ,cACJ,SAAS,iBAAiB,WAAW,KAAK,KAC1C;AAAA,MACJ;AAAA,IAAA;AAAA,EAEH,CAAA,EACA,OAAO,CAAC,EAAC,OAAO,aAAY;AAC3B,SAAI,qDAAkB,UAAS,QAAQ,iBAAiB,OAAO;AACtD,aAAA;AAAA,IACT;AAEA,SACE,qDAAkB,WAClB,UACA,SAAS,iBAAiB,QAC1B;AACO,aAAA;AAAA,IACT;AAEO,WAAA;AAAA,EAAA,CACR;AAQL;"}
|
|
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 */\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/2025-01/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrogen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loading = 'lazy',\n sizes,\n src,\n srcSetOptions = {\n intervals: 15,\n startingWidth: 200,\n incrementSize: 200,\n placeholderWidth: 100,\n },\n width = '100%',\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n data={data}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n data={data}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> &\n Pick<HydrogenImageBaseProps, 'data'> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n };\n\nconst FixedWidthImage = React.forwardRef<\n HTMLImageElement,\n FixedWidthImageProps\n>(\n (\n {\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n width,\n data,\n },\n ref,\n ) => {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop, {\n width: data?.width ?? undefined,\n height: data?.height ?? undefined,\n });\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [\n aspectRatio,\n crop,\n data,\n height,\n imageWidths,\n loader,\n normalizedProps,\n width,\n ]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fixed.height}\n loading={loading}\n src={fixed.src}\n srcSet={fixed.srcSet}\n width={fixed.width}\n style={{\n aspectRatio: fixed.aspectRatio,\n ...passthroughProps.style,\n }}\n {...passthroughProps}\n />\n );\n },\n);\n\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> &\n Pick<HydrogenImageBaseProps, 'data'> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n };\n\nconst FluidImage = React.forwardRef<HTMLImageElement, FluidImageProps>(\n (\n {\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n sizes,\n data,\n },\n ref,\n ) => {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop, {\n width: data?.width ?? undefined,\n height: data?.height ?? undefined,\n });\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, data, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n },\n);\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nconst PLACEHOLDER_DOMAIN = 'https://placeholder.shopify.com';\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src, PLACEHOLDER_DOMAIN);\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.replace(PLACEHOLDER_DOMAIN, '');\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return typeof width === 'number' || fixedEndings.test(width);\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n sourceDimensions?: {width?: number; height?: number},\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n return imageWidths\n .map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n })\n .filter(({width, height}) => {\n if (sourceDimensions?.width && width > sourceDimensions.width) {\n return false;\n }\n\n if (\n sourceDimensions?.height &&\n height &&\n height > sourceDimensions.height\n ) {\n return false;\n }\n\n return true;\n });\n /*\n Given:\n ([100, 200], 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,iBAAiB,WAAW,KAAK,KAC1C;AAAA,MACJ;AAAA,IAAA;AAAA,EAEH,CAAA,EACA,OAAO,CAAC,EAAC,OAAO,aAAY;AAC3B,SAAI,qDAAkB,UAAS,QAAQ,iBAAiB,OAAO;AACtD,aAAA;AAAA,IACT;AAEA,SACE,qDAAkB,WAClB,UACA,SAAS,iBAAiB,QAC1B;AACO,aAAA;AAAA,IACT;AAEO,WAAA;AAAA,EAAA,CACR;AAQL;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ModelViewer.mjs","sources":["../../src/ModelViewer.tsx"],"sourcesContent":["import {useState, useEffect, useCallback} from 'react';\nimport {useLoadScript} from './load-script.js';\nimport type {Model3d} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport type {ModelViewerElement} from '@google/model-viewer/lib/model-viewer.js';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'model-viewer': PartialDeep<\n ModelViewerElement,\n {recurseIntoArrays: true}\n >;\n }\n }\n}\n\ntype ModelViewerProps = Omit<\n PartialDeep<JSX.IntrinsicElements['model-viewer'], {recurseIntoArrays: true}>,\n 'src'\n> &\n ModelViewerBaseProps;\n\ntype ModelViewerBaseProps = {\n /** An object with fields that correspond to the Storefront API's [Model3D object](https://shopify.dev/api/storefront/2025-01/objects/model3d). */\n data: PartialDeep<Model3d, {recurseIntoArrays: true}>;\n /** The callback to invoke when the 'error' event is triggered. Refer to [error in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-error). */\n onError?: (event: Event) => void;\n /** The callback to invoke when the `load` event is triggered. Refer to [load in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-load). */\n onLoad?: (event: Event) => void;\n /** The callback to invoke when the 'preload' event is triggered. Refer to [preload in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-preload). */\n onPreload?: (event: Event) => void;\n /** The callback to invoke when the 'model-visibility' event is triggered. Refer to [model-visibility in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-modelVisibility). */\n onModelVisibility?: (event: Event) => void;\n /** The callback to invoke when the 'progress' event is triggered. Refer to [progress in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-progress). */\n onProgress?: (event: Event) => void;\n /** The callback to invoke when the 'ar-status' event is triggered. Refer to [ar-status in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arStatus). */\n onArStatus?: (event: Event) => void;\n /** The callback to invoke when the 'ar-tracking' event is triggered. Refer to [ar-tracking in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arTracking). */\n onArTracking?: (event: Event) => void;\n /** The callback to invoke when the 'quick-look-button-tapped' event is triggered. Refer to [quick-look-button-tapped in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-quickLookButtonTapped). */\n onQuickLookButtonTapped?: (event: Event) => void;\n /** The callback to invoke when the 'camera-change' event is triggered. Refer to [camera-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-events-cameraChange). */\n onCameraChange?: (event: Event) => void;\n /** The callback to invoke when the 'environment-change' event is triggered. Refer to [environment-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-lightingandenv-events-environmentChange). */\n onEnvironmentChange?: (event: Event) => void;\n /** The callback to invoke when the 'play' event is triggered. Refer to [play in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-play). */\n onPlay?: (event: Event) => void;\n /** The callback to invoke when the 'pause' event is triggered. Refer to [pause in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-pause). */\n onPause?: (event: Event) => void;\n /** The callback to invoke when the 'scene-graph-ready' event is triggered. Refer to [scene-graph-ready in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-scenegraph-events-sceneGraphReady). */\n onSceneGraphReady?: (event: Event) => void;\n};\n\n/**\n * The `ModelViewer` component renders a 3D model (with the `model-viewer` custom element) for\n * the Storefront API's [Model3d object](https://shopify.dev/api/storefront/reference/products/model3d).\n *\n * The `model-viewer` custom element is lazily downloaded through a dynamically-injected `<script type=\"module\">` tag when the `<ModelViewer />` component is rendered\n *\n * ModelViewer is using version `1.21.1` of the `@google/model-viewer` library.\n */\nexport function ModelViewer(props: ModelViewerProps): JSX.Element | null {\n const [modelViewer, setModelViewer] = useState<undefined | HTMLElement>(\n undefined,\n );\n const callbackRef = useCallback((node: HTMLElement) => {\n setModelViewer(node);\n }, []);\n const {data, children, className, ...passthroughProps} = props;\n\n const modelViewerLoadedStatus = useLoadScript(\n 'https://unpkg.com/@google/model-viewer@v1.12.1/dist/model-viewer.min.js',\n {\n module: true,\n },\n );\n\n useEffect(() => {\n const hydrogenEventListener = {\n error: passthroughProps.onError,\n load: passthroughProps.onLoad,\n preload: passthroughProps.onPreload,\n 'model-visibility': passthroughProps.onModelVisibility,\n progress: passthroughProps.onProgress,\n 'ar-status': passthroughProps.onArStatus,\n 'ar-tracking': passthroughProps.onArTracking,\n 'quick-look-button-tapped': passthroughProps.onQuickLookButtonTapped,\n 'camera-change': passthroughProps.onCameraChange,\n 'environment-change': passthroughProps.onEnvironmentChange,\n play: passthroughProps.onPlay,\n pause: passthroughProps.onPause,\n 'scene-graph-ready': passthroughProps.onSceneGraphReady,\n };\n\n if (!modelViewer) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.addEventListener(eventName, callbackFunc);\n }\n },\n );\n\n return () => {\n if (modelViewer == null) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.removeEventListener(eventName, callbackFunc);\n }\n },\n );\n };\n }, [\n modelViewer,\n passthroughProps.onArStatus,\n passthroughProps.onArTracking,\n passthroughProps.onCameraChange,\n passthroughProps.onEnvironmentChange,\n passthroughProps.onError,\n passthroughProps.onLoad,\n passthroughProps.onModelVisibility,\n passthroughProps.onPause,\n passthroughProps.onPlay,\n passthroughProps.onPreload,\n passthroughProps.onProgress,\n passthroughProps.onQuickLookButtonTapped,\n passthroughProps.onSceneGraphReady,\n ]);\n\n if (modelViewerLoadedStatus !== 'done') {\n // TODO: What do we want to display while the model-viewer library loads?\n return null;\n }\n\n if (!data.sources?.[0]?.url) {\n const sourcesUrlError = `<ModelViewer/> requires 'data.sources' prop to be an array, with an object that has a property 'url' on it. Rendering 'null'`;\n if (__HYDROGEN_DEV__) {\n throw new Error(sourcesUrlError);\n } else {\n console.error(sourcesUrlError);\n return null;\n }\n }\n\n if (__HYDROGEN_DEV__ && !data.alt) {\n console.warn(\n `<ModelViewer/> requires the 'data.alt' prop for accessibility`,\n );\n }\n\n return (\n <model-viewer\n ref={callbackRef}\n {...passthroughProps}\n // @ts-expect-error src should exist\n // @eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n class={className}\n id={passthroughProps.id ?? data.id}\n src={data.sources[0].url}\n alt={data.alt ?? null}\n camera-controls={passthroughProps.cameraControls ?? true}\n poster={(passthroughProps.poster || data.previewImage?.url) ?? null}\n autoplay={passthroughProps.autoplay ?? true}\n loading={passthroughProps.loading}\n reveal={passthroughProps.reveal}\n ar={passthroughProps.ar}\n ar-modes={passthroughProps.arModes}\n ar-scale={passthroughProps.arScale}\n // @ts-expect-error arPlacement should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-attributes-arPlacement\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n ar-placement={passthroughProps.arPlacement}\n ios-src={passthroughProps.iosSrc}\n touch-action={passthroughProps.touchAction}\n disable-zoom={passthroughProps.disableZoom}\n orbit-sensitivity={passthroughProps.orbitSensitivity}\n auto-rotate={passthroughProps.autoRotate}\n auto-rotate-delay={passthroughProps.autoRotateDelay}\n // @ts-expect-error rotationPerSecond should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-attributes-rotationPerSecond\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n rotation-per-second={passthroughProps.rotationPerSecond}\n interaction-policy={passthroughProps.interactionPolicy}\n interaction-prompt={passthroughProps.interactionPrompt}\n interaction-prompt-style={passthroughProps.interactionPromptStyle}\n interaction-prompt-threshold={passthroughProps.interactionPromptThreshold}\n camera-orbit={passthroughProps.cameraOrbit}\n camera-target={passthroughProps.cameraTarget}\n field-of-view={passthroughProps.fieldOfView}\n max-camera-orbit={passthroughProps.maxCameraOrbit}\n min-camera-orbit={passthroughProps.minCameraOrbit}\n max-field-of-view={passthroughProps.maxFieldOfView}\n min-field-of-view={passthroughProps.minFieldOfView}\n bounds={passthroughProps.bounds}\n interpolation-decay={passthroughProps.interpolationDecay ?? 100}\n skybox-image={passthroughProps.skyboxImage}\n environment-image={passthroughProps.environmentImage}\n exposure={passthroughProps.exposure}\n shadow-intensity={passthroughProps.shadowIntensity ?? 0}\n shadow-softness={passthroughProps.shadowSoftness ?? 0}\n animation-name={passthroughProps.animationName}\n animation-crossfade-duration={passthroughProps.animationCrossfadeDuration}\n variant-name={passthroughProps.variantName}\n orientation={passthroughProps.orientation}\n scale={passthroughProps.scale}\n >\n {children}\n </model-viewer>\n );\n}\n"],"names":[],"mappings":";;;AA+DO,SAAS,YAAY,OAA6C;;AACjE,QAAA,CAAC,aAAa,cAAc,IAAI;AAAA,IACpC;AAAA,EAAA;AAEI,QAAA,cAAc,YAAY,CAAC,SAAsB;AACrD,mBAAe,IAAI;AAAA,EACrB,GAAG,CAAE,CAAA;AACL,QAAM,EAAC,MAAM,UAAU,WAAW,GAAG,iBAAoB,IAAA;AAEzD,QAAM,0BAA0B;AAAA,IAC9B;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,IACV;AAAA,EAAA;AAGF,YAAU,MAAM;AACd,UAAM,wBAAwB;AAA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B;AAAA,MAC5D,gBAAc,iBAAiB;AAAA,MAC/B,qBAAmB,iBAAiB;AAAA,MACpC,UAAU,iBAAiB;AAAA,MAC3B,oBAAkB,iBAAiB,mBAAmB;AAAA,MACtD,mBAAiB,iBAAiB,kBAAkB;AAAA,MACpD,kBAAgB,iBAAiB;AAAA,MACjC,gCAA8B,iBAAiB;AAAA,MAC/C,gBAAc,iBAAiB;AAAA,MAC/B,aAAa,iBAAiB;AAAA,MAC9B,OAAO,iBAAiB;AAAA,MAEvB;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
1
|
+
{"version":3,"file":"ModelViewer.mjs","sources":["../../src/ModelViewer.tsx"],"sourcesContent":["import {useState, useEffect, useCallback} from 'react';\nimport {useLoadScript} from './load-script.js';\nimport type {Model3d} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport type {ModelViewerElement} from '@google/model-viewer/lib/model-viewer.js';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'model-viewer': PartialDeep<\n ModelViewerElement,\n {recurseIntoArrays: true}\n >;\n }\n }\n}\n\ntype ModelViewerProps = Omit<\n PartialDeep<JSX.IntrinsicElements['model-viewer'], {recurseIntoArrays: true}>,\n 'src'\n> &\n ModelViewerBaseProps;\n\ntype ModelViewerBaseProps = {\n /** An object with fields that correspond to the Storefront API's [Model3D object](https://shopify.dev/api/storefront/2025-01/objects/model3d). */\n data: PartialDeep<Model3d, {recurseIntoArrays: true}>;\n /** The callback to invoke when the 'error' event is triggered. Refer to [error in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-error). */\n onError?: (event: Event) => void;\n /** The callback to invoke when the `load` event is triggered. Refer to [load in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-load). */\n onLoad?: (event: Event) => void;\n /** The callback to invoke when the 'preload' event is triggered. Refer to [preload in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-preload). */\n onPreload?: (event: Event) => void;\n /** The callback to invoke when the 'model-visibility' event is triggered. Refer to [model-visibility in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-modelVisibility). */\n onModelVisibility?: (event: Event) => void;\n /** The callback to invoke when the 'progress' event is triggered. Refer to [progress in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-progress). */\n onProgress?: (event: Event) => void;\n /** The callback to invoke when the 'ar-status' event is triggered. Refer to [ar-status in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arStatus). */\n onArStatus?: (event: Event) => void;\n /** The callback to invoke when the 'ar-tracking' event is triggered. Refer to [ar-tracking in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arTracking). */\n onArTracking?: (event: Event) => void;\n /** The callback to invoke when the 'quick-look-button-tapped' event is triggered. Refer to [quick-look-button-tapped in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-quickLookButtonTapped). */\n onQuickLookButtonTapped?: (event: Event) => void;\n /** The callback to invoke when the 'camera-change' event is triggered. Refer to [camera-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-events-cameraChange). */\n onCameraChange?: (event: Event) => void;\n /** The callback to invoke when the 'environment-change' event is triggered. Refer to [environment-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-lightingandenv-events-environmentChange). */\n onEnvironmentChange?: (event: Event) => void;\n /** The callback to invoke when the 'play' event is triggered. Refer to [play in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-play). */\n onPlay?: (event: Event) => void;\n /** The callback to invoke when the 'pause' event is triggered. Refer to [pause in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-pause). */\n onPause?: (event: Event) => void;\n /** The callback to invoke when the 'scene-graph-ready' event is triggered. Refer to [scene-graph-ready in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-scenegraph-events-sceneGraphReady). */\n onSceneGraphReady?: (event: Event) => void;\n};\n\n/**\n * The `ModelViewer` component renders a 3D model (with the `model-viewer` custom element) for\n * the Storefront API's [Model3d object](https://shopify.dev/api/storefront/reference/products/model3d).\n *\n * The `model-viewer` custom element is lazily downloaded through a dynamically-injected `<script type=\"module\">` tag when the `<ModelViewer />` component is rendered\n *\n * ModelViewer is using version `1.21.1` of the `@google/model-viewer` library.\n */\nexport function ModelViewer(props: ModelViewerProps): JSX.Element | null {\n const [modelViewer, setModelViewer] = useState<undefined | HTMLElement>(\n undefined,\n );\n const callbackRef = useCallback((node: HTMLElement) => {\n setModelViewer(node);\n }, []);\n const {data, children, className, ...passthroughProps} = props;\n\n const modelViewerLoadedStatus = useLoadScript(\n 'https://unpkg.com/@google/model-viewer@v1.12.1/dist/model-viewer.min.js',\n {\n module: true,\n },\n );\n\n useEffect(() => {\n const hydrogenEventListener = {\n error: passthroughProps.onError,\n load: passthroughProps.onLoad,\n preload: passthroughProps.onPreload,\n 'model-visibility': passthroughProps.onModelVisibility,\n progress: passthroughProps.onProgress,\n 'ar-status': passthroughProps.onArStatus,\n 'ar-tracking': passthroughProps.onArTracking,\n 'quick-look-button-tapped': passthroughProps.onQuickLookButtonTapped,\n 'camera-change': passthroughProps.onCameraChange,\n 'environment-change': passthroughProps.onEnvironmentChange,\n play: passthroughProps.onPlay,\n pause: passthroughProps.onPause,\n 'scene-graph-ready': passthroughProps.onSceneGraphReady,\n };\n\n if (!modelViewer) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.addEventListener(eventName, callbackFunc);\n }\n },\n );\n\n return (): void => {\n if (modelViewer == null) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.removeEventListener(eventName, callbackFunc);\n }\n },\n );\n };\n }, [\n modelViewer,\n passthroughProps.onArStatus,\n passthroughProps.onArTracking,\n passthroughProps.onCameraChange,\n passthroughProps.onEnvironmentChange,\n passthroughProps.onError,\n passthroughProps.onLoad,\n passthroughProps.onModelVisibility,\n passthroughProps.onPause,\n passthroughProps.onPlay,\n passthroughProps.onPreload,\n passthroughProps.onProgress,\n passthroughProps.onQuickLookButtonTapped,\n passthroughProps.onSceneGraphReady,\n ]);\n\n if (modelViewerLoadedStatus !== 'done') {\n // TODO: What do we want to display while the model-viewer library loads?\n return null;\n }\n\n if (!data.sources?.[0]?.url) {\n const sourcesUrlError = `<ModelViewer/> requires 'data.sources' prop to be an array, with an object that has a property 'url' on it. Rendering 'null'`;\n if (__HYDROGEN_DEV__) {\n throw new Error(sourcesUrlError);\n } else {\n console.error(sourcesUrlError);\n return null;\n }\n }\n\n if (__HYDROGEN_DEV__ && !data.alt) {\n console.warn(\n `<ModelViewer/> requires the 'data.alt' prop for accessibility`,\n );\n }\n\n return (\n <model-viewer\n ref={callbackRef}\n {...passthroughProps}\n // @ts-expect-error src should exist\n // @eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n class={className}\n id={passthroughProps.id ?? data.id}\n src={data.sources[0].url}\n alt={data.alt ?? null}\n camera-controls={passthroughProps.cameraControls ?? true}\n poster={(passthroughProps.poster || data.previewImage?.url) ?? null}\n autoplay={passthroughProps.autoplay ?? true}\n loading={passthroughProps.loading}\n reveal={passthroughProps.reveal}\n ar={passthroughProps.ar}\n ar-modes={passthroughProps.arModes}\n ar-scale={passthroughProps.arScale}\n // @ts-expect-error arPlacement should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-attributes-arPlacement\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n ar-placement={passthroughProps.arPlacement}\n ios-src={passthroughProps.iosSrc}\n touch-action={passthroughProps.touchAction}\n disable-zoom={passthroughProps.disableZoom}\n orbit-sensitivity={passthroughProps.orbitSensitivity}\n auto-rotate={passthroughProps.autoRotate}\n auto-rotate-delay={passthroughProps.autoRotateDelay}\n // @ts-expect-error rotationPerSecond should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-attributes-rotationPerSecond\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n rotation-per-second={passthroughProps.rotationPerSecond}\n interaction-policy={passthroughProps.interactionPolicy}\n interaction-prompt={passthroughProps.interactionPrompt}\n interaction-prompt-style={passthroughProps.interactionPromptStyle}\n interaction-prompt-threshold={passthroughProps.interactionPromptThreshold}\n camera-orbit={passthroughProps.cameraOrbit}\n camera-target={passthroughProps.cameraTarget}\n field-of-view={passthroughProps.fieldOfView}\n max-camera-orbit={passthroughProps.maxCameraOrbit}\n min-camera-orbit={passthroughProps.minCameraOrbit}\n max-field-of-view={passthroughProps.maxFieldOfView}\n min-field-of-view={passthroughProps.minFieldOfView}\n bounds={passthroughProps.bounds}\n interpolation-decay={passthroughProps.interpolationDecay ?? 100}\n skybox-image={passthroughProps.skyboxImage}\n environment-image={passthroughProps.environmentImage}\n exposure={passthroughProps.exposure}\n shadow-intensity={passthroughProps.shadowIntensity ?? 0}\n shadow-softness={passthroughProps.shadowSoftness ?? 0}\n animation-name={passthroughProps.animationName}\n animation-crossfade-duration={passthroughProps.animationCrossfadeDuration}\n variant-name={passthroughProps.variantName}\n orientation={passthroughProps.orientation}\n scale={passthroughProps.scale}\n >\n {children}\n </model-viewer>\n );\n}\n"],"names":[],"mappings":";;;AA+DO,SAAS,YAAY,OAA6C;;AACjE,QAAA,CAAC,aAAa,cAAc,IAAI;AAAA,IACpC;AAAA,EAAA;AAEI,QAAA,cAAc,YAAY,CAAC,SAAsB;AACrD,mBAAe,IAAI;AAAA,EACrB,GAAG,CAAE,CAAA;AACL,QAAM,EAAC,MAAM,UAAU,WAAW,GAAG,iBAAoB,IAAA;AAEzD,QAAM,0BAA0B;AAAA,IAC9B;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,IACV;AAAA,EAA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,iBAAiB;AAAA,MACzB,uBAAqB,iBAAiB,sBAAsB;AAAA,MAC5D,gBAAc,iBAAiB;AAAA,MAC/B,qBAAmB,iBAAiB;AAAA,MACpC,UAAU,iBAAiB;AAAA,MAC3B,oBAAkB,iBAAiB,mBAAmB;AAAA,MACtD,mBAAiB,iBAAiB,kBAAkB;AAAA,MACpD,kBAAgB,iBAAiB;AAAA,MACjC,gCAA8B,iBAAiB;AAAA,MAC/C,gBAAc,iBAAiB;AAAA,MAC/B,aAAa,iBAAiB;AAAA,MAC9B,OAAO,iBAAiB;AAAA,MAEvB;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
@@ -156,7 +156,6 @@ function searchView(payload) {
|
|
|
156
156
|
function addToCart(payload) {
|
|
157
157
|
const addToCartPayload = payload;
|
|
158
158
|
const cartToken = parseGid(addToCartPayload.cartId);
|
|
159
|
-
const cart_token = (cartToken == null ? void 0 : cartToken.id) ? `${cartToken.id}` : null;
|
|
160
159
|
return [
|
|
161
160
|
schemaWrapper(
|
|
162
161
|
SCHEMA_ID,
|
|
@@ -164,7 +163,7 @@ function addToCart(payload) {
|
|
|
164
163
|
{
|
|
165
164
|
event_name: PRODUCT_ADDED_TO_CART_EVENT_NAME,
|
|
166
165
|
customerId: addToCartPayload.customerId,
|
|
167
|
-
cart_token,
|
|
166
|
+
cart_token: (cartToken == null ? void 0 : cartToken.id) ? `${cartToken.id}` : null,
|
|
168
167
|
total_value: addToCartPayload.totalValue,
|
|
169
168
|
products: formatProductPayload(addToCartPayload.products),
|
|
170
169
|
customer_id: parseInt(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics-schema-custom-storefront-customer-tracking.mjs","sources":["../../src/analytics-schema-custom-storefront-customer-tracking.ts"],"sourcesContent":["import {\n ShopifyAnalyticsPayload,\n ShopifyPageViewPayload,\n ShopifyAddToCartPayload,\n ShopifyMonorailPayload,\n ShopifyAnalyticsProduct,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {AnalyticsPageType, ShopifySalesChannel} from './analytics-constants.js';\nimport {addDataIf, schemaWrapper, parseGid} from './analytics-utils.js';\nimport {buildUUID} from './cookies-utils.js';\nimport {version} from '../package.json';\n\nconst SCHEMA_ID = 'custom_storefront_customer_tracking/1.2';\nconst PAGE_RENDERED_EVENT_NAME = 'page_rendered';\nconst COLLECTION_PAGE_RENDERED_EVENT_NAME = 'collection_page_rendered';\nconst PRODUCT_PAGE_RENDERED_EVENT_NAME = 'product_page_rendered';\nconst PRODUCT_ADDED_TO_CART_EVENT_NAME = 'product_added_to_cart';\nconst SEARCH_SUBMITTED_EVENT_NAME = 'search_submitted';\n\nfunction prepareAdditionalPayload(\n payload: ShopifyPageViewPayload,\n): Pick<ShopifyMonorailPayload, 'canonical_url' | 'customer_id'> {\n return {\n canonical_url: payload.canonicalUrl || payload.url,\n customer_id: parseInt(parseGid(payload.customerId).id || '0'),\n };\n}\n\n// Send the page view event to the Monorail server.\n// It also sends additional page view events based on the page type.\nexport function pageView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = prepareAdditionalPayload(pageViewPayload);\n\n const pageType = pageViewPayload.pageType;\n const pageViewEvents = [];\n\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n\n switch (pageType) {\n case AnalyticsPageType.collection:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: COLLECTION_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n collection_name: pageViewPayload.collectionHandle,\n collection_id: parseInt(\n parseGid(pageViewPayload.collectionId).id,\n ),\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n case AnalyticsPageType.product:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PRODUCT_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n products: formatProductPayload(pageViewPayload.products),\n total_value: pageViewPayload.totalValue,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n case AnalyticsPageType.search:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: SEARCH_SUBMITTED_EVENT_NAME,\n ...additionalPayload,\n search_string: pageViewPayload.searchString,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n }\n\n return pageViewEvents;\n}\n\n// Sends page view event to the Monorail server.\nexport function pageView2(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = prepareAdditionalPayload(pageViewPayload);\n\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n ];\n}\n\n// Sends collection view event to the Monorail server.\nexport function collectionView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = prepareAdditionalPayload(pageViewPayload);\n\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: COLLECTION_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n collection_name: pageViewPayload.collectionHandle,\n collection_id: parseInt(parseGid(pageViewPayload.collectionId).id),\n },\n formatPayload(pageViewPayload),\n ),\n ),\n ];\n}\n\n// Sends product view event to the Monorail server.\nexport function productView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = prepareAdditionalPayload(pageViewPayload);\n\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PRODUCT_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n products: formatProductPayload(pageViewPayload.products),\n total_value: pageViewPayload.totalValue,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n ];\n}\n\n// Sends search view event to the Monorail server.\nexport function searchView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = prepareAdditionalPayload(pageViewPayload);\n\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: SEARCH_SUBMITTED_EVENT_NAME,\n ...additionalPayload,\n search_string: pageViewPayload.searchString,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n ];\n}\n\nexport function addToCart(\n payload: ShopifyAddToCartPayload,\n): ShopifyMonorailEvent[] {\n const addToCartPayload = payload;\n const cartToken = parseGid(addToCartPayload.cartId);\n const cart_token = cartToken?.id ? `${cartToken.id}` : null;\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PRODUCT_ADDED_TO_CART_EVENT_NAME,\n customerId: addToCartPayload.customerId,\n cart_token,\n total_value: addToCartPayload.totalValue,\n products: formatProductPayload(addToCartPayload.products),\n customer_id: parseInt(\n parseGid(addToCartPayload.customerId).id || '0',\n ),\n },\n formatPayload(addToCartPayload),\n ),\n ),\n ];\n}\n\nfunction formatPayload(\n payload: ShopifyAnalyticsPayload,\n): ShopifyMonorailPayload {\n return {\n source: payload.shopifySalesChannel || ShopifySalesChannel.headless,\n asset_version_id: payload.assetVersionId || version,\n hydrogenSubchannelId:\n payload.storefrontId || payload.hydrogenSubchannelId || '0',\n\n is_persistent_cookie: payload.hasUserConsent,\n deprecated_visit_token: payload.visitToken,\n unique_token: payload.uniqueToken,\n event_time: Date.now(),\n event_id: buildUUID(),\n\n event_source_url: payload.url,\n referrer: payload.referrer,\n user_agent: payload.userAgent,\n navigation_type: payload.navigationType,\n navigation_api: payload.navigationApi,\n\n shop_id: parseInt(parseGid(payload.shopId).id),\n currency: payload.currency,\n\n ccpa_enforced: payload.ccpaEnforced || false,\n gdpr_enforced: payload.gdprEnforced || false,\n gdpr_enforced_as_string: payload.gdprEnforced ? 'true' : 'false',\n analytics_allowed: payload.analyticsAllowed || false,\n marketing_allowed: payload.marketingAllowed || false,\n sale_of_data_allowed: payload.saleOfDataAllowed || false,\n };\n}\n\nfunction formatProductPayload(products?: ShopifyAnalyticsProduct[]): string[] {\n return products\n ? products.map((p: ShopifyAnalyticsProduct) => {\n const product = addDataIf(\n {\n variant_gid: p.variantGid,\n category: p.category,\n sku: p.sku,\n product_id: parseInt(parseGid(p.productGid).id),\n variant_id: parseInt(parseGid(p.variantGid).id),\n },\n {\n product_gid: p.productGid,\n name: p.name,\n variant: p.variantName || '',\n brand: p.brand,\n price: parseFloat(p.price),\n quantity: Number(p.quantity || 0),\n },\n );\n return JSON.stringify(product);\n })\n : [];\n}\n"],"names":[],"mappings":";;;;AAaA,MAAM,YAAY;AAClB,MAAM,2BAA2B;AACjC,MAAM,sCAAsC;AAC5C,MAAM,mCAAmC;AACzC,MAAM,mCAAmC;AACzC,MAAM,8BAA8B;AAEpC,SAAS,yBACP,SAC+D;AACxD,SAAA;AAAA,IACL,eAAe,QAAQ,gBAAgB,QAAQ;AAAA,IAC/C,aAAa,SAAS,SAAS,QAAQ,UAAU,EAAE,MAAM,GAAG;AAAA,EAAA;AAEhE;AAIO,SAAS,SACd,SACwB;AACxB,QAAM,kBAAkB;AAClB,QAAA,oBAAoB,yBAAyB,eAAe;AAElE,QAAM,WAAW,gBAAgB;AACjC,QAAM,iBAAiB,CAAA;AAER,iBAAA;AAAA,IACb;AAAA,MACE;AAAA,MACA;AAAA,QACE;AAAA,UACE,YAAY;AAAA,UACZ,GAAG;AAAA,QACL;AAAA,QACA,cAAc,eAAe;AAAA,MAC/B;AAAA,IACF;AAAA,EAAA;AAGF,UAAQ,UAAU;AAAA,IAChB,KAAK,kBAAkB;AACN,qBAAA;AAAA,QACb;AAAA,UACE;AAAA,UACA;AAAA,YACE;AAAA,cACE,YAAY;AAAA,cACZ,GAAG;AAAA,cACH,iBAAiB,gBAAgB;AAAA,cACjC,eAAe;AAAA,gBACb,SA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,wBAAwB,QAAQ;AAAA,IAChC,cAAc,QAAQ;AAAA,IACtB,YAAY,KAAK,IAAI;AAAA,IACrB,UAAU,UAAU;AAAA,IAEpB,kBAAkB,QAAQ;AAAA,IAC1B,UAAU,QAAQ;AAAA,IAClB,YAAY,QAAQ;AAAA,IACpB,iBAAiB,QAAQ;AAAA,IACzB,gBAAgB,QAAQ;AAAA,IAExB,SAAS,SAAS,SAAS,QAAQ,MAAM,EAAE,EAAE;AAAA,IAC7C,UAAU,QAAQ;AAAA,IAElB,eAAe,QAAQ,gBAAgB;AAAA,IACvC,eAAe,QAAQ,gBAAgB;AAAA,IACvC,yBAAyB,QAAQ,eAAe,SAAS;AAAA,IACzD,mBAAmB,QAAQ,oBAAoB;AAAA,IAC/C,mBAAmB,QAAQ,oBAAoB;AAAA,IAC/C,sBAAsB,QAAQ,qBAAqB;AAAA,EAAA;AAEvD;AAEA,SAAS,qBAAqB,UAAgD;AAC5E,SAAO,WACH,SAAS,IAAI,CAAC,MAA+B;AAC3C,UAAM,UAAU;AAAA,MACd;AAAA,QACE,aAAa,EAAE;AAAA,QACf,UAAU,EAAE;AAAA,QACZ,KAAK,EAAE;AAAA,QACP,YAAY,SAAS,SAAS,EAAE,UAAU,EAAE,EAAE;AAAA,QAC9C,YAAY,SAAS,SAAS,EAAE,UAAU,EAAE,EAAE;AAAA,MAChD;AAAA,MACA;AAAA,QACE,aAAa,EAAE;AAAA,QACf,MAAM,EAAE;AAAA,QACR,SAAS,EAAE,eAAe;AAAA,QAC1B,OAAO,EAAE;AAAA,QACT,OAAO,WAAW,EAAE,KAAK;AAAA,QACzB,UAAU,OAAO,EAAE,YAAY,CAAC;AAAA,MAClC;AAAA,IAAA;AAEK,WAAA,KAAK,UAAU,OAAO;AAAA,EAC9B,CAAA,IACD,CAAA;AACN;"}
|
|
1
|
+
{"version":3,"file":"analytics-schema-custom-storefront-customer-tracking.mjs","sources":["../../src/analytics-schema-custom-storefront-customer-tracking.ts"],"sourcesContent":["import {\n ShopifyAnalyticsPayload,\n ShopifyPageViewPayload,\n ShopifyAddToCartPayload,\n ShopifyMonorailPayload,\n ShopifyAnalyticsProduct,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {AnalyticsPageType, ShopifySalesChannel} from './analytics-constants.js';\nimport {addDataIf, schemaWrapper, parseGid} from './analytics-utils.js';\nimport {buildUUID} from './cookies-utils.js';\nimport {version} from '../package.json';\n\nconst SCHEMA_ID = 'custom_storefront_customer_tracking/1.2';\nconst PAGE_RENDERED_EVENT_NAME = 'page_rendered';\nconst COLLECTION_PAGE_RENDERED_EVENT_NAME = 'collection_page_rendered';\nconst PRODUCT_PAGE_RENDERED_EVENT_NAME = 'product_page_rendered';\nconst PRODUCT_ADDED_TO_CART_EVENT_NAME = 'product_added_to_cart';\nconst SEARCH_SUBMITTED_EVENT_NAME = 'search_submitted';\n\nfunction prepareAdditionalPayload(\n payload: ShopifyPageViewPayload,\n): Pick<ShopifyMonorailPayload, 'canonical_url' | 'customer_id'> {\n return {\n canonical_url: payload.canonicalUrl || payload.url,\n customer_id: parseInt(parseGid(payload.customerId).id || '0'),\n };\n}\n\n// Send the page view event to the Monorail server.\n// It also sends additional page view events based on the page type.\nexport function pageView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = prepareAdditionalPayload(pageViewPayload);\n\n const pageType = pageViewPayload.pageType;\n const pageViewEvents = [];\n\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n\n switch (pageType) {\n case AnalyticsPageType.collection:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: COLLECTION_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n collection_name: pageViewPayload.collectionHandle,\n collection_id: parseInt(\n parseGid(pageViewPayload.collectionId).id,\n ),\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n case AnalyticsPageType.product:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PRODUCT_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n products: formatProductPayload(pageViewPayload.products),\n total_value: pageViewPayload.totalValue,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n case AnalyticsPageType.search:\n pageViewEvents.push(\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: SEARCH_SUBMITTED_EVENT_NAME,\n ...additionalPayload,\n search_string: pageViewPayload.searchString,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n );\n break;\n }\n\n return pageViewEvents;\n}\n\n// Sends page view event to the Monorail server.\nexport function pageView2(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = prepareAdditionalPayload(pageViewPayload);\n\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n ];\n}\n\n// Sends collection view event to the Monorail server.\nexport function collectionView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = prepareAdditionalPayload(pageViewPayload);\n\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: COLLECTION_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n collection_name: pageViewPayload.collectionHandle,\n collection_id: parseInt(parseGid(pageViewPayload.collectionId).id),\n },\n formatPayload(pageViewPayload),\n ),\n ),\n ];\n}\n\n// Sends product view event to the Monorail server.\nexport function productView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = prepareAdditionalPayload(pageViewPayload);\n\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PRODUCT_PAGE_RENDERED_EVENT_NAME,\n ...additionalPayload,\n products: formatProductPayload(pageViewPayload.products),\n total_value: pageViewPayload.totalValue,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n ];\n}\n\n// Sends search view event to the Monorail server.\nexport function searchView(\n payload: ShopifyPageViewPayload,\n): ShopifyMonorailEvent[] {\n const pageViewPayload = payload;\n const additionalPayload = prepareAdditionalPayload(pageViewPayload);\n\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: SEARCH_SUBMITTED_EVENT_NAME,\n ...additionalPayload,\n search_string: pageViewPayload.searchString,\n },\n formatPayload(pageViewPayload),\n ),\n ),\n ];\n}\n\nexport function addToCart(\n payload: ShopifyAddToCartPayload,\n): ShopifyMonorailEvent[] {\n const addToCartPayload = payload;\n const cartToken = parseGid(addToCartPayload.cartId);\n return [\n schemaWrapper(\n SCHEMA_ID,\n addDataIf(\n {\n event_name: PRODUCT_ADDED_TO_CART_EVENT_NAME,\n customerId: addToCartPayload.customerId,\n cart_token: cartToken?.id ? `${cartToken.id}` : null,\n total_value: addToCartPayload.totalValue,\n products: formatProductPayload(addToCartPayload.products),\n customer_id: parseInt(\n parseGid(addToCartPayload.customerId).id || '0',\n ),\n },\n formatPayload(addToCartPayload),\n ),\n ),\n ];\n}\n\nfunction formatPayload(\n payload: ShopifyAnalyticsPayload,\n): ShopifyMonorailPayload {\n return {\n source: payload.shopifySalesChannel || ShopifySalesChannel.headless,\n asset_version_id: payload.assetVersionId || version,\n hydrogenSubchannelId:\n payload.storefrontId || payload.hydrogenSubchannelId || '0',\n\n is_persistent_cookie: payload.hasUserConsent,\n deprecated_visit_token: payload.visitToken,\n unique_token: payload.uniqueToken,\n event_time: Date.now(),\n event_id: buildUUID(),\n\n event_source_url: payload.url,\n referrer: payload.referrer,\n user_agent: payload.userAgent,\n navigation_type: payload.navigationType,\n navigation_api: payload.navigationApi,\n\n shop_id: parseInt(parseGid(payload.shopId).id),\n currency: payload.currency,\n\n ccpa_enforced: payload.ccpaEnforced || false,\n gdpr_enforced: payload.gdprEnforced || false,\n gdpr_enforced_as_string: payload.gdprEnforced ? 'true' : 'false',\n analytics_allowed: payload.analyticsAllowed || false,\n marketing_allowed: payload.marketingAllowed || false,\n sale_of_data_allowed: payload.saleOfDataAllowed || false,\n };\n}\n\nfunction formatProductPayload(products?: ShopifyAnalyticsProduct[]): string[] {\n return products\n ? products.map((p: ShopifyAnalyticsProduct) => {\n const product = addDataIf(\n {\n variant_gid: p.variantGid,\n category: p.category,\n sku: p.sku,\n product_id: parseInt(parseGid(p.productGid).id),\n variant_id: parseInt(parseGid(p.variantGid).id),\n },\n {\n product_gid: p.productGid,\n name: p.name,\n variant: p.variantName || '',\n brand: p.brand,\n price: parseFloat(p.price),\n quantity: Number(p.quantity || 0),\n },\n );\n return JSON.stringify(product);\n })\n : [];\n}\n"],"names":[],"mappings":";;;;AAaA,MAAM,YAAY;AAClB,MAAM,2BAA2B;AACjC,MAAM,sCAAsC;AAC5C,MAAM,mCAAmC;AACzC,MAAM,mCAAmC;AACzC,MAAM,8BAA8B;AAEpC,SAAS,yBACP,SAC+D;AACxD,SAAA;AAAA,IACL,eAAe,QAAQ,gBAAgB,QAAQ;AAAA,IAC/C,aAAa,SAAS,SAAS,QAAQ,UAAU,EAAE,MAAM,GAAG;AAAA,EAAA;AAEhE;AAIO,SAAS,SACd,SACwB;AACxB,QAAM,kBAAkB;AAClB,QAAA,oBAAoB,yBAAyB,eAAe;AAElE,QAAM,WAAW,gBAAgB;AACjC,QAAM,iBAAiB,CAAA;AAER,iBAAA;AAAA,IACb;AAAA,MACE;AAAA,MACA;AAAA,QACE;AAAA,UACE,YAAY;AAAA,UACZ,GAAG;AAAA,QACL;AAAA,QACA,cAAc,eAAe;AAAA,MAC/B;AAAA,IACF;AAAA,EAAA;AAGF,UAAQ,UAAU;AAAA,IAChB,KAAK,kBAAkB;AACN,qBAAA;AAAA,QACb;AAAA,UAC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|
|
@@ -139,13 +139,10 @@ function getNavigationTypeLegacy() {
|
|
|
139
139
|
switch (rawType) {
|
|
140
140
|
case PerformanceNavigation.TYPE_NAVIGATE:
|
|
141
141
|
return "navigate";
|
|
142
|
-
break;
|
|
143
142
|
case PerformanceNavigation.TYPE_RELOAD:
|
|
144
143
|
return "reload";
|
|
145
|
-
break;
|
|
146
144
|
case PerformanceNavigation.TYPE_BACK_FORWARD:
|
|
147
145
|
return "back_forward";
|
|
148
|
-
break;
|
|
149
146
|
default:
|
|
150
147
|
return `unknown: ${rawType}`;
|
|
151
148
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics.mjs","sources":["../../src/analytics.ts"],"sourcesContent":["import {SHOPIFY_S, SHOPIFY_Y} from './cart-constants.js';\nimport type {\n ClientBrowserParameters,\n ShopifyAddToCartPayload,\n ShopifyAnalytics,\n ShopifyPageViewPayload,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {AnalyticsEventName} from './analytics-constants.js';\nimport {errorIfServer} from './analytics-utils.js';\nimport {getShopifyCookies} from './cookies-utils.js';\n\nimport {pageView as trekkiePageView} from './analytics-schema-trekkie-storefront-page-view.js';\nimport {\n pageView as customerPageView,\n pageView2 as customerPageView2,\n collectionView as customerCollectionView,\n productView as customerProductView,\n searchView as customerSearchView,\n addToCart as customerAddToCart,\n} from './analytics-schema-custom-storefront-customer-tracking.js';\n\n/**\n * Set user and session cookies and refresh the expiry time\n * @param event - The analytics event.\n * @param shopDomain - The Online Store domain to sent Shopify analytics under the same\n * top level domain.\n */\nexport function sendShopifyAnalytics(\n event: ShopifyAnalytics,\n shopDomain?: string,\n): Promise<void> {\n const {eventName, payload} = event;\n if (!payload.hasUserConsent) return Promise.resolve();\n\n let events: ShopifyMonorailEvent[] = [];\n const pageViewPayload = payload as ShopifyPageViewPayload;\n\n if (eventName === AnalyticsEventName.PAGE_VIEW) {\n events = events.concat(\n trekkiePageView(pageViewPayload),\n customerPageView(pageViewPayload),\n );\n } else if (eventName === AnalyticsEventName.ADD_TO_CART) {\n events = events.concat(\n customerAddToCart(payload as ShopifyAddToCartPayload),\n );\n } else if (eventName === AnalyticsEventName.PAGE_VIEW_2) {\n events = events.concat(\n trekkiePageView(pageViewPayload),\n customerPageView2(pageViewPayload),\n );\n } else if (eventName === AnalyticsEventName.COLLECTION_VIEW) {\n events = events.concat(customerCollectionView(pageViewPayload));\n } else if (eventName === AnalyticsEventName.PRODUCT_VIEW) {\n events = events.concat(customerProductView(pageViewPayload));\n } else if (eventName === AnalyticsEventName.SEARCH_VIEW) {\n events = events.concat(customerSearchView(pageViewPayload));\n }\n\n if (events.length) {\n return sendToShopify(events, shopDomain);\n } else {\n return Promise.resolve();\n }\n}\n\n// Shopify monorail return invalid agent for Lighthouse userAgents\nfunction isLighthouseUserAgent(): boolean {\n if (typeof window === 'undefined' || !window.navigator) return false;\n return /Chrome-Lighthouse/.test(window.navigator.userAgent);\n}\n\ntype MonorailResponse = {\n status: number;\n message: string;\n};\n\nconst ERROR_MESSAGE = 'sendShopifyAnalytics request is unsuccessful';\n\nfunction sendToShopify(\n events: ShopifyMonorailEvent[],\n shopDomain?: string,\n): Promise<void> {\n if (isLighthouseUserAgent()) {\n return Promise.resolve();\n }\n\n const eventsToBeSent = {\n events,\n metadata: {\n event_sent_at_ms: Date.now(),\n },\n };\n\n try {\n return fetch(\n shopDomain\n ? `https://${shopDomain}/.well-known/shopify/monorail/unstable/produce_batch`\n : 'https://monorail-edge.shopifysvc.com/unstable/produce_batch',\n {\n method: 'post',\n headers: {\n 'content-type': 'text/plain',\n },\n body: JSON.stringify(eventsToBeSent),\n },\n )\n .then((response) => {\n if (!response.ok) {\n throw new Error('Response failed');\n }\n return response.text();\n })\n .then((data) => {\n if (data) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const jsonResponse = JSON.parse(data);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n jsonResponse.result.forEach((eventResponse: MonorailResponse) => {\n if (eventResponse.status !== 200) {\n console.error(ERROR_MESSAGE, '\\n\\n', eventResponse.message);\n }\n });\n }\n })\n .catch((err) => {\n console.error(ERROR_MESSAGE, err);\n if (__HYDROGEN_DEV__) {\n throw new Error(ERROR_MESSAGE);\n }\n });\n } catch (error) {\n // Do nothing\n return Promise.resolve();\n }\n}\n\nexport function getClientBrowserParameters(): ClientBrowserParameters {\n if (errorIfServer('getClientBrowserParameters')) {\n return {\n uniqueToken: '',\n visitToken: '',\n url: '',\n path: '',\n search: '',\n referrer: '',\n title: '',\n userAgent: '',\n navigationType: '',\n navigationApi: '',\n };\n }\n\n const [navigationType, navigationApi] = getNavigationType();\n const cookies = getShopifyCookies(document.cookie);\n\n return {\n uniqueToken: cookies[SHOPIFY_Y],\n visitToken: cookies[SHOPIFY_S],\n url: location.href,\n path: location.pathname,\n search: location.search,\n referrer: document.referrer,\n title: document.title,\n userAgent: navigator.userAgent,\n navigationType,\n navigationApi,\n };\n}\n\nfunction getNavigationTypeExperimental(): string | undefined {\n try {\n const navigationEntries =\n performance?.getEntriesByType &&\n performance?.getEntriesByType('navigation');\n\n if (navigationEntries && navigationEntries[0]) {\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming\n const rawType = (\n window.performance.getEntriesByType(\n 'navigation',\n )[0] as PerformanceNavigationTiming\n )['type'];\n const navType = rawType && rawType.toString();\n\n return navType;\n }\n } catch (err) {\n // Do nothing\n }\n return undefined;\n}\n\nfunction getNavigationTypeLegacy(): string | undefined {\n try {\n if (\n PerformanceNavigation &&\n performance?.navigation?.type !== null &&\n performance?.navigation?.type !== undefined\n ) {\n // https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation\n const rawType = performance.navigation.type;\n switch (rawType) {\n case PerformanceNavigation.TYPE_NAVIGATE:\n return 'navigate';\n break;\n case PerformanceNavigation.TYPE_RELOAD:\n return 'reload';\n break;\n case PerformanceNavigation.TYPE_BACK_FORWARD:\n return 'back_forward';\n break;\n default:\n return `unknown: ${rawType}`;\n }\n }\n } catch (err) {\n // do nothing\n }\n return undefined;\n}\n\nfunction getNavigationType(): [string, string] {\n try {\n let navApi = 'PerformanceNavigationTiming';\n let navType = getNavigationTypeExperimental();\n if (!navType) {\n navType = getNavigationTypeLegacy();\n navApi = 'performance.navigation';\n }\n if (navType) {\n return [navType, navApi];\n } else {\n return ['unknown', 'unknown'];\n }\n } catch (err) {\n // do nothing\n }\n return ['error', 'error'];\n}\n"],"names":["trekkiePageView","customerPageView","customerAddToCart","customerPageView2","customerCollectionView","customerProductView","customerSearchView"],"mappings":";;;;;;AA4BgB,SAAA,qBACd,OACA,YACe;AACT,QAAA,EAAC,WAAW,QAAW,IAAA;AAC7B,MAAI,CAAC,QAAQ;AAAgB,WAAO,QAAQ;AAE5C,MAAI,SAAiC,CAAA;AACrC,QAAM,kBAAkB;AAEpB,MAAA,cAAc,mBAAmB,WAAW;AAC9C,aAAS,OAAO;AAAA,MACdA,SAAgB,eAAe;AAAA,MAC/BC,WAAiB,eAAe;AAAA,IAAA;AAAA,EAClC,WACS,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO;AAAA,MACdC,UAAkB,OAAkC;AAAA,IAAA;AAAA,EACtD,WACS,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO;AAAA,MACdF,SAAgB,eAAe;AAAA,MAC/BG,UAAkB,eAAe;AAAA,IAAA;AAAA,EACnC,WACS,cAAc,mBAAmB,iBAAiB;AAC3D,aAAS,OAAO,OAAOC,eAAuB,eAAe,CAAC;AAAA,EAAA,WACrD,cAAc,mBAAmB,cAAc;AACxD,aAAS,OAAO,OAAOC,YAAoB,eAAe,CAAC;AAAA,EAAA,WAClD,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO,OAAOC,WAAmB,eAAe,CAAC;AAAA,EAC5D;AAEA,MAAI,OAAO,QAAQ;AACV,WAAA,cAAc,QAAQ,UAAU;AAAA,EAAA,OAClC;AACL,WAAO,QAAQ;E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,UAAU;AACd,QAAI,CAAC,SAAS;AACZ,gBAAU,wBAAwB;AACzB,eAAA;AAAA,IACX;AACA,QAAI,SAAS;AACJ,aAAA,CAAC,SAAS,MAAM;AAAA,IAAA,OAClB;AACE,aAAA,CAAC,WAAW,SAAS;AAAA,IAC9B;AAAA,WACO,KAAK;AAAA,EAEd;AACO,SAAA,CAAC,SAAS,OAAO;AAC1B;"}
|
|
1
|
+
{"version":3,"file":"analytics.mjs","sources":["../../src/analytics.ts"],"sourcesContent":["import {SHOPIFY_S, SHOPIFY_Y} from './cart-constants.js';\nimport type {\n ClientBrowserParameters,\n ShopifyAddToCartPayload,\n ShopifyAnalytics,\n ShopifyPageViewPayload,\n ShopifyMonorailEvent,\n} from './analytics-types.js';\nimport {AnalyticsEventName} from './analytics-constants.js';\nimport {errorIfServer} from './analytics-utils.js';\nimport {getShopifyCookies} from './cookies-utils.js';\n\nimport {pageView as trekkiePageView} from './analytics-schema-trekkie-storefront-page-view.js';\nimport {\n pageView as customerPageView,\n pageView2 as customerPageView2,\n collectionView as customerCollectionView,\n productView as customerProductView,\n searchView as customerSearchView,\n addToCart as customerAddToCart,\n} from './analytics-schema-custom-storefront-customer-tracking.js';\n\n/**\n * Set user and session cookies and refresh the expiry time\n * @param event - The analytics event.\n * @param shopDomain - The Online Store domain to sent Shopify analytics under the same\n * top level domain.\n */\nexport function sendShopifyAnalytics(\n event: ShopifyAnalytics,\n shopDomain?: string,\n): Promise<void> {\n const {eventName, payload} = event;\n if (!payload.hasUserConsent) return Promise.resolve();\n\n let events: ShopifyMonorailEvent[] = [];\n const pageViewPayload = payload as ShopifyPageViewPayload;\n\n if (eventName === AnalyticsEventName.PAGE_VIEW) {\n events = events.concat(\n trekkiePageView(pageViewPayload),\n customerPageView(pageViewPayload),\n );\n } else if (eventName === AnalyticsEventName.ADD_TO_CART) {\n events = events.concat(\n customerAddToCart(payload as ShopifyAddToCartPayload),\n );\n } else if (eventName === AnalyticsEventName.PAGE_VIEW_2) {\n events = events.concat(\n trekkiePageView(pageViewPayload),\n customerPageView2(pageViewPayload),\n );\n } else if (eventName === AnalyticsEventName.COLLECTION_VIEW) {\n events = events.concat(customerCollectionView(pageViewPayload));\n } else if (eventName === AnalyticsEventName.PRODUCT_VIEW) {\n events = events.concat(customerProductView(pageViewPayload));\n } else if (eventName === AnalyticsEventName.SEARCH_VIEW) {\n events = events.concat(customerSearchView(pageViewPayload));\n }\n\n if (events.length) {\n return sendToShopify(events, shopDomain);\n } else {\n return Promise.resolve();\n }\n}\n\n// Shopify monorail return invalid agent for Lighthouse userAgents\nfunction isLighthouseUserAgent(): boolean {\n if (typeof window === 'undefined' || !window.navigator) return false;\n return /Chrome-Lighthouse/.test(window.navigator.userAgent);\n}\n\ntype MonorailResponse = {\n status: number;\n message: string;\n};\n\nconst ERROR_MESSAGE = 'sendShopifyAnalytics request is unsuccessful';\n\nfunction sendToShopify(\n events: ShopifyMonorailEvent[],\n shopDomain?: string,\n): Promise<void> {\n if (isLighthouseUserAgent()) {\n return Promise.resolve();\n }\n\n const eventsToBeSent = {\n events,\n metadata: {\n event_sent_at_ms: Date.now(),\n },\n };\n\n try {\n return fetch(\n shopDomain\n ? `https://${shopDomain}/.well-known/shopify/monorail/unstable/produce_batch`\n : 'https://monorail-edge.shopifysvc.com/unstable/produce_batch',\n {\n method: 'post',\n headers: {\n 'content-type': 'text/plain',\n },\n body: JSON.stringify(eventsToBeSent),\n },\n )\n .then((response) => {\n if (!response.ok) {\n throw new Error('Response failed');\n }\n return response.text();\n })\n .then((data) => {\n if (data) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const jsonResponse = JSON.parse(data);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n jsonResponse.result.forEach((eventResponse: MonorailResponse) => {\n if (eventResponse.status !== 200) {\n console.error(ERROR_MESSAGE, '\\n\\n', eventResponse.message);\n }\n });\n }\n })\n .catch((err) => {\n console.error(ERROR_MESSAGE, err);\n if (__HYDROGEN_DEV__) {\n throw new Error(ERROR_MESSAGE);\n }\n });\n } catch (error) {\n // Do nothing\n return Promise.resolve();\n }\n}\n\nexport function getClientBrowserParameters(): ClientBrowserParameters {\n if (errorIfServer('getClientBrowserParameters')) {\n return {\n uniqueToken: '',\n visitToken: '',\n url: '',\n path: '',\n search: '',\n referrer: '',\n title: '',\n userAgent: '',\n navigationType: '',\n navigationApi: '',\n };\n }\n\n const [navigationType, navigationApi] = getNavigationType();\n const cookies = getShopifyCookies(document.cookie);\n\n return {\n uniqueToken: cookies[SHOPIFY_Y],\n visitToken: cookies[SHOPIFY_S],\n url: location.href,\n path: location.pathname,\n search: location.search,\n referrer: document.referrer,\n title: document.title,\n userAgent: navigator.userAgent,\n navigationType,\n navigationApi,\n };\n}\n\nfunction getNavigationTypeExperimental(): string | undefined {\n try {\n const navigationEntries =\n performance?.getEntriesByType &&\n performance?.getEntriesByType('navigation');\n\n if (navigationEntries && navigationEntries[0]) {\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming\n const rawType = (\n window.performance.getEntriesByType(\n 'navigation',\n )[0] as PerformanceNavigationTiming\n )['type'];\n const navType = rawType && rawType.toString();\n\n return navType;\n }\n } catch (err) {\n // Do nothing\n }\n return undefined;\n}\n\nfunction getNavigationTypeLegacy(): string | undefined {\n try {\n if (\n PerformanceNavigation &&\n performance?.navigation?.type !== null &&\n performance?.navigation?.type !== undefined\n ) {\n // https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation\n const rawType = performance.navigation.type;\n switch (rawType) {\n case PerformanceNavigation.TYPE_NAVIGATE:\n return 'navigate';\n case PerformanceNavigation.TYPE_RELOAD:\n return 'reload';\n case PerformanceNavigation.TYPE_BACK_FORWARD:\n return 'back_forward';\n default:\n return `unknown: ${rawType}`;\n }\n }\n } catch (err) {\n // do nothing\n }\n return undefined;\n}\n\nfunction getNavigationType(): [string, string] {\n try {\n let navApi = 'PerformanceNavigationTiming';\n let navType = getNavigationTypeExperimental();\n if (!navType) {\n navType = getNavigationTypeLegacy();\n navApi = 'performance.navigation';\n }\n if (navType) {\n return [navType, navApi];\n } else {\n return ['unknown', 'unknown'];\n }\n } catch (err) {\n // do nothing\n }\n return ['error', 'error'];\n}\n"],"names":["trekkiePageView","customerPageView","customerAddToCart","customerPageView2","customerCollectionView","customerProductView","customerSearchView"],"mappings":";;;;;;AA4BgB,SAAA,qBACd,OACA,YACe;AACT,QAAA,EAAC,WAAW,QAAW,IAAA;AAC7B,MAAI,CAAC,QAAQ;AAAgB,WAAO,QAAQ;AAE5C,MAAI,SAAiC,CAAA;AACrC,QAAM,kBAAkB;AAEpB,MAAA,cAAc,mBAAmB,WAAW;AAC9C,aAAS,OAAO;AAAA,MACdA,SAAgB,eAAe;AAAA,MAC/BC,WAAiB,eAAe;AAAA,IAAA;AAAA,EAClC,WACS,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO;AAAA,MACdC,UAAkB,OAAkC;AAAA,IAAA;AAAA,EACtD,WACS,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO;AAAA,MACdF,SAAgB,eAAe;AAAA,MAC/BG,UAAkB,eAAe;AAAA,IAAA;AAAA,EACnC,WACS,cAAc,mBAAmB,iBAAiB;AAC3D,aAAS,OAAO,OAAOC,eAAuB,eAAe,CAAC;AAAA,EAAA,WACrD,cAAc,mBAAmB,cAAc;AACxD,aAAS,OAAO,OAAOC,YAAoB,eAAe,CAAC;AAAA,EAAA,WAClD,cAAc,mBAAmB,aAAa;AACvD,aAAS,OAAO,OAAOC,WAAmB,eAAe,CAAC;AAAA,EAC5D;AAEA,MAAI,OAAO,QAAQ;AACV,WAAA,cAAc,QAAQ,UAAU;AAAA,EAAA,OAClC;AACL,WAAO,QAAQ;EACjB;AACF;AAGA,SAAS,wBAAiC;AACxC,MAAI,OAAO,WAAW,eAAe,CAAC,OAAO;AAAkB,WAAA;AAC/D,SAAO,oBAAoB,KAAK,OAAO,UAAU,SAAS;AAC5D;AAOA,MAAM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AAS;AAAA,IAC9B;AAAA,WACO,KAAK;AAAA,EAEd;AACO,SAAA,CAAC,SAAS,OAAO;AAC1B;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cart-hooks.mjs","sources":["../../src/cart-hooks.tsx"],"sourcesContent":["import {useState, useCallback} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {flattenConnection} from './flatten-connection.js';\nimport {CartInput, Cart as CartType} from './storefront-api-types.js';\nimport {CartCreate, defaultCartFragment} from './cart-queries.js';\nimport {Cart} from './cart-types.js';\nimport {\n SHOPIFY_STOREFRONT_ID_HEADER,\n SHOPIFY_STOREFRONT_Y_HEADER,\n SHOPIFY_STOREFRONT_S_HEADER,\n SHOPIFY_Y,\n SHOPIFY_S,\n} from './cart-constants.js';\nimport type {StorefrontApiResponseOkPartial} from './storefront-api-response.types.js';\nimport {getShopifyCookies} from './cookies-utils.js';\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartFetch() {\n const {storefrontId, getPublicTokenHeaders, getStorefrontApiUrl} = useShop();\n\n return useCallback(\n <ReturnDataGeneric,>({\n query,\n variables,\n }: {\n query: string;\n variables: Record<string, unknown>;\n }): Promise<StorefrontApiResponseOkPartial<ReturnDataGeneric>> => {\n const headers = getPublicTokenHeaders({contentType: 'json'});\n\n if (storefrontId) {\n headers[SHOPIFY_STOREFRONT_ID_HEADER] = storefrontId;\n }\n\n // Find Shopify cookies\n const cookieData = getShopifyCookies(document.cookie);\n headers[SHOPIFY_STOREFRONT_Y_HEADER] = cookieData[SHOPIFY_Y];\n headers[SHOPIFY_STOREFRONT_S_HEADER] = cookieData[SHOPIFY_S];\n\n return fetch(getStorefrontApiUrl(), {\n method: 'POST',\n headers,\n body: JSON.stringify({\n query: query.toString(),\n variables,\n }),\n })\n .then(\n (res) =>\n res.json() as StorefrontApiResponseOkPartial<ReturnDataGeneric>,\n )\n .catch((error) => {\n return {\n data: undefined,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n errors: error?.toString(),\n };\n });\n },\n [getPublicTokenHeaders, storefrontId, getStorefrontApiUrl],\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useInstantCheckout() {\n const [cart, updateCart] = useState<Cart | undefined>();\n const [checkoutUrl, updateCheckoutUrl] = useState<Cart['checkoutUrl']>();\n const [error, updateError] = useState<string | undefined>();\n\n const fetch = useCartFetch();\n\n const createInstantCheckout = useCallback(\n async (cartInput: CartInput) => {\n const {data, errors} = await fetch<{\n cartCreate: {cart: CartType};\n }>({\n query: CartCreate(defaultCartFragment),\n variables: {\n input: cartInput,\n },\n });\n\n if (errors) {\n updateError(errors.toString());\n updateCart(undefined);\n updateCheckoutUrl(undefined);\n }\n\n if (data?.cartCreate?.cart) {\n const dataCart = data.cartCreate.cart;\n updateCart({\n ...dataCart,\n lines: flattenConnection(dataCart.lines),\n note: dataCart.note ?? undefined,\n });\n updateCheckoutUrl(dataCart.checkoutUrl);\n }\n },\n [fetch],\n );\n\n return {cart, checkoutUrl, error, createInstantCheckout};\n}\n"],"names":[],"mappings":";;;;AAiBO,SAAS,eAAe;AAC7B,QAAM,EAAC,cAAc,uBAAuB,wBAAuB,QAAQ;AAEpE,SAAA;AAAA,IACL,CAAqB;AAAA,MACnB;AAAA,MACA;AAAA,IAAA,MAIgE;AAChE,YAAM,UAAU,sBAAsB,EAAC,aAAa,OAAO,CAAA;AAE3D,UAAI,cAAc;AAChB,gBAAQ,4BAA4B,IAAI;AAAA,MAC1C;AAGM,YAAA,aAAa,kBAAkB,SAAS,MAAM;AAC5C,cAAA,2BAA2B,IAAI,WAAW,SAAS;AACnD,cAAA,2BAA2B,IAAI,WAAW,SAAS;AAEpD,aAAA,MAAM,uBAAuB;AAAA,QAClC,QAAQ;AAAA,QACR;AAAA,QACA,MAAM,KAAK,UAAU;AAAA,UACnB,OAAO,MAAM,SAAS;AAAA,UACtB;AAAA,QAAA,CACD;AAAA,MACF,CAAA,EACE;AAAA,QACC,CAAC,QACC,IAAI,KAAK;AAAA,MAAA,EAEZ,MAAM,CAAC,UAAU;AACT,eAAA;AAAA,UACL,MAAM;AAAA;AAAA,UAEN,QAAQ,+BAAO;AAAA,QAAS;AAAA,MAC1B,CACD;AAAA,IACL;AAAA,IACA,CAAC,uBAAuB,cAAc,mBAAmB;AAAA,EAAA;AAE7D;"}
|
|
1
|
+
{"version":3,"file":"cart-hooks.mjs","sources":["../../src/cart-hooks.tsx"],"sourcesContent":["import {useState, useCallback} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {flattenConnection} from './flatten-connection.js';\nimport {CartInput, Cart as CartType} from './storefront-api-types.js';\nimport {CartCreate, defaultCartFragment} from './cart-queries.js';\nimport {Cart} from './cart-types.js';\nimport {\n SHOPIFY_STOREFRONT_ID_HEADER,\n SHOPIFY_STOREFRONT_Y_HEADER,\n SHOPIFY_STOREFRONT_S_HEADER,\n SHOPIFY_Y,\n SHOPIFY_S,\n} from './cart-constants.js';\nimport type {StorefrontApiResponseOkPartial} from './storefront-api-response.types.js';\nimport {getShopifyCookies} from './cookies-utils.js';\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartFetch() {\n const {storefrontId, getPublicTokenHeaders, getStorefrontApiUrl} = useShop();\n\n return useCallback(\n <ReturnDataGeneric,>({\n query,\n variables,\n }: {\n query: string;\n variables: Record<string, unknown>;\n }): Promise<StorefrontApiResponseOkPartial<ReturnDataGeneric>> => {\n const headers = getPublicTokenHeaders({contentType: 'json'});\n\n if (storefrontId) {\n headers[SHOPIFY_STOREFRONT_ID_HEADER] = storefrontId;\n }\n\n // Find Shopify cookies\n const cookieData = getShopifyCookies(document.cookie);\n headers[SHOPIFY_STOREFRONT_Y_HEADER] = cookieData[SHOPIFY_Y];\n headers[SHOPIFY_STOREFRONT_S_HEADER] = cookieData[SHOPIFY_S];\n\n return fetch(getStorefrontApiUrl(), {\n method: 'POST',\n headers,\n body: JSON.stringify({\n query: query.toString(),\n variables,\n }),\n })\n .then(\n (res) =>\n res.json() as StorefrontApiResponseOkPartial<ReturnDataGeneric>,\n )\n .catch((error) => {\n return {\n data: undefined,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n errors: error?.toString(),\n };\n });\n },\n [getPublicTokenHeaders, storefrontId, getStorefrontApiUrl],\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useInstantCheckout() {\n const [cart, updateCart] = useState<Cart | undefined>();\n const [checkoutUrl, updateCheckoutUrl] = useState<Cart['checkoutUrl']>();\n const [error, updateError] = useState<string | undefined>();\n\n const fetch = useCartFetch();\n\n const createInstantCheckout = useCallback(\n async (cartInput: CartInput) => {\n const {data, errors} = await fetch<{\n cartCreate: {cart: CartType};\n }>({\n query: CartCreate(defaultCartFragment),\n variables: {\n input: cartInput,\n },\n });\n\n if (errors) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n updateError(errors.toString());\n updateCart(undefined);\n updateCheckoutUrl(undefined);\n }\n\n if (data?.cartCreate?.cart) {\n const dataCart = data.cartCreate.cart;\n updateCart({\n ...dataCart,\n lines: flattenConnection(dataCart.lines),\n note: dataCart.note ?? undefined,\n });\n updateCheckoutUrl(dataCart.checkoutUrl);\n }\n },\n [fetch],\n );\n\n return {cart, checkoutUrl, error, createInstantCheckout};\n}\n"],"names":[],"mappings":";;;;AAiBO,SAAS,eAAe;AAC7B,QAAM,EAAC,cAAc,uBAAuB,wBAAuB,QAAQ;AAEpE,SAAA;AAAA,IACL,CAAqB;AAAA,MACnB;AAAA,MACA;AAAA,IAAA,MAIgE;AAChE,YAAM,UAAU,sBAAsB,EAAC,aAAa,OAAO,CAAA;AAE3D,UAAI,cAAc;AAChB,gBAAQ,4BAA4B,IAAI;AAAA,MAC1C;AAGM,YAAA,aAAa,kBAAkB,SAAS,MAAM;AAC5C,cAAA,2BAA2B,IAAI,WAAW,SAAS;AACnD,cAAA,2BAA2B,IAAI,WAAW,SAAS;AAEpD,aAAA,MAAM,uBAAuB;AAAA,QAClC,QAAQ;AAAA,QACR;AAAA,QACA,MAAM,KAAK,UAAU;AAAA,UACnB,OAAO,MAAM,SAAS;AAAA,UACtB;AAAA,QAAA,CACD;AAAA,MACF,CAAA,EACE;AAAA,QACC,CAAC,QACC,IAAI,KAAK;AAAA,MAAA,EAEZ,MAAM,CAAC,UAAU;AACT,eAAA;AAAA,UACL,MAAM;AAAA;AAAA,UAEN,QAAQ,+BAAO;AAAA,QAAS;AAAA,MAC1B,CACD;AAAA,IACL;AAAA,IACA,CAAC,uBAAuB,cAAc,mBAAmB;AAAA,EAAA;AAE7D;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flatten-connection.mjs","sources":["../../src/flatten-connection.ts"],"sourcesContent":["import type {PartialDeep} from 'type-fest';\n\n/**\n * The `flattenConnection` utility transforms a connection object from the Storefront API (for example, [Product-related connections](https://shopify.dev/api/storefront/reference/products/product)) into a flat array of nodes.\n * The utility works with either `nodes` or `edges.node`.\n *\n * If `connection` is null or undefined, will return an empty array instead in production. In development, an error will be thrown.\n */\nexport function flattenConnection<\n ConnectionGeneric extends\n | PartialDeep<ConnectionEdges, {recurseIntoArrays: true}>\n | PartialDeep<ConnectionNodes, {recurseIntoArrays: true}>\n | ConnectionEdges\n | ConnectionNodes,\n>(\n connection?: ConnectionGeneric,\n): ConnectionGeneric extends\n | {\n edges: Array<{node: infer ConnectionBaseType}>;\n }\n | {\n nodes: Array<infer ConnectionBaseType>;\n }\n ? // if it's not a PartialDeep, then return the infered type\n ConnectionBaseType[]\n : ConnectionGeneric extends\n | PartialDeep<\n {edges: {node: Array<infer ConnectionBaseType>}},\n {recurseIntoArrays: true}\n >\n | PartialDeep<\n {\n nodes: Array<infer ConnectionBaseType>;\n },\n {recurseIntoArrays: true}\n >\n ? // if it is a PartialDeep, return a PartialDeep inferred type\n PartialDeep<ConnectionBaseType[], {recurseIntoArrays: true}>\n : never {\n if (!connection) {\n const noConnectionErr = `flattenConnection(): needs a 'connection' to flatten, but received '${\n connection ?? ''\n }' instead.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noConnectionErr);\n } else {\n console.error(noConnectionErr + ` Returning an empty array`);\n // @ts-expect-error We don't want to crash prod, so return an empty array\n return [];\n }\n }\n\n if ('nodes' in connection) {\n // @ts-expect-error return type is failing\n return connection.nodes;\n }\n\n if ('edges' in connection && Array.isArray(connection.edges)) {\n // @ts-expect-error return type is failing\n return connection.edges.map((edge) => {\n if (!edge?.node) {\n throw new Error(\n 'flattenConnection(): Connection edges must contain nodes',\n );\n }\n return edge.node;\n }) as Array<unknown>;\n }\n\n if (__HYDROGEN_DEV__) {\n console.warn(\n `flattenConnection(): The connection did not contain either \"nodes\" or \"edges.node\". Returning an empty array.`,\n );\n }\n\n // @ts-expect-error We don't want to crash prod, so return an empty array\n return [];\n}\n\ntype ConnectionEdges = {\n edges: Array<{node: unknown}>;\n};\n\ntype ConnectionNodes = {\n nodes: Array<unknown>;\n};\n\n// This is only for documentation purposes, and it is not used in the code.\nexport interface ConnectionGenericForDoc {\n connection?: ConnectionEdges | ConnectionNodes;\n}\nexport type FlattenConnectionReturnForDoc =
|
|
1
|
+
{"version":3,"file":"flatten-connection.mjs","sources":["../../src/flatten-connection.ts"],"sourcesContent":["import type {PartialDeep} from 'type-fest';\n\n/**\n * The `flattenConnection` utility transforms a connection object from the Storefront API (for example, [Product-related connections](https://shopify.dev/api/storefront/reference/products/product)) into a flat array of nodes.\n * The utility works with either `nodes` or `edges.node`.\n *\n * If `connection` is null or undefined, will return an empty array instead in production. In development, an error will be thrown.\n */\nexport function flattenConnection<\n ConnectionGeneric extends\n | PartialDeep<ConnectionEdges, {recurseIntoArrays: true}>\n | PartialDeep<ConnectionNodes, {recurseIntoArrays: true}>\n | ConnectionEdges\n | ConnectionNodes,\n>(\n connection?: ConnectionGeneric,\n): ConnectionGeneric extends\n | {\n edges: Array<{node: infer ConnectionBaseType}>;\n }\n | {\n nodes: Array<infer ConnectionBaseType>;\n }\n ? // if it's not a PartialDeep, then return the infered type\n ConnectionBaseType[]\n : ConnectionGeneric extends\n | PartialDeep<\n {edges: {node: Array<infer ConnectionBaseType>}},\n {recurseIntoArrays: true}\n >\n | PartialDeep<\n {\n nodes: Array<infer ConnectionBaseType>;\n },\n {recurseIntoArrays: true}\n >\n ? // if it is a PartialDeep, return a PartialDeep inferred type\n PartialDeep<ConnectionBaseType[], {recurseIntoArrays: true}>\n : never {\n if (!connection) {\n const noConnectionErr = `flattenConnection(): needs a 'connection' to flatten, but received '${\n connection ?? ''\n }' instead.`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noConnectionErr);\n } else {\n console.error(noConnectionErr + ` Returning an empty array`);\n // @ts-expect-error We don't want to crash prod, so return an empty array\n return [];\n }\n }\n\n if ('nodes' in connection) {\n // @ts-expect-error return type is failing\n return connection.nodes;\n }\n\n if ('edges' in connection && Array.isArray(connection.edges)) {\n // @ts-expect-error return type is failing\n return connection.edges.map((edge) => {\n if (!edge?.node) {\n throw new Error(\n 'flattenConnection(): Connection edges must contain nodes',\n );\n }\n return edge.node;\n }) as Array<unknown>;\n }\n\n if (__HYDROGEN_DEV__) {\n console.warn(\n `flattenConnection(): The connection did not contain either \"nodes\" or \"edges.node\". Returning an empty array.`,\n );\n }\n\n // @ts-expect-error We don't want to crash prod, so return an empty array\n return [];\n}\n\ntype ConnectionEdges = {\n edges: Array<{node: unknown}>;\n};\n\ntype ConnectionNodes = {\n nodes: Array<unknown>;\n};\n\n// This is only for documentation purposes, and it is not used in the code.\nexport interface ConnectionGenericForDoc {\n connection?: ConnectionEdges | ConnectionNodes;\n}\nexport type FlattenConnectionReturnForDoc = unknown[];\n"],"names":[],"mappings":"AAQO,SAAS,kBAOd,YAuBQ;AACR,MAAI,CAAC,YAAY;AACT,UAAA,kBAAkB,uEACtB,cAAc,EAChB;AACsB;AACd,YAAA,IAAI,MAAM,eAAe;AAAA,IAKjC;AAAA,EACF;AAEA,MAAI,WAAW,YAAY;AAEzB,WAAO,WAAW;AAAA,EACpB;AAEA,MAAI,WAAW,cAAc,MAAM,QAAQ,WAAW,KAAK,GAAG;AAE5D,WAAO,WAAW,MAAM,IAAI,CAAC,SAAS;AAChC,UAAA,EAAC,6BAAM,OAAM;AACf,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAAA,MAEJ;AACA,aAAO,KAAK;AAAA,IAAA,CACb;AAAA,EACH;AAEsB;AACZ,YAAA;AAAA,MACN;AAAA,IAAA;AAAA,EAEJ;AAGA,SAAO;AACT;"}
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import { isOptionValueCombinationInEncodedVariant } from "./optionValueDecoder.mjs";
|
|
2
2
|
function mapProductOptions(options) {
|
|
3
|
-
return
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
3
|
+
return Object.assign(
|
|
4
|
+
{},
|
|
5
|
+
...options.map((option) => {
|
|
6
|
+
return {
|
|
7
|
+
[option.name]: Object.assign(
|
|
8
|
+
{},
|
|
9
|
+
...(option == null ? void 0 : option.optionValues) ? option.optionValues.map((value, index) => {
|
|
10
|
+
return { [value.name]: index };
|
|
11
|
+
}) : []
|
|
12
|
+
)
|
|
13
|
+
};
|
|
14
|
+
})
|
|
15
|
+
);
|
|
11
16
|
}
|
|
12
17
|
function mapSelectedProductOptionToObject(options) {
|
|
13
18
|
return Object.assign(
|
|
@@ -20,28 +25,30 @@ function mapSelectedProductOptionToObject(options) {
|
|
|
20
25
|
function mapSelectedProductOptionToObjectAsString(options) {
|
|
21
26
|
return JSON.stringify(mapSelectedProductOptionToObject(options));
|
|
22
27
|
}
|
|
23
|
-
function encodeSelectedProductOptionAsKey(selectedOption
|
|
28
|
+
function encodeSelectedProductOptionAsKey(selectedOption) {
|
|
24
29
|
if (Array.isArray(selectedOption)) {
|
|
25
30
|
return JSON.stringify(
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
31
|
+
Object.assign(
|
|
32
|
+
{},
|
|
33
|
+
...selectedOption.map((option) => ({ [option.name]: option.value }))
|
|
34
|
+
)
|
|
29
35
|
);
|
|
30
36
|
} else {
|
|
31
|
-
return JSON.stringify(
|
|
32
|
-
Object.keys(selectedOption).map((key, index) => {
|
|
33
|
-
return productOptionMappings[index][selectedOption[key]];
|
|
34
|
-
})
|
|
35
|
-
);
|
|
37
|
+
return JSON.stringify(selectedOption);
|
|
36
38
|
}
|
|
37
39
|
}
|
|
38
|
-
function
|
|
40
|
+
function buildEncodingArrayFromSelectedOptions(selectedOption, productOptionMappings) {
|
|
41
|
+
const encoding = Object.keys(selectedOption).map((key) => {
|
|
42
|
+
return productOptionMappings[key] ? productOptionMappings[key][selectedOption[key]] : null;
|
|
43
|
+
});
|
|
44
|
+
return encoding.filter((code) => code !== null);
|
|
45
|
+
}
|
|
46
|
+
function mapVariants(variants) {
|
|
39
47
|
return Object.assign(
|
|
40
48
|
{},
|
|
41
49
|
...variants.map((variant) => {
|
|
42
50
|
const variantKey = encodeSelectedProductOptionAsKey(
|
|
43
|
-
variant.selectedOptions || []
|
|
44
|
-
productOptionMappings
|
|
51
|
+
variant.selectedOptions || []
|
|
45
52
|
);
|
|
46
53
|
return { [variantKey]: variant };
|
|
47
54
|
})
|
|
@@ -177,15 +184,20 @@ function getProductOptions(product) {
|
|
|
177
184
|
encodedVariantAvailability,
|
|
178
185
|
handle: productHandle
|
|
179
186
|
} = checkedProduct;
|
|
187
|
+
const selectedOptionKeys = selectedVariant == null ? void 0 : selectedVariant.selectedOptions.map(
|
|
188
|
+
(option) => option.name
|
|
189
|
+
);
|
|
190
|
+
const filteredOptions = options.filter((option) => {
|
|
191
|
+
return selectedOptionKeys && selectedOptionKeys.indexOf(option.name) >= 0;
|
|
192
|
+
});
|
|
180
193
|
const productOptionMappings = mapProductOptions(options);
|
|
181
194
|
const variants = mapVariants(
|
|
182
|
-
selectedVariant ? [selectedVariant, ...adjacentVariants] : adjacentVariants
|
|
183
|
-
productOptionMappings
|
|
195
|
+
selectedVariant ? [selectedVariant, ...adjacentVariants] : adjacentVariants
|
|
184
196
|
);
|
|
185
197
|
const selectedOptions = mapSelectedProductOptionToObject(
|
|
186
198
|
selectedVariant ? selectedVariant.selectedOptions : []
|
|
187
199
|
);
|
|
188
|
-
const productOptions =
|
|
200
|
+
const productOptions = filteredOptions.map((option, optionIndex) => {
|
|
189
201
|
return {
|
|
190
202
|
...option,
|
|
191
203
|
optionValues: option.optionValues.map((value) => {
|
|
@@ -193,13 +205,13 @@ function getProductOptions(product) {
|
|
|
193
205
|
const targetOptionParams = { ...selectedOptions };
|
|
194
206
|
targetOptionParams[option.name] = value.name;
|
|
195
207
|
const targetKey = encodeSelectedProductOptionAsKey(
|
|
208
|
+
targetOptionParams || []
|
|
209
|
+
);
|
|
210
|
+
const encodingKey = buildEncodingArrayFromSelectedOptions(
|
|
196
211
|
targetOptionParams || [],
|
|
197
212
|
productOptionMappings
|
|
198
213
|
);
|
|
199
|
-
const topDownKey =
|
|
200
|
-
0,
|
|
201
|
-
optionIndex + 1
|
|
202
|
-
);
|
|
214
|
+
const topDownKey = encodingKey.slice(0, optionIndex + 1);
|
|
203
215
|
const exists = isOptionValueCombinationInEncodedVariant(
|
|
204
216
|
topDownKey,
|
|
205
217
|
encodedVariantExistence || ""
|