# GlassToaster

> News that arrives on the page: the page leans in towards the place where a toast is about to stand, the toast comes up out of it, and a ripple runs out as the page lets go. Toasts pile up behind the newest one; press the pile and it opens into a list under a header of glass buttons that shows less or clears it. Each toast is swiped away.

```tsx
import { HugeiconsIcon } from '@hugeicons/react'
import { Notification01Icon } from '@hugeicons/core-free-icons'
import { useEffect, useRef, useState } from 'react'

import { GlassButton } from '@/components/liquid-glass'
import { createToaster, GlassToaster } from '@/components/liquid-glass/glass-toast'

const COLS = 13
const ROWS = 7

/** 1 around the middle of the grid, falling to 0 at its edge. */
const fade = (col: number, row: number) => {
  const distance = Math.hypot((col - (COLS - 1) / 2) / (COLS / 2), (row - (ROWS - 1) / 2) / (ROWS / 2))
  return Math.min(1, Math.max(0, (1 - distance) / 0.45))
}

const NEWS = [
  { title: 'Event created', description: 'Friday, June 12 at 10:00', action: 'Undo' },
  { title: 'Message sent', description: 'To the whole design team', action: 'Undo' },
  { title: 'Hollis joined the board', description: 'They can edit the launch plan', action: 'Open' },
  { title: 'Invoice sent', description: 'Inès Moreau · $240.00', action: 'View' },
]

// Press it: at the top right of the screen the page leans in, a toast comes up out of it and a
// ripple runs out as the page lets go. Press again and the toasts pile up behind the newest.
// Press the pile and it opens into a list under its header: Show less folds it back, and the
// cross opens into Clear under the pointer. Swipe a toast down, close it from its
// corner, or wait: each leaves by itself after five seconds.
// The toaster here is the demo's own (`createToaster`), so its toasts do not mix with the page's.
// In an app, place `<GlassToaster />` once and call `toast()` from anywhere.
// Behind the button, only the Press demo's fine grid on the page's own colour, centred on it:
// plain DOM, every cell draws its own top and left line, fainter towards the edge.
export default function Demo() {
  const [toast] = useState(() => createToaster())
  const count = useRef(0)
  // The toasts leave with the demo.
  useEffect(() => () => void toast.dismiss(), [toast])
  const notify = () => {
    const news = NEWS[count.current++ % NEWS.length]
    toast(news.title, { description: news.description, action: { label: news.action } })
  }
  return (
    <div className="relative isolate flex h-[22rem] w-full max-w-xl items-center justify-center">
      <div aria-hidden className="absolute top-1/2 left-1/2 -z-10 grid -translate-x-1/2 -translate-y-1/2 grid-cols-[repeat(13,40px)]">
        {Array.from({ length: COLS * ROWS }, (_, i) => (
          <span key={i} className="relative size-10" style={{ opacity: fade(i % COLS, Math.floor(i / COLS)) }}>
            <span className="absolute inset-x-0 top-0 h-px bg-black/10 dark:bg-white/10" />
            <span className="absolute inset-y-0 left-0 w-px bg-black/10 dark:bg-white/10" />
          </span>
        ))}
      </div>
      <GlassButton size="lg" icon={<HugeiconsIcon icon={Notification01Icon} />} iconPosition="start" onClick={notify}>
        Notify
      </GlassButton>
      <GlassToaster toaster={toast} title="Notifications" />
    </div>
  )
}
```

**Use it for**

- News that asks nothing of the visitor, or offers one way back: saved, sent, copied, archived with an Undo.
- The outcome of something that took a moment: an upload, a save over a slow connection. One toast loads, then turns into the result.
- Something nobody pressed: a message from someone else, a payment that came in.

**Not for**

- A question that must be answered: use Dialog with `alert`. A toast leaves by itself.
- What is wrong with one field of a form: say it beside the field, where it stays.
- Every row checked or every key typed: the page leaning in marks a moment, and a moment that repeats is noise. Keep such toasts rare, or give the toaster `gather={false}`.

```bash
npx shadcn@latest add https://liquidglass.onemorethink.dev/r/toast.json
```

