@shopify/hydrogen-react 2023.7.2 → 2023.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser-dev/AddToCartButton.mjs +2 -1
- package/dist/browser-dev/AddToCartButton.mjs.map +1 -1
- package/dist/browser-dev/BaseButton.mjs.map +1 -1
- package/dist/browser-dev/BuyNowButton.mjs.map +1 -1
- package/dist/browser-dev/CartLineQuantityAdjustButton.mjs +2 -1
- package/dist/browser-dev/CartLineQuantityAdjustButton.mjs.map +1 -1
- package/dist/browser-dev/Image.mjs +111 -101
- package/dist/browser-dev/Image.mjs.map +1 -1
- package/dist/browser-dev/Money.mjs.map +1 -1
- package/dist/browser-dev/ProductPrice.mjs.map +1 -1
- package/dist/browser-prod/AddToCartButton.mjs +2 -1
- package/dist/browser-prod/AddToCartButton.mjs.map +1 -1
- package/dist/browser-prod/BaseButton.mjs.map +1 -1
- package/dist/browser-prod/BuyNowButton.mjs.map +1 -1
- package/dist/browser-prod/CartLineQuantityAdjustButton.mjs +2 -1
- package/dist/browser-prod/CartLineQuantityAdjustButton.mjs.map +1 -1
- package/dist/browser-prod/Image.mjs +111 -101
- package/dist/browser-prod/Image.mjs.map +1 -1
- package/dist/browser-prod/Money.mjs.map +1 -1
- package/dist/browser-prod/ProductPrice.mjs.map +1 -1
- package/dist/node-dev/AddToCartButton.js +2 -1
- package/dist/node-dev/AddToCartButton.js.map +1 -1
- package/dist/node-dev/AddToCartButton.mjs +2 -1
- package/dist/node-dev/AddToCartButton.mjs.map +1 -1
- package/dist/node-dev/BaseButton.js.map +1 -1
- package/dist/node-dev/BaseButton.mjs.map +1 -1
- package/dist/node-dev/BuyNowButton.js.map +1 -1
- package/dist/node-dev/BuyNowButton.mjs.map +1 -1
- package/dist/node-dev/CartLineQuantityAdjustButton.js +2 -1
- package/dist/node-dev/CartLineQuantityAdjustButton.js.map +1 -1
- package/dist/node-dev/CartLineQuantityAdjustButton.mjs +2 -1
- package/dist/node-dev/CartLineQuantityAdjustButton.mjs.map +1 -1
- package/dist/node-dev/Image.js +111 -101
- package/dist/node-dev/Image.js.map +1 -1
- package/dist/node-dev/Image.mjs +111 -101
- package/dist/node-dev/Image.mjs.map +1 -1
- package/dist/node-dev/Money.js.map +1 -1
- package/dist/node-dev/Money.mjs.map +1 -1
- package/dist/node-dev/ProductPrice.js.map +1 -1
- package/dist/node-dev/ProductPrice.mjs.map +1 -1
- package/dist/node-prod/AddToCartButton.js +2 -1
- package/dist/node-prod/AddToCartButton.js.map +1 -1
- package/dist/node-prod/AddToCartButton.mjs +2 -1
- package/dist/node-prod/AddToCartButton.mjs.map +1 -1
- package/dist/node-prod/BaseButton.js.map +1 -1
- package/dist/node-prod/BaseButton.mjs.map +1 -1
- package/dist/node-prod/BuyNowButton.js.map +1 -1
- package/dist/node-prod/BuyNowButton.mjs.map +1 -1
- package/dist/node-prod/CartLineQuantityAdjustButton.js +2 -1
- package/dist/node-prod/CartLineQuantityAdjustButton.js.map +1 -1
- package/dist/node-prod/CartLineQuantityAdjustButton.mjs +2 -1
- package/dist/node-prod/CartLineQuantityAdjustButton.mjs.map +1 -1
- package/dist/node-prod/Image.js +111 -101
- package/dist/node-prod/Image.js.map +1 -1
- package/dist/node-prod/Image.mjs +111 -101
- package/dist/node-prod/Image.mjs.map +1 -1
- package/dist/node-prod/Money.js.map +1 -1
- package/dist/node-prod/Money.mjs.map +1 -1
- package/dist/node-prod/ProductPrice.js.map +1 -1
- package/dist/node-prod/ProductPrice.mjs.map +1 -1
- package/dist/types/BaseButton.d.ts +1 -1
- package/dist/types/Money.d.ts +1 -1
- package/dist/types/ProductPrice.d.ts +1 -1
- package/dist/types/storefront-api-types.d.ts +18 -17
- package/dist/umd/hydrogen-react.dev.js +115 -103
- 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 +2 -2
- package/storefront.schema.json +1 -1
|
@@ -18,7 +18,8 @@ function AddToCartButton(props) {
|
|
|
18
18
|
const { status, linesAdd } = useCart();
|
|
19
19
|
const { selectedVariant } = useProduct();
|
|
20
20
|
const variantId = explicitVariantId ?? (selectedVariant == null ? void 0 : selectedVariant.id) ?? "";
|
|
21
|
-
const disabled = explicitVariantId === null || variantId === "" || selectedVariant === null || addingItem ||
|
|
21
|
+
const disabled = explicitVariantId === null || variantId === "" || selectedVariant === null || addingItem || // Only certain 'as' types such as 'button' contain `disabled`
|
|
22
|
+
passthroughProps.disabled;
|
|
22
23
|
useEffect(() => {
|
|
23
24
|
if (addingItem && status === "idle") {
|
|
24
25
|
setAddingItem(false);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AddToCartButton.mjs","sources":["../../src/AddToCartButton.tsx"],"sourcesContent":["import {useCallback, useEffect, useState} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {useProduct} from './ProductProvider.js';\nimport {\n BaseButton,\n type CustomBaseButtonProps,\n type BaseButtonProps,\n} from './BaseButton.js';\nimport * as React from 'react';\n\nexport interface AddToCartButtonPropsBase {\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 /** The ID of the variant. */\n variantId?: string | null;\n /** The item quantity. */\n quantity?: number;\n /** The text that is announced by the screen reader when the item is being added to the cart. Used for accessibility purposes only and not displayed on the page. */\n accessibleAddingToCartLabel?: string;\n /** The selling plan ID of the subscription variant */\n sellingPlanId?: string;\n}\n\nexport type AddToCartButtonProps<AsType extends React.ElementType = 'button'> =\n AddToCartButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `AddToCartButton` component renders a button that adds an item to the cart when pressed.\n * It must be a descendent of the `CartProvider` component.\n */\nexport function AddToCartButton<AsType extends React.ElementType = 'button'>(\n props: AddToCartButtonProps<AsType>,\n): JSX.Element {\n const [addingItem, setAddingItem] = useState<boolean>(false);\n const {\n variantId: explicitVariantId,\n quantity = 1,\n attributes,\n sellingPlanId,\n onClick,\n children,\n accessibleAddingToCartLabel,\n ...passthroughProps\n } = props;\n const {status, linesAdd} = useCart();\n const {selectedVariant} = useProduct();\n const variantId = explicitVariantId ?? selectedVariant?.id ?? '';\n const disabled =\n explicitVariantId === null ||\n variantId === '' ||\n selectedVariant === null ||\n addingItem ||\n passthroughProps.disabled;\n\n useEffect(() => {\n if (addingItem && status === 'idle') {\n setAddingItem(false);\n }\n }, [status, addingItem]);\n\n const handleAddItem = useCallback(() => {\n setAddingItem(true);\n linesAdd([\n {\n quantity,\n merchandiseId: variantId || '',\n attributes,\n sellingPlanId,\n },\n ]);\n }, [linesAdd, quantity, variantId, attributes, sellingPlanId]);\n\n return (\n <>\n <BaseButton\n {...passthroughProps}\n disabled={disabled}\n onClick={onClick}\n defaultOnClick={handleAddItem}\n >\n {children}\n </BaseButton>\n {accessibleAddingToCartLabel ? (\n <p\n style={{\n position: 'absolute',\n width: '1px',\n height: '1px',\n padding: '0',\n margin: '-1px',\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n borderWidth: '0',\n }}\n role=\"alert\"\n aria-live=\"assertive\"\n >\n {addingItem ? accessibleAddingToCartLabel : null}\n </p>\n ) : null}\n </>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface AddToCartButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends AddToCartButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n"],"names":[],"mappings":";;;;;AAiCO,SAAS,gBACd,OACa;AACb,QAAM,CAAC,YAAY,aAAa,IAAI,SAAkB,KAAK;AACrD,QAAA;AAAA,IACJ,WAAW;AAAA,IACX,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AACJ,QAAM,EAAC,QAAQ,SAAQ,IAAI,QAAQ;AAC7B,QAAA,EAAC,oBAAmB;AACpB,QAAA,YAAY,sBAAqB,mDAAiB,OAAM;
|
|
1
|
+
{"version":3,"file":"AddToCartButton.mjs","sources":["../../src/AddToCartButton.tsx"],"sourcesContent":["import {useCallback, useEffect, useState} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {useProduct} from './ProductProvider.js';\nimport {\n BaseButton,\n type CustomBaseButtonProps,\n type BaseButtonProps,\n} from './BaseButton.js';\nimport * as React from 'react';\n\nexport interface AddToCartButtonPropsBase {\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 /** The ID of the variant. */\n variantId?: string | null;\n /** The item quantity. */\n quantity?: number;\n /** The text that is announced by the screen reader when the item is being added to the cart. Used for accessibility purposes only and not displayed on the page. */\n accessibleAddingToCartLabel?: string;\n /** The selling plan ID of the subscription variant */\n sellingPlanId?: string;\n}\n\nexport type AddToCartButtonProps<AsType extends React.ElementType = 'button'> =\n AddToCartButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `AddToCartButton` component renders a button that adds an item to the cart when pressed.\n * It must be a descendent of the `CartProvider` component.\n */\nexport function AddToCartButton<AsType extends React.ElementType = 'button'>(\n props: AddToCartButtonProps<AsType>,\n): JSX.Element {\n const [addingItem, setAddingItem] = useState<boolean>(false);\n const {\n variantId: explicitVariantId,\n quantity = 1,\n attributes,\n sellingPlanId,\n onClick,\n children,\n accessibleAddingToCartLabel,\n ...passthroughProps\n } = props;\n const {status, linesAdd} = useCart();\n const {selectedVariant} = useProduct();\n const variantId = explicitVariantId ?? selectedVariant?.id ?? '';\n const disabled =\n explicitVariantId === null ||\n variantId === '' ||\n selectedVariant === null ||\n addingItem ||\n // Only certain 'as' types such as 'button' contain `disabled`\n (passthroughProps as {disabled?: boolean}).disabled;\n\n useEffect(() => {\n if (addingItem && status === 'idle') {\n setAddingItem(false);\n }\n }, [status, addingItem]);\n\n const handleAddItem = useCallback(() => {\n setAddingItem(true);\n linesAdd([\n {\n quantity,\n merchandiseId: variantId || '',\n attributes,\n sellingPlanId,\n },\n ]);\n }, [linesAdd, quantity, variantId, attributes, sellingPlanId]);\n\n return (\n <>\n <BaseButton\n {...passthroughProps}\n disabled={disabled}\n onClick={onClick}\n defaultOnClick={handleAddItem}\n >\n {children}\n </BaseButton>\n {accessibleAddingToCartLabel ? (\n <p\n style={{\n position: 'absolute',\n width: '1px',\n height: '1px',\n padding: '0',\n margin: '-1px',\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n borderWidth: '0',\n }}\n role=\"alert\"\n aria-live=\"assertive\"\n >\n {addingItem ? accessibleAddingToCartLabel : null}\n </p>\n ) : null}\n </>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface AddToCartButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends AddToCartButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n"],"names":[],"mappings":";;;;;AAiCO,SAAS,gBACd,OACa;AACb,QAAM,CAAC,YAAY,aAAa,IAAI,SAAkB,KAAK;AACrD,QAAA;AAAA,IACJ,WAAW;AAAA,IACX,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AACJ,QAAM,EAAC,QAAQ,SAAQ,IAAI,QAAQ;AAC7B,QAAA,EAAC,oBAAmB;AACpB,QAAA,YAAY,sBAAqB,mDAAiB,OAAM;AAC9D,QAAM,WACJ,sBAAsB,QACtB,cAAc,MACd,oBAAoB,QACpB;AAAA,EAEC,iBAA0C;AAE7C,YAAU,MAAM;AACV,QAAA,cAAc,WAAW,QAAQ;AACnC,oBAAc,KAAK;AAAA,IACrB;AAAA,EAAA,GACC,CAAC,QAAQ,UAAU,CAAC;AAEjB,QAAA,gBAAgB,YAAY,MAAM;AACtC,kBAAc,IAAI;AACT,aAAA;AAAA,MACP;AAAA,QACE;AAAA,QACA,eAAe,aAAa;AAAA,QAC5B;AAAA,QACA;AAAA,MACF;AAAA,IAAA,CACD;AAAA,EAAA,GACA,CAAC,UAAU,UAAU,WAAW,YAAY,aAAa,CAAC;AAE7D,SAEI,qBAAA,UAAA,EAAA,UAAA;AAAA,IAAA;AAAA,MAAC;AAAA,MAAA;AAAA,QACE,GAAG;AAAA,QACJ;AAAA,QACA;AAAA,QACA,gBAAgB;AAAA,QAEf;AAAA,MAAA;AAAA,IACH;AAAA,IACC,8BACC;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,OAAO;AAAA,UACL,UAAU;AAAA,UACV,OAAO;AAAA,UACP,QAAQ;AAAA,UACR,SAAS;AAAA,UACT,QAAQ;AAAA,UACR,UAAU;AAAA,UACV,MAAM;AAAA,UACN,YAAY;AAAA,UACZ,aAAa;AAAA,QACf;AAAA,QACA,MAAK;AAAA,QACL,aAAU;AAAA,QAET,uBAAa,8BAA8B;AAAA,MAAA;AAAA,IAAA,IAE5C;AAAA,EACN,EAAA,CAAA;AAEJ;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseButton.mjs","sources":["../../src/BaseButton.tsx"],"sourcesContent":["import {ReactNode, Ref, useCallback} from 'react';\n\nexport interface CustomBaseButtonProps<AsType> {\n /** Provide a React element or component to render as the underlying button. Note: for accessibility compliance, almost always you should use a `button` element, or a component that renders an underlying button. */\n as?: AsType;\n /** Any ReactNode elements. */\n children: ReactNode;\n /** Click event handler. Default behaviour triggers unless prevented */\n onClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A default `onClick` behavior */\n defaultOnClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A `ref` to the underlying button */\n buttonRef?: Ref<HTMLButtonElement>;\n}\n\nexport type BaseButtonProps<AsType extends React.ElementType> =\n CustomBaseButtonProps<AsType> &\n Omit<\n
|
|
1
|
+
{"version":3,"file":"BaseButton.mjs","sources":["../../src/BaseButton.tsx"],"sourcesContent":["import {ReactNode, Ref, useCallback} from 'react';\n\nexport interface CustomBaseButtonProps<AsType> {\n /** Provide a React element or component to render as the underlying button. Note: for accessibility compliance, almost always you should use a `button` element, or a component that renders an underlying button. */\n as?: AsType;\n /** Any ReactNode elements. */\n children: ReactNode;\n /** Click event handler. Default behaviour triggers unless prevented */\n onClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A default `onClick` behavior */\n defaultOnClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A `ref` to the underlying button */\n buttonRef?: Ref<HTMLButtonElement>;\n}\n\nexport type BaseButtonProps<AsType extends React.ElementType> =\n CustomBaseButtonProps<AsType> &\n (AsType extends keyof React.JSX.IntrinsicElements\n ? Omit<\n React.ComponentPropsWithoutRef<AsType>,\n keyof CustomBaseButtonProps<AsType>\n >\n : React.ComponentPropsWithoutRef<AsType>);\n\nexport function BaseButton<AsType extends React.ElementType = 'button'>(\n props: BaseButtonProps<AsType>,\n): JSX.Element {\n const {\n as,\n onClick,\n defaultOnClick,\n children,\n buttonRef,\n ...passthroughProps\n } = props;\n\n const handleOnClick = useCallback(\n (event?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {\n if (onClick) {\n const clickShouldContinue = onClick(event);\n if (\n (typeof clickShouldContinue === 'boolean' &&\n clickShouldContinue === false) ||\n event?.defaultPrevented\n )\n return;\n }\n\n defaultOnClick?.(event);\n },\n [defaultOnClick, onClick],\n );\n\n const Component = as || 'button';\n\n return (\n <Component ref={buttonRef} onClick={handleOnClick} {...passthroughProps}>\n {children}\n </Component>\n );\n}\n"],"names":[],"mappings":";;AA4BO,SAAS,WACd,OACa;AACP,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AAEJ,QAAM,gBAAgB;AAAA,IACpB,CAAC,UAA4D;AAC3D,UAAI,SAAS;AACL,cAAA,sBAAsB,QAAQ,KAAK;AACzC,YACG,OAAO,wBAAwB,aAC9B,wBAAwB,UAC1B,+BAAO;AAEP;AAAA,MACJ;AAEA,uDAAiB;AAAA,IACnB;AAAA,IACA,CAAC,gBAAgB,OAAO;AAAA,EAAA;AAG1B,QAAM,YAAY,MAAM;AAGtB,SAAA,oBAAC,aAAU,KAAK,WAAW,SAAS,eAAgB,GAAG,kBACpD,SACH,CAAA;AAEJ;"}
|
|
@@ -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 (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,
|
|
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 // Only certain 'as' types such as 'button' contain `disabled`\n disabled={loading ?? (passthroughProps as {disabled?: boolean}).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,MAEC,UAAU,WAAY,iBAA0C;AAAA,MAC/D,GAAG;AAAA,MACJ;AAAA,MACA,gBAAgB;AAAA,MAEf;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
@@ -31,13 +31,14 @@ function CartLineQuantityAdjustButton(props) {
|
|
|
31
31
|
linesRemove,
|
|
32
32
|
linesUpdate
|
|
33
33
|
]);
|
|
34
|
+
const disabledAttr = passthroughProps.disabled;
|
|
34
35
|
return /* @__PURE__ */ jsx(
|
|
35
36
|
BaseButton,
|
|
36
37
|
{
|
|
37
38
|
...passthroughProps,
|
|
38
39
|
onClick,
|
|
39
40
|
defaultOnClick: handleAdjust,
|
|
40
|
-
disabled: typeof
|
|
41
|
+
disabled: typeof disabledAttr !== "undefined" ? disabledAttr : status !== "idle",
|
|
41
42
|
children
|
|
42
43
|
}
|
|
43
44
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CartLineQuantityAdjustButton.mjs","sources":["../../src/CartLineQuantityAdjustButton.tsx"],"sourcesContent":["import {useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {useCartLine} from './CartLineProvider.js';\nimport {BaseButton, type BaseButtonProps} from './BaseButton.js';\nimport type {CartLineUpdateInput} from './storefront-api-types.js';\n\ninterface CartLineQuantityAdjustButtonBaseProps {\n /** The adjustment for a cart line's quantity. Valid values: `increase` (default), `decrease`, or `remove`. */\n adjust?: 'increase' | 'decrease' | 'remove';\n}\n\ntype CartLineQuantityAdjustButtonProps<\n AsType extends React.ElementType = 'button',\n> = BaseButtonProps<AsType> & CartLineQuantityAdjustButtonBaseProps;\n\n/**\n * The `<CartLineQuantityAdjustButton />` component renders a button that adjusts the cart line's quantity when pressed.\n *\n * It must be a descendent of `<CartLineProvider/>` and `<CartProvider/>`.\n */\nexport function CartLineQuantityAdjustButton<\n AsType extends React.ElementType = 'button',\n>(props: CartLineQuantityAdjustButtonProps<AsType>): JSX.Element {\n const {status, linesRemove, linesUpdate} = useCart();\n const cartLine = useCartLine();\n const {children, adjust, onClick, ...passthroughProps} = props;\n\n const handleAdjust = useCallback(() => {\n if (adjust === 'remove') {\n linesRemove([cartLine?.id ?? '']);\n return;\n }\n\n const quantity =\n adjust === 'decrease'\n ? (cartLine?.quantity ?? 0) - 1\n : (cartLine?.quantity ?? 0) + 1;\n\n if (quantity <= 0) {\n linesRemove([cartLine?.id ?? '']);\n return;\n }\n\n const lineUpdate = {\n id: cartLine?.id ?? '',\n quantity,\n attributes: (cartLine?.attributes ??\n []) as CartLineUpdateInput['attributes'],\n } satisfies CartLineUpdateInput;\n\n linesUpdate([lineUpdate]);\n }, [\n adjust,\n cartLine?.attributes,\n cartLine?.id,\n cartLine?.quantity,\n linesRemove,\n linesUpdate,\n ]);\n\n return (\n <BaseButton\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleAdjust}\n disabled={\n typeof
|
|
1
|
+
{"version":3,"file":"CartLineQuantityAdjustButton.mjs","sources":["../../src/CartLineQuantityAdjustButton.tsx"],"sourcesContent":["import {useCallback} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {useCartLine} from './CartLineProvider.js';\nimport {BaseButton, type BaseButtonProps} from './BaseButton.js';\nimport type {CartLineUpdateInput} from './storefront-api-types.js';\n\ninterface CartLineQuantityAdjustButtonBaseProps {\n /** The adjustment for a cart line's quantity. Valid values: `increase` (default), `decrease`, or `remove`. */\n adjust?: 'increase' | 'decrease' | 'remove';\n}\n\ntype CartLineQuantityAdjustButtonProps<\n AsType extends React.ElementType = 'button',\n> = BaseButtonProps<AsType> & CartLineQuantityAdjustButtonBaseProps;\n\n/**\n * The `<CartLineQuantityAdjustButton />` component renders a button that adjusts the cart line's quantity when pressed.\n *\n * It must be a descendent of `<CartLineProvider/>` and `<CartProvider/>`.\n */\nexport function CartLineQuantityAdjustButton<\n AsType extends React.ElementType = 'button',\n>(props: CartLineQuantityAdjustButtonProps<AsType>): JSX.Element {\n const {status, linesRemove, linesUpdate} = useCart();\n const cartLine = useCartLine();\n const {children, adjust, onClick, ...passthroughProps} = props;\n\n const handleAdjust = useCallback(() => {\n if (adjust === 'remove') {\n linesRemove([cartLine?.id ?? '']);\n return;\n }\n\n const quantity =\n adjust === 'decrease'\n ? (cartLine?.quantity ?? 0) - 1\n : (cartLine?.quantity ?? 0) + 1;\n\n if (quantity <= 0) {\n linesRemove([cartLine?.id ?? '']);\n return;\n }\n\n const lineUpdate = {\n id: cartLine?.id ?? '',\n quantity,\n attributes: (cartLine?.attributes ??\n []) as CartLineUpdateInput['attributes'],\n } satisfies CartLineUpdateInput;\n\n linesUpdate([lineUpdate]);\n }, [\n adjust,\n cartLine?.attributes,\n cartLine?.id,\n cartLine?.quantity,\n linesRemove,\n linesUpdate,\n ]);\n\n // Only certain 'as' types such as 'button' contain `disabled`\n const disabledAttr = (passthroughProps as {disabled?: boolean}).disabled;\n\n return (\n <BaseButton\n {...passthroughProps}\n onClick={onClick}\n defaultOnClick={handleAdjust}\n disabled={\n typeof disabledAttr !== 'undefined' ? disabledAttr : status !== 'idle'\n }\n >\n {children}\n </BaseButton>\n );\n}\n"],"names":[],"mappings":";;;;;AAoBO,SAAS,6BAEd,OAA+D;AAC/D,QAAM,EAAC,QAAQ,aAAa,gBAAe,QAAQ;AACnD,QAAM,WAAW;AACjB,QAAM,EAAC,UAAU,QAAQ,SAAS,GAAG,iBAAoB,IAAA;AAEnD,QAAA,eAAe,YAAY,MAAM;AACrC,QAAI,WAAW,UAAU;AACvB,kBAAY,EAAC,qCAAU,OAAM,EAAE,CAAC;AAChC;AAAA,IACF;AAEM,UAAA,WACJ,WAAW,eACN,qCAAU,aAAY,KAAK,MAC3B,qCAAU,aAAY,KAAK;AAElC,QAAI,YAAY,GAAG;AACjB,kBAAY,EAAC,qCAAU,OAAM,EAAE,CAAC;AAChC;AAAA,IACF;AAEA,UAAM,aAAa;AAAA,MACjB,KAAI,qCAAU,OAAM;AAAA,MACpB;AAAA,MACA,aAAa,qCAAU,eACrB,CAAC;AAAA,IAAA;AAGO,gBAAA,CAAC,UAAU,CAAC;AAAA,EAAA,GACvB;AAAA,IACD;AAAA,IACA,qCAAU;AAAA,IACV,qCAAU;AAAA,IACV,qCAAU;AAAA,IACV;AAAA,IACA;AAAA,EAAA,CACD;AAGD,QAAM,eAAgB,iBAA0C;AAG9D,SAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACE,GAAG;AAAA,MACJ;AAAA,MACA,gBAAgB;AAAA,MAChB,UACE,OAAO,iBAAiB,cAAc,eAAe,WAAW;AAAA,MAGjE;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
@@ -153,108 +153,118 @@ const Image = React.forwardRef(
|
|
|
153
153
|
}
|
|
154
154
|
}
|
|
155
155
|
);
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
}) {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
loading,
|
|
215
|
-
normalizedProps,
|
|
216
|
-
passthroughProps,
|
|
217
|
-
placeholderWidth,
|
|
218
|
-
ref,
|
|
219
|
-
sizes
|
|
220
|
-
}) {
|
|
221
|
-
const fluid = React.useMemo(() => {
|
|
222
|
-
const sizesArray = imageWidths === void 0 ? void 0 : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);
|
|
223
|
-
const placeholderHeight = normalizedProps.aspectRatio && placeholderWidth ? placeholderWidth * (parseAspectRatio(normalizedProps.aspectRatio) ?? 1) : void 0;
|
|
224
|
-
const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);
|
|
225
|
-
const src = loader({
|
|
226
|
-
src: normalizedProps.src,
|
|
227
|
-
width: placeholderWidth,
|
|
228
|
-
height: placeholderHeight,
|
|
229
|
-
crop
|
|
230
|
-
});
|
|
231
|
-
return {
|
|
232
|
-
placeholderHeight,
|
|
233
|
-
srcSet,
|
|
234
|
-
src
|
|
235
|
-
};
|
|
236
|
-
}, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);
|
|
237
|
-
return /* @__PURE__ */ jsx(
|
|
238
|
-
"img",
|
|
239
|
-
{
|
|
240
|
-
ref,
|
|
241
|
-
alt: normalizedProps.alt,
|
|
242
|
-
decoding,
|
|
243
|
-
height: fluid.placeholderHeight,
|
|
244
|
-
loading,
|
|
245
|
-
sizes,
|
|
246
|
-
src: fluid.src,
|
|
247
|
-
srcSet: fluid.srcSet,
|
|
248
|
-
width: placeholderWidth,
|
|
249
|
-
...passthroughProps,
|
|
250
|
-
style: {
|
|
251
|
-
width: normalizedProps.width,
|
|
252
|
-
aspectRatio: normalizedProps.aspectRatio,
|
|
253
|
-
...passthroughProps.style
|
|
156
|
+
const FixedWidthImage = React.forwardRef(
|
|
157
|
+
({
|
|
158
|
+
aspectRatio,
|
|
159
|
+
crop,
|
|
160
|
+
decoding,
|
|
161
|
+
height,
|
|
162
|
+
imageWidths,
|
|
163
|
+
loader = shopifyLoader,
|
|
164
|
+
loading,
|
|
165
|
+
normalizedProps,
|
|
166
|
+
passthroughProps,
|
|
167
|
+
width
|
|
168
|
+
}, ref) => {
|
|
169
|
+
const fixed = React.useMemo(() => {
|
|
170
|
+
const intWidth = getNormalizedFixedUnit(width);
|
|
171
|
+
const intHeight = getNormalizedFixedUnit(height);
|
|
172
|
+
const fixedAspectRatio = aspectRatio ? aspectRatio : unitsMatch(normalizedProps.width, normalizedProps.height) ? [intWidth, intHeight].join("/") : normalizedProps.aspectRatio ? normalizedProps.aspectRatio : void 0;
|
|
173
|
+
const sizesArray = imageWidths === void 0 ? void 0 : generateSizes(imageWidths, fixedAspectRatio, crop);
|
|
174
|
+
const fixedHeight = intHeight ? intHeight : fixedAspectRatio && intWidth ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1) : void 0;
|
|
175
|
+
const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);
|
|
176
|
+
const src = loader({
|
|
177
|
+
src: normalizedProps.src,
|
|
178
|
+
width: intWidth,
|
|
179
|
+
height: fixedHeight,
|
|
180
|
+
crop: normalizedProps.height === "auto" ? void 0 : crop
|
|
181
|
+
});
|
|
182
|
+
return {
|
|
183
|
+
width: intWidth,
|
|
184
|
+
aspectRatio: fixedAspectRatio,
|
|
185
|
+
height: fixedHeight,
|
|
186
|
+
srcSet,
|
|
187
|
+
src
|
|
188
|
+
};
|
|
189
|
+
}, [
|
|
190
|
+
aspectRatio,
|
|
191
|
+
crop,
|
|
192
|
+
height,
|
|
193
|
+
imageWidths,
|
|
194
|
+
loader,
|
|
195
|
+
normalizedProps,
|
|
196
|
+
width
|
|
197
|
+
]);
|
|
198
|
+
return /* @__PURE__ */ jsx(
|
|
199
|
+
"img",
|
|
200
|
+
{
|
|
201
|
+
ref,
|
|
202
|
+
alt: normalizedProps.alt,
|
|
203
|
+
decoding,
|
|
204
|
+
height: fixed.height,
|
|
205
|
+
loading,
|
|
206
|
+
src: fixed.src,
|
|
207
|
+
srcSet: fixed.srcSet,
|
|
208
|
+
width: fixed.width,
|
|
209
|
+
style: {
|
|
210
|
+
aspectRatio: fixed.aspectRatio,
|
|
211
|
+
...passthroughProps.style
|
|
212
|
+
},
|
|
213
|
+
...passthroughProps
|
|
254
214
|
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
);
|
|
218
|
+
const FluidImage = React.forwardRef(
|
|
219
|
+
({
|
|
220
|
+
crop,
|
|
221
|
+
decoding,
|
|
222
|
+
imageWidths,
|
|
223
|
+
loader = shopifyLoader,
|
|
224
|
+
loading,
|
|
225
|
+
normalizedProps,
|
|
226
|
+
passthroughProps,
|
|
227
|
+
placeholderWidth,
|
|
228
|
+
sizes
|
|
229
|
+
}, ref) => {
|
|
230
|
+
const fluid = React.useMemo(() => {
|
|
231
|
+
const sizesArray = imageWidths === void 0 ? void 0 : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);
|
|
232
|
+
const placeholderHeight = normalizedProps.aspectRatio && placeholderWidth ? placeholderWidth * (parseAspectRatio(normalizedProps.aspectRatio) ?? 1) : void 0;
|
|
233
|
+
const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);
|
|
234
|
+
const src = loader({
|
|
235
|
+
src: normalizedProps.src,
|
|
236
|
+
width: placeholderWidth,
|
|
237
|
+
height: placeholderHeight,
|
|
238
|
+
crop
|
|
239
|
+
});
|
|
240
|
+
return {
|
|
241
|
+
placeholderHeight,
|
|
242
|
+
srcSet,
|
|
243
|
+
src
|
|
244
|
+
};
|
|
245
|
+
}, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);
|
|
246
|
+
return /* @__PURE__ */ jsx(
|
|
247
|
+
"img",
|
|
248
|
+
{
|
|
249
|
+
ref,
|
|
250
|
+
alt: normalizedProps.alt,
|
|
251
|
+
decoding,
|
|
252
|
+
height: fluid.placeholderHeight,
|
|
253
|
+
loading,
|
|
254
|
+
sizes,
|
|
255
|
+
src: fluid.src,
|
|
256
|
+
srcSet: fluid.srcSet,
|
|
257
|
+
width: placeholderWidth,
|
|
258
|
+
...passthroughProps,
|
|
259
|
+
style: {
|
|
260
|
+
width: normalizedProps.width,
|
|
261
|
+
aspectRatio: normalizedProps.aspectRatio,
|
|
262
|
+
...passthroughProps.style
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
);
|
|
258
268
|
function shopifyLoader({ src, width, height, crop }) {
|
|
259
269
|
if (!src) {
|
|
260
270
|
return "";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Image.mjs","sources":["../../src/Image.tsx"],"sourcesContent":["/* eslint-disable eslint-comments/disable-enable-pair */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable hydrogen/prefer-image-component */\nimport * as React from 'react';\nimport type {PartialDeep} from 'type-fest';\nimport type {Image as ImageType} from './storefront-api-types.js';\n\n/*\n * An optional prop you can use to change the\n * default srcSet generation behaviour\n */\ntype SrcSetOptions = {\n /** The number of sizes to generate */\n intervals: number;\n /** The smallest image size */\n startingWidth: number;\n /** The increment by which to increase for each size, in pixels */\n incrementSize: number;\n /** The size used for placeholder fallback images */\n placeholderWidth: number;\n};\n\ntype 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-07/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n /** @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":";;AAmIO,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,SAC/C;AAAA,UAAA,EACA,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,SAC/C;AAAA,UAAA,EACA,KAAK,GAAG;AAAA,QAAA;AAAA,MAEd;AAAA,IACF;AAKM,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B,KAAK,KAAK;AAAA,EAAA;AAGjD,SAAA,aAAa,KAAK,IAAI,QAAQ;AACvC;AASO,SAAS,iBAAiB,aAA0C;AACzE,MAAI,CAAC;AAAa;AAClB,QAAM,CAAC,OAAO,MAAM,IAAI,YAAY,MAAM,GAAG;AAC7C,SAAO,KAAK,OAAO,KAAK,IAAI,OAAO,MAAM;AAC3C;AAGO,SAAS,cACd,aACA,aACA,OAAa,UAOD;AACZ,MAAI,CAAC;AAAa;AAClB,QAAM,QAAQ,YAAY,IAAI,CAAC,UAAkB;AACxC,WAAA;AAAA,MACL;AAAA,MACA,QAAQ,cACJ,SAAS,iBAAiB,WAAW,KAAK,KAC1C;AAAA,MACJ;AAAA,IAAA;AAAA,EACF,CACD;AACM,SAAA;AAQT;"}
|
|
1
|
+
{"version":3,"file":"Image.mjs","sources":["../../src/Image.tsx"],"sourcesContent":["/* eslint-disable eslint-comments/disable-enable-pair */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable hydrogen/prefer-image-component */\nimport * as React from 'react';\nimport type {PartialDeep} from 'type-fest';\nimport type {Image as ImageType} from './storefront-api-types.js';\n\n/*\n * An optional prop you can use to change the\n * default srcSet generation behaviour\n */\ntype SrcSetOptions = {\n /** The number of sizes to generate */\n intervals: number;\n /** The smallest image size */\n startingWidth: number;\n /** The increment by which to increase for each size, in pixels */\n incrementSize: number;\n /** The size used for placeholder fallback images */\n placeholderWidth: number;\n};\n\ntype 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-07/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n /** @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\nconst FixedWidthImage = React.forwardRef<\n HTMLImageElement,\n FixedWidthImageProps\n>(\n (\n {\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n width,\n },\n ref,\n ) => {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all of the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop);\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [\n aspectRatio,\n crop,\n height,\n imageWidths,\n loader,\n normalizedProps,\n width,\n ]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fixed.height}\n loading={loading}\n src={fixed.src}\n srcSet={fixed.srcSet}\n width={fixed.width}\n style={{\n aspectRatio: fixed.aspectRatio,\n ...passthroughProps.style,\n }}\n {...passthroughProps}\n />\n );\n },\n);\n\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n};\n\nconst FluidImage = React.forwardRef<HTMLImageElement, FluidImageProps>(\n (\n {\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n sizes,\n },\n ref,\n ) => {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop);\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n },\n);\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href;\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return (\n typeof width === 'number' ||\n (typeof width === 'string' && fixedEndings.test(width))\n );\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n const sizes = imageWidths.map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n });\n return sizes;\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n"],"names":[],"mappings":";;AAmIO,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,SAC/C;AAAA,UAAA,EACA,KAAK,GAAG;AAAA,QAAA;AAAA,MAEd;AAEA,UAAI,QAAQ;AACF,gBAAA;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,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Money.mjs","sources":["../../src/Money.tsx"],"sourcesContent":["import {type ReactNode} from 'react';\nimport {useMoney} from './useMoney.js';\nimport type {MoneyV2, UnitPriceMeasurement} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface MoneyPropsBase<ComponentGeneric extends React.ElementType> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `div`. */\n as?: ComponentGeneric;\n /** An object with fields that correspond to the Storefront API's [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2). */\n data: PartialDeep<MoneyV2, {recurseIntoArrays: true}>;\n /** Whether to remove the currency symbol from the output. */\n withoutCurrency?: boolean;\n /** Whether to remove trailing zeros (fractional money) from the output. */\n withoutTrailingZeros?: boolean;\n /** A [UnitPriceMeasurement object](https://shopify.dev/api/storefront/2023-07/objects/unitpricemeasurement). */\n measurement?: PartialDeep<UnitPriceMeasurement, {recurseIntoArrays: true}>;\n /** Customizes the separator between the money output and the measurement output. Used with the `measurement` prop. Defaults to `'/'`. */\n measurementSeparator?: ReactNode;\n}\n\n// This article helps understand the typing here https://www.benmvp.com/blog/polymorphic-react-components-typescript/ Ben is the best :)\nexport type MoneyProps<ComponentGeneric extends React.ElementType> =\n MoneyPropsBase<ComponentGeneric> &\n Omit<\n
|
|
1
|
+
{"version":3,"file":"Money.mjs","sources":["../../src/Money.tsx"],"sourcesContent":["import {type ReactNode} from 'react';\nimport {useMoney} from './useMoney.js';\nimport type {MoneyV2, UnitPriceMeasurement} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface MoneyPropsBase<ComponentGeneric extends React.ElementType> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `div`. */\n as?: ComponentGeneric;\n /** An object with fields that correspond to the Storefront API's [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2). */\n data: PartialDeep<MoneyV2, {recurseIntoArrays: true}>;\n /** Whether to remove the currency symbol from the output. */\n withoutCurrency?: boolean;\n /** Whether to remove trailing zeros (fractional money) from the output. */\n withoutTrailingZeros?: boolean;\n /** A [UnitPriceMeasurement object](https://shopify.dev/api/storefront/2023-07/objects/unitpricemeasurement). */\n measurement?: PartialDeep<UnitPriceMeasurement, {recurseIntoArrays: true}>;\n /** Customizes the separator between the money output and the measurement output. Used with the `measurement` prop. Defaults to `'/'`. */\n measurementSeparator?: ReactNode;\n}\n\n// This article helps understand the typing here https://www.benmvp.com/blog/polymorphic-react-components-typescript/ Ben is the best :)\nexport type MoneyProps<ComponentGeneric extends React.ElementType> =\n MoneyPropsBase<ComponentGeneric> &\n (ComponentGeneric extends keyof React.JSX.IntrinsicElements\n ? Omit<\n React.ComponentPropsWithoutRef<ComponentGeneric>,\n keyof MoneyPropsBase<ComponentGeneric>\n >\n : React.ComponentPropsWithoutRef<ComponentGeneric>);\n\n/**\n * The `Money` component renders a string of the Storefront API's\n * [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2)\n * according to the `locale` in the `ShopifyProvider` component.\n * \n * @see {@link https://shopify.dev/api/hydrogen/components/money}\n * @example basic usage, outputs: $100.00\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} />\n * ```\n * \n *\n * @example without currency, outputs: 100.00\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} withoutCurrency />\n * ```\n * \n *\n * @example without trailing zeros, outputs: $100\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} withoutTrailingZeros />\n * ```\n * \n *\n * @example with per-unit measurement, outputs: $100.00 per G\n * ```ts\n * <Money\n * data={{amount: '100.00', currencyCode: 'USD'}}\n * measurement={{referenceUnit: 'G'}}\n * measurementSeparator=\" per \"\n * />\n * ```\n */\nexport function Money<ComponentGeneric extends React.ElementType = 'div'>({\n data,\n as,\n withoutCurrency,\n withoutTrailingZeros,\n measurement,\n measurementSeparator = '/',\n ...passthroughProps\n}: MoneyProps<ComponentGeneric>): JSX.Element {\n if (!isMoney(data)) {\n throw new Error(\n `<Money/> needs a valid 'data' prop that has 'amount' and 'currencyCode'`,\n );\n }\n const moneyObject = useMoney(data);\n const Wrapper = as ?? 'div';\n\n let output = moneyObject.localizedString;\n\n if (withoutCurrency || withoutTrailingZeros) {\n if (withoutCurrency && !withoutTrailingZeros) {\n output = moneyObject.amount;\n } else if (!withoutCurrency && withoutTrailingZeros) {\n output = moneyObject.withoutTrailingZeros;\n } else {\n // both\n output = moneyObject.withoutTrailingZerosAndCurrency;\n }\n }\n\n return (\n <Wrapper {...passthroughProps}>\n {output}\n {measurement && measurement.referenceUnit && (\n <>\n {measurementSeparator}\n {measurement.referenceUnit}\n </>\n )}\n </Wrapper>\n );\n}\n\n// required in order to narrow the money object down and make TS happy\nfunction isMoney(\n maybeMoney: PartialDeep<MoneyV2, {recurseIntoArrays: true}>,\n): maybeMoney is MoneyV2 {\n return (\n typeof maybeMoney.amount === 'string' &&\n !!maybeMoney.amount &&\n typeof maybeMoney.currencyCode === 'string' &&\n !!maybeMoney.currencyCode\n );\n}\n"],"names":[],"mappings":";;AA+DO,SAAS,MAA0D;AAAA,EACxE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAuB;AAAA,EACvB,GAAG;AACL,GAA8C;AACxC,MAAA,CAAC,QAAQ,IAAI,GAAG;AAClB,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AACM,QAAA,cAAc,SAAS,IAAI;AACjC,QAAM,UAAU,MAAM;AAEtB,MAAI,SAAS,YAAY;AAEzB,MAAI,mBAAmB,sBAAsB;AACvC,QAAA,mBAAmB,CAAC,sBAAsB;AAC5C,eAAS,YAAY;AAAA,IAAA,WACZ,CAAC,mBAAmB,sBAAsB;AACnD,eAAS,YAAY;AAAA,IAAA,OAChB;AAEL,eAAS,YAAY;AAAA,IACvB;AAAA,EACF;AAGE,SAAA,qBAAC,SAAS,EAAA,GAAG,kBACV,UAAA;AAAA,IAAA;AAAA,IACA,eAAe,YAAY,iBAEvB,qBAAA,UAAA,EAAA,UAAA;AAAA,MAAA;AAAA,MACA,YAAY;AAAA,IAAA,GACf;AAAA,EAEJ,EAAA,CAAA;AAEJ;AAGA,SAAS,QACP,YACuB;AACvB,SACE,OAAO,WAAW,WAAW,YAC7B,CAAC,CAAC,WAAW,UACb,OAAO,WAAW,iBAAiB,YACnC,CAAC,CAAC,WAAW;AAEjB;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProductPrice.mjs","sources":["../../src/ProductPrice.tsx"],"sourcesContent":["import type {\n MoneyV2,\n UnitPriceMeasurement,\n Product,\n} from './storefront-api-types.js';\nimport {Money, type MoneyProps, type MoneyPropsBase} from './Money.js';\nimport type {PartialDeep} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\nexport interface ProductPriceProps {\n /** A Storefront API [Product object](https://shopify.dev/api/storefront/reference/products/product). */\n data: PartialDeep<Product, {recurseIntoArrays: true}>;\n /** The type of price. Valid values: `regular` (default) or `compareAt`. */\n priceType?: 'regular' | 'compareAt';\n /** The type of value. Valid values: `min` (default), `max` or `unit`. */\n valueType?: 'max' | 'min' | 'unit';\n /** The ID of the variant. */\n variantId?: string;\n}\n\n/**\n * The `ProductPrice` component renders a `Money` component with the product\n * [`priceRange`](https://shopify.dev/api/storefront/reference/products/productpricerange)'s `maxVariantPrice` or `minVariantPrice`, for either the regular price or compare at price range.\n */\nexport function ProductPrice
|
|
1
|
+
{"version":3,"file":"ProductPrice.mjs","sources":["../../src/ProductPrice.tsx"],"sourcesContent":["import type {\n MoneyV2,\n UnitPriceMeasurement,\n Product,\n} from './storefront-api-types.js';\nimport {Money, type MoneyProps, type MoneyPropsBase} from './Money.js';\nimport type {PartialDeep} from 'type-fest';\nimport {flattenConnection} from './flatten-connection.js';\n\nexport interface ProductPriceProps {\n /** A Storefront API [Product object](https://shopify.dev/api/storefront/reference/products/product). */\n data: PartialDeep<Product, {recurseIntoArrays: true}>;\n /** The type of price. Valid values: `regular` (default) or `compareAt`. */\n priceType?: 'regular' | 'compareAt';\n /** The type of value. Valid values: `min` (default), `max` or `unit`. */\n valueType?: 'max' | 'min' | 'unit';\n /** The ID of the variant. */\n variantId?: string;\n}\n\n/**\n * The `ProductPrice` component renders a `Money` component with the product\n * [`priceRange`](https://shopify.dev/api/storefront/reference/products/productpricerange)'s `maxVariantPrice` or `minVariantPrice`, for either the regular price or compare at price range.\n */\nexport function ProductPrice<\n ComponentGeneric extends React.ElementType = 'div',\n>(\n props: ProductPriceProps &\n Omit<MoneyProps<ComponentGeneric>, 'data' | 'measurement'>,\n): JSX.Element | null {\n const {\n priceType = 'regular',\n variantId,\n valueType = 'min',\n data: product,\n ...passthroughProps\n } = props;\n\n if (product == null) {\n throw new Error(`<ProductPrice/> requires a product as the 'data' prop`);\n }\n\n let price: Partial<MoneyV2> | undefined | null;\n let measurement: Partial<UnitPriceMeasurement> | undefined | null;\n\n const variant = variantId\n ? flattenConnection(product?.variants ?? {}).find(\n (variant) => variant?.id === variantId,\n ) ?? null\n : null;\n\n if (priceType === 'compareAt') {\n if (variantId && variant) {\n if (variant.compareAtPriceV2?.amount === variant.priceV2?.amount) {\n return null;\n }\n price = variant.compareAtPriceV2;\n } else if (valueType === 'max') {\n price = product?.compareAtPriceRange?.maxVariantPrice;\n } else {\n price = product?.compareAtPriceRange?.minVariantPrice;\n }\n } else {\n if (variantId && variant) {\n price = variant.priceV2;\n if (valueType === 'unit') {\n price = variant.unitPrice;\n measurement = variant.unitPriceMeasurement;\n }\n } else if (valueType === 'max') {\n price = product.priceRange?.maxVariantPrice;\n } else {\n price = product.priceRange?.minVariantPrice;\n }\n }\n\n if (!price) {\n return null;\n }\n\n if (measurement) {\n return (\n <Money {...passthroughProps} data={price} measurement={measurement} />\n );\n }\n\n return <Money {...passthroughProps} data={price} />;\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface ProductPricePropsForDocs<\n AsType extends React.ElementType = 'div',\n> extends Omit<MoneyPropsBase<AsType>, 'data' | 'measurement'>,\n ProductPriceProps {}\n"],"names":["variant"],"mappings":";;;AAwBO,SAAS,aAGd,OAEoB;;AACd,QAAA;AAAA,IACJ,YAAY;AAAA,IACZ;AAAA,IACA,YAAY;AAAA,IACZ,MAAM;AAAA,IACN,GAAG;AAAA,EACD,IAAA;AAEJ,MAAI,WAAW,MAAM;AACb,UAAA,IAAI,MAAM,uDAAuD;AAAA,EACzE;AAEI,MAAA;AACA,MAAA;AAEJ,QAAM,UAAU,YACZ,mBAAkB,mCAAS,aAAY,CAAE,CAAA,EAAE;AAAA,IACzC,CAACA,cAAYA,qCAAS,QAAO;AAAA,EAAA,KAC1B,OACL;AAEJ,MAAI,cAAc,aAAa;AAC7B,QAAI,aAAa,SAAS;AACxB,YAAI,aAAQ,qBAAR,mBAA0B,cAAW,aAAQ,YAAR,mBAAiB,SAAQ;AACzD,eAAA;AAAA,MACT;AACA,cAAQ,QAAQ;AAAA,IAAA,WACP,cAAc,OAAO;AAC9B,eAAQ,wCAAS,wBAAT,mBAA8B;AAAA,IAAA,OACjC;AACL,eAAQ,wCAAS,wBAAT,mBAA8B;AAAA,IACxC;AAAA,EAAA,OACK;AACL,QAAI,aAAa,SAAS;AACxB,cAAQ,QAAQ;AAChB,UAAI,cAAc,QAAQ;AACxB,gBAAQ,QAAQ;AAChB,sBAAc,QAAQ;AAAA,MACxB;AAAA,IAAA,WACS,cAAc,OAAO;AAC9B,eAAQ,aAAQ,eAAR,mBAAoB;AAAA,IAAA,OACvB;AACL,eAAQ,aAAQ,eAAR,mBAAoB;AAAA,IAC9B;AAAA,EACF;AAEA,MAAI,CAAC,OAAO;AACH,WAAA;AAAA,EACT;AAEA,MAAI,aAAa;AACf,+BACG,OAAO,EAAA,GAAG,kBAAkB,MAAM,OAAO,YAA0B,CAAA;AAAA,EAExE;AAEA,SAAQ,oBAAA,OAAA,EAAO,GAAG,kBAAkB,MAAM,MAAO,CAAA;AACnD;"}
|
|
@@ -18,7 +18,8 @@ function AddToCartButton(props) {
|
|
|
18
18
|
const { status, linesAdd } = useCart();
|
|
19
19
|
const { selectedVariant } = useProduct();
|
|
20
20
|
const variantId = explicitVariantId ?? (selectedVariant == null ? void 0 : selectedVariant.id) ?? "";
|
|
21
|
-
const disabled = explicitVariantId === null || variantId === "" || selectedVariant === null || addingItem ||
|
|
21
|
+
const disabled = explicitVariantId === null || variantId === "" || selectedVariant === null || addingItem || // Only certain 'as' types such as 'button' contain `disabled`
|
|
22
|
+
passthroughProps.disabled;
|
|
22
23
|
useEffect(() => {
|
|
23
24
|
if (addingItem && status === "idle") {
|
|
24
25
|
setAddingItem(false);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AddToCartButton.mjs","sources":["../../src/AddToCartButton.tsx"],"sourcesContent":["import {useCallback, useEffect, useState} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {useProduct} from './ProductProvider.js';\nimport {\n BaseButton,\n type CustomBaseButtonProps,\n type BaseButtonProps,\n} from './BaseButton.js';\nimport * as React from 'react';\n\nexport interface AddToCartButtonPropsBase {\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 /** The ID of the variant. */\n variantId?: string | null;\n /** The item quantity. */\n quantity?: number;\n /** The text that is announced by the screen reader when the item is being added to the cart. Used for accessibility purposes only and not displayed on the page. */\n accessibleAddingToCartLabel?: string;\n /** The selling plan ID of the subscription variant */\n sellingPlanId?: string;\n}\n\nexport type AddToCartButtonProps<AsType extends React.ElementType = 'button'> =\n AddToCartButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `AddToCartButton` component renders a button that adds an item to the cart when pressed.\n * It must be a descendent of the `CartProvider` component.\n */\nexport function AddToCartButton<AsType extends React.ElementType = 'button'>(\n props: AddToCartButtonProps<AsType>,\n): JSX.Element {\n const [addingItem, setAddingItem] = useState<boolean>(false);\n const {\n variantId: explicitVariantId,\n quantity = 1,\n attributes,\n sellingPlanId,\n onClick,\n children,\n accessibleAddingToCartLabel,\n ...passthroughProps\n } = props;\n const {status, linesAdd} = useCart();\n const {selectedVariant} = useProduct();\n const variantId = explicitVariantId ?? selectedVariant?.id ?? '';\n const disabled =\n explicitVariantId === null ||\n variantId === '' ||\n selectedVariant === null ||\n addingItem ||\n passthroughProps.disabled;\n\n useEffect(() => {\n if (addingItem && status === 'idle') {\n setAddingItem(false);\n }\n }, [status, addingItem]);\n\n const handleAddItem = useCallback(() => {\n setAddingItem(true);\n linesAdd([\n {\n quantity,\n merchandiseId: variantId || '',\n attributes,\n sellingPlanId,\n },\n ]);\n }, [linesAdd, quantity, variantId, attributes, sellingPlanId]);\n\n return (\n <>\n <BaseButton\n {...passthroughProps}\n disabled={disabled}\n onClick={onClick}\n defaultOnClick={handleAddItem}\n >\n {children}\n </BaseButton>\n {accessibleAddingToCartLabel ? (\n <p\n style={{\n position: 'absolute',\n width: '1px',\n height: '1px',\n padding: '0',\n margin: '-1px',\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n borderWidth: '0',\n }}\n role=\"alert\"\n aria-live=\"assertive\"\n >\n {addingItem ? accessibleAddingToCartLabel : null}\n </p>\n ) : null}\n </>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface AddToCartButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends AddToCartButtonPropsBase,\n CustomBaseButtonProps<AsType> {}\n"],"names":[],"mappings":";;;;;AAiCO,SAAS,gBACd,OACa;AACb,QAAM,CAAC,YAAY,aAAa,IAAI,SAAkB,KAAK;AACrD,QAAA;AAAA,IACJ,WAAW;AAAA,IACX,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AACJ,QAAM,EAAC,QAAQ,SAAQ,IAAI,QAAQ;AAC7B,QAAA,EAAC,oBAAmB;AACpB,QAAA,YAAY,sBAAqB,mDAAiB,OAAM;
|
|
1
|
+
{"version":3,"file":"AddToCartButton.mjs","sources":["../../src/AddToCartButton.tsx"],"sourcesContent":["import {useCallback, useEffect, useState} from 'react';\nimport {useCart} from './CartProvider.js';\nimport {useProduct} from './ProductProvider.js';\nimport {\n BaseButton,\n type CustomBaseButtonProps,\n type BaseButtonProps,\n} from './BaseButton.js';\nimport * as React from 'react';\n\nexport interface AddToCartButtonPropsBase {\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 /** The ID of the variant. */\n variantId?: string | null;\n /** The item quantity. */\n quantity?: number;\n /** The text that is announced by the screen reader when the item is being added to the cart. Used for accessibility purposes only and not displayed on the page. */\n accessibleAddingToCartLabel?: string;\n /** The selling plan ID of the subscription variant */\n sellingPlanId?: string;\n}\n\nexport type AddToCartButtonProps<AsType extends React.ElementType = 'button'> =\n AddToCartButtonPropsBase & BaseButtonProps<AsType>;\n\n/**\n * The `AddToCartButton` component renders a button that adds an item to the cart when pressed.\n * It must be a descendent of the `CartProvider` component.\n */\nexport function AddToCartButton<AsType extends React.ElementType = 'button'>(\n props: AddToCartButtonProps<AsType>,\n): JSX.Element {\n const [addingItem, setAddingItem] = useState<boolean>(false);\n const {\n variantId: explicitVariantId,\n quantity = 1,\n attributes,\n sellingPlanId,\n onClick,\n children,\n accessibleAddingToCartLabel,\n ...passthroughProps\n } = props;\n const {status, linesAdd} = useCart();\n const {selectedVariant} = useProduct();\n const variantId = explicitVariantId ?? selectedVariant?.id ?? '';\n const disabled =\n explicitVariantId === null ||\n variantId === '' ||\n selectedVariant === null ||\n addingItem ||\n // Only certain 'as' types such as 'button' contain `disabled`\n (passthroughProps as {disabled?: boolean}).disabled;\n\n useEffect(() => {\n if (addingItem && status === 'idle') {\n setAddingItem(false);\n }\n }, [status, addingItem]);\n\n const handleAddItem = useCallback(() => {\n setAddingItem(true);\n linesAdd([\n {\n quantity,\n merchandiseId: variantId || '',\n attributes,\n sellingPlanId,\n },\n ]);\n }, [linesAdd, quantity, variantId, attributes, sellingPlanId]);\n\n return (\n <>\n <BaseButton\n {...passthroughProps}\n disabled={disabled}\n onClick={onClick}\n defaultOnClick={handleAddItem}\n >\n {children}\n </BaseButton>\n {accessibleAddingToCartLabel ? (\n <p\n style={{\n position: 'absolute',\n width: '1px',\n height: '1px',\n padding: '0',\n margin: '-1px',\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n borderWidth: '0',\n }}\n role=\"alert\"\n aria-live=\"assertive\"\n >\n {addingItem ? accessibleAddingToCartLabel : null}\n </p>\n ) : null}\n </>\n );\n}\n\n// This is only for documenation purposes, and it is not used in the code.\nexport interface AddToCartButtonPropsForDocs<\n AsType extends React.ElementType = 'button',\n> extends AddToCartButtonPropsBase,\n Custom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8B;AAAA,MAAA;AAAA,IAAA,IAE5C;AAAA,EACN,EAAA,CAAA;AAEJ;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseButton.mjs","sources":["../../src/BaseButton.tsx"],"sourcesContent":["import {ReactNode, Ref, useCallback} from 'react';\n\nexport interface CustomBaseButtonProps<AsType> {\n /** Provide a React element or component to render as the underlying button. Note: for accessibility compliance, almost always you should use a `button` element, or a component that renders an underlying button. */\n as?: AsType;\n /** Any ReactNode elements. */\n children: ReactNode;\n /** Click event handler. Default behaviour triggers unless prevented */\n onClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A default `onClick` behavior */\n defaultOnClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A `ref` to the underlying button */\n buttonRef?: Ref<HTMLButtonElement>;\n}\n\nexport type BaseButtonProps<AsType extends React.ElementType> =\n CustomBaseButtonProps<AsType> &\n Omit<\n
|
|
1
|
+
{"version":3,"file":"BaseButton.mjs","sources":["../../src/BaseButton.tsx"],"sourcesContent":["import {ReactNode, Ref, useCallback} from 'react';\n\nexport interface CustomBaseButtonProps<AsType> {\n /** Provide a React element or component to render as the underlying button. Note: for accessibility compliance, almost always you should use a `button` element, or a component that renders an underlying button. */\n as?: AsType;\n /** Any ReactNode elements. */\n children: ReactNode;\n /** Click event handler. Default behaviour triggers unless prevented */\n onClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A default `onClick` behavior */\n defaultOnClick?: (\n event?: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n ) => void | boolean;\n /** A `ref` to the underlying button */\n buttonRef?: Ref<HTMLButtonElement>;\n}\n\nexport type BaseButtonProps<AsType extends React.ElementType> =\n CustomBaseButtonProps<AsType> &\n (AsType extends keyof React.JSX.IntrinsicElements\n ? Omit<\n React.ComponentPropsWithoutRef<AsType>,\n keyof CustomBaseButtonProps<AsType>\n >\n : React.ComponentPropsWithoutRef<AsType>);\n\nexport function BaseButton<AsType extends React.ElementType = 'button'>(\n props: BaseButtonProps<AsType>,\n): JSX.Element {\n const {\n as,\n onClick,\n defaultOnClick,\n children,\n buttonRef,\n ...passthroughProps\n } = props;\n\n const handleOnClick = useCallback(\n (event?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {\n if (onClick) {\n const clickShouldContinue = onClick(event);\n if (\n (typeof clickShouldContinue === 'boolean' &&\n clickShouldContinue === false) ||\n event?.defaultPrevented\n )\n return;\n }\n\n defaultOnClick?.(event);\n },\n [defaultOnClick, onClick],\n );\n\n const Component = as || 'button';\n\n return (\n <Component ref={buttonRef} onClick={handleOnClick} {...passthroughProps}>\n {children}\n </Component>\n );\n}\n"],"names":[],"mappings":";;AA4BO,SAAS,WACd,OACa;AACP,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACD,IAAA;AAEJ,QAAM,gBAAgB;AAAA,IACpB,CAAC,UAA4D;AAC3D,UAAI,SAAS;AACL,cAAA,sBAAsB,QAAQ,KAAK;AACzC,YACG,OAAO,wBAAwB,aAC9B,wBAAwB,UAC1B,+BAAO;AAEP;AAAA,MACJ;AAEA,uDAAiB;AAAA,IACnB;AAAA,IACA,CAAC,gBAAgB,OAAO;AAAA,EAAA;AAG1B,QAAM,YAAY,MAAM;AAGtB,SAAA,oBAAC,aAAU,KAAK,WAAW,SAAS,eAAgB,GAAG,kBACpD,SACH,CAAA;AAEJ;"}
|
|
@@ -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 (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,
|
|
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 // Only certain 'as' types such as 'button' contain `disabled`\n disabled={loading ?? (passthroughProps as {disabled?: boolean}).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,MAEC,UAAU,WAAY,iBAA0C;AAAA,MAC/D,GAAG;AAAA,MACJ;AAAA,MACA,gBAAgB;AAAA,MAEf;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|