Cart drawer
A side drawer shopping cart with quantity steppers, a free-shipping progress bar, swipe-to-remove items and a total that updates as you go.
"use client";
import {
useEffect,
useRef,
useState,
type CSSProperties,
type PointerEvent as ReactPointerEvent,
} from "react";
import "./cart-drawer.css";
type Line = {
id: string;
name: string;
variant: string;
price: number;
qty: number;
image: string;
tone: string;
};
const START: Line[] = [
{
id: "a",
name: "Linen overshirt",
variant: "Sand · M",
price: 89,
qty: 1,
image: "/images/components-cart-drawer-item-01.jpg",
tone: "#d9c9a8",
},
{
id: "b",
name: "Ceramic pour-over set",
variant: "Speckled white",
price: 46,
qty: 2,
image: "/images/components-cart-drawer-item-02.jpg",
tone: "#e6e0d6",
},
{
id: "c",
name: "Canvas weekender bag",
variant: "Olive",
price: 120,
qty: 1,
image: "/images/components-cart-drawer-item-03.jpg",
tone: "#8a8f6a",
},
];
const FREE_SHIPPING = 300;
const money = (n: number) => `€${n.toFixed(2)}`;
function Thumb({ src, tone }: { src: string; tone: string }) {
const img = useRef<HTMLImageElement>(null);
const [missing, setMissing] = useState(false);
useEffect(() => {
const el = img.current;
if (el && el.complete && el.naturalWidth === 0) setMissing(true);
}, []);
return (
<span className="gu-cart__thumb" style={{ background: tone }}>
{!missing && (
<img ref={img} src={src} alt="" onError={() => setMissing(true)} />
)}
</span>
);
}
/** One cart line that can be dragged left to reveal a Remove button. */
function Row({
line,
onQty,
onRemove,
}: {
line: Line;
onQty: (q: number) => void;
onRemove: () => void;
}) {
const [dx, setDx] = useState(0);
const start = useRef<{ x: number; y: number; base: number } | null>(null);
const [leaving, setLeaving] = useState(false);
const [dragging, setDragging] = useState(false);
const remove = () => {
setLeaving(true);
setTimeout(
onRemove,
matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 300,
);
};
const down = (e: ReactPointerEvent<HTMLDivElement>) => {
if ((e.target as HTMLElement).closest("button")) return;
start.current = { x: e.clientX, y: e.clientY, base: dx };
};
const move = (e: ReactPointerEvent<HTMLDivElement>) => {
if (!start.current) return;
const mx = e.clientX - start.current.x;
if (Math.abs(mx) < 6) return;
e.currentTarget.setPointerCapture(e.pointerId);
setDragging(true);
setDx(Math.max(-96, Math.min(0, start.current.base + mx)));
};
const up = () => {
if (!start.current) return;
start.current = null;
setDragging(false);
setDx((d) => (d < -48 ? -96 : 0)); // snap open or closed
};
return (
<li className="gu-cart__line" data-leaving={leaving ? "" : undefined}>
<button
type="button"
className="gu-cart__swipe-remove"
onClick={remove}
tabIndex={dx ? 0 : -1}
aria-hidden={!dx}
>
Remove
</button>
<div
className="gu-cart__item"
style={{ "--dx": `${dx}px` } as CSSProperties}
data-dragging={dragging ? "" : undefined}
onPointerDown={down}
onPointerMove={move}
onPointerUp={up}
onPointerCancel={up}
>
<Thumb src={line.image} tone={line.tone} />
<span className="gu-cart__info">
<b>{line.name}</b>
<small>{line.variant}</small>
<span
className="gu-cart__qty"
role="group"
aria-label={`Quantity of ${line.name}`}
>
<button
type="button"
onClick={() => (line.qty > 1 ? onQty(line.qty - 1) : remove())}
aria-label={line.qty > 1 ? "One less" : `Remove ${line.name}`}
>
{line.qty > 1 ? "−" : "×"}
</button>
<output aria-live="polite">{line.qty}</output>
<button
type="button"
onClick={() => onQty(line.qty + 1)}
aria-label="One more"
>
+
</button>
</span>
</span>
<span className="gu-cart__price">{money(line.price * line.qty)}</span>
</div>
</li>
);
}
/**
* CartDrawer
* - A native <dialog> opened with showModal(), styled as a right-side drawer.
* - Free-shipping bar fills toward FREE_SHIPPING and turns lime when reached.
*/
export function CartDrawer({ theme = "light" }: { theme?: "light" | "dark" }) {
const dialog = useRef<HTMLDialogElement>(null);
const [lines, setLines] = useState(START);
const count = lines.reduce((s, l) => s + l.qty, 0);
const subtotal = lines.reduce((s, l) => s + l.qty * l.price, 0);
const left = Math.max(0, FREE_SHIPPING - subtotal);
return (
<div className="gu-cart" data-theme={theme}>
<button
type="button"
className="gu-cart__open"
onClick={() => dialog.current?.showModal()}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M5 8h14l-1.2 11.1a2 2 0 0 1-2 1.9H8.2a2 2 0 0 1-2-1.9zM9 8V6a3 3 0 0 1 6 0v2" />
</svg>
Bag
<span key={count} className="gu-cart__badge">
{count}
</span>
</button>
<dialog
ref={dialog}
className="gu-cart__drawer"
data-theme={theme}
aria-labelledby="gu-cart-title"
onClick={(e) => e.target === e.currentTarget && dialog.current?.close()}
>
<div className="gu-cart__inner">
<header>
<h2 id="gu-cart-title">
Your bag <span>({count})</span>
</h2>
<button
type="button"
className="gu-cart__close"
onClick={() => dialog.current?.close()}
aria-label="Close bag"
>
<svg viewBox="0 0 16 16" aria-hidden="true">
<path d="m4 4 8 8m0-8-8 8" />
</svg>
</button>
</header>
<div
className="gu-cart__ship"
data-free={left === 0 ? "" : undefined}
style={
{ "--p": Math.min(1, subtotal / FREE_SHIPPING) } as CSSProperties
}
>
<p>
{left ? (
<>You're {money(left)} away from free shipping</>
) : (
<>Free shipping unlocked 🎉</>
)}
</p>
<span
className="gu-cart__bar"
role="progressbar"
aria-label="Progress to free shipping"
aria-valuemin={0}
aria-valuemax={FREE_SHIPPING}
aria-valuenow={Math.min(subtotal, FREE_SHIPPING)}
/>
</div>
{lines.length ? (
<ul className="gu-cart__lines">
{lines.map((l) => (
<Row
key={l.id}
line={l}
onQty={(q) =>
setLines((ls) =>
ls.map((x) => (x.id === l.id ? { ...x, qty: q } : x)),
)
}
onRemove={() =>
setLines((ls) => ls.filter((x) => x.id !== l.id))
}
/>
))}
</ul>
) : (
<div className="gu-cart__empty">
<p>Your bag is empty.</p>
<button type="button" onClick={() => setLines(START)}>
Refill the demo bag
</button>
</div>
)}
<footer>
<p>
<span>Subtotal</span>
<b>{money(subtotal)}</b>
</p>
<small>Taxes included. Shipping calculated at checkout.</small>
<a
href="#checkout"
className="gu-cart__checkout"
aria-disabled={!lines.length}
>
Checkout
</a>
</footer>
</div>
</dialog>
</div>
);
}
Paste this into ChatGPT, Claude, Cursor, v0, Lovable or Bolt. It describes the layout, motion, colors and accessibility and includes the code, so the AI can rebuild it in any framework.
# Build this UI piece: Cart drawer
You are a senior front-end engineer. Recreate the piece below in my project. If I don't say which framework I use, ask once, then build it in that framework (React, Vue, Svelte, Angular, Astro, plain HTML/CSS/JS or anything else). Keep the behavior, motion, colors, spacing and accessibility exactly as described. Keep the code clean and commented for beginners.
## What it is
A shopping cart drawer on the native <dialog> element: it slides in from the right with a free-shipping progress bar, cart lines with quantity steppers, swipe-left-to-remove, and a sticky subtotal with an orange Checkout button.
## Layout and look
- Trigger: Ink pill "Bag" with a bag icon and an orange count badge that bumps when the count changes.
- Drawer: 420px wide (full width on phones), full height, card background, soft left shadow, 50% Ink backdrop.
- Header: "Your bag (4)" (26px, weight 900) and a 44px round close button.
- Shipping box: soft tinted panel, "You're €39.00 away from free shipping", a 6px bar filling orange, lime when unlocked.
- Lines: 72×88 photo (rounded 12px), name, variant, a pill quantity stepper (− count +; − becomes × at 1), and the line price on the right; hairline separators.
- Footer: Subtotal row, a muted tax line, 56px orange Checkout.
## Behavior and motion
1. showModal(); backdrop click and Escape close. Opening slides in from 100% (500ms cubic-bezier(0.16, 1, 0.3, 1)).
2. Drag a line left: it follows the pointer (max 96px), snaps open past 48px, revealing a red Remove button.
3. Removing collapses the row height (grid-template-rows 1fr → 0fr) and fades it out.
4. The shipping bar fills with scaleX.
## Images
Three product photos (4:5). Until they exist, each thumb shows a striped tone block.
## Accessibility
- Dialog labelled by its title; quantity groups labelled per product with a polite live count; progressbar with values; the swipe Remove button is only focusable when revealed (the − / × button is the keyboard path).
- prefers-reduced-motion: no slides or collapses.
## Props
theme. Edit START, FREE_SHIPPING and money().
## Reference implementation
The original is written in React with one plain CSS file. Dependencies: none (plain React and CSS). Translate it faithfully; do not add new libraries unless my framework needs them.
### CartDrawer.tsx
```tsx
"use client";
import {
useEffect,
useRef,
useState,
type CSSProperties,
type PointerEvent as ReactPointerEvent,
} from "react";
import "./cart-drawer.css";
type Line = {
id: string;
name: string;
variant: string;
price: number;
qty: number;
image: string;
tone: string;
};
const START: Line[] = [
{
id: "a",
name: "Linen overshirt",
variant: "Sand · M",
price: 89,
qty: 1,
image: "/images/components-cart-drawer-item-01.jpg",
tone: "#d9c9a8",
},
{
id: "b",
name: "Ceramic pour-over set",
variant: "Speckled white",
price: 46,
qty: 2,
image: "/images/components-cart-drawer-item-02.jpg",
tone: "#e6e0d6",
},
{
id: "c",
name: "Canvas weekender bag",
variant: "Olive",
price: 120,
qty: 1,
image: "/images/components-cart-drawer-item-03.jpg",
tone: "#8a8f6a",
},
];
const FREE_SHIPPING = 300;
const money = (n: number) => `€${n.toFixed(2)}`;
function Thumb({ src, tone }: { src: string; tone: string }) {
const img = useRef<HTMLImageElement>(null);
const [missing, setMissing] = useState(false);
useEffect(() => {
const el = img.current;
if (el && el.complete && el.naturalWidth === 0) setMissing(true);
}, []);
return (
<span className="gu-cart__thumb" style={{ background: tone }}>
{!missing && (
<img ref={img} src={src} alt="" onError={() => setMissing(true)} />
)}
</span>
);
}
/** One cart line that can be dragged left to reveal a Remove button. */
function Row({
line,
onQty,
onRemove,
}: {
line: Line;
onQty: (q: number) => void;
onRemove: () => void;
}) {
const [dx, setDx] = useState(0);
const start = useRef<{ x: number; y: number; base: number } | null>(null);
const [leaving, setLeaving] = useState(false);
const [dragging, setDragging] = useState(false);
const remove = () => {
setLeaving(true);
setTimeout(
onRemove,
matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 300,
);
};
const down = (e: ReactPointerEvent<HTMLDivElement>) => {
if ((e.target as HTMLElement).closest("button")) return;
start.current = { x: e.clientX, y: e.clientY, base: dx };
};
const move = (e: ReactPointerEvent<HTMLDivElement>) => {
if (!start.current) return;
const mx = e.clientX - start.current.x;
if (Math.abs(mx) < 6) return;
e.currentTarget.setPointerCapture(e.pointerId);
setDragging(true);
setDx(Math.max(-96, Math.min(0, start.current.base + mx)));
};
const up = () => {
if (!start.current) return;
start.current = null;
setDragging(false);
setDx((d) => (d < -48 ? -96 : 0)); // snap open or closed
};
return (
<li className="gu-cart__line" data-leaving={leaving ? "" : undefined}>
<button
type="button"
className="gu-cart__swipe-remove"
onClick={remove}
tabIndex={dx ? 0 : -1}
aria-hidden={!dx}
>
Remove
</button>
<div
className="gu-cart__item"
style={{ "--dx": `${dx}px` } as CSSProperties}
data-dragging={dragging ? "" : undefined}
onPointerDown={down}
onPointerMove={move}
onPointerUp={up}
onPointerCancel={up}
>
<Thumb src={line.image} tone={line.tone} />
<span className="gu-cart__info">
<b>{line.name}</b>
<small>{line.variant}</small>
<span
className="gu-cart__qty"
role="group"
aria-label={`Quantity of ${line.name}`}
>
<button
type="button"
onClick={() => (line.qty > 1 ? onQty(line.qty - 1) : remove())}
aria-label={line.qty > 1 ? "One less" : `Remove ${line.name}`}
>
{line.qty > 1 ? "−" : "×"}
</button>
<output aria-live="polite">{line.qty}</output>
<button
type="button"
onClick={() => onQty(line.qty + 1)}
aria-label="One more"
>
+
</button>
</span>
</span>
<span className="gu-cart__price">{money(line.price * line.qty)}</span>
</div>
</li>
);
}
/**
* CartDrawer
* - A native <dialog> opened with showModal(), styled as a right-side drawer.
* - Free-shipping bar fills toward FREE_SHIPPING and turns lime when reached.
*/
export function CartDrawer({ theme = "light" }: { theme?: "light" | "dark" }) {
const dialog = useRef<HTMLDialogElement>(null);
const [lines, setLines] = useState(START);
const count = lines.reduce((s, l) => s + l.qty, 0);
const subtotal = lines.reduce((s, l) => s + l.qty * l.price, 0);
const left = Math.max(0, FREE_SHIPPING - subtotal);
return (
<div className="gu-cart" data-theme={theme}>
<button
type="button"
className="gu-cart__open"
onClick={() => dialog.current?.showModal()}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M5 8h14l-1.2 11.1a2 2 0 0 1-2 1.9H8.2a2 2 0 0 1-2-1.9zM9 8V6a3 3 0 0 1 6 0v2" />
</svg>
Bag
<span key={count} className="gu-cart__badge">
{count}
</span>
</button>
<dialog
ref={dialog}
className="gu-cart__drawer"
data-theme={theme}
aria-labelledby="gu-cart-title"
onClick={(e) => e.target === e.currentTarget && dialog.current?.close()}
>
<div className="gu-cart__inner">
<header>
<h2 id="gu-cart-title">
Your bag <span>({count})</span>
</h2>
<button
type="button"
className="gu-cart__close"
onClick={() => dialog.current?.close()}
aria-label="Close bag"
>
<svg viewBox="0 0 16 16" aria-hidden="true">
<path d="m4 4 8 8m0-8-8 8" />
</svg>
</button>
</header>
<div
className="gu-cart__ship"
data-free={left === 0 ? "" : undefined}
style={
{ "--p": Math.min(1, subtotal / FREE_SHIPPING) } as CSSProperties
}
>
<p>
{left ? (
<>You're {money(left)} away from free shipping</>
) : (
<>Free shipping unlocked 🎉</>
)}
</p>
<span
className="gu-cart__bar"
role="progressbar"
aria-label="Progress to free shipping"
aria-valuemin={0}
aria-valuemax={FREE_SHIPPING}
aria-valuenow={Math.min(subtotal, FREE_SHIPPING)}
/>
</div>
{lines.length ? (
<ul className="gu-cart__lines">
{lines.map((l) => (
<Row
key={l.id}
line={l}
onQty={(q) =>
setLines((ls) =>
ls.map((x) => (x.id === l.id ? { ...x, qty: q } : x)),
)
}
onRemove={() =>
setLines((ls) => ls.filter((x) => x.id !== l.id))
}
/>
))}
</ul>
) : (
<div className="gu-cart__empty">
<p>Your bag is empty.</p>
<button type="button" onClick={() => setLines(START)}>
Refill the demo bag
</button>
</div>
)}
<footer>
<p>
<span>Subtotal</span>
<b>{money(subtotal)}</b>
</p>
<small>Taxes included. Shipping calculated at checkout.</small>
<a
href="#checkout"
className="gu-cart__checkout"
aria-disabled={!lines.length}
>
Checkout
</a>
</footer>
</div>
</dialog>
</div>
);
}
```
### cart-drawer.css
```css
/* CartDrawer: change these colors to match your brand. */
.gu-cart,
.gu-cart__drawer {
--card: #fbf8f2;
--text: #0e0e10;
--muted: #57534b;
--line: rgb(14 14 16 / 0.12);
--soft: rgb(14 14 16 / 0.06);
--accent: #ff5a1f;
--volt: #d7ff3a;
--danger: #dc2626;
--focus: #2b35ff;
--ease: cubic-bezier(0.16, 1, 0.3, 1);
color: var(--text);
font-family: system-ui, sans-serif;
}
.gu-cart[data-theme="dark"],
.gu-cart__drawer[data-theme="dark"] {
--card: #18181b;
--text: #f3eee3;
--muted: #aea89c;
--line: rgb(243 238 227 / 0.12);
--soft: rgb(243 238 227 / 0.07);
--focus: #d7ff3a;
}
.gu-cart button,
.gu-cart__drawer button {
font: inherit;
cursor: pointer;
}
.gu-cart :focus-visible,
.gu-cart__drawer :focus-visible {
outline: 3px solid var(--focus);
outline-offset: 2px;
}
.gu-cart__open {
display: inline-flex;
align-items: center;
gap: 10px;
min-height: 52px;
padding: 0 10px 0 20px;
border: 0;
border-radius: 999px;
background: var(--text);
color: var(--card);
font-weight: 800 !important;
}
.gu-cart__open svg,
.gu-cart__close svg {
width: 20px;
fill: none;
stroke: currentColor;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
.gu-cart__badge {
display: grid;
place-items: center;
min-width: 32px;
height: 32px;
border-radius: 999px;
background: var(--accent);
color: #0e0e10;
animation: gu-cart-bump 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
}
@keyframes gu-cart-bump {
40% {
transform: scale(1.3);
}
}
/* Drawer = dialog pinned to the right edge */
.gu-cart__drawer {
width: min(420px, 100vw);
max-width: none;
height: 100dvh;
max-height: none;
margin: 0 0 0 auto;
padding: 0;
border: 0;
background: var(--card);
box-shadow: -30px 0 60px -30px rgb(0 0 0 / 0.4);
}
.gu-cart__drawer[open] {
animation: gu-cart-in 0.5s var(--ease);
}
.gu-cart__drawer::backdrop {
background: rgb(14 14 16 / 0.5);
animation: gu-cart-fade 0.3s;
}
@keyframes gu-cart-in {
from {
transform: translateX(100%);
}
}
@keyframes gu-cart-fade {
from {
opacity: 0;
}
}
.gu-cart__inner {
display: grid;
grid-template-rows: auto auto 1fr auto;
height: 100%;
}
.gu-cart__inner header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px 20px 12px 24px;
}
.gu-cart__inner h2 {
margin: 0;
font-size: 1.6rem;
font-weight: 900;
letter-spacing: -0.03em;
}
.gu-cart__inner h2 span {
color: var(--muted);
font-weight: 600;
}
.gu-cart__close {
display: grid;
place-items: center;
width: 44px;
height: 44px;
border: 0;
border-radius: 50%;
background: var(--soft);
color: inherit;
}
.gu-cart__ship {
margin: 0 24px 8px;
padding: 14px;
border-radius: 16px;
background: var(--soft);
}
.gu-cart__ship p {
margin: 0 0 10px;
font-size: 0.88rem;
font-weight: 700;
}
.gu-cart__bar {
display: block;
height: 6px;
border-radius: 6px;
background: var(--line);
overflow: hidden;
}
.gu-cart__bar::after {
content: "";
display: block;
height: 100%;
border-radius: inherit;
background: var(--accent);
transform: scaleX(var(--p));
transform-origin: left;
transition:
transform 0.6s var(--ease),
background-color 0.3s;
}
.gu-cart__ship[data-free] .gu-cart__bar::after {
background: var(--volt);
}
.gu-cart__lines {
margin: 0;
padding: 8px 24px;
overflow: auto;
list-style: none;
}
.gu-cart__line {
position: relative;
display: grid;
grid-template-rows: 1fr;
border-bottom: 1px solid var(--line);
overflow: hidden;
transition:
grid-template-rows 0.3s var(--ease),
opacity 0.3s,
border-color 0.3s;
}
.gu-cart__line[data-leaving] {
grid-template-rows: 0fr;
opacity: 0;
border-color: transparent;
}
.gu-cart__swipe-remove {
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 96px;
border: 0;
background: var(--danger);
color: #fff;
font-weight: 800 !important;
}
.gu-cart__item {
position: relative;
display: grid;
grid-template-columns: 72px 1fr auto;
gap: 14px;
min-height: 0;
padding: 16px 0;
background: var(--card);
transform: translateX(var(--dx));
transition: transform 0.35s var(--ease);
touch-action: pan-y;
user-select: none;
}
.gu-cart__item[data-dragging] {
transition: none;
}
.gu-cart__thumb {
position: relative;
width: 72px;
height: 88px;
overflow: hidden;
border-radius: 12px;
background-image: repeating-linear-gradient(
135deg,
rgb(255 255 255 / 0.2) 0 2px,
transparent 2px 12px
) !important;
}
.gu-cart__thumb img {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.gu-cart__info {
display: grid;
align-content: start;
gap: 2px;
min-width: 0;
}
.gu-cart__info b {
font-size: 0.95rem;
}
.gu-cart__info small {
color: var(--muted);
}
.gu-cart__qty {
display: inline-flex;
align-items: center;
justify-self: start;
margin-top: 8px;
border: 1px solid var(--line);
border-radius: 999px;
}
.gu-cart__qty button {
width: 40px;
height: 36px;
border: 0;
border-radius: 999px;
background: none;
color: inherit;
font-size: 1.1rem !important;
}
.gu-cart__qty button:hover {
background: var(--soft);
}
.gu-cart__qty output {
min-width: 1.6em;
font-weight: 800;
text-align: center;
font-variant-numeric: tabular-nums;
}
.gu-cart__price {
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.gu-cart__empty {
display: grid;
place-content: center;
justify-items: center;
gap: 12px;
color: var(--muted);
}
.gu-cart__empty button {
min-height: 44px;
padding: 0 18px;
border: 1.5px solid var(--line);
border-radius: 999px;
background: none;
color: var(--text);
font-weight: 700 !important;
}
.gu-cart__inner footer {
display: grid;
gap: 6px;
padding: 18px 24px 24px;
border-top: 1px solid var(--line);
}
.gu-cart__inner footer p {
display: flex;
justify-content: space-between;
margin: 0;
font-size: 1.1rem;
font-weight: 700;
}
.gu-cart__inner footer small {
color: var(--muted);
}
.gu-cart__checkout {
display: grid;
place-items: center;
min-height: 56px;
margin-top: 10px;
border-radius: 999px;
background: var(--accent);
color: #0e0e10;
font-weight: 800;
text-decoration: none;
}
.gu-cart__checkout[aria-disabled="true"] {
opacity: 0.4;
pointer-events: none;
}
@media (prefers-reduced-motion: reduce) {
.gu-cart__drawer[open],
.gu-cart__drawer::backdrop,
.gu-cart__badge {
animation: none;
}
.gu-cart__line,
.gu-cart__item,
.gu-cart__bar::after {
transition: none;
}
}
```
You might also want
Next piece: Collapsible sidebarDraggable bottom sheet
Components, advanced
Activity rings
Components, intermediate
Stacked toasts
Components, advanced