# Sign up

A create-account form built from `Field`, `Checkbox`, `Button` and `Link` in a `Card`. The password’s `Field.Description` holds a four-segment strength meter and a checklist of requirements that tick off as you type, including one that compares the password with the email above it.

**Example: Create a Ledger account** (`examples/recipes/sign-up.tsx`)

```tsx
'use client'

import {
  Body,
  BodySmall,
  Button,
  Card,
  Checkbox,
  Field,
  Heading,
  Input,
  Link,
  Stack,
  toastSuccess,
} from '@blocks/design-system'
import { Check, Circle } from 'lucide-react'
import { type FormEvent, useEffect, useId, useRef, useState } from 'react'
import styles from './sign-up.module.css'

type FieldName = 'name' | 'email' | 'password' | 'terms'
type Errors = Partial<Record<FieldName, string>>

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

// Each rule reads the password and the email typed above it.
const requirements = [
  { id: 'length', label: 'At least 12 characters', test: (password: string) => password.length >= 12 },
  { id: 'number', label: 'A number', test: (password: string) => /\d/.test(password) },
  { id: 'symbol', label: 'A symbol, like ! or #', test: (password: string) => /[^A-Za-z0-9\s]/.test(password) },
  {
    id: 'email',
    label: 'Doesn’t contain your email',
    test: (password: string, email: string) => {
      const [name = ''] = email.toLowerCase().split('@')
      return password.length > 0 && (name.length < 3 || !password.toLowerCase().includes(name))
    },
  },
]

const strengthLabels = ['Too weak', 'Weak', 'Fair', 'Good', 'Strong']

interface Account {
  name: string
  email: string
  password: string
  accepted: boolean
}

function validate({ name, email, password, accepted }: Account): 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 (!requirements.every((requirement) => requirement.test(password, email))) {
    errors.password = 'Choose a password that meets every requirement.'
  }
  if (!accepted) errors.terms = 'Accept the terms to create an account.'
  return errors
}

// A create-account form: the password's requirements tick as you type, a
// four-segment meter sums them up, and submit validates every field at once.
// After a failed submit, focus moves to the first invalid control.
export default function SignUp() {
  const titleId = useId()
  const [account, setAccount] = useState<Account>({ name: '', email: '', password: '', accepted: false })
  const [attempts, setAttempts] = useState(0)
  const formRef = useRef<HTMLFormElement>(null)

  // Errors appear after the first submit, then follow the fields as they're fixed.
  const errors = attempts > 0 ? validate(account) : {}
  const met = requirements.filter((requirement) => requirement.test(account.password, account.email))
  const strength = account.password ? met.length : 0

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

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

  function createAccount(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setAttempts((count) => count + 1)
    if (Object.keys(validate(account)).length > 0) return
    toastSuccess('Account created', { description: `We sent a confirmation link to ${account.email}.` })
  }

  return (
    <Card
      as="section"
      aria-labelledby={titleId}
      padding={{ base: 'lg', sm: 'xl' }}
      maxWidth="sm"
      marginX="auto"
      borderRadius="xl"
    >
      <Stack gap="lg">
        <Stack gap="xs">
          <Heading as="h3" id={titleId} fontSize="xl" margin="none">
            Create your account
          </Heading>
          <Body color="text-muted" margin="none">
            Free for 14 days. No card needed.
          </Body>
        </Stack>

        <Stack as="form" ref={formRef} gap="lg" noValidate onSubmit={createAccount} aria-labelledby={titleId}>
          <Field name="name" invalid={Boolean(errors.name)}>
            <Field.Label>Full name</Field.Label>
            <Field.Control
              render={<Input size="lg" />}
              autoComplete="name"
              value={account.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
              render={<Input size="lg" />}
              type="email"
              autoComplete="email"
              value={account.email}
              onValueChange={(value) => update('email', value.trim())}
            />
            {errors.email && <Field.Error match>{errors.email}</Field.Error>}
          </Field>

          <Field name="password" invalid={Boolean(errors.password)}>
            <Field.Label>Password</Field.Label>
            <Field.Control
              render={<Input size="lg" />}
              type="password"
              autoComplete="new-password"
              value={account.password}
              onValueChange={(value) => update('password', value)}
            />
            {/* The checklist is the field's description, so it's read with the input. */}
            <Field.Description render={<div />}>
              <div className={styles.meter} data-strength={strength} aria-hidden>
                <span />
                <span />
                <span />
                <span />
              </div>
              <p className={styles.strength} aria-live="polite">
                Strength: <strong>{account.password ? strengthLabels[strength] : 'Not set'}</strong>
              </p>
              <ul className={styles.checklist} aria-label="Password requirements">
                {requirements.map((requirement) => {
                  const done = met.includes(requirement)
                  return (
                    <li key={requirement.id} data-met={done || undefined}>
                      {done ? <Check aria-hidden size={14} /> : <Circle aria-hidden size={14} />}
                      {requirement.label}
                      <span className={styles.visuallyHidden}>{done ? ' (met)' : ' (not met)'}</span>
                    </li>
                  )
                })}
              </ul>
            </Field.Description>
            {errors.password && <Field.Error match>{errors.password}</Field.Error>}
          </Field>

          <Field name="terms" invalid={Boolean(errors.terms)}>
            <Checkbox checked={account.accepted} onCheckedChange={(checked) => update('accepted', checked)}>
              <span>
                I accept the <Link href="#terms">Terms</Link> and <Link href="#privacy">Privacy Policy</Link>
              </span>
            </Checkbox>
            {errors.terms && <Field.Error match>{errors.terms}</Field.Error>}
          </Field>

          <Button type="submit" variant="primary" size="lg">
            Create account
          </Button>
        </Stack>

        <Stack align="center">
          <BodySmall color="text-muted" margin="none">
            Already have an account? <Link href="#sign-in">Sign in</Link>
          </BodySmall>
        </Stack>
      </Stack>
    </Card>
  )
}
```

