# Alert and toast

Tells people about something that affects their work: an Alert stays in the page, a toast confirms what just happened and leaves on its own.

Status: Stable. Group: Feedback.

## When to use

- Alert: a condition on this page, such as a paused calendar sync or a project that is read-only.
- Toast: the result of an action, such as Task moved to Done, with an optional Undo.
- Toast in error: something failed in the background; it stays until dismissed.
- Two files: Alert.tsx for Alert, Toast.tsx for toast(), dismissToast() and the Toaster. Copy only Alert.tsx if a page never toasts.
- While a Modal or Drawer is open, toast() waits and shows the toast when that dialog closes: the dialog makes the rest of the page inert, so a toast shown over it could not be reached. The id is still returned at once.

## When not to use

- The error belongs to one field. Use the error state of Input instead.
- People must decide before they can go on. Use Modal instead.
- It is a one-word state on an item. Use Badge instead.

## Scenarios

### Calendar sync paused

The calendar page shows an info Alert above the week: Calendar sync is paused, with a Reconnect button. It stays until the sync works again, because the page is wrong without it.

### Task moved

Dragging a task to Done shows a success toast at the bottom right with Undo. It leaves after 5 seconds, or stays while the pointer rests on it.

## Do and avoid

- Do: Lead with what happened in the title: Calendar sync is paused.
- Avoid: Title it Warning or Error and explain below.
- Do: Offer the next step as an action: Reconnect, Undo.
- Avoid: Put the only way to fix a problem in a toast that disappears.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `tone` | `'neutral' \| 'info' \| 'success' \| 'warning' \| 'error'` | `'neutral'` | Sets the fill and the icon. |
| `title` | `string` |  | Required. What happened, in a few words. |
| `description` | `ReactNode` |  | One or two sentences on why it matters or what to do. |
| `action` | `ReactNode` |  | Alert: buttons under the text, such as a small secondary Button. |
| `onDismiss` | `() => void` |  | Alert: shows a close button and is called when it is pressed. |
| `dismissLabel` | `string` | `'Dismiss'` | Accessible name of the close button. |
| `...rest` | `HTMLAttributes<HTMLDivElement>` |  | Alert: any div attribute. Add role="alert" when you insert it after an action. |
| `toast` | `(options: ToastOptions) => string` |  | Shows a toast with title, description, tone, duration and action { label, onClick }; returns its id. |
| `duration` | `number` | `5000` | Toast: ms before it leaves. Errors default to Infinity (stay until dismissed). |
| `dismissToast` | `(id: string) => void` |  | Closes a toast early. |
| `label` | `string` | `'Notifications'` | Toaster: names the toast region. |
| `max` | `number` | `3` | Toaster: toasts shown at once; the oldest leaves first. |

## Anatomy

1. Container (`data-part="root"`): Radius lg, one flat fill in the tone wash step with a hairline in the soft step (no gradient, no coloured edge), 16 px padding, 12 px between icon and text.
2. Icon (`data-part="icon"`): 20 px glyph in the tone strong step. Decorative; the title carries the meaning.
3. Title (`data-part="title"`): Label 13/16 at weight 600 in the tone strong step.
4. Description (`data-part="description"`): Body text in fg, 4 px under the title.
5. Action (`data-part="action"`): Small buttons 8 px under the text.
6. Dismiss (`data-part="dismiss"`): Round 28 px button with a 1 px line-subtle ring and a 16 px cross in icon; the ring darkens on hover.

## Motion

| Interaction | Property | Duration | Easing | From the keyboard |
| --- | --- | --- | --- | --- |
| Alert appears | opacity | base | out | Same, opacity only. |
| Status changes (Alert or toast) | old icon out over the new one: opacity, blur 4 px, scale .8; text blurs in | quick | out | Same, the component is reporting progress. |
| Toast enters | translate 8 px to 0, opacity | base | out | Opacity only, no 8 px rise, when a key press showed it. |
| Stack folds and fans out | translate and scale of every card (older ones peek 10 px, 5 % smaller each) | gentle | spring | Focus inside the stack fans it out the same way. |
| Swipe to dismiss | translate follows the pointer; a flick over 0.11 px/ms or 64 px sends it off, less springs back | gentle | spring | Esc or Dismiss instead; no movement. |
| Toast leaves (timeout, Dismiss or Esc) | opacity | quick | out | Same, opacity only. |

