Product card
A shop product card with an SVG illustration (tee, crewneck or tote) that recolours with the selected swatch, so no image files are needed. It has colour swatches and size choices as real radio groups with sold-out sizes, a regular or sale price with the discount badge, a star rating with partial stars, a save toggle, and an add-to-cart button with adding and added states. It asks for a size when one is missing and announces the result to screen readers.
Source
"use client";
import * as React from "react";
import { Check, Heart, LoaderCircle, ShoppingBag, Star } from "lucide-react";
import { cn } from "@/lib/utils";
export type ProductShape = "tee" | "crew" | "tote";
export interface ProductColor {
name: string;
/** Any CSS colour, used for the swatch and the generated visual. */
value: string;
}
export interface ProductSize {
label: string;
available?: boolean;
}
export interface Product {
id: string;
name: string;
category?: string;
price: number;
salePrice?: number;
currency?: string;
rating?: number;
reviewCount?: number;
colors: ProductColor[];
sizes?: ProductSize[];
/** Short badge such as "New". A sale badge is added automatically. */
badge?: string;
shape?: ProductShape;
}
export interface CartSelection {
productId: string;
color: string;
size?: string;
}
export interface ProductCardProps {
product: Product;
onAddToCart?: (selection: CartSelection) => void | Promise<void>;
onWishlistChange?: (productId: string, saved: boolean) => void;
defaultSaved?: boolean;
className?: string;
}
const shade = (color: string, amount: number) => `color-mix(in oklab, ${color} ${100 - amount}%, black)`;
const tint = (color: string, amount: number) => `color-mix(in oklab, ${color} ${100 - amount}%, white)`;
/* A product illustration drawn in SVG and coloured by the selected swatch, so no image files are needed. */
export function ProductVisual({ shape = "tee", color, className }: { shape?: ProductShape; color: string; className?: string }) {
const id = React.useId().replace(/[^a-zA-Z0-9_-]/g, "");
const light = `${id}-light`;
const fabric = { fill: color };
const trim = { fill: shade(color, 18) };
const seam = { stroke: shade(color, 30), strokeOpacity: 0.55 };
return (
<svg viewBox="0 0 200 200" className={className} aria-hidden>
<defs>
<linearGradient id={light} x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stopColor="white" stopOpacity="0.22" />
<stop offset="0.45" stopColor="white" stopOpacity="0" />
<stop offset="1" stopColor="black" stopOpacity="0.16" />
</linearGradient>
</defs>
<ellipse cx="100" cy="182" rx="58" ry="5" fill="black" opacity="0.09" />
{shape === "tee" && (
<g>
<path d="M80 38C86 50 114 50 120 38L143 45Q158 51 175 76L158 99L141 87L141 168Q100 173 59 168L59 87L42 99L25 76Q42 51 57 45Z" style={fabric} />
<path d="M80 38C86 50 114 50 120 38L143 45Q158 51 175 76L158 99L141 87L141 168Q100 173 59 168L59 87L42 99L25 76Q42 51 57 45Z" fill={`url(#${light})`} />
<path d="M80 38C86 51 114 51 120 38" fill="none" strokeWidth="4.5" strokeLinecap="round" style={{ stroke: shade(color, 22) }} />
<path d="M28 80L44 93M172 80L156 93M61 162Q100 167 139 162" fill="none" strokeWidth="1.2" style={seam} />
<path d="M59 87L59 120M141 87L141 120" fill="none" strokeWidth="1" style={seam} />
<path d="M84 108Q88 136 82 162M118 116Q114 140 120 160" fill="none" strokeWidth="1.4" stroke="black" strokeOpacity="0.05" />
</g>
)}
{shape === "crew" && (
<g>
<path d="M78 36C86 50 114 50 122 36L145 42Q162 48 169 76L181 146L164 151L151 94L146 102L146 160L54 160L54 102L49 94L36 151L19 146L31 76Q38 48 55 42Z" style={fabric} />
<path d="M78 36C86 50 114 50 122 36L145 42Q162 48 169 76L181 146L164 151L151 94L146 102L146 160L54 160L54 102L49 94L36 151L19 146L31 76Q38 48 55 42Z" fill={`url(#${light})`} />
<rect x="54" y="157" width="92" height="15" rx="3" style={trim} />
<path d="M19 146L36 151L34 165L17 160ZM181 146L164 151L166 165L183 160Z" style={trim} />
<path d="M78 36C86 52 114 52 122 36" fill="none" strokeWidth="6" strokeLinecap="round" style={{ stroke: shade(color, 18) }} />
<path d="M62 160V170M70 160V170M78 160V170M86 160V170M94 160V170M102 160V170M110 160V170M118 160V170M126 160V170M134 160V170" strokeWidth="1" style={{ stroke: shade(color, 34), strokeOpacity: 0.5 }} />
<path d="M54 102V140M146 102V140" fill="none" strokeWidth="1" style={seam} />
<path d="M88 96Q94 124 86 154M114 104Q110 130 116 152" fill="none" strokeWidth="1.4" stroke="black" strokeOpacity="0.05" />
</g>
)}
{shape === "tote" && (
<g>
<path d="M80 76C80 40 120 40 120 76" fill="none" strokeWidth="5" strokeLinecap="round" style={{ stroke: shade(color, 34) }} />
<path d="M68 78C68 26 132 26 132 78" fill="none" strokeWidth="6" strokeLinecap="round" style={{ stroke: shade(color, 14) }} />
<path d="M52 72H148L152 172Q100 176 48 172Z" style={fabric} />
<path d="M52 72H148L152 172Q100 176 48 172Z" fill={`url(#${light})`} />
<path d="M52 72H148L148.6 84H51.4Z" style={trim} />
<rect x="70" y="104" width="60" height="38" rx="3" style={{ fill: tint(color, 72) }} opacity="0.9" />
<path d="M80 117H120M80 125H108" strokeWidth="3" strokeLinecap="round" style={{ stroke: shade(color, 10) }} opacity="0.55" />
</g>
)}
</svg>
);
}
function Rating({ value, count }: { value: number; count?: number }) {
const percent = Math.max(0, Math.min(100, (value / 5) * 100));
return (
<div className="flex items-center gap-1.5">
<span role="img" aria-label={`Rated ${value.toFixed(1)} out of 5`} className="relative inline-flex">
<span className="flex text-muted-foreground/30">
{[0, 1, 2, 3, 4].map((i) => (
<Star key={i} aria-hidden className="size-3.5 fill-current" strokeWidth={0} />
))}
</span>
<span className="absolute inset-y-0 left-0 flex overflow-hidden text-amber-500 dark:text-amber-400" style={{ width: `${percent}%` }}>
{[0, 1, 2, 3, 4].map((i) => (
<Star key={i} aria-hidden className="size-3.5 shrink-0 fill-current" strokeWidth={0} />
))}
</span>
</span>
<span className="text-xs text-muted-foreground tabular-nums">
{value.toFixed(1)}
{count !== undefined && (
<>
{" "}
({count.toLocaleString()}
<span className="sr-only"> reviews</span>)
</>
)}
</span>
</div>
);
}
export function ProductCard({ product, onAddToCart, onWishlistChange, defaultSaved = false, className }: ProductCardProps) {
const [color, setColor] = React.useState(product.colors[0]?.name ?? "");
const [size, setSize] = React.useState<string | null>(null);
const [saved, setSaved] = React.useState(defaultSaved);
const [state, setState] = React.useState<"idle" | "adding" | "added">("idle");
const [sizeError, setSizeError] = React.useState(false);
const [status, setStatus] = React.useState("");
const sizesRef = React.useRef<HTMLFieldSetElement>(null);
const id = React.useId();
const format = (value: number) => new Intl.NumberFormat(undefined, { style: "currency", currency: product.currency || "USD" }).format(value);
const current = product.colors.find((item) => item.name === color) ?? product.colors[0];
const onSale = product.salePrice !== undefined && product.salePrice < product.price;
const discount = onSale ? Math.round((1 - product.salePrice! / product.price) * 100) : 0;
React.useEffect(() => {
if (state !== "added") return;
const timer = setTimeout(() => setState("idle"), 2200);
return () => clearTimeout(timer);
}, [state]);
async function add() {
if (product.sizes?.length && !size) {
setSizeError(true);
sizesRef.current?.querySelector<HTMLInputElement>("input:not(:disabled)")?.focus();
return;
}
setState("adding");
try {
await onAddToCart?.({ productId: product.id, color, size: size ?? undefined });
setState("added");
setStatus(`${product.name}, ${color}${size ? `, size ${size}` : ""}, added to cart.`);
} catch {
setState("idle");
setStatus("Could not add to cart. Try again.");
}
}
return (
<article aria-labelledby={`${id}-name`} className={cn("flex flex-col overflow-hidden rounded-xl border bg-card text-card-foreground shadow-xs", className)}>
<div
className="relative aspect-[5/4] overflow-hidden"
style={{ background: `radial-gradient(120% 90% at 50% 20%, color-mix(in oklab, ${current?.value} 10%, var(--card)), color-mix(in oklab, ${current?.value} 18%, var(--muted)))` }}
>
<ProductVisual shape={product.shape} color={current?.value ?? "gray"} className="absolute inset-0 m-auto h-[88%] w-[88%] motion-safe:transition-transform motion-safe:duration-300" />
<div className="absolute top-3 left-3 flex gap-1.5">
{onSale && <span className="rounded-md bg-rose-600 px-1.5 py-0.5 text-xs font-semibold text-white">−{discount}%</span>}
{product.badge && <span className="rounded-md bg-background/90 px-1.5 py-0.5 text-xs font-medium text-foreground shadow-xs backdrop-blur">{product.badge}</span>}
</div>
<button
type="button"
aria-pressed={saved}
aria-label={saved ? `Remove ${product.name} from saved items` : `Save ${product.name}`}
onClick={() => {
setSaved(!saved);
onWishlistChange?.(product.id, !saved);
}}
className="absolute top-3 right-3 grid size-9 place-items-center rounded-full bg-background/90 text-foreground shadow-xs outline-none backdrop-blur transition-colors hover:bg-background focus-visible:ring-2 focus-visible:ring-ring"
>
<Heart aria-hidden className={cn("size-4 motion-safe:transition-transform motion-safe:active:scale-90", saved && "fill-rose-500 text-rose-500")} />
</button>
</div>
<div className="flex flex-1 flex-col gap-4 p-4">
<div>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
{product.category && <p className="text-xs text-muted-foreground">{product.category}</p>}
<h3 id={`${id}-name`} className="mt-0.5 truncate font-medium">
{product.name}
</h3>
</div>
<p className="shrink-0 text-right">
<span className={cn("block font-semibold tabular-nums", onSale && "text-rose-600 dark:text-rose-400")}>
{onSale && <span className="sr-only">Sale price </span>}
{format(onSale ? product.salePrice! : product.price)}
</span>
{onSale && (
<del className="block text-xs text-muted-foreground tabular-nums">
<span className="sr-only">Original price </span>
{format(product.price)}
</del>
)}
</p>
</div>
{product.rating !== undefined && (
<div className="mt-1.5">
<Rating value={product.rating} count={product.reviewCount} />
</div>
)}
</div>
<fieldset>
<legend className="mb-2 text-xs text-muted-foreground">
Colour <span className="font-medium text-foreground">{color}</span>
</legend>
<div className="flex flex-wrap gap-2">
{product.colors.map((option) => (
<label key={option.name} className="relative cursor-pointer">
<input
type="radio"
name={`${id}-color`}
value={option.name}
checked={color === option.name}
onChange={() => setColor(option.name)}
className="peer sr-only"
/>
<span className="sr-only">{option.name}</span>
<span
aria-hidden
className="block size-7 rounded-full ring-1 ring-black/10 ring-offset-2 ring-offset-card transition-shadow peer-checked:ring-2 peer-checked:ring-foreground peer-focus-visible:ring-2 peer-focus-visible:ring-ring dark:ring-white/15"
style={{ background: option.value }}
/>
</label>
))}
</div>
</fieldset>
{!!product.sizes?.length && (
<fieldset ref={sizesRef} aria-describedby={sizeError ? `${id}-size-error` : undefined}>
<legend className="mb-2 text-xs text-muted-foreground">Size</legend>
<div className="grid grid-cols-5 gap-1.5">
{product.sizes.map((option) => {
const available = option.available !== false;
return (
<label key={option.label} className={cn("relative", available ? "cursor-pointer" : "cursor-not-allowed")}>
<input
type="radio"
name={`${id}-size`}
value={option.label}
disabled={!available}
checked={size === option.label}
onChange={() => {
setSize(option.label);
setSizeError(false);
}}
className="peer sr-only"
/>
<span
className={cn(
"grid h-9 place-items-center rounded-md border text-sm font-medium transition-colors peer-checked:border-foreground peer-checked:bg-foreground peer-checked:text-background peer-focus-visible:ring-2 peer-focus-visible:ring-ring peer-focus-visible:ring-offset-2 peer-focus-visible:ring-offset-card",
available ? "hover:bg-accent" : "text-muted-foreground/50 line-through",
sizeError && "border-destructive/60",
)}
>
{option.label}
{!available && <span className="sr-only"> (sold out)</span>}
</span>
</label>
);
})}
</div>
{sizeError && (
<p id={`${id}-size-error`} className="mt-2 text-xs font-medium text-destructive">
Choose a size
</p>
)}
</fieldset>
)}
<button
type="button"
onClick={add}
disabled={state === "adding"}
className={cn(
"mt-auto inline-flex h-10 items-center justify-center gap-2 rounded-md px-4 text-sm font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card disabled:cursor-wait",
state === "added"
? "bg-emerald-600 text-white hover:bg-emerald-600 dark:bg-emerald-500 dark:text-emerald-950"
: "bg-primary text-primary-foreground hover:bg-primary/90",
)}
>
{state === "adding" ? (
<LoaderCircle aria-hidden className="size-4 motion-safe:animate-spin" />
) : state === "added" ? (
<Check aria-hidden className="size-4" />
) : (
<ShoppingBag aria-hidden className="size-4" />
)}
{state === "adding" ? "Adding…" : state === "added" ? "Added to cart" : "Add to cart"}
</button>
<p aria-live="polite" className="sr-only">
{status}
</p>
</div>
</article>
);
}
