# Empty states

Three empty states in `Card`s, each saying why the space is empty and what to do next: a first run with an illustration drawn in SVG, a search with no results that echoes the query and offers suggestions, and a load error whose retry shows a `Spinner` and then recovers.

**Example: First run, no results and error** (`examples/recipes/empty-states.tsx`)

```tsx
'use client'

import { Body, Button, Card, Code, Heading, Input, Spinner, Stack, Text, toastSuccess } from '@blocks/design-system'
import { CloudOff, FileText, Plus, RotateCw, Search, SearchX, Upload } from 'lucide-react'
import { useEffect, useId, useRef, useState } from 'react'
import styles from './empty-states.module.css'

const documents = ['Quarterly forecast', 'Quarterly board update', 'Hiring plan 2027', 'Brand guidelines', 'Security review checklist']
const suggestions = ['quarterly forecast', 'hiring plan', 'brand']
const invoices = [
  { id: 'INV-2093', customer: 'Alder & Finch', amount: '$4,200.00' },
  { id: 'INV-2092', customer: 'Northgate Clinic', amount: '$860.00' },
  { id: 'INV-2091', customer: 'Juniper Studio', amount: '$1,315.50' },
]

// First run: an illustration, a headline, why it's empty and what to do next.
function FirstRun() {
  return (
    <Card as="section" padding="xl" borderRadius="xl" aria-labelledby="empty-states-first-run" dangerouslySetClassName={styles.card}>
      <svg className={styles.illustration} viewBox="0 0 160 96" aria-hidden>
        <rect className={styles.sheetBack} x="44" y="10" width="72" height="56" rx="8" />
        <rect className={styles.sheet} x="30" y="22" width="72" height="56" rx="8" />
        <rect className={styles.line} x="42" y="38" width="36" height="6" rx="3" />
        <rect className={styles.lineMuted} x="42" y="52" width="48" height="6" rx="3" />
        <circle className={styles.plusDisc} cx="112" cy="70" r="18" />
        <path className={styles.plus} d="M112 62v16M104 70h16" />
      </svg>
      <Stack gap="sm" align="center">
        <Heading as="h3" id="empty-states-first-run" fontSize="lg">
          Create your first project
        </Heading>
        <Body fontSize="sm" color="text-muted" margin="none">
          Projects keep a team’s docs, tasks and files in one place. Start from scratch, or bring in what you already have.
        </Body>
      </Stack>
      <Stack direction="row" gap="sm" justify="center" wrap="wrap" dangerouslySetClassName={styles.actions}>
        <Button type="button" variant="primary" onClick={() => toastSuccess('Created “Untitled project”')}>
          <Plus aria-hidden size={16} />
          New project
        </Button>
        <Button type="button" onClick={() => toastSuccess('Import started from projects.csv')}>
          <Upload aria-hidden size={16} />
          Import from CSV
        </Button>
      </Stack>
    </Card>
  )
}

// No results: echo the query and offer searches that will find something.
function NoResults() {
  const [query, setQuery] = useState('quaterly forcast')
  const id = useId()
  const terms = query.trim().toLowerCase()
  const results = terms ? documents.filter((title) => title.toLowerCase().includes(terms)) : documents

  return (
    <Card as="section" padding="xl" borderRadius="xl" aria-labelledby={`${id}-title`} dangerouslySetClassName={styles.card}>
      <Heading as="h3" id={`${id}-title`} fontSize="md" dangerouslySetClassName={styles.srOnly}>
        Search documents
      </Heading>
      <search className={styles.search}>
        <Search aria-hidden size={16} className={styles.searchIcon} />
        <Input type="search" aria-label="Search documents" value={query} onChange={(event) => setQuery(event.target.value)} />
      </search>
      {results.length > 0 ? (
        <ul className={styles.results} aria-label="Matching documents">
          {results.map((title) => (
            <li key={title}>
              <FileText aria-hidden size={16} />
              <a href={`#${title.toLowerCase().replaceAll(' ', '-')}`}>{title}</a>
            </li>
          ))}
        </ul>
      ) : (
        <Stack gap="md" align="center" role="status">
          <span className={styles.iconDisc}>
            <SearchX aria-hidden size={24} />
          </span>
          <Stack gap="xs" align="center">
            <Text fontWeight="semibold">No results for “{query.trim()}”</Text>
            <Text fontSize="sm" color="text-muted">
              Check the spelling, or try one of these:
            </Text>
          </Stack>
          <Stack as="ul" direction="row" gap="sm" justify="center" wrap="wrap" dangerouslySetClassName={styles.suggestions}>
            {suggestions.map((suggestion) => (
              <li key={suggestion}>
                <Button type="button" size="sm" borderRadius="pill" onClick={() => setQuery(suggestion)}>
                  {suggestion}
                </Button>
              </li>
            ))}
          </Stack>
          <Button type="button" variant="link" size="sm" onClick={() => setQuery('')}>
            Clear search
          </Button>
        </Stack>
      )}
    </Card>
  )
}

