# Email inbox

A mail client for a fictional team: folders with unread counts, a message list with sender, subject, snippet, time, unread weight and a star toggle, and a reading pane where you can reply or archive. The folders are a `NavList` laid out in a row, and `Button`, `Badge`, `Heading`, `Field`, `Textarea` and `toast` come from the system; the panes and rows are app-owned CSS on tokens.

**Example: Fieldnote mail** (`examples/recipes/email-inbox.tsx`)

```tsx
'use client'

import { Badge, Body, BodySmall, Button, Field, Heading, NavList, Stack, Text, Textarea, toast, toastSuccess } from '@blocks/design-system'
import { Archive, ArrowLeft, Inbox, type LucideIcon, Reply, Send, Star } from 'lucide-react'
import { type FormEvent, useId, useRef, useState } from 'react'
import styles from './email-inbox.module.css'

type FolderId = 'inbox' | 'starred' | 'sent' | 'archive'

interface Message {
  id: string
  folder: 'inbox' | 'sent' | 'archive'
  name: string
  initials: string
  address: string
  subject: string
  snippet: string
  body: string[]
  time: string
  unread: boolean
  starred: boolean
}

const folders: { id: FolderId; label: string; icon: LucideIcon }[] = [
  { id: 'inbox', label: 'Inbox', icon: Inbox },
  { id: 'starred', label: 'Starred', icon: Star },
  { id: 'sent', label: 'Sent', icon: Send },
  { id: 'archive', label: 'Archive', icon: Archive },
]

const initialMessages: Message[] = [
  {
    id: 'venues',
    folder: 'inbox',
    name: 'Maya Okafor',
    initials: 'MO',
    address: 'maya@fieldnote.example',
    subject: 'Venue shortlist for the March offsite',
    snippet: 'Three places made the cut. The lake house has the best rooms but',
    body: [
      'Hi team, three places made the cut after Friday’s calls.',
      'The lake house has the best rooms but needs a bus from the airport. The mill in town is walkable and has a kitchen we can use. The vineyard is lovely and the most expensive by about 30%.',
      'Can you reply with your first and second choice by Wednesday? I’ll hold all three until then.',
    ],
    time: '9:41 AM',
    unread: true,
    starred: true,
  },
  {
    id: 'invoice',
    folder: 'inbox',
    name: 'Ledgerline Billing',
    initials: 'LB',
    address: 'billing@ledgerline.example',
    subject: 'Your November invoice is ready',
    snippet: 'Invoice LL-20481 for $1,240.00 is available in your billing',
    body: [
      'Invoice LL-20481 for $1,240.00 is available in your billing settings.',
      'It will be charged to the card ending in 4417 on December 5. No action is needed.',
    ],
    time: '8:15 AM',
    unread: true,
    starred: false,
  },
  {
    id: 'review',
    folder: 'inbox',
    name: 'Priya Natarajan',
    initials: 'PN',
    address: 'priya@fieldnote.example',
    subject: 'Design review notes: search filters',
    snippet: 'Thanks for walking us through it. Two things to settle before',
    body: [
      'Thanks for walking us through it. Two things to settle before we build:',
      'Do filters apply as you pick them, or on Apply? And does clearing the query also clear the filters? I lean towards live filters and keeping them.',
    ],
    time: 'Yesterday',
    unread: true,
    starred: false,
  },
  {
    id: 'checklist',
    folder: 'inbox',
    name: 'Tomás Reyes',
    initials: 'TR',
    address: 'tomas@fieldnote.example',
    subject: 'Re: Onboarding checklist v2',
    snippet: 'Merged your edits. I moved “Set up your laptop” to day one',
    body: ['Merged your edits. I moved “Set up your laptop” to day one and dropped the duplicate security quiz.'],
    time: 'Yesterday',
    unread: false,
    starred: false,
  },
  {
    id: 'lunch',
    folder: 'inbox',
    name: 'Jun Park',
    initials: 'JP',
    address: 'jun@fieldnote.example',
    subject: 'Lunch Thursday?',
    snippet: 'The noodle place on Alder reopened. 12:30 work for you?',
    body: ['The noodle place on Alder reopened. 12:30 work for you?'],
    time: 'Nov 28',
    unread: false,
    starred: true,
  },
  {
    id: 'agenda',
    folder: 'sent',
    name: 'Maya Okafor',
    initials: 'MO',
    address: 'maya@fieldnote.example',
    subject: 'Offsite agenda, first draft',
    snippet: 'Day one is planning, day two is workshops. Edit freely.',
    body: ['Day one is planning, day two is workshops. Edit freely; I’ll lock it on the 15th.'],
    time: 'Nov 27',
    unread: false,
    starred: false,
  },
  {
    id: 'welcome',
    folder: 'archive',
    name: 'Elena Vasquez',
    initials: 'EV',
    address: 'elena@fieldnote.example',
    subject: 'Welcome to Fieldnote!',
    snippet: 'We’re so glad you’re here. Your first week is mostly',
    body: ['We’re so glad you’re here. Your first week is mostly meeting people, so don’t worry about shipping anything yet.'],
    time: 'Oct 2',
    unread: false,
    starred: false,
  },
]

const inFolder = (message: Message, folder: FolderId) => (folder === 'starred' ? message.starred : message.folder === folder)

// A two-pane mail client. Wide containers show the list and the message side
// by side; narrow ones show one pane at a time, switched by `view`.
export default function EmailInbox() {
  const [messages, setMessages] = useState(initialMessages)
  const [folder, setFolder] = useState<FolderId>('inbox')
  const [selectedId, setSelectedId] = useState<string | null>('venues')
  const [view, setView] = useState<'list' | 'message'>('list')
  const [replying, setReplying] = useState(false)
  const [replyError, setReplyError] = useState('')
  const listRef = useRef<HTMLDivElement>(null)
  const subjectRef = useRef<HTMLHeadingElement>(null)
  const replyRef = useRef<HTMLInputElement>(null)
  const id = useId()

  const visible = messages.filter((message) => inFolder(message, folder))
  const selected = visible.find((message) => message.id === selectedId)
  const folderLabel = folders.find((entry) => entry.id === folder)?.label
  const itemId = (messageId: string) => `${id}-message-${messageId}`

  function update(messageId: string, change: Partial<Message>) {
    setMessages((current) => current.map((message) => (message.id === messageId ? { ...message, ...change } : message)))
  }

  function openFolder(next: FolderId) {
    setFolder(next)
    setSelectedId(messages.find((message) => inFolder(message, next))?.id ?? null)
    setView('list')
    setReplying(false)
  }

  // On a phone only one pane shows, so focus follows the pane that opens.
  const listHidden = () => listRef.current?.getClientRects().length === 0
  const focusItem = (messageId: string) => requestAnimationFrame(() => document.getElementById(itemId(messageId))?.focus())

  function openMessage(messageId: string) {
    update(messageId, { unread: false })
    setSelectedId(messageId)
    setView('message')
    setReplying(false)
    requestAnimationFrame(() => {
      if (listHidden()) subjectRef.current?.focus()
    })
  }

  function backToList() {
    setView('list')
    if (selectedId) focusItem(selectedId)
  }

  function archive(message: Message) {
    const index = visible.indexOf(message)
    const next = visible[index + 1] ?? visible[index - 1]
    const destination = message.folder === 'archive' ? 'inbox' : 'archive'
    update(message.id, { folder: destination })
    setSelectedId(next?.id ?? null)
    if (next && listHidden()) focusItem(next.id)
    setView('list')
    toast(destination === 'archive' ? `Archived “${message.subject}”` : `Moved “${message.subject}” to Inbox`)
  }

  function startReply() {
    setReplyError('')
    setReplying(true)
    requestAnimationFrame(() => replyRef.current?.focus())
  }

  function sendReply(event: FormEvent<HTMLFormElement>, message: Message) {
    event.preventDefault()
    const reply = String(new FormData(event.currentTarget).get('reply')).trim()
    if (!reply) {
      setReplyError('Write a reply before sending.')
      return
    }
    setReplying(false)
    toastSuccess(`Reply sent to ${message.name}`)
  }

  return (
    <section className={styles.root} aria-label="Mail">
      <NavList aria-label="Mail folders" dangerouslySetClassName={styles.folders}>
        {folders.map(({ id: folderId, label, icon: Icon }) => {
          const unread = messages.filter((message) => message.unread && inFolder(message, folderId)).length
          return (
            <NavList.Item key={folderId} as="button" type="button" active={folder === folderId} onClick={() => openFolder(folderId)}>
              <Icon aria-hidden size={14} />
              <span className={styles.folderLabel}>{label}</span>
              {unread > 0 && (
                <Badge tone="accent">
                  {unread}
                  <span className={styles.srOnly}> unread</span>
                </Badge>
              )}
            </NavList.Item>
          )
        })}
      </NavList>

      <div className={styles.panes} data-view={view}>
        <div className={styles.list} ref={listRef}>
          {visible.length === 0 ? (
            <BodySmall color="text-muted" margin="none" dangerouslySetClassName={styles.listEmpty}>
              Nothing in {folderLabel}.
            </BodySmall>
          ) : (
            <ul className={styles.messages} aria-label={`${folderLabel} messages`}>
              {visible.map((message) => (
                <li key={message.id} className={styles.item} data-unread={message.unread || undefined}>
                  <button
                    type="button"
                    id={itemId(message.id)}
                    className={styles.itemButton}
                    aria-current={message.id === selected?.id ? 'true' : undefined}
                    onClick={() => openMessage(message.id)}
                  >
                    <span className={styles.avatar} aria-hidden>
                      {message.initials}
                    </span>
                    <span className={styles.itemText}>
                      <span className={styles.itemTop}>
                        <span className={styles.sender}>
                          {message.unread && <span className={styles.srOnly}>Unread, </span>}
                          {message.folder === 'sent' ? `To ${message.name}` : message.name}
                        </span>
                        <span className={styles.time}>{message.time}</span>
                      </span>
                      <span className={styles.subject}>{message.subject}</span>
                      <span className={styles.snippet}>{message.snippet}</span>
                    </span>
                  </button>
                  <button
                    type="button"
                    className={styles.star}
                    aria-pressed={message.starred}
                    aria-label={`Star “${message.subject}”`}
                    onClick={() => update(message.id, { starred: !message.starred })}
                  >
                    <Star aria-hidden size={16} />
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>

        <article className={styles.reader} aria-label="Message">
          <Button type="button" size="sm" variant="ghost" dangerouslySetClassName={styles.back} onClick={backToList}>
            <ArrowLeft aria-hidden size={14} />
            Back to {folderLabel}
          </Button>
          {selected ? (
            <Stack gap="lg">
              <Stack gap="md">
                <Heading as="h3" fontSize="lg" ref={subjectRef} tabIndex={-1} dangerouslySetClassName={styles.subjectHeading}>
                  {selected.subject}
                </Heading>
                <Stack direction="row" gap="md" align="center">
                  <span className={styles.avatar} aria-hidden>
                    {selected.initials}
                  </span>
                  <Stack gap="none" flex="1">
                    <Text fontSize="sm" fontWeight="semibold">
                      {selected.folder === 'sent' ? `To ${selected.name}` : selected.name}
                    </Text>
                    <Text fontSize="xs" color="text-muted">
                      {selected.address} · {selected.time}
                    </Text>
                  </Stack>
                </Stack>
              </Stack>
              <Stack gap="md">
                {selected.body.map((paragraph) => (
                  <Body key={paragraph} fontSize="sm" margin="none">
                    {paragraph}
                  </Body>
                ))}
              </Stack>
              {replying ? (
                <Stack as="form" gap="sm" noValidate onSubmit={(event: FormEvent<HTMLFormElement>) => sendReply(event, selected)}>
                  <Field name="reply" invalid={Boolean(replyError)}>
                    <Field.Label>Reply to {selected.name}</Field.Label>
                    <Field.Control ref={replyRef} render={<Textarea rows={4} />} onValueChange={() => setReplyError('')} />
                    {replyError && <Field.Error match>{replyError}</Field.Error>}
                  </Field>
                  <Stack direction="row" gap="sm">
                    <Button type="submit" variant="primary" size="sm">
                      <Send aria-hidden size={14} />
                      Send
                    </Button>
                    <Button type="button" variant="ghost" size="sm" onClick={() => setReplying(false)}>
                      Discard
                    </Button>
                  </Stack>
                </Stack>
              ) : (
                <Stack direction="row" gap="sm" wrap="wrap">
                  <Button
                    type="button"
                    size="sm"
                    onClick={startReply}
                  >
                    <Reply aria-hidden size={14} />
                    Reply
                  </Button>
                  <Button type="button" size="sm" onClick={() => archive(selected)}>
                    <Archive aria-hidden size={14} />
                    {selected.folder === 'archive' ? 'Move to Inbox' : 'Archive'}
                  </Button>
                </Stack>
              )}
            </Stack>
          ) : (
            <BodySmall color="text-muted" margin="none">
              Select a message to read it here.
            </BodySmall>
          )}
        </article>
      </div>
    </section>
  )
}
```