> The behaviour (the queue and its timers, the top layer, the stack's measures, the swipe, F6 and Escape, the announcements to screen readers) comes from UI SDK, so Toast needs `@ui-sdk/core` and `@ui-sdk/react`. The install command adds them at the exact version this was built on: UI SDK is in beta and its API may still change.

## Usage

```tsx
import { GlassToaster, toast } from '@/components/liquid-glass/glass-toast'

// Once, near the root of your app.
<GlassToaster />

// From anywhere: a component, a server action's callback, plain code.
toast('Event created')
toast.success('Changes saved', { description: 'Friday at 10:00' })
toast('Message archived', { action: { label: 'Undo', onAction: restore } })
```

Place `GlassToaster` once and call `toast()` from anywhere; it returns the toast's id. As a toast arrives, the page around where it will stand is drawn in towards that place for a third of a second, softening in a ring around it. Half way through, the toast comes up out of it: it fades up as it grows from 80%, lands a little past its size and settles, on the spring Dialog's pane rises on. Then the page lets go and one crest runs outwards, leaving it flat. The toast wears the glass of every surface that opens over the page (Dialog's pane, a Popover, a Menu): a 60% tint, a 10 px frost and a rim that bends the page it covers, and its text follows the tone of the glass.

The stack stands at the top right of the screen unless you place it elsewhere (`side`, `align`). Newer toasts come in front: the ones behind stand as tall as the newest, a little smaller each, and show 10 px under it. It looks the same wherever it stands, the newest on top and the rest under it: at the bottom of the screen the stack stands on its place, so the newest is lifted by the ones under it. Press the pile, or move the keyboard's focus into it, and it opens into a list, as a notification centre does: each toast under the one before it, below a header with the list's name (`title`) and two small glass buttons. The header's row only frosts the page behind it, with the toasts' own blur: no tint, no line, no bend and no edge. The frost has nowhere it begins: it grows from nothing well past the row to twice the toasts' blur under the name, so the name reads over whatever the list covers and no card stands behind it. Show less folds the list back into the pile. The other is a cross that opens into Clear while the pointer is on it, as Show less folds into an arrow, and dismisses every toast. The words are yours to translate (`labels`), `expanded` keeps the stack a list, and a list left with one toast closes by itself. The timers wait while the pointer or focus is in the stack. A toast leaves after five seconds (`duration`, in ms, on one toast or on a toaster made with `createToaster`; `Infinity` keeps it). It can be swiped towards the edge it stands on or the end it is aligned to, the glass following the finger over a picture of the page it already has, and the close button in its corner shows while the pointer is on it. However a toast is closed, it goes where it stands, as a notification does: within a seventh of a second what it says blurs away and the glass fades as it grows a little, so the page shows sharp through it before it has gone. A swiped one goes the same way on its way off to the side.

## Types and promises

`toast.success`, `.info`, `.warning`, `.error` and `.loading` set the toast's type: it brings its own icon, and decides how the toast is announced (an error interrupts, the others wait for a pause). `toast.promise()` shows a loading toast and turns the same toast into the result when the promise settles; each message is a string, or options with a description and an action. A loading toast stays until it is updated or dismissed.

### Every type, and a promise

```tsx
import { useEffect, useState } from 'react'

import { GlassButton } from '@/components/liquid-glass'
import { createToaster, GlassToaster } from '@/components/liquid-glass/glass-toast'

const COLS = 13
const ROWS = 7

/** 1 around the middle of the grid, falling to 0 at its edge. */
const fade = (col: number, row: number) => {
  const distance = Math.hypot((col - (COLS - 1) / 2) / (COLS / 2), (row - (ROWS - 1) / 2) / (ROWS / 2))
  return Math.min(1, Math.max(0, (1 - distance) / 0.45))
}

/** An upload that takes two seconds, and fails every second time. */
let uploads = 0
const upload = () => new Promise<void>((resolve, reject) => setTimeout(++uploads % 2 ? resolve : () => reject(new Error('Network error')), 2000))

// Each type brings its own icon, and says how the toast is announced: an error interrupts a
// screen reader, the others wait for a pause. `toast.promise` shows one toast that loads, then
// turns into the result in place: saved the first time, failed the second, with a way to retry.
// Behind the buttons, only the Press demo's fine grid on the page's own colour, centred on them:
// plain DOM, every cell draws its own top and left line, fainter towards the edge.
export default function Demo() {
  const [toast] = useState(() => createToaster())
  // The toasts leave with the demo.
  useEffect(() => () => void toast.dismiss(), [toast])
  const send = () => {
    toast.promise(upload, {
      loading: 'Uploading photos…',
      success: { title: 'Photos uploaded', description: '12 photos added to Summer trip' },
      error: { title: 'Upload failed', description: 'Check your connection and try again.', action: { label: 'Retry', onAction: send } },
    })
  }
  return (
    <div className="relative isolate flex h-[22rem] w-full max-w-xl items-center justify-center">
      <div aria-hidden className="absolute top-1/2 left-1/2 -z-10 grid -translate-x-1/2 -translate-y-1/2 grid-cols-[repeat(13,40px)]">
        {Array.from({ length: COLS * ROWS }, (_, i) => (
          <span key={i} className="relative size-10" style={{ opacity: fade(i % COLS, Math.floor(i / COLS)) }}>
            <span className="absolute inset-x-0 top-0 h-px bg-black/10 dark:bg-white/10" />
            <span className="absolute inset-y-0 left-0 w-px bg-black/10 dark:bg-white/10" />
          </span>
        ))}
      </div>
      <div className="flex max-w-sm flex-wrap justify-center gap-3">
        <GlassButton onClick={() => toast.success('Changes saved')}>Success</GlassButton>
        <GlassButton onClick={() => toast.info('A new version is ready', { description: 'Reload the page to use it.' })}>Info</GlassButton>
        <GlassButton onClick={() => toast.warning('Storage is almost full')}>Warning</GlassButton>
        <GlassButton onClick={() => toast.error('Changes not saved', { description: 'You are offline. Reconnect, then try again.' })}>Error</GlassButton>
        <GlassButton onClick={send}>Promise</GlassButton>
      </div>
      <GlassToaster toaster={toast} />
    </div>
  )
}
```

## Actions

An `action` is a soft pill at the end of the toast, like Undo; with an `href` it is a link. Pressing it runs `onAction` and closes the toast, and a Promise returned from it keeps the toast open and the button pending until it settles. A `cancel` is a second button, plain text beside the action, that only dismisses (`GlassToastClose` in a toast you render yourself). `onDismiss` tells you why a toast is closing (`timeout`, `swipe`, `close-press`, `escape-key`, `action`), and `dismissible: false` takes the swipe, Escape and the corner button away for a toast that has to be answered with its own button.

```tsx
const id = toast('Message archived', {
  action: { label: 'Undo', onAction: async () => { await restore() } },
  onDismiss: ({ reason }) => console.log(reason),
})

toast.update(id, { title: 'Message restored', type: 'success' })
toast.dismiss(id) // or toast.dismiss() for every toast
```

## A toast of your own

The toaster's children render each toast. `GlassToast` is the pane of glass; put `GlassToastTitle`, `GlassToastDescription`, `GlassToastAction` and `GlassToastClose` in it, and anything of yours beside them. Empty, each part shows the text of the toast it is in. `icon` replaces the type's icon with an avatar or an app's mark, and whatever else a toast needs travels in `data`. `side` and `align` place the stack: `top` or `bottom`, and `start`, `center` or `end`; the page leans in wherever it stands.

### Messages, at the bottom of the screen

```tsx
import { HugeiconsIcon } from '@hugeicons/react'
import { Mail01Icon } from '@hugeicons/core-free-icons'
import { useEffect, useRef, useState } from 'react'

import { GlassButton } from '@/components/liquid-glass'
import { createToaster, GlassToast, GlassToastAction, GlassToastDescription, GlassToastTitle, GlassToaster } from '@/components/liquid-glass/glass-toast'

type Sender = { initials: string; color: string }

const MESSAGES = [
  { title: 'Hollis Grant', description: 'Can you review the draft before noon?', data: { initials: 'HG', color: '#2563eb' } },
  { title: 'Inès Moreau', description: 'The invoice went out this morning.', data: { initials: 'IM', color: '#db2777' } },
  { title: 'Tomás Rey', description: 'Lunch at one? The usual place.', data: { initials: 'TR', color: '#059669' } },
]

// A toast of your own: the toaster's children render each toast, and whatever else it needs
// comes in `data`. Here every message carries its sender, drawn as a disc of flat colour before
// the text, and the stack stands at the bottom of the screen, in the middle: the page leans in
// towards it there. Swipe a message down to dismiss it.
// The backdrop is the demo's own: three flat fields of colour for the button to bend.
export default function Demo() {
  const [toast] = useState(() => createToaster({ duration: 8000 }))
  const [replied, setReplied] = useState('')
  const count = useRef(0)
  // The toasts leave with the demo.
  useEffect(() => () => void toast.dismiss(), [toast])
  const receive = () => {
    const message = MESSAGES[count.current++ % MESSAGES.length]
    toast({ ...message, action: { label: 'Reply', onAction: () => setReplied(message.title) } })
  }
  return (
    <div className="relative isolate flex h-[22rem] w-full max-w-xl flex-col items-center justify-center gap-4 overflow-hidden rounded-3xl bg-[#fde68a]">
      <div aria-hidden className="absolute -top-16 -left-10 -z-10 size-64 rounded-full bg-[#f97316]" />
      <div aria-hidden className="absolute -right-14 -bottom-20 -z-10 size-72 rounded-full bg-[#7c3aed]" />
      <GlassButton size="lg" icon={<HugeiconsIcon icon={Mail01Icon} />} iconPosition="start" onClick={receive}>
        New message
      </GlassButton>
      <p aria-live="polite" className="h-5 text-sm font-medium text-neutral-900">
        {replied && `Replying to ${replied}`}
      </p>
      <GlassToaster toaster={toast} side="bottom" align="center" aria-label="Messages">
        {(item) => {
          const sender = item.data as Sender
          return (
            <GlassToast
              icon={
                <span aria-hidden className="grid size-9 shrink-0 place-items-center rounded-full text-xs font-semibold text-white" style={{ background: sender.color }}>
                  {sender.initials}
                </span>
              }
            >
              <div className="flex min-w-0 flex-1 flex-col gap-0.5">
                <GlassToastTitle />
                <GlassToastDescription />
              </div>
              <GlassToastAction />
            </GlassToast>
          )
        }}
      </GlassToaster>
    </div>
  )
}
```

## The page leaning in

The lean is `gatherPage()`, in `glass-gather.ts`, and it is ported from the page effect of glimm (glimm.dev, MIT): the gather that reads the page further out around a point, the ring of blur around it, and the crest and trough of the ripple are its, with its numbers, but for the ring, which is wider for a toast: 40 px of blur where glimm has 16 (Sweep's lean keeps 16). glimm moves the page itself, which takes HTML-in-Canvas (Chrome 157 and later). This moves a picture of the page, painted by the kit's own `dom-snapshot`, so it runs wherever WebGL2 does. The picture is of the field around the toast alone and is taken once (again every 120 ms only while something in it moves by itself), and it shows only where it moves the page: everywhere else, and before and after, the page under it is the page. A scroll or a resize lets go at once. It carries no colour band of its own.

```tsx
// The page stays still: toasts only come up.
<GlassToaster gather={false} />

// The lean by itself, for something of your own that arrives (a point of the viewport, CSS px).
import { gatherPage } from '@/components/liquid-glass/glass-gather'

gatherPage({ x: 640, y: 80 })

// The lean alone, for a page that waits on something it was asked for: you say how far in it is
// (0 to 1 is a toast's own lean; up to 2 is further in) and when it ends. `keep` is left as it
// is while the page leans in around it. The ripple is yours to run too: where its crest is, as a
// share of the field (0 to 1), and how strong.
import { leanPage } from '@/components/liquid-glass/glass-gather'

const page = leanPage({ x: 640, y: 400 }, { keep: button })
page?.lean(1)
page?.ripple(0.4, 1)
page?.end()
```

## API reference

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `toast(message, options) / toast(options)` | `(…) => string` | — | Shows a toast and returns its id. `toast.success`, `.info`, `.warning`, `.error` and `.loading` set the type; `toast.promise(promise, { loading, success, error })` follows a promise; `toast.update(id, options)` changes one and `toast.dismiss(id?)` closes one, or all. |
| `title / description` | `ReactNode` | — | On a toast: the main message, and more detail under it. |
| `duration` | `number` | `5000` | On a toast, or in `createToaster({ duration })`: how long it shows, in ms. `Infinity` keeps it until it is dismissed. Timers wait while the pointer or focus is in the stack, and while the page is hidden. |
| `action` | `{ label, onAction?, href?, dismiss? }` | — | On a toast: a button that does something, like Undo. A Promise from `onAction` keeps the toast open until it settles; `href` makes it a link. |
| `cancel / dismissible / onDismiss` | `{ label, onCancel? } / boolean / (details) => void` | — | On a toast: a button that only dismisses it, whether the visitor can dismiss it (default `true`), and a callback with the reason it closes; `details.cancel()` keeps it. |
| `id / type / priority / data` | `string / ToastType / 'polite' \| 'assertive' / unknown` | — | On a toast: an id of your own (a toast with an id that is showing is updated in place), its type, how it is announced, and anything else for your own rendering. |
| `GlassToaster side / align` | `'top' \| 'bottom' / 'start' \| 'center' \| 'end'` | `'top' / 'end'` | Where the stack stands: the top right corner by default. On either side the newest is on top and the rest show under it. Swiping towards the side dismisses a toast and, unless it is centred, so does swiping towards the end it is aligned to. |
| `GlassToaster gather` | `boolean` | `true` | The page leans in towards a toast as it arrives, and ripples as it lets go. `false` leaves the page still. |
| `GlassToaster maxVisible / expanded` | `number / boolean` | `3 / false` | How many toasts show at once (the rest wait, with their timers stopped), and whether the stack is always a list (its header then has no Show less). |
| `GlassToaster title / labels` | `ReactNode / { less?: string; clear?: string }` | `— / { less: 'Show less', clear: 'Clear' }` | The name of the open list, at the start of its header (left out: the two buttons alone), and the words on those buttons, in the page's language. |
| `GlassToaster offset` | `number` | `16` | How far the stack keeps from the edges of the screen, in px. |
| `GlassToaster toaster` | `Toaster` | — | From `createToaster()`: a second queue, for a second toaster with its own toasts. |
| `GlassToaster shortcut / aria-label` | `string \| null / string` | `'F6' / 'Notifications'` | The key that moves focus into the stack and back (`null` turns it off), and the name of the region: set it in the page's language. |
| `GlassToaster tint / blur / optics` | `number / number / GlassOptics` | `0.6 / 10.25` | The toasts' glass, as on Card: how much tint covers the page, how much it is frosted (px), and the fine-tuning. |
| `GlassToaster children` | `(toast, item) => ReactNode` | — | Renders each toast, with `GlassToast` and its parts. Left out, a toast shows its icon, title, description, cancel button and action. |
| `GlassToast icon` | `ReactNode` | — | What stands before the text, in place of the type's icon. `null`: nothing. |
| `GlassToast className` | `string` | — | Classes for the pane: `rounded-[22px]` by default. |
| `GlassToastTitle / GlassToastDescription` | `children, className` | — | The toast's title and description; the toast's own text when they have no children. |
| `GlassToastAction onAction / dismiss` | `(event, details) => unknown / boolean` | — | The action's button. `onAction` runs in place of the toast's own; `dismiss={false}` keeps the toast open after it. |
| `GlassToastClose action` | `() => unknown` | — | A text button that closes the toast. Its `action` runs first; a Promise from it keeps the toast open until it settles. |

## Accessibility

- Every toast is announced once through a live region, without taking focus: politely, and an error at once. Keep messages short, and give one that has to stay `duration: Infinity`.
- While it has toasts the stack is a landmark named Notifications: set `aria-label` in the page's language.
- F6 moves focus to the newest toast and back, and the pile opens into a list as the keyboard's focus comes in; Tab goes through the header's buttons, the toasts and their buttons, and Escape dismisses the toast that has focus. The stack stays reachable over a modal dialog.
- The timers wait while the pointer or focus is in the stack, while the page is hidden and while its window is inactive.
- With reduced motion the page stays still and a toast only fades. Without WebGL2 it is a plain frosted panel, and the page stays still too.

Source: https://liquidglass.onemorethink.dev/docs/toast
