UNPKG

@shopify/hydrogen-react

Version:

React components, hooks, and utilities for creating custom Shopify storefronts

77 lines (76 loc) 2.2 kB
import { jsxs, Fragment, jsx } from "react/jsx-runtime"; import { useState, useEffect, useCallback } from "react"; import { useCart } from "./CartProvider.mjs"; import { useProduct } from "./ProductProvider.mjs"; import { BaseButton } from "./BaseButton.mjs"; function AddToCartButton(props) { const [addingItem, setAddingItem] = useState(false); const { variantId: explicitVariantId, quantity = 1, attributes, sellingPlanId, onClick, children, accessibleAddingToCartLabel, parent, ...passthroughProps } = props; const { status, linesAdd } = useCart(); const { selectedVariant } = useProduct(); const variantId = explicitVariantId ?? (selectedVariant == null ? void 0 : selectedVariant.id) ?? ""; const disabled = explicitVariantId === null || variantId === "" || selectedVariant === null || addingItem || // Only certain 'as' types such as 'button' contain `disabled` passthroughProps.disabled; useEffect(() => { if (addingItem && status === "idle") { setAddingItem(false); } }, [status, addingItem]); const handleAddItem = useCallback(() => { setAddingItem(true); linesAdd([ { quantity, merchandiseId: variantId || "", attributes, parent, sellingPlanId } ]); }, [linesAdd, quantity, variantId, attributes, sellingPlanId, parent]); return /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx( BaseButton, { ...passthroughProps, disabled, onClick, defaultOnClick: handleAddItem, children } ), accessibleAddingToCartLabel ? /* @__PURE__ */ jsx( "p", { style: { position: "absolute", width: "1px", height: "1px", padding: "0", margin: "-1px", overflow: "hidden", clip: "rect(0, 0, 0, 0)", whiteSpace: "nowrap", borderWidth: "0" }, role: "alert", "aria-live": "assertive", children: addingItem ? accessibleAddingToCartLabel : null } ) : null ] }); } export { AddToCartButton }; //# sourceMappingURL=AddToCartButton.mjs.map