Cart drawer

A slide-over shopping cart. It lists line items with a thumbnail, variant, line total, quantity stepper (respecting a maximum) and remove button, shows progress toward a free-shipping threshold, and ends with the subtotal, shipping and a checkout button. As a modal dialog it traps focus, closes on Escape or a backdrop click, locks page scroll, restores focus on close and announces quantity changes. Includes an empty state; currency and locale are configurable.

E-commerceBlockTailwind v4

Source

"use client";

import * as React from "react";
import { Minus, Plus, ShoppingBag, Truck, X } from "lucide-react";
import { cn } from "@/lib/utils";

export interface CartLine {
  id: string;
  name: string;
  /** e.g. "Moss · M" */
  variant?: string;
  /** Unit price. */
  price: number;
  quantity: number;
  maxQuantity?: number;
  /** Image or illustration. Defaults to a tile in `color`. */
  thumbnail?: React.ReactNode;
  color?: string;
}

export interface CartDrawerProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  items: CartLine[];
  onQuantityChange: (id: string, quantity: number) => void;
  onRemove: (id: string) => void;
  onCheckout?: () => void;
  /** Subtotal that unlocks free shipping. Omit to hide the progress bar. */
  freeShippingThreshold?: number;
  currency?: string;
  locale?: string;
  title?: string;
}

const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring";
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])';

/* Keeps the panel mounted until its exit transition ends; entry uses @starting-style (Tailwind `starting:`). */
function usePresence(open: boolean, duration = 250) {
  const [mounted, setMounted] = React.useState(open);
  React.useEffect(() => {
    if (open) {
      setMounted(true);
      return;
    }
    const timer = setTimeout(() => setMounted(false), duration);
    return () => clearTimeout(timer);
  }, [open, duration]);
  return mounted || open;
}

