# Shopping cart

A bag of outdoor gear: each line has art, its name and variant, a quantity stepper, a Remove `Button` and a line total. The summary `Card` holds a free-shipping meter, a promo code `Field` and the totals, and removing the last item swaps everything for an empty state. Try the code `TRAIL10`, or any other code to see the error.

**Example: Your bag** (`examples/recipes/shopping-cart.tsx`)

```tsx
'use client'

import {
  Body,
  BodySmall,
  Button,
  Card,
  Field,
  Heading,
  Separator,
  Stack,
  Text,
  toast,
} from '@blocks/design-system'
import { Backpack, Check, Footprints, type LucideIcon, Minus, Plus, Shirt, ShoppingBag, Trash2 } from 'lucide-react'
import { type FormEvent, useRef, useState } from 'react'
import styles from './shopping-cart.module.css'

interface LineItem {
  id: string
  name: string
  variant: string
  price: number
  quantity: number
  icon: LucideIcon
}

const initialItems: LineItem[] = [
  { id: 'ridgeline', name: 'Ridgeline insulated jacket', variant: 'Spruce · M', price: 248, quantity: 1, icon: Shirt },
  { id: 'socks', name: 'Merino trail socks, 3 pairs', variant: 'Charcoal · L', price: 36, quantity: 2, icon: Footprints },
  { id: 'daypack', name: 'Summit 28 L daypack', variant: 'Basalt', price: 139, quantity: 1, icon: Backpack },
]

const promoCodes: Record<string, number> = { TRAIL10: 0.1 }
const freeShippingFrom = 150
const shippingFee = 8
const taxRate = 0.08
const maxQuantity = 10

const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

// A cart whose totals are derived from the line items on every render:
// quantities, removals and the promo code all flow into one summary.
export default function ShoppingCart() {
  const [items, setItems] = useState(initialItems)
  const [promo, setPromo] = useState<{ code: string; rate: number } | null>(null)
  const [promoError, setPromoError] = useState<string | null>(null)
  const headingRef = useRef<HTMLHeadingElement>(null)

  const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0)
  const discount = promo ? subtotal * promo.rate : 0
  const shipping = subtotal >= freeShippingFrom ? 0 : shippingFee
  const tax = (subtotal - discount) * taxRate
  const total = subtotal - discount + shipping + tax
  const itemCount = items.reduce((sum, item) => sum + item.quantity, 0)

  function setQuantity(id: string, quantity: number) {
    setItems((current) => current.map((item) => (item.id === id ? { ...item, quantity } : item)))
  }

  function remove(item: LineItem) {
    setItems((current) => current.filter((other) => other.id !== item.id))
    toast(`Removed ${item.name}`)
    // The button that had focus is gone; move focus to the cart heading.
    headingRef.current?.focus()
  }

  function applyPromo(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const code = String(new FormData(event.currentTarget).get('promo')).trim().toUpperCase()
    const rate = promoCodes[code]
    if (rate !== undefined) {
      setPromo({ code, rate })
      setPromoError(null)
    } else {
      setPromoError(code ? `${code} isn’t a valid code.` : 'Enter a promo code.')
    }
  }

  if (items.length === 0) {
    return (
      <Card as="section" aria-labelledby="shopping-cart-empty" padding="xl" textAlign="center">
        <Stack gap="md" align="center">
          <ShoppingBag aria-hidden className={styles.emptyIcon} />
          <Heading as="h2" id="shopping-cart-empty" fontSize="lg">
            Your bag is empty
          </Heading>
          <Body margin="none" color="text-muted">
            Saved items and recently viewed gear are waiting in your account.
          </Body>
          <Button as="a" href="#shopping-cart-shop" variant="primary">
            Continue shopping
          </Button>
        </Stack>
      </Card>
    )
  }

  return (
    <section aria-labelledby="shopping-cart-title" className={styles.root}>
      <div className={styles.layout}>
        <Stack gap="md">
          <Stack direction="row" justify="space-between" align="baseline" gap="sm" wrap="wrap">
            <Heading as="h2" id="shopping-cart-title" ref={headingRef} tabIndex={-1} fontSize="xl">
              Your bag
            </Heading>
            <Text fontSize="sm" color="text-muted">
              {itemCount} {itemCount === 1 ? 'item' : 'items'}
            </Text>
          </Stack>
          <ul className={styles.items}>
            {items.map((item) => (
              <li key={item.id} className={styles.item}>
                <div className={styles.art}>
                  <item.icon aria-hidden />
                </div>
                <Stack gap="xxs" dangerouslySetClassName={styles.info}>
                  <Text fontWeight="semibold">{item.name}</Text>
                  <Text fontSize="sm" color="text-muted">
                    {item.variant}
                  </Text>
                  <Text fontSize="sm" color="text-muted">
                    {money.format(item.price)} each
                  </Text>
                </Stack>
                <Text fontWeight="semibold" dangerouslySetClassName={styles.lineTotal}>
                  {money.format(item.price * item.quantity)}
                </Text>
                <Stack direction="row" justify="space-between" align="center" gap="sm" dangerouslySetClassName={styles.controls}>
                  <Stepper item={item} onChange={(quantity) => setQuantity(item.id, quantity)} />
                  <Button type="button" variant="ghost" size="sm" aria-label={`Remove ${item.name}`} onClick={() => remove(item)}>
                    <Trash2 aria-hidden className={styles.icon} />
                    Remove
                  </Button>
                </Stack>
              </li>
            ))}
          </ul>
        </Stack>

        <Card as="aside" aria-labelledby="shopping-cart-summary" padding="lg" backgroundColor="bg-subtle" borderRadius="xl">
          <Stack gap="md">
            <Heading as="h3" id="shopping-cart-summary" fontSize="md">
              Order summary
            </Heading>

            <FreeShipping subtotal={subtotal} />

            <Stack as="form" gap="xs" onSubmit={applyPromo} aria-label="Promo code" noValidate>
              {promo ? (
                <Stack direction="row" justify="space-between" align="center" gap="sm">
                  <Text fontSize="sm" color="success-text" role="status">
                    <Check aria-hidden className={styles.icon} /> {promo.code} applied: {promo.rate * 100}% off
                  </Text>
                  <Button type="button" variant="link" size="sm" onClick={() => setPromo(null)}>
                    Remove
                  </Button>
                </Stack>
              ) : (
                <Field name="promo" invalid={promoError !== null}>
                  <Field.Label>Promo code</Field.Label>
                  <Stack direction="row" gap="sm">
                    <Field.Control
                      placeholder="TRAIL10"
                      autoComplete="off"
                      autoCapitalize="characters"
                      onValueChange={() => setPromoError(null)}
                    />
                    <Button type="submit" dangerouslySetClassName={styles.apply}>
                      Apply
                    </Button>
                  </Stack>
                  {promoError ? (
                    <Field.Error match>{promoError}</Field.Error>
                  ) : (
                    <Field.Description>Members get TRAIL10 for 10% off.</Field.Description>
                  )}
                </Field>
              )}
            </Stack>

            <Separator />

            <dl className={styles.summary}>
              <SummaryRow label="Subtotal" value={money.format(subtotal)} />
              {promo && <SummaryRow label={`Discount (${promo.code})`} value={`−${money.format(discount)}`} />}
              <SummaryRow label="Shipping" value={shipping === 0 ? 'Free' : money.format(shipping)} />
              <SummaryRow label="Estimated tax" value={money.format(tax)} />
              <SummaryRow label="Total" value={money.format(total)} emphasis />
            </dl>

            <Button as="a" href="#shopping-cart-checkout" variant="primary" size="lg" dangerouslySetClassName={styles.checkout}>
              Check out
            </Button>
          </Stack>
        </Card>
      </div>
    </section>
  )
}

function Stepper({ item, onChange }: { item: LineItem; onChange: (quantity: number) => void }) {
  return (
    <fieldset aria-label={`Quantity of ${item.name}`} className={styles.stepper}>
      <button
        type="button"
        aria-label={`Decrease quantity of ${item.name}`}
        disabled={item.quantity <= 1}
        onClick={() => onChange(item.quantity - 1)}
      >
        <Minus aria-hidden />
      </button>
      <output aria-live="polite" className={styles.quantity}>
        {item.quantity}
      </output>
      <button
        type="button"
        aria-label={`Increase quantity of ${item.name}`}
        disabled={item.quantity >= maxQuantity}
        onClick={() => onChange(item.quantity + 1)}
      >
        <Plus aria-hidden />
      </button>
    </fieldset>
  )
}

function FreeShipping({ subtotal }: { subtotal: number }) {
  const remaining = freeShippingFrom - subtotal
  return (
    <Stack gap="xs">
      <BodySmall margin="none" aria-live="polite">
        {remaining > 0 ? (
          <>
            Add <strong>{money.format(remaining)}</strong> more for free shipping.
          </>
        ) : (
          'Your order ships free.'
        )}
      </BodySmall>
      <div aria-hidden className={styles.progress}>
        <div className={styles.progressFill} style={{ width: `${Math.min(subtotal / freeShippingFrom, 1) * 100}%` }} />
      </div>
    </Stack>
  )
}

function SummaryRow({ label, value, emphasis }: { label: string; value: string; emphasis?: boolean }) {
  return (
    <div className={emphasis ? styles.totalRow : styles.row}>
      <dt>{label}</dt>
      <dd>{value}</dd>
    </div>
  )
}
```

