AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

product.tsx 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. import { router } from '@inertiajs/react';
  2. import {
  3. ChevronDown,
  4. MessageCircle,
  5. ShieldCheck,
  6. Tag,
  7. Truck,
  8. } from 'lucide-react';
  9. import { useEffect, useRef, useState } from 'react';
  10. import { useStorefront } from '../context';
  11. import { ProductCard, ProductImage } from '../product-card';
  12. import { storefrontText } from '../text';
  13. import { formatPrice } from '../theme';
  14. import { cn } from '@/lib/utils';
  15. import type { StoreProduct, StoreVariant } from '../types';
  16. import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
  17. import { whatsappLink } from '../whatsapp';
  18. /** One product's own page. Built by us, in the store's colours and fonts. */
  19. export function ProductPage({
  20. product,
  21. related,
  22. }: {
  23. product: StoreProduct;
  24. related: StoreProduct[];
  25. }) {
  26. const { language, shop } = useStorefront();
  27. const t = storefrontText(language);
  28. const [selected, setSelected] = useState(0);
  29. const offers = shop.offers.filter(
  30. (offer) =>
  31. offer.product_ids === null ||
  32. offer.product_ids.includes(product.id),
  33. );
  34. const shown = product.images[selected] ?? product.image;
  35. // Start on the first combination that is in stock, so the page opens ready to buy.
  36. const start =
  37. product.variants.find((candidate) => candidate.in_stock) ??
  38. product.variants[0];
  39. const [choice, setChoice] = useState<string[]>(start?.options ?? []);
  40. const variant =
  41. product.variants.find(
  42. (candidate) =>
  43. candidate.options.length === choice.length &&
  44. candidate.options.every((value, i) => value === choice[i]),
  45. ) ?? null;
  46. const price = variant ? variant.price : product.price;
  47. const compareAt = variant
  48. ? variant.compare_at_price
  49. : product.compare_at_price;
  50. const inStock = variant ? variant.in_stock : product.in_stock;
  51. function choose(index: number, value: string) {
  52. setChoice((current) =>
  53. current.map((old, i) => (i === index ? value : old)),
  54. );
  55. }
  56. /** Whether picking this value, with the other choices kept, gives something in stock. */
  57. function isAvailable(index: number, value: string): boolean {
  58. const wanted = choice.map((old, i) => (i === index ? value : old));
  59. return product.variants.some(
  60. (candidate) =>
  61. candidate.in_stock &&
  62. candidate.options.every((v, i) => v === wanted[i]),
  63. );
  64. }
  65. return (
  66. <main className="py-10 md:py-14">
  67. <Container>
  68. <SfLink
  69. href="/shop"
  70. className="text-sm text-(--sf-muted) transition-colors hover:text-(--sf-fg)"
  71. >
  72. ← {t.backToShop}
  73. </SfLink>
  74. <div className="mt-6 grid gap-10 md:grid-cols-2 md:gap-14">
  75. {/* On wide screens the photos stay in view while the shopper reads. */}
  76. <div className="md:sticky md:top-24 md:self-start">
  77. <ProductImage
  78. src={shown}
  79. alt={product.name}
  80. className="aspect-square w-full"
  81. />
  82. {product.images.length > 1 && (
  83. <ul className="mt-3 grid grid-cols-5 gap-3">
  84. {product.images.map((image, index) => (
  85. <li key={image}>
  86. <button
  87. type="button"
  88. onClick={() => setSelected(index)}
  89. aria-label={`${product.name} ${index + 1}`}
  90. aria-pressed={index === selected}
  91. 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'}`}
  92. >
  93. <ProductImage
  94. src={image}
  95. alt=""
  96. className="aspect-square w-full"
  97. />
  98. </button>
  99. </li>
  100. ))}
  101. </ul>
  102. )}
  103. </div>
  104. <div>
  105. <h1 className="sf-heading text-3xl leading-tight font-semibold sm:text-4xl">
  106. {product.name}
  107. </h1>
  108. <p className="mt-4 text-2xl font-semibold tabular-nums">
  109. {formatPrice(price)}
  110. {compareAt !== null && (
  111. <s className="ml-3 text-base font-normal text-(--sf-muted)">
  112. {formatPrice(compareAt)}
  113. </s>
  114. )}
  115. </p>
  116. <p className="mt-2 text-sm text-(--sf-muted)">
  117. {inStock ? t.inStock : t.soldOut}
  118. </p>
  119. {offers.length > 0 && (
  120. <ul className="mt-4 space-y-2" data-test="offers">
  121. {offers.map((offer) => (
  122. <li
  123. key={offer.name}
  124. className="flex items-center gap-2 rounded-(--sf-radius) bg-(--sf-surface) px-3 py-2 text-sm"
  125. >
  126. <Tag
  127. className="size-4 shrink-0 text-(--sf-primary)"
  128. aria-hidden="true"
  129. />
  130. <span>
  131. <span className="font-semibold">
  132. {offer.name}:
  133. </span>{' '}
  134. {offer.text}
  135. </span>
  136. </li>
  137. ))}
  138. </ul>
  139. )}
  140. {product.options.length > 0 && (
  141. <div className="mt-6 space-y-5">
  142. {product.options.map((option, index) => (
  143. <fieldset key={option.name}>
  144. <legend className="text-sm font-medium">
  145. {option.name}:{' '}
  146. <span className="font-normal text-(--sf-muted)">
  147. {choice[index]}
  148. </span>
  149. </legend>
  150. <div className="mt-2 flex flex-wrap gap-2">
  151. {option.values.map((value) => {
  152. const chosen =
  153. choice[index] === value;
  154. const available = isAvailable(
  155. index,
  156. value,
  157. );
  158. return (
  159. <button
  160. key={value}
  161. type="button"
  162. aria-pressed={chosen}
  163. aria-label={
  164. available
  165. ? value
  166. : `${value}, ${t.soldOut}`
  167. }
  168. onClick={() =>
  169. choose(index, value)
  170. }
  171. className={cn(
  172. '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)',
  173. chosen
  174. ? 'border-(--sf-primary) bg-(--sf-primary) text-(--sf-primary-fg)'
  175. : 'border-(--sf-border) hover:bg-(--sf-surface)',
  176. !available &&
  177. 'text-(--sf-muted) line-through',
  178. )}
  179. >
  180. {value}
  181. </button>
  182. );
  183. })}
  184. </div>
  185. </fieldset>
  186. ))}
  187. </div>
  188. )}
  189. {product.bundle.length > 0 && (
  190. <div className="mt-6">
  191. <h2 className="text-sm font-medium">
  192. {t.whatsInside}
  193. </h2>
  194. <ul className="sf-card mt-2 divide-y divide-(--sf-border) rounded-(--sf-radius-card) border border-(--sf-border)">
  195. {product.bundle.map((item) => (
  196. <li
  197. key={item.name}
  198. className="flex items-center gap-3 px-4 py-2.5 text-sm"
  199. >
  200. <span className="min-w-8 font-semibold tabular-nums">
  201. {item.quantity} ×
  202. </span>
  203. {item.slug ? (
  204. <SfLink
  205. href={`/products/${item.slug}`}
  206. className="underline-offset-4 hover:underline"
  207. >
  208. {item.name}
  209. </SfLink>
  210. ) : (
  211. <span>{item.name}</span>
  212. )}
  213. </li>
  214. ))}
  215. </ul>
  216. </div>
  217. )}
  218. {product.description && (
  219. <p className="mt-6 leading-relaxed whitespace-pre-line text-(--sf-muted)">
  220. {product.description}
  221. </p>
  222. )}
  223. <AddToCart
  224. product={product}
  225. variant={variant}
  226. price={price}
  227. key={variant?.id ?? 'simple'}
  228. />
  229. <TrustPoints product={product} />
  230. <Sections product={product} />
  231. </div>
  232. </div>
  233. {related.length > 0 && (
  234. <section className="mt-20" data-test="related-products">
  235. <h2 className="sf-heading text-2xl font-semibold sm:text-3xl">
  236. {t.pairsWellWith}
  237. </h2>
  238. <ul className="mt-6 grid grid-cols-2 gap-x-4 gap-y-8 md:grid-cols-4 md:gap-x-6">
  239. {related.map((item, index) => (
  240. <li key={item.id}>
  241. <ProductCard product={item} seed={index} />
  242. </li>
  243. ))}
  244. </ul>
  245. </section>
  246. )}
  247. </Container>
  248. </main>
  249. );
  250. }
  251. /** Short reassurances under the button, from the store's real settings. */
  252. function TrustPoints({ product }: { product: StoreProduct }) {
  253. const { shop, language, storeName } = useStorefront();
  254. const t = storefrontText(language);
  255. const free = shop.free_shipping_over;
  256. return (
  257. <ul
  258. className="mt-6 space-y-2.5 border-t border-(--sf-border) pt-6 text-sm"
  259. data-test="trust-points"
  260. >
  261. <li className="flex items-center gap-3">
  262. <Truck
  263. className="size-4 shrink-0 text-(--sf-primary)"
  264. aria-hidden="true"
  265. />
  266. <span>
  267. {free === 0
  268. ? t.trustFreeShipping
  269. : free !== null
  270. ? t.trustFreeShippingOver(formatPrice(free))
  271. : t.trustShippingFrom(
  272. formatPrice(shop.shipping_from),
  273. )}
  274. <span className="text-(--sf-muted)">
  275. {' '}
  276. · {t.trustShippingText}
  277. </span>
  278. </span>
  279. </li>
  280. <li className="flex items-center gap-3">
  281. <ShieldCheck
  282. className="size-4 shrink-0 text-(--sf-primary)"
  283. aria-hidden="true"
  284. />
  285. <span>
  286. {t.trustPayment}
  287. <span className="text-(--sf-muted)">
  288. {' '}
  289. · {t.trustPaymentText}
  290. </span>
  291. </span>
  292. </li>
  293. {shop.whatsapp && (
  294. <li className="flex items-center gap-3">
  295. <MessageCircle
  296. className="size-4 shrink-0 text-(--sf-primary)"
  297. aria-hidden="true"
  298. />
  299. <a
  300. href={whatsappLink(
  301. shop.whatsapp,
  302. t.askAboutProduct(product.name, storeName),
  303. )}
  304. target="_blank"
  305. rel="noreferrer"
  306. className="underline underline-offset-4 hover:text-(--sf-primary)"
  307. >
  308. {t.askOnWhatsApp}
  309. </a>
  310. </li>
  311. )}
  312. </ul>
  313. );
  314. }
  315. /**
  316. * Folding sections: the product's own (such as "How to use") and a shipping section the store writes
  317. * from its real fees, so it is always right.
  318. */
  319. function Sections({ product }: { product: StoreProduct }) {
  320. const { shop, language } = useStorefront();
  321. const t = storefrontText(language);
  322. const free = shop.free_shipping_over;
  323. const shipping = [
  324. t.shippingWest(formatPrice(shop.shipping_west)),
  325. t.shippingEast(formatPrice(shop.shipping_east)),
  326. free === 0
  327. ? t.shippingFreeAll
  328. : free !== null
  329. ? t.shippingFreeOver(formatPrice(free))
  330. : null,
  331. ]
  332. .filter(Boolean)
  333. .join('\n');
  334. const sections = [
  335. ...product.details,
  336. { title: t.shipping, body: shipping },
  337. ];
  338. return (
  339. <div
  340. className="mt-6 divide-y divide-(--sf-border) border-y border-(--sf-border)"
  341. data-test="product-sections"
  342. >
  343. {sections.map((section) => (
  344. <details key={section.title} className="group">
  345. <summary className="flex cursor-pointer list-none items-center justify-between gap-4 py-4 font-medium [&::-webkit-details-marker]:hidden">
  346. {section.title}
  347. <ChevronDown
  348. className="size-4 shrink-0 text-(--sf-muted) transition-transform group-open:rotate-180"
  349. aria-hidden="true"
  350. />
  351. </summary>
  352. <p className="pb-4 text-sm leading-relaxed whitespace-pre-line text-(--sf-muted)">
  353. {section.body}
  354. </p>
  355. </details>
  356. ))}
  357. </div>
  358. );
  359. }
  360. function AddToCart({
  361. product,
  362. variant,
  363. price,
  364. }: {
  365. product: StoreProduct;
  366. variant: StoreVariant | null;
  367. price: number;
  368. }) {
  369. const { baseUrl, language, cart } = useStorefront();
  370. const t = storefrontText(language);
  371. const [quantity, setQuantity] = useState(1);
  372. const [busy, setBusy] = useState(false);
  373. const [added, setAdded] = useState(false);
  374. const [error, setError] = useState<string | null>(null);
  375. const needsChoice = product.options.length > 0 && variant === null;
  376. const lineKey = variant
  377. ? `${product.id}-${variant.id}`
  378. : String(product.id);
  379. const stockLeft = variant ? variant.stock_left : product.stock_left;
  380. const inStock = variant ? variant.in_stock : product.in_stock;
  381. const inCart =
  382. cart.lines.find((line) => line.key === lineKey)?.quantity ?? 0;
  383. const max = Math.max(0, Math.min(stockLeft, 99) - inCart);
  384. const canAdd = !needsChoice && inStock && max > 0;
  385. // On phones, once the main button scrolls out of view, a bar with the price and the button
  386. // stays at the bottom of the screen.
  387. const buttonRef = useRef<HTMLButtonElement>(null);
  388. const [showBar, setShowBar] = useState(false);
  389. useEffect(() => {
  390. let frame = 0;
  391. // Shown once the button has gone up under the sticky header, not before the shopper reaches it.
  392. const check = () => {
  393. cancelAnimationFrame(frame);
  394. frame = requestAnimationFrame(() => {
  395. const button = buttonRef.current;
  396. if (button) {
  397. setShowBar(button.getBoundingClientRect().bottom < 96);
  398. }
  399. });
  400. };
  401. check();
  402. window.addEventListener('scroll', check, { passive: true });
  403. window.addEventListener('resize', check);
  404. return () => {
  405. cancelAnimationFrame(frame);
  406. window.removeEventListener('scroll', check);
  407. window.removeEventListener('resize', check);
  408. };
  409. }, []);
  410. // Nothing to offer for a sold-out product, so no bar then.
  411. const barVisible = showBar && (canAdd || needsChoice);
  412. // Lets the WhatsApp button move up so the bar never covers it.
  413. useEffect(() => {
  414. document.documentElement.classList.toggle('sf-sticky-cart', barVisible);
  415. return () =>
  416. document.documentElement.classList.remove('sf-sticky-cart');
  417. }, [barVisible]);
  418. const label = needsChoice
  419. ? t.unavailable
  420. : inStock
  421. ? t.addToCart
  422. : t.soldOut;
  423. function add() {
  424. setError(null);
  425. router.post(
  426. `${baseUrl}/cart/items`,
  427. {
  428. product_id: product.id,
  429. variant_id: variant?.id ?? null,
  430. quantity: Math.min(quantity, max),
  431. },
  432. {
  433. preserveScroll: true,
  434. onStart: () => setBusy(true),
  435. onFinish: () => setBusy(false),
  436. onSuccess: () => {
  437. setAdded(true);
  438. setQuantity(1);
  439. },
  440. onError: (errors) =>
  441. setError(
  442. errors.quantity ??
  443. errors.variant_id ??
  444. errors.product_id ??
  445. null,
  446. ),
  447. },
  448. );
  449. }
  450. return (
  451. <div className="mt-8">
  452. {canAdd && (
  453. <div className="mb-4 flex items-center gap-3">
  454. <span className="text-sm text-(--sf-muted)">
  455. {t.quantity}
  456. </span>
  457. <QuantityStepper
  458. value={Math.min(quantity, max)}
  459. max={max}
  460. onChange={setQuantity}
  461. decreaseLabel={t.decrease}
  462. increaseLabel={t.increase}
  463. />
  464. {stockLeft <= 5 && (
  465. <span className="text-sm text-(--sf-muted)">
  466. {t.onlyLeft(stockLeft)}
  467. </span>
  468. )}
  469. </div>
  470. )}
  471. <button
  472. ref={buttonRef}
  473. type="button"
  474. onClick={add}
  475. disabled={!canAdd || busy}
  476. 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"
  477. >
  478. {label}
  479. </button>
  480. {barVisible && (
  481. <div
  482. 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"
  483. data-test="sticky-cart-bar"
  484. >
  485. <div className="flex items-center gap-3">
  486. <div className="min-w-0 flex-1">
  487. <p className="truncate text-sm font-medium">
  488. {product.name}
  489. {variant && (
  490. <span className="text-(--sf-muted)">
  491. {' '}
  492. · {variant.name}
  493. </span>
  494. )}
  495. </p>
  496. <p className="text-sm font-semibold tabular-nums">
  497. {formatPrice(price)}
  498. </p>
  499. </div>
  500. <button
  501. type="button"
  502. onClick={() =>
  503. canAdd
  504. ? add()
  505. : buttonRef.current?.scrollIntoView({
  506. behavior: 'smooth',
  507. block: 'center',
  508. })
  509. }
  510. disabled={busy || (!canAdd && !needsChoice)}
  511. 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"
  512. >
  513. {needsChoice ? t.chooseShort : label}
  514. </button>
  515. </div>
  516. </div>
  517. )}
  518. <div aria-live="polite" className="mt-3 min-h-6 text-sm">
  519. {error && <p className="text-red-700">{error}</p>}
  520. {added && !error && (
  521. <p className="flex flex-wrap items-center gap-3">
  522. <span>{t.added}</span>
  523. <SfButton
  524. href="/cart"
  525. variant="outline"
  526. className="px-3 py-1.5"
  527. >
  528. {t.viewCart}
  529. </SfButton>
  530. </p>
  531. )}
  532. </div>
  533. </div>
  534. );
  535. }