| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579 |
- import { router } from '@inertiajs/react';
- import {
- ChevronDown,
- MessageCircle,
- ShieldCheck,
- Tag,
- Truck,
- } from 'lucide-react';
- import { useEffect, useRef, useState } from 'react';
- import { useStorefront } from '../context';
- import { ProductCard, 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';
- import { whatsappLink } from '../whatsapp';
-
- /** One product's own page. Built by us, in the store's colours and fonts. */
- export function ProductPage({
- product,
- related,
- }: {
- product: StoreProduct;
- related: 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">
- {/* On wide screens the photos stay in view while the shopper reads. */}
- <div className="md:sticky md:top-24 md:self-start">
- <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="sf-card 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}
- price={price}
- key={variant?.id ?? 'simple'}
- />
-
- <TrustPoints product={product} />
-
- <Sections product={product} />
- </div>
- </div>
-
- {related.length > 0 && (
- <section className="mt-20" data-test="related-products">
- <h2 className="sf-heading text-2xl font-semibold sm:text-3xl">
- {t.pairsWellWith}
- </h2>
- <ul className="mt-6 grid grid-cols-2 gap-x-4 gap-y-8 md:grid-cols-4 md:gap-x-6">
- {related.map((item, index) => (
- <li key={item.id}>
- <ProductCard product={item} seed={index} />
- </li>
- ))}
- </ul>
- </section>
- )}
- </Container>
- </main>
- );
- }
-
- /** Short reassurances under the button, from the store's real settings. */
- function TrustPoints({ product }: { product: StoreProduct }) {
- const { shop, language, storeName } = useStorefront();
- const t = storefrontText(language);
- const free = shop.free_shipping_over;
-
- return (
- <ul
- className="mt-6 space-y-2.5 border-t border-(--sf-border) pt-6 text-sm"
- data-test="trust-points"
- >
- <li className="flex items-center gap-3">
- <Truck
- className="size-4 shrink-0 text-(--sf-primary)"
- aria-hidden="true"
- />
- <span>
- {free === 0
- ? t.trustFreeShipping
- : free !== null
- ? t.trustFreeShippingOver(formatPrice(free))
- : t.trustShippingFrom(
- formatPrice(shop.shipping_from),
- )}
- <span className="text-(--sf-muted)">
- {' '}
- · {t.trustShippingText}
- </span>
- </span>
- </li>
- <li className="flex items-center gap-3">
- <ShieldCheck
- className="size-4 shrink-0 text-(--sf-primary)"
- aria-hidden="true"
- />
- <span>
- {t.trustPayment}
- <span className="text-(--sf-muted)">
- {' '}
- · {t.trustPaymentText}
- </span>
- </span>
- </li>
- {shop.whatsapp && (
- <li className="flex items-center gap-3">
- <MessageCircle
- className="size-4 shrink-0 text-(--sf-primary)"
- aria-hidden="true"
- />
- <a
- href={whatsappLink(
- shop.whatsapp,
- t.askAboutProduct(product.name, storeName),
- )}
- target="_blank"
- rel="noreferrer"
- className="underline underline-offset-4 hover:text-(--sf-primary)"
- >
- {t.askOnWhatsApp}
- </a>
- </li>
- )}
- </ul>
- );
- }
-
- /**
- * Folding sections: the product's own (such as "How to use") and a shipping section the store writes
- * from its real fees, so it is always right.
- */
- function Sections({ product }: { product: StoreProduct }) {
- const { shop, language } = useStorefront();
- const t = storefrontText(language);
- const free = shop.free_shipping_over;
-
- const shipping = [
- t.shippingWest(formatPrice(shop.shipping_west)),
- t.shippingEast(formatPrice(shop.shipping_east)),
- free === 0
- ? t.shippingFreeAll
- : free !== null
- ? t.shippingFreeOver(formatPrice(free))
- : null,
- ]
- .filter(Boolean)
- .join('\n');
-
- const sections = [
- ...product.details,
- { title: t.shipping, body: shipping },
- ];
-
- return (
- <div
- className="mt-6 divide-y divide-(--sf-border) border-y border-(--sf-border)"
- data-test="product-sections"
- >
- {sections.map((section) => (
- <details key={section.title} className="group">
- <summary className="flex cursor-pointer list-none items-center justify-between gap-4 py-4 font-medium [&::-webkit-details-marker]:hidden">
- {section.title}
- <ChevronDown
- className="size-4 shrink-0 text-(--sf-muted) transition-transform group-open:rotate-180"
- aria-hidden="true"
- />
- </summary>
- <p className="pb-4 text-sm leading-relaxed whitespace-pre-line text-(--sf-muted)">
- {section.body}
- </p>
- </details>
- ))}
- </div>
- );
- }
-
- function AddToCart({
- product,
- variant,
- price,
- }: {
- product: StoreProduct;
- variant: StoreVariant | null;
- price: number;
- }) {
- 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;
-
- // On phones, once the main button scrolls out of view, a bar with the price and the button
- // stays at the bottom of the screen.
- const buttonRef = useRef<HTMLButtonElement>(null);
- const [showBar, setShowBar] = useState(false);
-
- useEffect(() => {
- let frame = 0;
-
- // Shown once the button has gone up under the sticky header, not before the shopper reaches it.
- const check = () => {
- cancelAnimationFrame(frame);
- frame = requestAnimationFrame(() => {
- const button = buttonRef.current;
-
- if (button) {
- setShowBar(button.getBoundingClientRect().bottom < 96);
- }
- });
- };
-
- check();
- window.addEventListener('scroll', check, { passive: true });
- window.addEventListener('resize', check);
-
- return () => {
- cancelAnimationFrame(frame);
- window.removeEventListener('scroll', check);
- window.removeEventListener('resize', check);
- };
- }, []);
-
- // Nothing to offer for a sold-out product, so no bar then.
- const barVisible = showBar && (canAdd || needsChoice);
-
- // Lets the WhatsApp button move up so the bar never covers it.
- useEffect(() => {
- document.documentElement.classList.toggle('sf-sticky-cart', barVisible);
-
- return () =>
- document.documentElement.classList.remove('sf-sticky-cart');
- }, [barVisible]);
-
- const label = needsChoice
- ? t.unavailable
- : inStock
- ? t.addToCart
- : t.soldOut;
-
- 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
- ref={buttonRef}
- type="button"
- onClick={add}
- disabled={!canAdd || busy}
- className="sf-btn-primary 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"
- >
- {label}
- </button>
-
- {barVisible && (
- <div
- className="sf-fade-in fixed inset-x-0 bottom-0 z-40 border-t border-(--sf-border) bg-(--sf-bg) px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] shadow-[0_-6px_20px_rgba(0,0,0,0.08)] md:hidden"
- data-test="sticky-cart-bar"
- >
- <div className="flex items-center gap-3">
- <div className="min-w-0 flex-1">
- <p className="truncate text-sm font-medium">
- {product.name}
- {variant && (
- <span className="text-(--sf-muted)">
- {' '}
- · {variant.name}
- </span>
- )}
- </p>
- <p className="text-sm font-semibold tabular-nums">
- {formatPrice(price)}
- </p>
- </div>
- <button
- type="button"
- onClick={() =>
- canAdd
- ? add()
- : buttonRef.current?.scrollIntoView({
- behavior: 'smooth',
- block: 'center',
- })
- }
- disabled={busy || (!canAdd && !needsChoice)}
- className="sf-btn-primary shrink-0 rounded-(--sf-radius) bg-(--sf-primary) px-5 py-2.5 text-sm font-semibold text-(--sf-primary-fg) disabled:opacity-50"
- >
- {needsChoice ? t.chooseShort : label}
- </button>
- </div>
- </div>
- )}
-
- <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>
- );
- }
|