AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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