AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

product.tsx 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import { router } from '@inertiajs/react';
  2. import { useState } from 'react';
  3. import { useStorefront } from '../context';
  4. import { ProductImage } from '../product-card';
  5. import { storefrontText } from '../text';
  6. import { formatPrice } from '../theme';
  7. import { cn } from '@/lib/utils';
  8. import type { StoreProduct, StoreVariant } from '../types';
  9. import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
  10. /** One product's own page. Built by us, in the store's colours and fonts. */
  11. export function ProductPage({ product }: { product: StoreProduct }) {
  12. const { language } = useStorefront();
  13. const t = storefrontText(language);
  14. const [selected, setSelected] = useState(0);
  15. const shown = product.images[selected] ?? product.image;
  16. // Start on the first combination that is in stock, so the page opens ready to buy.
  17. const start =
  18. product.variants.find((candidate) => candidate.in_stock) ??
  19. product.variants[0];
  20. const [choice, setChoice] = useState<string[]>(start?.options ?? []);
  21. const variant =
  22. product.variants.find(
  23. (candidate) =>
  24. candidate.options.length === choice.length &&
  25. candidate.options.every((value, i) => value === choice[i]),
  26. ) ?? null;
  27. const price = variant ? variant.price : product.price;
  28. const compareAt = variant
  29. ? variant.compare_at_price
  30. : product.compare_at_price;
  31. const inStock = variant ? variant.in_stock : product.in_stock;
  32. function choose(index: number, value: string) {
  33. setChoice((current) =>
  34. current.map((old, i) => (i === index ? value : old)),
  35. );
  36. }
  37. /** Whether picking this value, with the other choices kept, gives something in stock. */
  38. function isAvailable(index: number, value: string): boolean {
  39. const wanted = choice.map((old, i) => (i === index ? value : old));
  40. return product.variants.some(
  41. (candidate) =>
  42. candidate.in_stock &&
  43. candidate.options.every((v, i) => v === wanted[i]),
  44. );
  45. }
  46. return (
  47. <main className="py-10 md:py-14">
  48. <Container>
  49. <SfLink
  50. href="/shop"
  51. className="text-sm text-(--sf-muted) transition-colors hover:text-(--sf-fg)"
  52. >
  53. ← {t.backToShop}
  54. </SfLink>
  55. <div className="mt-6 grid gap-10 md:grid-cols-2 md:gap-14">
  56. <div>
  57. <ProductImage
  58. src={shown}
  59. alt={product.name}
  60. className="aspect-square w-full"
  61. />
  62. {product.images.length > 1 && (
  63. <ul className="mt-3 grid grid-cols-5 gap-3">
  64. {product.images.map((image, index) => (
  65. <li key={image}>
  66. <button
  67. type="button"
  68. onClick={() => setSelected(index)}
  69. aria-label={`${product.name} ${index + 1}`}
  70. aria-pressed={index === selected}
  71. 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'}`}
  72. >
  73. <ProductImage
  74. src={image}
  75. alt=""
  76. className="aspect-square w-full"
  77. />
  78. </button>
  79. </li>
  80. ))}
  81. </ul>
  82. )}
  83. </div>
  84. <div>
  85. <h1 className="sf-heading text-3xl leading-tight font-semibold sm:text-4xl">
  86. {product.name}
  87. </h1>
  88. <p className="mt-4 text-2xl font-semibold tabular-nums">
  89. {formatPrice(price)}
  90. {compareAt !== null && (
  91. <s className="ml-3 text-base font-normal text-(--sf-muted)">
  92. {formatPrice(compareAt)}
  93. </s>
  94. )}
  95. </p>
  96. <p className="mt-2 text-sm text-(--sf-muted)">
  97. {inStock ? t.inStock : t.soldOut}
  98. </p>
  99. {product.options.length > 0 && (
  100. <div className="mt-6 space-y-5">
  101. {product.options.map((option, index) => (
  102. <fieldset key={option.name}>
  103. <legend className="text-sm font-medium">
  104. {option.name}:{' '}
  105. <span className="font-normal text-(--sf-muted)">
  106. {choice[index]}
  107. </span>
  108. </legend>
  109. <div className="mt-2 flex flex-wrap gap-2">
  110. {option.values.map((value) => {
  111. const chosen =
  112. choice[index] === value;
  113. const available = isAvailable(
  114. index,
  115. value,
  116. );
  117. return (
  118. <button
  119. key={value}
  120. type="button"
  121. aria-pressed={chosen}
  122. aria-label={
  123. available
  124. ? value
  125. : `${value}, ${t.soldOut}`
  126. }
  127. onClick={() =>
  128. choose(index, value)
  129. }
  130. className={cn(
  131. '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)',
  132. chosen
  133. ? 'border-(--sf-primary) bg-(--sf-primary) text-(--sf-primary-fg)'
  134. : 'border-(--sf-border) hover:bg-(--sf-surface)',
  135. !available &&
  136. 'text-(--sf-muted) line-through',
  137. )}
  138. >
  139. {value}
  140. </button>
  141. );
  142. })}
  143. </div>
  144. </fieldset>
  145. ))}
  146. </div>
  147. )}
  148. {product.bundle.length > 0 && (
  149. <div className="mt-6">
  150. <h2 className="text-sm font-medium">
  151. {t.whatsInside}
  152. </h2>
  153. <ul className="mt-2 divide-y divide-(--sf-border) rounded-(--sf-radius-card) border border-(--sf-border)">
  154. {product.bundle.map((item) => (
  155. <li
  156. key={item.name}
  157. className="flex items-center gap-3 px-4 py-2.5 text-sm"
  158. >
  159. <span className="min-w-8 font-semibold tabular-nums">
  160. {item.quantity} ×
  161. </span>
  162. {item.slug ? (
  163. <SfLink
  164. href={`/products/${item.slug}`}
  165. className="underline-offset-4 hover:underline"
  166. >
  167. {item.name}
  168. </SfLink>
  169. ) : (
  170. <span>{item.name}</span>
  171. )}
  172. </li>
  173. ))}
  174. </ul>
  175. </div>
  176. )}
  177. {product.description && (
  178. <p className="mt-6 leading-relaxed whitespace-pre-line text-(--sf-muted)">
  179. {product.description}
  180. </p>
  181. )}
  182. <AddToCart
  183. product={product}
  184. variant={variant}
  185. key={variant?.id ?? 'simple'}
  186. />
  187. </div>
  188. </div>
  189. </Container>
  190. </main>
  191. );
  192. }
  193. function AddToCart({
  194. product,
  195. variant,
  196. }: {
  197. product: StoreProduct;
  198. variant: StoreVariant | null;
  199. }) {
  200. const { baseUrl, language, cart } = useStorefront();
  201. const t = storefrontText(language);
  202. const [quantity, setQuantity] = useState(1);
  203. const [busy, setBusy] = useState(false);
  204. const [added, setAdded] = useState(false);
  205. const [error, setError] = useState<string | null>(null);
  206. const needsChoice = product.options.length > 0 && variant === null;
  207. const lineKey = variant
  208. ? `${product.id}-${variant.id}`
  209. : String(product.id);
  210. const stockLeft = variant ? variant.stock_left : product.stock_left;
  211. const inStock = variant ? variant.in_stock : product.in_stock;
  212. const inCart =
  213. cart.lines.find((line) => line.key === lineKey)?.quantity ?? 0;
  214. const max = Math.max(0, Math.min(stockLeft, 99) - inCart);
  215. const canAdd = !needsChoice && inStock && max > 0;
  216. function add() {
  217. setError(null);
  218. router.post(
  219. `${baseUrl}/cart/items`,
  220. {
  221. product_id: product.id,
  222. variant_id: variant?.id ?? null,
  223. quantity: Math.min(quantity, max),
  224. },
  225. {
  226. preserveScroll: true,
  227. onStart: () => setBusy(true),
  228. onFinish: () => setBusy(false),
  229. onSuccess: () => {
  230. setAdded(true);
  231. setQuantity(1);
  232. },
  233. onError: (errors) =>
  234. setError(
  235. errors.quantity ??
  236. errors.variant_id ??
  237. errors.product_id ??
  238. null,
  239. ),
  240. },
  241. );
  242. }
  243. return (
  244. <div className="mt-8">
  245. {canAdd && (
  246. <div className="mb-4 flex items-center gap-3">
  247. <span className="text-sm text-(--sf-muted)">
  248. {t.quantity}
  249. </span>
  250. <QuantityStepper
  251. value={Math.min(quantity, max)}
  252. max={max}
  253. onChange={setQuantity}
  254. decreaseLabel={t.decrease}
  255. increaseLabel={t.increase}
  256. />
  257. {stockLeft <= 5 && (
  258. <span className="text-sm text-(--sf-muted)">
  259. {t.onlyLeft(stockLeft)}
  260. </span>
  261. )}
  262. </div>
  263. )}
  264. <button
  265. type="button"
  266. onClick={add}
  267. disabled={!canAdd || busy}
  268. 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"
  269. >
  270. {needsChoice
  271. ? t.unavailable
  272. : inStock
  273. ? t.addToCart
  274. : t.soldOut}
  275. </button>
  276. <div aria-live="polite" className="mt-3 min-h-6 text-sm">
  277. {error && <p className="text-red-700">{error}</p>}
  278. {added && !error && (
  279. <p className="flex flex-wrap items-center gap-3">
  280. <span>{t.added}</span>
  281. <SfButton
  282. href="/cart"
  283. variant="outline"
  284. className="px-3 py-1.5"
  285. >
  286. {t.viewCart}
  287. </SfButton>
  288. </p>
  289. )}
  290. </div>
  291. </div>
  292. );
  293. }