# Notifications

Four ways to tell someone something, from a toast that confirms and leaves to a dialog that stops everything. Nacre picks the quietest one that still gets read.

## Pick the quietest signal that works

Start at the top of this list and move down only when the message needs more attention than the one above can give.

| Signal | Use it for | How long it stays | Interrupts |
| --- | --- | --- | --- |
| Badge | A count or a state on something already on screen: 3 unread, At risk. | As long as it is true | No |
| Toast | Confirming what the person just did, with Undo: File archived. | 5 s, errors until dismissed | No |
| Alert | A problem or news about this page that needs action: Calendar sync paused. | Until fixed or dismissed | No |
| Modal | A decision that must happen before anything else: Delete this project? | Until answered | Yes |

## Toasts confirm and undo

A toast answers the action that caused it, so it shows near where attention already is and leaves on its own. Put Undo in it instead of asking Are you sure before a reversible action.

Errors stay until dismissed, because a failure read too late is a failure missed. Only one Toaster is mounted per app; toasts asked for while a dialog is open wait until it closes.

- Do: Use the past tense of what happened: Q4 roadmap.pdf archived.
- Avoid: Say Success! or anything that needs the context to make sense.

### Demo: Archive with undo

Archive a file, then press Undo in the toast.

```tsx
'use client'
import { useEffect, useRef, useState } from 'react'
import { FileText } from 'lucide-react'
import { Button } from '@/nacre/components/Button'
import { toast, Toaster } from '@/nacre/components/Toast'

// A toast confirms something the person just did and offers Undo. It never carries the only copy of important
// information: success toasts leave after 5 s, error toasts stay until dismissed. The Toaster is mounted once per app;
// here the demo mounts it. The archived row takes focus with it, so focus moves to the next row; the demo reset goes
// away too, so focus moves to the first row.

const FILES = [
  { id: 'roadmap', name: 'Q4 roadmap.pdf', meta: 'Ana Ribeiro, 2.4 MB' },
  { id: 'brief', name: 'Onboarding brief.docx', meta: 'Ben Okafor, 180 KB' },
  { id: 'notes', name: 'Billing v2 notes.md', meta: 'Chen Wei, 12 KB' },
]

export function ToastDemo() {
  const [files, setFiles] = useState(FILES)
  const buttons = useRef<Record<string, HTMLButtonElement | null>>({})
  const list = useRef<HTMLUListElement>(null)
  const focusAfter = useRef<string | null>(null)
  useEffect(() => {
    const id = focusAfter.current
    if (!id) return
    focusAfter.current = null
    if (id === 'list') list.current?.focus()
    else buttons.current[id]?.focus()
  }, [files])
  const archive = (id: string) => {
    const file = FILES.find((f) => f.id === id)!
    const next = files[files.findIndex((f) => f.id === id) + 1] ?? files[files.findIndex((f) => f.id === id) - 1]
    focusAfter.current = next ? next.id : 'list'
    setFiles((current) => current.filter((f) => f.id !== id))
    toast({
      title: `${file.name} archived`,
      description: 'It stays in Archive for 30 days.',
      tone: 'success',
      action: { label: 'Undo', onClick: () => setFiles((current) => FILES.filter((f) => f.id === id || current.some((c) => c.id === f.id))) },
    })
  }
  return (
    <div className="flex w-full max-w-[28rem] flex-col gap-4">
      <ul ref={list} tabIndex={-1} aria-label="Recent files" className="m-0 flex flex-col gap-2 p-0 outline-none">
        {files.map((f) => (
          <li key={f.id} className="flex list-none items-center gap-3 rounded-sm bg-surface px-3 py-2 shadow-1">
            <FileText size={16} aria-hidden="true" className="shrink-0 text-icon-muted" />
            <span className="flex min-w-0 flex-1 flex-col">
              <span className="truncate text-body text-fg-strong">{f.name}</span>
              <span className="text-caption text-fg-muted">{f.meta}</span>
            </span>
            <Button ref={(el) => { buttons.current[f.id] = el }} variant="ghost" size="sm" aria-label={`Archive ${f.name}`} onClick={() => archive(f.id)}>Archive</Button>
          </li>
        ))}
        {files.length === 0 && <li className="list-none text-body text-fg-muted">Everything is archived.</li>}
      </ul>
      <div className="flex flex-wrap gap-2">
        <Button variant="secondary" onClick={() => toast({ title: 'Upload failed', description: 'Design review.fig is larger than 200 MB.', tone: 'error' })}>Try a failed upload</Button>
        {files.length < FILES.length && <Button variant="ghost" onClick={() => { focusAfter.current = FILES[0].id; setFiles(FILES) }}>Reset the demo</Button>}
      </div>
      <Toaster label="Demo notifications" />
    </div>
  )
}
```

## Alerts stay until fixed

An Alert lives in the page, above the thing it is about. It names the problem and its consequence, and carries the fix as its action. When the fix works, it becomes a short success message that can be dismissed.

### Demo: Calendar sync

Press Reconnect. Dismiss the info alert and bring it back.