export function CartDrawer({
  open,
  onOpenChange,
  items,
  onQuantityChange,
  onRemove,
  onCheckout,
  freeShippingThreshold,
  currency = "USD",
  locale,
  title = "Cart",
}: CartDrawerProps) {
  const mounted = usePresence(open);
  const panelRef = React.useRef<HTMLDivElement>(null);
  const headingRef = React.useRef<HTMLHeadingElement>(null);
  const closeRef = React.useRef<HTMLButtonElement>(null);
  const [message, setMessage] = React.useState("");
  const headingId = React.useId();
  const money = React.useMemo(() => new Intl.NumberFormat(locale, { style: "currency", currency }), [locale, currency]);

  const count = items.reduce((sum, item) => sum + item.quantity, 0);
  const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
  const remaining = freeShippingThreshold !== undefined ? Math.max(0, freeShippingThreshold - subtotal) : 0;
  const progress = freeShippingThreshold ? Math.min(100, (subtotal / freeShippingThreshold) * 100) : 0;

  // Latest callback without re-running the open effect (which would steal focus) on every render.
  const onOpenChangeRef = React.useRef(onOpenChange);
  onOpenChangeRef.current = onOpenChange;

  // Focus trap, Escape, scroll lock, and focus restore while open.
  React.useEffect(() => {
    if (!open) return;
    const previous = document.activeElement as HTMLElement | null;
    closeRef.current?.focus();
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        onOpenChangeRef.current(false);
        return;
      }
      if (event.key !== "Tab" || !panelRef.current) return;
      const list = Array.from(panelRef.current.querySelectorAll<HTMLElement>(FOCUSABLE));
      if (!list.length) return;
      const first = list[0];
      const last = list[list.length - 1];
      if (event.shiftKey && (document.activeElement === first || document.activeElement === panelRef.current)) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    const overflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = overflow;
      previous?.focus?.();
    };
  }, [open]);

  if (!mounted) return null;

  function setQuantity(item: CartLine, quantity: number) {
    onQuantityChange(item.id, quantity);
    setMessage(`${item.name} quantity ${quantity}.`);
  }

  function remove(item: CartLine) {
    onRemove(item.id);
    setMessage(`Removed ${item.name}.`);
    headingRef.current?.focus();
  }

  return (
    <div className="fixed inset-0 z-50">
      <div
        aria-hidden
        onClick={() => onOpenChange(false)}
        className={cn(
          "absolute inset-0 bg-black/40 motion-safe:transition-opacity motion-safe:duration-250 dark:bg-black/60",
          open ? "opacity-100 starting:opacity-0" : "opacity-0",
        )}
      />
      <div
        ref={panelRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby={headingId}
        className={cn(
          "absolute inset-y-0 right-0 flex w-full max-w-md flex-col border-l bg-background text-foreground shadow-2xl motion-safe:transition-transform motion-safe:duration-250 motion-safe:ease-out",
          open ? "translate-x-0 starting:translate-x-full" : "translate-x-full",
        )}
      >
        <header className="flex items-center gap-3 border-b px-5 py-4">
          <h2 id={headingId} ref={headingRef} tabIndex={-1} className="text-base font-semibold tracking-tight outline-none">
            {title}
          </h2>
          {count > 0 && (
            <span className="rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground tabular-nums">
              {count} {count === 1 ? "item" : "items"}
            </span>
          )}
          <button
            ref={closeRef}
            type="button"
            onClick={() => onOpenChange(false)}
            aria-label="Close cart"
            className={cn("ml-auto grid size-9 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground", focusRing)}
          >
            <X aria-hidden className="size-[18px]" />
          </button>
        </header>

        {items.length === 0 ? (
          <div className="flex flex-1 flex-col items-center justify-center gap-4 p-8 text-center">
            <span className="grid size-14 place-items-center rounded-full bg-muted text-muted-foreground">
              <ShoppingBag aria-hidden className="size-6" />
            </span>
            <p className="font-medium">Your cart is empty</p>
            <button
              type="button"
              onClick={() => onOpenChange(false)}
              className={cn("h-9 rounded-md border px-4 text-sm font-medium hover:bg-accent hover:text-accent-foreground", focusRing)}
            >
              Continue shopping
            </button>
          </div>
        ) : (
          <>
            {freeShippingThreshold !== undefined && (
              <div className="border-b px-5 py-4">
                <p className="flex items-center gap-2 text-sm">
                  <Truck aria-hidden className={cn("size-4", remaining === 0 ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground")} />
                  {remaining === 0 ? (
                    <span className="font-medium">Free shipping unlocked</span>
                  ) : (
                    <span>
                      <span className="font-medium tabular-nums">{money.format(remaining)}</span> away from free shipping
                    </span>
                  )}
                </p>
                <div
                  role="progressbar"
                  aria-label="Progress to free shipping"
                  aria-valuemin={0}
                  aria-valuemax={100}
                  aria-valuenow={Math.round(progress)}
                  className="mt-3 h-1.5 overflow-hidden rounded-full bg-muted"
                >
                  <div
                    className={cn("h-full rounded-full motion-safe:transition-[width] motion-safe:duration-500", remaining === 0 ? "bg-emerald-500" : "bg-primary")}
                    style={{ width: `${progress}%` }}
                  />
                </div>
              </div>
            )}

            <ul className="flex-1 divide-y overflow-y-auto px-5" aria-label="Items">
              {items.map((item) => {
                const max = item.maxQuantity ?? 99;
                return (
                  <li key={item.id} className="flex gap-4 py-5">
                    <div
                      className="grid size-20 shrink-0 place-items-center overflow-hidden rounded-lg border"
                      style={{ background: item.color ? `color-mix(in oklab, ${item.color} 16%, var(--muted))` : undefined }}
                    >
                      {item.thumbnail ?? <span aria-hidden className="size-8 rounded-full" style={{ background: item.color || "var(--muted-foreground)" }} />}
                    </div>
                    <div className="flex min-w-0 flex-1 flex-col">
                      <div className="flex items-start justify-between gap-3">
                        <div className="min-w-0">
                          <p className="truncate text-sm font-medium">{item.name}</p>
                          {item.variant && <p className="mt-0.5 truncate text-xs text-muted-foreground">{item.variant}</p>}
                        </div>
                        <p className="shrink-0 text-sm font-medium tabular-nums">{money.format(item.price * item.quantity)}</p>
                      </div>
                      <div className="mt-auto flex items-center justify-between pt-3">
                        <div role="group" aria-label={`Quantity of ${item.name}`} className="inline-flex h-8 items-center rounded-md border">
                          <button
                            type="button"
                            onClick={() => setQuantity(item, item.quantity - 1)}
                            disabled={item.quantity <= 1}
                            aria-label="Decrease quantity"
                            className={cn("grid h-full w-8 place-items-center rounded-l-md text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent", focusRing)}
                          >
                            <Minus aria-hidden className="size-3.5" />
                          </button>
                          <output aria-live="off" className="w-8 text-center text-sm font-medium tabular-nums">
                            {item.quantity}
                          </output>
                          <button
                            type="button"
                            onClick={() => setQuantity(item, item.quantity + 1)}
                            disabled={item.quantity >= max}
                            aria-label="Increase quantity"
                            className={cn("grid h-full w-8 place-items-center rounded-r-md text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent", focusRing)}
                          >
                            <Plus aria-hidden className="size-3.5" />
                          </button>
                        </div>
                        <button
                          type="button"
                          onClick={() => remove(item)}
                          aria-label={`Remove ${item.name}`}
                          className={cn("rounded px-1 text-xs font-medium text-muted-foreground underline-offset-4 hover:text-foreground hover:underline", focusRing)}
                        >
                          Remove
                        </button>
                      </div>
                    </div>
                  </li>
                );
              })}
            </ul>

            <footer className="border-t bg-muted/30 px-5 pt-4 pb-5">
              <dl className="space-y-1.5 text-sm">
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Subtotal</dt>
                  <dd className="font-medium tabular-nums">{money.format(subtotal)}</dd>
                </div>
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Shipping</dt>
                  <dd className={cn("tabular-nums", remaining === 0 && freeShippingThreshold !== undefined ? "font-medium text-emerald-700 dark:text-emerald-400" : "text-muted-foreground")}>
                    {remaining === 0 && freeShippingThreshold !== undefined ? "Free" : "At checkout"}
                  </dd>
                </div>
              </dl>
              <button
                type="button"
                onClick={onCheckout}
                className={cn(
                  "mt-4 inline-flex h-11 w-full items-center justify-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90",
                  focusRing,
                  "focus-visible:ring-offset-2 focus-visible:ring-offset-background",
                )}
              >
                Checkout · <span className="ml-1 tabular-nums">{money.format(subtotal)}</span>
              </button>
              <button
                type="button"
                onClick={() => onOpenChange(false)}
                className={cn("mt-2 h-9 w-full rounded-md text-sm font-medium text-muted-foreground hover:text-foreground", focusRing)}
              >
                Continue shopping
              </button>
            </footer>
          </>
        )}
        <p aria-live="polite" className="sr-only">
          {message}
        </p>
      </div>
    </div>
  );
}