@shopify/hydrogen-react 2023.4.0 → 2023.4.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/BuyNowButton.mjs +2 -2
- package/dist/browser-dev/BuyNowButton.mjs.map +1 -1
- package/dist/browser-dev/Image.mjs.map +1 -1
- package/dist/browser-dev/analytics-utils.mjs.map +1 -1
- package/dist/browser-dev/index.mjs +2 -0
- package/dist/browser-dev/index.mjs.map +1 -1
- package/dist/browser-dev/storefront-client.mjs.map +1 -1
- package/dist/browser-prod/BuyNowButton.mjs +2 -2
- package/dist/browser-prod/BuyNowButton.mjs.map +1 -1
- package/dist/browser-prod/Image.mjs.map +1 -1
- package/dist/browser-prod/analytics-utils.mjs.map +1 -1
- package/dist/browser-prod/index.mjs +2 -0
- package/dist/browser-prod/index.mjs.map +1 -1
- package/dist/browser-prod/storefront-client.mjs.map +1 -1
- package/dist/node-dev/BuyNowButton.js +2 -2
- package/dist/node-dev/BuyNowButton.js.map +1 -1
- package/dist/node-dev/BuyNowButton.mjs +2 -2
- package/dist/node-dev/BuyNowButton.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/analytics-utils.js.map +1 -1
- package/dist/node-dev/analytics-utils.mjs.map +1 -1
- package/dist/node-dev/index.js +2 -0
- package/dist/node-dev/index.js.map +1 -1
- package/dist/node-dev/index.mjs +2 -0
- package/dist/node-dev/index.mjs.map +1 -1
- package/dist/node-dev/storefront-client.js.map +1 -1
- package/dist/node-dev/storefront-client.mjs.map +1 -1
- package/dist/node-prod/BuyNowButton.js +2 -2
- package/dist/node-prod/BuyNowButton.js.map +1 -1
- package/dist/node-prod/BuyNowButton.mjs +2 -2
- package/dist/node-prod/BuyNowButton.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/analytics-utils.js.map +1 -1
- package/dist/node-prod/analytics-utils.mjs.map +1 -1
- package/dist/node-prod/index.js +2 -0
- package/dist/node-prod/index.js.map +1 -1
- package/dist/node-prod/index.mjs +2 -0
- package/dist/node-prod/index.mjs.map +1 -1
- package/dist/node-prod/storefront-client.js.map +1 -1
- package/dist/node-prod/storefront-client.mjs.map +1 -1
- package/dist/types/Image.d.ts +6 -68
- package/dist/types/analytics-types.d.ts +1 -1
- package/dist/types/analytics-utils.d.ts +2 -2
- package/dist/types/index.d.cts +2 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/storefront-client.d.ts +1 -1
- package/dist/umd/hydrogen-react.dev.js +3 -2
- package/dist/umd/hydrogen-react.dev.js.map +1 -1
- package/dist/umd/hydrogen-react.prod.js +5 -5
- package/dist/umd/hydrogen-react.prod.js.map +1 -1
- package/package.json +1 -1
|
@@ -14,10 +14,10 @@ function BuyNowButton(props) {
|
|
|
14
14
|
...passthroughProps
|
|
15
15
|
} = props;
|
|
16
16
|
useEffect(() => {
|
|
17
|
-
if (checkoutUrl) {
|
|
17
|
+
if (loading && checkoutUrl) {
|
|
18
18
|
window.location.href = checkoutUrl;
|
|
19
19
|
}
|
|
20
|
-
}, [checkoutUrl]);
|
|
20
|
+
}, [loading, checkoutUrl]);
|
|
21
21
|
const handleBuyNow = useCallback(() => {
|
|
22
22
|
setLoading(true);
|
|
23
23
|
cartCreate({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BuyNowButton.mjs","sources":["../../src/BuyNowButton.tsx"],"sourcesContent":["import {useEffect, useState, useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ninterface BuyNowButtonPropsBase {\n /** The item quantity. Defaults to 1. */\n quantity?: number;\n /** The ID of the variant. */\n variantId: string;\n /** An array of cart line attributes that belong to the item being added to the cart. */\n attributes?: {\n key: string;\n value: string;\n }[];\n}\n\ntype BuyNowButtonProps<AsType extends React.ElementType = 'button'> =\n BuyNowButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `BuyNowButton` component renders a button that adds an item to the cart and redirects the customer to checkout.\n * Must be a child of a `CartProvider` component.\n */\nexport function BuyNowButton<AsType extends React.ElementType = 'button'>(\n props: BuyNowButtonProps<AsType>,\n): JSX.Element {\n const {cartCreate, checkoutUrl} = useCart();\n const [loading, setLoading] = useState<boolean>(false);\n\n const {\n quantity,\n variantId,\n onClick,\n attributes,\n children,\n ...passthroughProps\n } = props;\n\n useEffect(() => {\n if (checkoutUrl) {\n window.location.href = checkoutUrl;\n }\n }, [checkoutUrl]);\n\n const handleBuyNow = useCallback(() => {\n setLoading(true);\n cartCreate({\n lines: [\n {\n quantity: quantity ?? 1,\n merchandiseId: variantId,\n attributes,\n },\n ],\n });\n }, [cartCreate, quantity, variantId, attributes]);\n\n return (\n <BaseButton\n disabled={loading ?? passthroughProps.disabled}\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleBuyNow}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface BuyNowButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends BuyNowButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n"],"names":[],"mappings":";;;;AA2BO,SAAS,aACd,OACa;AACb,QAAM,EAAC,YAAY,YAAW,IAAI,QAAQ;AAC1C,QAAM,CAAC,SAAS,UAAU,IAAI,SAAkB,KAAK;AAE/C,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AAEJ,YAAU,MAAM;AACd,QAAI,aAAa;
|
|
1
|
+
{"version":3,"file":"BuyNowButton.mjs","sources":["../../src/BuyNowButton.tsx"],"sourcesContent":["import {useEffect, useState, useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ninterface BuyNowButtonPropsBase {\n /** The item quantity. Defaults to 1. */\n quantity?: number;\n /** The ID of the variant. */\n variantId: string;\n /** An array of cart line attributes that belong to the item being added to the cart. */\n attributes?: {\n key: string;\n value: string;\n }[];\n}\n\ntype BuyNowButtonProps<AsType extends React.ElementType = 'button'> =\n BuyNowButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `BuyNowButton` component renders a button that adds an item to the cart and redirects the customer to checkout.\n * Must be a child of a `CartProvider` component.\n */\nexport function BuyNowButton<AsType extends React.ElementType = 'button'>(\n props: BuyNowButtonProps<AsType>,\n): JSX.Element {\n const {cartCreate, checkoutUrl} = useCart();\n const [loading, setLoading] = useState<boolean>(false);\n\n const {\n quantity,\n variantId,\n onClick,\n attributes,\n children,\n ...passthroughProps\n } = props;\n\n useEffect(() => {\n if (loading && checkoutUrl) {\n window.location.href = checkoutUrl;\n }\n }, [loading, checkoutUrl]);\n\n const handleBuyNow = useCallback(() => {\n setLoading(true);\n cartCreate({\n lines: [\n {\n quantity: quantity ?? 1,\n merchandiseId: variantId,\n attributes,\n },\n ],\n });\n }, [cartCreate, quantity, variantId, attributes]);\n\n return (\n <BaseButton\n disabled={loading ?? passthroughProps.disabled}\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleBuyNow}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface BuyNowButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends BuyNowButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n"],"names":[],"mappings":";;;;AA2BO,SAAS,aACd,OACa;AACb,QAAM,EAAC,YAAY,YAAW,IAAI,QAAQ;AAC1C,QAAM,CAAC,SAAS,UAAU,IAAI,SAAkB,KAAK;AAE/C,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AAEJ,YAAU,MAAM;AACd,QAAI,WAAW,aAAa;AAC1B,aAAO,SAAS,OAAO;AAAA,IACzB;AAAA,EAAA,GACC,CAAC,SAAS,WAAW,CAAC;AAEnB,QAAA,eAAe,YAAY,MAAM;AACrC,eAAW,IAAI;AACJ,eAAA;AAAA,MACT,OAAO;AAAA,QACL;AAAA,UACE,UAAU,YAAY;AAAA,UACtB,eAAe;AAAA,UACf;AAAA,QACF;AAAA,MACF;AAAA,IAAA,CACD;AAAA,KACA,CAAC,YAAY,UAAU,WAAW,UAAU,CAAC;AAG9C,SAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,UAAU,WAAW,iBAAiB;AAAA,MACrC,GAAG;AAAA,MACJ;AAAA,MACA,gBAAgB;AAAA,MAEf;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 intervals: number;\n startingWidth: number;\n incrementSize: number;\n placeholderWidth: number;\n};\n\ntype HtmlImageProps = React.DetailedHTMLProps<\n React.ImgHTMLAttributes<HTMLImageElement>,\n HTMLImageElement\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/** Legacy type for backwards compatibility *\n * @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop. Or pass a custom `loader` with `LoaderParams` */\nexport type ShopifyLoaderOptions = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: HtmlImageProps['width'] | ImageType['width'];\n /** The URL param that controls height */\n height?: HtmlImageProps['height'] | ImageType['height'];\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\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.ImgHTMLAttributes<HTMLImageElement> & {\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` object. Must be an Image object.\n * Optionally, import the `IMAGE_FRAGMENT` to use in your GraphQL queries.\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 key?: React.Key;\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 /** @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop */\n loaderOptions?: ShopifyLoaderOptions;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n /** @deprecated Autocalculated, use only `width` prop, or srcSetOptions */\n widths?: (HtmlImageProps['width'] | ImageType['width'])[];\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrgen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loaderOptions,\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 widths,\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Deprecated Props from original Image component\n */\n if (__HYDROGEN_DEV__) {\n if (loaderOptions) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `Use the \\`crop\\`, \\`width\\`, \\`height\\`, and src props, or`,\n `the \\`data\\` prop to achieve the same result. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n if (widths) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `\\`widths\\` are now calculated automatically based on the`,\n `config and width props. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n }\n\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FixedWidthImage({\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n ref,\n width,\n}: FixedWidthImageProps) {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all of the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop);\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [aspectRatio, crop, height, imageWidths, loader, normalizedProps, width]);\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\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FluidImage({\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n ref,\n sizes,\n}: FluidImageProps) {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n}\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href;\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return (\n typeof width === 'number' ||\n (typeof width === 'string' && fixedEndings.test(width))\n );\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n const sizes = imageWidths.map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n });\n return sizes;\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n"],"names":[],"mappings":";;AA8HO,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;AAAA,IACA,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;AAAA,IACA,GAAG;AAAA,KAEL,QACG;AAImB;AACpB,UAAI,eAAe;AACT,gBAAA;AAAA,UACN;AAAA,YACE;AAAA,YACA;AAAA,YACA,+DACE,QAAO,6BAAM,SAAO,qDAAkB,QAAO;AAAA,UAAA,EAE/C,KAAK,GAAG;AAAA,QAAA;AAAA,MAEd;AAEA,UAAI,QAAQ;AACF,gBAAA;AAAA,UACN;AAAA,YACE;AAAA,YACA;AAAA,YACA,yCACE,QAAO,6BAAM,SAAO,qDAAkB,QAAO;AAAA,UAAA,EAE/C,KAAK,GAAG;AAAA,QAAA;AAAA,MAEd;AAAA,IACF;AAKM,UAAA,iBAAi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ACvC;AASO,SAAS,iBAAiB,aAA0C;AACzE,MAAI,CAAC;AAAa;AAClB,QAAM,CAAC,OAAO,MAAM,IAAI,YAAY,MAAM,GAAG;AAC7C,SAAO,KAAK,OAAO,KAAK,IAAI,OAAO,MAAM;AAC3C;AAGO,SAAS,cACd,aACA,aACA,OAAa,UAOD;AACZ,MAAI,CAAC;AAAa;AAClB,QAAM,QAAQ,YAAY,IAAI,CAAC,UAAkB;AACxC,WAAA;AAAA,MACL;AAAA,MACA,QAAQ,cACJ,SAAS,iBAAiB,WAAW,KAAK,KAC1C;AAAA,MACJ;AAAA,IAAA;AAAA,EACF,CACD;AACM,SAAA;AAQT;"}
|
|
1
|
+
{"version":3,"file":"Image.mjs","sources":["../../src/Image.tsx"],"sourcesContent":["/* eslint-disable eslint-comments/disable-enable-pair */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable hydrogen/prefer-image-component */\nimport * as React from 'react';\nimport type {PartialDeep} from 'type-fest';\nimport type {Image as ImageType} from './storefront-api-types.js';\n\n/*\n * An optional prop you can use to change the\n * default srcSet generation behaviour\n */\ntype SrcSetOptions = {\n intervals: number;\n startingWidth: number;\n incrementSize: number;\n placeholderWidth: number;\n};\n\ntype HtmlImageProps = React.DetailedHTMLProps<\n React.ImgHTMLAttributes<HTMLImageElement>,\n HTMLImageElement\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/** Legacy type for backwards compatibility *\n * @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop. Or pass a custom `loader` with `LoaderParams` */\nexport type ShopifyLoaderOptions = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: HtmlImageProps['width'] | ImageType['width'];\n /** The URL param that controls height */\n height?: HtmlImageProps['height'] | ImageType['height'];\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\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/2023-04/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n /** @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop */\n loaderOptions?: ShopifyLoaderOptions;\n /** @deprecated Autocalculated, use only `width` prop, or srcSetOptions */\n widths?: (HtmlImageProps['width'] | ImageType['width'])[];\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrgen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loaderOptions,\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 widths,\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Deprecated Props from original Image component\n */\n if (__HYDROGEN_DEV__) {\n if (loaderOptions) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `Use the \\`crop\\`, \\`width\\`, \\`height\\`, and src props, or`,\n `the \\`data\\` prop to achieve the same result. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n if (widths) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `\\`widths\\` are now calculated automatically based on the`,\n `config and width props. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n }\n\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FixedWidthImage({\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n ref,\n width,\n}: FixedWidthImageProps) {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all of the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop);\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [aspectRatio, crop, height, imageWidths, loader, normalizedProps, width]);\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\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FluidImage({\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n ref,\n sizes,\n}: FluidImageProps) {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n}\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href;\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return (\n typeof width === 'number' ||\n (typeof width === 'string' && fixedEndings.test(width))\n );\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n const sizes = imageWidths.map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n });\n return sizes;\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n"],"names":[],"mappings":";;AA+HO,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;AAAA,IACA,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;AAAA,IACA,GAAG;AAAA,KAEL,QACG;AAImB;AACpB,UAAI,eAAe;AACT,gBAAA;AAAA,UACN;AAAA,YACE;AAAA,YACA;AAAA,YACA,+DACE,QAAO,6BAAM,SAAO,qDAAkB,QAAO;AAAA,UAAA,EAE/C,KAAK,GAAG;AAAA,QAAA;AAAA,MAEd;AAEA,UAAI,QAAQ;AACF,gBAAA;AAAA,UACN;AAAA,YACE;AAAA,YACA;AAAA,YACA,yCACE,QAAO,6BAAM,SAAO,qDAAkB,QAAO;AAAA,UAAA,EAE/C,KAAK,GAAG;AAAA,QAAA;AAAA,MAEd;AAAA,IACF;AAKM,UAAA,iBAAiB,MAAM,QAAQ,MAAM;AAEzC,YAAM,aACJ,6BAAM,WAAS,6BAAM,UAAS,6BAAM,QAAQ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AAM,IAAI,YAAY,MAAM,GAAG;AAC7C,SAAO,KAAK,OAAO,KAAK,IAAI,OAAO,MAAM;AAC3C;AAGO,SAAS,cACd,aACA,aACA,OAAa,UAOD;AACZ,MAAI,CAAC;AAAa;AAClB,QAAM,QAAQ,YAAY,IAAI,CAAC,UAAkB;AACxC,WAAA;AAAA,MACL;AAAA,MACA,QAAQ,cACJ,SAAS,iBAAiB,WAAW,KAAK,KAC1C;AAAA,MACJ;AAAA,IAAA;AAAA,EACF,CACD;AACM,SAAA;AAQT;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics-utils.mjs","sources":["../../src/analytics-utils.ts"],"sourcesContent":["import type {\n ShopifyMonorailPayload,\n ShopifyMonorailEvent,\n
|
|
1
|
+
{"version":3,"file":"analytics-utils.mjs","sources":["../../src/analytics-utils.ts"],"sourcesContent":["import type {\n ShopifyMonorailPayload,\n ShopifyMonorailEvent,\n ShopifyGid,\n} from './analytics-types.js';\n\n/**\n * Builds a Shopify Monorail event from a Shopify Monorail payload and a schema ID.\n * @param payload - The Monorail payload\n * @param schemaId - The schema ID to use\n * @returns The formatted payload\n **/\nexport function schemaWrapper(\n schemaId: string,\n payload: ShopifyMonorailPayload,\n): ShopifyMonorailEvent {\n return {\n schema_id: schemaId,\n payload,\n metadata: {\n event_created_at_ms: Date.now(),\n },\n };\n}\n\n/**\n * Parses global id (gid) and returns the resource type and id.\n * @see https://shopify.dev/api/usage/gids\n * @param gid - A shopify GID (string)\n *\n * @example\n * ```ts\n * const {id, resource} = parseGid('gid://shopify/Order/123')\n * // => id = \"123\", resource = 'Order'\n *\n * * const {id, resource} = parseGid('gid://shopify/Cart/abc123')\n * // => id = \"abc123\", resource = 'Cart'\n * ```\n **/\nexport function parseGid(gid: string | undefined): ShopifyGid {\n const defaultReturn = {id: '', resource: null};\n\n if (typeof gid !== 'string') {\n return defaultReturn;\n }\n\n // TODO: add support for parsing query parameters on complex gids\n // Reference: https://shopify.dev/api/usage/gids\n const matches = gid.match(/^gid:\\/\\/shopify\\/(\\w+)\\/([^/]+)/);\n\n if (!matches || matches.length === 1) {\n return defaultReturn;\n }\n const id = matches[2] ?? null;\n const resource = matches[1] ?? null;\n\n return {id, resource};\n}\n\n/**\n * Filters properties from an object and returns a new object with only the properties that have a truthy value.\n * @param keyValuePairs - An object of key-value pairs\n * @param formattedData - An object which will hold the truthy values\n * @returns The formatted object\n **/\nexport function addDataIf(\n keyValuePairs: ShopifyMonorailPayload,\n formattedData: ShopifyMonorailPayload,\n): ShopifyMonorailPayload {\n if (typeof keyValuePairs !== 'object') {\n return {};\n }\n Object.entries(keyValuePairs).forEach(([key, value]) => {\n if (value) {\n formattedData[key] = value;\n }\n });\n return formattedData;\n}\n\n/**\n * Utility that errors if a function is called on the server.\n * @param fnName - The name of the function\n * @returns A boolean\n **/\nexport function errorIfServer(fnName: string): boolean {\n if (typeof document === 'undefined') {\n console.error(\n `${fnName} should only be used within the useEffect callback or event handlers`,\n );\n return true;\n }\n return false;\n}\n"],"names":[],"mappings":"AAYgB,SAAA,cACd,UACA,SACsB;AACf,SAAA;AAAA,IACL,WAAW;AAAA,IACX;AAAA,IACA,UAAU;AAAA,MACR,qBAAqB,KAAK,IAAI;AAAA,IAChC;AAAA,EAAA;AAEJ;AAgBO,SAAS,SAAS,KAAqC;AAC5D,QAAM,gBAAgB,EAAC,IAAI,IAAI,UAAU,KAAI;AAEzC,MAAA,OAAO,QAAQ,UAAU;AACpB,WAAA;AAAA,EACT;AAIM,QAAA,UAAU,IAAI,MAAM,kCAAkC;AAE5D,MAAI,CAAC,WAAW,QAAQ,WAAW,GAAG;AAC7B,WAAA;AAAA,EACT;AACM,QAAA,KAAK,QAAQ,CAAC,KAAK;AACnB,QAAA,WAAW,QAAQ,CAAC,KAAK;AAExB,SAAA,EAAC,IAAI;AACd;AAQgB,SAAA,UACd,eACA,eACwB;AACpB,MAAA,OAAO,kBAAkB,UAAU;AACrC,WAAO;EACT;AACO,SAAA,QAAQ,aAAa,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AACtD,QAAI,OAAO;AACT,oBAAc,GAAG,IAAI;AAAA,IACvB;AAAA,EAAA,CACD;AACM,SAAA;AACT;AAOO,SAAS,cAAc,QAAyB;AACjD,MAAA,OAAO,aAAa,aAAa;AAC3B,YAAA;AAAA,MACN,GAAG;AAAA,IAAA;AAEE,WAAA;AAAA,EACT;AACO,SAAA;AACT;"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AddToCartButton } from "./AddToCartButton.mjs";
|
|
2
2
|
import { getClientBrowserParameters, sendShopifyAnalytics } from "./analytics.mjs";
|
|
3
3
|
import { AnalyticsEventName, AnalyticsPageType, ShopifySalesChannel } from "./analytics-constants.mjs";
|
|
4
|
+
import { parseGid } from "./analytics-utils.mjs";
|
|
4
5
|
import { BuyNowButton } from "./BuyNowButton.mjs";
|
|
5
6
|
import { SHOPIFY_S, SHOPIFY_STOREFRONT_ID_HEADER, SHOPIFY_STOREFRONT_S_HEADER, SHOPIFY_STOREFRONT_Y_HEADER, SHOPIFY_Y } from "./cart-constants.mjs";
|
|
6
7
|
import { CartCheckoutButton } from "./CartCheckoutButton.mjs";
|
|
@@ -58,6 +59,7 @@ export {
|
|
|
58
59
|
flattenConnection,
|
|
59
60
|
getClientBrowserParameters,
|
|
60
61
|
getShopifyCookies,
|
|
62
|
+
parseGid,
|
|
61
63
|
parseMetafield,
|
|
62
64
|
sendShopifyAnalytics,
|
|
63
65
|
storefrontApiCustomScalars,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\ntype StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n *\n * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient(\n props: StorefrontClientProps,\n): StorefrontClientReturn {\n const {\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion,\n contentType,\n } = props;\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `StorefrontClient: The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting. You may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (__HYDROGEN_DEV__ && !privateStorefrontToken && !globalThis.document) {\n warnOnce(\n `StorefrontClient: Using a private storefront token is recommended for server environments. Refer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n `StorefrontClient: You are attempting to use a private token in an environment where it can be easily accessed by anyone. This is a security risk; please use the public token and the 'publicStorefrontToken' prop`,\n );\n }\n\n return {\n getShopifyDomain(overrideProps): string {\n return overrideProps?.storeDomain ?? storeDomain;\n },\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl = overrideProps?.storeDomain ?? storeDomain;\n return `${finalDomainUrl}${finalDomainUrl.endsWith('/') ? '' : '/'}api/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (!privateStorefrontToken && !overrideProps?.privateStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'privateStorefrontToken' while using 'getPrivateTokenHeaders()'`,\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n `StorefrontClient: it is recommended to pass in the 'buyerIp' property which improves analytics and data in the admin.`,\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (!publicStorefrontToken && !overrideProps?.publicStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'publicStorefrontToken' while using 'getPublicTokenHeaders()'`,\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst warnOnce = (string: string): void => {\n if (!warnings.has(string)) {\n console.warn(string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAwBO,SAAS,uBACd,OACwB;AAClB,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACE,IAAA;AAEJ,MAAI,yBAAyB,eAAe;AAC1C;AAAA,MACE,+NAA+N,4CAA4C;AAAA,IAAA;AAAA,EAE/Q;AAGA,MAAwB,CAAC,0BAA0B,CAAC,WAAW,UAAU;AACvE;AAAA,MACE;AAAA,IAAA;AAAA,EAEJ;AAGI,MAAoB,0BAA0B,WAAW,UAAU;AACrE;AAAA,MACE;AAAA,IAAA;AAAA,E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,MAAM,WAAW,CAAC,WAAyB;AACzC,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACzB,YAAQ,KAAK,MAAM;AACnB,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
|
|
1
|
+
{"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n *\n * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient(\n props: StorefrontClientProps,\n): StorefrontClientReturn {\n const {\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion,\n contentType,\n } = props;\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `StorefrontClient: The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting. You may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (__HYDROGEN_DEV__ && !privateStorefrontToken && !globalThis.document) {\n warnOnce(\n `StorefrontClient: Using a private storefront token is recommended for server environments. Refer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n `StorefrontClient: You are attempting to use a private token in an environment where it can be easily accessed by anyone. This is a security risk; please use the public token and the 'publicStorefrontToken' prop`,\n );\n }\n\n return {\n getShopifyDomain(overrideProps): string {\n return overrideProps?.storeDomain ?? storeDomain;\n },\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl = overrideProps?.storeDomain ?? storeDomain;\n return `${finalDomainUrl}${finalDomainUrl.endsWith('/') ? '' : '/'}api/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (!privateStorefrontToken && !overrideProps?.privateStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'privateStorefrontToken' while using 'getPrivateTokenHeaders()'`,\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n `StorefrontClient: it is recommended to pass in the 'buyerIp' property which improves analytics and data in the admin.`,\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (!publicStorefrontToken && !overrideProps?.publicStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'publicStorefrontToken' while using 'getPublicTokenHeaders()'`,\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst warnOnce = (string: string): void => {\n if (!warnings.has(string)) {\n console.warn(string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAwBO,SAAS,uBACd,OACwB;AAClB,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACE,IAAA;AAEJ,MAAI,yBAAyB,eAA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;AAEgB,SAAA,yBACd,aACA,sBACA,aAOA;AACO,SAAA;AAAA;AAAA,IAEL,gBACE,gBAAgB,YAAY,wBAAwB;AAAA,IACtD,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,IACxB,iBAAiB;AAAA,IACjB,qCAAqC;AAAA,EAAA;AAEzC;AAEA,MAAM,+BAAe;AACrB,MAAM,WAAW,CAAC,WAAyB;AACzC,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACzB,YAAQ,KAAK,MAAM;AACnB,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
|
|
@@ -14,10 +14,10 @@ function BuyNowButton(props) {
|
|
|
14
14
|
...passthroughProps
|
|
15
15
|
} = props;
|
|
16
16
|
useEffect(() => {
|
|
17
|
-
if (checkoutUrl) {
|
|
17
|
+
if (loading && checkoutUrl) {
|
|
18
18
|
window.location.href = checkoutUrl;
|
|
19
19
|
}
|
|
20
|
-
}, [checkoutUrl]);
|
|
20
|
+
}, [loading, checkoutUrl]);
|
|
21
21
|
const handleBuyNow = useCallback(() => {
|
|
22
22
|
setLoading(true);
|
|
23
23
|
cartCreate({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BuyNowButton.mjs","sources":["../../src/BuyNowButton.tsx"],"sourcesContent":["import {useEffect, useState, useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ninterface BuyNowButtonPropsBase {\n /** The item quantity. Defaults to 1. */\n quantity?: number;\n /** The ID of the variant. */\n variantId: string;\n /** An array of cart line attributes that belong to the item being added to the cart. */\n attributes?: {\n key: string;\n value: string;\n }[];\n}\n\ntype BuyNowButtonProps<AsType extends React.ElementType = 'button'> =\n BuyNowButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `BuyNowButton` component renders a button that adds an item to the cart and redirects the customer to checkout.\n * Must be a child of a `CartProvider` component.\n */\nexport function BuyNowButton<AsType extends React.ElementType = 'button'>(\n props: BuyNowButtonProps<AsType>,\n): JSX.Element {\n const {cartCreate, checkoutUrl} = useCart();\n const [loading, setLoading] = useState<boolean>(false);\n\n const {\n quantity,\n variantId,\n onClick,\n attributes,\n children,\n ...passthroughProps\n } = props;\n\n useEffect(() => {\n if (checkoutUrl) {\n window.location.href = checkoutUrl;\n }\n }, [checkoutUrl]);\n\n const handleBuyNow = useCallback(() => {\n setLoading(true);\n cartCreate({\n lines: [\n {\n quantity: quantity ?? 1,\n merchandiseId: variantId,\n attributes,\n },\n ],\n });\n }, [cartCreate, quantity, variantId, attributes]);\n\n return (\n <BaseButton\n disabled={loading ?? passthroughProps.disabled}\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleBuyNow}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface BuyNowButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends BuyNowButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n"],"names":[],"mappings":";;;;AA2BO,SAAS,aACd,OACa;AACb,QAAM,EAAC,YAAY,YAAW,IAAI,QAAQ;AAC1C,QAAM,CAAC,SAAS,UAAU,IAAI,SAAkB,KAAK;AAE/C,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AAEJ,YAAU,MAAM;AACd,QAAI,aAAa;
|
|
1
|
+
{"version":3,"file":"BuyNowButton.mjs","sources":["../../src/BuyNowButton.tsx"],"sourcesContent":["import {useEffect, useState, useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ninterface BuyNowButtonPropsBase {\n /** The item quantity. Defaults to 1. */\n quantity?: number;\n /** The ID of the variant. */\n variantId: string;\n /** An array of cart line attributes that belong to the item being added to the cart. */\n attributes?: {\n key: string;\n value: string;\n }[];\n}\n\ntype BuyNowButtonProps<AsType extends React.ElementType = 'button'> =\n BuyNowButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `BuyNowButton` component renders a button that adds an item to the cart and redirects the customer to checkout.\n * Must be a child of a `CartProvider` component.\n */\nexport function BuyNowButton<AsType extends React.ElementType = 'button'>(\n props: BuyNowButtonProps<AsType>,\n): JSX.Element {\n const {cartCreate, checkoutUrl} = useCart();\n const [loading, setLoading] = useState<boolean>(false);\n\n const {\n quantity,\n variantId,\n onClick,\n attributes,\n children,\n ...passthroughProps\n } = props;\n\n useEffect(() => {\n if (loading && checkoutUrl) {\n window.location.href = checkoutUrl;\n }\n }, [loading, checkoutUrl]);\n\n const handleBuyNow = useCallback(() => {\n setLoading(true);\n cartCreate({\n lines: [\n {\n quantity: quantity ?? 1,\n merchandiseId: variantId,\n attributes,\n },\n ],\n });\n }, [cartCreate, quantity, variantId, attributes]);\n\n return (\n <BaseButton\n disabled={loading ?? passthroughProps.disabled}\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleBuyNow}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface BuyNowButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends BuyNowButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n"],"names":[],"mappings":";;;;AA2BO,SAAS,aACd,OACa;AACb,QAAM,EAAC,YAAY,YAAW,IAAI,QAAQ;AAC1C,QAAM,CAAC,SAAS,UAAU,IAAI,SAAkB,KAAK;AAE/C,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AAEJ,YAAU,MAAM;AACd,QAAI,WAAW,aAAa;AAC1B,aAAO,SAAS,OAAO;AAAA,IACzB;AAAA,EAAA,GACC,CAAC,SAAS,WAAW,CAAC;AAEnB,QAAA,eAAe,YAAY,MAAM;AACrC,eAAW,IAAI;AACJ,eAAA;AAAA,MACT,OAAO;AAAA,QACL;AAAA,UACE,UAAU,YAAY;AAAA,UACtB,eAAe;AAAA,UACf;AAAA,QACF;AAAA,MACF;AAAA,IAAA,CACD;AAAA,KACA,CAAC,YAAY,UAAU,WAAW,UAAU,CAAC;AAG9C,SAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,UAAU,WAAW,iBAAiB;AAAA,MACrC,GAAG;AAAA,MACJ;AAAA,MACA,gBAAgB;AAAA,MAEf;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 intervals: number;\n startingWidth: number;\n incrementSize: number;\n placeholderWidth: number;\n};\n\ntype HtmlImageProps = React.DetailedHTMLProps<\n React.ImgHTMLAttributes<HTMLImageElement>,\n HTMLImageElement\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/** Legacy type for backwards compatibility *\n * @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop. Or pass a custom `loader` with `LoaderParams` */\nexport type ShopifyLoaderOptions = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: HtmlImageProps['width'] | ImageType['width'];\n /** The URL param that controls height */\n height?: HtmlImageProps['height'] | ImageType['height'];\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\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.ImgHTMLAttributes<HTMLImageElement> & {\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` object. Must be an Image object.\n * Optionally, import the `IMAGE_FRAGMENT` to use in your GraphQL queries.\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 key?: React.Key;\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 /** @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop */\n loaderOptions?: ShopifyLoaderOptions;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n /** @deprecated Autocalculated, use only `width` prop, or srcSetOptions */\n widths?: (HtmlImageProps['width'] | ImageType['width'])[];\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrgen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loaderOptions,\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 widths,\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Deprecated Props from original Image component\n */\n if (__HYDROGEN_DEV__) {\n if (loaderOptions) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `Use the \\`crop\\`, \\`width\\`, \\`height\\`, and src props, or`,\n `the \\`data\\` prop to achieve the same result. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n if (widths) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `\\`widths\\` are now calculated automatically based on the`,\n `config and width props. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n }\n\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FixedWidthImage({\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n ref,\n width,\n}: FixedWidthImageProps) {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all of the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop);\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [aspectRatio, crop, height, imageWidths, loader, normalizedProps, width]);\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\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FluidImage({\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n ref,\n sizes,\n}: FluidImageProps) {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n}\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href;\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return (\n typeof width === 'number' ||\n (typeof width === 'string' && fixedEndings.test(width))\n );\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n const sizes = imageWidths.map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n });\n return sizes;\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n"],"names":[],"mappings":";;AA8HO,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;AAAA,IACA,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;AAAA,IACA,GAAG;AAAA,KAEL,QACG;AAiCG,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,SAAS,WAAW;AAE3C,YAAA,aAAa,WAAW,UAAa,WAAW;AACtD,YAAM,cAAc,aAChB,OACA,kBAAkB,O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AAA,CACZ,KAAK,WAAW,WAAW,IAAI,GAAG,IAAI,OAAO,GAAG,KAAK,SAAS;AAAA,EAAA,EAElE,KAAK,IAAI;AACd;AAUO,SAAS,oBACd,QAAyB,QACzB,WACA,eACA,eACU;AACV,QAAM,aAAa,MAAM;AAAA,IACvB,EAAC,QAAQ,UAAS;AAAA,IAClB,CAAC,GAAG,MAAM,IAAI,gBAAgB;AAAA,EAAA;AAGhC,QAAM,QAAQ,MAAM;AAAA,IAClB,EAAC,QAAQ,EAAC;AAAA,IACV,CAAC,GAAG,OAAO,IAAI,MAAM,uBAAuB,KAAK,KAAK;AAAA,EAAA;AAGjD,SAAA,aAAa,KAAK,IAAI,QAAQ;AACvC;AASO,SAAS,iBAAiB,aAA0C;AACzE,MAAI,CAAC;AAAa;AAClB,QAAM,CAAC,OAAO,MAAM,IAAI,YAAY,MAAM,GAAG;AAC7C,SAAO,KAAK,OAAO,KAAK,IAAI,OAAO,MAAM;AAC3C;AAGO,SAAS,cACd,aACA,aACA,OAAa,UAOD;AACZ,MAAI,CAAC;AAAa;AAClB,QAAM,QAAQ,YAAY,IAAI,CAAC,UAAkB;AACxC,WAAA;AAAA,MACL;AAAA,MACA,QAAQ,cACJ,SAAS,iBAAiB,WAAW,KAAK,KAC1C;AAAA,MACJ;AAAA,IAAA;AAAA,EACF,CACD;AACM,SAAA;AAQT;"}
|
|
1
|
+
{"version":3,"file":"Image.mjs","sources":["../../src/Image.tsx"],"sourcesContent":["/* eslint-disable eslint-comments/disable-enable-pair */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable hydrogen/prefer-image-component */\nimport * as React from 'react';\nimport type {PartialDeep} from 'type-fest';\nimport type {Image as ImageType} from './storefront-api-types.js';\n\n/*\n * An optional prop you can use to change the\n * default srcSet generation behaviour\n */\ntype SrcSetOptions = {\n intervals: number;\n startingWidth: number;\n incrementSize: number;\n placeholderWidth: number;\n};\n\ntype HtmlImageProps = React.DetailedHTMLProps<\n React.ImgHTMLAttributes<HTMLImageElement>,\n HTMLImageElement\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/** Legacy type for backwards compatibility *\n * @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop. Or pass a custom `loader` with `LoaderParams` */\nexport type ShopifyLoaderOptions = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: HtmlImageProps['width'] | ImageType['width'];\n /** The URL param that controls height */\n height?: HtmlImageProps['height'] | ImageType['height'];\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\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/2023-04/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n /** @deprecated Use `crop`, `width`, `height`, and `src` props, and/or `data` prop */\n loaderOptions?: ShopifyLoaderOptions;\n /** @deprecated Autocalculated, use only `width` prop, or srcSetOptions */\n widths?: (HtmlImageProps['width'] | ImageType['width'])[];\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrgen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loaderOptions,\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 widths,\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Deprecated Props from original Image component\n */\n if (__HYDROGEN_DEV__) {\n if (loaderOptions) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `Use the \\`crop\\`, \\`width\\`, \\`height\\`, and src props, or`,\n `the \\`data\\` prop to achieve the same result. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n if (widths) {\n console.warn(\n [\n `Deprecated property from original Image component in use:`,\n `\\`widths\\` are now calculated automatically based on the`,\n `config and width props. Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n }\n\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FixedWidthImage({\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n ref,\n width,\n}: FixedWidthImageProps) {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all of the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop);\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [aspectRatio, crop, height, imageWidths, loader, normalizedProps, width]);\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\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n};\n\nfunction FluidImage({\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n ref,\n sizes,\n}: FluidImageProps) {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n}\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href;\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return (\n typeof width === 'number' ||\n (typeof width === 'string' && fixedEndings.test(width))\n );\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n const sizes = imageWidths.map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n });\n return sizes;\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n"],"names":[],"mappings":";;AA+HO,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;AAAA,IACA,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;AAAA,IACA,GAAG;AAAA,KAEL,QACG;AAiCG,UAAA,iBAAiB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AAA,MACL;AAAA,MACA,QAAQ,cACJ,SAAS,iBAAiB,WAAW,KAAK,KAC1C;AAAA,MACJ;AAAA,IAAA;AAAA,EACF,CACD;AACM,SAAA;AAQT;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics-utils.mjs","sources":["../../src/analytics-utils.ts"],"sourcesContent":["import type {\n ShopifyMonorailPayload,\n ShopifyMonorailEvent,\n
|
|
1
|
+
{"version":3,"file":"analytics-utils.mjs","sources":["../../src/analytics-utils.ts"],"sourcesContent":["import type {\n ShopifyMonorailPayload,\n ShopifyMonorailEvent,\n ShopifyGid,\n} from './analytics-types.js';\n\n/**\n * Builds a Shopify Monorail event from a Shopify Monorail payload and a schema ID.\n * @param payload - The Monorail payload\n * @param schemaId - The schema ID to use\n * @returns The formatted payload\n **/\nexport function schemaWrapper(\n schemaId: string,\n payload: ShopifyMonorailPayload,\n): ShopifyMonorailEvent {\n return {\n schema_id: schemaId,\n payload,\n metadata: {\n event_created_at_ms: Date.now(),\n },\n };\n}\n\n/**\n * Parses global id (gid) and returns the resource type and id.\n * @see https://shopify.dev/api/usage/gids\n * @param gid - A shopify GID (string)\n *\n * @example\n * ```ts\n * const {id, resource} = parseGid('gid://shopify/Order/123')\n * // => id = \"123\", resource = 'Order'\n *\n * * const {id, resource} = parseGid('gid://shopify/Cart/abc123')\n * // => id = \"abc123\", resource = 'Cart'\n * ```\n **/\nexport function parseGid(gid: string | undefined): ShopifyGid {\n const defaultReturn = {id: '', resource: null};\n\n if (typeof gid !== 'string') {\n return defaultReturn;\n }\n\n // TODO: add support for parsing query parameters on complex gids\n // Reference: https://shopify.dev/api/usage/gids\n const matches = gid.match(/^gid:\\/\\/shopify\\/(\\w+)\\/([^/]+)/);\n\n if (!matches || matches.length === 1) {\n return defaultReturn;\n }\n const id = matches[2] ?? null;\n const resource = matches[1] ?? null;\n\n return {id, resource};\n}\n\n/**\n * Filters properties from an object and returns a new object with only the properties that have a truthy value.\n * @param keyValuePairs - An object of key-value pairs\n * @param formattedData - An object which will hold the truthy values\n * @returns The formatted object\n **/\nexport function addDataIf(\n keyValuePairs: ShopifyMonorailPayload,\n formattedData: ShopifyMonorailPayload,\n): ShopifyMonorailPayload {\n if (typeof keyValuePairs !== 'object') {\n return {};\n }\n Object.entries(keyValuePairs).forEach(([key, value]) => {\n if (value) {\n formattedData[key] = value;\n }\n });\n return formattedData;\n}\n\n/**\n * Utility that errors if a function is called on the server.\n * @param fnName - The name of the function\n * @returns A boolean\n **/\nexport function errorIfServer(fnName: string): boolean {\n if (typeof document === 'undefined') {\n console.error(\n `${fnName} should only be used within the useEffect callback or event handlers`,\n );\n return true;\n }\n return false;\n}\n"],"names":[],"mappings":"AAYgB,SAAA,cACd,UACA,SACsB;AACf,SAAA;AAAA,IACL,WAAW;AAAA,IACX;AAAA,IACA,UAAU;AAAA,MACR,qBAAqB,KAAK,IAAI;AAAA,IAChC;AAAA,EAAA;AAEJ;AAgBO,SAAS,SAAS,KAAqC;AAC5D,QAAM,gBAAgB,EAAC,IAAI,IAAI,UAAU,KAAI;AAEzC,MAAA,OAAO,QAAQ,UAAU;AACpB,WAAA;AAAA,EACT;AAIM,QAAA,UAAU,IAAI,MAAM,kCAAkC;AAE5D,MAAI,CAAC,WAAW,QAAQ,WAAW,GAAG;AAC7B,WAAA;AAAA,EACT;AACM,QAAA,KAAK,QAAQ,CAAC,KAAK;AACnB,QAAA,WAAW,QAAQ,CAAC,KAAK;AAExB,SAAA,EAAC,IAAI;AACd;AAQgB,SAAA,UACd,eACA,eACwB;AACpB,MAAA,OAAO,kBAAkB,UAAU;AACrC,WAAO;EACT;AACO,SAAA,QAAQ,aAAa,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AACtD,QAAI,OAAO;AACT,oBAAc,GAAG,IAAI;AAAA,IACvB;AAAA,EAAA,CACD;AACM,SAAA;AACT;AAOO,SAAS,cAAc,QAAyB;AACjD,MAAA,OAAO,aAAa,aAAa;AAC3B,YAAA;AAAA,MACN,GAAG;AAAA,IAAA;AAEE,WAAA;AAAA,EACT;AACO,SAAA;AACT;"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AddToCartButton } from "./AddToCartButton.mjs";
|
|
2
2
|
import { getClientBrowserParameters, sendShopifyAnalytics } from "./analytics.mjs";
|
|
3
3
|
import { AnalyticsEventName, AnalyticsPageType, ShopifySalesChannel } from "./analytics-constants.mjs";
|
|
4
|
+
import { parseGid } from "./analytics-utils.mjs";
|
|
4
5
|
import { BuyNowButton } from "./BuyNowButton.mjs";
|
|
5
6
|
import { SHOPIFY_S, SHOPIFY_STOREFRONT_ID_HEADER, SHOPIFY_STOREFRONT_S_HEADER, SHOPIFY_STOREFRONT_Y_HEADER, SHOPIFY_Y } from "./cart-constants.mjs";
|
|
6
7
|
import { CartCheckoutButton } from "./CartCheckoutButton.mjs";
|
|
@@ -58,6 +59,7 @@ export {
|
|
|
58
59
|
flattenConnection,
|
|
59
60
|
getClientBrowserParameters,
|
|
60
61
|
getShopifyCookies,
|
|
62
|
+
parseGid,
|
|
61
63
|
parseMetafield,
|
|
62
64
|
sendShopifyAnalytics,
|
|
63
65
|
storefrontApiCustomScalars,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\ntype StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n *\n * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient(\n props: StorefrontClientProps,\n): StorefrontClientReturn {\n const {\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion,\n contentType,\n } = props;\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `StorefrontClient: The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting. You may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (__HYDROGEN_DEV__ && !privateStorefrontToken && !globalThis.document) {\n warnOnce(\n `StorefrontClient: Using a private storefront token is recommended for server environments. Refer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n `StorefrontClient: You are attempting to use a private token in an environment where it can be easily accessed by anyone. This is a security risk; please use the public token and the 'publicStorefrontToken' prop`,\n );\n }\n\n return {\n getShopifyDomain(overrideProps): string {\n return overrideProps?.storeDomain ?? storeDomain;\n },\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl = overrideProps?.storeDomain ?? storeDomain;\n return `${finalDomainUrl}${finalDomainUrl.endsWith('/') ? '' : '/'}api/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (!privateStorefrontToken && !overrideProps?.privateStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'privateStorefrontToken' while using 'getPrivateTokenHeaders()'`,\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n `StorefrontClient: it is recommended to pass in the 'buyerIp' property which improves analytics and data in the admin.`,\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (!publicStorefrontToken && !overrideProps?.publicStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'publicStorefrontToken' while using 'getPublicTokenHeaders()'`,\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst warnOnce = (string: string): void => {\n if (!warnings.has(string)) {\n console.warn(string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAwBO,SAAS,uBACd,OACwB;AAClB,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACE,IAAA;AAEJ,MAAI,yBAAyB,eAAe;AAC1C;AAAA,MACE,+NAA+N,4CAA4C;AAAA,IAAA;AAAA,EAE/Q;AAgBO,SAAA;AAAA,IACL,iBAAiB,eAAuB;AACtC,cAAO,+CAAe,gBAAe;AAAA,IACvC;AAAA,IACA,oBAAoB,eAAuB;AACnC,YAAA,kBAAiB,+CAAe,gBAAe;AAC9C,aAAA,GAAG,iBAAiB,eAAe,SAAS,GAAG,IAAI,KAAK,WAC7D,+CAAe,yBAAwB;AAAA,IAE3C;AAAA,IACA,uBAAuB,eAAuC;AAC5D,UAAI,CAAC,0BAA0B,EAAC,+CAAe,yBAAwB;AACrE,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAAA,MAEJ;AAQM,YAAA,oBAAmB,+CAAe,gBAAe;AAEhD,aAAA;AAAA;AAAA,QAEL,gBACE,qBAAqB,YACjB,wBACA;AAAA,QACN,iBAAiB;AAAA,QACjB,wBAAwB;AAAA,QACxB,iBAAiB;AAAA,QACjB,qCACE,+CAAe,2BAA0B,0BAA0B;AAAA,QACrE,IAAI,+CAAe,WACf,EAAC,+BAA+B,cAAc,QAAA,IAC9C,CAAC;AAAA,MAAA;AAAA,IAET;AAAA,IACA,sBAAsB,eAAuC;AAC3D,UAAI,CAAC,yBAAyB,EAAC,+CAAe,wBAAuB;AACnE,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAAA,MAEJ;AAEM,YAAA,oBACJ,+CAAe,gBAAe,eAAe;AAExC,aAAA;AAAA,QACL;AAAA,QACA;AAAA,SACA,+CAAe,0BAAyB,yBAAyB;AAAA,MAAA;AAAA,IAErE;AAAA,EAAA;AAEJ;AAEgB,SAAA,yBACd,aACA,sBACA,aAOA;AACO,SAAA;AAAA;AAAA,IAEL,gBACE,gBAAgB,YAAY,wBAAwB;AAAA,IACtD,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,IACxB,iBAAiB;AAAA,IACjB,qCAAqC;AAAA,EAAA;AAEzC;AAEA,MAAM,+BAAe;AACrB,MAAM,WAAW,CAAC,WAAyB;AACzC,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACzB,YAAQ,KAAK,MAAM;AACnB,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
|
|
1
|
+
{"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: string;\n /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n storefrontApiVersion: string;\n /**\n * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n *\n * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient(\n props: StorefrontClientProps,\n): StorefrontClientReturn {\n const {\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion,\n contentType,\n } = props;\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `StorefrontClient: The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting. You may run into unexpected errors if these versions don't match. Received verion: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (__HYDROGEN_DEV__ && !privateStorefrontToken && !globalThis.document) {\n warnOnce(\n `StorefrontClient: Using a private storefront token is recommended for server environments. Refer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n `StorefrontClient: You are attempting to use a private token in an environment where it can be easily accessed by anyone. This is a security risk; please use the public token and the 'publicStorefrontToken' prop`,\n );\n }\n\n return {\n getShopifyDomain(overrideProps): string {\n return overrideProps?.storeDomain ?? storeDomain;\n },\n getStorefrontApiUrl(overrideProps): string {\n const finalDomainUrl = overrideProps?.storeDomain ?? storeDomain;\n return `${finalDomainUrl}${finalDomainUrl.endsWith('/') ? '' : '/'}api/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (!privateStorefrontToken && !overrideProps?.privateStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'privateStorefrontToken' while using 'getPrivateTokenHeaders()'`,\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n `StorefrontClient: it is recommended to pass in the 'buyerIp' property which improves analytics and data in the admin.`,\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (!publicStorefrontToken && !overrideProps?.publicStorefrontToken) {\n throw new Error(\n `StorefrontClient: You did not pass in a 'publicStorefrontToken' while using 'getPublicTokenHeaders()'`,\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst warnOnce = (string: string): void => {\n if (!warnings.has(string)) {\n console.warn(string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\n /**\n * Creates the fully-qualified URL to your myshopify.com domain.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\n /**\n * Creates the fully-qualified URL to your store's GraphQL endpoint.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAwBO,SAAS,uBACd,OACwB;AAClB,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACE,IAAA;AAEJ,MAAI,yBAAyB,eAAe;AAC1C;AAAA,MACE,+NAA+N,4CAA4C;AAAA,IAAA;AAAA,EAE/Q;AAgBO,SAAA;AAAA,IACL,iBAAiB,eAAuB;AACtC,cAAO,+CAAe,gBAAe;AAAA,IACvC;AAAA,IACA,oBAAoB,eAAuB;AACnC,YAAA,kBAAiB,+CAAe,gBAAe;AAC9C,aAAA,GAAG,iBAAiB,eAAe,SAAS,GAAG,IAAI,KAAK,WAC7D,+CAAe,yBAAwB;AAAA,IAE3C;AAAA,IACA,uBAAuB,eAAuC;AAC5D,UAAI,CAAC,0BAA0B,EAAC,+CAAe,yBAAwB;AACrE,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAAA,MAEJ;AAQM,YAAA,oBAAmB,+CAAe,gBAAe;AAEhD,aAAA;AAAA;AAAA,QAEL,gBACE,qBAAqB,YACjB,wBACA;AAAA,QACN,iBAAiB;AAAA,QACjB,wBAAwB;AAAA,QACxB,iBAAiB;AAAA,QACjB,qCACE,+CAAe,2BAA0B,0BAA0B;AAAA,QACrE,IAAI,+CAAe,WACf,EAAC,+BAA+B,cAAc,QAAA,IAC9C,CAAC;AAAA,MAAA;AAAA,IAET;AAAA,IACA,sBAAsB,eAAuC;AAC3D,UAAI,CAAC,yBAAyB,EAAC,+CAAe,wBAAuB;AACnE,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAAA,MAEJ;AAEM,YAAA,oBACJ,+CAAe,gBAAe,eAAe;AAExC,aAAA;AAAA,QACL;AAAA,QACA;AAAA,SACA,+CAAe,0BAAyB,yBAAyB;AAAA,MAAA;AAAA,IAErE;AAAA,EAAA;AAEJ;AAEgB,SAAA,yBACd,aACA,sBACA,aAOA;AACO,SAAA;AAAA;AAAA,IAEL,gBACE,gBAAgB,YAAY,wBAAwB;AAAA,IACtD,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,IACxB,iBAAiB;AAAA,IACjB,qCAAqC;AAAA,EAAA;AAEzC;AAEA,MAAM,+BAAe;AACrB,MAAM,WAAW,CAAC,WAAyB;AACzC,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACzB,YAAQ,KAAK,MAAM;AACnB,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
|
|
@@ -16,10 +16,10 @@ function BuyNowButton(props) {
|
|
|
16
16
|
...passthroughProps
|
|
17
17
|
} = props;
|
|
18
18
|
React.useEffect(() => {
|
|
19
|
-
if (checkoutUrl) {
|
|
19
|
+
if (loading && checkoutUrl) {
|
|
20
20
|
window.location.href = checkoutUrl;
|
|
21
21
|
}
|
|
22
|
-
}, [checkoutUrl]);
|
|
22
|
+
}, [loading, checkoutUrl]);
|
|
23
23
|
const handleBuyNow = React.useCallback(() => {
|
|
24
24
|
setLoading(true);
|
|
25
25
|
cartCreate({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BuyNowButton.js","sources":["../../src/BuyNowButton.tsx"],"sourcesContent":["import {useEffect, useState, useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ninterface BuyNowButtonPropsBase {\n /** The item quantity. Defaults to 1. */\n quantity?: number;\n /** The ID of the variant. */\n variantId: string;\n /** An array of cart line attributes that belong to the item being added to the cart. */\n attributes?: {\n key: string;\n value: string;\n }[];\n}\n\ntype BuyNowButtonProps<AsType extends React.ElementType = 'button'> =\n BuyNowButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `BuyNowButton` component renders a button that adds an item to the cart and redirects the customer to checkout.\n * Must be a child of a `CartProvider` component.\n */\nexport function BuyNowButton<AsType extends React.ElementType = 'button'>(\n props: BuyNowButtonProps<AsType>,\n): JSX.Element {\n const {cartCreate, checkoutUrl} = useCart();\n const [loading, setLoading] = useState<boolean>(false);\n\n const {\n quantity,\n variantId,\n onClick,\n attributes,\n children,\n ...passthroughProps\n } = props;\n\n useEffect(() => {\n if (checkoutUrl) {\n window.location.href = checkoutUrl;\n }\n }, [checkoutUrl]);\n\n const handleBuyNow = useCallback(() => {\n setLoading(true);\n cartCreate({\n lines: [\n {\n quantity: quantity ?? 1,\n merchandiseId: variantId,\n attributes,\n },\n ],\n });\n }, [cartCreate, quantity, variantId, attributes]);\n\n return (\n <BaseButton\n disabled={loading ?? passthroughProps.disabled}\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleBuyNow}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface BuyNowButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends BuyNowButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n"],"names":["useCart","useState","useEffect","useCallback","jsx","BaseButton"],"mappings":";;;;;;AA2BO,SAAS,aACd,OACa;AACb,QAAM,EAAC,YAAY,YAAW,IAAIA,aAAQ,QAAA;AAC1C,QAAM,CAAC,SAAS,UAAU,IAAIC,eAAkB,KAAK;AAE/C,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AAEJC,QAAAA,UAAU,MAAM;AACd,QAAI,aAAa;
|
|
1
|
+
{"version":3,"file":"BuyNowButton.js","sources":["../../src/BuyNowButton.tsx"],"sourcesContent":["import {useEffect, useState, useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {\n BaseButton,\n type BaseButtonProps,\n type CustomBaseButtonProps,\n} from './BaseButton.js';\n\ninterface BuyNowButtonPropsBase {\n /** The item quantity. Defaults to 1. */\n quantity?: number;\n /** The ID of the variant. */\n variantId: string;\n /** An array of cart line attributes that belong to the item being added to the cart. */\n attributes?: {\n key: string;\n value: string;\n }[];\n}\n\ntype BuyNowButtonProps<AsType extends React.ElementType = 'button'> =\n BuyNowButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `BuyNowButton` component renders a button that adds an item to the cart and redirects the customer to checkout.\n * Must be a child of a `CartProvider` component.\n */\nexport function BuyNowButton<AsType extends React.ElementType = 'button'>(\n props: BuyNowButtonProps<AsType>,\n): JSX.Element {\n const {cartCreate, checkoutUrl} = useCart();\n const [loading, setLoading] = useState<boolean>(false);\n\n const {\n quantity,\n variantId,\n onClick,\n attributes,\n children,\n ...passthroughProps\n } = props;\n\n useEffect(() => {\n if (loading && checkoutUrl) {\n window.location.href = checkoutUrl;\n }\n }, [loading, checkoutUrl]);\n\n const handleBuyNow = useCallback(() => {\n setLoading(true);\n cartCreate({\n lines: [\n {\n quantity: quantity ?? 1,\n merchandiseId: variantId,\n attributes,\n },\n ],\n });\n }, [cartCreate, quantity, variantId, attributes]);\n\n return (\n <BaseButton\n disabled={loading ?? passthroughProps.disabled}\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleBuyNow}\n >\n {children}\n </BaseButton>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface BuyNowButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends BuyNowButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n"],"names":["useCart","useState","useEffect","useCallback","jsx","BaseButton"],"mappings":";;;;;;AA2BO,SAAS,aACd,OACa;AACb,QAAM,EAAC,YAAY,YAAW,IAAIA,aAAQ,QAAA;AAC1C,QAAM,CAAC,SAAS,UAAU,IAAIC,eAAkB,KAAK;AAE/C,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AAEJC,QAAAA,UAAU,MAAM;AACd,QAAI,WAAW,aAAa;AAC1B,aAAO,SAAS,OAAO;AAAA,IACzB;AAAA,EAAA,GACC,CAAC,SAAS,WAAW,CAAC;AAEnB,QAAA,eAAeC,MAAAA,YAAY,MAAM;AACrC,eAAW,IAAI;AACJ,eAAA;AAAA,MACT,OAAO;AAAA,QACL;AAAA,UACE,UAAU,YAAY;AAAA,UACtB,eAAe;AAAA,UACf;AAAA,QACF;AAAA,MACF;AAAA,IAAA,CACD;AAAA,KACA,CAAC,YAAY,UAAU,WAAW,UAAU,CAAC;AAG9C,SAAAC,2BAAA;AAAA,IAACC,WAAA;AAAA,IAAA;AAAA,MACC,UAAU,WAAW,iBAAiB;AAAA,MACrC,GAAG;AAAA,MACJ;AAAA,MACA,gBAAgB;AAAA,MAEf;AAAA,IAAA;AAAA,EAAA;AAGP;;"}
|