# Checkout

A single-page checkout: contact email, a shipping address in a responsive `Grid` of `Field`s, shipping methods as a `RadioGroup` of cards with prices and arrival dates, card payment, and a `Checkbox` that reveals a billing address when it’s unchecked. The order summary `Card` follows the chosen shipping method, and Place order validates everything at once.

**Example: Checkout** (`examples/recipes/checkout.tsx`)

```tsx
'use client'

import {
  BodySmall,
  Button,
  Card,
  Checkbox,
  Field,
  type FieldControlProps,
  Grid,
  Heading,
  Radio,
  RadioGroup,
  Separator,
  Stack,
  Text,
  toastSuccess,
} from '@blocks/design-system'
import { ChevronDown, Lock } from 'lucide-react'
import { type FormEvent, type ReactNode, useId, useState } from 'react'
import styles from './checkout.module.css'

const lines = [
  { name: 'Ridgeline jacket', detail: 'Insulated · Spruce · M', price: 248 },
  { name: 'Merino trail socks', detail: '3 pairs · Charcoal · L · Qty 2', price: 72 },
]

const shippingMethods = [
  { value: 'standard', label: 'Standard', eta: 'Arrives Dec 9–11', price: 0 },
  { value: 'express', label: 'Express', eta: 'Arrives Fri, Dec 4', price: 18 },
  { value: 'overnight', label: 'Overnight', eta: 'Tomorrow, Dec 3', price: 42 },
]

const taxRate = 0.08
const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

type Errors = Record<string, string>

const required: Record<string, string> = {
  email: 'Enter an email for your receipt.',
  firstName: 'Enter a first name.',
  lastName: 'Enter a last name.',
  address: 'Enter a street address.',
  city: 'Enter a city.',
  region: 'Enter a state.',
  postalCode: 'Enter a ZIP code.',
  cardName: 'Enter the name on the card.',
}

const requiredForBilling: Record<string, string> = {
  billingAddress: 'Enter the billing street address.',
  billingCity: 'Enter the billing city.',
  billingPostalCode: 'Enter the billing ZIP code.',
}

function validate(data: FormData, billingSame: boolean): Errors {
  const value = (name: string) => String(data.get(name) ?? '').trim()
  const errors: Errors = {}

  for (const [name, message] of Object.entries({ ...required, ...(billingSame ? {} : requiredForBilling) })) {
    if (!value(name)) errors[name] = message
  }
  if (value('email') && !/^\S+@\S+\.\S+$/.test(value('email'))) errors.email = 'Enter an email like name@example.com.'
  if (value('postalCode') && !/^\d{5}(-\d{4})?$/.test(value('postalCode'))) errors.postalCode = 'Enter a 5-digit ZIP code.'
  if (value('cardNumber').replace(/\s/g, '').length !== 16) errors.cardNumber = 'Enter the 16-digit card number.'

  const [month = 0, year = 0] = value('expiry').split('/').map(Number)
  const now = new Date()
  const expired = 2000 + year < now.getFullYear() || (2000 + year === now.getFullYear() && month < now.getMonth() + 1)
  if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(value('expiry'))) errors.expiry = 'Enter the expiry as MM/YY.'
  else if (expired) errors.expiry = 'This card has expired.'
  if (!/^\d{3,4}$/.test(value('cvc'))) errors.cvc = 'Enter the 3 or 4 digits on the back.'

  return errors
}

// Groups digits as they're typed: "4242424242424242" → "4242 4242 4242 4242".
const formatCardNumber = (value: string) =>
  value
    .replace(/\D/g, '')
    .slice(0, 16)
    .replace(/(\d{4})(?=\d)/g, '$1 ')

const formatExpiry = (value: string) => {
  const digits = value.replace(/\D/g, '').slice(0, 4)
  return digits.length > 2 ? `${digits.slice(0, 2)}/${digits.slice(2)}` : digits
}

// One-page checkout. The form is uncontrolled apart from the formatted card
// fields; validation runs on submit and each field's error clears as it changes.
export default function Checkout() {
  const [errors, setErrors] = useState<Errors>({})
  const [shipping, setShipping] = useState('standard')
  const [billingSame, setBillingSame] = useState(true)
  const [cardNumber, setCardNumber] = useState('')
  const [expiry, setExpiry] = useState('')

  const subtotal = lines.reduce((sum, line) => sum + line.price, 0)
  const shippingPrice = shippingMethods.find((method) => method.value === shipping)?.price ?? 0
  const tax = subtotal * taxRate
  const total = subtotal + shippingPrice + tax
  const errorCount = Object.keys(errors).length

  function placeOrder(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const form = event.currentTarget
    const data = new FormData(form)
    const next = validate(data, billingSame)
    setErrors(next)

    const [firstInvalid] = Object.keys(next)
    if (firstInvalid) {
      ;(form.elements.namedItem(firstInvalid) as HTMLElement | null)?.focus()
      return
    }
    toastSuccess('Order NF-20431 placed', { description: `A receipt is on its way to ${data.get('email')}.` })
  }

  function clearError(name: string) {
    if (!(name in errors)) return
    setErrors(({ [name]: _cleared, ...rest }) => rest)
  }

  return (
    <Stack gap="lg" dangerouslySetClassName={styles.root}>
      <Heading as="h2" id="checkout-title" fontSize="xl">
        Checkout
      </Heading>
      <div className={styles.layout}>
        <OrderSummary subtotal={subtotal} shippingPrice={shippingPrice} tax={tax} total={total} />

        <form
          noValidate
          aria-labelledby="checkout-title"
          onSubmit={placeOrder}
          onChange={({ target }) => target instanceof HTMLInputElement && clearError(target.name)}
        >
          <Stack gap="xl">
            <Section title="Contact">
              <TextField name="email" label="Email" type="email" autoComplete="email" error={errors.email} />
            </Section>

            <Section title="Shipping address">
              <Grid columns={2} gap="lg">
                <TextField name="firstName" label="First name" autoComplete="shipping given-name" error={errors.firstName} />
                <TextField name="lastName" label="Last name" autoComplete="shipping family-name" error={errors.lastName} />
                <TextField name="address" label="Street address" autoComplete="shipping address-line1" error={errors.address} wide />
                <TextField name="address2" label="Apartment, suite (optional)" autoComplete="shipping address-line2" wide />
                <TextField name="city" label="City" autoComplete="shipping address-level2" error={errors.city} />
                <TextField name="region" label="State" autoComplete="shipping address-level1" error={errors.region} />
                <TextField
                  name="postalCode"
                  label="ZIP code"
                  inputMode="numeric"
                  autoComplete="shipping postal-code"
                  error={errors.postalCode}
                />
                <TextField name="phone" label="Phone (optional)" type="tel" autoComplete="shipping tel" />
              </Grid>
            </Section>

            <Section title="Shipping method">
              <RadioGroup
                name="shipping"
                aria-label="Shipping method"
                value={shipping}
                onValueChange={(value) => setShipping(String(value))}
                dangerouslySetClassName={styles.methods}
              >
                {shippingMethods.map((method) => (
                  <Radio key={method.value} value={method.value}>
                    <Stack as="span" gap="none" flex="1">
                      <Text fontWeight="semibold">{method.label}</Text>
                      <Text fontSize="sm" color="text-muted" dangerouslySetClassName={styles.nowrap}>
                        {method.eta}
                      </Text>
                    </Stack>
                    <Text fontWeight="semibold">{method.price === 0 ? 'Free' : money.format(method.price)}</Text>
                  </Radio>
                ))}
              </RadioGroup>
            </Section>

            <Section title="Payment">
              <Grid columns={2} gap="lg">
                <TextField
                  name="cardNumber"
                  label="Card number"
                  inputMode="numeric"
                  autoComplete="cc-number"
                  placeholder="1234 5678 9012 3456"
                  value={cardNumber}
                  onValueChange={(value) => setCardNumber(formatCardNumber(value))}
                  error={errors.cardNumber}
                  wide
                />
                <TextField
                  name="expiry"
                  label="Expiry"
                  inputMode="numeric"
                  autoComplete="cc-exp"
                  placeholder="MM/YY"
                  value={expiry}
                  onValueChange={(value) => setExpiry(formatExpiry(value))}
                  error={errors.expiry}
                />
                <TextField name="cvc" label="Security code" inputMode="numeric" autoComplete="cc-csc" maxLength={4} error={errors.cvc} />
                <TextField name="cardName" label="Name on card" autoComplete="cc-name" error={errors.cardName} wide />
              </Grid>
              <Checkbox name="billingSame" checked={billingSame} onCheckedChange={setBillingSame}>
                Billing address is the same as shipping
              </Checkbox>
              {!billingSame && (
                <Grid columns={2} gap="lg">
                  <TextField
                    name="billingAddress"
                    label="Billing street address"
                    autoComplete="billing address-line1"
                    error={errors.billingAddress}
                    wide
                  />
                  <TextField name="billingCity" label="City" autoComplete="billing address-level2" error={errors.billingCity} />
                  <TextField
                    name="billingPostalCode"
                    label="ZIP code"
                    inputMode="numeric"
                    autoComplete="billing postal-code"
                    error={errors.billingPostalCode}
                  />
                </Grid>
              )}
            </Section>

            <Stack gap="sm">
              {errorCount > 0 && (
                <BodySmall role="alert" margin="none" color="danger-text">
                  Fix the {errorCount === 1 ? 'highlighted field' : `${errorCount} highlighted fields`} to place your order.
                </BodySmall>
              )}
              <Button type="submit" variant="primary" size="lg" dangerouslySetClassName={styles.submit}>
                <Lock aria-hidden className={styles.icon} />
                Place order · {money.format(total)}
              </Button>
              <BodySmall margin="none" color="text-muted">
                Card details are encrypted and never stored on our servers.
              </BodySmall>
            </Stack>
          </Stack>
        </form>
      </div>
    </Stack>
  )
}

// On a phone the summary collapses to one row with the total; from 38rem it
// is a sticky column and the toggle is hidden (see the module).
function OrderSummary({ subtotal, shippingPrice, tax, total }: { subtotal: number; shippingPrice: number; tax: number; total: number }) {
  const [open, setOpen] = useState(false)
  const bodyId = useId()

  return (
    <Card as="aside" aria-labelledby={`${bodyId}-title`} padding="lg" backgroundColor="bg-subtle" borderRadius="xl" dangerouslySetClassName={styles.summary}>
      <button type="button" aria-expanded={open} aria-controls={bodyId} onClick={() => setOpen(!open)} className={styles.summaryToggle}>
        <span>{open ? 'Hide' : 'Show'} order summary</span>
        <span className={styles.amount}>{money.format(total)}</span>
        <ChevronDown aria-hidden className={styles.chevron} />
      </button>
      <Stack gap="md" id={bodyId} hidden={!open} dangerouslySetClassName={styles.summaryBody}>
        <Heading as="h3" id={`${bodyId}-title`} fontSize="md" dangerouslySetClassName={styles.summaryTitle}>
          Order summary
        </Heading>
        <Stack as="ul" gap="md" dangerouslySetClassName={styles.list}>
          {lines.map((line) => (
            <Stack as="li" key={line.name} direction="row" justify="space-between" gap="md">
              <Stack gap="none">
                <Text fontSize="sm" fontWeight="semibold">
                  {line.name}
                </Text>
                <Text fontSize="xs" color="text-muted">
                  {line.detail}
                </Text>
              </Stack>
              <Text fontSize="sm" dangerouslySetClassName={styles.amount}>
                {money.format(line.price)}
              </Text>
            </Stack>
          ))}
        </Stack>
        <Separator />
        <dl className={styles.totals}>
          <TotalRow label="Subtotal">{money.format(subtotal)}</TotalRow>
          <TotalRow label="Shipping">{shippingPrice === 0 ? 'Free' : money.format(shippingPrice)}</TotalRow>
          <TotalRow label="Estimated tax">{money.format(tax)}</TotalRow>
          <TotalRow label="Total" emphasis>
            {money.format(total)}
          </TotalRow>
        </dl>
      </Stack>
    </Card>
  )
}

function Section({ title, children }: { title: string; children: ReactNode }) {
  return (
    <fieldset className={styles.fieldset}>
      <legend className={styles.legend}>
        <Heading as="h3" fontSize="md">
          {title}
        </Heading>
      </legend>
      <Stack gap="lg">{children}</Stack>
    </fieldset>
  )
}

type TextFieldProps = FieldControlProps & { name: string; label: string; error?: string; wide?: boolean }

function TextField({ label, error, wide, ...control }: TextFieldProps) {
  return (
    <Field name={control.name} invalid={error !== undefined} dangerouslySetClassName={wide ? styles.wide : undefined}>
      <Field.Label>{label}</Field.Label>
      <Field.Control {...control} />
      {error && <Field.Error match>{error}</Field.Error>}
    </Field>
  )
}

function TotalRow({ label, emphasis, children }: { label: string; emphasis?: boolean; children: ReactNode }) {
  return (
    <div className={emphasis ? styles.totalRow : styles.row}>
      <dt>{label}</dt>
      <dd>{children}</dd>
    </div>
  )
}
```

