# Contact form

A “Talk to sales” section: the pitch on the left with three reasons and contact details, and a form on the right in a `Card`. `Field`s take the name, work email and message, a `Select` takes the company size, a `Checkbox` records consent, and a confirmation replaces the form once it’s sent.

**Example: Talk to sales** (`examples/recipes/contact-form.tsx`)

```tsx
'use client'

import {
  Body,
  BodySmall,
  Button,
  Card,
  Checkbox,
  Field,
  Heading,
  Link,
  Select,
  Stack,
  Text,
  Textarea,
} from '@blocks/design-system'
import { CircleCheck, Clock, Mail, Phone, ShieldCheck, Truck, Users } from 'lucide-react'
import { type FormEvent, useEffect, useId, useRef, useState } from 'react'
import styles from './contact-form.module.css'

const companySizes = [
  { value: '1-49', label: '1–49 people' },
  { value: '50-199', label: '50–199 people' },
  { value: '200-999', label: '200–999 people' },
  { value: '1000+', label: '1,000 or more' },
]

const reasons = [
  { icon: Users, title: 'Volume pricing', text: 'Annual plans for teams of 50 or more, billed once.' },
  { icon: ShieldCheck, title: 'Security review', text: 'Our SOC 2 report, SAML SSO and a signed DPA.' },
  { icon: Truck, title: 'Guided migration', text: 'We move your projects over from spreadsheets or another tool.' },
]

interface Inquiry {
  name: string
  email: string
  size: string | null
  message: string
  consent: boolean
}

type Errors = Partial<Record<keyof Inquiry, string>>

const emptyInquiry: Inquiry = { name: '', email: '', size: null, message: '', consent: false }
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

function validate({ name, email, size, message, consent }: Inquiry): Errors {
  const errors: Errors = {}
  if (!name.trim()) errors.name = 'Enter your name.'
  if (!email) errors.email = 'Enter your work email.'
  else if (!emailPattern.test(email)) errors.email = 'Enter an email address like name@company.com.'
  if (!size) errors.size = 'Choose your company’s size.'
  if (message.trim().length < 20) errors.message = 'Tell us a little more, at least 20 characters.'
  if (!consent) errors.consent = 'We need your permission to reply.'
  return errors
}

// A "Talk to sales" page section: the pitch on the left, the form on the
// right, and a confirmation that takes the form's place once it's sent.
export default function ContactForm() {
  const pitchId = useId()
  const formTitleId = useId()
  const [inquiry, setInquiry] = useState(emptyInquiry)
  const [attempts, setAttempts] = useState(0)
  const [sent, setSent] = useState(false)
  const formRef = useRef<HTMLFormElement>(null)
  const confirmation = useRef<HTMLHeadingElement>(null)
  // Errors appear after the first submit, then follow the fields as they're fixed.
  const errors = attempts > 0 ? validate(inquiry) : {}

  function update<Key extends keyof Inquiry>(key: Key, value: Inquiry[Key]) {
    setInquiry((current) => ({ ...current, [key]: value }))
  }

  // Focus the first invalid control after a failed submit (Base UI mirrors
  // checkboxes on hidden inputs, which the selector skips).
  useEffect(() => {
    if (attempts === 0) return
    formRef.current?.querySelector<HTMLElement>('[aria-invalid="true"]:not([aria-hidden="true"])')?.focus()
  }, [attempts])

  // The form is gone once it's sent; move focus to what replaced it.
  useEffect(() => {
    if (sent) confirmation.current?.focus()
  }, [sent])

  function send(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (Object.keys(validate(inquiry)).length > 0) {
      setAttempts((count) => count + 1)
      return
    }
    setSent(true)
  }

  function startOver() {
    setInquiry(emptyInquiry)
    setAttempts(0)
    setSent(false)
  }

  const firstName = inquiry.name.trim().split(/\s+/)[0]

  return (
    <div className={styles.layout}>
      <div className={styles.layoutInner}>
        <section className={styles.pitch} aria-labelledby={pitchId}>
          <Stack gap="sm">
            <Text fontSize="xs" fontWeight="semibold" color="accent-text" dangerouslySetClassName={styles.eyebrow}>
              Ledger for teams
            </Text>
            <Heading as="h3" id={pitchId} fontSize="xl" margin="none">
              Talk to sales
            </Heading>
            <Body color="text-muted" margin="none">
              Rolling Ledger out across a company? We’ll walk you through pricing, security and getting everyone moved
              in.
            </Body>
          </Stack>

          <ul className={styles.reasons}>
            {reasons.map(({ icon: Icon, title, text }) => (
              <li key={title}>
                <span className={styles.reasonIcon}>
                  <Icon aria-hidden size={18} />
                </span>
                <Stack gap="xxs">
                  <Text fontWeight="semibold" fontSize="sm">
                    {title}
                  </Text>
                  <BodySmall color="text-muted" margin="none">
                    {text}
                  </BodySmall>
                </Stack>
              </li>
            ))}
          </ul>

          <address className={styles.contact}>
            <span>
              <Mail aria-hidden size={16} />
              <Link href="mailto:sales@ledger.example">sales@ledger.example</Link>
            </span>
            <span>
              <Phone aria-hidden size={16} />
              <Link href="tel:+15550104477">+1 (555) 010-4477</Link>
            </span>
            <span>
              <Clock aria-hidden size={16} />
              Weekdays, 8 am to 6 pm Mountain
            </span>
          </address>
        </section>

        <Card padding="lg" borderRadius="xl" dangerouslySetClassName={styles.formCard}>
          {sent ? (
            <Stack gap="md" align="start">
              <CircleCheck aria-hidden size={32} className={styles.success} />
              <Heading as="h4" ref={confirmation} tabIndex={-1} fontSize="lg" margin="none">
                Thanks, {firstName}. We’ll be in touch.
              </Heading>
              <Body color="text-muted" margin="none">
                A specialist will reply to {inquiry.email} within one business day, usually sooner.
              </Body>
              <Button type="button" onClick={startOver}>
                Send another message
              </Button>
            </Stack>
          ) : (
            <Stack as="form" ref={formRef} gap="lg" noValidate onSubmit={send} aria-labelledby={formTitleId}>
              <Heading as="h4" id={formTitleId} fontSize="md" margin="none">
                Send us a note
              </Heading>
              <Field name="name" invalid={Boolean(errors.name)}>
                <Field.Label>Full name</Field.Label>
                <Field.Control
                  autoComplete="name"
                  value={inquiry.name}
                  onValueChange={(value) => update('name', value)}
                />
                {errors.name && <Field.Error match>{errors.name}</Field.Error>}
              </Field>
              <Field name="email" invalid={Boolean(errors.email)}>
                <Field.Label>Work email</Field.Label>
                <Field.Control
                  type="email"
                  autoComplete="email"
                  value={inquiry.email}
                  onValueChange={(value) => update('email', value.trim())}
                />
                {errors.email && <Field.Error match>{errors.email}</Field.Error>}
              </Field>
              <Field name="size" invalid={Boolean(errors.size)}>
                <Select items={companySizes} value={inquiry.size} onValueChange={(value) => update('size', value)}>
                  <Select.Label>Company size</Select.Label>
                  <Select.Trigger placeholder="Choose a size" />
                  <Select.Content>
                    {companySizes.map((option) => (
                      <Select.Item key={option.value} value={option.value}>
                        {option.label}
                      </Select.Item>
                    ))}
                  </Select.Content>
                </Select>
                {errors.size && <Field.Error match>{errors.size}</Field.Error>}
              </Field>
              <Field name="message" invalid={Boolean(errors.message)}>
                <Field.Label>How can we help?</Field.Label>
                <Field.Control
                  render={<Textarea rows={4} />}
                  placeholder="Team size, tools you use today, timeline…"
                  value={inquiry.message}
                  onValueChange={(value) => update('message', value)}
                />
                {errors.message && <Field.Error match>{errors.message}</Field.Error>}
              </Field>
              <Field name="consent" invalid={Boolean(errors.consent)}>
                <Checkbox checked={inquiry.consent} onCheckedChange={(checked) => update('consent', checked)}>
                  Ledger may reply to me by email.
                </Checkbox>
                {errors.consent && <Field.Error match>{errors.consent}</Field.Error>}
              </Field>
              <Button type="submit" variant="primary">
                Send message
              </Button>
            </Stack>
          )}
        </Card>
      </div>
    </div>
  )
}
```

