Undo Toast
Toast that confirms a reversible action and offers Undo, with a thin bar and a seconds count for how long the undo stays open. Use it for archive, delete or move actions that are applied at once.
How it differs. One inline action above a countdown it owns: the bar holds while pointer or focus is in the toast region, commit fires once on expiry or dismissal and never after an undo, which is confirmed in place.
Install
pnpm dlx shadcn@latest add @hazine/toast-undo-actionAdds 1 file, 1 shadcn primitive (button), and 2 packages (sonner, lucide-react).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/toast-undo-action.tsx, 363 lines
"use client"
import * as React from "react"
import { Pause, Undo2, X } from "lucide-react"
import { toast } from "sonner"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
/** Why the undo window closed without an undo. */
export type ToastUndoCommitReason = "expired" | "dismissed"
export interface ToastUndoActionProps
extends Omit<React.ComponentProps<"div">, "title"> {
/** What just happened, in the past tense: "Conversation archived". */
title: string
/** The object the action touched. Clamped to two lines. */
description?: string
/** A 16px lucide icon for the action. Decorative. */
icon?: React.ReactNode
/** Length of the undo window in milliseconds. */
duration?: number
/** Milliseconds left when the toast mounts. Defaults to `duration`. */
defaultRemaining?: number
/** Holds the countdown from outside, on top of hover and focus. */
paused?: boolean
undoLabel?: string
dismissLabel?: string
/** Replaces the title once the action has been undone. */
undoneTitle?: string
locale?: string
/** Screen reader sentence for the window. Receives the localised length, such as "8 seconds". */
formatHint?: (length: string) => string
/** Undo was pressed. Reverse the action here. */
onUndo?: () => void
/**
* The window closed without an undo, so the action is final. Fires once,
* when the countdown ends or when the toast is dismissed. Never after an undo.
*/
onCommit?: (reason: ToastUndoCommitReason) => void
/** The toast is finished and should be removed from the screen. */
onClose?: () => void
}
// A frame that arrives late (hidden tab, paused debugger) counts as one frame.
const LONGEST_FRAME = 100
const UNDONE_CLOSE_DELAY = 2400
function defaultFormatHint(length: string) {
return `Undo available for ${length}.`
}
function formatSeconds(
locale: string,
seconds: number,
unitDisplay: "narrow" | "long"
) {
return new Intl.NumberFormat(locale, {
style: "unit",
unit: "second",
unitDisplay,
}).format(seconds)
}
export function ToastUndoAction({
title,
description,
icon,
duration = 8000,
defaultRemaining,
paused = false,
undoLabel = "Undo",
dismissLabel = "Dismiss",
undoneTitle = "Action undone",
locale = "en-US",
formatHint = defaultFormatHint,
onUndo,
onCommit,
onClose,
ref,
className,
...props
}: ToastUndoActionProps) {
const start = Math.min(Math.max(defaultRemaining ?? duration, 0), duration)
const [undone, setUndone] = React.useState(false)
const [shown, setShown] = React.useState(start)
const [hovered, setHovered] = React.useState(false)
const [focused, setFocused] = React.useState(false)
const remaining = React.useRef(start)
const settled = React.useRef(false)
const rootRef = React.useRef<HTMLDivElement>(null)
const dismissRef = React.useRef<HTMLButtonElement>(null)
const messageId = `${React.useId()}-message`
const handlers = React.useRef({ onUndo, onCommit, onClose })
React.useImperativeHandle(ref, () => rootRef.current as HTMLDivElement)
React.useEffect(() => {
handlers.current = { onUndo, onCommit, onClose }
})
const held = paused || hovered || focused
const running = !undone && !held
const close = React.useCallback((reason: ToastUndoCommitReason) => {
if (!settled.current) {
settled.current = true
handlers.current.onCommit?.(reason)
}
// Sonner hands focus back only when its last toast closes. With others
// still open, a keyboard user is moved to the next one, not dropped.
const item = rootRef.current?.closest<HTMLElement>("[data-sonner-toast]")
const active = document.activeElement
if (item && item.contains(active) && active?.matches(":focus-visible")) {
const next = Array.from(
item.parentElement?.querySelectorAll<HTMLElement>(
"[data-sonner-toast]"
) ?? []
).find((other) => other !== item && other.dataset.removed !== "true")
next?.focus()
}
handlers.current.onClose?.()
}, [])
// The countdown is driven from script, not CSS, so it can stop mid-way and
// so nothing keeps animating once the user asks for reduced motion.
React.useEffect(() => {
if (!running) return
const stepped = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches
let last = performance.now()
let frame = requestAnimationFrame(function tick(now) {
const next = Math.max(
0,
remaining.current - Math.min(now - last, LONGEST_FRAME)
)
remaining.current = next
last = now
setShown(stepped ? Math.ceil(next / 1000) * 1000 : next)
if (next > 0) frame = requestAnimationFrame(tick)
else close("expired")
})
return () => cancelAnimationFrame(frame)
}, [running, close])
React.useEffect(() => {
if (!undone || held) return
const timer = setTimeout(
() => handlers.current.onClose?.(),
UNDONE_CLOSE_DELAY
)
return () => clearTimeout(timer)
}, [undone, held])
React.useEffect(() => {
const root = rootRef.current
if (!root) return
// Sonner wraps a toast in a list item that is itself a tab stop, so Escape
// is read there. Hover and focus are read on the whole list: its hotkey
// puts focus on the list first, and a toast that closed under the pointer
// would move the others. Rendered alone, the root plays both parts.
const item = root.closest<HTMLElement>("[data-sonner-toast]") ?? root
const region = root.closest<HTMLElement>("[data-sonner-toaster]") ?? root
const enter = () => setHovered(true)
const leave = () => setHovered(false)
const focusIn = (event: FocusEvent) =>
setFocused(
event.target instanceof Element && event.target.matches(":focus-visible")
)
const focusOut = (event: FocusEvent) => {
const next = event.relatedTarget
// Switching to another window is not leaving the toast.
if (!document.hasFocus()) return
if (!(next instanceof Node && region.contains(next))) setFocused(false)
}
const keyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") close("dismissed")
}
region.addEventListener("pointerenter", enter)
region.addEventListener("pointerleave", leave)
region.addEventListener("focusin", focusIn)
region.addEventListener("focusout", focusOut)
item.addEventListener("keydown", keyDown)
return () => {
region.removeEventListener("pointerenter", enter)
region.removeEventListener("pointerleave", leave)
region.removeEventListener("focusin", focusIn)
region.removeEventListener("focusout", focusOut)
item.removeEventListener("keydown", keyDown)
}
}, [close])
function undo(event: React.MouseEvent<HTMLButtonElement>) {
if (settled.current) return
settled.current = true
// The Undo button unmounts and takes its focus with it. A keyboard user
// keeps a place in the toast.
if (event.currentTarget.matches(":focus-visible")) {
dismissRef.current?.focus()
}
setUndone(true)
handlers.current.onUndo?.()
}
const seconds = Math.ceil(shown / 1000)
const state = undone ? "undone" : held ? "paused" : "running"
return (
<div
{...props}
ref={rootRef}
data-slot="toast-undo-action"
data-state={state}
className={cn(
"group rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-md",
// Sonner's list item is a tab stop that removes its own outline.
"in-focus-visible:outline-2 in-focus-visible:outline-offset-2 in-focus-visible:outline-foreground",
className
)}
>
<div className="flex flex-wrap items-start gap-x-3 gap-y-2">
{icon && (
<span
aria-hidden="true"
data-slot="toast-undo-action-icon"
className="mt-1 flex h-5 shrink-0 items-center text-muted-foreground"
>
{undone ? <Undo2 className="size-4" /> : icon}
</span>
)}
<div
id={messageId}
role="status"
data-slot="toast-undo-action-message"
className="min-w-0 flex-1 basis-40 py-1"
>
<p className="text-sm font-semibold break-words">
{undone ? undoneTitle : title}
</p>
{description && (
<p
title={description}
className="mt-0.5 line-clamp-2 text-sm break-words text-muted-foreground"
>
{description}
</p>
)}
{!undone && (
<span className="sr-only">
{formatHint(
formatSeconds(locale, Math.ceil(start / 1000), "long")
)}
</span>
)}
</div>
<div
data-slot="toast-undo-action-actions"
className="ms-auto flex max-w-full min-w-0 items-center gap-1"
>
{!undone && (
<Button
type="button"
variant="outline"
size="sm"
aria-describedby={messageId}
className="min-w-0 shrink"
onClick={undo}
>
<Undo2 aria-hidden="true" data-icon="inline-start" />
<span className="min-w-0 truncate">{undoLabel}</span>
</Button>
)}
<Button
ref={dismissRef}
type="button"
variant="ghost"
size="icon-sm"
aria-label={`${dismissLabel}: ${undone ? undoneTitle : title}`}
onClick={() => close("dismissed")}
>
<X aria-hidden="true" />
</Button>
</div>
</div>
{!undone && (
<div
aria-hidden="true"
data-slot="toast-undo-action-countdown"
className="mt-3 flex items-center gap-2 text-muted-foreground"
>
<div className="h-1 min-w-0 flex-1 overflow-hidden rounded-full bg-muted">
<div
className="h-full rounded-full bg-primary"
style={{ inlineSize: `${(shown / duration) * 100}%` }}
/>
</div>
<Pause className="size-3.5 shrink-0 opacity-0 transition-opacity duration-150 group-data-[state=paused]:opacity-100" />
<span className="min-w-6 text-end font-mono text-xs tabular-nums">
{formatSeconds(locale, seconds, "narrow")}
</span>
</div>
)}
</div>
)
}
export interface ToastUndoActionOptions
extends Pick<
ToastUndoActionProps,
| "title"
| "description"
| "icon"
| "duration"
| "paused"
| "undoLabel"
| "dismissLabel"
| "undoneTitle"
| "locale"
| "formatHint"
| "onUndo"
| "onCommit"
> {
/** Reuse an id to update a toast that is already on screen. */
id?: string | number
}
/**
* Shows the toast through Sonner. A `<Toaster />` has to be mounted once in the
* app. Sonner never times this toast out: the countdown inside it decides.
*/
export function showToastUndoAction({
id,
onUndo,
onCommit,
...options
}: ToastUndoActionOptions) {
let open = true
const settle = (callback: () => void) => {
if (!open) return
open = false
callback()
}
return toast.custom(
(toastId) => (
<ToastUndoAction
{...options}
onUndo={() => settle(() => onUndo?.())}
onCommit={(reason) => settle(() => onCommit?.(reason))}
onClose={() => toast.dismiss(toastId)}
/>
),
{
id,
duration: Infinity,
// Sonner sizes only its own styled toasts, so the item fills the list.
className: "w-full",
// A swipe removes the toast without passing through its buttons.
onDismiss: () => settle(() => onCommit?.("dismissed")),
}
)
}
The demo in the preview, 378 lines
"use client"
import * as React from "react"
import {
Archive,
FolderInput,
Inbox,
RotateCcw,
UserMinus,
} from "lucide-react"
import { Toaster } from "sonner"
import { Button } from "@/components/ui/button"
import { Kbd } from "@/components/ui/kbd"
import {
ToastUndoAction,
showToastUndoAction,
} from "@/components/hazine/toast-undo-action"
type Stage = "open" | "undoable" | "archived"
interface Conversation {
id: string
subject: string
from: string
received: string
stage: Stage
}
const UNDO_WINDOW = 8000
const SEED_ID = "refund-48213"
const EMPTY_ID = "empty"
const WAKE_EVENTS = ["pointermove", "pointerdown", "keydown"] as const
// The first conversation was archived a moment ago, so the toast is on screen
// from the start with its full window left.
const CONVERSATIONS: Conversation[] = [
{
id: SEED_ID,
subject: "Refund for order 48213",
from: "Mirela Ostrowska",
received: "09:12",
stage: "undoable",
},
{
id: "vat-number",
subject: "Invoice shows the wrong VAT number",
from: "Kofi Asante",
received: "09:40",
stage: "open",
},
{
id: "move-booking",
subject: "Can I move my booking to Friday",
from: "Linnea Sjoberg",
received: "10:05",
stage: "open",
},
{
id: "missing-charger",
subject: "Charger missing from the box",
from: "Tadeo Villanueva",
received: "10:31",
stage: "open",
},
]
// Key caps sit on a solid muted fill, where only foreground text has the contrast.
const KEY = "text-foreground"
// The measure sits one level inside the full-width root, so a canvas that sizes
// the root of a demo cannot stretch the content.
function Frame({ className, children }: { className: string; children: React.ReactNode }) {
return (
<div className="w-full">
<div className={`mx-auto grid gap-3 ${className}`}>{children}</div>
</div>
)
}
function plural(count: number, one: string, many: string) {
return `${count} ${count === 1 ? one : many}`
}
export default function ToastUndoActionDemo() {
const [conversations, setConversations] = React.useState(CONVERSATIONS)
const buttons = React.useRef(new Map<string, HTMLButtonElement>())
const emptyRef = React.useRef<HTMLDivElement>(null)
const focusNext = React.useRef<string | null>(null)
const setStage = React.useCallback((id: string, stage: Stage) => {
setConversations((previous) =>
previous.map((conversation) =>
conversation.id === id ? { ...conversation, stage } : conversation
)
)
}, [])
const announce = React.useCallback(
(conversation: Conversation, paused: boolean) => {
showToastUndoAction({
id: conversation.id,
title: "Conversation archived",
description: `${conversation.subject}, from ${conversation.from}`,
icon: <Archive className="size-4" />,
undoneTitle: "Conversation restored",
duration: UNDO_WINDOW,
paused,
onUndo: () => setStage(conversation.id, "open"),
onCommit: () => setStage(conversation.id, "archived"),
})
},
[setStage]
)
// The opening toast waits for the first sign of a reader before it counts
// down, so the page looks the same every time it loads.
React.useEffect(() => {
const seed = CONVERSATIONS[0]
announce(seed, true)
const sleep = () =>
WAKE_EVENTS.forEach((type) => window.removeEventListener(type, begin))
function begin() {
sleep()
announce(seed, false)
}
WAKE_EVENTS.forEach((type) => window.addEventListener(type, begin))
return sleep
}, [announce])
React.useEffect(() => {
if (!focusNext.current) return
const target = buttons.current.get(focusNext.current) ?? emptyRef.current
target?.focus()
focusNext.current = null
})
const open = conversations.filter((item) => item.stage === "open")
const undoable = conversations.filter((item) => item.stage === "undoable")
const archived = conversations.filter((item) => item.stage === "archived")
function archive(conversation: Conversation) {
const index = open.indexOf(conversation)
const neighbour = open[index + 1] ?? open[index - 1]
focusNext.current = neighbour ? neighbour.id : EMPTY_ID
setStage(conversation.id, "undoable")
announce(conversation, false)
}
function restoreArchived() {
focusNext.current = archived[0]?.id ?? null
setConversations((previous) =>
previous.map((conversation) =>
conversation.stage === "archived"
? { ...conversation, stage: "open" }
: conversation
)
)
}
return (
<Frame className="max-w-xl">
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
{open.length} of {conversations.length} conversations in the inbox.
</span>{" "}
<span className="tabular-nums">
{undoable.length} can still be undone, {archived.length} archived.
</span>
</p>
{open.length > 0 ? (
<ul className="divide-y divide-border rounded-xl border border-border">
{open.map((conversation) => (
<li
key={conversation.id}
className="flex items-center gap-3 px-4 py-3"
>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold">
{conversation.subject}
</p>
<p className="mt-0.5 truncate text-sm text-muted-foreground">
{conversation.from}
<span className="tabular-nums">
, {conversation.received}
</span>
</p>
</div>
<Button
ref={(node) => {
if (node) buttons.current.set(conversation.id, node)
else buttons.current.delete(conversation.id)
}}
type="button"
variant="outline"
size="icon"
aria-label={`Archive ${conversation.subject}`}
onClick={() => archive(conversation)}
>
<Archive aria-hidden="true" />
</Button>
</li>
))}
</ul>
) : (
<div
ref={emptyRef}
tabIndex={-1}
className="flex items-center gap-3 rounded-xl border border-dashed border-border px-4 py-6 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground"
>
<Inbox
aria-hidden="true"
strokeWidth={1.5}
className="size-6 shrink-0 text-muted-foreground"
/>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
The inbox is clear.
</span>{" "}
New conversations appear here as customers write in.
</p>
</div>
)}
<div className="flex flex-wrap items-center justify-between gap-3">
<p className="text-sm text-pretty text-muted-foreground">
<Kbd className={KEY}>Alt</Kbd> <Kbd className={KEY}>T</Kbd> moves
focus to the toast. <Kbd className={KEY}>Esc</Kbd> dismisses it.
</p>
<Button
type="button"
variant="ghost"
size="sm"
disabled={archived.length === 0}
onClick={restoreArchived}
>
<RotateCcw aria-hidden="true" data-icon="inline-start" />
Restore {plural(archived.length, "archived conversation", "archived conversations")}
</Button>
</div>
<Toaster expand visibleToasts={4} />
</Frame>
)
}
interface StillToastProps {
children: (close: () => void) => React.ReactNode
caption: string
}
/** A toast drawn in the page flow with its countdown held, for a fixed picture. */
function StillToast({ children, caption }: StillToastProps) {
const [view, setView] = React.useState({ open: true, swapped: false })
const regionRef = React.useRef<HTMLElement>(null)
// The toast and the button replace each other, so focus follows the swap.
React.useEffect(() => {
if (view.swapped) regionRef.current?.querySelector("button")?.focus()
}, [view])
const swap = (open: boolean) => setView({ open, swapped: true })
return (
<Frame className="max-w-sm">
<section ref={regionRef} aria-label="Notifications">
{view.open ? (
children(() => swap(false))
) : (
<Button type="button" variant="outline" onClick={() => swap(true)}>
<RotateCcw aria-hidden="true" data-icon="inline-start" />
Show the toast again
</Button>
)}
</section>
<p className="text-sm text-pretty text-muted-foreground">{caption}</p>
</Frame>
)
}
function ToastUndoActionPaused() {
return (
<StillToast caption="Held with 5 of 8 seconds left. The pause mark beside the seconds shows that the countdown is not running.">
{(close) => (
<ToastUndoAction
paused
title="Conversation archived"
description="Invoice shows the wrong VAT number, from Kofi Asante"
icon={<Archive className="size-4" />}
undoneTitle="Conversation restored"
duration={UNDO_WINDOW}
defaultRemaining={5000}
onClose={close}
/>
)}
</StillToast>
)
}
function ToastUndoActionOverflow() {
return (
<StillToast caption="The title wraps, the description stops at two lines with the full text in its tooltip, and the actions drop under the message when the row runs out of room.">
{(close) => (
<ToastUndoAction
paused
title="14 conversations moved to the Billing disputes and chargebacks folder"
description="Refund for order 48213, Invoice shows the wrong VAT number, Charged twice for the annual plan after switching cards, and 11 more from 9 customers"
icon={<FolderInput className="size-4" />}
undoLabel="Move all 14 back to the inbox"
undoneTitle="14 conversations moved back to the inbox"
duration={120000}
defaultRemaining={96000}
onClose={close}
/>
)}
</StillToast>
)
}
function ToastUndoActionTitleOnly() {
return (
<StillToast caption="Without a description or an icon the toast is one line of text, the two actions and the countdown.">
{(close) => (
<ToastUndoAction
paused
title="Davina Okoro removed from the team"
undoneTitle="Davina Okoro is back on the team"
duration={10000}
onClose={close}
/>
)}
</StillToast>
)
}
function ToastUndoActionShortWindow() {
const [log, setLog] = React.useState({ shown: 0, undone: 0, final: 0 })
function remove() {
setLog((previous) => ({ ...previous, shown: previous.shown + 1 }))
showToastUndoAction({
title: "Seat removed",
description: "Davina Okoro loses access when the window closes",
icon: <UserMinus className="size-4" />,
undoneTitle: "Seat kept",
duration: 4000,
onUndo: () =>
setLog((previous) => ({ ...previous, undone: previous.undone + 1 })),
onCommit: () =>
setLog((previous) => ({ ...previous, final: previous.final + 1 })),
})
}
const waiting = log.shown - log.undone - log.final
return (
<Frame className="max-w-sm justify-items-start">
<Button type="button" variant="outline" onClick={remove}>
<UserMinus aria-hidden="true" data-icon="inline-start" />
Remove a seat
</Button>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
{plural(log.shown, "removal", "removals")}: {log.undone} undone,{" "}
{log.final} final, {waiting} waiting.
</span>{" "}
A four second window. A removal turns final when its countdown ends or
its toast is dismissed, and never after an undo.
</p>
<Toaster expand visibleToasts={4} />
</Frame>
)
}
export const scenarios = {
paused: ToastUndoActionPaused,
overflow: ToastUndoActionOverflow,
"title-only": ToastUndoActionTitleOnly,
"short-window": ToastUndoActionShortWindow,
}
Props14
- titlerequired
- string
- What just happened, in the past tense: "Conversation archived".
- description
- string
- The object the action touched. Clamped to two lines.
- icon
- React.ReactNode
- A 16px lucide icon for the action. Decorative.
- duration
- number = 8000
- Length of the undo window in milliseconds.
- defaultRemaining
- number
- Milliseconds left when the toast mounts. Defaults to `duration`.
- paused
- boolean = false
- Holds the countdown from outside, on top of hover and focus.
- undoLabel
- string = "Undo"
- dismissLabel
- string = "Dismiss"
- undoneTitle
- string = "Action undone"
- Replaces the title once the action has been undone.
- locale
- string = "en-US"
- formatHint
- (length: string) => string = defaultFormatHint
- Screen reader sentence for the window. Receives the localised length, such as "8 seconds".
- onUndo
- () => void
- Undo was pressed. Reverse the action here.
- onCommit
- (reason: ToastUndoCommitReason) => void
- The window closed without an undo, so the action is final. Fires once, when the countdown ends or when the toast is dismissed. Never after an undo.
- onClose
- () => void
- The toast is finished and should be removed from the screen.
Also accepts every prop of Omit<React.ComponentProps<"div">, "title">.
Accessibility
- Pattern
- Toast with a status region, Button (APG, opens in a new tab)
- Keyboard
Keyboard support for Undo Toast Key Effect Alt+T Moves focus to the toast region (the Sonner hotkey). Every countdown holds from then on Tab Moves through the toast, then Undo, then Dismiss. The countdowns hold while keyboard focus is anywhere in the region Enter or Space on Undo Reverses the action, announces the restored title and moves focus to Dismiss Enter or Space on Dismiss Closes the toast. Before an undo this also makes the action final. Focus moves to the next toast, or back to where it was when the last one closes Escape Dismisses the focused toast, with the same result as Dismiss - Screen reader
The message is a status region, kept apart from the buttons so their names are not read as part of it, and it carries a hidden sentence with the length of the window. Undo is described by that message and Dismiss names the title, so stacked toasts can be told apart. The bar and the seconds are hidden from assistive technology. Sonner supplies the Notifications region, and its focused list item is outlined by the toast.
- Announces: {title} {description} {formatHint}
- Announces: {undoneTitle} {description}
- Reduced motion
- The bar and the seconds change once a second instead of every frame. No CSS animation runs in either mode.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies3
- button
- sonner
- lucide-react
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.