Components
Sonner
The corner where notes from toast() show: the newest in front, two more peeking out above. Pointing at the stack spreads it out and holds their time. A note rises in from below and leaves faster.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add sonner<script type="module" src="/spyglass-ds/elements/sonner.js"></script>Usage
Saying something just happened, for a moment: saved to a board, a brand added, a link copied. Mount one Toaster per app and call toast(title, { description, action }) from anywhere.
Never
- Errors that need an answer: keep them where they happened
- What the page already shows
- Notes that leave while someone is reading them: the time holds while the stack is pointed at
Adds with it: toast
Props
The web component takes the same as attributes or properties (<spyglass-sonner>); title is heading there.
<Toaster>
| Prop | Type | Default |
|---|---|---|
label | string The region's name for assistive tech. | 'Notifications' |
Examples
The same example in React and as web components; both render identically.
'use client'
import { useRef } from 'react'
import { Button } from '@/react/components/ui/Button'
import { toast, Toaster } from '@/react/components/ui/Sonner'
// Press Save: a note rises in the corner, with Undo. Press it quickly and they stack, three at most; point at the stack
// to spread it out and hold their time.
export default function Board() {
const count = useRef(23)
function save() {
count.current += 1
toast('Saved to board', { description: `Acme hooks now has ${count.current} creatives.`, action: { label: 'Undo' } })
}
return (
<div className="flex min-h-72 flex-wrap items-start justify-center gap-2">
<Button onClick={save}>Save to board</Button>
<Button variant="secondary" onClick={() => toast('Brand added', { description: 'New ads from Acme Studio show up here every day.' })}>Track brand</Button>
<Toaster />
</div>
)
}<!-- Press Save: a note rises in the corner, with Undo. Press it quickly and they stack, three at most; point at the
stack to spread it out and hold their time. -->
<div class="flex min-h-72 flex-wrap items-start justify-center gap-2">
<spyglass-button id="sonner-save">Save to board</spyglass-button>
<spyglass-button id="sonner-track" variant="secondary">Track brand</spyglass-button>
<spyglass-sonner id="sonner"></spyglass-sonner>
</div>
<script type="module">
const sonner = document.getElementById('sonner')
let count = 23
document.getElementById('sonner-save').addEventListener('click', () => {
count += 1
sonner.toast('Saved to board', { description: `Acme hooks now has ${count} creatives.`, action: { label: 'Undo' } })
})
document.getElementById('sonner-track').addEventListener('click', () => {
sonner.toast('Brand added', { description: 'New ads from Acme Studio show up here every day.' })
})
</script>Source
'use client'
import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from 'react'
import { Toast } from '@/react/components/ui/Toast'
import { getToasts, subscribeToasts, toast, TOAST_MOST, type ToastData } from '@/lib/sonner'
export { toast } from '@/lib/sonner'
// The corner where notes from toast() show (shadcn's sonner): the bottom right, full width on a phone. The newest is in
// front; the two before it peek out above, 12px apart and a little smaller. Pointing at the stack (or tabbing into it)
// spreads it out and stops every note's time, as does a hidden tab, so none leaves unread. A note rises in from below
// over 360ms on the strong ease-out and leaves faster, 160ms, fading as it drops; the others move to their new places
// as one goes. Each has a close button; an action closes it after it runs. Reduced motion keeps only the fades. Mount
// one per app, then call toast('Saved to board', { description, action }) from anywhere.
export interface ToasterProps {
/** The region's name for assistive tech. */
label?: string
}
const STEP = 100
const PEEK = 12
const GAP = 12
type Item = ToastData & { mounted: boolean, removed: boolean }
export function Toaster({ label = 'Notifications' }: ToasterProps) {
const store = useSyncExternalStore(subscribeToasts, getToasts, getToasts)
const [items, setItems] = useState<Item[]>([])
// Spread while pointed at or while focus is inside: two reasons, kept apart so losing one keeps the other.
const [hovered, setHovered] = useState(false)
const [focused, setFocused] = useState(false)
const expanded = hovered || focused
const [heights, setHeights] = useState<Record<number, number>>({})
const nodes = useRef(new Map<number, HTMLElement>())
const left = useRef(new Map<number, { left: number, shown: number }>())
const last = useRef(new Map<number, string>())
const exits = useRef(new Map<number, ReturnType<typeof setTimeout>>())
const list = useRef<HTMLOListElement | null>(null)
const held = useRef(false)
held.current = expanded
// The store's notes, with those still leaving kept in their places.
useEffect(() => {
setItems((prev) => {
const next: Item[] = prev.map((p) => {
const t = store.find((s) => s.id === p.id)
return t ? { ...t, mounted: p.mounted, removed: false } : { ...p, removed: true }
})
for (const t of store) if (!prev.some((p) => p.id === t.id)) next.push({ ...t, mounted: false, removed: false })
return next
})
}, [store])
// A new note starts below, out of sight, for one frame, then rises; a leaving one goes once its exit has played. A note
// that leaves with focus in it takes the focus away without a blur: the stack is no longer focused then.
useEffect(() => {
if (focused && !list.current?.contains(document.activeElement)) setFocused(false)
let frame = 0
if (items.some((i) => !i.mounted && !i.removed)) {
frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => setItems((p) => p.map((i) => (i.removed ? i : { ...i, mounted: true }))))
})
}
for (const i of items) {
if (!i.removed || exits.current.has(i.id)) continue
// ds-latency: the note stays in the page until its exit has played.
exits.current.set(i.id, setTimeout(() => {
exits.current.delete(i.id)
setItems((p) => p.filter((x) => x.id !== i.id))
}, 160))
}
return () => cancelAnimationFrame(frame)
}, [items])
useEffect(() => () => { for (const t of exits.current.values()) clearTimeout(t) }, [])
// One clock for every note, only while there are any; it stops while the stack is pointed at or the tab is hidden.
const count = store.length
useEffect(() => {
if (!count) return
// ds-latency: the notes' own clock, off the input path; nothing waits on it.
const timer = setInterval(() => {
if (held.current || document.hidden) return
for (const t of getToasts()) {
const l = left.current.get(t.id)
const now = !l || l.shown !== t.shown ? t.duration : l.left - STEP
if (now <= 0) {
left.current.delete(t.id)
toast.dismiss(t.id)
}
else left.current.set(t.id, { left: now, shown: t.shown })
}
}, STEP)
return () => clearInterval(timer)
}, [count > 0]) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!count) {
setHovered(false)
setFocused(false)
}
}, [count])
// Each note's own height, for spreading the stack out.
useLayoutEffect(() => {
const next: Record<number, number> = {}
for (const [id, node] of nodes.current) next[id] = (node.firstElementChild as HTMLElement | null)?.offsetHeight ?? 0
if (Object.keys(next).length !== Object.keys(heights).length || Object.entries(next).some(([id, h]) => heights[Number(id)] !== h)) setHeights(next)
})
const showing = items.filter((i) => !i.removed).reverse()
const front = showing[0] ? heights[showing[0].id] ?? 0 : 0
const spread = showing.reduce((sum, i) => sum + (heights[i.id] ?? 0), 0) + Math.max(0, showing.length - 1) * GAP
const height = !showing.length ? 0 : expanded ? spread : front + (Math.min(showing.length, TOAST_MOST) - 1) * PEEK
function style(item: Item): CSSProperties {
const i = showing.indexOf(item)
if (item.removed || i < 0) return { transform: `${last.current.get(item.id) ?? 'translateY(0)'} translateY(50%)`, opacity: 0, zIndex: 0 }
if (!item.mounted) return { transform: 'translateY(100%)', opacity: 0, zIndex: showing.length - i }
const y = expanded ? -(showing.slice(0, i).reduce((sum, x) => sum + (heights[x.id] ?? 0), 0) + i * GAP) : -i * PEEK
const transform = `translateY(${y}px) scale(${expanded ? 1 : 1 - i * 0.05})`
last.current.set(item.id, transform)
return { transform, opacity: i < TOAST_MOST ? 1 : 0, zIndex: showing.length - i, height: !expanded && i > 0 && front ? `${front}px` : undefined }
}
return (
<>
<style href="ds-sonner" precedence="ds">{css}</style>
<section data-ds="sonner" aria-label={label} aria-live="polite">
<ol
ref={list}
className="ds-sonner"
style={{ height: `${height}px` }}
onPointerEnter={() => setHovered(true)}
onPointerLeave={() => setHovered(false)}
onFocus={() => setFocused(true)}
onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setFocused(false) }}
>
{items.map((item) => (
<li
key={item.id}
ref={(el) => { if (el) nodes.current.set(item.id, el); else nodes.current.delete(item.id) }}
className="ds-sonner-toast"
data-removed={item.removed || undefined}
style={style(item)}
>
<Toast
title={item.title}
description={item.description}
action={item.action && { label: item.action.label, onClick: () => { item.action?.onClick?.(); toast.dismiss(item.id) } }}
onDismiss={() => toast.dismiss(item.id)}
/>
</li>
))}
</ol>
</section>
</>
)
}
export default Toaster
const css = `
.ds-sonner { position: fixed; right: var(--ds-space-lg); bottom: calc(var(--ds-space-lg) + env(safe-area-inset-bottom)); z-index: 70; width: min(22.5rem, calc(100vw - 2 * var(--ds-space-lg))); margin: 0; padding: 0; list-style: none; }
.ds-sonner-toast { position: absolute; right: 0; bottom: 0; left: 0; overflow: hidden; border-radius: var(--ds-radius-container); transform-origin: 50% 100%; transition: transform var(--ds-duration-entrance) var(--ds-easing-out), opacity var(--ds-duration-entrance) var(--ds-easing-out); }
.ds-sonner-toast[data-removed] { pointer-events: none; transition-duration: var(--ds-duration-exit); }
@media (prefers-reduced-motion: reduce) {
.ds-sonner-toast { transition: opacity var(--ds-duration-enter) var(--ds-easing-out); }
}
`// The toasts' store for the sonner item, framework-free so both flavors share its behavior: toast() adds a note,
// toast.dismiss() takes one (or all) away, and a Toaster subscribes and draws them. Three at most: a fourth pushes the
// oldest out. The same title and description again restarts that note's time instead of stacking a copy. The time
// itself is the Toaster's, so it can stop while a note is pointed at or the tab is hidden.
export interface ToastAction {
/** The button's label. */
label: string
/** What it does; the toast closes after it. */
onClick?: () => void
}
export interface ToastOptions {
/** A line under the title. */
description?: string
/** One button beside the text. */
action?: ToastAction
/** How long it stays, in ms (4000 by default). */
duration?: number
}
export interface ToastData extends ToastOptions {
id: number
title: string
duration: number
/** Bumped when the same note is shown again, so its time restarts. */
shown: number
}
export const TOAST_MS = 4000
export const TOAST_MOST = 3
let toasts: ToastData[] = []
let last = 0
let shown = 0
const listeners = new Set<() => void>()
const set = (next: ToastData[]) => {
toasts = next
for (const l of listeners) l()
}
/** Shows a note: what just happened, for a moment. Returns its id. */
export function toast(title: string, options: ToastOptions = {}): number {
shown += 1
const same = toasts.find((t) => t.title === title && t.description === options.description)
if (same) {
set(toasts.map((t) => (t === same ? { ...t, shown } : t)))
return same.id
}
last += 1
set([...toasts.slice(1 - TOAST_MOST), { ...options, id: last, title, duration: options.duration ?? TOAST_MS, shown }])
return last
}
/** Takes a note away, or every note. */
toast.dismiss = (id?: number) => set(id === undefined ? [] : toasts.filter((t) => t.id !== id))
/** The notes showing, oldest first. */
export const getToasts = () => toasts
/** Calls `listener` whenever the notes change; returns the unsubscribe. */
export function subscribeToasts(listener: () => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}import { html } from 'lit'
import { repeat } from 'lit/directives/repeat.js'
import { styleMap } from 'lit/directives/style-map.js'
import { DsElement, define } from '@/elements/lib/element'
import '@/elements/components/ui/toast'
import { getToasts, subscribeToasts, toast, TOAST_MOST, type ToastData } from '@/lib/sonner'
import styles from 'virtual:tw'
export { toast } from '@/lib/sonner'
// Sonner.tsx as <spyglass-sonner>: the corner where notes from toast() show: the bottom right, full width on a phone.
// The newest is in front; the two before it peek out above, 12px apart and a little smaller. Pointing at the stack (or
// tabbing into it) spreads it out and stops every note's time, as does a hidden tab. A note rises in from below over
// 360ms and leaves faster, 160ms, fading as it drops. Each has a close button; an action closes it after it runs. Put
// one on the page; show a note with `toast(title, { description, action })` from this module, or the element's
// toast() method.
const STEP = 100
const PEEK = 12
const GAP = 12
type Item = ToastData & { mounted: boolean, removed: boolean }
/**
* @summary The corner where notes from toast() show, stacked.
*/
export class Sonner extends DsElement {
static styles = [DsElement.styles, styles]
static properties = { label: {}, items: { state: true }, hovered: { state: true }, focused: { state: true }, heights: { state: true } }
/** The region's name for assistive tech. */
label = 'Notifications'
private items: Item[] = []
// Spread while pointed at or while focus is inside: two reasons, kept apart so losing one keeps the other.
private hovered = false
private focused = false
private get expanded() {
return this.hovered || this.focused
}
private heights: Record<number, number> = {}
private left = new Map<number, { left: number, shown: number }>()
private last = new Map<number, string>()
private exits = new Map<number, ReturnType<typeof setTimeout>>()
private timer?: ReturnType<typeof setInterval>
private frame = 0
private unsubscribe?: () => void
/** Shows a note (the module's toast()). */
toast(title: string, options?: Parameters<typeof toast>[1]) {
return toast(title, options)
}
// The store's notes, with those still leaving kept in their places.
private sync = () => {
const store = getToasts()
const next: Item[] = this.items.map((p) => {
const t = store.find((s) => s.id === p.id)
return t ? { ...t, mounted: p.mounted, removed: false } : { ...p, removed: true }
})
for (const t of store) if (!this.items.some((p) => p.id === t.id)) next.push({ ...t, mounted: false, removed: false })
this.items = next
this.clock()
}
// One clock for every note, only while there are any; it stops while the stack is pointed at or the tab is hidden.
private clock() {
const count = getToasts().length
if (count && !this.timer) {
// ds-latency: the notes' own clock, off the input path; nothing waits on it.
this.timer = setInterval(() => {
if (this.expanded || document.hidden) return
for (const t of getToasts()) {
const l = this.left.get(t.id)
const now = !l || l.shown !== t.shown ? t.duration : l.left - STEP
if (now <= 0) {
this.left.delete(t.id)
toast.dismiss(t.id)
} else this.left.set(t.id, { left: now, shown: t.shown })
}
}, STEP)
}
if (!count && this.timer) {
clearInterval(this.timer)
this.timer = undefined
this.hovered = false
this.focused = false
}
}
connectedCallback() {
super.connectedCallback()
this.unsubscribe = subscribeToasts(this.sync)
this.sync()
}
disconnectedCallback() {
super.disconnectedCallback()
this.unsubscribe?.()
clearInterval(this.timer)
this.timer = undefined
cancelAnimationFrame(this.frame)
for (const t of this.exits.values()) clearTimeout(t)
this.exits.clear()
}
protected updated() {
// A note that leaves with focus in it takes the focus away: the stack is no longer focused then.
if (this.focused && !(this.renderRoot as ShadowRoot).activeElement) this.focused = false
// Each note's own height, for spreading the stack out.
const next: Record<number, number> = {}
for (const li of this.renderRoot.querySelectorAll<HTMLElement>('.ds-sonner-toast')) {
const box = li.firstElementChild?.shadowRoot?.querySelector<HTMLElement>('[data-ds="toast"]')
next[Number(li.dataset.id)] = box?.offsetHeight ?? 0
}
if (Object.keys(next).length !== Object.keys(this.heights).length || Object.entries(next).some(([id, h]) => this.heights[Number(id)] !== h)) this.heights = next
// A new note starts below, out of sight, for one frame, then rises; a leaving one goes once its exit has played.
if (this.items.some((i) => !i.mounted && !i.removed)) {
cancelAnimationFrame(this.frame)
this.frame = requestAnimationFrame(() => {
this.frame = requestAnimationFrame(() => {
this.items = this.items.map((i) => (i.removed ? i : { ...i, mounted: true }))
})
})
}
for (const i of this.items) {
if (!i.removed || this.exits.has(i.id)) continue
// ds-latency: the note stays in the page until its exit has played.
this.exits.set(i.id, setTimeout(() => {
this.exits.delete(i.id)
this.items = this.items.filter((x) => x.id !== i.id)
}, 160))
}
}
private onFocusOut = (event: FocusEvent) => {
const next = event.relatedTarget as Node | null
if (!next || !this.renderRoot.contains(next)) this.focused = false
}
render() {
const showing = this.items.filter((i) => !i.removed).reverse()
const h = this.heights
const front = showing[0] ? h[showing[0].id] ?? 0 : 0
const spread = showing.reduce((sum, i) => sum + (h[i.id] ?? 0), 0) + Math.max(0, showing.length - 1) * GAP
const height = !showing.length ? 0 : this.expanded ? spread : front + (Math.min(showing.length, TOAST_MOST) - 1) * PEEK
const style = (item: Item): Record<string, string | undefined> => {
const i = showing.indexOf(item)
if (item.removed || i < 0) return { transform: `${this.last.get(item.id) ?? 'translateY(0)'} translateY(50%)`, opacity: '0', zIndex: '0' }
if (!item.mounted) return { transform: 'translateY(100%)', opacity: '0', zIndex: String(showing.length - i) }
const y = this.expanded ? -(showing.slice(0, i).reduce((sum, x) => sum + (h[x.id] ?? 0), 0) + i * GAP) : -i * PEEK
const transform = `translateY(${y}px) scale(${this.expanded ? 1 : 1 - i * 0.05})`
this.last.set(item.id, transform)
return { transform, opacity: i < TOAST_MOST ? '1' : '0', zIndex: String(showing.length - i), height: !this.expanded && i > 0 && front ? `${front}px` : undefined }
}
return html`<section data-ds="sonner" aria-label=${this.label} aria-live="polite"><ol class="ds-sonner" style=${styleMap({ height: `${height}px` })} @pointerenter=${() => { this.hovered = true }} @pointerleave=${() => { this.hovered = false }} @focusin=${() => { this.focused = true }} @focusout=${this.onFocusOut}>${repeat(
this.items,
(item) => item.id,
(item) => html`<li class="ds-sonner-toast" data-id=${item.id} ?data-removed=${item.removed} style=${styleMap(style(item))}><spyglass-toast heading=${item.title} description=${item.description ?? ''} action-label=${item.action?.label ?? ''} dismissable @action=${() => { item.action?.onClick?.(); toast.dismiss(item.id) }} @dismiss=${() => toast.dismiss(item.id)}></spyglass-toast></li>`,
)}</ol></section>`
}
}
define('sonner', Sonner).ds-sonner { position: fixed; right: var(--ds-space-lg); bottom: calc(var(--ds-space-lg) + env(safe-area-inset-bottom)); z-index: 70; width: min(22.5rem, calc(100vw - 2 * var(--ds-space-lg))); margin: 0; padding: 0; list-style: none; }
.ds-sonner-toast { position: absolute; right: 0; bottom: 0; left: 0; overflow: hidden; border-radius: var(--ds-radius-container); transform-origin: 50% 100%; transition: transform var(--ds-duration-entrance) var(--ds-easing-out), opacity var(--ds-duration-entrance) var(--ds-easing-out); }
.ds-sonner-toast[data-removed] { pointer-events: none; transition-duration: var(--ds-duration-exit); }
@media (prefers-reduced-motion: reduce) {
.ds-sonner-toast { transition: opacity var(--ds-duration-enter) var(--ds-easing-out); }
}Reference: Derived from the brand guidelines (no toast in the brand assets): the Toast note, stacked in the corner of Black.