## How it works

- Each row is two real buttons side by side: the message itself (`aria-current` marks the open one) and the star (`aria-pressed`). Unread rows are heavier and carry a dot, and a visually hidden “Unread,” says the same thing to a screen reader. Opening a message marks it read, and the folder counts follow.
- The layout responds to its own width with a container query, not the viewport. Above 34rem the list and the message sit side by side and scroll on their own; below it one pane shows at a time, `view` decides which, and a Back button returns to the list. On a phone the folders stay on one row: only the current folder shows its name, and the others keep theirs visually hidden for screen readers.
- On a phone focus follows the pane that opens: the subject heading when a message opens, the same row on Back, and the next row after Archive. The check is whether the list is still rendered, so the same code does nothing on a wide screen.
- Reply opens an inline form. Sending an empty reply sets `invalid` on the `Field` and shows a `Field.Error`; a real reply closes the form with a success toast.

## App-owned CSS

`examples/recipes/email-inbox.module.css`:

```css
.root {
  container-type: inline-size;
  overflow: hidden;
  background-color: var(--ds-color-bg);
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-xl);
}

.folders {
  padding: var(--ds-space-md);
  background-color: var(--ds-color-bg-subtle);
  border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);

  /* NavList stacks its items; the folders run along the top instead */
  & > ul {
    flex-direction: row;
    flex-wrap: wrap;
    gap: var(--ds-space-xs);
  }

  & button {
    gap: var(--ds-space-sm);
    padding: var(--ds-space-sm) var(--ds-space-md);
    white-space: nowrap;
  }
}

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

.panes {
  display: grid;
}

.list {
  min-width: 0;
}

.listEmpty {
  padding: var(--ds-space-lg);
}

.item {
  position: relative;
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  align-items: start;
  border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}

.itemButton {
  display: grid;
  min-width: 0;
  grid-template-columns: auto minmax(0, 1fr);
  gap: var(--ds-space-md);
  padding: var(--ds-space-md) 0 var(--ds-space-md) var(--ds-space-lg);
  font: inherit;
  color: inherit;
  text-align: left;
  background: transparent;
  border: none;
  cursor: pointer;

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

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

/* The selected row: a tint and an accent edge, not color alone */
.item:has([aria-current='true']) {
  background-color: color-mix(in srgb, var(--ds-color-accent-subtle) 70%, transparent);
  box-shadow: inset var(--ds-border-width-md) 0 0 var(--ds-color-accent);
}

.avatar {
  display: inline-grid;
  flex-shrink: 0;
  place-items: center;
  inline-size: var(--ds-control-height-md);
  block-size: var(--ds-control-height-md);
  font-size: var(--ds-font-size-xs);
  font-weight: var(--ds-font-weight-semibold);
  color: var(--ds-color-accent-text);
  background-color: var(--ds-color-accent-subtle);
  border-radius: var(--ds-border-radius-circle);
}

.itemText {
  display: grid;
  grid-template-columns: minmax(0, 1fr);
  min-width: 0;
  font-size: var(--ds-font-size-sm);
  line-height: var(--ds-line-height-body);
}

.itemTop {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: var(--ds-space-md);
}

.sender,
.subject,
.snippet {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.sender {
  flex: 1;
  min-width: 0;
}

.time {
  flex-shrink: 0;
  font-size: var(--ds-font-size-xs);
  color: var(--ds-color-text-muted);
}

.snippet {
  color: var(--ds-color-text-muted);
}

/* Unread rows: heavier sender and subject, plus a dot (the hidden "Unread" names it) */
.item[data-unread] {
  & .sender,
  & .subject {
    font-weight: var(--ds-font-weight-semibold);
  }

  & .sender::before {
    content: '';
    display: inline-block;
    margin-right: var(--ds-space-sm);
    vertical-align: middle;
    inline-size: var(--ds-space-md);
    block-size: var(--ds-space-md);
    background-color: var(--ds-color-accent);
    border-radius: var(--ds-border-radius-circle);
  }

  & .time {
    color: var(--ds-color-accent-text);
  }
}

.star {
  display: grid;
  place-items: center;
  margin: var(--ds-space-md) var(--ds-space-md) 0 0;
  inline-size: var(--ds-control-height-sm);
  block-size: var(--ds-control-height-sm);
  color: var(--ds-color-text-muted);
  background: transparent;
  border: none;
  border-radius: var(--ds-border-radius-circle);
  cursor: pointer;

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

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

  &[aria-pressed='true'] {
    color: var(--ds-color-warning);

    & svg {
      fill: currentColor;
    }
  }
}

.reader {
  display: grid;
  align-content: start;
  gap: var(--ds-space-lg);
  min-width: 0;
  padding: var(--ds-space-lg);
}

.subjectHeading:focus {
  outline: none;
}

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

.back {
  justify-self: start;
}

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

/* Narrow: one pane at a time, and the folders keep one row by showing
   only the current folder's name (the others keep theirs for screen readers) */
@container (width < 34rem) {
  .folders > ul {
    flex-wrap: nowrap;
  }

  .folders button:not([aria-current]) .folderLabel {
    position: absolute;
    inline-size: var(--ds-space-xxs);
    block-size: var(--ds-space-xxs);
    overflow: hidden;
    clip-path: inset(50%);
    white-space: nowrap;
  }

  .panes[data-view='list'] .reader,
  .panes[data-view='message'] .list {
    display: none;
  }
}

/* Wide: list and message side by side, each scrolling on its own */
@container (width >= 34rem) {
  .panes {
    grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr);
    block-size: 30rem;
  }

  .list,
  .reader {
    overflow-y: auto;
  }

  .list {
    border-right: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  }

  .back {
    display: none;
  }
}

@media (prefers-reduced-motion: no-preference) {
  .itemButton,
  .star {
    transition: background-color var(--ds-duration-fast) var(--ds-easing-standard);
  }
}
```