## Accessibility

| Keys | Action |
| --- | --- |
| Tab | Reaches the action and the Dismiss button of an Alert or a toast. |
| Esc | Dismisses the toast that holds focus. |
| Tab into the stack | Fans the toasts out so each one can be read and reached; every timer waits. |

- Toasts are announced politely: the Toaster is a region named Notifications with an aria-live="polite" list.
- An Alert is plain page content. Add role="alert" only when it appears after an action and must interrupt.
- Timers pause on hover and focus, and error toasts stay until dismissed (WCAG 2.2.1).
- A toast asked for while a Modal or Drawer is open appears when it closes, so it is never hidden behind the dialog or unreachable by keyboard.
- Dismissing a toast that holds focus (Esc or Dismiss) moves focus to the next toast still showing; with none left, focus is left where the browser puts it.
- Icons are aria-hidden; the title says what happened.

## Code

### Alert.tsx

```tsx
'use client'
import { useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type Ref } from 'react'

// Nacre Alert: a message in the page about something that affects the work there. Toasts (short notices about
// something that just happened) live in Toast.tsx, so a page with only Alerts does not ship the toast store.
// React plus Tailwind classes only; needs nacre-theme.css. Motion: an Alert fades in (base 240). When its tone or title
// changes in place (Syncing to Synced), the old icon blurs out over the new one (opacity, blur 4 px, scale .8) and the
// text blurs in, quick 160 out, so the change reads as one status moving on. Reduced motion or
// [data-nacre-motion="off"]: the change is instant.

export type AlertTone = 'neutral' | 'info' | 'success' | 'warning' | 'error'

export type AlertProps = Omit<HTMLAttributes<HTMLDivElement>, 'title'> & {
  tone?: AlertTone
  title: string
  description?: ReactNode
  action?: ReactNode
  onDismiss?: () => void
  dismissLabel?: string
  ref?: Ref<HTMLDivElement>
}

// One flat fill in the state's pale wash step with a hairline in its soft step, no gradient. The icon sits in a round chip in the
// soft step; the title uses the state's strong ink.
const washes: Record<AlertTone, string> = {
  neutral: 'bg-neutral-wash ring-1 ring-inset ring-neutral-soft',
  info: 'bg-info-wash ring-1 ring-inset ring-info-soft',
  success: 'bg-success-wash ring-1 ring-inset ring-success-soft',
  warning: 'bg-warning-wash ring-1 ring-inset ring-warning-soft',
  error: 'bg-error-wash ring-1 ring-inset ring-error-soft',
}
const chips: Record<AlertTone, string> = {
  neutral: 'bg-neutral-soft',
  info: 'bg-info-soft',
  success: 'bg-success-soft',
  warning: 'bg-warning-soft',
  error: 'bg-error-soft',
}
const iconTones: Record<AlertTone, string> = {
  neutral: 'text-neutral-strong',
  info: 'text-info-strong',
  success: 'text-success-strong',
  warning: 'text-warning-strong',
  error: 'text-error-strong',
}
// 20 px glyphs on a 20 grid: a circle with i, check or cross, and a triangle with ! for warning.
const CIRCLE = 'M10 2.5a7.5 7.5 0 1 1 0 15a7.5 7.5 0 1 1 0-15'
const glyphs: Record<AlertTone, string> = {
  neutral: `${CIRCLE}M10 9v4.5M10 6.5v.01`,
  info: `${CIRCLE}M10 9v4.5M10 6.5v.01`,
  success: `${CIRCLE}M7 10.25l2 2 4-4.5`,
  warning: 'M10 3l7.5 13H2.5zM10 8.5v3.25M10 14v.01',
  error: `${CIRCLE}M7.75 7.75l4.5 4.5M12.25 7.75l-4.5 4.5`,
}

function ToneIcon({ tone }: { tone: AlertTone }) {
  return (
    <svg aria-hidden="true" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className={`col-start-1 row-start-1 size-5 ${iconTones[tone]}`}>
      <path d={glyphs[tone]} />
    </svg>
  )
}

function DismissButton({ label, onClick }: { label: string; onClick: () => void }) {
  return (
    <button
      type="button"
      data-part="dismiss"
      aria-label={label}
      onClick={onClick}
      className="-my-0.5 -me-1 inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full border border-line-subtle bg-secondary text-icon transition-colors duration-(--nx-dur-quick) ease-out hover:border-line hover:text-icon-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus motion-safe:active:scale-[.97]"
    >
      <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-4">
        <path d="M4 4l8 8M12 4l-8 8" />
      </svg>
    </button>
  )
}

const BLURRED = { opacity: 0, filter: 'blur(4px)', transform: 'scale(.8)' }
const CLEAR = { opacity: 1, filter: 'blur(0px)', transform: 'none' }

function motionOk(el: Element): boolean {
  return !window.matchMedia('(prefers-reduced-motion: reduce)').matches && !el.closest('[data-nacre-motion="off"]')
}

export function Alert({ tone = 'neutral', title, description, action, onDismiss, dismissLabel = 'Dismiss', className = '', ref, ...rest }: AlertProps) {
  const root = useRef<HTMLDivElement | null>(null)
  const icon = useRef<HTMLSpanElement>(null)
  const old = useRef<HTMLSpanElement>(null)
  const text = useRef<HTMLDivElement>(null)
  // Status change: keep the icon that was shown for one blur-out over the new one. A change mid-swap replaces it.
  const key = `${tone}|${title}`
  const [shown, setShown] = useState({ key, tone, n: 0 })
  const [leaving, setLeaving] = useState<AlertTone | null>(null)
  if (shown.key !== key) {
    setShown({ key, tone, n: shown.n + 1 })
    setLeaving(shown.tone !== tone ? shown.tone : null)
  }
  useLayoutEffect(() => {
    const el = root.current
    if (!shown.n || !el) return
    if (!motionOk(el)) return setLeaving(null)
    const opts = { duration: 160, easing: 'cubic-bezier(.23, 1, .32, 1)' }
    old.current?.animate([CLEAR, BLURRED], { ...opts, fill: 'forwards' }).finished.then(() => setLeaving(null), () => {})
    if (old.current) icon.current?.firstElementChild?.animate([BLURRED, CLEAR], opts)
    text.current?.animate([{ opacity: 0, filter: 'blur(4px)' }, { opacity: 1, filter: 'blur(0px)' }], opts)
  }, [shown.n])
  return (
    <div
      ref={(el) => {
        root.current = el
        if (typeof ref === 'function') ref(el)
        else if (ref) ref.current = el
      }}
      data-part="root"
      className={`flex items-start gap-3 rounded-lg p-4 transition-[opacity,background-color] duration-(--nx-dur-base) ease-out starting:opacity-0 ${washes[tone]} ${className}`}
      {...rest}
    >
      <span ref={icon} data-part="icon" aria-hidden="true" className={`grid size-8 shrink-0 place-items-center rounded-full ${chips[tone]} transition-colors duration-(--nx-dur-base) ease-out`}>
        <ToneIcon tone={tone} />
        {leaving && <span ref={old} className="col-start-1 row-start-1 grid"><ToneIcon tone={leaving} /></span>}
      </span>
      <div ref={text} className="flex min-w-0 flex-1 flex-col gap-1 pt-2">
        <p data-part="title" className={`text-label font-[600] ${iconTones[tone]}`}>{title}</p>
        {description && <div data-part="description" className="text-body text-fg">{description}</div>}
        {action && <div data-part="action" className="mt-2 flex flex-wrap gap-2">{action}</div>}
      </div>
      {onDismiss && <DismissButton label={dismissLabel} onClick={onDismiss} />}
    </div>
  )
}
```

