All blocks
Cardioid capsule · Brushed aluminum · $148.00 each
Low-profile clamp · Matte graphite · $92.00 each
High-density isolation · Pair (5° tilt) · $54.00 each
Checkout Wizard
Four-step two-column checkout flow with live cart quantities and promo codes, country-aware shipping validation, delivery method selection, payment review, sticky order summary, and local order confirmation.
Built withAlertBadgeButtonCardCheckboxCollapsibleFieldGridHeadingIconIcon ButtonInputNumber InputRadio CardSelectSeparatorStackStepsTextTextareaToastTooltip
Checkout
Secure checkoutReview your cart
Adjust quantities or apply a studio promo code before entering shipping details.

FieldMic Condenser USB-C
$148.00
Anodized Desk Arm
$92.00
Acoustic Monitor PadsLimited run
$108.00Try STUDIO10 (10% off) or DESK20 (20% off).
Install
1npx stylexblocks add checkout-wizardSource
components/blocks/ui-sdk/checkout-wizard.tsx
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909import * as stylex from "@stylexjs/stylex";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { Alert } from "#components/ui/ui-sdk/alert.tsx";import { Badge } from "#components/ui/ui-sdk/badge.tsx";import { Button } from "#components/ui/ui-sdk/button.tsx";import { Card } from "#components/ui/ui-sdk/card.tsx";import { Checkbox } from "#components/ui/ui-sdk/checkbox.tsx";import { Collapsible } from "#components/ui/ui-sdk/collapsible.tsx";import { Field } from "#components/ui/ui-sdk/field.tsx";import { Grid } from "#components/ui/ui-sdk/grid.tsx";import { Heading } from "#components/ui/ui-sdk/heading.tsx";import { Icon } from "#components/ui/ui-sdk/icon.tsx";import { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";import { Input } from "#components/ui/ui-sdk/input.tsx";import { NumberInput } from "#components/ui/ui-sdk/number-input.tsx";import { RadioCard } from "#components/ui/ui-sdk/radio-card.tsx";import { Select } from "#components/ui/ui-sdk/select.tsx";import { Separator } from "#components/ui/ui-sdk/separator.tsx";import { HStack, Stack, VStack } from "#components/ui/ui-sdk/stack.tsx";import { Steps } from "#components/ui/ui-sdk/steps.tsx";import { Text } from "#components/ui/ui-sdk/text.tsx";import { Textarea } from "#components/ui/ui-sdk/textarea.tsx";import { Toast, Toaster } from "#components/ui/ui-sdk/toast.tsx";import { Tooltip } from "#components/ui/ui-sdk/tooltip.tsx";import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";import { accentPalette, bluePalette, greenPalette, redPalette,} from "@stylexblocks/ui/themes/palettes.ts";import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";import type { StyleOverrideProps } from "#lib/recipe-props.ts";
// ── Inline SVG icons (zero external icon packages) ───────────────────────────
function CartIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <circle cx="8" cy="16.25" r="1.25" /> <circle cx="15" cy="16.25" r="1.25" /> <path d="M2.5 3.5h2.2l1.6 8.2a1 1 0 0 0 1 .8h7.9a1 1 0 0 0 .97-.76l1.33-5.24H5.4" /> </Icon> );}
function LocationIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <path d="M10 17.2s5.25-4.35 5.25-8.45a5.25 5.25 0 1 0-10.5 0C4.75 12.85 10 17.2 10 17.2Z" /> <circle cx="10" cy="8.75" r="1.85" /> </Icon> );}
function TruckIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <path d="M2.5 5.25h9.25v8.5H2.5z" /> <path d="M11.75 8h3.3l2.2 2.45v3.3h-5.5V8Z" /> <circle cx="5.75" cy="14.5" r="1.5" /> <circle cx="14.75" cy="14.5" r="1.5" /> </Icon> );}
function CreditCardIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <rect x="2.25" y="4.5" width="15.5" height="11" rx="2" /> <path d="M2.25 8.25h15.5" /> <path d="M5.5 12.25h3.5" /> </Icon> );}
function LockIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <rect x="4" y="9" width="12" height="8" rx="1.75" /> <path d="M6.75 9V6.5a3.25 3.25 0 0 1 6.5 0V9" /> </Icon> );}
function AlertCircleIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <circle cx="10" cy="10" r="7.25" /> <path d="M10 6.75v3.75" /> <path d="M10 13.5v.1" /> </Icon> );}
function CheckCircleIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <circle cx="10" cy="10" r="7.25" /> <path d="m7 10.2 2 2 4-4.4" /> </Icon> );}
function InfoCircleIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <circle cx="10" cy="10" r="7.25" /> <path d="M10 9.25v4" /> <path d="M10 6.5v.1" /> </Icon> );}
function ChevronDownIcon({ rotated }: { rotated?: boolean }) { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={rotated ? styles.chevronOpen : styles.chevronClosed} > <path d="m5.5 7.75 4.5 4.5 4.5-4.5" /> </Icon> );}
// ── Data & validation rules ───────────────────────────────────────────────────
export interface CheckoutItem { id: string; name: string; variant: string; price: number; qty: number; thumbnailSrc: string; isLimited?: boolean;}
export interface CheckoutOrderSummary { orderNumber: string; items: CheckoutItem[]; subtotal: number; discount: number; shipping: number; tax: number; total: number; email: string; deliveryMethod: string;}
const DEFAULT_CART_ITEMS: CheckoutItem[] = [ { id: "fieldmic", name: "FieldMic Condenser USB-C", variant: "Cardioid capsule · Brushed aluminum", price: 148, qty: 1, thumbnailSrc: "/images/blocks/checkout-wizard/fieldmic.webp", isLimited: false, }, { id: "desk-arm", name: "Anodized Desk Arm", variant: "Low-profile clamp · Matte graphite", price: 92, qty: 1, thumbnailSrc: "/images/blocks/checkout-wizard/desk-arm.webp", isLimited: false, }, { id: "monitor-pads", name: "Acoustic Monitor Pads", variant: "High-density isolation · Pair (5° tilt)", price: 54, qty: 2, thumbnailSrc: "/images/blocks/checkout-wizard/monitor-pads.webp", isLimited: true, },];
const STEPS = [ { label: "Cart", icon: CartIcon }, { label: "Shipping", icon: LocationIcon }, { label: "Delivery", icon: TruckIcon }, { label: "Payment", icon: CreditCardIcon },] as const;
const COUNTRIES = [ { value: "us", label: "United States" }, { value: "ca", label: "Canada" }, { value: "uk", label: "United Kingdom" },];
const US_STATES = [ "California", "Colorado", "Illinois", "Massachusetts", "New York", "Oregon", "Texas", "Washington",];
const US_STATE_ITEMS = US_STATES.map((st) => ({ value: st, label: st }));
const DELIVERY_OPTIONS = [ { value: "standard", label: "Standard ground", window: "3–7 business days", price: 6.95, }, { value: "expedited", label: "Expedited air", window: "1–2 business days", price: 14.95, }, { value: "overnight", label: "Overnight priority", window: "Next business day by 5pm (US only)", price: 28.95, },] as const;
const PROMOS: Record<string, { label: string; rate: number }> = { STUDIO10: { label: "STUDIO10 · 10% off", rate: 0.1 }, DESK20: { label: "DESK20 · 20% off", rate: 0.2 },};
const TAX_RATE = 0.08;const FREE_SHIPPING_THRESHOLD = 380;const NARROW_HOST_WIDTH = 860;const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const POSTAL_CODE_RULES: Record< string, { label: string; placeholder: string; pattern: RegExp; error: string }> = { us: { label: "ZIP code", placeholder: "94110", pattern: /^\d{5}(?:-\d{4})?$/, error: "Enter a 5-digit ZIP code, with an optional 4-digit suffix.", }, ca: { label: "Postal code", placeholder: "V6B 1A1", pattern: /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i, error: "Enter a Canadian postal code, for example V6B 1A1.", }, uk: { label: "Postcode", placeholder: "EC1V 9BP", pattern: /^(?:GIR\s?0AA|[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2})$/i, error: "Enter a UK postcode, for example EC1V 9BP.", },};
const money = (amount: number) => `$${amount.toFixed(2)}`;
const blockedMessage = (count: number) => count === 1 ? "One problem above needs fixing first." : `${count} problems above need fixing first.`;
// ── Styles ────────────────────────────────────────────────────────────────────
const styles = stylex.create({ root: { backgroundColor: semanticColors.bg, color: semanticColors.fg, fontFamily: fonts.body, minHeight: "100%", paddingBlock: spacing._6, paddingInline: spacing._6, width: "100%", }, container: { marginInline: "auto", maxWidth: "62.5rem", width: "100%", }, headingReset: { marginBlock: 0, }, mutedColor: { color: semanticColors.fgMuted, }, fullWidth: { width: "100%", }, flexGrow: { flexGrow: 1, }, noShrink: { flexShrink: 0, }, nowrap: { whiteSpace: "nowrap", }, formColumn: { flexBasis: 0, flexGrow: 1, flexShrink: 1, width: "100%", }, summaryColumnSticky: { alignSelf: "flex-start", flexShrink: 0, maxWidth: "100%", position: "sticky", top: spacing._6, width: "22.5rem", }, summaryCardBody: { gap: spacing._4, }, summaryTrigger: { alignItems: "center", appearance: "none", backgroundColor: "transparent", borderWidth: 0, color: semanticColors.fg, cursor: "pointer", display: "flex", fontFamily: "inherit", gap: spacing._2, justifyContent: "space-between", paddingBlock: 0, paddingInline: 0, textAlign: "start", width: "100%", }, summaryPanelBody: { paddingTop: spacing._4, }, topPadding1: { paddingTop: spacing._1, }, stepItemLast: { flexBasis: "auto", flexGrow: 0, flexShrink: 0, }, stepIndicatorError: { backgroundColor: semanticColors.bgError, borderColor: semanticColors.borderError, borderStyle: "solid", borderWidth: "2px", color: semanticColors.fgError, }, stepTitleHidden: { display: "none", }, stepSection: { outline: "none", }, thumbnail: { backgroundColor: semanticColors.bgMuted, borderColor: semanticColors.border, borderRadius: semanticRadii.panelSm, borderStyle: "solid", borderWidth: "1px", display: "block", flexShrink: 0, height: "4rem", objectFit: "cover", width: "4rem", }, thumbnailSm: { backgroundColor: semanticColors.bgMuted, borderColor: semanticColors.border, borderRadius: semanticRadii.panelSm, borderStyle: "solid", borderWidth: "1px", display: "block", flexShrink: 0, height: "3rem", objectFit: "cover", width: "3rem", }, qtyInputRoot: { width: "5.75rem", }, emptyCartBox: { backgroundColor: semanticColors.bgMuted, borderColor: semanticColors.border, borderRadius: semanticRadii.panel, borderStyle: "dashed", borderWidth: "1px", paddingBlock: spacing._5, paddingInline: spacing._5, }, promoInputWrap: { flexBasis: 0, flexGrow: 1, minWidth: 0, }, successColor: { color: semanticColors.fgSuccess, }, warningColor: { color: semanticColors.fgWarning, }, errorColor: { color: semanticColors.fgError, }, radioListStack: { display: "flex", flexDirection: "column", gap: spacing._2_5, width: "100%", }, radioItemControl: { alignItems: "center", justifyContent: "space-between", width: "100%", }, inputWithLeadingIcon: { position: "relative", width: "100%", }, leadingIconSlot: { alignItems: "center", color: semanticColors.fgMuted, display: "inline-flex", insetBlock: 0, insetInlineStart: spacing._3, pointerEvents: "none", position: "absolute", zIndex: 1, }, cardNumberInput: { paddingInlineStart: spacing._9, }, shortField: { width: "8.75rem", }, helpTrigger: { color: semanticColors.fgMuted, height: "1.125rem", minWidth: "1.125rem", width: "1.125rem", }, reviewBox: { backgroundColor: semanticColors.bgPanel, borderColor: semanticColors.border, borderRadius: semanticRadii.panel, borderStyle: "solid", borderWidth: "1px", paddingBlock: spacing._3_5, paddingInline: spacing._4, }, continueButton: { flexBasis: 0, flexGrow: 1, width: "100%", }, confirmationDetails: { backgroundColor: semanticColors.bgPanel, borderColor: semanticColors.border, borderRadius: semanticRadii.panel, borderStyle: "solid", borderWidth: "1px", paddingBlock: spacing._4, paddingInline: spacing._4, }, chevronClosed: { transform: "rotate(0deg)", transitionDuration: "160ms", transitionProperty: "transform", }, chevronOpen: { transform: "rotate(180deg)", transitionDuration: "160ms", transitionProperty: "transform", },});
export interface CheckoutWizardProps extends StyleOverrideProps { /** Initial cart line items. Defaults to the modular studio hardware demo order. */ items?: CheckoutItem[]; /** Zero-based starting step index (0 = Cart, 1 = Shipping, 2 = Delivery, 3 = Payment). */ initialStep?: number; /** Called when the final payment step passes validation and completes locally. */ onOrderComplete?: (order: CheckoutOrderSummary) => void;}
/** * CheckoutWizard — stepped two-column checkout flow with a sticky derived * order summary, per-step validation with focus forwarding, responsive narrow * host collapsible summary, and local order confirmation state. */export function CheckoutWizard({ items: initialItems = DEFAULT_CART_ITEMS, initialStep = 0, onOrderComplete, palette, style,}: CheckoutWizardProps) { const queue = useMemo(() => Toast.createToaster(), []);
// Measure the host container directly rather than the viewport so embedded // previews switch cleanly to the stacked narrow layout. const hostRef = useRef<HTMLElement | null>(null); const [isNarrow, setIsNarrow] = useState(false);
const attachHost = useCallback((element: HTMLElement | null) => { hostRef.current = element; if (element && element.clientWidth > 0) { setIsNarrow(element.clientWidth <= NARROW_HOST_WIDTH); } }, []);
useEffect(() => { const host = hostRef.current; if (!host || typeof ResizeObserver === "undefined") { return; }
const observer = new ResizeObserver((entries) => { const width = entries[0]?.contentRect.width ?? host.clientWidth; if (width > 0) { setIsNarrow(width <= NARROW_HOST_WIDTH); } }); observer.observe(host); return () => observer.disconnect(); }, []);
const [step, setStep] = useState(() => Math.min(Math.max(initialStep, 0), STEPS.length - 1), ); const [attempted, setAttempted] = useState<ReadonlySet<number>>(() => new Set()); const [isComplete, setIsComplete] = useState(false); const [summaryOpen, setSummaryOpen] = useState(false); const [orderNumber, setOrderNumber] = useState("SB-4821");
const [quantities, setQuantities] = useState<Record<string, number>>(() => Object.fromEntries(initialItems.map((item) => [item.id, item.qty])), ); const [promoInput, setPromoInput] = useState(""); const [promoWasChecked, setPromoWasChecked] = useState(false); const [appliedPromo, setAppliedPromo] = useState<string | null>(null);
const [email, setEmail] = useState(""); const [firstName, setFirstName] = useState(""); const [lastName, setLastName] = useState(""); const [address, setAddress] = useState(""); const [apartment, setApartment] = useState(""); const [city, setCity] = useState(""); const [state, setState] = useState(""); const [postalCode, setPostalCode] = useState(""); const [country, setCountry] = useState("us");
const [delivery, setDelivery] = useState("standard"); const [deliveryNote, setDeliveryNote] = useState(""); const [isGift, setIsGift] = useState(false);
const [cardNumber, setCardNumber] = useState(""); const [cardName, setCardName] = useState(""); const [expiry, setExpiry] = useState(""); const [cvc, setCvc] = useState(""); const [billingMatches, setBillingMatches] = useState(true);
// ── Derived summary figures ─────────────────────────────────────────────────
const items = useMemo( () => initialItems .map((item) => ({ ...item, qty: quantities[item.id] ?? item.qty, })) .filter((item) => item.qty > 0), [initialItems, quantities], );
const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0); const promo = appliedPromo ? PROMOS[appliedPromo] : undefined; const discount = promo ? subtotal * promo.rate : 0; const deliveryOption = DELIVERY_OPTIONS.find((option) => option.value === delivery) ?? DELIVERY_OPTIONS[0]; const shipping = items.length === 0 ? 0 : subtotal - discount >= FREE_SHIPPING_THRESHOLD && delivery === "standard" ? 0 : deliveryOption.price; const tax = (subtotal - discount) * TAX_RATE; const total = subtotal - discount + shipping + tax; const itemCount = items.reduce((sum, item) => sum + item.qty, 0);
const postalRule = POSTAL_CODE_RULES[country] ?? POSTAL_CODE_RULES.us; const countryLabel = COUNTRIES.find((entry) => entry.value === country)?.label ?? "United States";
// ── Per-step validation ─────────────────────────────────────────────────────
const errorsByStep = useMemo<Array<Record<string, string>>>(() => { const cartErrors: Record<string, string> = {}; if (items.length === 0) { cartErrors.items = "Your cart is empty. Restore items to continue."; }
const shippingErrors: Record<string, string> = {}; if (!EMAIL_PATTERN.test(email.trim())) { shippingErrors.email = "Enter an email address for order updates."; } if (!firstName.trim()) { shippingErrors.firstName = "Required"; } if (!lastName.trim()) { shippingErrors.lastName = "Required"; } if (!address.trim()) { shippingErrors.address = "Required"; } if (!city.trim()) { shippingErrors.city = "Required"; } if (country === "us" && !state) { shippingErrors.state = "Required"; } if (!postalRule.pattern.test(postalCode.trim())) { shippingErrors.postalCode = postalRule.error; }
const deliveryErrors: Record<string, string> = {}; if (delivery === "overnight" && country !== "us") { deliveryErrors.delivery = "Overnight delivery is only available in the United States."; }
const paymentErrors: Record<string, string> = {}; if (cardNumber.replace(/[\s-]/g, "").length < 15) { paymentErrors.cardNumber = "Enter the full card number."; } if (!cardName.trim()) { paymentErrors.cardName = "Enter the name printed on the card."; } if (!/^(0[1-9]|1[0-2])\s?\/\s?\d{2}$/.test(expiry.trim())) { paymentErrors.expiry = "Use MM/YY."; } if (!/^\d{3,4}$/.test(cvc.trim())) { paymentErrors.cvc = "3 or 4 digits."; }
return [cartErrors, shippingErrors, deliveryErrors, paymentErrors]; }, [ items.length, email, firstName, lastName, address, city, state, postalCode, country, postalRule, delivery, cardNumber, cardName, expiry, cvc, ]);
const shownErrors = (index: number) => attempted.has(index) ? errorsByStep[index] : {}; const currentErrors = shownErrors(step); const currentErrorCount = Object.keys(currentErrors).length; const isLastStep = step === STEPS.length - 1;
// Forward focus to the first invalid control after a blocked step advance. const stepContentRef = useRef<HTMLDivElement | null>(null); const pendingFocusStepRef = useRef<number | null>(null);
useEffect(() => { if (pendingFocusStepRef.current !== step) { return; } pendingFocusStepRef.current = null;
const root = stepContentRef.current; if (!root) { return; } const invalid = root.matches('[aria-invalid="true"], [data-invalid]') ? root : root.querySelector<HTMLElement>('[aria-invalid="true"], [data-invalid]'); const focusableSelector = 'input:not(:disabled), button:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])'; const focusTarget = invalid?.matches(focusableSelector) ? invalid : invalid?.querySelector<HTMLElement>(focusableSelector); focusTarget?.focus(); }, [attempted, step]);
const markAttempted = useCallback((indices: ReadonlyArray<number>) => { setAttempted((previous) => { const next = new Set(previous); for (const index of indices) { next.add(index); } return next; }); }, []);
const goNext = () => { markAttempted([step]); if (Object.keys(errorsByStep[step]).length > 0) { pendingFocusStepRef.current = step; return; } if (isLastStep) { const nextOrderNumber = `SB-${4800 + ((itemCount * 37 + Math.round(total)) % 900)}`; setOrderNumber(nextOrderNumber); setIsComplete(true); onOrderComplete?.({ orderNumber: nextOrderNumber, items, subtotal, discount, shipping, tax, total, email: email.trim(), deliveryMethod: deliveryOption.label, }); queue.success("Order confirmed", { description: `Reference ${nextOrderNumber} recorded locally for ${money(total)}.`, }); return; } setStep((current) => current + 1); };
const goTo = (index: number) => { if (index <= step) { setStep(index); return; }
const checked: number[] = []; let firstInvalid: number | null = null; for (let candidate = step; candidate < index; candidate += 1) { checked.push(candidate); if (Object.keys(errorsByStep[candidate]).length > 0) { firstInvalid = candidate; break; } } markAttempted(checked);
if (firstInvalid != null) { pendingFocusStepRef.current = firstInvalid; setStep(firstInvalid); return; } setStep(index); };
const handlePromoInputChange = (value: string) => { setPromoInput(value); setPromoWasChecked(false); setAppliedPromo(null); };
const applyPromo = () => { const code = promoInput.trim().toUpperCase(); setPromoWasChecked(code.length > 0); if (PROMOS[code]) { setAppliedPromo(code); queue.success("Promo code applied", { description: PROMOS[code].label, }); } else { setAppliedPromo(null); } };
const restoreDefaultItems = () => { setQuantities(Object.fromEntries(initialItems.map((item) => [item.id, item.qty]))); };
const resetCheckout = () => { setIsComplete(false); setStep(0); setAttempted(new Set()); restoreDefaultItems(); setPromoInput(""); setPromoWasChecked(false); setAppliedPromo(null); setCardNumber(""); setCardName(""); setExpiry(""); setCvc(""); setBillingMatches(true); };
// ── Shared Order Summary ────────────────────────────────────────────────────
const formattedAddress = [ address.trim(), apartment.trim(), [city.trim(), country === "us" ? state : "", postalCode.trim()] .filter(Boolean) .join(", "), countryLabel, ] .filter(Boolean) .join(" · ");
const freeShippingRemaining = Math.max( 0, FREE_SHIPPING_THRESHOLD - (subtotal - discount), );
const totalsRows = ( <VStack gap="2"> <HStack justify="between" gap="2"> <Text render={<span />} size="sm" tone="muted"> Subtotal </Text> <Text render={<span />} size="sm" tabular="true"> {money(subtotal)} </Text> </HStack> {promo ? ( <HStack justify="between" gap="2"> <Text render={<span />} size="sm" tone="muted"> {promo.label} </Text> <Text render={<span />} size="sm" tone="success" weight="medium" tabular="true"> −{money(discount)} </Text> </HStack> ) : null} <HStack justify="between" gap="2"> <Text render={<span />} size="sm" tone="muted"> {deliveryOption.label} </Text> <Text render={<span />} size="sm" tabular="true"> {shipping === 0 ? "Free" : money(shipping)} </Text> </HStack> <HStack justify="between" gap="2"> <Text render={<span />} size="sm" tone="muted"> Estimated tax </Text> <Text render={<span />} size="sm" tabular="true"> {money(tax)} </Text> </HStack> <Separator /> <HStack justify="between" gap="2" style={styles.topPadding1}> <Text render={<span />} size="lg" weight="semibold"> Total </Text> <Text render={<span />} size="lg" weight="semibold" tabular="true"> {money(total)} </Text> </HStack> </VStack> );
const summaryBody = ( <VStack gap="4"> {items.length > 0 ? ( <VStack gap="3"> {items.map((item) => ( <HStack key={item.id} align="start" gap="3"> <img src={item.thumbnailSrc} alt={item.name} {...stylex.props(styles.thumbnailSm)} /> <VStack gap="0.5" style={styles.flexGrow}> <HStack align="start" justify="between" gap="2"> <Text render={<span />} size="sm" weight="medium"> {item.name} </Text> <Text render={<span />} size="sm" weight="semibold" tabular="true" style={styles.nowrap} > {money(item.price * item.qty)} </Text> </HStack> <Text render={<span />} variant="caption"> {item.variant} · Qty {item.qty} </Text> </VStack> </HStack> ))} </VStack> ) : ( <Text variant="muted" size="sm"> No hardware selected yet. </Text> )} <Separator /> {totalsRows} {items.length > 0 && freeShippingRemaining > 0 ? ( <Alert.Root status="info" variant="subtle" size="sm" palette={bluePalette}> <Alert.Indicator> <TruckIcon /> </Alert.Indicator> <Alert.Content> <Alert.Title> {money(freeShippingRemaining)} away from free standard shipping </Alert.Title> </Alert.Content> </Alert.Root> ) : null} </VStack> );
const summaryCard = ( <Card.Root variant="outline" size="lg"> <Card.Body style={styles.summaryCardBody}> {isNarrow ? ( <Collapsible.Root open={summaryOpen} onOpenChange={setSummaryOpen}> <Collapsible.Trigger render={<button type="button" {...stylex.props(styles.summaryTrigger)} />} > <Text render={<span />} size="md" weight="medium"> Order summary </Text> <HStack render={<span />} gap="2"> <Text render={<span />} size="md" weight="medium" tabular="true"> {money(total)} </Text> <ChevronDownIcon rotated={summaryOpen} /> </HStack> </Collapsible.Trigger> <Collapsible.Panel> <div {...stylex.props(styles.summaryPanelBody)}>{summaryBody}</div> </Collapsible.Panel> </Collapsible.Root> ) : ( <> <HStack justify="between" gap="2"> <Text render={<h2 />} size="md" weight="semibold"> Order summary </Text> <Badge variant="subtle" size="sm"> {itemCount} {itemCount === 1 ? "item" : "items"} </Badge> </HStack> {summaryBody} </> )} </Card.Body> </Card.Root> );
// ── Progress stepper ────────────────────────────────────────────────────────
const progress = ( <Steps.Root count={STEPS.length} step={step} onStepChange={({ step: next }) => goTo(next)} size="sm" orientation="horizontal" palette={accentPalette} aria-label="Checkout progress" > <Steps.List> {STEPS.map(({ label, icon: StepIcon }, index) => { const hasError = Object.keys(shownErrors(index)).length > 0; const isLast = index === STEPS.length - 1; return ( <Steps.Item key={label} index={index} style={isLast ? styles.stepItemLast : undefined} > <Steps.Trigger aria-label={label}> <Steps.Indicator palette={hasError ? redPalette : undefined} style={hasError ? styles.stepIndicatorError : undefined} > {hasError ? <AlertCircleIcon /> : <StepIcon />} </Steps.Indicator> <Steps.Title style={isNarrow && index !== step ? styles.stepTitleHidden : undefined} > {label} </Steps.Title> </Steps.Trigger> <Steps.Separator /> </Steps.Item> ); })} </Steps.List> </Steps.Root> );
// ── Step actions ────────────────────────────────────────────────────────────
const actions = ( <VStack gap="3" style={styles.topPadding1}> {currentErrorCount > 0 ? ( <HStack role="status" aria-live="polite" gap="1.5" style={styles.errorColor}> <AlertCircleIcon /> <Text render={<span />} size="xs" weight="medium" tone="error"> {blockedMessage(currentErrorCount)} </Text> </HStack> ) : null} <HStack gap="3" style={styles.fullWidth}> <Button variant="surface" onClick={() => { if (step === 0) { queue.info("Returning to hardware catalog", { description: "Your studio cart stays saved while you browse.", }); return; } setStep((current) => Math.max(0, current - 1)); }} > {step === 0 ? "Continue shopping" : "Back"} </Button> <Button variant="solid" palette={accentPalette} style={styles.continueButton} onClick={goNext} > {isLastStep ? `Pay ${money(total)}` : "Continue"} </Button> </HStack> </VStack> );
// ── Render ──────────────────────────────────────────────────────────────────
return ( <VStack gap="0" palette={palette} style={[styles.root, style]}> <VStack render={<main ref={attachHost} />} gap="6" style={styles.container}> <HStack render={<header />} wrap="wrap" justify="between" gap="3"> <Heading render={<h1 />} size="2xl" style={styles.headingReset}> Checkout </Heading> <HStack render={<span />} gap="1.5" style={styles.mutedColor}> <LockIcon /> <Text render={<span />} variant="caption"> Secure checkout </Text> </HStack> </HStack>
<Stack direction={isNarrow ? "column" : "row"} align={isNarrow ? "stretch" : "start"} gap={isNarrow ? "6" : "8"} style={styles.fullWidth} > {isNarrow ? <div {...stylex.props(styles.fullWidth)}>{summaryCard}</div> : null}
<VStack gap="6" style={isNarrow ? styles.fullWidth : styles.formColumn}> {isComplete ? ( <VStack render={<section aria-label="Order confirmation" />} gap="5"> <Alert.Root status="success" variant="subtle" size="md" palette={greenPalette} > <Alert.Indicator> <CheckCircleIcon /> </Alert.Indicator> <Alert.Content> <Alert.Title>Order {orderNumber} confirmed</Alert.Title> <Alert.Description> This local example completed an order for {money(total)}. No payment was sent. </Alert.Description> </Alert.Content> </Alert.Root>
<VStack gap="1"> <Heading render={<h2 />} size="xl" style={styles.headingReset}> Thanks for your order </Heading> <Text variant="muted" size="sm"> The confirmation is stored in local component state so you can inspect the complete checkout outcome or start again. </Text> </VStack>
<VStack gap="3" style={styles.confirmationDetails}> <VStack gap="0.5"> <Text render={<span />} variant="caption"> Confirmation sent to </Text> <Text render={<span />} size="sm"> {email.trim() || "studio@example.com"} </Text> </VStack> <Separator /> <VStack gap="0.5"> <Text render={<span />} variant="caption"> Shipping destination </Text> <Text render={<span />} size="sm"> {`${firstName.trim()} ${lastName.trim()}`.trim()} {formattedAddress ? ` · ${formattedAddress}` : ""} </Text> </VStack> <Separator /> <VStack gap="0.5"> <Text render={<span />} variant="caption"> Delivery speed </Text> <Text render={<span />} size="sm"> {deliveryOption.label} ({deliveryOption.window}) </Text> </VStack> </VStack>
<div> <Button variant="surface" onClick={resetCheckout}> Start a new order </Button> </div> </VStack> ) : ( progress )}
{/* Step 0: Cart */} {!isComplete && step === 0 ? ( <VStack ref={stepContentRef} gap="5" aria-invalid={currentErrors.items ? true : undefined} tabIndex={-1} style={styles.stepSection} > <VStack gap="1"> <Heading render={<h2 />} size="xl" style={styles.headingReset}> Review your cart </Heading> <Text variant="muted" size="sm"> Adjust quantities or apply a studio promo code before entering shipping details. </Text> </VStack>
{items.length > 0 ? ( <VStack gap="4"> {items.map((item) => ( <VStack key={item.id} gap="4"> <HStack align="start" gap="4"> <img src={item.thumbnailSrc} alt={item.name} {...stylex.props(styles.thumbnail)} /> <VStack gap="1.5" style={styles.flexGrow}> <HStack align="start" justify="between" gap="2"> <HStack wrap="wrap" gap="2"> <Text render={<span />} size="sm" weight="medium"> {item.name} </Text> {item.isLimited ? ( <Badge variant="subtle" size="sm" palette={greenPalette} > Limited run </Badge> ) : null} </HStack> <Text render={<span />} size="sm" weight="semibold" tabular="true" style={styles.nowrap} > {money(item.price * item.qty)} </Text> </HStack> <Text render={<span />} variant="caption"> {item.variant} · {money(item.price)} each </Text> <HStack gap="2" style={styles.topPadding1}> <NumberInput.Root value={item.qty} onValueChange={(nextValue) => setQuantities((prev) => ({ ...prev, [item.id]: nextValue ?? 0, })) } min={0} max={10} step={1} palette={accentPalette} style={styles.qtyInputRoot} > <NumberInput.Group> <NumberInput.Input aria-label={`Quantity of ${item.name}`} /> <NumberInput.Control /> </NumberInput.Group> </NumberInput.Root> <Button variant="ghost" onClick={() => setQuantities((prev) => ({ ...prev, [item.id]: 0, })) } > Remove </Button> </HStack> </VStack> </HStack> <Separator /> </VStack> ))} </VStack> ) : ( <VStack align="start" gap="3" style={styles.emptyCartBox}> <Text variant="muted" size="sm"> {currentErrors.items ?? "Your cart has no hardware items right now."} </Text> <Button variant="surface" onClick={restoreDefaultItems}> Restore sample items </Button> </VStack> )}
<Field.Root> <Field.Label> Promo code <Text render={<span />} size="xs" tone="subtle" weight="normal"> Optional </Text> </Field.Label> <HStack gap="2" style={styles.fullWidth}> <div {...stylex.props(styles.promoInputWrap)}> <Input value={promoInput} onValueChange={handlePromoInputChange} placeholder="STUDIO10" onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); applyPromo(); } }} /> </div> <Button variant="surface" onClick={applyPromo}> Apply </Button> </HStack> {appliedPromo && promo ? ( <HStack render={<span />} gap="1.5" style={styles.successColor}> <CheckCircleIcon /> <Text render={<span />} size="xs" weight="medium" tone="success"> {promo.label} applied. </Text> </HStack> ) : promoInput.trim() && promoWasChecked ? ( <HStack render={<span />} gap="1.5" style={styles.warningColor}> <AlertCircleIcon /> <Text render={<span />} size="xs" weight="medium" tone="warning"> That promo code is not valid. Try STUDIO10 or DESK20. </Text> </HStack> ) : promoInput.trim() ? ( <HStack render={<span />} gap="1.5" style={styles.warningColor}> <InfoCircleIcon /> <Text render={<span />} size="xs" weight="medium" tone="warning"> Press Apply to check this code. </Text> </HStack> ) : ( <Field.Description> Try STUDIO10 (10% off) or DESK20 (20% off). </Field.Description> )} </Field.Root> </VStack> ) : null}
{/* Step 1: Shipping */} {!isComplete && step === 1 ? ( <VStack ref={stepContentRef} gap="5" style={styles.stepSection}> <VStack gap="1"> <Heading render={<h2 />} size="xl" style={styles.headingReset}> Where should it go? </Heading> <Text variant="muted" size="sm"> Delivery options and tax are calculated from this address. </Text> </VStack>
<VStack gap="4"> <Field.Root required invalid={Boolean(currentErrors.email)}> <Field.Label> Email <Field.RequiredIndicator /> </Field.Label> <Input type="email" autoComplete="email" value={email} onValueChange={setEmail} placeholder="studio@example.com" aria-invalid={currentErrors.email ? true : undefined} /> <Field.Description> Order confirmation and tracking go here. </Field.Description> {currentErrors.email ? ( <Field.Error match={true}>{currentErrors.email}</Field.Error> ) : null} </Field.Root>
<Grid columns={isNarrow ? "1" : "2"} gap="4" style={styles.fullWidth}> <Field.Root required invalid={Boolean(currentErrors.firstName)}> <Field.Label> First name <Field.RequiredIndicator /> </Field.Label> <Input autoComplete="given-name" value={firstName} onValueChange={setFirstName} aria-invalid={currentErrors.firstName ? true : undefined} /> {currentErrors.firstName ? ( <Field.Error match={true}>{currentErrors.firstName}</Field.Error> ) : null} </Field.Root>
<Field.Root required invalid={Boolean(currentErrors.lastName)}> <Field.Label> Last name <Field.RequiredIndicator /> </Field.Label> <Input autoComplete="family-name" value={lastName} onValueChange={setLastName} aria-invalid={currentErrors.lastName ? true : undefined} /> {currentErrors.lastName ? ( <Field.Error match={true}>{currentErrors.lastName}</Field.Error> ) : null} </Field.Root> </Grid>
<Select.Root items={COUNTRIES} value={country} onValueChange={(nextCountry) => { if (nextCountry) { setCountry(nextCountry); } }} placeholder="Select country" palette={accentPalette} > <Select.Label>Country</Select.Label> <Select.Control> <Select.Trigger> <Select.Value /> </Select.Trigger> <Select.IndicatorGroup> <Select.Icon /> </Select.IndicatorGroup> </Select.Control> <Select.Content> {COUNTRIES.map((option) => ( <Select.Item key={option.value} value={option.value}> <Select.ItemText>{option.label}</Select.ItemText> <Select.ItemIndicator /> </Select.Item> ))} </Select.Content> </Select.Root>
<Field.Root required invalid={Boolean(currentErrors.address)}> <Field.Label> Street address <Field.RequiredIndicator /> </Field.Label> <Input autoComplete="street-address" value={address} onValueChange={setAddress} placeholder="742 Valencia Street" aria-invalid={currentErrors.address ? true : undefined} /> {currentErrors.address ? ( <Field.Error match={true}>{currentErrors.address}</Field.Error> ) : null} </Field.Root>
<Field.Root> <Field.Label> Apartment, suite, etc. <Text render={<span />} size="xs" tone="subtle" weight="normal"> Optional </Text> </Field.Label> <Input autoComplete="address-line2" value={apartment} onValueChange={setApartment} placeholder="Suite 4B" /> </Field.Root>
<Grid columns={isNarrow ? "1" : country === "us" ? "3" : "2"} gap="4" style={styles.fullWidth} > <Field.Root required invalid={Boolean(currentErrors.city)}> <Field.Label> City <Field.RequiredIndicator /> </Field.Label> <Input autoComplete="address-level2" value={city} onValueChange={setCity} aria-invalid={currentErrors.city ? true : undefined} /> {currentErrors.city ? ( <Field.Error match={true}>{currentErrors.city}</Field.Error> ) : null} </Field.Root>
{country === "us" ? ( <Field.Root required invalid={Boolean(currentErrors.state)}> <Select.Root items={US_STATE_ITEMS} value={state || null} onValueChange={(nextState) => setState(nextState ?? "")} placeholder="Select state" palette={accentPalette} > <Select.Label>State</Select.Label> <Select.Control> <Select.Trigger aria-invalid={currentErrors.state ? true : undefined} > <Select.Value /> </Select.Trigger> <Select.IndicatorGroup> <Select.Icon /> </Select.IndicatorGroup> </Select.Control> <Select.Content> {US_STATE_ITEMS.map((option) => ( <Select.Item key={option.value} value={option.value}> <Select.ItemText>{option.label}</Select.ItemText> <Select.ItemIndicator /> </Select.Item> ))} </Select.Content> </Select.Root> {currentErrors.state ? ( <Field.Error match={true}>{currentErrors.state}</Field.Error> ) : null} </Field.Root> ) : null}
<Field.Root required invalid={Boolean(currentErrors.postalCode)}> <Field.Label> {postalRule.label} <Field.RequiredIndicator /> </Field.Label> <Input autoComplete="postal-code" value={postalCode} onValueChange={setPostalCode} placeholder={postalRule.placeholder} aria-invalid={currentErrors.postalCode ? true : undefined} /> {currentErrors.postalCode ? ( <Field.Error match={true}> {currentErrors.postalCode} </Field.Error> ) : null} </Field.Root> </Grid> </VStack> </VStack> ) : null}
{/* Step 2: Delivery */} {!isComplete && step === 2 ? ( <VStack ref={stepContentRef} gap="5" style={styles.stepSection}> <VStack gap="1"> <Heading render={<h2 />} size="xl" style={styles.headingReset}> How fast do you need it? </Heading> <Text variant="muted" size="sm"> Estimates run from the day the order ships, usually 1–2 business days after you place it. </Text> </VStack>
<VStack gap="4"> <Field.Root invalid={Boolean(currentErrors.delivery)}> <Field.Label>Delivery method</Field.Label> <RadioCard.Root value={delivery} onValueChange={(nextDelivery) => { if (nextDelivery) { setDelivery(nextDelivery); } }} variant="outline" size="md" palette={accentPalette} aria-label="Delivery method" aria-invalid={currentErrors.delivery ? true : undefined} style={styles.radioListStack} > {DELIVERY_OPTIONS.map((option) => { const isFree = option.value === "standard" && subtotal - discount >= FREE_SHIPPING_THRESHOLD; return ( <RadioCard.Item key={option.value} value={option.value}> <RadioCard.ItemControl style={styles.radioItemControl}> <RadioCard.ItemContent> <RadioCard.ItemText>{option.label}</RadioCard.ItemText> <RadioCard.ItemDescription> {option.window} </RadioCard.ItemDescription> </RadioCard.ItemContent> <HStack render={<span />} gap="3" style={styles.noShrink}> <Text render={<span />} size="sm" weight="medium" tabular="true" style={styles.nowrap} > {isFree ? "Free" : money(option.price)} </Text> <RadioCard.ItemIndicator /> </HStack> </RadioCard.ItemControl> </RadioCard.Item> ); })} </RadioCard.Root> {currentErrors.delivery ? ( <Field.Error match={true}>{currentErrors.delivery}</Field.Error> ) : null} </Field.Root>
<Separator />
<Checkbox.Root palette={accentPalette}> <Checkbox.Control checked={isGift} onCheckedChange={(checked) => setIsGift(checked === true)} /> <Checkbox.Label>This is a gift</Checkbox.Label> </Checkbox.Root>
<Field.Root> <Field.Label> {isGift ? "Gift message" : "Delivery instructions"} <Text render={<span />} size="xs" tone="subtle" weight="normal"> Optional </Text> </Field.Label> <Textarea rows={3} maxLength={240} value={deliveryNote} onValueChange={setDeliveryNote} placeholder={ isGift ? "Enjoy the new desk setup — happy recording." : "Ring the studio buzzer at the side entrance." } /> <Field.Description> {isGift ? "Printed on an enclosure card. Prices are omitted from the packing slip." : "Shared with the courier where supported."} </Field.Description> </Field.Root> </VStack> </VStack> ) : null}
{/* Step 3: Payment & Review */} {!isComplete && step === 3 ? ( <VStack ref={stepContentRef} gap="5" style={styles.stepSection}> <VStack gap="1"> <Heading render={<h2 />} size="xl" style={styles.headingReset}> Payment & review </Heading> <Text variant="muted" size="sm"> This block validates payment details and completes locally. No card is charged. </Text> </VStack>
<VStack gap="3" style={styles.reviewBox}> <HStack justify="between" gap="3"> <VStack gap="0.5"> <Text render={<span />} variant="caption"> Ship to </Text> <Text render={<span />} size="sm"> {formattedAddress || "Shipping address not entered"} </Text> </VStack> <Button variant="ghost" onClick={() => setStep(1)}> Edit </Button> </HStack> <Separator /> <HStack justify="between" gap="3"> <VStack gap="0.5"> <Text render={<span />} variant="caption"> Delivery </Text> <Text render={<span />} size="sm"> {deliveryOption.label} · {deliveryOption.window} </Text> </VStack> <Button variant="ghost" onClick={() => setStep(2)}> Edit </Button> </HStack> </VStack>
<VStack gap="4"> <Field.Root required invalid={Boolean(currentErrors.cardNumber)}> <Field.Label> Card number <Field.RequiredIndicator /> </Field.Label> <div {...stylex.props(styles.inputWithLeadingIcon)}> <span {...stylex.props(styles.leadingIconSlot)}> <LockIcon /> </span> <Input inputMode="numeric" autoComplete="cc-number" value={cardNumber} onValueChange={setCardNumber} placeholder="4242 4242 4242 4242" aria-invalid={currentErrors.cardNumber ? true : undefined} style={styles.cardNumberInput} /> </div> {currentErrors.cardNumber ? ( <Field.Error match={true}>{currentErrors.cardNumber}</Field.Error> ) : null} </Field.Root>
<Field.Root required invalid={Boolean(currentErrors.cardName)}> <Field.Label> Name on card <Field.RequiredIndicator /> </Field.Label> <Input autoComplete="cc-name" value={cardName} onValueChange={setCardName} placeholder="Jordan Ellis" aria-invalid={currentErrors.cardName ? true : undefined} /> {currentErrors.cardName ? ( <Field.Error match={true}>{currentErrors.cardName}</Field.Error> ) : null} </Field.Root>
{/* Fixed-width short fields stay sized to their expected values */} <HStack align="start" wrap="wrap" gap="4"> <Field.Root required invalid={Boolean(currentErrors.expiry)} style={styles.shortField} > <Field.Label> Expiry <Field.RequiredIndicator /> </Field.Label> <Input inputMode="numeric" autoComplete="cc-exp" value={expiry} onValueChange={setExpiry} placeholder="MM/YY" aria-invalid={currentErrors.expiry ? true : undefined} /> {currentErrors.expiry ? ( <Field.Error match={true}>{currentErrors.expiry}</Field.Error> ) : null} </Field.Root>
<Field.Root required invalid={Boolean(currentErrors.cvc)} style={styles.shortField} > <Field.Label> <HStack render={<span />} gap="1.5"> <span>CVC</span> <Field.RequiredIndicator /> <Tooltip.Root variant="inverted"> <Tooltip.Trigger render={ <IconButton type="button" variant="ghost" size="2xs" shape="rounded" aria-label="About card security code" style={styles.helpTrigger} /> } > <InfoCircleIcon /> </Tooltip.Trigger> <Tooltip.Content side="top" sideOffset={6}> Three digits on the back of the card, or four on the front for American Express. <Tooltip.Arrow /> </Tooltip.Content> </Tooltip.Root> </HStack> </Field.Label> <Input inputMode="numeric" autoComplete="cc-csc" value={cvc} onValueChange={setCvc} placeholder="123" aria-invalid={currentErrors.cvc ? true : undefined} /> {currentErrors.cvc ? ( <Field.Error match={true}>{currentErrors.cvc}</Field.Error> ) : null} </Field.Root> </HStack>
<Separator />
<Checkbox.Root palette={accentPalette}> <Checkbox.Control checked={billingMatches} onCheckedChange={(checked) => setBillingMatches(checked === true) } /> <Checkbox.Label> Billing address matches the shipping address </Checkbox.Label> </Checkbox.Root>
{!billingMatches ? ( <Alert.Root status="info" variant="subtle" size="sm" palette={bluePalette} > <Alert.Indicator> <InfoCircleIcon /> </Alert.Indicator> <Alert.Content> <Alert.Title>Connect a billing-address step</Alert.Title> <Alert.Description> This local example does not collect a separate billing address or transmit card data. Mount your payment provider's elements here in production. </Alert.Description> </Alert.Content> </Alert.Root> ) : null} </VStack> </VStack> ) : null}
{!isComplete ? actions : null} </VStack>
{!isNarrow ? ( <aside aria-label="Order summary" {...stylex.props(styles.summaryColumnSticky)} > {summaryCard} </aside> ) : null} </Stack> </VStack>
<Toaster toaster={queue} /> </VStack> );}
Inspired by the Checkout Wizard template from Astryx (MIT License · Copyright (c) 2026 Meta Platforms, Inc.).