## How it works

- **The checklist is the field’s description.** `Field.Description` renders a `<div>` here (`render={<div />}`), so the meter and the list are announced with the password input. Each requirement changes its icon and carries visually hidden “met” or “not met” text, so the state never depends on color.
- **One source of truth.** The form is controlled, and errors are derived from its values once the reader has submitted: they appear all at once, then disappear as each field is fixed. After a failed submit, focus moves to the first invalid control.
- **Strength is described, not just drawn.** The meter is decorative; the “Strength: Good” line beside it is a polite live region that updates only when the level changes.

## App-owned CSS

The strength meter and the requirement checklist.

`examples/recipes/sign-up.module.css`:

```css
/* The password strength meter and its requirement checklist. */

.meter {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: var(--ds-space-sm);
  margin-top: var(--ds-space-xs);

  & span {
    height: var(--ds-space-sm);
    background: var(--ds-color-border-subtle);
    border-radius: var(--ds-border-radius-pill);
    transition: background-color var(--ds-duration-normal) var(--ds-easing-standard);
  }

  /* Fill one segment per requirement met; the color follows the strength. */
  &[data-strength="1"] span:nth-child(-n + 1),
  &[data-strength="2"] span:nth-child(-n + 2) {
    background: var(--ds-color-warning);
  }

  &[data-strength="3"] span:nth-child(-n + 3) {
    background: var(--ds-color-accent);
  }

  &[data-strength="4"] span {
    background: var(--ds-color-success);
  }
}

.strength {
  margin: var(--ds-space-sm) 0 0;

  & strong {
    color: var(--ds-color-text);
    font-weight: var(--ds-font-weight-semibold);
  }
}

.checklist {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr));
  gap: var(--ds-space-sm) var(--ds-space-lg);
  margin: var(--ds-space-md) 0 0;
  padding: 0;
  list-style: none;

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

  & li[data-met] {
    color: var(--ds-color-success-text);
  }
}

.visuallyHidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

@media (prefers-reduced-motion: reduce) {
  .meter span {
    transition: none;
  }
}
```
