# Sign in

A sign-in card for a fictional product: `Field` wraps a large `Input` for the email and password, a `Checkbox` keeps the session, and a primary `Button` submits. A rule labelled “or” separates two more `Button`s for passkey and SSO, and `Link`s point to password recovery and sign-up. A `toast` confirms the sign-in.

**Example: Sign in to Ledger** (`examples/recipes/sign-in.tsx`)

```tsx
'use client'

import {
  Body,
  BodySmall,
  Button,
  Card,
  Checkbox,
  Field,
  Heading,
  Input,
  Link,
  Spinner,
  Stack,
  toastInfo,
  toastSuccess,
} from '@blocks/design-system'
import { Eye, EyeOff, FingerprintPattern, KeyRound } from 'lucide-react'
import { type FormEvent, useEffect, useId, useRef, useState } from 'react'
import styles from './sign-in.module.css'

interface Errors {
  email?: string
  password?: string
}

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

function validate(email: string, password: string): Errors {
  const errors: Errors = {}
  if (!email) errors.email = 'Enter your email address.'
  else if (!emailPattern.test(email)) errors.email = 'Enter an email address like name@company.com.'
  if (!password) errors.password = 'Enter your password.'
  return errors
}

// A product sign-in card. The form validates itself (noValidate) so every
// message is a Field.Error tied to its control. Errors appear on submit, then
// clear as each field is fixed. Field.Control renders a large Input.
export default function SignIn() {
  const titleId = useId()
  const formRef = useRef<HTMLFormElement>(null)
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [attempts, setAttempts] = useState(0)
  const [signingInAs, setSigningInAs] = useState<string | null>(null)
  const errors = attempts > 0 ? validate(email, password) : {}

  // After a failed submit, focus the first field that needs attention.
  useEffect(() => {
    if (attempts > 0) formRef.current?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus()
  }, [attempts])

  // Stands in for the network request; the timer is cleared if the card unmounts.
  useEffect(() => {
    if (!signingInAs) return
    const timer = setTimeout(() => {
      toastSuccess('Signed in', { description: `Welcome back, ${signingInAs}.` })
      setSigningInAs(null)
    }, 900)
    return () => clearTimeout(timer)
  }, [signingInAs])

  function signIn(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (signingInAs) return
    setAttempts((count) => count + 1)
    if (Object.keys(validate(email, password)).length > 0) return
    setSigningInAs(email)
  }

  return (
    <Card
      as="section"
      aria-labelledby={titleId}
      padding={{ base: 'lg', sm: 'xl' }}
      maxWidth="sm"
      marginX="auto"
      borderRadius="xl"
    >
      <Stack gap="lg">
        <Stack gap="sm">
          <span className={styles.mark} aria-hidden>
            L
          </span>
          <Heading as="h3" id={titleId} fontSize="xl" margin="none">
            Sign in to Ledger
          </Heading>
          <Body color="text-muted" margin="none">
            Welcome back. Use the email you signed up with.
          </Body>
        </Stack>

        <Stack as="form" ref={formRef} gap="lg" noValidate onSubmit={signIn} aria-labelledby={titleId}>
          <Field name="email" invalid={Boolean(errors.email)}>
            <Field.Label>Email</Field.Label>
            <Field.Control
              render={<Input size="lg" />}
              type="email"
              autoComplete="email"
              placeholder="you@company.com"
              value={email}
              onValueChange={(value) => setEmail(value.trim())}
            />
            {errors.email && <Field.Error match>{errors.email}</Field.Error>}
          </Field>

          <Field name="password" invalid={Boolean(errors.password)}>
            <Stack direction="row" justify="space-between" align="baseline" gap="sm">
              <Field.Label>Password</Field.Label>
              <Link href="#forgot-password" fontSize="sm">
                Forgot password?
              </Link>
            </Stack>
            <div className={styles.password}>
              <Field.Control
                render={<Input size="lg" dangerouslySetClassName={styles.passwordInput} />}
                type={showPassword ? 'text' : 'password'}
                autoComplete="current-password"
                value={password}
                onValueChange={setPassword}
              />
              <button
                type="button"
                className={styles.reveal}
                aria-label="Show password"
                aria-pressed={showPassword}
                onClick={() => setShowPassword((shown) => !shown)}
              >
                {showPassword ? <EyeOff aria-hidden size={18} /> : <Eye aria-hidden size={18} />}
              </button>
            </div>
            {errors.password && <Field.Error match>{errors.password}</Field.Error>}
          </Field>

          <Checkbox name="remember" defaultChecked>
            Keep me signed in for 30 days
          </Checkbox>

          {/* aria-disabled, not disabled, so focus stays on the button while it waits. */}
          <Button type="submit" variant="primary" size="lg" aria-disabled={signingInAs !== null}>
            {signingInAs && <Spinner size="sm" aria-hidden />}
            {signingInAs ? 'Signing in…' : 'Sign in'}
          </Button>
        </Stack>

        <div className={styles.divider}>or</div>

        <Stack gap="sm">
          <Button type="button" size="lg" onClick={() => toastInfo('Waiting for your passkey…')}>
            <FingerprintPattern aria-hidden size={18} />
            Continue with passkey
          </Button>
          <Button type="button" size="lg" onClick={() => toastInfo('Redirecting to your identity provider…')}>
            <KeyRound aria-hidden size={18} />
            Continue with SSO
          </Button>
        </Stack>

        <Stack align="center">
          <BodySmall color="text-muted" margin="none">
            New to Ledger? <Link href="#sign-up">Create an account</Link>
          </BodySmall>
        </Stack>
      </Stack>
    </Card>
  )
}
```