```tsx
'use client'
import { useEffect, useRef, useState } from 'react'
import { Alert } from '@/nacre/components/Alert'
import { Button } from '@/nacre/components/Button'

// An Alert sits in the page next to what it is about and stays until the problem is gone or the person dismisses it.
// The fix goes in the Alert as its action; when the fix works, the Alert turns into a short success message and
// focus moves to it, because the button that was pressed is gone. Focus reads it, so it has no live role as well
// (that would announce it twice).

type Sync = 'paused' | 'working' | 'back'

export function AlertDemo() {
  const [sync, setSync] = useState<Sync>('paused')
  const [shared, setShared] = useState(true)
  const done = useRef<HTMLDivElement>(null)
  useEffect(() => {
    if (sync !== 'working') return
    const t = setTimeout(() => setSync('back'), 1200)
    return () => clearTimeout(t)
  }, [sync])
  useEffect(() => {
    if (sync === 'back') done.current?.focus()
  }, [sync])
  return (
    <div className="flex w-full max-w-[30rem] flex-col gap-3">
      {sync === 'back' ? (
        <Alert ref={done} tabIndex={-1} tone="success" className="outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus" title="Calendar sync is back on" description="12 events from Google Calendar were added to this week." onDismiss={() => setSync('paused')} dismissLabel="Dismiss and reset the demo" />
      ) : (
        <Alert
          tone="warning"
          title="Calendar sync paused"
          description="Nacre has not reached Google Calendar since 09:40. New events will not show until it reconnects."
          action={<Button size="sm" variant="secondary" loading={sync === 'working'} onClick={() => setSync('working')}>Reconnect</Button>}
        />
      )}
      {shared ? (
        <Alert tone="info" title="Ben Okafor shared Onboarding brief with you" description="You can comment. Ben gets a note when you do." onDismiss={() => setShared(false)} />
      ) : (
        <div><Button variant="ghost" size="sm" onClick={() => setShared(true)}>Show the dismissed alert again</Button></div>
      )}
    </div>
  )
}
```

## The inbox keeps the rest

Mentions, assignments and comments do not need to interrupt. They collect in the inbox, a badge on its icon says how many are new, and opening one marks it read.

### Demo: Inbox

Open a notification, or mark all as read.

```tsx
'use client'
import { useRef, useState } from 'react'
import { Avatar } from '@/nacre/components/Avatar'
import { Badge } from '@/nacre/components/Badge'
import { Button } from '@/nacre/components/Button'

// The inbox holds what can wait: mentions, assignments, comments. A count badge says how many are new; opening one
// marks it read. Nothing here interrupts. The count sits in a polite live region, and when Mark all as read (or the
// demo reset) goes away, focus moves to the Inbox heading.

const ITEMS = [
  { id: 'n1', who: 'Chen Wei', what: 'mentioned you in Billing v2: can we ship the proration fix before the 12th?', when: '10:04', unread: true },
  { id: 'n2', who: 'Farah Haddad', what: 'assigned you Write the November release notes.', when: '09:31', unread: true },
  { id: 'n3', who: 'Eli Moss', what: 'commented on Help center refresh: 14 articles left to review.', when: '08:52', unread: true },
  { id: 'n4', who: 'Dara Novak', what: 'closed Fix the invite link expiry.', when: 'Fri', unread: false },
]

export function InboxDemo() {
  const [items, setItems] = useState(ITEMS)
  const heading = useRef<HTMLHeadingElement>(null)
  const unread = items.filter((i) => i.unread).length
  return (
    <div data-testid="inbox-demo" className="flex w-full max-w-[30rem] flex-col gap-3 rounded-lg bg-surface p-4 shadow-1">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          <h3 ref={heading} tabIndex={-1} className="rounded-xs text-heading-3 text-fg-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">Inbox</h3>
          <span role="status">
            {unread > 0 ? <Badge tone="info" size="sm">{unread} unread</Badge> : <Badge tone="success" size="sm" dot>All caught up</Badge>}
          </span>
        </div>
        <span className="flex gap-1">
          {unread > 0 && <Button variant="ghost" size="sm" onClick={() => { setItems((l) => l.map((i) => ({ ...i, unread: false }))); heading.current?.focus() }}>Mark all as read</Button>}
          {unread === 0 && <Button variant="ghost" size="sm" onClick={() => { setItems(ITEMS); heading.current?.focus() }}>Reset the demo</Button>}
        </span>
      </div>
      <ul className="m-0 flex flex-col p-0">
        {items.map((i, n) => (
          <li key={i.id} className={`list-none ${n > 0 ? 'border-t border-line-subtle' : ''}`}>
            <button
              type="button"
              onClick={() => setItems((l) => l.map((x) => (x.id === i.id ? { ...x, unread: false } : x)))}
              className="flex w-full cursor-pointer items-start gap-3 rounded-sm px-2 py-3 text-start hover:bg-row-hover"
            >
              <Avatar name={i.who} size="sm" />
              <span className="flex min-w-0 flex-1 flex-col gap-0.5">
                <span className="text-body text-fg"><span className="text-fg-strong">{i.who}</span> {i.what}</span>
                <span className="text-caption text-fg-muted">{i.when}</span>
              </span>
              {i.unread && <span className="mt-2 size-2 shrink-0 rounded-full bg-info" aria-label="Unread" role="img" />}
            </button>
          </li>
        ))}
      </ul>
    </div>
  )
}
```

## Built with

- [Button](https://enxm.me/services/design-systems/nacre/components/button)
- [Badge](https://enxm.me/services/design-systems/nacre/components/badge)
- [Avatar](https://enxm.me/services/design-systems/nacre/components/avatar)
- [Alert and toast](https://enxm.me/services/design-systems/nacre/components/alert)