## How it works

- **Errors follow the fields.** Nothing is flagged until the first submit. After that the errors are derived from the current values, so each one clears as soon as its field is fixed, and focus moves to the first invalid control. The `Select` and `Checkbox` join their `Field`, so they show the same invalid state as the text inputs.
- **Success takes the form’s place.** The confirmation heading receives focus when it appears, so keyboard and screen reader users land on it instead of the top of the page. “Send another message” resets the form.
- **The layout follows its container.** A container query puts the pitch and the form side by side when the section is about 38rem wide, and stacks them on a phone. Contact details are an `<address>` with `mailto:` and `tel:` links.

## App-owned CSS

The two-column layout, the reason icons and the contact block.

`examples/recipes/contact-form.module.css`:

```css
/* Pitch beside the form when the container is wide enough, stacked otherwise. */

.layout {
  container-type: inline-size;
  text-wrap: pretty;
}

.layoutInner {
  display: grid;
  gap: var(--ds-space-xl);
  align-items: start;
}

@container (min-width: 38rem) {
  .layoutInner {
    grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr);
  }
}

.pitch {
  display: grid;
  gap: var(--ds-space-lg);
  padding-top: var(--ds-space-sm);
}

.eyebrow {
  letter-spacing: 0.08em;
  text-transform: uppercase;
}

.reasons {
  display: grid;
  gap: var(--ds-space-lg);
  margin: 0;
  padding: 0;
  list-style: none;

  & li {
    display: flex;
    gap: var(--ds-space-md);
  }
}

.reasonIcon {
  display: grid;
  place-items: center;
  flex: none;
  width: var(--ds-control-height-md);
  height: var(--ds-control-height-md);
  color: var(--ds-color-accent-text);
  background: var(--ds-color-accent-subtle);
  border-radius: var(--ds-border-radius-md);
}

.contact {
  display: grid;
  gap: var(--ds-space-sm);
  padding-top: var(--ds-space-lg);
  font-size: var(--ds-font-size-sm);
  font-style: normal;
  color: var(--ds-color-text-muted);
  border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);

  & span {
    display: inline-flex;
    align-items: center;
    gap: var(--ds-space-md);
  }
}

.formCard {
  background: var(--ds-color-bg);
  box-shadow: var(--ds-shadow-md);
}

.success {
  color: var(--ds-color-success);
}
```