### Toast.tsx

```tsx
'use client'
import { useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties, type PointerEvent } from 'react'

// Nacre toast: a short notice about something that just happened, shown by the one <Toaster /> of the app. It ships
// next to Alert.tsx (same tones and icons) but stands alone, so a page that only needs Alert does not carry the toast
// store. React plus Tailwind classes only; needs nacre-theme.css. The Toaster is a popover="manual" region, so it sits
// in the top layer without a portal.
// Stack: the newest toast is in front; up to two older ones peek 10 px above it, each 5 % smaller, showing only their
// edge. Hovering or focusing the stack fans it out into a list (and pauses every timer); leaving folds it back. Every
// position is a transition on translate and scale (gentle 360 on the spring curve), so a new toast or a quick hover
// retargets from where the cards are.
// Motion: a toast rises 8 px and fades in when a pointer or program shows it, and only fades in when a key press did;
// it fades out (quick 160). Swipe it toward the edge to dismiss: it follows the finger, a flick faster than
// 0.11 px/ms or a drag past 64 px sends it off, anything less springs back; dragging the other way meets friction.
// updateToast() changes a toast in place (Saving to Saved): the old icon blurs out over the new one and the text blurs
// in (quick 160 out). Reduced motion or [data-nacre-motion="off"]: nothing moves, the stack still folds and fans.
// Toasts leave after 5 s, errors and loading toasts stay until dismissed or updated, Esc dismisses the focused one.

export type ToastTone = 'neutral' | 'info' | 'success' | 'warning' | 'error' | 'loading'

const iconTones: Record<ToastTone, string> = {
  neutral: 'text-neutral-strong',
  info: 'text-info-strong',
  success: 'text-success-strong',
  warning: 'text-warning-strong',
  error: 'text-error-strong',
  loading: 'text-icon',
}
// 20 px glyphs on a 20 grid, the same as Alert: a circle with i, check or cross, and a triangle with ! for warning.
// Loading is an open arc that turns.
const DISC = 'M10 1.75a8.25 8.25 0 1 1 0 16.5a8.25 8.25 0 1 1 0-16.5'
// Filled shapes with a mark cut out in the card colour: crisp at 20 px where a 1.5 px outline blurs.
const shapes: Record<ToastTone, string> = {
  neutral: DISC,
  info: DISC,
  success: DISC,
  warning: 'M10 2.75l7.5 13.25h-15z',
  error: DISC,
  loading: 'M10 2.5a7.5 7.5 0 1 0 7.5 7.5',
}
const marks: Record<ToastTone, string> = {
  neutral: 'M10 9.25v3.75M10 6.6v.01',
  info: 'M10 9.25v3.75M10 6.6v.01',
  success: 'M6.9 10.2l2.1 2.1 4.2-4.6',
  warning: 'M10 8v3.5M10 13.9v.01',
  error: 'M7.6 7.6l4.8 4.8M12.4 7.6l-4.8 4.8',
  loading: '',
}

// Toast store: module state shared by toast(), updateToast(), dismissToast() and the Toaster (one Toaster per app).
export type ToastOptions = { title: string; description?: string; tone?: ToastTone; duration?: number; action?: { label: string; onClick: () => void } }
type ToastItem = ToastOptions & { id: string; closing: boolean; keyboard: boolean; rev: number }

let items: ToastItem[] = []
let seq = 0
const listeners = new Set<() => void>()
const emit = (next: ToastItem[]) => {
  items = next
  for (const l of listeners) l()
}
const subscribe = (l: () => void) => {
  listeners.add(l)
  return () => {
    listeners.delete(l)
  }
}
const snapshot = () => items

// Toasts asked for while a modal dialog is open; they show when it closes (see toast()).
const pending = new Map<string, ToastOptions>()

function openModalDialog(): Element | null {
  try {
    return typeof document === 'undefined' ? null : document.querySelector('dialog:modal')
  } catch {
    return null
  }
}

/** Shows a toast and returns its id. While a Modal or Drawer is open the toast waits for it to close: the Toaster
 *  sits in the top layer below a later showModal() dialog and is inert behind it, so it could not be seen or reached. */
export function toast(options: ToastOptions): string {
  const id = `nx-toast-${++seq}`
  // Shown from a key press (the focused control matches :focus-visible): fade only, no movement.
  const keyboard = typeof document !== 'undefined' && !!document.activeElement?.matches(':focus-visible')
  pending.set(id, options)
  const show = () => {
    const latest = pending.get(id)
    if (latest && pending.delete(id)) emit([...items, { ...latest, id, closing: false, keyboard, rev: 0 }])
  }
  const modal = openModalDialog()
  if (modal) modal.addEventListener('close', show, { once: true })
  else show()
  return id
}

/** Changes a toast in place, such as Saving changes (loading) to Changes saved (success). Its timer restarts. */
export function updateToast(id: string, options: Partial<ToastOptions>): void {
  const waiting = pending.get(id)
  if (waiting) pending.set(id, { ...waiting, ...options })
  if (items.some((t) => t.id === id && !t.closing)) emit(items.map((t) => (t.id === id ? { ...t, ...options, rev: t.rev + 1 } : t)))
}

/** Starts a toast's exit; it is removed when its fade has finished. A toast still waiting for a dialog is dropped. */
export function dismissToast(id: string): void {
  pending.delete(id)
  if (items.some((t) => t.id === id && !t.closing)) emit(items.map((t) => (t.id === id ? { ...t, closing: true } : t)))
}

/** Dismisses a toast; if focus was inside it, focus moves to the next remaining toast (else it is left as is). */
function dismissFrom(li: HTMLElement | null, id: string) {
  if (li?.contains(document.activeElement)) {
    const all = Array.from(li.parentElement?.querySelectorAll<HTMLElement>('[data-part="toast"][data-state="open"]') ?? [])
    const at = all.indexOf(li)
    const next = all[at + 1] ?? all[at - 1]
    next?.querySelector<HTMLElement>('button')?.focus()
  }
  dismissToast(id)
}

function removeToast(id: string) {
  emit(items.filter((t) => t.id !== id))
}

const PEEK = 10
const GAP = 8
const SWIPE_PX = 64
const SWIPE_VELOCITY = 0.11
const EASE_OUT = 'cubic-bezier(.23, 1, .32, 1)'

function motionOk(el: Element): boolean {
  return !window.matchMedia('(prefers-reduced-motion: reduce)').matches && !el.closest('[data-nacre-motion="off"]')
}

/** Where a card sits: y offset from the bottom of the stack, scale, the clipped-off bottom and whether its text shows. */
type Pos = { y: number; scale: number; clip: number; front: boolean; z: number }

function Glyph({ tone, part }: { tone: ToastTone; part?: string }) {
  return (
    <svg data-part={part} aria-hidden="true" viewBox="0 0 20 20" fill={tone === 'loading' ? 'none' : 'currentColor'} stroke="currentColor" strokeWidth={tone === 'loading' ? 1.5 : tone === 'warning' ? 1.5 : 0} strokeLinecap="round" strokeLinejoin="round" className={`col-start-1 row-start-1 size-5 ${iconTones[tone]} ${tone === 'loading' ? 'motion-safe:animate-spin' : ''}`}>
      <path d={shapes[tone]} />
      {marks[tone] && <path d={marks[tone]} fill="none" stroke="var(--nx-toast)" strokeWidth="1.75" />}
    </svg>
  )
}

function ToastCard({ item, pos, paused, onHeight }: { item: ToastItem; pos: Pos; paused: boolean; onHeight: (id: string, h: number) => void }) {
  const ref = useRef<HTMLLIElement>(null)
  const text = useRef<HTMLDivElement>(null)
  const oldIcon = useRef<HTMLSpanElement>(null)
  const [focus, setFocus] = useState(false)
  const tone = item.tone ?? 'neutral'
  const limit = item.duration ?? (tone === 'error' || tone === 'loading' ? Infinity : 5000)
  const remaining = useRef(limit)
  const at = pos

  // Status change: remember the icon that was shown; it blurs out over the new one.
  const [shown, setShown] = useState({ rev: item.rev, tone })
  const [leaving, setLeaving] = useState<ToastTone | null>(null)
  if (shown.rev !== item.rev) {
    setShown({ rev: item.rev, tone })
    if (shown.tone !== tone) setLeaving(shown.tone)
  }
  useLayoutEffect(() => {
    const el = ref.current
    if (!el || shown.rev === 0) return
    if (!motionOk(el)) return setLeaving(null)
    const opts = { duration: 160, easing: EASE_OUT }
    const blurred = { opacity: 0, filter: 'blur(4px)', transform: 'scale(.8)' }
    const clear = { opacity: 1, filter: 'blur(0px)', transform: 'none' }
    oldIcon.current?.animate([clear, blurred], { ...opts, fill: 'forwards' }).finished.then(() => setLeaving(null), () => {})
    el.querySelector('[data-part="icon"]')?.animate([blurred, clear], opts)
    text.current?.animate([{ opacity: 0, filter: 'blur(4px)' }, { opacity: 1, filter: 'blur(0px)' }], opts)
  }, [shown.rev])

  // An update starts the count again, from its own duration.
  useEffect(() => {
    remaining.current = limit
  }, [item.rev, limit])

  // Count down only while nobody is reading it (stack not hovered, no focus inside).
  useEffect(() => {
    if (item.closing || paused || focus || !Number.isFinite(remaining.current)) return
    const start = Date.now()
    const t = window.setTimeout(() => dismissToast(item.id), remaining.current)
    return () => {
      window.clearTimeout(t)
      remaining.current -= Date.now() - start
    }
  }, [item.closing, item.id, item.rev, paused, focus])

  // Remove after the exit fade; reading the computed duration follows slow motion and reduced motion.
  useEffect(() => {
    if (!item.closing) return
    const el = ref.current
    const ms = el ? parseFloat(getComputedStyle(el).transitionDuration) * 1000 || 0 : 0
    const t = window.setTimeout(() => removeToast(item.id), ms)
    return () => window.clearTimeout(t)
  }, [item.closing, item.id])

  // The stack needs each card's height to place the others.
  useLayoutEffect(() => {
    const el = ref.current
    if (!el) return
    onHeight(item.id, el.offsetHeight)
    const ro = new ResizeObserver(() => onHeight(item.id, el.offsetHeight))
    ro.observe(el)
    return () => ro.disconnect()
  }, [item.id, onHeight])

  // Swipe to dismiss, toward the end edge. One pointer at a time; the card follows it with no transition.
  const drag = useRef<{ pointer: number; x: number; t: number; dx: number } | null>(null)
  const setSwipe = (v: string) => ref.current?.style.setProperty('--swipe', v)
  const down = (e: PointerEvent<HTMLLIElement>) => {
    if (drag.current || item.closing || e.button !== 0 || (e.target as Element).closest('button, a')) return
    drag.current = { pointer: e.pointerId, x: e.clientX, t: performance.now(), dx: 0 }
    e.currentTarget.setPointerCapture(e.pointerId)
  }
  const move = (e: PointerEvent<HTMLLIElement>) => {
    const d = drag.current
    if (!d || e.pointerId !== d.pointer) return
    d.dx = e.clientX - d.x
    if (Math.abs(d.dx) > 2) e.currentTarget.setAttribute('data-swiping', '')
    // Toward the edge it follows 1:1; the other way it meets friction and slows the further it goes.
    setSwipe(`${d.dx >= 0 ? d.dx : -Math.sqrt(-d.dx) * 2}px`)
  }
  const up = (e: PointerEvent<HTMLLIElement>) => {
    const d = drag.current
    if (!d || e.pointerId !== d.pointer) return
    drag.current = null
    e.currentTarget.removeAttribute('data-swiping')
    const velocity = Math.abs(d.dx) / Math.max(1, performance.now() - d.t)
    if (d.dx > 4 && (d.dx >= SWIPE_PX || velocity > SWIPE_VELOCITY)) {
      setSwipe('calc(100% + 2rem)')
      dismissToast(item.id)
    } else setSwipe('0px')
  }

  // The clip reaches 80 px past the card on every side (so the shadow shows) except the bottom of a folded card.
  const style = { '--y': `${at.y}px`, '--s': at.scale, '--clip': at.clip > 0 ? `${at.clip}px` : '-80px', zIndex: at.z } as CSSProperties
  const entry = item.keyboard ? 'starting:opacity-0' : 'starting:opacity-0 starting:[translate:0_8px]'
  return (
    <li
      ref={ref}
      data-part="toast"
      data-state={item.closing ? 'closing' : 'open'}
      data-front={at.front || undefined}
      style={style}
      onFocus={() => setFocus(true)}
      onBlur={(e) => {
        if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocus(false)
      }}
      onKeyDown={(e) => {
        if (e.key !== 'Escape') return
        // the toast takes this Esc: a page or layer around it must not also close
        e.preventDefault()
        dismissFrom(ref.current, item.id)
      }}
      onPointerDown={down}
      onPointerMove={move}
      onPointerUp={up}
      onPointerCancel={up}
      className={`absolute inset-x-0 bottom-0 flex touch-pan-y items-start gap-3 rounded-lg border border-line-subtle bg-toast p-4 text-fg shadow-3 select-none origin-top [translate:var(--swipe,0px)_var(--y)] [scale:var(--s)] [clip-path:inset(-80px_-80px_var(--clip)_-80px)] ${
        item.closing
          ? `opacity-0 [transition:opacity_var(--nx-dur-quick)_var(--nx-ease-out),translate_var(--nx-dur-quick)_var(--nx-ease-out)]`
          : `${entry} [transition:opacity_var(--nx-dur-base)_var(--nx-ease-out),translate_var(--nx-dur-gentle)_var(--nx-ease-spring),scale_var(--nx-dur-gentle)_var(--nx-ease-spring),clip-path_var(--nx-dur-gentle)_var(--nx-ease-out)] data-swiping:transition-none data-swiping:select-none`
      }`}
    >
      <span className="mt-px grid size-5 shrink-0">
        <Glyph tone={tone} part="icon" />
        {leaving && <span ref={oldIcon} className="col-start-1 row-start-1 grid"><Glyph tone={leaving} /></span>}
      </span>
      <div ref={text} className={`flex min-w-0 flex-1 flex-col gap-1 transition-opacity duration-(--nx-dur-quick) ease-out ${at.front ? '' : 'opacity-0'}`}>
        <p data-part="title" className="text-label font-[600] text-fg-strong">{item.title}</p>
        {item.description && <p data-part="description" className="text-caption text-fg-muted">{item.description}</p>}
        {item.action && (
          <button
            type="button"
            data-part="action"
            onClick={() => {
              item.action!.onClick()
              dismissFrom(ref.current, item.id)
            }}
            className="mt-1.5 inline-flex h-8 cursor-pointer items-center self-start rounded-full bg-sunken px-3.5 text-label font-[600] text-fg-strong transition-colors duration-(--nx-dur-quick) ease-out hover:bg-[color-mix(in_oklab,var(--nx-fg)_7%,var(--nx-sunken))] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus"
          >
            {item.action.label}
          </button>
        )}
      </div>
      <button
        type="button"
        data-part="dismiss"
        aria-label="Dismiss"
        onClick={() => dismissFrom(ref.current, item.id)}
        className="-my-0.5 -me-1 inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full border border-line-subtle bg-secondary text-icon transition-colors duration-(--nx-dur-quick) ease-out hover:border-line hover:text-icon-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus motion-safe:active:scale-[.97]"
      >
        <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-4">
          <path d="M4 4l8 8M12 4l-8 8" />
        </svg>
      </button>
    </li>
  )
}

export type ToasterProps = { label?: string; max?: number; className?: string }

/** Renders the toasts at the bottom end of the viewport. Mount one, inside [data-nacre] or your themed root. */
export function Toaster({ label = 'Notifications', max = 3, className = '' }: ToasterProps) {
  const raw = useSyncExternalStore(subscribe, snapshot, snapshot)
  const ref = useRef<HTMLElement>(null)
  const [heights, setHeights] = useState<Record<string, number>>({})
  const [hover, setHover] = useState(false)
  const [focus, setFocus] = useState(false)
  const onHeight = useCallback((id: string, h: number) => setHeights((m) => (m[id] === h ? m : { ...m, [id]: h })), [])

  useEffect(() => {
    const el = ref.current
    if (el && !el.matches(':popover-open')) el.showPopover()
  }, [])

  // More than max: the oldest open toasts leave first. Worked out in render so a fourth card never shows open; the
  // card's own exit effect then removes it from the store.
  const open = raw.filter((t) => !t.closing)
  const excess = new Set(open.slice(0, Math.max(0, open.length - max)).map((t) => t.id))
  const list = raw.map((t) => (excess.has(t.id) ? { ...t, closing: true } : t))
  const expanded = (hover || focus) && open.length > 0

  // Newest first: index 0 is the front card. A closing card keeps its place while it fades, then the rest move up.
  const order = [...list].reverse()
  const h = (id: string) => heights[id] ?? 0
  const frontH = order.length ? h(order[0].id) : 0
  const positions = new Map<string, Pos>()
  let above = 0
  order.forEach((t, i) => {
    const own = h(t.id)
    positions.set(
      t.id,
      expanded || i === 0
        ? { y: -above, scale: 1, clip: 0, front: true, z: max + 1 - i }
        : { y: own - frontH - i * PEEK, scale: 1 - i * 0.05, clip: Math.max(0, own - frontH), front: false, z: max + 1 - i },
    )
    above += own + GAP
  })
  const stackH = expanded ? Math.max(0, above - GAP) : frontH

  return (
    <section
      ref={ref}
      popover="manual"
      aria-label={label}
      data-part="region"
      className={`inset-auto end-4 bottom-4 m-0 w-[min(22rem,calc(100%_-_2rem))] overflow-visible border-0 bg-transparent p-0 text-fg ${className}`}
    >
      <ol
        aria-live="polite"
        data-expanded={expanded || undefined}
        style={{ height: stackH }}
        onPointerEnter={(e) => e.pointerType === 'mouse' && setHover(true)}
        onPointerLeave={(e) => e.pointerType === 'mouse' && setHover(false)}
        onFocus={() => setFocus(true)}
        onBlur={(e) => {
          if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocus(false)
        }}
        className="relative m-0 list-none p-0"
      >
        {list.map((t) => (
          <ToastCard key={t.id} item={t} pos={positions.get(t.id)!} paused={expanded} onHeight={onHeight} />
        ))}
      </ol>
    </section>
  )
}
```