## How it works

- The form is native and uncontrolled: Place order reads it with `FormData`, so the browser’s autofill works through the `autocomplete` tokens (`shipping postal-code`, `cc-number`, `cc-exp`, `cc-csc`). Only the card number and expiry are controlled, to group digits and insert the slash as you type, and every number field uses `inputMode="numeric"` for a phone’s number pad.
- Validation runs on submit with `noValidate` on the form. Each failing `Field` gets `invalid` and a `Field.Error`, which `Field` links to its input with `aria-describedby`, focus moves to the first invalid field, and a short alert above the button counts what’s left. Editing a field clears its error.
- Each section is a `fieldset` whose legend holds an `h3`, so the groups are named for screen readers and appear in the heading outline. The shipping methods are one `RadioGroup`; each `Radio`’s label is drawn as a card, so the name, arrival date and price are all part of its accessible name.
- The billing address is not rendered while “same as shipping” is checked, so its required fields are only checked when they are shown.
- On a phone the summary collapses to one row under the heading, “Show order summary” with the total, a button with `aria-expanded` that opens the details. From 38rem wide the toggle goes away and the summary is a sticky second column, always open, beside the form it totals. Address fields stay in pairs (first and last name, city and state) even on a phone.

## App-owned CSS

`examples/recipes/checkout.module.css`:

```css
.root {
  container-type: inline-size;
}

/* On a phone the summary is a collapsed row above the form; with room it
   becomes a sticky column, always open, and the toggle goes away. */
.layout {
  display: grid;
  gap: var(--ds-space-xl);
}

.summaryToggle {
  display: flex;
  align-items: center;
  gap: var(--ds-space-md);
  width: 100%;
  padding: 0;
  font: inherit;
  font-size: var(--ds-font-size-sm);
  font-weight: var(--ds-font-weight-semibold);
  color: var(--ds-color-text);
  text-align: left;
  background: none;
  border: none;
  cursor: pointer;

  & > span:first-child {
    flex: 1;
    color: var(--ds-color-accent-text);
  }

  &:focus-visible {
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
    outline-offset: var(--ds-space-sm);
  }
}

.chevron {
  flex-shrink: 0;
  width: var(--ds-icon-size-sm);
  height: var(--ds-icon-size-sm);
  transition: rotate var(--ds-duration-normal) var(--ds-easing-standard);

  [aria-expanded="true"] > & {
    rotate: 180deg;
  }
}

/* Stack's display class outranks the browser's [hidden] rule, so restate it. */
.summaryBody[hidden] {
  display: none;
}

.summaryBody {
  margin-top: var(--ds-space-lg);
}

.summaryTitle {
  display: none;
}

@container (min-width: 38rem) {
  .layout {
    grid-template-columns: minmax(0, 1fr) 16rem;
    align-items: start;
  }

  .summary {
    position: sticky;
    top: var(--ds-space-xxl);
    grid-column: 2;
    grid-row: 1;
  }

  .summary .summaryToggle {
    display: none;
  }

  .summary .summaryBody,
  .summary .summaryBody[hidden] {
    display: flex;
    margin-top: 0;
  }

  .summary .summaryTitle {
    display: block;
  }
}

.list {
  margin: 0;
  padding: 0;
  list-style: none;
}

.amount {
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
}

.nowrap {
  white-space: nowrap;
}

.totals {
  display: grid;
  gap: var(--ds-space-sm);
  margin: 0;
  font-size: var(--ds-font-size-sm);
}

.row,
.totalRow {
  display: flex;
  justify-content: space-between;
  gap: var(--ds-space-md);

  & dt {
    color: var(--ds-color-text-muted);
  }

  & dd {
    margin: 0;
    font-variant-numeric: tabular-nums;
  }
}

.totalRow {
  padding-top: var(--ds-space-md);
  margin-top: var(--ds-space-sm);
  font-size: var(--ds-font-size-md);
  font-weight: var(--ds-font-weight-semibold);
  border-top: var(--ds-border-width-sm) solid var(--ds-color-border);

  & dt {
    color: var(--ds-color-text);
  }
}

.fieldset {
  min-width: 0;
  margin: 0;
  padding: 0;
  border: none;
}

.legend {
  padding: 0;
  margin-bottom: var(--ds-space-lg);
}

.wide {
  grid-column: 1 / -1;
}

/* Shipping methods: each Radio's label becomes a selectable card. */
.root .methods {
  gap: var(--ds-space-sm);
}

.root .methods > label {
  display: flex;
  gap: var(--ds-space-lg);
  padding: var(--ds-space-lg);
  border: var(--ds-border-width-sm) solid var(--ds-color-border);
  border-radius: var(--ds-border-radius-md);
  transition: border-color var(--ds-duration-fast) var(--ds-easing-standard);

  &:hover {
    border-color: var(--ds-color-border-strong);
  }

  &:has([data-checked]) {
    background-color: var(--ds-color-accent-subtle);
    border-color: var(--ds-color-accent);
  }
}

.submit {
  width: 100%;
}

.icon {
  width: var(--ds-icon-size-sm);
  height: var(--ds-icon-size-sm);
}

@media (prefers-reduced-motion: reduce) {
  .root .methods > label,
  .chevron {
    transition: none;
  }
}
```