## How it works

- The line items are the only state. Subtotal, discount, shipping, tax, total and the item count are derived from them on every render, so a stepper press or a removal updates the whole summary at once.
- Each stepper is a labelled `fieldset` of two buttons, named for the item (“Decrease quantity of Summit 28 L daypack”), around an `output` that announces the new quantity. The minus button is disabled at 1, so removing an item is always a deliberate press of Remove.
- Removing a line takes its buttons with it, so focus moves to the cart heading rather than falling back to the page, and a toast names what was removed.
- The promo code is a small form of its own. An unknown code sets `invalid` on the `Field` and shows a `Field.Error`, which `Field` links to the input; typing clears it. A valid code turns into a status line with a Remove button and a discount row.
- The shipping meter is decorative: the sentence above it says how much more is needed, and updates politely.

## App-owned CSS

`examples/recipes/shopping-cart.module.css`:

```css
.root {
  container-type: inline-size;
}

/* Items above the summary; side by side only when there's room for both. */
.layout {
  display: grid;
  gap: var(--ds-space-xl);
}

@container (min-width: 44rem) {
  .layout {
    grid-template-columns: minmax(0, 1fr) 16rem;
    align-items: start;
  }
}

.items {
  margin: 0;
  padding: 0;
  list-style: none;
  border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}

/* Art, details and line total on one row; the controls under the details. */
.item {
  display: grid;
  grid-template-columns: auto minmax(0, 1fr) auto;
  gap: var(--ds-space-md) var(--ds-space-lg);
  padding-block: var(--ds-space-lg);
  border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}

.art {
  display: grid;
  place-items: center;
  grid-row: span 2;
  width: calc(var(--ds-space-xxl) + var(--ds-space-md));
  aspect-ratio: 1;
  color: var(--ds-color-text-muted);
  background-color: var(--ds-color-bg-subtle);
  border-radius: var(--ds-border-radius-md);

  & svg {
    width: var(--ds-control-height-sm);
    height: var(--ds-control-height-sm);
  }
}

.lineTotal {
  font-variant-numeric: tabular-nums;
  text-align: right;
}

.controls {
  grid-column: 2 / -1;
}

.stepper {
  display: inline-flex;
  align-items: center;
  min-width: 0;
  margin: 0;
  padding: 0;
  border: var(--ds-border-width-sm) solid var(--ds-color-border);
  border-radius: var(--ds-border-radius-pill);

  & button {
    display: grid;
    place-items: center;
    width: var(--ds-control-height-md);
    height: var(--ds-control-height-md);
    padding: 0;
    color: var(--ds-color-text);
    background: none;
    border: none;
    border-radius: var(--ds-border-radius-circle);
    cursor: pointer;
  }

  & button:hover:not(:disabled) {
    background-color: var(--ds-color-surface-hover);
  }

  & button:disabled {
    color: var(--ds-color-text-muted);
    cursor: not-allowed;
    opacity: 0.5;
  }

  & button:focus-visible {
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
  }

  & svg {
    width: var(--ds-icon-size-sm);
    height: var(--ds-icon-size-sm);
  }
}

.quantity {
  min-width: var(--ds-control-height-sm);
  font-size: var(--ds-font-size-sm);
  font-weight: var(--ds-font-weight-semibold);
  font-variant-numeric: tabular-nums;
  text-align: center;
}

.icon {
  display: inline-block;
  width: var(--ds-icon-size-sm);
  height: var(--ds-icon-size-sm);
  vertical-align: text-bottom;
}

.progress {
  height: var(--ds-space-sm);
  overflow: hidden;
  background-color: var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-pill);
}

.progressFill {
  height: 100%;
  background-color: var(--ds-color-success);
  border-radius: inherit;
  transition: width var(--ds-duration-normal) var(--ds-easing-standard);
}

.summary {
  display: grid;
  gap: var(--ds-space-sm);
  margin: 0;
  font-size: var(--ds-font-size-sm);
}

.row,
.totalRow {
  display: flex;
  justify-content: space-between;
  gap: var(--ds-space-md);

  & dt {
    color: var(--ds-color-text-muted);
  }

  & dd {
    margin: 0;
    font-variant-numeric: tabular-nums;
  }
}

.totalRow {
  padding-top: var(--ds-space-md);
  margin-top: var(--ds-space-sm);
  font-size: var(--ds-font-size-md);
  font-weight: var(--ds-font-weight-semibold);
  border-top: var(--ds-border-width-sm) solid var(--ds-color-border);

  & dt {
    color: var(--ds-color-text);
  }
}

/* Check out fills the summary card. */
.checkout {
  width: 100%;
}

/* Apply sits beside the input as an outlined secondary action. */
.root .apply {
  flex-shrink: 0;
  background-color: var(--ds-color-bg);
  border-color: var(--ds-color-border);
}

.emptyIcon {
  width: var(--ds-control-height-lg);
  height: var(--ds-control-height-lg);
  color: var(--ds-color-text-muted);
}

@media (prefers-reduced-motion: reduce) {
  .progressFill {
    transition: none;
  }
}
```
