Checkout
Checkout flow on Stepper — shipping with a gliding delivery-speed choice, display-only payment fields and an editable review — beside an order summary with compact quantity steppers, a promo code that shakes when invalid and pops a removable badge when valid, and subtotal, discount, tax and total that roll on every change.
Preview
Install
Add it with the shadcn CLI, or copy the source manually.
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import { useEffect, useState } from "react";
/**
* Returns true only on devices that have a true hover (mouse / trackpad).
* Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere
* — gate hover-only effects (scale lifts, magnetic pulls) behind this.
*/
export function useHoverCapable() {
const [canHover, setCanHover] = useState(false);
useEffect(() => {
if (typeof window === "undefined" || !window.matchMedia) return;
const mq = window.matchMedia("(hover: hover) and (pointer: fine)");
const update = () => setCanHover(mq.matches);
update();
mq.addEventListener?.("change", update);
return () => mq.removeEventListener?.("change", update);
}, []);
return canHover;
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Grow a small control's *hit area* to at least 44×44px (WCAG 2.5.5, Apple
* HIG) on a coarse pointer, without changing what it looks like or the space
* it takes in layout. An invisible `::after` box, centered on the control and
* `max(100%, 2.75rem)` on each axis, catches the taps: a 32px icon button
* reaches 6px past each edge, a wide 40px button only grows vertically, and a
* control already 44px or larger is left as it is. Hit-testing a pseudo
* element lands on its owner, so handlers, focus and `:active` all behave.
*
* Mouse and trackpad rendering is untouched — nothing here applies outside
* `pointer: coarse`. Requirements on the element it goes on:
* - It must be the containing block: add `relative` (and keep it mergeable, so
* a consumer's `absolute` still wins through `cn`).
* - It must not clip itself (`overflow-hidden`), or the overhang is clipped
* away along with its hit area.
* - It must render children: `<input>` and other void elements have no
* `::after`. Put it on the wrapper or label instead.
* - It must not already use `::after` for something visible.
*
* Centered 44px means two 32px buttons with a 4px gap overlap by 8px; the
* later one wins that strip, which still ends well short of the earlier
* button's visual center. Below a ~32px pitch the later neighbour starts
* eating into that center — use `TOUCH_TARGET_Y_CLASS` for such dense rows.
*
* The overhang is real geometry: inside a scroll container it counts as
* scrollable overflow, so a control flush against a scroller's edge can add a
* few pixels of scroll on touch screens. Give such a scroller a little padding
* on that side.
*/
export const TOUCH_TARGET_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-[max(100%,2.75rem)] pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* `TOUCH_TARGET_CLASS` on the vertical axis only, for controls packed tighter
* than ~32px apart in a row (pagination dots, dense swatches), where growing
* sideways would hand most of each control to its neighbour. Same rules.
*/
export const TOUCH_TARGET_Y_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:top-1/2 pointer-coarse:after:h-[max(100%,2.75rem)] pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
Copy the source code
"use client";
// karaui.kamisama-v0.my.id/components/blocks/checkout
import { Lock, Minus, Plus, Tag, Truck, Zap } from "lucide-react";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import { type ReactNode, useCallback, useId, useMemo, useRef, useState } from "react";
import { Badge } from "@/components/motion/badge";
import { Button, StatefulButton } from "@/components/motion/button";
import { Input } from "@/components/motion/input";
import { NumberTicker } from "@/components/motion/number-ticker";
import {
Stepper,
StepperIndicator,
StepperNext,
StepperPanels,
StepperPrevious,
type StepperStep,
useStepper,
} from "@/components/motion/stepper";
import { EASE_OUT, SPRING_LAYOUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type CheckoutItem = {
id: string;
name: string;
/** Secondary line — size, color, plan. */
variant?: string;
/** Unit price in major units (12.5 = $12.50). */
price: number;
quantity: number;
/** Thumbnail node; defaults to a tinted swatch. */
image?: ReactNode;
};
export type CheckoutPromo = {
code: string;
label: string;
/** Percentage off the subtotal (0–100). */
percentOff?: number;
/** Fixed amount off, in major units. */
amountOff?: number;
};
export type CheckoutShipping = {
name: string;
address: string;
city: string;
zip: string;
};
export type CheckoutDelivery = "standard" | "express";
export type CheckoutTotals = {
subtotal: number;
discount: number;
shipping: number;
tax: number;
total: number;
};
export type CheckoutOrder = {
items: CheckoutItem[];
shipping: CheckoutShipping;
delivery: CheckoutDelivery;
promo: CheckoutPromo | null;
totals: CheckoutTotals;
};
export interface CheckoutProps {
items?: CheckoutItem[];
defaultItems?: CheckoutItem[];
onItemsChange?: (items: CheckoutItem[]) => void;
/** Known codes (case-insensitive) when `onApplyPromo` isn't given. */
promoCodes?: CheckoutPromo[];
/** Async promo check. Resolve with the promo, reject to mark the code invalid. */
onApplyPromo?: (code: string) => Promise<CheckoutPromo>;
/**
* Places the order. Card fields are UI only and never included — wire a
* payment provider's hosted fields for real card entry. Resolve with an
* order reference to show it; reject to show the message on the review step.
*/
onComplete?: (order: CheckoutOrder) => Promise<string | undefined> | string | undefined;
/** Sales tax rate (0.08 = 8%). Default 0.08. */
taxRate?: number;
/** Express delivery price in major units. Default 15. */
expressPrice?: number;
currency?: string;
locale?: string;
className?: string;
}
const STEPS: StepperStep[] = [
{ id: "shipping", title: "Shipping" },
{ id: "payment", title: "Payment" },
{ id: "review", title: "Review" },
];
const SWATCHES = ["bg-chart-1", "bg-chart-2", "bg-chart-3", "bg-chart-4", "bg-chart-5"];
const SHAKE = { x: [0, -6, 6, -4, 4, -2, 0] };
const EMPTY_SHIPPING: CheckoutShipping = { name: "", address: "", city: "", zip: "" };
const cents = (major: number) => Math.round(major * 100);
function digits(value: string, max: number) {
return value.replace(/\D/g, "").slice(0, max);
}
function messageOf(reason: unknown, fallback: string) {
if (reason instanceof Error && reason.message) return reason.message;
if (typeof reason === "string" && reason) return reason;
return fallback;
}
/** Money that rolls when it changes. Values are cents so decimals survive `NumberTicker`'s rounding. */
function Money({
value,
format,
className,
}: {
value: number;
format: (cents: number) => string;
className?: string;
}) {
return (
<NumberTicker
value={value}
format={format}
startOnView={false}
duration={0.5}
stagger={0.015}
className={cn("tabular-nums", className)}
/>
);
}
/**
* Compact quantity control. `NumberStepper`'s 48px editable field is too big
* for a summary line, so this keeps two pressable buttons around a rolling
* digit and exposes the same spinbutton semantics.
*/
function Quantity({
value,
onChange,
label,
min = 1,
max = 9,
}: {
value: number;
onChange: (next: number) => void;
label: string;
min?: number;
max?: number;
}) {
const reduce = useReducedMotion();
const button = (dir: -1 | 1) => {
const Icon = dir < 0 ? Minus : Plus;
const blocked = dir < 0 ? value <= min : value >= max;
return (
<motion.button
type="button"
aria-label={`${dir < 0 ? "Decrease" : "Increase"} ${label}`}
disabled={blocked}
whileTap={reduce || blocked ? undefined : { scale: 0.85 }}
transition={SPRING_PRESS}
onClick={() => onChange(value + dir)}
className="grid size-6 place-items-center rounded-full text-foreground outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring disabled:text-muted-foreground/50 disabled:hover:bg-transparent"
>
<Icon className="size-3" aria-hidden />
</motion.button>
);
};
return (
<div className="inline-flex items-center gap-0.5 rounded-full border border-border bg-background p-0.5">
{button(-1)}
<span
role="spinbutton"
tabIndex={0}
aria-label={label}
aria-valuenow={value}
aria-valuemin={min}
aria-valuemax={max}
onKeyDown={(event) => {
if (event.key === "ArrowUp" && value < max) {
event.preventDefault();
onChange(value + 1);
} else if (event.key === "ArrowDown" && value > min) {
event.preventDefault();
onChange(value - 1);
}
}}
className="min-w-4 rounded text-center text-xs font-semibold outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<NumberTicker value={value} startOnView={false} duration={0.35} stagger={0} />
</span>
{button(1)}
</div>
);
}
/** Finish button that shows the total and the stepper's pending state. */
function PlaceOrder({ label }: { label: string }) {
const { isLast, pending } = useStepper();
return (
<StepperNext finishLabel={pending && isLast ? "Placing order…" : label} size="md">
Continue
</StepperNext>
);
}
/**
* Checkout block: `Stepper`-driven Shipping → Payment → Review with guarded
* steps that shake when incomplete, an order summary with compact quantity
* controls, a promo field that shakes on an invalid code and pops a removable
* `Badge` on a valid one, and totals that roll through `NumberTicker`. Card
* inputs are display-only placeholders and are never passed to `onComplete`.
*/
export function Checkout({
items: itemsProp,
defaultItems = [],
onItemsChange,
promoCodes = [],
onApplyPromo,
onComplete,
taxRate = 0.08,
expressPrice = 15,
currency = "USD",
locale = "en-US",
className,
}: CheckoutProps) {
const reduce = useReducedMotion();
const baseId = useId();
const [internalItems, setInternalItems] = useState(defaultItems);
const items = itemsProp ?? internalItems;
const setQuantity = (id: string, quantity: number) => {
const next = items.map((item) => (item.id === id ? { ...item, quantity } : item));
if (itemsProp === undefined) setInternalItems(next);
onItemsChange?.(next);
};
const [shipping, setShipping] = useState<CheckoutShipping>(EMPTY_SHIPPING);
const [delivery, setDelivery] = useState<CheckoutDelivery>("standard");
// UI-only card fields: local state, never leaves this component.
const [card, setCard] = useState({ number: "", expiry: "", cvc: "" });
const [touched, setTouched] = useState<{ shipping?: boolean; payment?: boolean }>({});
const [promoInput, setPromoInput] = useState("");
const [promo, setPromo] = useState<CheckoutPromo | null>(null);
const [promoState, setPromoState] = useState<"idle" | "loading" | "success" | "error">(
"idle",
);
const [promoError, setPromoError] = useState<string>();
const promoRef = useRef<HTMLFormElement>(null);
const [placed, setPlaced] = useState<{ reference?: string } | null>(null);
const [orderError, setOrderError] = useState<string>();
const formatter = useMemo(
() => new Intl.NumberFormat(locale, { style: "currency", currency }),
[locale, currency],
);
const format = useCallback((c: number) => formatter.format(c / 100), [formatter]);
const totals = useMemo(() => {
const subtotal = items.reduce((sum, item) => sum + cents(item.price) * item.quantity, 0);
const discount = promo
? Math.min(
subtotal,
promo.percentOff
? Math.round((subtotal * promo.percentOff) / 100)
: cents(promo.amountOff ?? 0),
)
: 0;
const ship = delivery === "express" ? cents(expressPrice) : 0;
const tax = Math.round((subtotal - discount) * taxRate);
return { subtotal, discount, shipping: ship, tax, total: subtotal - discount + ship + tax };
}, [items, promo, delivery, expressPrice, taxRate]);
const shippingErrors = {
name: shipping.name.trim() ? undefined : "Required",
address: shipping.address.trim() ? undefined : "Required",
city: shipping.city.trim() ? undefined : "Required",
zip: /^[A-Za-z0-9 -]{3,10}$/.test(shipping.zip.trim()) ? undefined : "Invalid",
};
const [mm, yy] = card.expiry.split("/");
const paymentErrors = {
number: digits(card.number, 16).length === 16 ? undefined : "Enter 16 digits",
expiry:
Number(mm) >= 1 && Number(mm) <= 12 && (yy ?? "").length === 2 ? undefined : "MM/YY",
cvc: /^\d{3,4}$/.test(card.cvc) ? undefined : "3–4 digits",
};
const hasErrors = (errors: Record<string, string | undefined>) =>
Object.values(errors).some(Boolean);
const canAdvance = (index: number) => {
if (index === 0) {
setTouched((t) => ({ ...t, shipping: true }));
return !hasErrors(shippingErrors);
}
if (index === 1) {
setTouched((t) => ({ ...t, payment: true }));
return !hasErrors(paymentErrors);
}
return items.length > 0;
};
const complete = async () => {
setOrderError(undefined);
try {
const reference = await onComplete?.({
items,
shipping,
delivery,
promo,
totals: {
subtotal: totals.subtotal / 100,
discount: totals.discount / 100,
shipping: totals.shipping / 100,
tax: totals.tax / 100,
total: totals.total / 100,
},
});
setPlaced({ reference: reference ?? undefined });
} catch (reason) {
setOrderError(messageOf(reason, "Payment didn't go through. Try again."));
}
};
const applyPromo = async () => {
const code = promoInput.trim();
if (!code) return;
setPromoState("loading");
setPromoError(undefined);
try {
let result: CheckoutPromo | undefined;
if (onApplyPromo) result = await onApplyPromo(code);
else result = promoCodes.find((p) => p.code.toLowerCase() === code.toLowerCase());
if (!result) throw new Error("That code isn't valid.");
setPromo(result);
setPromoInput("");
setPromoState("idle");
} catch (reason) {
setPromoState("idle");
setPromoError(messageOf(reason, "That code isn't valid."));
if (!reduce && promoRef.current) {
animate(promoRef.current, SHAKE, { duration: 0.42, ease: EASE_OUT });
}
}
};
const fieldError = (show: boolean | undefined, error: string | undefined) =>
show ? error : undefined;
const shippingPanel = (
<div className="flex flex-col gap-2.5">
<Input
aria-label="Full name"
placeholder="Full name"
autoComplete="name"
value={shipping.name}
onChange={(name) => setShipping((s) => ({ ...s, name }))}
error={fieldError(touched.shipping, shippingErrors.name) && true}
/>
<Input
aria-label="Street address"
placeholder="Street address"
autoComplete="street-address"
value={shipping.address}
onChange={(address) => setShipping((s) => ({ ...s, address }))}
error={fieldError(touched.shipping, shippingErrors.address) && true}
/>
<div className="grid grid-cols-[minmax(0,1fr)_7rem] gap-2.5">
<Input
aria-label="City"
placeholder="City"
autoComplete="address-level2"
value={shipping.city}
onChange={(city) => setShipping((s) => ({ ...s, city }))}
error={fieldError(touched.shipping, shippingErrors.city) && true}
/>
<Input
aria-label="Postal code"
placeholder="ZIP"
autoComplete="postal-code"
value={shipping.zip}
onChange={(zip) => setShipping((s) => ({ ...s, zip }))}
error={fieldError(touched.shipping, shippingErrors.zip) && true}
/>
</div>
<fieldset className="m-0 grid grid-cols-2 gap-2.5 border-0 p-0">
<legend className="sr-only">Delivery speed</legend>
{(
[
{ id: "standard", label: "Standard", note: "Free · 5–7 days", icon: Truck },
{
id: "express",
label: "Express",
note: `${format(cents(expressPrice))} · 1–2 days`,
icon: Zap,
},
] as const
).map((option) => {
const active = delivery === option.id;
const Icon = option.icon;
return (
<label
key={option.id}
className={cn(
"relative flex cursor-pointer items-center gap-2.5 rounded-2xl border px-3 py-2 transition-colors has-focus-visible:ring-2 has-focus-visible:ring-ring",
active ? "border-foreground/40" : "border-border hover:border-border-strong",
)}
>
<input
type="radio"
name={`${baseId}-delivery`}
value={option.id}
checked={active}
onChange={() => setDelivery(option.id)}
className="sr-only"
/>
{active ? (
<motion.span
layoutId={`${baseId}-delivery-pill`}
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className="absolute inset-0 rounded-2xl bg-muted"
aria-hidden
/>
) : null}
<Icon className="relative size-4 shrink-0 text-muted-foreground" aria-hidden />
<span className="relative min-w-0">
<span className="block text-sm font-medium text-foreground">{option.label}</span>
<span className="block truncate text-xs text-muted-foreground">
{option.note}
</span>
</span>
</label>
);
})}
</fieldset>
</div>
);
const paymentPanel = (
<div className="flex flex-col gap-2.5">
{/* Placeholders only: autocomplete is off so no saved card is ever
offered, and these values never leave the component. */}
<Input
aria-label="Card number"
placeholder="1234 1234 1234 1234"
inputMode="numeric"
autoComplete="off"
leftIcon={<Lock />}
value={digits(card.number, 16).replace(/(\d{4})(?=\d)/g, "$1 ")}
onChange={(number) => setCard((c) => ({ ...c, number: digits(number, 16) }))}
error={fieldError(touched.payment, paymentErrors.number) && true}
/>
<div className="grid grid-cols-2 gap-2.5">
<Input
aria-label="Expiry (MM/YY)"
placeholder="MM / YY"
inputMode="numeric"
autoComplete="off"
value={card.expiry}
onChange={(next) => {
const d = digits(next, 4);
setCard((c) => ({ ...c, expiry: d.length > 2 ? `${d.slice(0, 2)}/${d.slice(2)}` : d }));
}}
error={fieldError(touched.payment, paymentErrors.expiry) && true}
/>
<Input
aria-label="Security code"
placeholder="CVC"
inputMode="numeric"
autoComplete="off"
value={card.cvc}
onChange={(cvc) => setCard((c) => ({ ...c, cvc: digits(cvc, 4) }))}
error={fieldError(touched.payment, paymentErrors.cvc) && true}
/>
</div>
<p className="flex items-center gap-1.5 px-1 text-xs text-muted-foreground">
<Lock className="size-3" aria-hidden />
Demo fields — no card data is stored or sent.
</p>
</div>
);
const reviewRow = (label: string, value: ReactNode, step: number) => (
<ReviewRow label={label} step={step}>
{value}
</ReviewRow>
);
const reviewPanel = (
<div className="flex flex-col gap-2">
{reviewRow(
"Ship to",
<>
{shipping.name}, {shipping.address}, {shipping.city} {shipping.zip}
</>,
0,
)}
{reviewRow(
"Delivery",
delivery === "express" ? "Express · 1–2 days" : "Standard · 5–7 days",
0,
)}
{reviewRow("Payment", `Card ending ${digits(card.number, 16).slice(-4)}`, 1)}
<AnimatePresence initial={false}>
{orderError ? (
<motion.p
role="alert"
initial={reduce ? { opacity: 0 } : { opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
className="rounded-2xl border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive"
>
{orderError}
</motion.p>
) : null}
</AnimatePresence>
</div>
);
const summary = (
<aside
aria-label="Order summary"
className="flex flex-col gap-3 rounded-2xl bg-muted/50 p-3.5"
>
<p className="text-sm font-semibold text-foreground">Order summary</p>
<ul className="flex flex-col gap-2.5">
{items.map((item, index) => (
<li key={item.id} className="flex items-center gap-2.5">
{item.image ?? (
<span
aria-hidden
className={cn(
"size-9 shrink-0 rounded-xl opacity-80",
SWATCHES[index % SWATCHES.length],
)}
/>
)}
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-foreground">
{item.name}
{item.variant ? (
<span className="font-normal text-muted-foreground"> · {item.variant}</span>
) : null}
</p>
<div className="mt-0.5 flex items-center justify-between gap-2">
{placed ? (
<span className="text-xs text-muted-foreground">Qty {item.quantity}</span>
) : (
<Quantity
label={`${item.name} quantity`}
value={item.quantity}
onChange={(q) => setQuantity(item.id, q)}
/>
)}
<Money
value={cents(item.price) * item.quantity}
format={format}
className="text-xs text-foreground"
/>
</div>
</div>
</li>
))}
</ul>
<div className="h-px bg-border" aria-hidden />
<AnimatePresence mode="popLayout" initial={false}>
{promo ? (
<motion.div
key="applied"
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.85 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: reduce ? 1 : 0.9, transition: { duration: 0.12 } }}
transition={reduce ? { duration: 0.15 } : SPRING_SWAP}
className="flex items-center justify-between gap-2"
>
<Badge
variant="success"
icon={<Tag />}
onRemove={placed ? undefined : () => setPromo(null)}
removeLabel={`Remove code ${promo.code}`}
>
{promo.code.toUpperCase()}
</Badge>
<span className="truncate text-xs text-muted-foreground">{promo.label}</span>
</motion.div>
) : placed ? null : (
<motion.form
key="field"
ref={promoRef}
noValidate
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0, transition: { duration: 0.1 } }}
onSubmit={(event) => {
event.preventDefault();
void applyPromo();
}}
className="flex flex-col gap-1"
>
<div className="flex items-center gap-2">
<Input
aria-label="Promo code"
placeholder="Promo code"
autoComplete="off"
value={promoInput}
onChange={(next) => {
setPromoInput(next);
setPromoError(undefined);
}}
error={Boolean(promoError)}
className="min-w-0 flex-1"
classNames={{ field: "h-9" }}
/>
<StatefulButton
type="submit"
size="sm"
variant="secondary"
state={promoState}
loadingText="…"
disabled={!promoInput.trim()}
>
Apply
</StatefulButton>
</div>
<AnimatePresence initial={false}>
{promoError ? (
<motion.p
role="alert"
initial={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
className="px-1 text-xs text-destructive"
>
{promoError}
</motion.p>
) : null}
</AnimatePresence>
</motion.form>
)}
</AnimatePresence>
<dl className="flex flex-col gap-1.5 text-xs">
<div className="flex justify-between text-muted-foreground">
<dt>Subtotal</dt>
<dd>
<Money value={totals.subtotal} format={format} className="text-foreground" />
</dd>
</div>
<AnimatePresence initial={false}>
{totals.discount > 0 ? (
<motion.div
key="discount"
initial={reduce ? { opacity: 0 } : { opacity: 0, x: -8 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.22, ease: EASE_OUT }}
className="flex justify-between text-muted-foreground"
>
<dt>Discount</dt>
<dd className="text-success">
−<Money value={totals.discount} format={format} />
</dd>
</motion.div>
) : null}
</AnimatePresence>
<div className="flex justify-between text-muted-foreground">
<dt>Shipping</dt>
<dd className="text-foreground">
{totals.shipping === 0 ? "Free" : <Money value={totals.shipping} format={format} />}
</dd>
</div>
<div className="flex justify-between text-muted-foreground">
<dt>Tax</dt>
<dd>
<Money value={totals.tax} format={format} className="text-foreground" />
</dd>
</div>
<div className="mt-1 flex items-baseline justify-between border-t border-border pt-2.5">
<dt className="text-sm font-medium text-foreground">Total</dt>
<dd>
<Money
value={totals.total}
format={format}
className="text-base font-semibold text-foreground"
/>
</dd>
</div>
</dl>
</aside>
);
return (
<div className={cn("@container w-full", className)}>
<div className="grid gap-4 rounded-3xl border border-border bg-card p-4 @xl:grid-cols-[minmax(0,1fr)_15rem]">
<div className="min-w-0">
<AnimatePresence mode="wait" initial={false}>
{placed ? (
<motion.div
key="placed"
role="status"
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97, y: 8 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
transition={{ duration: 0.3, ease: EASE_OUT }}
className="flex h-full min-h-72 flex-col items-center justify-center gap-3 text-center"
>
<motion.span
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.5 }}
animate={{ opacity: 1, scale: 1 }}
transition={reduce ? { duration: 0.2 } : { ...SPRING_SWAP, delay: 0.08 }}
className="grid size-14 place-items-center rounded-full bg-success/15 text-success"
>
<svg viewBox="0 0 24 24" className="size-7" fill="none" aria-hidden="true">
<motion.path
d="M5 12.5l4.5 4.5L19 7.5"
stroke="currentColor"
strokeWidth={2.4}
strokeLinecap="round"
strokeLinejoin="round"
initial={{ pathLength: reduce ? 1 : 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 0.4, delay: 0.2, ease: EASE_OUT }}
/>
</svg>
</motion.span>
<h2 className="text-lg font-semibold tracking-tight text-foreground">
Order placed
</h2>
<p className="max-w-xs text-sm text-muted-foreground">
{placed.reference ? (
<>
Order <span className="font-medium text-foreground">{placed.reference}</span>{" "}
is confirmed.{" "}
</>
) : null}
A receipt is on its way to you, {shipping.name.split(" ")[0]}.
</p>
</motion.div>
) : (
<motion.div
key="steps"
exit={{ opacity: 0, transition: { duration: 0.14 } }}
>
<Stepper steps={STEPS} canAdvance={canAdvance} onComplete={complete} className="gap-4">
<StepperIndicator showTitles />
<StepperPanels>
{shippingPanel}
{paymentPanel}
{reviewPanel}
</StepperPanels>
<div className="flex items-center justify-between">
<StepperPrevious size="md" />
<PlaceOrder label={`Pay ${format(totals.total)}`} />
</div>
</Stepper>
</motion.div>
)}
</AnimatePresence>
</div>
{summary}
</div>
</div>
);
}
function ReviewRow({
label,
step,
children,
}: {
label: string;
step: number;
children: ReactNode;
}) {
const { goTo } = useStepper();
return (
<div className="flex items-start justify-between gap-3 rounded-2xl border border-border px-3 py-2.5">
<div className="min-w-0">
<p className="text-xs text-muted-foreground">{label}</p>
<p className="text-sm text-foreground">{children}</p>
</div>
<Button
type="button"
size="sm"
variant="ghost"
aria-label={`Edit ${label.toLowerCase()}`}
onClick={() => void goTo(step)}
>
Edit
</Button>
</div>
);
}
"use client";
import { X } from "lucide-react";
import {
AnimatePresence,
motion,
PresenceContext,
useAnimate,
useReducedMotion,
type Variants,
} from "motion/react";
import {
type KeyboardEvent as ReactKeyboardEvent,
type ReactNode,
useContext,
useEffect,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_LAYOUT, SPRING_PANEL, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type BadgeVariant =
| "default"
| "secondary"
| "outline"
| "destructive"
| "success"
| "warning";
export type BadgeSize = "sm" | "md" | "lg";
/** Soft tinted surface or a filled one. Only the status variants differ. */
export type BadgeTone = "soft" | "solid";
const BASE: Record<"default" | "secondary" | "outline", string> = {
default: "border-transparent bg-primary text-primary-foreground",
secondary: "border-transparent bg-foreground/[0.07] text-foreground",
outline: "border-border-strong bg-transparent text-foreground",
};
// Status tints mix the token toward --foreground/--background (as `alert`
// does), so the text keeps its contrast in both themes and every design style.
const SOFT: Record<"destructive" | "success" | "warning", string> = {
destructive:
"border-[color-mix(in_oklab,var(--destructive)_30%,transparent)] bg-[color-mix(in_oklab,var(--destructive)_10%,var(--background))] text-[color-mix(in_oklab,var(--destructive)_78%,var(--foreground))]",
success:
"border-[color-mix(in_oklab,var(--success)_32%,transparent)] bg-[color-mix(in_oklab,var(--success)_11%,var(--background))] text-[color-mix(in_oklab,var(--success)_60%,var(--foreground))]",
warning:
"border-[color-mix(in_oklab,var(--warning)_40%,transparent)] bg-[color-mix(in_oklab,var(--warning)_13%,var(--background))] text-[color-mix(in_oklab,var(--warning)_52%,var(--foreground))]",
};
// Filled status badges. Red reads best with light text in both themes;
// green and amber are light hues, so they always get dark text.
const SOLID: Record<"destructive" | "success" | "warning", string> = {
destructive:
"border-transparent bg-destructive text-background dark:text-foreground",
success:
"border-transparent bg-success text-[color-mix(in_oklab,var(--success)_22%,var(--foreground))] dark:text-[color-mix(in_oklab,var(--success)_22%,var(--background))]",
warning:
"border-transparent bg-warning text-[color-mix(in_oklab,var(--warning)_22%,var(--foreground))] dark:text-[color-mix(in_oklab,var(--warning)_22%,var(--background))]",
};
const SIZE: Record<BadgeSize, string> = {
sm: "h-5 gap-1 px-1.5 text-[11px] [&_svg]:size-3",
md: "h-6 gap-1.5 px-2 text-xs [&_svg]:size-3.5",
lg: "h-7 gap-1.5 px-2.5 text-[13px] [&_svg]:size-3.5",
};
// Count badges are circles at one digit and pills beyond.
const COUNT_SIZE: Record<BadgeSize, string> = {
sm: "h-4 min-w-4 px-1 text-[10px]",
md: "h-5 min-w-5 px-1.5 text-[11px]",
lg: "h-6 min-w-6 px-1.5 text-xs",
};
function variantClass(variant: BadgeVariant, tone: BadgeTone) {
if (variant === "default" || variant === "secondary" || variant === "outline") {
return BASE[variant];
}
return tone === "solid" ? SOLID[variant] : SOFT[variant];
}
export interface BadgeProps {
children?: ReactNode;
variant?: BadgeVariant;
/** Status variants only (destructive/success/warning). Default "soft". */
tone?: BadgeTone;
size?: BadgeSize;
/** Leading status dot in the text color; `"pulse"` adds a radiating ring. */
dot?: boolean | "pulse";
/** Leading icon (sized to the badge). Ignored when `dot` is set. */
icon?: ReactNode;
/**
* Makes the badge removable: an × button plays the exit, then calls this.
* Focus moves to the neighbouring chip's × when the removal came from it.
*/
onRemove?: () => void;
/** Accessible name of the × button. Default `Remove <text>`. */
removeLabel?: string;
/**
* Count mode: renders a compact number that rolls up or down as it changes
* and bumps when it rises. Hidden at 0 unless `showZero`.
*/
count?: number;
/** Counts above this read "max+". Default 99. */
max?: number;
showZero?: boolean;
/** Spoken label for count mode, e.g. `(n) => \`${n} unread\``. */
countLabel?: (count: number) => string;
className?: string;
}
/**
* General-purpose badge: six variants, three sizes, an optional (pulsing) dot
* or icon, removable chips with an exit animation, and a count mode with
* rolling digits capped at "99+". For animated status transitions
* (loading → success) use `AnimatedBadge` instead.
*/
export function Badge(props: BadgeProps) {
if (props.count !== undefined) return <CountBadge {...props} count={props.count} />;
return <LabelBadge {...props} />;
}
/* -------------------------------------------------------------------------- */
/* Label badge */
/* -------------------------------------------------------------------------- */
function LabelBadge({
children,
variant = "default",
tone = "soft",
size = "md",
dot = false,
icon,
onRemove,
removeLabel,
className,
}: BadgeProps) {
const reduce = useReducedMotion() ?? false;
// Inside an AnimatePresence the badge pops in when added; anywhere else it
// renders as-is so server HTML is visible before hydration.
const inPresence = useContext(PresenceContext) !== null;
const rootRef = useRef<HTMLSpanElement>(null);
const [leaving, setLeaving] = useState(false);
const refocus = useRef<HTMLElement | null>(null);
const removable = Boolean(onRemove);
const hidden = reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 };
const startRemove = (fromKeyboardFocus: boolean) => {
if (leaving) return;
if (fromKeyboardFocus) refocus.current = neighbourRemoveButton(rootRef.current);
setLeaving(true);
};
const finishRemove = () => {
if (!leaving) return;
const target = refocus.current;
refocus.current = null;
onRemove?.();
if (target) requestAnimationFrame(() => target.focus({ preventScroll: true }));
};
const text = typeof children === "string" ? children : undefined;
return (
<motion.span
ref={rootRef}
data-badge=""
// Siblings glide into the gap a removed chip leaves (transform-only).
layout={removable && !reduce ? "position" : false}
initial={inPresence ? hidden : false}
animate={
leaving
? { ...hidden, pointerEvents: "none" }
: { opacity: 1, scale: 1, pointerEvents: "auto" }
}
// Already faded out by the × — leave at once so siblings close the gap.
exit={{
...hidden,
pointerEvents: "none",
transition: { duration: leaving ? 0 : 0.12, ease: EASE_OUT },
}}
transition={
leaving
? { duration: 0.14, ease: EASE_OUT }
: reduce
? { duration: 0.12 }
: { ...SPRING_PANEL, layout: SPRING_LAYOUT }
}
onAnimationComplete={finishRemove}
className={cn(
"inline-flex shrink-0 select-none items-center whitespace-nowrap rounded-full border font-medium leading-none",
SIZE[size],
variantClass(variant, tone),
removable && (size === "sm" ? "pr-0.5" : "pr-1"),
className,
)}
>
{dot ? (
<Dot pulse={dot === "pulse" && !reduce} />
) : icon ? (
<span aria-hidden="true" className="inline-flex shrink-0">
{icon}
</span>
) : null}
<span className="min-w-0 truncate">{children}</span>
{removable ? (
<button
type="button"
data-badge-remove=""
aria-label={removeLabel ?? (text ? `Remove ${text}` : "Remove")}
onClick={(event) => startRemove(event.detail === 0)}
onKeyDown={(event: ReactKeyboardEvent<HTMLButtonElement>) => {
if (event.key === "Backspace" || event.key === "Delete") {
event.preventDefault();
startRemove(true);
}
}}
className={cn(
"inline-flex shrink-0 items-center justify-center rounded-full opacity-70 outline-none transition-[opacity,background-color] hover:bg-current/15 hover:opacity-100 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-current/40",
size === "sm" ? "size-4" : "size-[18px]",
)}
>
<X aria-hidden="true" strokeWidth={2.4} className="size-3!" />
</button>
) : null}
</motion.span>
);
}
/** The × of the next chip in the row, else the previous one. */
function neighbourRemoveButton(node: HTMLElement | null) {
if (!node) return null;
const pick = (el: Element | null) =>
el?.querySelector<HTMLElement>("[data-badge-remove]") ?? null;
let next = node.nextElementSibling;
while (next && !pick(next)) next = next.nextElementSibling;
if (next) return pick(next);
let prev = node.previousElementSibling;
while (prev && !pick(prev)) prev = prev.previousElementSibling;
return prev ? pick(prev) : null;
}
// One pulse cycle of the dot's radiating ring, in seconds. Slow on purpose:
// an ambient "live" signal, not feedback, so it sits well outside UI timing.
const PULSE_DURATION = 1.6;
function Dot({ pulse }: { pulse: boolean }) {
return (
<span aria-hidden="true" className="relative inline-flex size-1.5 shrink-0">
{pulse ? (
<motion.span
className="absolute inset-0 rounded-full bg-current"
initial={{ scale: 1, opacity: 0.55 }}
animate={{ scale: 2.6, opacity: 0 }}
transition={{
duration: PULSE_DURATION,
ease: EASE_OUT,
repeat: Number.POSITIVE_INFINITY,
}}
/>
) : null}
<span className="relative size-1.5 rounded-full bg-current" />
</span>
);
}
/* -------------------------------------------------------------------------- */
/* Count badge */
/* -------------------------------------------------------------------------- */
function CountBadge({
count,
max = 99,
showZero = false,
countLabel,
variant = "destructive",
tone = "solid",
size = "md",
className,
}: BadgeProps & { count: number }) {
const reduce = useReducedMotion() ?? false;
const [scope, animate] = useAnimate<HTMLSpanElement>();
const value = Math.max(0, Math.round(count));
const visible = value > 0 || showZero;
const text = value > max ? `${max}+` : String(value);
// Direction is derived during render (not in an effect) so the very render
// that swaps the digits already rolls them the right way.
const [seen, setSeen] = useState(value);
const [direction, setDirection] = useState<1 | -1>(1);
if (value !== seen) {
setSeen(value);
setDirection(value > seen ? 1 : -1);
}
// Rising counts bump the pill (not on the pop-in from zero, which has its
// own entrance).
const previous = useRef(value);
useEffect(() => {
const prev = previous.current;
previous.current = value;
if (value > prev && prev > 0 && !reduce && scope.current) {
animate(scope.current, { scale: [1, 1.18, 1] }, { duration: 0.32, ease: EASE_OUT });
}
}, [value, reduce, animate, scope]);
return (
<AnimatePresence initial={false}>
{visible ? (
<motion.span
key="count"
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.4 }}
animate={{ opacity: 1, scale: 1 }}
exit={
reduce
? { opacity: 0, transition: { duration: 0.1 } }
: { opacity: 0, scale: 0.4, transition: { duration: 0.14, ease: EASE_OUT } }
}
transition={reduce ? { duration: 0.12 } : SPRING_PANEL}
className={cn("inline-flex shrink-0", className)}
>
<span
ref={scope}
data-badge-count=""
className={cn(
"inline-flex items-center justify-center rounded-full border font-semibold leading-none tabular-nums",
COUNT_SIZE[size],
variantClass(variant, tone),
)}
>
<span className="sr-only">{countLabel ? countLabel(value) : text}</span>
<RollingCount text={text} direction={direction} reduce={reduce} />
</span>
</motion.span>
) : null}
</AnimatePresence>
);
}
const roll: Variants = {
enter: (dir: 1 | -1) => ({ y: dir > 0 ? "100%" : "-100%", opacity: 0 }),
center: { y: "0%", opacity: 1 },
exit: (dir: 1 | -1) => ({
y: dir > 0 ? "-100%" : "100%",
opacity: 0,
transition: { duration: 0.14, ease: EASE_OUT },
}),
};
const fade: Variants = {
enter: { opacity: 0 },
center: { opacity: 1 },
exit: { opacity: 0, transition: { duration: 0.1 } },
};
/**
* Direction-aware digit roll. `NumberTicker` spins each digit along a 0–9
* strip, so 9 → 10 would roll the ones digit backwards; here every changed
* glyph slides in from the direction of change instead.
*/
function RollingCount({
text,
direction,
reduce,
}: {
text: string;
direction: 1 | -1;
reduce: boolean;
}) {
const chars = text.split("");
// Keyed by place value from the right so a digit keeps its slot as the
// number grows on the left.
const glyphs = chars.map((char, i) => ({ char, place: chars.length - 1 - i }));
return (
<span aria-hidden="true" className="inline-flex">
{glyphs.map(({ char, place }) => (
<span
key={place}
className="relative inline-flex h-[1.2em] items-center justify-center overflow-hidden"
>
<span className="invisible">{char}</span>
<AnimatePresence initial={false} custom={direction}>
<motion.span
key={char}
custom={direction}
variants={reduce ? fade : roll}
initial="enter"
animate="center"
exit="exit"
transition={reduce ? { duration: 0.12 } : SPRING_SWAP}
className="absolute inset-0 flex items-center justify-center"
>
{char}
</motion.span>
</AnimatePresence>
</span>
))}
</span>
);
}
export type {
ButtonLinkProps,
ButtonProps,
ButtonSize,
ButtonVariant,
} from "./base";
export { Button, ButtonLink } from "./base";
export type { MagneticButtonProps } from "./magnetic";
export { MagneticButton } from "./magnetic";
export type { ButtonState, StatefulButtonProps } from "./stateful";
export { StatefulButton } from "./stateful";
"use client";
import {
AnimatePresence,
animate,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
useEffect,
useId,
useRef,
useState,
type InputHTMLAttributes,
type ReactNode,
} from "react";
import { cn } from "@/lib/utils";
export type InputClassNames = {
root?: string;
label?: string;
field?: string;
input?: string;
leftIcon?: string;
rightIcon?: string;
successIcon?: string;
errorMessage?: string;
};
export interface InputProps extends Omit<
InputHTMLAttributes<HTMLInputElement>,
"value" | "defaultValue" | "onChange"
> {
label?: string;
value?: string;
defaultValue?: string;
onChange?: (value: string) => void;
/** Truthy error triggers a shake, red border and (if a string) a message. */
error?: string | boolean;
success?: boolean;
leftIcon?: ReactNode;
rightIcon?: ReactNode;
className?: string;
classNames?: InputClassNames;
}
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
{
label,
value: valueProp,
defaultValue,
onChange,
onFocus,
onBlur,
error,
success,
leftIcon,
rightIcon,
className,
classNames,
disabled,
id: idProp,
type,
...rest
},
ref,
) {
const reactId = useId();
const id = idProp ?? reactId;
const reduce = useReducedMotion();
const controlled = valueProp !== undefined;
const [internal, setInternal] = useState(defaultValue ?? "");
const value = controlled ? (valueProp ?? "") : internal;
const [focused, setFocused] = useState(false);
const fieldRef = useRef<HTMLDivElement>(null);
const hasError = Boolean(error);
const errorMessage = typeof error === "string" ? error : null;
// Right edge shows the success check, otherwise the caller's right icon.
const rightSlot = success ? null : rightIcon;
// Shake the field when an error appears.
useEffect(() => {
if (!fieldRef.current || reduce || !hasError) return;
animate(
fieldRef.current,
{ x: [0, -6, 6, -4, 4, -2, 0] },
{ duration: 0.45 },
);
}, [hasError, reduce]);
const handleChange = (next: string) => {
if (!controlled) setInternal(next);
onChange?.(next);
};
return (
<div
className={cn("flex flex-col gap-1.5", className, classNames?.root)}
>
{label ? (
<label
htmlFor={id}
className={cn(
"px-1 text-sm font-medium text-foreground",
classNames?.label,
)}
>
{label}
</label>
) : null}
<div
ref={fieldRef}
data-state={
hasError
? "error"
: success
? "success"
: focused
? "focused"
: "idle"
}
className={cn(
"relative h-11 overflow-hidden rounded-full border transition-colors duration-200",
"border-border",
focused && !hasError && "border-foreground/40 ring-2 ring-ring/40",
hasError && "border-destructive ring-2 ring-destructive/25",
disabled && "opacity-60",
classNames?.field,
)}
>
{leftIcon ? (
<span
className={cn(
"pointer-events-none absolute left-3 top-1/2 flex -translate-y-1/2 items-center text-muted-foreground [&_svg]:h-4 [&_svg]:w-4",
classNames?.leftIcon,
)}
>
{leftIcon}
</span>
) : null}
<input
ref={ref}
id={id}
type={type}
value={value}
disabled={disabled}
aria-invalid={hasError || undefined}
aria-describedby={errorMessage ? `${id}-error` : undefined}
{...rest}
onChange={(e) => handleChange(e.target.value)}
onFocus={(event) => {
setFocused(true);
onFocus?.(event);
}}
onBlur={(event) => {
setFocused(false);
onBlur?.(event);
}}
className={cn(
"peer h-full w-full bg-transparent text-base leading-6 text-foreground caret-foreground outline-none",
"placeholder:text-muted-foreground/60",
leftIcon ? "pl-10" : "pl-3.5",
rightSlot || success ? "pr-10" : "pr-3.5",
disabled && "cursor-not-allowed",
classNames?.input,
)}
/>
{success ? (
<motion.svg
viewBox="0 0 24 24"
fill="none"
className={cn(
"absolute right-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-(--color-success)",
classNames?.successIcon,
)}
>
<motion.path
d="M5 12.5l4.5 4.5L19 7.5"
stroke="currentColor"
strokeWidth={2.5}
strokeLinecap="round"
strokeLinejoin="round"
initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 0.35, ease: "easeOut" }}
/>
</motion.svg>
) : rightSlot ? (
<span
className={cn(
"absolute right-0 top-0 flex h-full items-center text-muted-foreground [&_button]:grid [&_button]:size-11 [&_button]:place-items-center [&_svg]:h-4 [&_svg]:w-4",
classNames?.rightIcon,
)}
>
{rightSlot}
</span>
) : null}
</div>
<AnimatePresence initial={false}>
{errorMessage ? (
<motion.p
id={`${id}-error`}
role="alert"
initial={
reduce
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(4px)" }
}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={
reduce
? { opacity: 0 }
: { opacity: 0, y: -4, filter: "blur(4px)" }
}
transition={{ duration: 0.2 }}
className={cn(
"px-1 text-xs text-destructive",
classNames?.errorMessage,
)}
>
{errorMessage}
</motion.p>
) : null}
</AnimatePresence>
</div>
);
});
"use client";
import { animate, motion, useInView, useReducedMotion } from "motion/react";
import { useEffect, useMemo, useRef, useState } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export interface NumberTickerProps {
value: number;
/** Digits to pad to (left). */
pad?: number;
/** Per-digit roll duration in seconds. */
duration?: number;
/** Stagger between digits. */
stagger?: number;
/** Render only after the element enters the viewport. */
startOnView?: boolean;
prefix?: string;
suffix?: string;
/** Add a small blur during digit rolls. */
blur?: boolean;
className?: string;
digitClassName?: string;
/** Insert en-US group separators (commas); fixed so server and client match. Server-component safe. */
locale?: boolean;
/** Custom formatter. Client-only — server components must use `locale` instead. */
format?: (value: number) => string;
}
const DIGIT_HEIGHT_EM = 1.1;
const DIGITS = Array.from({ length: 10 }, (_, n) => n);
export function NumberTicker({
value,
pad,
duration = 0.9,
stagger = 0.04,
startOnView = true,
prefix,
suffix,
blur = false,
className,
digitClassName,
locale,
format,
}: NumberTickerProps) {
const containerRef = useRef<HTMLSpanElement>(null);
const inView = useInView(containerRef, { once: true, amount: 0.6 });
const [armed, setArmed] = useState(!startOnView);
useEffect(() => {
if (startOnView && inView) setArmed(true);
}, [startOnView, inView]);
const text = useMemo(() => {
const rounded = Math.round(value);
const formatted = format
? format(rounded)
: locale
? rounded.toLocaleString("en-US")
: rounded.toString();
return pad ? formatted.padStart(pad, "0") : formatted;
}, [value, pad, format, locale]);
const glyphs = useMemo(() => {
const chars = text.split("");
// Key by place value (position from the right): a changing digit keeps its
// identity and rolls to the new value instead of remounting and replaying
// from 0. Growing numbers add glyphs on the left without re-keying the
// ones, tens, hundreds already on screen.
return chars.map((char, i) => ({ char, id: `g-${chars.length - 1 - i}` }));
}, [text]);
const readableText = `${prefix ?? ""}${text}${suffix ?? ""}`;
// Stagger is an entrance flourish. Once the reveal has played, value
// changes roll every digit immediately — a per-digit delay on live updates
// reads as lag.
const [entered, setEntered] = useState(false);
useEffect(() => {
if (!armed || entered) return;
const total = (duration + glyphs.length * stagger) * 1000;
const t = window.setTimeout(() => setEntered(true), total);
return () => window.clearTimeout(t);
}, [armed, entered, duration, stagger, glyphs.length]);
return (
<span
ref={containerRef}
className={cn("inline-flex items-center tabular-nums", className)}
>
<span className="sr-only">{readableText}</span>
<span aria-hidden="true" className="inline-flex items-center">
{prefix ? <span>{prefix}</span> : null}
{glyphs.map(({ char, id }, i) => {
const isDigit = /\d/.test(char);
if (!isDigit) {
return (
<span key={id} className="inline-block">
{char}
</span>
);
}
const digit = Number(char);
return (
<Digit
key={id}
digit={armed ? digit : 0}
delay={entered ? 0 : i * stagger}
duration={duration}
blur={blur}
className={digitClassName}
/>
);
})}
{suffix ? <span>{suffix}</span> : null}
</span>
</span>
);
}
function Digit({
digit,
delay,
duration,
blur,
className,
}: {
digit: number;
delay: number;
duration: number;
blur: boolean;
className?: string;
}) {
const reduce = useReducedMotion();
const columnRef = useRef<HTMLSpanElement>(null);
useEffect(() => {
if (reduce || !blur || !columnRef.current || !Number.isFinite(digit)) {
return;
}
const node = columnRef.current;
const controls = animate(
node,
{ filter: ["blur(10px)", "blur(0px)"] },
{
duration: Math.min(duration * 0.75, 0.32),
delay,
ease: EASE_OUT,
},
);
return () => {
controls.stop();
node.style.filter = "blur(0px)";
};
}, [blur, delay, digit, duration, reduce]);
return (
<span
className={cn("relative inline-block overflow-hidden", className)}
style={{ height: `${DIGIT_HEIGHT_EM}em`, width: "1ch" }}
>
<motion.span
ref={columnRef}
initial={{ y: 0 }}
animate={{ y: `-${digit * DIGIT_HEIGHT_EM}em` }}
transition={
reduce
? { duration: 0 }
: { duration, delay, ease: EASE_OUT }
}
className="absolute inset-x-0 top-0 flex flex-col items-center will-change-[transform,filter]"
>
{DIGITS.map((n) => (
<span
key={n}
className="flex h-[1.1em] items-center justify-center leading-none"
>
{n}
</span>
))}
</motion.span>
</span>
);
}
"use client";
import { Check } from "lucide-react";
import {
AnimatePresence,
motion,
useAnimationControls,
useReducedMotion,
} from "motion/react";
import {
Children,
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { Button, type ButtonProps } from "@/components/motion/button";
import { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type StepperStep = {
id: string;
title: string;
description?: string;
};
/** Return false (or a promise of false) to keep the user on the current step. */
export type StepperGuard = (index: number) => boolean | Promise<boolean>;
export interface StepperProps {
steps: StepperStep[];
/** Controlled active step index. */
value?: number;
/** Uncontrolled initial step index. Default 0. */
defaultValue?: number;
onValueChange?: (index: number) => void;
/** Runs before leaving a step forward (Next, or jumping ahead). */
canAdvance?: StepperGuard;
/** Called when Next is pressed on the last step and its guard passes. */
onComplete?: () => void | Promise<void>;
/**
* Linear (default): the indicator only jumps back, or forward to steps
* already reached. Non-linear: any step, still guarded by `canAdvance`.
*/
linear?: boolean;
children: ReactNode;
className?: string;
}
type StepperContextValue = {
steps: StepperStep[];
value: number;
count: number;
direction: 1 | -1;
reached: number;
completed: ReadonlySet<number>;
errorStep: number | null;
errorTick: number;
pending: boolean;
linear: boolean;
isFirst: boolean;
isLast: boolean;
baseId: string;
next: () => Promise<boolean>;
previous: () => void;
goTo: (index: number) => Promise<boolean>;
};
const StepperContext = createContext<StepperContextValue | null>(null);
/** Step state and navigation for custom controls inside `<Stepper>`. */
export function useStepper() {
const ctx = useContext(StepperContext);
if (!ctx) throw new Error("useStepper must be used within <Stepper>");
return ctx;
}
const clamp = (n: number, max: number) => Math.min(Math.max(n, 0), max);
/**
* Multi-step flow: an indicator whose active ring glides between steps and
* whose connectors fill as you advance, panels that slide in from the
* direction of travel while the container morphs to each panel's height, and
* a guard per step that shakes the indicator when it refuses. Controlled or
* uncontrolled; reduced-motion safe.
*/
export function Stepper({
steps,
value: controlledValue,
defaultValue = 0,
onValueChange,
canAdvance,
onComplete,
linear = true,
children,
className,
}: StepperProps) {
const count = steps.length;
const baseId = useId();
const [internalValue, setInternalValue] = useState(() =>
clamp(defaultValue, count - 1),
);
const value = clamp(controlledValue ?? internalValue, count - 1);
const [direction, setDirection] = useState<1 | -1>(1);
const [reached, setReached] = useState(value);
const [completed, setCompleted] = useState<ReadonlySet<number>>(
() => new Set(),
);
const [errorStep, setErrorStep] = useState<number | null>(null);
// Bumped on every refusal so the same step can shake twice in a row.
const [errorTick, setErrorTick] = useState(0);
const [pending, setPending] = useState(false);
// A controlled jump past `reached` (e.g. restoring a draft) still counts.
useEffect(() => setReached((r) => Math.max(r, value)), [value]);
const commit = useCallback(
(index: number) => {
setDirection(index > value ? 1 : -1);
setErrorStep(null);
if (controlledValue === undefined) setInternalValue(index);
onValueChange?.(index);
},
[value, controlledValue, onValueChange],
);
const guard = useCallback(
async (index: number) => {
if (!canAdvance) return true;
setPending(true);
try {
return await canAdvance(index);
} finally {
setPending(false);
}
},
[canAdvance],
);
const refuse = useCallback((index: number) => {
setErrorStep(index);
setErrorTick((t) => t + 1);
}, []);
const markDone = useCallback((from: number, to: number) => {
setCompleted((prev) => {
const next = new Set(prev);
for (let i = from; i < to; i++) next.add(i);
return next;
});
}, []);
const goTo = useCallback(
async (target: number) => {
const index = clamp(target, count - 1);
if (index === value || pending) return false;
if (index < value) {
commit(index);
return true;
}
// Linear: forward only to steps already reached, or the very next one.
if (linear && index > Math.max(reached, value + 1)) return false;
// Every step being skipped over must pass its guard, in order.
for (let i = value; i < index; i++) {
if (!(await guard(i))) {
refuse(i);
if (i !== value) commit(i);
return false;
}
}
markDone(value, index);
setReached((r) => Math.max(r, index));
commit(index);
return true;
},
[count, value, pending, linear, reached, guard, refuse, markDone, commit],
);
const next = useCallback(async () => {
if (pending) return false;
if (value < count - 1) return goTo(value + 1);
if (!(await guard(value))) {
refuse(value);
return false;
}
markDone(value, value + 1);
setErrorStep(null);
setPending(true);
try {
await onComplete?.();
} finally {
setPending(false);
}
return true;
}, [pending, value, count, goTo, guard, refuse, markDone, onComplete]);
const previous = useCallback(() => {
if (value > 0 && !pending) commit(value - 1);
}, [value, pending, commit]);
const ctx = useMemo<StepperContextValue>(
() => ({
steps,
value,
count,
direction,
reached,
completed,
errorStep,
errorTick,
pending,
linear,
isFirst: value === 0,
isLast: value === count - 1,
baseId,
next,
previous,
goTo,
}),
[
steps,
value,
count,
direction,
reached,
completed,
errorStep,
errorTick,
pending,
linear,
baseId,
next,
previous,
goTo,
],
);
return (
<StepperContext.Provider value={ctx}>
<div className={cn("flex w-full flex-col gap-6", className)}>
{children}
</div>
</StepperContext.Provider>
);
}
// ── indicator ──────────────────────────────────────────────────────────────
export interface StepperIndicatorProps {
/** Show each step's title under its marker. Default true. */
showTitles?: boolean;
className?: string;
}
/** Numbered markers joined by connectors that fill as steps complete. */
export function StepperIndicator({
showTitles = true,
className,
}: StepperIndicatorProps) {
const {
steps,
value,
reached,
completed,
errorStep,
errorTick,
linear,
baseId,
goTo,
} = useStepper();
const reduce = useReducedMotion();
return (
<ol className={cn("flex w-full items-start", className)}>
{steps.map((step, i) => {
const active = i === value;
const done = completed.has(i) && !active;
const error = errorStep === i;
const reachable = !linear || i <= reached;
const state = error
? "error"
: done
? "completed"
: active
? "current"
: "upcoming";
return (
<li
key={step.id}
// Equal columns keep the markers centered and make each connector
// span exactly one column width, center to center.
className="relative flex min-w-0 flex-1 flex-col items-center gap-2"
>
{i < steps.length - 1 && (
// Connector from this marker's center to the next one's.
<span
aria-hidden
className="absolute top-4 left-[calc(50%+1.25rem)] right-[calc(-50%+1.25rem)] h-0.5 -translate-y-1/2 overflow-hidden rounded-full bg-border"
>
<motion.span
className="absolute inset-0 origin-left bg-primary"
initial={false}
animate={{ scaleX: completed.has(i) ? 1 : 0 }}
transition={
reduce
? { duration: 0 }
: { duration: 0.36, ease: EASE_OUT }
}
/>
</span>
)}
<StepMarker
index={i}
state={state}
shakeKey={error ? errorTick : 0}
disabled={!reachable || active}
label={`Step ${i + 1} of ${steps.length}: ${step.title}${
done ? ", completed" : error ? ", needs attention" : ""
}`}
current={active}
controls={`${baseId}-panel`}
onSelect={() => goTo(i)}
layoutGroup={baseId}
/>
{showTitles && (
<span
aria-hidden
className={cn(
"max-w-28 truncate px-1 text-center text-xs transition-colors",
active || done ? "text-foreground" : "text-muted-foreground",
error && "text-destructive",
)}
>
{step.title}
</span>
)}
</li>
);
})}
</ol>
);
}
function StepMarker({
index,
state,
shakeKey,
disabled,
label,
current,
controls,
onSelect,
layoutGroup,
}: {
index: number;
state: "upcoming" | "current" | "completed" | "error";
shakeKey: number;
disabled: boolean;
label: string;
current: boolean;
controls: string;
onSelect: () => void;
layoutGroup: string;
}) {
const reduce = useReducedMotion();
const shake = useAnimationControls();
useEffect(() => {
if (!shakeKey || reduce) return;
shake.start({
x: [0, -5, 5, -3, 3, 0],
transition: { duration: 0.4, ease: EASE_OUT },
});
}, [shakeKey, reduce, shake]);
return (
<motion.button
type="button"
animate={shake}
disabled={disabled}
aria-label={label}
aria-current={current ? "step" : undefined}
aria-controls={current ? controls : undefined}
onClick={onSelect}
className={cn(
"relative isolate flex size-8 shrink-0 items-center justify-center rounded-full border text-xs font-medium tabular-nums outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default",
state === "completed" &&
"border-primary bg-primary text-primary-foreground",
state === "current" && "border-transparent text-foreground",
state === "upcoming" && "border-border bg-card text-muted-foreground",
state === "error" &&
"border-destructive bg-destructive/10 text-destructive",
!disabled && state !== "current" && "hover:border-primary/60",
)}
>
{state === "current" && (
<motion.span
aria-hidden
// The ring glides from marker to marker as the active step changes.
layoutId={`${layoutGroup}-ring`}
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className="absolute -inset-px -z-10 rounded-full border-2 border-primary bg-card"
/>
)}
<AnimatePresence mode="popLayout" initial={false}>
{state === "completed" ? (
<motion.span
key="check"
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.4 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, transition: { duration: 0.1 } }}
transition={SPRING_SWAP}
>
<Check className="size-4" strokeWidth={2.5} />
</motion.span>
) : (
<motion.span
key="number"
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, transition: { duration: 0.1 } }}
transition={SPRING_SWAP}
>
{index + 1}
</motion.span>
)}
</AnimatePresence>
</motion.button>
);
}
// ── panels ─────────────────────────────────────────────────────────────────
export interface StepperPanelsProps {
/** One child per step, in step order. */
children: ReactNode;
className?: string;
}
/**
* Shows the active step's child. Panels slide in from the direction of
* travel and the container morphs to each panel's height. Focus moves to the
* new panel after navigation so keyboard and screen-reader users land on it.
*/
export function StepperPanels({ children, className }: StepperPanelsProps) {
const { value, direction, steps, baseId } = useStepper();
const reduce = useReducedMotion();
const panels = Children.toArray(children);
const containerRef = useRef<HTMLDivElement>(null);
const shownStep = useRef(value);
useEffect(() => {
// Only move focus in response to navigation, never on first render.
if (shownStep.current === value) return;
shownStep.current = value;
// The exiting panel is still mounted mid-transition, so look the entering
// one up by its step instead of trusting a shared ref.
containerRef.current
?.querySelector<HTMLElement>(`[data-step="${value}"]`)
?.focus({ preventScroll: true });
}, [value]);
const offset = reduce ? 0 : 24;
return (
<motion.div
layout
ref={containerRef}
transition={reduce ? { duration: 0 } : SPRING_LAYOUT}
className={cn("relative overflow-hidden", className)}
>
<AnimatePresence mode="popLayout" initial={false} custom={direction}>
<motion.div
key={value}
data-step={value}
id={`${baseId}-panel`}
role="group"
aria-label={`Step ${value + 1}: ${steps[value]?.title ?? ""}`}
tabIndex={-1}
layout="position"
custom={direction}
variants={{
enter: (dir: number) => ({
opacity: 0,
x: dir * offset,
filter: reduce ? "blur(0px)" : "blur(4px)",
}),
center: {
opacity: 1,
x: 0,
filter: "blur(0px)",
transition: { duration: 0.26, ease: EASE_OUT },
},
exit: (dir: number) => ({
opacity: 0,
x: dir * -offset,
filter: reduce ? "blur(0px)" : "blur(4px)",
transition: { duration: 0.16, ease: EASE_OUT },
}),
}}
initial="enter"
animate="center"
exit="exit"
className="outline-none"
>
{panels[value]}
</motion.div>
</AnimatePresence>
</motion.div>
);
}
// ── controls ───────────────────────────────────────────────────────────────
export interface StepperPreviousProps extends Omit<ButtonProps, "onClick"> {
children?: ReactNode;
}
/** Goes back one step. Hidden from layout on the first step. */
export function StepperPrevious({
children = "Back",
className,
variant = "ghost",
...props
}: StepperPreviousProps) {
const { isFirst, pending, previous } = useStepper();
return (
<Button
type="button"
variant={variant}
disabled={isFirst || pending}
onClick={previous}
className={cn(isFirst && "invisible", className)}
{...props}
>
{children}
</Button>
);
}
export interface StepperNextProps extends Omit<ButtonProps, "onClick"> {
children?: ReactNode;
/** Label on the last step. Default "Finish". */
finishLabel?: ReactNode;
}
/** Advances through the step guard; on the last step it runs `onComplete`. */
export function StepperNext({
children = "Continue",
finishLabel = "Finish",
...props
}: StepperNextProps) {
const { isLast, pending, next } = useStepper();
return (
<Button
type="button"
disabled={pending}
aria-busy={pending || undefined}
onClick={() => void next()}
{...props}
>
{isLast ? finishLabel : children}
</Button>
);
}
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useReducedMotion,
} from "motion/react";
import {
forwardRef,
type PointerEvent,
type ReactNode,
useCallback,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { TOUCH_TARGET_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
export type ButtonVariant = "primary" | "secondary" | "ghost" | "outline";
export type ButtonSize = "sm" | "md" | "lg" | "icon";
export interface ButtonProps extends Omit<
HTMLMotionProps<"button">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
/** Spawn a Material-style ripple from the press point. Off by default. */
ripple?: boolean;
children?: ReactNode;
}
export interface ButtonLinkProps extends Omit<
HTMLMotionProps<"a">,
"children"
> {
variant?: ButtonVariant;
size?: ButtonSize;
pressScale?: number;
children?: ReactNode;
}
type Ripple = { id: number; x: number; y: number; size: number };
const VARIANT_CLASS: Record<ButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
ghost: "text-muted-foreground hover:text-foreground hover:bg-primary/5",
outline:
"border border-border bg-transparent text-foreground hover:bg-primary/5",
};
const SIZE_CLASS: Record<ButtonSize, string> = {
sm: "h-8 px-3 text-xs gap-1.5 rounded-full",
md: "h-10 px-5 text-sm gap-2 rounded-full",
lg: "h-12 px-6 text-base gap-2 rounded-full",
icon: "h-8 w-8 rounded-lg",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
function Button(
{
variant = "primary",
size = "md",
pressScale = 0.93,
ripple = false,
className,
children,
onPointerDown,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
const [ripples, setRipples] = useState<Ripple[]>([]);
const nextId = useRef(0);
const handlePointerDown = useCallback(
(event: PointerEvent<HTMLButtonElement>) => {
if (ripple && !reduce) {
const rect = event.currentTarget.getBoundingClientRect();
const size = Math.max(rect.width, rect.height) * 2;
const id = nextId.current++;
setRipples((prev) => [
...prev,
{
id,
x: event.clientX - rect.left,
y: event.clientY - rect.top,
size,
},
]);
}
onPointerDown?.(event);
},
[ripple, reduce, onPointerDown],
);
return (
<motion.button
ref={ref}
type="button"
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
onPointerDown={handlePointerDown}
className={cn(
"relative inline-flex items-center justify-center font-medium select-none",
"transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
// The ripple layer clips itself, so on a touch screen the button can
// stop clipping and let its enlarged hit area overhang.
ripple && "overflow-hidden pointer-coarse:overflow-visible",
TOUCH_TARGET_CLASS,
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{ripple && !reduce ? (
<span className="pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]">
<AnimatePresence>
{ripples.map((r) => (
<motion.span
key={r.id}
className="absolute rounded-full bg-current"
style={{
left: r.x,
top: r.y,
width: r.size,
height: r.size,
x: "-50%",
y: "-50%",
}}
initial={{ scale: 0.05, opacity: 0.3 }}
animate={{ scale: 1, opacity: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 1.6, ease: EASE_OUT }}
onAnimationComplete={() =>
setRipples((prev) => prev.filter((x) => x.id !== r.id))
}
/>
))}
</AnimatePresence>
</span>
) : null}
{children}
</motion.button>
);
},
);
export const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(
function ButtonLink(
{
variant = "primary",
size = "md",
pressScale = 0.93,
className,
children,
...rest
},
ref,
) {
const reduce = useReducedMotion();
const canHover = useHoverCapable();
return (
<motion.a
ref={ref}
whileTap={reduce ? undefined : { scale: pressScale }}
whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}
transition={SPRING_PRESS}
className={cn(
"relative inline-flex items-center justify-center font-medium select-none",
"transition-colors",
TOUCH_TARGET_CLASS,
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
{...rest}
>
{children}
</motion.a>
);
},
);
"use client";
import { forwardRef } from "react";
import { Magnetic } from "../magnetic";
import { Button, type ButtonProps } from "./base";
export interface MagneticButtonProps extends ButtonProps {
/** Magnetic pull strength. Default 0.25. */
strength?: number;
/** Class applied to the magnetic wrapper. */
magneticClassName?: string;
}
export const MagneticButton = forwardRef<HTMLButtonElement, MagneticButtonProps>(function MagneticButton(
{ strength = 0.25, magneticClassName, children, ...rest },
ref,
) {
return (
<Magnetic strength={strength} className={magneticClassName}>
<Button ref={ref} {...rest}>
{children}
</Button>
</Magnetic>
);
});
"use client";
import { Check, Loader2, X } from "lucide-react";
import {
AnimatePresence,
motion,
useReducedMotion,
type Variants,
} from "motion/react";
import {
forwardRef,
type ReactNode,
useLayoutEffect,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { Button, type ButtonProps } from "./base";
export type ButtonState = "idle" | "loading" | "success" | "error";
export interface StatefulButtonProps extends Omit<ButtonProps, "children"> {
state?: ButtonState;
children: ReactNode;
loadingText?: ReactNode;
successText?: ReactNode;
errorText?: ReactNode;
icon?: ReactNode;
}
const CASCADE_STAGGER = 0.025;
const ROLL_BLUR = "blur(6px)";
const CASCADE_LETTER_VARIANTS: Variants = {
initial: { opacity: 0, y: "105%", filter: ROLL_BLUR },
animate: (delay: number = 0) => ({
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: { ...SPRING_SWAP, delay },
}),
exit: (delay: number = 0) => ({
opacity: 0,
y: "-105%",
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },
}),
};
const ICON_VARIANTS: Variants = {
// Width collapses too, so the icon adds/removes its own space smoothly
// instead of popping the row width in a single frame.
initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },
animate: {
opacity: 1,
width: "1.5rem",
scale: 1,
filter: "blur(0px)",
transition: SPRING_SWAP,
},
exit: {
opacity: 0,
width: 0,
scale: 0.7,
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT },
},
};
function IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {
const reduce = useReducedMotion();
return (
<motion.span
key={keyId}
variants={ICON_VARIANTS}
initial={reduce ? { opacity: 0 } : "initial"}
animate={reduce ? { opacity: 1 } : "animate"}
exit={reduce ? { opacity: 0 } : "exit"}
transition={reduce ? { duration: 0.15 } : undefined}
className="inline-grid shrink-0 place-items-center overflow-hidden"
>
{children}
</motion.span>
);
}
function TextSlot({
value,
children,
}: {
value: string;
children: ReactNode;
}) {
const reduce = useReducedMotion();
const measureRef = useRef<HTMLSpanElement>(null);
const [width, setWidth] = useState<number>();
const label = typeof children === "string" ? children : null;
const cascade = label !== null && !reduce;
// Measure strings with the same per-letter layout as the cascade. Measuring
// the whole string preserves kerning, which can make it narrower than the
// inline-block letters and clip the final glyph during the width animation.
useLayoutEffect(() => {
const nextWidth = measureRef.current?.offsetWidth;
if (!nextWidth) return;
setWidth((current) => (current === nextWidth ? current : nextWidth));
});
return (
<motion.span
initial={false}
animate={{ width }}
transition={reduce ? { duration: 0 } : SPRING_SWAP}
className="relative inline-block overflow-hidden whitespace-nowrap align-bottom"
>
<span
ref={measureRef}
aria-hidden
className="invisible inline-block whitespace-nowrap"
>
{cascade
? label.split("").map((char, index) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
className="inline-block whitespace-pre"
>
{char}
</span>
))
: children}
</span>
{cascade ? (
<>
<span className="sr-only">{label}</span>
<AnimatePresence initial={false}>
<motion.span
key={`cascade-${value}`}
aria-hidden
initial="initial"
animate="animate"
exit="exit"
className="absolute left-0 top-0 inline-block whitespace-pre"
>
{label.split("").map((char, index) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
custom={index * CASCADE_STAGGER}
variants={CASCADE_LETTER_VARIANTS}
className="inline-block whitespace-pre will-change-[opacity,filter,transform]"
>
{char}
</motion.span>
))}
</motion.span>
</AnimatePresence>
</>
) : (
<AnimatePresence initial={false}>
<motion.span
key={`text-${value}`}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: "blur(0px)" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}
transition={reduce ? { duration: 0.15 } : SPRING_SWAP}
className="absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</motion.span>
);
}
export const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(
{
state = "idle",
children,
loadingText = "Loading",
successText = "Done",
errorText = "Try again",
icon,
disabled,
...rest
},
ref,
) {
const isBusy = state === "loading";
const stateText =
state === "loading"
? loadingText
: state === "success"
? successText
: state === "error"
? errorText
: children;
const textKey =
typeof stateText === "string" ? `${state}-${stateText}` : state;
return (
<Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} whileHover={undefined} {...rest}>
<span
aria-live="polite"
className="relative inline-flex items-center justify-center overflow-hidden"
>
<AnimatePresence initial={false}>
{state === "loading" ? (
<IconSlot keyId="loading-icon">
<Loader2 className="h-4 w-4 animate-spin" />
</IconSlot>
) : null}
{state === "success" ? (
<IconSlot keyId="success-icon">
<Check className="h-4 w-4" />
</IconSlot>
) : null}
{state === "error" ? (
<IconSlot keyId="error-icon">
<X className="h-4 w-4" />
</IconSlot>
) : null}
</AnimatePresence>
<TextSlot value={textKey}>{stateText}</TextSlot>
<AnimatePresence initial={false}>
{state === "idle" && icon ? (
<IconSlot keyId="idle-icon">{icon}</IconSlot>
) : null}
</AnimatePresence>
</span>
</Button>
);
});
"use client";
import { motion, useMotionValue, useReducedMotion, useSpring } from "motion/react";
import { useRef, type ReactNode } from "react";
import { SPRING_MOUSE } from "@/lib/ease";
import { useHoverCapable } from "@/lib/hooks/use-hover-capable";
import { cn } from "@/lib/utils";
export interface MagneticProps {
children: ReactNode;
strength?: number;
className?: string;
}
export function Magnetic({ children, strength = 0.35, className }: MagneticProps) {
const ref = useRef<HTMLDivElement>(null);
const reduce = useReducedMotion();
const canHover = useHoverCapable();
// Decorative cursor-follow: skip on touch (phantom hover) and reduced motion.
const enabled = !reduce && canHover;
const x = useMotionValue(0);
const y = useMotionValue(0);
const sx = useSpring(x, SPRING_MOUSE);
const sy = useSpring(y, SPRING_MOUSE);
const onMove = (e: React.MouseEvent<HTMLDivElement>) => {
const el = ref.current;
if (!el || !enabled) return;
const rect = el.getBoundingClientRect();
x.set((e.clientX - rect.left - rect.width / 2) * strength);
y.set((e.clientY - rect.top - rect.height / 2) * strength);
};
const onLeave = () => {
x.set(0);
y.set(0);
};
return (
<motion.div
ref={ref}
onMouseMove={onMove}
onMouseLeave={onLeave}
style={{ x: sx, y: sy }}
className={cn("inline-block", className)}
>
{children}
</motion.div>
);
}
@karaui not found? Add it to components.json
{
"registries": {
"@karaui": "https://karaui.kamisama-v0.my.id/r/{name}.json"
}
}@karaui is in shadcn's public registry directory, so the latest CLI needs no setup. On an older CLI, merge this into the existing file once and every @karaui/… install resolves.
API Reference
items?CheckoutItem[]—defaultItems?CheckoutItem[][]onItemsChange?((items: CheckoutItem[]) => void)—promoCodes?CheckoutPromo[]Known codes (case-insensitive) when `onApplyPromo` isn't given.
[]onApplyPromo?((code: string) => Promise<CheckoutPromo>)Async promo check. Resolve with the promo, reject to mark the code invalid.
—onComplete?((order: CheckoutOrder) => string | Promise<string>) | undefinedPlaces the order. Card fields are UI only and never included — wire a payment provider's hosted fields for real card entry. Resolve with an order reference to show it; reject to show the message on the review step.
—taxRate?numberSales tax rate (0.08 = 8%). Default 0.08.
0.08expressPrice?numberExpress delivery price in major units. Default 15.
15currency?stringUSDlocale?stringen-USclassName?string—Keep in mind
Some components on this site are inspired by or recreated from existing work across the web. I'm not here to take credit; just to learn, experiment, and sometimes push things a bit further. If something looks familiar and I forgot to mention you, reach out and I'll fix that right away.
Updated