Number 11: Add button that becomes a quantity
Specification
- Catalogue
- No. 11 of 110
- Section
- Buttons and toggles
- Interaction
- Feedback, Layout Animation
- Element
- Button, Counter
- Preview
- Live component
- Imports
- react 19.3.1, @number-flow/react 0.6.2
- Added
Notes
Tap Add and the same button turns into minus, count and plus; at one, minus becomes a bin.
A shopper changes their order where they are, without opening the basket. The button keeps its size, so nothing around it moves, and each change is announced to screen readers.
Add swaps for the stepper in 200ms (fade and 0.96 scale); the box keeps its 8.5rem width. Hold plus or minus to repeat: starts after 450ms, then every 110ms. The count and the basket total roll with NumberFlow. Focus moves to plus after Add, and back to Add after the last one is removed.
The names, figures and pictures in the demo are sample content; a real build uses the client's own.
Code
React and plain CSS"use client";
import { useEffect, useRef, useState } from "react";
import { Num } from "@/components/pieces/shared";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./cart-button.css";
const gbp = { style: "currency", currency: "GBP" } as const;
function Icon({ d, size = 18 }: { d: string; size?: number }) {
return (
<svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d={d} />
</svg>
);
}
const PLUS = "M12 5v14M5 12h14";
const MINUS = "M5 12h14";
const BIN = "M4 7h16M10 11v6M14 11v6M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12M9 7V4h6v3";
/** Press runs once; holding repeats after 450ms, every 110ms. */
function useHold(action: () => void) {
const timers = useRef<{ t?: number; i?: number; repeated: boolean }>({ repeated: false });
const stop = () => {
window.clearTimeout(timers.current.t);
window.clearInterval(timers.current.i);
};
useEffect(() => stop, []);
return {
onPointerDown: () => {
timers.current.repeated = false;
stop();
timers.current.t = window.setTimeout(() => {
timers.current.repeated = true;
action();
timers.current.i = window.setInterval(action, 110);
}, 450);
},
onPointerUp: stop,
onPointerLeave: stop,
onPointerCancel: stop,
onClick: () => {
// A hold already acted; the click that ends it must not add one more.
if (timers.current.repeated) {
timers.current.repeated = false;
return;
}
action();
},
};
}
const MAX_QTY = 20;
function CartButton({ name, qty, setQty }: { name: string; qty: number; setQty: (n: number | ((q: number) => number)) => void }) {
const addRef = useRef<HTMLButtonElement>(null);
const plusRef = useRef<HTMLButtonElement>(null);
const focusNext = useRef<"add" | "plus" | null>(null);
useEffect(() => {
if (focusNext.current === "add") addRef.current?.focus();
if (focusNext.current === "plus") plusRef.current?.focus();
focusNext.current = null;
}, [qty]);
const inc = useHold(() => setQty((q) => Math.min(MAX_QTY, q + 1)));
const dec = useHold(() =>
setQty((q) => {
if (q <= 1) focusNext.current = "add";
return Math.max(0, q - 1);
}),
);
return (
<div className="cart-btn" data-open={qty > 0 || undefined}>
{qty === 0 ? (
<button
ref={addRef}
type="button"
className="cart-add"
onClick={() => {
focusNext.current = "plus";
setQty(1);
}}
>
<Icon d={PLUS} size={16} />
Add
<span className="sr-only"> {name} to basket</span>
</button>
) : (
<div className="cart-step" role="group" aria-label={`${name} in basket`}>
<button type="button" className="cart-icon" aria-label={qty === 1 ? `Remove ${name}` : `One fewer ${name}`} {...dec}>
<Icon d={qty === 1 ? BIN : MINUS} />
</button>
<span className="cart-qty" aria-hidden="true">
<Num value={qty} />
</span>
<button ref={plusRef} type="button" className="cart-icon" aria-label={`One more ${name}`} disabled={qty >= MAX_QTY} {...inc}>
<Icon d={PLUS} />
</button>
</div>
)}
</div>
);
}
const BAKES = [
{ id: "loaf", name: "Sourdough loaf", note: "800g, baked this morning", price: 4.5 },
{ id: "buns", name: "Cardamom buns", note: "Box of four", price: 9 },
];
function CartButtonDemo() {
const [qty, setQty] = useState<Record<string, number>>({ loaf: 0, buns: 0 });
const items = BAKES.reduce((n, b) => n + (qty[b.id] ?? 0), 0);
const total = BAKES.reduce((n, b) => n + (qty[b.id] ?? 0) * b.price, 0);
const [said, setSaid] = useState("");
return (
<div className="dm">
<ul className="cart-list" aria-label="Sample bakery menu">
{BAKES.map((b) => (
<li key={b.id} className="cart-row">
<div className="cart-name">
<strong>{b.name}</strong>
<span>
{b.note} · {new Intl.NumberFormat("en-GB", gbp).format(b.price)}
</span>
</div>
<CartButton
name={b.name}
qty={qty[b.id] ?? 0}
setQty={(n) =>
setQty((cur) => {
const next = typeof n === "function" ? n(cur[b.id] ?? 0) : n;
setSaid(next === 0 ? `${b.name} removed from basket` : `${next} ${b.name.toLowerCase()} in basket`);
return { ...cur, [b.id]: next };
})
}
/>
</li>
))}
</ul>
<p className="cart-total">
<span>
Basket: {items} {items === 1 ? "item" : "items"}
</span>
<strong>
<Num value={total} format={gbp} />
</strong>
</p>
<p className="sr-only" aria-live="polite">
{said}
</p>
</div>
);
}
// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [
{ click: ".cart-add", nth: 0, wait: 1300 },
// The first Add is now a quantity, so the remaining Add is the first match again.
{ click: ".cart-add", nth: 0, wait: 1800 },
];
export default function CartButtonEntry(props: LivePreviewProps) {
return (
<PieceStage {...props} label="Add button that becomes a quantity" sample tour={TOUR}>
<CartButtonDemo />
</PieceStage>
);
}