| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344 |
- import { router } from '@inertiajs/react';
- import { Tag } from 'lucide-react';
- import { useState } from 'react';
- import { useStorefront } from '../context';
- import { ProductImage } from '../product-card';
- import { storefrontText } from '../text';
- import { formatPrice } from '../theme';
- import { cn } from '@/lib/utils';
- import type { StoreProduct, StoreVariant } from '../types';
- import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
-
- /** One product's own page. Built by us, in the store's colours and fonts. */
- export function ProductPage({ product }: { product: StoreProduct }) {
- const { language, shop } = useStorefront();
- const t = storefrontText(language);
- const [selected, setSelected] = useState(0);
- const offers = shop.offers.filter(
- (offer) =>
- offer.product_ids === null ||
- offer.product_ids.includes(product.id),
- );
- const shown = product.images[selected] ?? product.image;
-
- // Start on the first combination that is in stock, so the page opens ready to buy.
- const start =
- product.variants.find((candidate) => candidate.in_stock) ??
- product.variants[0];
- const [choice, setChoice] = useState<string[]>(start?.options ?? []);
- const variant =
- product.variants.find(
- (candidate) =>
- candidate.options.length === choice.length &&
- candidate.options.every((value, i) => value === choice[i]),
- ) ?? null;
-
- const price = variant ? variant.price : product.price;
- const compareAt = variant
- ? variant.compare_at_price
- : product.compare_at_price;
- const inStock = variant ? variant.in_stock : product.in_stock;
-
- function choose(index: number, value: string) {
- setChoice((current) =>
- current.map((old, i) => (i === index ? value : old)),
- );
- }
-
- /** Whether picking this value, with the other choices kept, gives something in stock. */
- function isAvailable(index: number, value: string): boolean {
- const wanted = choice.map((old, i) => (i === index ? value : old));
-
- return product.variants.some(
- (candidate) =>
- candidate.in_stock &&
- candidate.options.every((v, i) => v === wanted[i]),
- );
- }
-
- return (
- <main className="py-10 md:py-14">
- <Container>
- <SfLink
- href="/shop"
- className="text-sm text-(--sf-muted) transition-colors hover:text-(--sf-fg)"
- >
- ← {t.backToShop}
- </SfLink>
-
- <div className="mt-6 grid gap-10 md:grid-cols-2 md:gap-14">
- <div>
- <ProductImage
- src={shown}
- alt={product.name}
- className="aspect-square w-full"
- />
-
- {product.images.length > 1 && (
- <ul className="mt-3 grid grid-cols-5 gap-3">
- {product.images.map((image, index) => (
- <li key={image}>
- <button
- type="button"
- onClick={() => setSelected(index)}
- aria-label={`${product.name} ${index + 1}`}
- aria-pressed={index === selected}
- className={`block w-full rounded-(--sf-radius-card) outline-offset-2 focus-visible:outline-2 focus-visible:outline-(--sf-primary) ${index === selected ? 'ring-2 ring-(--sf-primary)' : 'opacity-70 hover:opacity-100'}`}
- >
- <ProductImage
- src={image}
- alt=""
- className="aspect-square w-full"
- />
- </button>
- </li>
- ))}
- </ul>
- )}
- </div>
-
- <div>
- <h1 className="sf-heading text-3xl leading-tight font-semibold sm:text-4xl">
- {product.name}
- </h1>
-
- <p className="mt-4 text-2xl font-semibold tabular-nums">
- {formatPrice(price)}
- {compareAt !== null && (
- <s className="ml-3 text-base font-normal text-(--sf-muted)">
- {formatPrice(compareAt)}
- </s>
- )}
- </p>
-
- <p className="mt-2 text-sm text-(--sf-muted)">
- {inStock ? t.inStock : t.soldOut}
- </p>
-
- {offers.length > 0 && (
- <ul className="mt-4 space-y-2" data-test="offers">
- {offers.map((offer) => (
- <li
- key={offer.name}
- className="flex items-center gap-2 rounded-(--sf-radius) bg-(--sf-surface) px-3 py-2 text-sm"
- >
- <Tag
- className="size-4 shrink-0 text-(--sf-primary)"
- aria-hidden="true"
- />
- <span>
- <span className="font-semibold">
- {offer.name}:
- </span>{' '}
- {offer.text}
- </span>
- </li>
- ))}
- </ul>
- )}
-
- {product.options.length > 0 && (
- <div className="mt-6 space-y-5">
- {product.options.map((option, index) => (
- <fieldset key={option.name}>
- <legend className="text-sm font-medium">
- {option.name}:{' '}
- <span className="font-normal text-(--sf-muted)">
- {choice[index]}
- </span>
- </legend>
- <div className="mt-2 flex flex-wrap gap-2">
- {option.values.map((value) => {
- const chosen =
- choice[index] === value;
- const available = isAvailable(
- index,
- value,
- );
-
- return (
- <button
- key={value}
- type="button"
- aria-pressed={chosen}
- aria-label={
- available
- ? value
- : `${value}, ${t.soldOut}`
- }
- onClick={() =>
- choose(index, value)
- }
- className={cn(
- 'rounded-(--sf-radius) border px-4 py-2 text-sm transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary)',
- chosen
- ? 'border-(--sf-primary) bg-(--sf-primary) text-(--sf-primary-fg)'
- : 'border-(--sf-border) hover:bg-(--sf-surface)',
- !available &&
- 'text-(--sf-muted) line-through',
- )}
- >
- {value}
- </button>
- );
- })}
- </div>
- </fieldset>
- ))}
- </div>
- )}
-
- {product.bundle.length > 0 && (
- <div className="mt-6">
- <h2 className="text-sm font-medium">
- {t.whatsInside}
- </h2>
- <ul className="mt-2 divide-y divide-(--sf-border) rounded-(--sf-radius-card) border border-(--sf-border)">
- {product.bundle.map((item) => (
- <li
- key={item.name}
- className="flex items-center gap-3 px-4 py-2.5 text-sm"
- >
- <span className="min-w-8 font-semibold tabular-nums">
- {item.quantity} ×
- </span>
- {item.slug ? (
- <SfLink
- href={`/products/${item.slug}`}
- className="underline-offset-4 hover:underline"
- >
- {item.name}
- </SfLink>
- ) : (
- <span>{item.name}</span>
- )}
- </li>
- ))}
- </ul>
- </div>
- )}
-
- {product.description && (
- <p className="mt-6 leading-relaxed whitespace-pre-line text-(--sf-muted)">
- {product.description}
- </p>
- )}
-
- <AddToCart
- product={product}
- variant={variant}
- key={variant?.id ?? 'simple'}
- />
- </div>
- </div>
- </Container>
- </main>
- );
- }
-
- function AddToCart({
- product,
- variant,
- }: {
- product: StoreProduct;
- variant: StoreVariant | null;
- }) {
- const { baseUrl, language, cart } = useStorefront();
- const t = storefrontText(language);
- const [quantity, setQuantity] = useState(1);
- const [busy, setBusy] = useState(false);
- const [added, setAdded] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- const needsChoice = product.options.length > 0 && variant === null;
- const lineKey = variant
- ? `${product.id}-${variant.id}`
- : String(product.id);
- const stockLeft = variant ? variant.stock_left : product.stock_left;
- const inStock = variant ? variant.in_stock : product.in_stock;
- const inCart =
- cart.lines.find((line) => line.key === lineKey)?.quantity ?? 0;
- const max = Math.max(0, Math.min(stockLeft, 99) - inCart);
- const canAdd = !needsChoice && inStock && max > 0;
-
- function add() {
- setError(null);
- router.post(
- `${baseUrl}/cart/items`,
- {
- product_id: product.id,
- variant_id: variant?.id ?? null,
- quantity: Math.min(quantity, max),
- },
- {
- preserveScroll: true,
- onStart: () => setBusy(true),
- onFinish: () => setBusy(false),
- onSuccess: () => {
- setAdded(true);
- setQuantity(1);
- },
- onError: (errors) =>
- setError(
- errors.quantity ??
- errors.variant_id ??
- errors.product_id ??
- null,
- ),
- },
- );
- }
-
- return (
- <div className="mt-8">
- {canAdd && (
- <div className="mb-4 flex items-center gap-3">
- <span className="text-sm text-(--sf-muted)">
- {t.quantity}
- </span>
- <QuantityStepper
- value={Math.min(quantity, max)}
- max={max}
- onChange={setQuantity}
- decreaseLabel={t.decrease}
- increaseLabel={t.increase}
- />
- {stockLeft <= 5 && (
- <span className="text-sm text-(--sf-muted)">
- {t.onlyLeft(stockLeft)}
- </span>
- )}
- </div>
- )}
-
- <button
- type="button"
- onClick={add}
- disabled={!canAdd || busy}
- className="inline-flex w-full items-center justify-center rounded-(--sf-radius) bg-(--sf-primary) px-6 py-3 text-sm font-semibold text-(--sf-primary-fg) transition-opacity hover:opacity-85 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary) disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
- >
- {needsChoice
- ? t.unavailable
- : inStock
- ? t.addToCart
- : t.soldOut}
- </button>
-
- <div aria-live="polite" className="mt-3 min-h-6 text-sm">
- {error && <p className="text-red-700">{error}</p>}
- {added && !error && (
- <p className="flex flex-wrap items-center gap-3">
- <span>{t.added}</span>
- <SfButton
- href="/cart"
- variant="outline"
- className="px-3 py-1.5"
- >
- {t.viewCart}
- </SfButton>
- </p>
- )}
- </div>
- </div>
- );
- }
|