Checkout
Contact, shipping and payment on one page.
Installation
Run the CLI
Run
pnpm dlx asta-ui@latest initonce, then this. The file lands incomponents/astabyte/, installsradix-ui@base-ui/reactand the colour tokens go into your CSS. This is the Radix build. Drop --radix for Base UI.This is the Base UI build, the default. Want Radix? Add --radix.$ pnpm dlx asta-ui@latest add checkout --radixOr install the package
Don’t want the file? Import from
asta-uiasta-ui/baseand update withpnpm update asta-ui. Add the stylesheet once. More.$ pnpm add asta-ui radix-ui @base-ui/reactimport { Checkout } from "asta-ui";import { Checkout } from "asta-ui/base";Or copy it by hand
Install
radix-ui@base-ui/react, then copy these files. Keep the paths, or fix the@/imports. Then add the tokens fromglobals.css."use client"; import { useEffect, useId, useMemo, useRef, useState, type ChangeEvent, type ComponentProps, type ReactNode } from "react"; import { Button } from "@/components/kit/button"; import { Input } from "@/components/kit/input"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const CURVE = "cubic-bezier(.16,1,.3,1)"; export interface CheckoutLineItem { id: string; name: string; /** Size, colour or plan, e.g. "Oat · M". */ variant?: string; /** Unit price in major units, e.g. 48 or 12.5. */ price: number; qty: number; image?: string; } export interface CheckoutShippingOption { id: string; label: string; /** e.g. "2–4 business days". */ eta: string; price: number; } export interface CheckoutDetails { email: string; name: string; address: string; city: string; postal: string; country: string; shipping: string; /** Digits only. */ cardNumber: string; /** "MM/YY". */ cardExpiry: string; cardCvc: string; } export interface CheckoutProps { /** * The cart. The buyer can change quantities inside the checkout, and `onItemsChange` reports each change. * Pass a new array (a new identity) to replace the cart: the internal copy resets to it. Keep the same * array identity between renders if you don't want to discard the buyer's quantity changes. */ items: CheckoutLineItem[]; /** Runs when Pay is pressed and every field is valid. Reject to show the error and let the buyer retry. */ onPay: (order: { details: CheckoutDetails; items: CheckoutLineItem[]; total: number }) => Promise<unknown>; shippingOptions?: CheckoutShippingOption[]; countries?: { value: string; label: string }[]; /** Tax as a fraction of the discounted subtotal, e.g. 0.11. */ taxRate?: number; /** Promo code → discount as a fraction, e.g. { WELCOME10: 0.1 }. Codes are matched case-insensitively. */ promoCodes?: Record<string, number>; /** ISO 4217 code. */ currency?: string; locale?: string; defaultDetails?: Partial<CheckoutDetails>; /** Called when quantities change. */ onItemsChange?: (items: CheckoutLineItem[]) => void; className?: string; } const KEYFRAMES = `@keyframes kit-co-roll { from { opacity: 0; transform: translateY(calc(var(--kit-co-d, 1) * 70%)) } } @keyframes kit-co-up { from { opacity: 0; transform: translateY(8px) } } @keyframes kit-co-pop { 0% { opacity: 0; transform: scale(.4) } 60% { opacity: 1; transform: scale(1.08) } 100% { transform: scale(1) } } @media (prefers-reduced-motion: reduce) { .kit-co, .kit-co * { animation: none !important; transition-duration: 0s !important; } }`; const DEFAULT_SHIPPING: CheckoutShippingOption[] = [ { id: "standard", label: "Standard", eta: "3–5 business days", price: 0 }, { id: "express", label: "Express", eta: "1–2 business days", price: 14 }, ]; const DEFAULT_COUNTRIES = [ { value: "ID", label: "Indonesia" }, { value: "SG", label: "Singapore" }, { value: "AU", label: "Australia" }, { value: "GB", label: "United Kingdom" }, { value: "US", label: "United States" }, ]; const digits = (s: string) => s.replace(/\D/g, ""); // Amex (34/37, 15 digits) groups 4-6-5. Everything else groups by 4, up to 19 digits. const isAmex = (d: string) => /^3[47]/.test(d); const fmtCard = (d: string) => { if (isAmex(d)) { const v = d.slice(0, 15); return [v.slice(0, 4), v.slice(4, 10), v.slice(10)].filter(Boolean).join(" "); } return d.slice(0, 19).replace(/(\d{4})(?=\d)/g, "$1 "); }; const fmtExpiry = (d: string) => { const v = d.slice(0, 4); return v.length > 2 ? `${v.slice(0, 2)} / ${v.slice(2)}` : v; }; type Field = "email" | "name" | "address" | "city" | "postal" | "cardNumber" | "cardExpiry" | "cardCvc"; const ORDER: Field[] = ["email", "name", "address", "city", "postal", "cardNumber", "cardExpiry", "cardCvc"]; function check(f: Field, d: CheckoutDetails): string | null { const v = d[f].trim(); switch (f) { case "email": return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? null : "Enter an email like [email protected]."; case "cardNumber": return (isAmex(v) ? v.length === 15 : v.length >= 13 && v.length <= 19) ? null : isAmex(v) ? "Enter all 15 digits on the front of the card." : "Enter the full card number from the front of the card."; case "cardExpiry": { const [m, y] = v.split("/").map(Number); if (!/^\d{2}\/\d{2}$/.test(v) || !m || m > 12) return "Enter the expiry as MM / YY, like 08 / 29."; const now = new Date(); const end = new Date(2000 + y, m, 1); return end > now ? null : "This card has expired. Use one with a later date."; } case "cardCvc": return v.length >= 3 ? null : "Enter the 3 or 4 digits on the back of the card."; default: return v ? null : (REQUIRED[f] ?? "Fill in this field."); } } const REQUIRED: Partial<Record<Field, string>> = { name: "Enter your full name.", address: "Enter your street address.", city: "Enter your city.", postal: "Enter your postal code.", }; /* ---------- rolling money ---------- */ /** One character. It rolls in only if it mounted after the first render, i.e. because the value changed. */ function RollChar({ c, animate, delay }: { c: string; animate: boolean; delay: number }) { const [on] = useState(animate); return ( <span className="inline-block whitespace-pre" style={on ? { animation: `kit-co-roll .5s ${CURVE} ${delay}ms both` } : undefined}> {c} </span> ); } /** Formatted money whose changed characters roll in from the direction the value moved. */ function Money({ value, format, className }: { value: number; format: (n: number) => string; className?: string }) { const [prev, setPrev] = useState(value); const [dir, setDir] = useState(0); if (prev !== value) { setDir(value > prev ? 1 : -1); setPrev(value); } const s = format(value); const chars = s.split(""); return ( <span className={cx("inline-flex overflow-hidden tabular-nums", className)} style={{ ["--kit-co-d" as string]: dir || 1 }}> <span className="sr-only">{s}</span> <span aria-hidden className="inline-flex"> {chars.map((c, i) => ( // Keyed by position from the right, so only characters that changed re-mount and roll. <RollChar key={`${chars.length - i}-${c}`} c={c} animate={dir !== 0} delay={(chars.length - i) * 18} /> ))} </span> </span> ); } /* ---------- small pieces ---------- */ function Section({ n, title, children }: { n: number; title: string; children: ReactNode }) { return ( <fieldset className="min-w-0"> <legend className="mb-4 flex items-center gap-2.5 text-[14px] font-medium tracking-[-0.01em] text-ink"> <span className="grid h-5 w-5 place-items-center rounded-md bg-paper-2 text-[11px] tabular-nums text-ink-2">{n}</span> {title} </legend> <div className="grid gap-3">{children}</div> </fieldset> ); } function Labeled({ id, label, error, children, className }: { id: string; label: string; error?: string | null; children: ReactNode; className?: string }) { return ( <div className={cx("min-w-0", className)}> <label htmlFor={id} className="mb-1.5 block text-[12.5px] text-ink-2"> {label} </label> {children} {error && ( <p id={`${id}-err`} className="mt-1.5 flex items-center gap-1.5 text-[12px] text-ink-2" style={{ animation: `kit-co-up .3s ${CURVE}` }}> <svg viewBox="0 0 24 24" className="h-3.5 w-3.5 shrink-0" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <circle cx="12" cy="12" r="8.5" /> <path d="M12 7.5v5" /> <path d="M12 16h.01" /> </svg> {error} </p> )} </div> ); } const INVALID = "!shadow-[inset_0_0_0_1.5px_var(--color-ink)]"; function CardGlyph() { return ( <svg viewBox="0 0 24 24" className="h-3.5 w-5" fill="none" stroke="currentColor" strokeWidth="2.23" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <rect x="3" y="5.5" width="18" height="13" rx="2" /> <path d="M3 10h18" /> <path d="M6.5 15h3" /> </svg> ); } function Stepper({ name, qty, onChange, disabled }: { name: string; qty: number; onChange: (q: number) => void; disabled?: boolean }) { const btn = "grid h-6 w-6 place-items-center rounded-md text-ink-2 outline-none transition-colors duration-200 hover:bg-paper hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 disabled:opacity-35 disabled:hover:bg-transparent"; return ( <div className="inline-flex items-center gap-1" role="group" aria-label={`Quantity of ${name}`}> <button type="button" className={btn} aria-label="Fewer" disabled={disabled || qty <= 1} onClick={() => onChange(qty - 1)}> <svg viewBox="0 0 24 24" className="h-3 w-3" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="M5 12h14" /> </svg> </button> <span className="w-5 text-center text-[12.5px] tabular-nums text-ink" aria-live="polite"> {qty} </span> <button type="button" className={btn} aria-label="More" disabled={disabled || qty >= 99} onClick={() => onChange(qty + 1)}> <svg viewBox="0 0 24 24" className="h-3 w-3" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="M12 5v14" /> <path d="M5 12h14" /> </svg> </button> </div> ); } /* ---------- checkout ---------- */ /** * A one-page checkout: contact, shipping and payment on the left, the order on the right. Card fields * format as you type. Change a quantity, the shipping speed or add a promo code and the totals roll to * the new amount. Pay shows a pending state, then a receipt. A failed payment keeps everything filled in. */ export function Checkout({ items: initialItems, onPay, shippingOptions = DEFAULT_SHIPPING, countries = DEFAULT_COUNTRIES, taxRate = 0, promoCodes = {}, currency = "USD", locale, defaultDetails, onItemsChange, className, }: CheckoutProps) { const uid = useId(); const id = (f: string) => `${uid}-${f}`; const [items, setItems] = useState(initialItems); // A new `items` array from the parent replaces the cart (see the prop docs). const [seenItems, setSeenItems] = useState(initialItems); if (seenItems !== initialItems) { setSeenItems(initialItems); setItems(initialItems); } const [d, setD] = useState<CheckoutDetails>(() => ({ email: "", name: "", address: "", city: "", postal: "", country: countries[0]?.value ?? "", shipping: shippingOptions[0]?.id ?? "", cardNumber: "", cardExpiry: "", cardCvc: "", ...defaultDetails, })); const [touched, setTouched] = useState<Partial<Record<Field, boolean>>>({}); const [promoOpen, setPromoOpen] = useState(false); const [promoText, setPromoText] = useState(""); const [promo, setPromo] = useState<{ code: string; off: number } | null>(null); const [promoMsg, setPromoMsg] = useState(""); const [state, setState] = useState<"idle" | "pending" | "done">("idle"); const [payError, setPayError] = useState(""); const alive = useRef(true); useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); const money = useMemo(() => { const f = new Intl.NumberFormat(locale, { style: "currency", currency }); return (n: number) => f.format(n); }, [locale, currency]); const ship = shippingOptions.find((s) => s.id === d.shipping) ?? shippingOptions[0]; const subtotal = items.reduce((a, i) => a + i.price * i.qty, 0); const discount = promo ? Math.round(subtotal * promo.off * 100) / 100 : 0; const tax = Math.round((subtotal - discount) * taxRate * 100) / 100; const total = Math.max(0, subtotal - discount + (ship?.price ?? 0) + tax); const errors = Object.fromEntries(ORDER.map((f) => [f, check(f, d)])) as Record<Field, string | null>; const shown = (f: Field) => (touched[f] ? errors[f] : null); const locked = state !== "idle"; // Errors show on blur or Pay. Typing never adds one: a field that becomes valid clears its error and stays // quiet until the next blur. const set = (f: keyof CheckoutDetails, v: string) => { setD((p) => ({ ...p, [f]: v })); const k = f as Field; if (ORDER.includes(k) && touched[k] && !check(k, { ...d, [f]: v })) setTouched((t) => ({ ...t, [k]: false })); }; const blur = (f: Field) => setTouched((t) => ({ ...t, [f]: true })); // Formatted fields keep the caret after the same number of digits. const formatted = (f: "cardNumber" | "cardExpiry" | "cardCvc", fmt: (d: string) => string, max: number) => (e: ChangeEvent<HTMLInputElement>) => { const el = e.currentTarget; const before = digits(el.value.slice(0, el.selectionStart ?? el.value.length)).length; const raw = digits(el.value).slice(0, max); const out = fmt(raw); // Card numbers store what the format kept (Amex stops at 15). set(f, f === "cardExpiry" ? out.replace(/\s/g, "") : f === "cardNumber" ? digits(out) : raw); let pos = 0; for (let seen = 0; pos < out.length && seen < before; pos++) if (/\d/.test(out[pos])) seen++; requestAnimationFrame(() => { if (document.activeElement === el) el.setSelectionRange(pos, pos); }); }; const changeQty = (itemId: string, qty: number) => { const next = items.map((i) => (i.id === itemId ? { ...i, qty } : i)); setItems(next); onItemsChange?.(next); }; const applyPromo = () => { const code = promoText.trim().toUpperCase(); const hit = Object.entries(promoCodes).find(([k]) => k.toUpperCase() === code); if (!code) return setPromoMsg("Enter a promo code first."); if (hit) { setPromo({ code: hit[0].toUpperCase(), off: hit[1] }); setPromoMsg(`${hit[0].toUpperCase()} applied.`); setPromoText(""); setPromoOpen(false); } else setPromoMsg("That code isn't valid. Check the spelling and try again."); }; const pay = async () => { if (locked) return; const bad = ORDER.filter((f) => errors[f]); if (bad.length) { setTouched(Object.fromEntries(ORDER.map((f) => [f, true]))); document.getElementById(id(bad[0]))?.focus(); return; } setPayError(""); setState("pending"); try { await onPay({ details: d, items, total }); if (alive.current) setState("done"); } catch (err) { if (!alive.current) return; setState("idle"); setPayError(err instanceof Error && err.message ? err.message : "The payment didn't go through. Check the card and try again."); } }; const input = (f: Field, extra: Partial<ComponentProps<typeof Input>> = {}) => ( <Input id={id(f)} name={f} value={f === "cardNumber" ? fmtCard(d[f]) : f === "cardExpiry" ? fmtExpiry(digits(d[f])) : d[f]} onChange={(e) => set(f, e.target.value)} onBlur={() => blur(f)} disabled={locked} aria-invalid={!!shown(f) || undefined} aria-describedby={shown(f) ? `${id(f)}-err` : undefined} className={cx(shown(f) && INVALID)} {...extra} /> ); const rowCls = "flex items-baseline justify-between gap-4 text-[13px]"; return ( <div className={cx("kit-co grid w-full gap-8 md:grid-cols-[minmax(0,1fr)_340px] md:gap-10", className)}> <style href="asta-checkout" precedence="asta">{KEYFRAMES}</style> {/* ---------- form ---------- */} <div className="min-w-0"> {state === "done" ? ( <div className="flex h-full min-h-[420px] flex-col items-start justify-center" role="status" style={{ animation: `kit-co-up .5s ${CURVE}` }}> <span className="grid h-12 w-12 place-items-center rounded-full bg-brand text-on-brand" style={{ animation: `kit-co-pop .55s ${CURVE} .1s both` }}> <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="m5 12.5 4.5 4.5L19 7.5" /> </svg> </span> <h3 className="mt-6 text-[24px] font-medium tracking-[-0.03em] text-ink">Payment received</h3> <p className="mt-2 max-w-[360px] text-[14px] leading-relaxed text-mute"> We charged {money(total)} to the card ending {d.cardNumber.slice(-4)}. A receipt is on its way to {d.email}. </p> <Button variant="ghost" size="sm" className="mt-6 -ml-3" onClick={() => setState("idle")}> Back to checkout </Button> </div> ) : ( <form noValidate className="grid gap-9" onSubmit={(e) => { e.preventDefault(); pay(); }} > <Section n={1} title="Contact"> <Labeled id={id("email")} label="Email" error={shown("email")}> {input("email", { type: "email", autoComplete: "email", inputMode: "email", autoCapitalize: "none", spellCheck: false, placeholder: "[email protected]" })} </Labeled> </Section> <Section n={2} title="Shipping"> <Labeled id={id("name")} label="Full name" error={shown("name")}> {input("name", { autoComplete: "name" })} </Labeled> <Labeled id={id("address")} label="Address" error={shown("address")}> {input("address", { autoComplete: "address-line1" })} </Labeled> <div className="grid grid-cols-2 gap-3"> <Labeled id={id("city")} label="City" error={shown("city")}> {input("city", { autoComplete: "address-level2" })} </Labeled> <Labeled id={id("postal")} label="Postal code" error={shown("postal")}> {input("postal", { autoComplete: "postal-code", autoCapitalize: "characters" })} </Labeled> </div> {/* A native select: browsers autofill it from autocomplete="country", phones open their own picker, and it saves the ~25 KB of popup code a custom select would bring into every checkout. */} <Labeled id={id("country")} label="Country"> <div className={cx("relative", locked && "pointer-events-none opacity-50")}> <select id={id("country")} name="country" autoComplete="country" value={d.country} onChange={(e) => set("country", e.target.value)} disabled={locked} className="h-10 w-full appearance-none rounded-lg bg-paper pl-3 pr-9 text-[16px] text-ink outline-none transition-shadow duration-200 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_14%,transparent)] hover:shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_24%,transparent)] focus-visible:!shadow-[inset_0_0_0_1px_var(--color-brand),0_0_0_4px_color-mix(in_srgb,var(--color-brand)_16%,transparent)] sm:text-[14px]" > {countries.map((c) => ( <option key={c.value} value={c.value}> {c.label} </option> ))} </select> <svg viewBox="0 0 16 16" className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-mute" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="m4 6 4 4 4-4" /> </svg> </div> </Labeled> <div role="radiogroup" aria-label="Shipping speed" className="mt-1 grid gap-2 sm:grid-cols-2"> {shippingOptions.map((s) => { const on = s.id === d.shipping; return ( <label key={s.id} className={cx( "relative flex cursor-pointer items-start justify-between gap-3 rounded-[10px] p-3 transition-shadow duration-300 has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-brand/50", on ? "shadow-[inset_0_0_0_1.5px_var(--color-brand)]" : "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_12%,transparent)] hover:shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_26%,transparent)]", locked && "pointer-events-none opacity-60", )} > <input type="radio" name={id("ship")} value={s.id} checked={on} disabled={locked} onChange={() => set("shipping", s.id)} className="sr-only" /> <span> <span className="block text-[13.5px] text-ink">{s.label}</span> <span className="block text-[12px] text-mute">{s.eta}</span> </span> <span className="text-[13px] tabular-nums text-ink">{s.price ? money(s.price) : "Free"}</span> </label> ); })} </div> </Section> <Section n={3} title="Payment"> <Labeled id={id("cardNumber")} label="Card number" error={shown("cardNumber")}> {input("cardNumber", { inputMode: "numeric", autoComplete: "cc-number", placeholder: "1234 1234 1234 1234", onChange: formatted("cardNumber", fmtCard, 19), iconRight: <CardGlyph />, })} </Labeled> <div className="grid grid-cols-2 gap-3"> <Labeled id={id("cardExpiry")} label="Expiry" error={shown("cardExpiry")}> {input("cardExpiry", { inputMode: "numeric", autoComplete: "cc-exp", placeholder: "MM / YY", onChange: formatted("cardExpiry", fmtExpiry, 4) })} </Labeled> <Labeled id={id("cardCvc")} label="CVC" error={shown("cardCvc")}> {input("cardCvc", { inputMode: "numeric", autoComplete: "cc-csc", placeholder: "123", onChange: formatted("cardCvc", (x) => x, 4) })} </Labeled> </div> </Section> <div> <Button type="submit" variant="accent" size="lg" className="w-full" loading={state === "pending"}> Pay {money(total)} </Button> <p className="mt-3 h-4 text-center text-[12px] text-mute" aria-live="polite"> {state === "pending" ? "Processing your payment…" : payError || "Payments are encrypted. You won't be charged twice."} </p> </div> </form> )} </div> {/* ---------- summary ---------- */} <aside aria-label="Order summary" className="h-max rounded-[14px] bg-paper-2 p-5 md:sticky md:top-4"> <h3 className="text-[14px] font-medium tracking-[-0.01em] text-ink">Order</h3> <ul className="mt-4 grid gap-4"> {items.map((i) => ( <li key={i.id} className="flex gap-3"> {i.image ? ( <img src={i.image} alt="" className="h-14 w-14 shrink-0 rounded-[10px] bg-paper object-cover" /> ) : ( <span aria-hidden className="grid h-14 w-14 shrink-0 place-items-center rounded-[10px] bg-paper text-[15px] font-medium text-mute"> {i.name[0]} </span> )} <div className="min-w-0 flex-1"> <div className="flex items-baseline justify-between gap-3"> <p className="truncate text-[13.5px] text-ink">{i.name}</p> <Money value={i.price * i.qty} format={money} className="text-[13px] text-ink" /> </div> {i.variant && <p className="text-[12px] text-mute">{i.variant}</p>} <div className="mt-1 -ml-1"> <Stepper name={i.name} qty={i.qty} disabled={locked} onChange={(q) => changeQty(i.id, q)} /> </div> </div> </li> ))} </ul> <div className="mt-5"> {promo ? ( <p className="flex items-center justify-between text-[12.5px] text-ink-2"> <span> Code <span className="font-medium text-ink">{promo.code}</span> </span> <button type="button" disabled={locked} onClick={() => { setPromo(null); setPromoMsg("Code removed."); }} className="rounded text-mute outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 disabled:opacity-40" > Remove </button> </p> ) : promoOpen ? ( <div className="flex gap-2" style={{ animation: `kit-co-up .3s ${CURVE}` }}> <Input size="sm" name="promo" aria-label="Promo code" aria-describedby={promoMsg ? `${uid}-promo-msg` : undefined} placeholder="Enter code…" autoComplete="off" autoCapitalize="characters" spellCheck={false} value={promoText} autoFocus disabled={locked} onChange={(e) => { setPromoText(e.target.value); setPromoMsg(""); }} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); applyPromo(); } else if (e.key === "Escape") setPromoOpen(false); }} /> <Button size="sm" variant="outline" onClick={applyPromo} disabled={locked}> Apply </Button> </div> ) : ( <button type="button" disabled={locked} onClick={() => setPromoOpen(true)} className="rounded text-[12.5px] text-ink-2 underline decoration-[color-mix(in_srgb,var(--color-ink)_25%,transparent)] underline-offset-4 outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 disabled:opacity-40" > Add a promo code </button> )} <p id={`${uid}-promo-msg`} className="mt-1.5 min-h-4 text-[12px] text-mute" aria-live="polite"> {promoMsg} </p> </div> <dl className="mt-3 grid gap-2"> <div className={rowCls}> <dt className="text-mute">Subtotal</dt> <dd> <Money value={subtotal} format={money} className="text-ink" /> </dd> </div> {discount > 0 && ( <div className={rowCls} style={{ animation: `kit-co-up .35s ${CURVE}` }}> <dt className="text-mute">Discount</dt> <dd className="text-brand"> −<Money value={discount} format={money} /> </dd> </div> )} <div className={rowCls}> <dt className="text-mute">Shipping</dt> <dd className="text-ink">{ship && ship.price ? <Money value={ship.price} format={money} /> : "Free"}</dd> </div> {taxRate > 0 && ( <div className={rowCls}> <dt className="text-mute">Tax</dt> <dd> <Money value={tax} format={money} className="text-ink" /> </dd> </div> )} <div className="mt-3 flex items-baseline justify-between gap-4 pt-1"> <dt className="text-[14px] font-medium text-ink">Total</dt> <dd> <Money value={total} format={money} className="text-[20px] font-medium tracking-[-0.02em] text-ink" /> </dd> </div> </dl> </aside> </div> ); } export default Checkout;"use client"; import { useEffect, useId, useMemo, useRef, useState, type ChangeEvent, type ComponentProps, type ReactNode } from "react"; import { Button } from "@/components/kit/base/button"; import { Input } from "@/components/kit/input"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const CURVE = "cubic-bezier(.16,1,.3,1)"; export interface CheckoutLineItem { id: string; name: string; /** Size, colour or plan, e.g. "Oat · M". */ variant?: string; /** Unit price in major units, e.g. 48 or 12.5. */ price: number; qty: number; image?: string; } export interface CheckoutShippingOption { id: string; label: string; /** e.g. "2–4 business days". */ eta: string; price: number; } export interface CheckoutDetails { email: string; name: string; address: string; city: string; postal: string; country: string; shipping: string; /** Digits only. */ cardNumber: string; /** "MM/YY". */ cardExpiry: string; cardCvc: string; } export interface CheckoutProps { /** * The cart. The buyer can change quantities inside the checkout, and `onItemsChange` reports each change. * Pass a new array (a new identity) to replace the cart: the internal copy resets to it. Keep the same * array identity between renders if you don't want to discard the buyer's quantity changes. */ items: CheckoutLineItem[]; /** Runs when Pay is pressed and every field is valid. Reject to show the error and let the buyer retry. */ onPay: (order: { details: CheckoutDetails; items: CheckoutLineItem[]; total: number }) => Promise<unknown>; shippingOptions?: CheckoutShippingOption[]; countries?: { value: string; label: string }[]; /** Tax as a fraction of the discounted subtotal, e.g. 0.11. */ taxRate?: number; /** Promo code → discount as a fraction, e.g. { WELCOME10: 0.1 }. Codes are matched case-insensitively. */ promoCodes?: Record<string, number>; /** ISO 4217 code. */ currency?: string; locale?: string; defaultDetails?: Partial<CheckoutDetails>; /** Called when quantities change. */ onItemsChange?: (items: CheckoutLineItem[]) => void; className?: string; } const KEYFRAMES = `@keyframes kit-co-roll { from { opacity: 0; transform: translateY(calc(var(--kit-co-d, 1) * 70%)) } } @keyframes kit-co-up { from { opacity: 0; transform: translateY(8px) } } @keyframes kit-co-pop { 0% { opacity: 0; transform: scale(.4) } 60% { opacity: 1; transform: scale(1.08) } 100% { transform: scale(1) } } @media (prefers-reduced-motion: reduce) { .kit-co, .kit-co * { animation: none !important; transition-duration: 0s !important; } }`; const DEFAULT_SHIPPING: CheckoutShippingOption[] = [ { id: "standard", label: "Standard", eta: "3–5 business days", price: 0 }, { id: "express", label: "Express", eta: "1–2 business days", price: 14 }, ]; const DEFAULT_COUNTRIES = [ { value: "ID", label: "Indonesia" }, { value: "SG", label: "Singapore" }, { value: "AU", label: "Australia" }, { value: "GB", label: "United Kingdom" }, { value: "US", label: "United States" }, ]; const digits = (s: string) => s.replace(/\D/g, ""); // Amex (34/37, 15 digits) groups 4-6-5. Everything else groups by 4, up to 19 digits. const isAmex = (d: string) => /^3[47]/.test(d); const fmtCard = (d: string) => { if (isAmex(d)) { const v = d.slice(0, 15); return [v.slice(0, 4), v.slice(4, 10), v.slice(10)].filter(Boolean).join(" "); } return d.slice(0, 19).replace(/(\d{4})(?=\d)/g, "$1 "); }; const fmtExpiry = (d: string) => { const v = d.slice(0, 4); return v.length > 2 ? `${v.slice(0, 2)} / ${v.slice(2)}` : v; }; type Field = "email" | "name" | "address" | "city" | "postal" | "cardNumber" | "cardExpiry" | "cardCvc"; const ORDER: Field[] = ["email", "name", "address", "city", "postal", "cardNumber", "cardExpiry", "cardCvc"]; function check(f: Field, d: CheckoutDetails): string | null { const v = d[f].trim(); switch (f) { case "email": return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? null : "Enter an email like [email protected]."; case "cardNumber": return (isAmex(v) ? v.length === 15 : v.length >= 13 && v.length <= 19) ? null : isAmex(v) ? "Enter all 15 digits on the front of the card." : "Enter the full card number from the front of the card."; case "cardExpiry": { const [m, y] = v.split("/").map(Number); if (!/^\d{2}\/\d{2}$/.test(v) || !m || m > 12) return "Enter the expiry as MM / YY, like 08 / 29."; const now = new Date(); const end = new Date(2000 + y, m, 1); return end > now ? null : "This card has expired. Use one with a later date."; } case "cardCvc": return v.length >= 3 ? null : "Enter the 3 or 4 digits on the back of the card."; default: return v ? null : (REQUIRED[f] ?? "Fill in this field."); } } const REQUIRED: Partial<Record<Field, string>> = { name: "Enter your full name.", address: "Enter your street address.", city: "Enter your city.", postal: "Enter your postal code.", }; /* ---------- rolling money ---------- */ /** One character. It rolls in only if it mounted after the first render, i.e. because the value changed. */ function RollChar({ c, animate, delay }: { c: string; animate: boolean; delay: number }) { const [on] = useState(animate); return ( <span className="inline-block whitespace-pre" style={on ? { animation: `kit-co-roll .5s ${CURVE} ${delay}ms both` } : undefined}> {c} </span> ); } /** Formatted money whose changed characters roll in from the direction the value moved. */ function Money({ value, format, className }: { value: number; format: (n: number) => string; className?: string }) { const [prev, setPrev] = useState(value); const [dir, setDir] = useState(0); if (prev !== value) { setDir(value > prev ? 1 : -1); setPrev(value); } const s = format(value); const chars = s.split(""); return ( <span className={cx("inline-flex overflow-hidden tabular-nums", className)} style={{ ["--kit-co-d" as string]: dir || 1 }}> <span className="sr-only">{s}</span> <span aria-hidden className="inline-flex"> {chars.map((c, i) => ( // Keyed by position from the right, so only characters that changed re-mount and roll. <RollChar key={`${chars.length - i}-${c}`} c={c} animate={dir !== 0} delay={(chars.length - i) * 18} /> ))} </span> </span> ); } /* ---------- small pieces ---------- */ function Section({ n, title, children }: { n: number; title: string; children: ReactNode }) { return ( <fieldset className="min-w-0"> <legend className="mb-4 flex items-center gap-2.5 text-[14px] font-medium tracking-[-0.01em] text-ink"> <span className="grid h-5 w-5 place-items-center rounded-md bg-paper-2 text-[11px] tabular-nums text-ink-2">{n}</span> {title} </legend> <div className="grid gap-3">{children}</div> </fieldset> ); } function Labeled({ id, label, error, children, className }: { id: string; label: string; error?: string | null; children: ReactNode; className?: string }) { return ( <div className={cx("min-w-0", className)}> <label htmlFor={id} className="mb-1.5 block text-[12.5px] text-ink-2"> {label} </label> {children} {error && ( <p id={`${id}-err`} className="mt-1.5 flex items-center gap-1.5 text-[12px] text-ink-2" style={{ animation: `kit-co-up .3s ${CURVE}` }}> <svg viewBox="0 0 24 24" className="h-3.5 w-3.5 shrink-0" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <circle cx="12" cy="12" r="8.5" /> <path d="M12 7.5v5" /> <path d="M12 16h.01" /> </svg> {error} </p> )} </div> ); } const INVALID = "!shadow-[inset_0_0_0_1.5px_var(--color-ink)]"; function CardGlyph() { return ( <svg viewBox="0 0 24 24" className="h-3.5 w-5" fill="none" stroke="currentColor" strokeWidth="2.23" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <rect x="3" y="5.5" width="18" height="13" rx="2" /> <path d="M3 10h18" /> <path d="M6.5 15h3" /> </svg> ); } function Stepper({ name, qty, onChange, disabled }: { name: string; qty: number; onChange: (q: number) => void; disabled?: boolean }) { const btn = "grid h-6 w-6 place-items-center rounded-md text-ink-2 outline-none transition-colors duration-200 hover:bg-paper hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 disabled:opacity-35 disabled:hover:bg-transparent"; return ( <div className="inline-flex items-center gap-1" role="group" aria-label={`Quantity of ${name}`}> <button type="button" className={btn} aria-label="Fewer" disabled={disabled || qty <= 1} onClick={() => onChange(qty - 1)}> <svg viewBox="0 0 24 24" className="h-3 w-3" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="M5 12h14" /> </svg> </button> <span className="w-5 text-center text-[12.5px] tabular-nums text-ink" aria-live="polite"> {qty} </span> <button type="button" className={btn} aria-label="More" disabled={disabled || qty >= 99} onClick={() => onChange(qty + 1)}> <svg viewBox="0 0 24 24" className="h-3 w-3" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="M12 5v14" /> <path d="M5 12h14" /> </svg> </button> </div> ); } /* ---------- checkout ---------- */ /** * A one-page checkout: contact, shipping and payment on the left, the order on the right. Card fields * format as you type. Change a quantity, the shipping speed or add a promo code and the totals roll to * the new amount. Pay shows a pending state, then a receipt. A failed payment keeps everything filled in. */ export function Checkout({ items: initialItems, onPay, shippingOptions = DEFAULT_SHIPPING, countries = DEFAULT_COUNTRIES, taxRate = 0, promoCodes = {}, currency = "USD", locale, defaultDetails, onItemsChange, className, }: CheckoutProps) { const uid = useId(); const id = (f: string) => `${uid}-${f}`; const [items, setItems] = useState(initialItems); // A new `items` array from the parent replaces the cart (see the prop docs). const [seenItems, setSeenItems] = useState(initialItems); if (seenItems !== initialItems) { setSeenItems(initialItems); setItems(initialItems); } const [d, setD] = useState<CheckoutDetails>(() => ({ email: "", name: "", address: "", city: "", postal: "", country: countries[0]?.value ?? "", shipping: shippingOptions[0]?.id ?? "", cardNumber: "", cardExpiry: "", cardCvc: "", ...defaultDetails, })); const [touched, setTouched] = useState<Partial<Record<Field, boolean>>>({}); const [promoOpen, setPromoOpen] = useState(false); const [promoText, setPromoText] = useState(""); const [promo, setPromo] = useState<{ code: string; off: number } | null>(null); const [promoMsg, setPromoMsg] = useState(""); const [state, setState] = useState<"idle" | "pending" | "done">("idle"); const [payError, setPayError] = useState(""); const alive = useRef(true); useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); const money = useMemo(() => { const f = new Intl.NumberFormat(locale, { style: "currency", currency }); return (n: number) => f.format(n); }, [locale, currency]); const ship = shippingOptions.find((s) => s.id === d.shipping) ?? shippingOptions[0]; const subtotal = items.reduce((a, i) => a + i.price * i.qty, 0); const discount = promo ? Math.round(subtotal * promo.off * 100) / 100 : 0; const tax = Math.round((subtotal - discount) * taxRate * 100) / 100; const total = Math.max(0, subtotal - discount + (ship?.price ?? 0) + tax); const errors = Object.fromEntries(ORDER.map((f) => [f, check(f, d)])) as Record<Field, string | null>; const shown = (f: Field) => (touched[f] ? errors[f] : null); const locked = state !== "idle"; // Errors show on blur or Pay. Typing never adds one: a field that becomes valid clears its error and stays // quiet until the next blur. const set = (f: keyof CheckoutDetails, v: string) => { setD((p) => ({ ...p, [f]: v })); const k = f as Field; if (ORDER.includes(k) && touched[k] && !check(k, { ...d, [f]: v })) setTouched((t) => ({ ...t, [k]: false })); }; const blur = (f: Field) => setTouched((t) => ({ ...t, [f]: true })); // Formatted fields keep the caret after the same number of digits. const formatted = (f: "cardNumber" | "cardExpiry" | "cardCvc", fmt: (d: string) => string, max: number) => (e: ChangeEvent<HTMLInputElement>) => { const el = e.currentTarget; const before = digits(el.value.slice(0, el.selectionStart ?? el.value.length)).length; const raw = digits(el.value).slice(0, max); const out = fmt(raw); // Card numbers store what the format kept (Amex stops at 15). set(f, f === "cardExpiry" ? out.replace(/\s/g, "") : f === "cardNumber" ? digits(out) : raw); let pos = 0; for (let seen = 0; pos < out.length && seen < before; pos++) if (/\d/.test(out[pos])) seen++; requestAnimationFrame(() => { if (document.activeElement === el) el.setSelectionRange(pos, pos); }); }; const changeQty = (itemId: string, qty: number) => { const next = items.map((i) => (i.id === itemId ? { ...i, qty } : i)); setItems(next); onItemsChange?.(next); }; const applyPromo = () => { const code = promoText.trim().toUpperCase(); const hit = Object.entries(promoCodes).find(([k]) => k.toUpperCase() === code); if (!code) return setPromoMsg("Enter a promo code first."); if (hit) { setPromo({ code: hit[0].toUpperCase(), off: hit[1] }); setPromoMsg(`${hit[0].toUpperCase()} applied.`); setPromoText(""); setPromoOpen(false); } else setPromoMsg("That code isn't valid. Check the spelling and try again."); }; const pay = async () => { if (locked) return; const bad = ORDER.filter((f) => errors[f]); if (bad.length) { setTouched(Object.fromEntries(ORDER.map((f) => [f, true]))); document.getElementById(id(bad[0]))?.focus(); return; } setPayError(""); setState("pending"); try { await onPay({ details: d, items, total }); if (alive.current) setState("done"); } catch (err) { if (!alive.current) return; setState("idle"); setPayError(err instanceof Error && err.message ? err.message : "The payment didn't go through. Check the card and try again."); } }; const input = (f: Field, extra: Partial<ComponentProps<typeof Input>> = {}) => ( <Input id={id(f)} name={f} value={f === "cardNumber" ? fmtCard(d[f]) : f === "cardExpiry" ? fmtExpiry(digits(d[f])) : d[f]} onChange={(e) => set(f, e.target.value)} onBlur={() => blur(f)} disabled={locked} aria-invalid={!!shown(f) || undefined} aria-describedby={shown(f) ? `${id(f)}-err` : undefined} className={cx(shown(f) && INVALID)} {...extra} /> ); const rowCls = "flex items-baseline justify-between gap-4 text-[13px]"; return ( <div className={cx("kit-co grid w-full gap-8 md:grid-cols-[minmax(0,1fr)_340px] md:gap-10", className)}> <style href="asta-checkout" precedence="asta">{KEYFRAMES}</style> {/* ---------- form ---------- */} <div className="min-w-0"> {state === "done" ? ( <div className="flex h-full min-h-[420px] flex-col items-start justify-center" role="status" style={{ animation: `kit-co-up .5s ${CURVE}` }}> <span className="grid h-12 w-12 place-items-center rounded-full bg-brand text-on-brand" style={{ animation: `kit-co-pop .55s ${CURVE} .1s both` }}> <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="m5 12.5 4.5 4.5L19 7.5" /> </svg> </span> <h3 className="mt-6 text-[24px] font-medium tracking-[-0.03em] text-ink">Payment received</h3> <p className="mt-2 max-w-[360px] text-[14px] leading-relaxed text-mute"> We charged {money(total)} to the card ending {d.cardNumber.slice(-4)}. A receipt is on its way to {d.email}. </p> <Button variant="ghost" size="sm" className="mt-6 -ml-3" onClick={() => setState("idle")}> Back to checkout </Button> </div> ) : ( <form noValidate className="grid gap-9" onSubmit={(e) => { e.preventDefault(); pay(); }} > <Section n={1} title="Contact"> <Labeled id={id("email")} label="Email" error={shown("email")}> {input("email", { type: "email", autoComplete: "email", inputMode: "email", autoCapitalize: "none", spellCheck: false, placeholder: "[email protected]" })} </Labeled> </Section> <Section n={2} title="Shipping"> <Labeled id={id("name")} label="Full name" error={shown("name")}> {input("name", { autoComplete: "name" })} </Labeled> <Labeled id={id("address")} label="Address" error={shown("address")}> {input("address", { autoComplete: "address-line1" })} </Labeled> <div className="grid grid-cols-2 gap-3"> <Labeled id={id("city")} label="City" error={shown("city")}> {input("city", { autoComplete: "address-level2" })} </Labeled> <Labeled id={id("postal")} label="Postal code" error={shown("postal")}> {input("postal", { autoComplete: "postal-code", autoCapitalize: "characters" })} </Labeled> </div> {/* A native select: browsers autofill it from autocomplete="country", phones open their own picker, and it saves the ~25 KB of popup code a custom select would bring into every checkout. */} <Labeled id={id("country")} label="Country"> <div className={cx("relative", locked && "pointer-events-none opacity-50")}> <select id={id("country")} name="country" autoComplete="country" value={d.country} onChange={(e) => set("country", e.target.value)} disabled={locked} className="h-10 w-full appearance-none rounded-lg bg-paper pl-3 pr-9 text-[16px] text-ink outline-none transition-shadow duration-200 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_14%,transparent)] hover:shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_24%,transparent)] focus-visible:!shadow-[inset_0_0_0_1px_var(--color-brand),0_0_0_4px_color-mix(in_srgb,var(--color-brand)_16%,transparent)] sm:text-[14px]" > {countries.map((c) => ( <option key={c.value} value={c.value}> {c.label} </option> ))} </select> <svg viewBox="0 0 16 16" className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-mute" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="m4 6 4 4 4-4" /> </svg> </div> </Labeled> <div role="radiogroup" aria-label="Shipping speed" className="mt-1 grid gap-2 sm:grid-cols-2"> {shippingOptions.map((s) => { const on = s.id === d.shipping; return ( <label key={s.id} className={cx( "relative flex cursor-pointer items-start justify-between gap-3 rounded-[10px] p-3 transition-shadow duration-300 has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-brand/50", on ? "shadow-[inset_0_0_0_1.5px_var(--color-brand)]" : "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_12%,transparent)] hover:shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_26%,transparent)]", locked && "pointer-events-none opacity-60", )} > <input type="radio" name={id("ship")} value={s.id} checked={on} disabled={locked} onChange={() => set("shipping", s.id)} className="sr-only" /> <span> <span className="block text-[13.5px] text-ink">{s.label}</span> <span className="block text-[12px] text-mute">{s.eta}</span> </span> <span className="text-[13px] tabular-nums text-ink">{s.price ? money(s.price) : "Free"}</span> </label> ); })} </div> </Section> <Section n={3} title="Payment"> <Labeled id={id("cardNumber")} label="Card number" error={shown("cardNumber")}> {input("cardNumber", { inputMode: "numeric", autoComplete: "cc-number", placeholder: "1234 1234 1234 1234", onChange: formatted("cardNumber", fmtCard, 19), iconRight: <CardGlyph />, })} </Labeled> <div className="grid grid-cols-2 gap-3"> <Labeled id={id("cardExpiry")} label="Expiry" error={shown("cardExpiry")}> {input("cardExpiry", { inputMode: "numeric", autoComplete: "cc-exp", placeholder: "MM / YY", onChange: formatted("cardExpiry", fmtExpiry, 4) })} </Labeled> <Labeled id={id("cardCvc")} label="CVC" error={shown("cardCvc")}> {input("cardCvc", { inputMode: "numeric", autoComplete: "cc-csc", placeholder: "123", onChange: formatted("cardCvc", (x) => x, 4) })} </Labeled> </div> </Section> <div> <Button type="submit" variant="accent" size="lg" className="w-full" loading={state === "pending"}> Pay {money(total)} </Button> <p className="mt-3 h-4 text-center text-[12px] text-mute" aria-live="polite"> {state === "pending" ? "Processing your payment…" : payError || "Payments are encrypted. You won't be charged twice."} </p> </div> </form> )} </div> {/* ---------- summary ---------- */} <aside aria-label="Order summary" className="h-max rounded-[14px] bg-paper-2 p-5 md:sticky md:top-4"> <h3 className="text-[14px] font-medium tracking-[-0.01em] text-ink">Order</h3> <ul className="mt-4 grid gap-4"> {items.map((i) => ( <li key={i.id} className="flex gap-3"> {i.image ? ( <img src={i.image} alt="" className="h-14 w-14 shrink-0 rounded-[10px] bg-paper object-cover" /> ) : ( <span aria-hidden className="grid h-14 w-14 shrink-0 place-items-center rounded-[10px] bg-paper text-[15px] font-medium text-mute"> {i.name[0]} </span> )} <div className="min-w-0 flex-1"> <div className="flex items-baseline justify-between gap-3"> <p className="truncate text-[13.5px] text-ink">{i.name}</p> <Money value={i.price * i.qty} format={money} className="text-[13px] text-ink" /> </div> {i.variant && <p className="text-[12px] text-mute">{i.variant}</p>} <div className="mt-1 -ml-1"> <Stepper name={i.name} qty={i.qty} disabled={locked} onChange={(q) => changeQty(i.id, q)} /> </div> </div> </li> ))} </ul> <div className="mt-5"> {promo ? ( <p className="flex items-center justify-between text-[12.5px] text-ink-2"> <span> Code <span className="font-medium text-ink">{promo.code}</span> </span> <button type="button" disabled={locked} onClick={() => { setPromo(null); setPromoMsg("Code removed."); }} className="rounded text-mute outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 disabled:opacity-40" > Remove </button> </p> ) : promoOpen ? ( <div className="flex gap-2" style={{ animation: `kit-co-up .3s ${CURVE}` }}> <Input size="sm" name="promo" aria-label="Promo code" aria-describedby={promoMsg ? `${uid}-promo-msg` : undefined} placeholder="Enter code…" autoComplete="off" autoCapitalize="characters" spellCheck={false} value={promoText} autoFocus disabled={locked} onChange={(e) => { setPromoText(e.target.value); setPromoMsg(""); }} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); applyPromo(); } else if (e.key === "Escape") setPromoOpen(false); }} /> <Button size="sm" variant="outline" onClick={applyPromo} disabled={locked}> Apply </Button> </div> ) : ( <button type="button" disabled={locked} onClick={() => setPromoOpen(true)} className="rounded text-[12.5px] text-ink-2 underline decoration-[color-mix(in_srgb,var(--color-ink)_25%,transparent)] underline-offset-4 outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 disabled:opacity-40" > Add a promo code </button> )} <p id={`${uid}-promo-msg`} className="mt-1.5 min-h-4 text-[12px] text-mute" aria-live="polite"> {promoMsg} </p> </div> <dl className="mt-3 grid gap-2"> <div className={rowCls}> <dt className="text-mute">Subtotal</dt> <dd> <Money value={subtotal} format={money} className="text-ink" /> </dd> </div> {discount > 0 && ( <div className={rowCls} style={{ animation: `kit-co-up .35s ${CURVE}` }}> <dt className="text-mute">Discount</dt> <dd className="text-brand"> −<Money value={discount} format={money} /> </dd> </div> )} <div className={rowCls}> <dt className="text-mute">Shipping</dt> <dd className="text-ink">{ship && ship.price ? <Money value={ship.price} format={money} /> : "Free"}</dd> </div> {taxRate > 0 && ( <div className={rowCls}> <dt className="text-mute">Tax</dt> <dd> <Money value={tax} format={money} className="text-ink" /> </dd> </div> )} <div className="mt-3 flex items-baseline justify-between gap-4 pt-1"> <dt className="text-[14px] font-medium text-ink">Total</dt> <dd> <Money value={total} format={money} className="text-[20px] font-medium tracking-[-0.02em] text-ink" /> </dd> </div> </dl> </aside> </div> ); } export default Checkout;Or ask your AI agent
Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.
Add the Astabyte UI Checkout component to my project. Contact, shipping and payment on one page. It includes: card fields, shipping, promo code, rolling totals, pending, success. Install it (Radix build): ```sh pnpm dlx asta-ui@latest add checkout --radix ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/checkout.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Checkout, type CheckoutLineItem } from "@/components/astabyte/checkout"; ``` Usage example and props: https://ui.astabyte.com/checkout Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Radix primitives from the radix-ui package). - Stay on Radix: install other Astabyte UI components with `--radix` so the project uses one primitive library. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Add the Astabyte UI Checkout component to my project. Contact, shipping and payment on one page. It includes: card fields, shipping, promo code, rolling totals, pending, success. Install it (Base UI build): ```sh pnpm dlx asta-ui@latest add checkout ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/checkout.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Checkout, type CheckoutLineItem } from "@/components/astabyte/checkout"; ``` Usage example and props: https://ui.astabyte.com/checkout Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Base UI primitives from the @base-ui/react package). - Stay on Base UI: install other Astabyte UI components without `--radix` so the project uses one primitive library. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Or use plain HTML + CSS
Not on React? Use it from Django, Rails, Laravel, Go
html/template, htmx or a static page. Loadasta.cssandasta.jsonce (thehead.htmltab), then paste the markup. Theui.astabyte.com/cdnlink is temporary: pin a version from jsDelivr for production. More in HTML + CSS.<!-- Needs asta.js (card formatting, quantity, totals) and a server: /checkout recalculates the summary and takes the order. --> <div style="max-width:960px"> <form id="checkout" data-asta-checkout action="/checkout" method="post" novalidate hx-post="/checkout" hx-target="#checkout" hx-swap="outerHTML" hx-indicator="find button[type=submit]" class="asta-checkout-form"> <div class="asta-checkout-main"><div class="asta-checkout-steps"> <fieldset class="asta-checkout-section"><legend class="asta-checkout-legend"><span class="asta-checkout-num">1</span>Contact</legend><div class="asta-checkout-fields"><div class="asta-field"><div class="asta-field-head"><label class="asta-label" for="co-email">Email</label></div><label class="asta-input"><input class="asta-input-control" id="co-email" name="email" type="email" placeholder="[email protected]" autocomplete="email" inputmode="email" autocapitalize="none" spellcheck="false"></label></div></div></fieldset> <fieldset class="asta-checkout-section"><legend class="asta-checkout-legend"><span class="asta-checkout-num">2</span>Shipping</legend><div class="asta-checkout-fields"> <div class="asta-field"><div class="asta-field-head"><label class="asta-label" for="co-name">Full name</label></div><label class="asta-input"><input class="asta-input-control" id="co-name" name="name" type="text" autocomplete="name"></label></div><div class="asta-field"><div class="asta-field-head"><label class="asta-label" for="co-address">Address</label></div><label class="asta-input"><input class="asta-input-control" id="co-address" name="address" type="text" autocomplete="address-line1"></label></div> <div class="asta-checkout-pair"><div class="asta-field"><div class="asta-field-head"><label class="asta-label" for="co-city">City</label></div><label class="asta-input"><input class="asta-input-control" id="co-city" name="city" type="text" autocomplete="address-level2"></label></div><div class="asta-field"><div class="asta-field-head"><label class="asta-label" for="co-postal">Postal code</label></div><label class="asta-input"><input class="asta-input-control" id="co-postal" name="postal" type="text" autocomplete="postal-code" autocapitalize="characters"></label></div></div> <div class="asta-field"><div class="asta-field-head"><label class="asta-label" for="co-country">Country</label></div><div class="asta-select "><select class="asta-select-control" id="co-country" name="country" autocomplete="country"><option value="indonesia" selected>Indonesia</option><option value="singapore">Singapore</option><option value="australia">Australia</option><option value="united kingdom">United Kingdom</option><option value="united states">United States</option></select><svg class="asta-select-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m4 6 4 4 4-4"/></svg></div></div> <div role="radiogroup" aria-label="Shipping speed" class="asta-checkout-shipping"> <label class="asta-checkout-option"><input type="radio" name="shipping" value="standard" checked data-asta-checkout-recalc class="asta-sr-only"><span><span class="asta-checkout-option-label">Standard</span><span class="asta-checkout-option-eta">3–5 business days</span></span><span class="asta-checkout-option-price">Free</span></label> <label class="asta-checkout-option"><input type="radio" name="shipping" value="express" data-asta-checkout-recalc class="asta-sr-only"><span><span class="asta-checkout-option-label">Express</span><span class="asta-checkout-option-eta">1–2 business days</span></span><span class="asta-checkout-option-price">$14.00</span></label> </div></div></fieldset> <fieldset class="asta-checkout-section"><legend class="asta-checkout-legend"><span class="asta-checkout-num">3</span>Payment</legend><div class="asta-checkout-fields"> <div class="asta-field"><div class="asta-field-head"><label class="asta-label" for="co-card">Card number</label></div><label class="asta-input"><input class="asta-input-control" id="co-card" name="cardNumber" type="text" placeholder="1234 1234 1234 1234" inputmode="numeric" data-asta-checkout-format="card" autocomplete="cc-number"><span class="asta-input-trailing"><svg viewBox="0 0 20 14" class="asta-checkout-card-glyph" fill="none" stroke="currentColor" stroke-width="1.3" aria-hidden="true"><rect x=".75" y=".75" width="18.5" height="12.5" rx="2.2"/><path d="M.75 4.5h18.5M4 9.5h4" stroke-linecap="round"/></svg></span></label></div> <div class="asta-checkout-pair"><div class="asta-field"><div class="asta-field-head"><label class="asta-label" for="co-exp">Expiry</label></div><label class="asta-input"><input class="asta-input-control" id="co-exp" name="cardExpiry" type="text" placeholder="MM / YY" inputmode="numeric" data-asta-checkout-format="expiry" autocomplete="cc-exp"></label></div><div class="asta-field"><div class="asta-field-head"><label class="asta-label" for="co-cvc">CVC</label></div><label class="asta-input"><input class="asta-input-control" id="co-cvc" name="cardCvc" type="text" placeholder="123" inputmode="numeric" data-asta-checkout-format="cvc" autocomplete="cc-csc"></label></div></div> </div></fieldset> <div><button class="asta-btn asta-btn-accent asta-btn-lg asta-checkout-pay" type="submit"><span class="asta-btn-label"><span>Pay</span><span id="checkout-pay-total">$88.80</span></span><span class="asta-btn-spinner" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><circle cx="8" cy="8" r="6" stroke="currentColor" stroke-opacity="0.25" stroke-width="2"/><path d="M14 8a6 6 0 0 0-6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></span></button><p class="asta-checkout-note">Payments are encrypted. You won't be charged twice.</p></div> </div></div> <aside id="checkout-summary" aria-label="Order summary" data-asta-checkout-summary class="asta-checkout-summary"> <h3 class="asta-checkout-summary-title">Order</h3> <ul class="asta-checkout-items"><li class="asta-checkout-item"><span aria-hidden="true" class="asta-checkout-thumb">A</span><div class="asta-checkout-item-body"><div class="asta-checkout-item-head"><p class="asta-checkout-item-name">Astabyte tee</p><span data-asta-money="line-tee" class="asta-checkout-amount"><span>$32.00</span></span></div><p class="asta-checkout-item-variant">Oat · M</p><div class="asta-checkout-qty" role="group" aria-label="Quantity of Astabyte tee" data-asta-checkout-qty><input type="hidden" name="qty_tee" value="1"> <button type="button" class="asta-checkout-qty-btn" aria-label="Fewer" data-asta-checkout-step="-1" disabled><svg viewBox="0 0 12 12" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><path d="M2.5 6h7"/></svg></button> <span class="asta-checkout-qty-text" data-asta-checkout-qty-text>1</span> <button type="button" class="asta-checkout-qty-btn" aria-label="More" data-asta-checkout-step="1"><svg viewBox="0 0 12 12" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><path d="M2.5 6h7M6 2.5v7"/></svg></button></div></div></li><li class="asta-checkout-item"><span aria-hidden="true" class="asta-checkout-thumb">F</span><div class="asta-checkout-item-body"><div class="asta-checkout-item-head"><p class="asta-checkout-item-name">Field cap</p><span data-asta-money="line-cap" class="asta-checkout-amount"><span>$48.00</span></span></div><p class="asta-checkout-item-variant">Black</p><div class="asta-checkout-qty" role="group" aria-label="Quantity of Field cap" data-asta-checkout-qty><input type="hidden" name="qty_cap" value="2"> <button type="button" class="asta-checkout-qty-btn" aria-label="Fewer" data-asta-checkout-step="-1"><svg viewBox="0 0 12 12" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><path d="M2.5 6h7"/></svg></button> <span class="asta-checkout-qty-text" data-asta-checkout-qty-text>2</span> <button type="button" class="asta-checkout-qty-btn" aria-label="More" data-asta-checkout-step="1"><svg viewBox="0 0 12 12" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><path d="M2.5 6h7M6 2.5v7"/></svg></button></div></div></li></ul> <div class="asta-checkout-promo"><details><summary class="asta-checkout-promo-toggle">Add a promo code</summary><div class="asta-checkout-promo-row"><label class="asta-input asta-input-sm"><input class="asta-input-control" name="promo" placeholder="Enter code…" aria-label="Promo code" data-asta-checkout-promo autocomplete="off" autocapitalize="characters" spellcheck="false"></label><button type="button" class="asta-btn asta-btn-outline asta-btn-sm" data-asta-checkout-apply><span class="asta-btn-label">Apply</span><span class="asta-btn-spinner" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><circle cx="8" cy="8" r="6" stroke="currentColor" stroke-opacity="0.25" stroke-width="2"/><path d="M14 8a6 6 0 0 0-6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></span></button></div></details><p class="asta-checkout-promo-msg" aria-live="polite"></p></div> <dl class="asta-checkout-totals"> <div><dt>Subtotal</dt><dd><span data-asta-money="subtotal" class="asta-checkout-amount"><span>$80.00</span></span></dd></div> <div class="asta-checkout-discount"><dt>Discount</dt><dd><span data-asta-money="discount" class="asta-checkout-amount"><span>−$8.00</span></span></dd></div> <div><dt>Shipping</dt><dd>Free</dd></div> <div><dt>Tax</dt><dd><span data-asta-money="tax" class="asta-checkout-amount"><span>$8.80</span></span></dd></div> <div class="asta-checkout-total"><dt>Total</dt><dd><span data-asta-money="total" class="asta-checkout-amount"><span>$88.80</span></span></dd></div> </dl></aside> </form> </div>
Usage
The demo above, as code.
"use client";
import { Checkout, type CheckoutLineItem } from "@/components/astabyte/checkout";
const ITEMS: CheckoutLineItem[] = [
{ id: "i1", name: "Linen overshirt", variant: "Oat · M", price: 68, qty: 1 },
{ id: "i2", name: "Everyday tote", variant: "Charcoal", price: 34, qty: 1 },
{ id: "i3", name: "Wool socks", variant: "Pack of 3", price: 18, qty: 2 },
];
/** Fake payment: waits a moment, declines any card ending in 0000. */
const pay = ({ details }: { details: { cardNumber: string } }) =>
new Promise<void>((resolve, reject) =>
setTimeout(() => (details.cardNumber.endsWith("0000") ? reject(new Error("Your card was declined. Try another card.")) : resolve()), 1400),
);
export default function CheckoutDemo() {
return (
<div className="flex min-h-[420px] w-full flex-col items-center justify-center gap-4 p-4 sm:p-8">
<div className="w-full max-w-[860px]">
<Checkout
items={ITEMS}
taxRate={0.08}
promoCodes={{ WELCOME10: 0.1 }}
defaultDetails={{ email: "[email protected]", name: "Rani Pratama", address: "Jl. Kenanga 12", city: "Bandung", postal: "40115" }}
onPay={pay}
/>
</div>
<p className="text-center text-[12.5px] text-mute">Any 16 digits and a future date work. End the card with 0000 to see a decline. Try the code WELCOME10.</p>
</div>
);
}