## HTML

The default example as plain HTML, for any stack. Needs nacre-theme.css.

```html
<div data-part="root" class="flex items-start gap-3 rounded-lg p-4 transition-[opacity,background-color] duration-(--nx-dur-base) ease-out starting:opacity-0 bg-info-wash ring-1 ring-inset ring-info-soft ">
  <span data-part="icon" aria-hidden="true" class="grid size-8 shrink-0 place-items-center rounded-full bg-info-soft transition-colors duration-(--nx-dur-base) ease-out">
    <svg aria-hidden="true" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="col-start-1 row-start-1 size-5 text-info-strong">
      <path d="M10 2.5a7.5 7.5 0 1 1 0 15a7.5 7.5 0 1 1 0-15M10 9v4.5M10 6.5v.01"></path>
    </svg>
  </span>
  <div class="flex min-w-0 flex-1 flex-col gap-1 pt-2">
    <p data-part="title" class="text-label font-[600] text-info-strong">Calendar sync is paused</p>
    <div data-part="description" class="text-body text-fg">Reconnect your calendar to see new meetings in Nacre.</div>
  </div>
</div>
```

## Related

- [Badge](https://enxm.me/services/design-systems/nacre/components/badge)
- [Progress and steps](https://enxm.me/services/design-systems/nacre/components/progress)
- [Modal](https://enxm.me/services/design-systems/nacre/components/modal)