// Error: say what failed and that nothing was lost, then retry in place.
function LoadError() {
  const [status, setStatus] = useState<'failed' | 'retrying' | 'loaded'>('failed')
  const heading = useRef<HTMLHeadingElement>(null)
  const retry = useRef<HTMLButtonElement>(null)
  const id = useId()

  // The button that had focus goes away either way, so focus moves with the content.
  useEffect(() => {
    if (status !== 'retrying') return
    const timer = setTimeout(() => {
      setStatus('loaded')
      requestAnimationFrame(() => heading.current?.focus())
    }, 1400)
    return () => clearTimeout(timer)
  }, [status])

  function showError() {
    setStatus('failed')
    requestAnimationFrame(() => retry.current?.focus())
  }

  return (
    <Card as="section" padding="xl" borderRadius="xl" aria-labelledby={`${id}-title`} dangerouslySetClassName={styles.card}>
      {status === 'loaded' ? (
        <Stack gap="md" width="full" textAlign="left">
          <Heading as="h3" id={`${id}-title`} fontSize="md" ref={heading} tabIndex={-1} dangerouslySetClassName={styles.focusTarget}>
            Recent invoices
          </Heading>
          <ul className={styles.invoices}>
            {invoices.map((invoice) => (
              <li key={invoice.id}>
                <Code>{invoice.id}</Code>
                <Text fontSize="sm">{invoice.customer}</Text>
                <Text fontSize="sm" fontWeight="semibold">
                  {invoice.amount}
                </Text>
              </li>
            ))}
          </ul>
          <div>
            <Button type="button" variant="link" size="sm" onClick={showError}>
              Show the error again
            </Button>
          </div>
        </Stack>
      ) : (
        <>
          <span className={styles.iconDisc} data-tone="danger">
            <CloudOff aria-hidden size={24} />
          </span>
          <Stack gap="sm" align="center">
            <Heading as="h3" id={`${id}-title`} fontSize="lg">
              We couldn’t load your invoices
            </Heading>
            <Body fontSize="sm" color="text-muted" margin="none">
              The billing service didn’t answer in time. Your invoices are safe; this is a connection problem on our side.
            </Body>
            <Text fontSize="xs" color="text-muted">
              Error 503 · Request <Code fontSize="xs">7f3a-21c9</Code>
            </Text>
          </Stack>
          <Button ref={retry} type="button" variant="primary" aria-disabled={status === 'retrying'} onClick={() => setStatus('retrying')}>
            {status === 'retrying' ? <Spinner size="sm" aria-hidden /> : <RotateCw aria-hidden size={16} />}
            {status === 'retrying' ? 'Retrying…' : 'Try again'}
          </Button>
        </>
      )}
    </Card>
  )
}

export default function EmptyStates() {
  return (
    <Stack gap="lg">
      <FirstRun />
      <NoResults />
      <LoadError />
    </Stack>
  )
}
```

## How it works

- The illustration is inline SVG painted by classes in the module, so its fills and strokes are tokens and it follows the theme. It is `aria-hidden`; the heading says what matters.
- The search is live: change the query, or press a suggestion, and the results come back. The no-results message is a `role="status"` region, so it is announced when it appears.
- Retry keeps its place and its focus while it works (`aria-disabled`, a `Spinner` and “Retrying…”). The timer lives in an effect that clears itself, and when the invoices load, focus moves to their heading because the button that had it is gone.

## App-owned CSS

`examples/recipes/empty-states.module.css`:

```css
.card {
  container-type: inline-size;
  display: grid;
  justify-items: center;
  gap: var(--ds-space-lg);
  text-align: center;
  background-color: var(--ds-color-bg);

  & p {
    max-inline-size: 26rem;
  }
}

/* On a phone the two actions stack at one full width */
@container (width < 22rem) {
  .card .actions {
    flex-direction: column;
    justify-self: stretch;
  }
}

/* The first-run illustration: two sheets and a plus, drawn from the tokens */
.illustration {
  inline-size: 10rem;
  block-size: auto;
}

.sheetBack {
  fill: var(--ds-color-accent-subtle);
}

.sheet {
  fill: var(--ds-color-bg);
  stroke: var(--ds-color-border);
  stroke-width: 1.5;
}

.line {
  fill: var(--ds-color-border-strong);
}

.lineMuted {
  fill: var(--ds-color-border-subtle);
}

.plusDisc {
  fill: var(--ds-color-accent);
}

.plus {
  stroke: var(--ds-color-accent-fg);
  stroke-width: 3;
  stroke-linecap: round;
}

.iconDisc {
  display: grid;
  place-items: center;
  inline-size: var(--ds-space-xxl);
  block-size: var(--ds-space-xxl);
  color: var(--ds-color-text-muted);
  background-color: var(--ds-color-surface);
  border-radius: var(--ds-border-radius-circle);

  &[data-tone='danger'] {
    color: var(--ds-color-danger-text);
    background-color: var(--ds-color-danger-subtle);
  }
}

.search {
  position: relative;
  inline-size: 100%;
  max-inline-size: 26rem;

  & input {
    padding-left: calc(var(--ds-space-md) * 2 + var(--ds-icon-size-sm));
  }
}

.searchIcon {
  position: absolute;
  top: 50%;
  left: var(--ds-space-md);
  translate: 0 -50%;
  color: var(--ds-color-text-muted);
  pointer-events: none;
}

.results,
.suggestions,
.invoices {
  margin: 0;
  padding: 0;
  list-style: none;
}

.results {
  display: grid;
  gap: var(--ds-space-sm);
  inline-size: 100%;
  max-inline-size: 26rem;
  text-align: left;

  & li {
    display: flex;
    align-items: center;
    gap: var(--ds-space-md);
    padding: var(--ds-space-md);
    font-size: var(--ds-font-size-sm);
    color: var(--ds-color-text-muted);
    border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
    border-radius: var(--ds-border-radius-md);
  }

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

.invoices {
  display: grid;

  & li {
    display: grid;
    grid-template-columns: auto minmax(0, 1fr) auto;
    align-items: center;
    gap: var(--ds-space-md);
    padding: var(--ds-space-md) 0;
    border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  }
}

.focusTarget:focus {
  outline: none;
}

.srOnly {
  position: absolute;
  inline-size: var(--ds-space-xxs);
  block-size: var(--ds-space-xxs);
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}
```
