Cart Store
createCartProvider builds a typed cart context: lines, quantities clamped per line, promo codes, favourites, persistence and a totals calculator with inclusive or additive tax.
npx shadcn@latest add https://ui.develop-better-solutions.com/r/commerce-cart.jsonUses:commerce-money
Catalogue
Cart (0)
Add something to see the totals.
- Subtotal
- 0 MAD
- Discount
- 0 MAD
- VAT included
- 0 MAD
- Total
- 0 MAD
1,000 MAD to free shipping.
Usage
commerce-cart-example.tsx
"use client";
import {
clampQuantityTo,
createCartProvider,
createPriceFormatter,
createTotalsCalculator,
lineKey,
type ResolvedLineBase,
} from "@dbs/ui";
const format = createPriceFormatter("MAD");
const CATALOG = [
{ id: "tote", name: "Atlas Canvas Tote", price: 390 },
{ id: "shirt", name: "Souk Linen Shirt", price: 640 },
{ id: "scarf", name: "Draa Wool Scarf", price: 280 },
];
interface Resolved extends ResolvedLineBase {
name: string;
}
const totals = createTotalsCalculator({
freeShippingThreshold: 1000,
taxRate: 0.2,
taxMode: "inclusive",
delivery: {
standard: { label: "Standard", days: "2 to 4 days", price: 40, minDays: 2, maxDays: 4 },
express: { label: "Express", days: "next day", price: 90, minDays: 1, maxDays: 1 },
},
});
// One call builds a typed provider and hook for a store.
const { CartProvider, useCart } = createCartProvider<Resolved>({
storageKeys: { cart: "catalog-demo-cart", favorites: "catalog-demo-favorites" },
isKnownProduct: (id) => CATALOG.some((p) => p.id === id),
resolveLines: (lines) =>
lines.flatMap((line) => {
const product = CATALOG.find((p) => p.id === line.productId);
return product
? [{ key: lineKey(line), line, lineTotal: product.price * line.quantity, name: product.name }]
: [];
}),
computeTotals: (lines, promo) => totals(lines, promo),
clampLine: (_line, quantity) => clampQuantityTo(5, quantity),
maxQuantity: 5,
});
function Cart() {
const cart = useCart();
return (
<div className="grid w-full max-w-3xl gap-6 text-sm sm:grid-cols-2">
<div className="flex flex-col gap-2">
<p className="text-xs uppercase tracking-[0.14em] text-ink-subtle">Catalogue</p>
{CATALOG.map((p) => (
<button
key={p.id}
type="button"
onClick={() => cart.add({ productId: p.id, colorId: "default", size: "one", quantity: 1 })}
className="flex items-center justify-between rounded-xl border border-line px-4 py-3 text-left hover:bg-surface"
>
<span>{p.name}</span>
<span className="text-ink-muted">{format(p.price)}</span>
</button>
))}
</div>
<div className="flex flex-col gap-3 rounded-xl border border-line bg-surface p-4">
<p className="text-xs uppercase tracking-[0.14em] text-ink-subtle">Cart ({cart.count})</p>
{cart.lines.length === 0 && <p className="text-ink-muted">Add something to see the totals.</p>}
{cart.lines.map((l) => (
<div key={l.key} className="flex items-center justify-between gap-2">
<span className="truncate">{l.name}</span>
<span className="flex items-center gap-2">
<button type="button" aria-label="Fewer" onClick={() => cart.setQuantity(l.key, l.line.quantity - 1)} className="size-7 rounded-full border border-line">-</button>
<span className="w-4 text-center">{l.line.quantity}</span>
<button type="button" aria-label="More" onClick={() => cart.setQuantity(l.key, l.line.quantity + 1)} className="size-7 rounded-full border border-line">+</button>
<button type="button" aria-label="Remove" onClick={() => cart.remove(l.key)} className="ml-1 text-ink-subtle hover:text-ink">x</button>
</span>
</div>
))}
<button
type="button"
onClick={() => (cart.promo ? cart.clearPromo() : cart.applyPromo("WELCOME10"))}
className="self-start rounded-full border border-line px-3 py-1 text-xs"
>
{cart.promo ? `Remove ${cart.promo}` : "Apply WELCOME10"}
</button>
<dl className="grid grid-cols-[1fr_auto] gap-1 border-t border-line pt-3">
<dt className="text-ink-muted">Subtotal</dt>
<dd>{format(cart.totals.subtotal)}</dd>
<dt className="text-ink-muted">Discount</dt>
<dd>{format(cart.totals.discount)}</dd>
<dt className="text-ink-muted">VAT included</dt>
<dd>{format(cart.totals.tax)}</dd>
<dt className="font-medium">Total</dt>
<dd className="font-medium">{format(cart.totals.total)}</dd>
</dl>
<p className="text-xs text-ink-subtle">
{cart.totals.freeShipping
? "Free standard shipping unlocked."
: `${format(cart.totals.toFreeShipping)} to free shipping.`}
</p>
</div>
</div>
);
}
export default function CommerceCartExample() {
return (
<CartProvider>
<Cart />
</CartProvider>
);
}