## How it works

- **The form validates itself.** `noValidate` turns off the browser’s bubbles, so every message is a `Field.Error` tied to its control. Errors appear on the first submit, then clear field by field as they’re fixed, and focus moves to the first field that needs attention.
- **The reveal button is a real toggle.** It’s a `<button>` with `aria-pressed` and a fixed label, “Show password”, and it sits inside the input’s border without covering the text.
- **Pending keeps focus.** While the request runs the submit button is `aria-disabled` rather than `disabled`, so keyboard focus stays on it. The stand-in request is a timer the effect clears if the card unmounts.
- **App-owned vs. system.** Sizes, spacing, color and focus rings come from the package; the product mark, the reveal button’s position and the “or” rule are the app’s.

## App-owned CSS

The product mark, the password reveal button and the “or” rule.

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

```css
/* The product mark, the password reveal button and the "or" rule. */

.mark {
  display: inline-grid;
  place-items: center;
  width: var(--ds-control-height-lg);
  height: var(--ds-control-height-lg);
  margin-bottom: var(--ds-space-md);
  font: var(--ds-font-weight-bold) var(--ds-font-size-lg) / 1 var(--ds-font-heading);
  color: var(--ds-color-accent-fg);
  background: var(--ds-color-accent);
  border-radius: var(--ds-border-radius-md);
}

.password {
  position: relative;
}

/* Room for the reveal button inside the input's border. */
.password .passwordInput {
  padding-right: calc(var(--ds-control-height-lg) + var(--ds-space-xs));
}

.reveal {
  position: absolute;
  top: var(--ds-space-xs);
  right: var(--ds-space-xs);
  display: grid;
  place-items: center;
  width: calc(var(--ds-control-height-lg) - var(--ds-space-xs) * 2);
  height: calc(var(--ds-control-height-lg) - var(--ds-space-xs) * 2);
  padding: 0;
  color: var(--ds-color-text-muted);
  background: transparent;
  border: 0;
  border-radius: var(--ds-border-radius-sm);
  cursor: pointer;

  &:hover {
    color: var(--ds-color-text);
    background: var(--ds-color-surface-hover);
  }

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

.divider {
  display: flex;
  align-items: center;
  gap: var(--ds-space-md);
  font-size: var(--ds-font-size-xs);
  color: var(--ds-color-text-muted);
  text-transform: uppercase;
  letter-spacing: 0.08em;

  &::before,
  &::after {
    content: "";
    flex: 1;
    border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  }
}
```
