import { buildProductSelectionSearchParams, canAddToCart, createProductFormRegister, createProductFormStore, } from "@shopify/hydrogen"; import { useLocation, useNavigate } from "@solidjs/router"; import { createEffect, createMemo, createSignal, For, onCleanup, Show } from "solid-js"; import { getCartStore } from "../lib/cart"; import { openCartDrawer } from "../lib/cart-drawer"; import { formatMoney } from "../lib/money"; import type { ProductData, ProductFormState, ValidProductSelectionResult } from "../lib/product"; import { ShopPayButton } from "./ShopPayButton"; type ProductOptionValueSwatch = ProductData["options"][number]["optionValues"][number]["swatch"]; function isColor(name: string): boolean { return name.toLowerCase() === "color"; } function getSwatchStyle(swatch: ProductOptionValueSwatch | null | undefined) { const image = swatch?.image?.previewImage?.url; return { "background-color": swatch?.color ?? "#999", ...(image ? { "background-image": `url(${image})` } : {}), "background-position": "center", "background-size": "cover", }; } export function ProductPurchasePanel(props: { product: ProductData }) { const navigate = useNavigate(); const location = useLocation(); const store = createProductFormStore(props.product, getCartStore()); const [formState, setFormState] = createSignal(store.getState()); const [quantity, setQuantity] = createSignal(1); const [pending, setPending] = createSignal(false); let mounted = false; const unsubscribe = store.subscribe((nextState) => setFormState(nextState)); onCleanup(() => { unsubscribe(); store.destroy(); }); createEffect(() => { const identity = `${props.product.id}:${props.product.selectedOrFirstAvailableVariant?.id ?? ""}`; if (!mounted) { mounted = true; void identity; return; } store.hydrate(props.product); }); const register = createMemo(() => createProductFormRegister(formState().selectedVariant, selectOption), ); const addable = createMemo(() => canAddToCart(props.product, formState().options)); function selectOption(name: string, value: string) { const result = store.selectOption(name, value); if (result.status !== "invalid") handleSelect(result); } function handleOptionClick( event: MouseEvent & { currentTarget: HTMLAnchorElement }, name: string, value: string, ) { const link = event.currentTarget; if ( event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || (link.target !== "" && link.target.toLowerCase() !== "_self") || link.hasAttribute("download") ) { return; } event.preventDefault(); selectOption(name, value); } function handleSelect(result: ValidProductSelectionResult) { const targetHandle = result.selectedVariant?.product?.handle ?? props.product.handle; navigate(`/products/${targetHandle}${variantSearch(result.selectedOptions)}`, { replace: true, scroll: false, }); } function variantSearch(selectedOptions: { name: string; value: string }[]) { const params = buildProductSelectionSearchParams({ selectedOptions, optionNames: props.product.options.map((option) => option.name), base: new URLSearchParams(location.search), }); const search = params.toString(); return search ? `?${search}` : ""; } function variantHref(selectedOptions: { name: string; value: string }[], handle?: string) { const targetHandle = handle ?? props.product.handle; return `/products/${targetHandle}${variantSearch(selectedOptions)}`; } async function submitForm(event: SubmitEvent) { event.preventDefault(); setPending(true); try { await store.handleFormSubmit(event); openCartDrawer(); } catch (error) { console.error("[hydrogen] product form submission error:", error); } finally { setPending(false); } } function sanitizeQuantity(value: number) { setQuantity(Number.isFinite(value) && value > 0 ? Math.floor(value) : 1); } return ( ); }