Undo Toast
Archive sample list items with one undo window, paused timing, focus recovery, and a commit event.
pnpm dlx shadcn@latest add @haze/undo-toast---
import { Archive } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import Toast from "./toast.astro";
interface Props {
id: string;
label?: string;
items?: { id: string; title: string; detail?: string }[];
timeout?: number;
class?: string;
}
const { id, label = "Review inbox", timeout = 8000, class: className, items = [
{ id: "layout", title: "Responsive layout", detail: "Mila · Ready for review" },
{ id: "exports", title: "Scheduled exports", detail: "Owen · Changes requested" },
{ id: "billing", title: "Billing settings", detail: "Lea · Ready for review" },
] } = Astro.props;
---
<section data-haze-undo-toast data-timeout={Math.max(1000, timeout)} aria-label={label} class={cn("group/undo grid min-w-0 gap-3", className)}>
<p tabindex="-1" data-undo-heading class="rounded-sm text-[0.9375rem] font-medium tracking-[-0.01em] focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">{label}</p>
<ul class="grid min-w-0 gap-1.5">
{items.map(item => <li data-undo-item data-key={item.id} class="flex min-w-0 items-center justify-between gap-2 rounded-xl border border-border bg-card px-4 py-2.5 opacity-100 motion-safe:transition-[height,opacity,display] motion-safe:duration-200 motion-safe:ease-snappy [&[hidden]]:hidden">
<div class="min-w-0"><p class="text-[0.8125rem]/5 font-medium wrap-anywhere">{item.title}</p><p class="text-xs/5 text-muted-foreground">{item.detail}</p></div>
<Button data-archive size="icon" variant="ghost" aria-label={`Archive ${item.title}`} class="hidden size-8 shrink-0 group-data-[enhanced]/undo:inline-flex"><Archive aria-hidden="true" /></Button>
</li>)}
</ul>
<Toast id={`${id}-notice`} message="Items archived" description="" duration={0} open={false}>
<div class="mt-1 flex flex-wrap items-center gap-2">
<Button data-undo-action variant="secondary" size="sm">Undo</Button>
<span data-undo-time aria-hidden="true" class="font-mono text-xs/5 text-muted-foreground"></span>
</div>
</Toast>
<span role="status" data-undo-status class="sr-only"></span>
</section>
<script>
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const toast = root.querySelector<HTMLElement>("[data-haze-toast]");
const undo = root.querySelector<HTMLButtonElement>("[data-undo-action]");
const status = root.querySelector<HTMLElement>("[data-undo-status]");
const time = root.querySelector<HTMLElement>("[data-undo-time]");
if (!toast || !undo || !status || !time) return;
const pending = new Set<HTMLElement>();
let remaining = 0, last = 0, frame = 0;
const pause = () => { cancelAnimationFrame(frame); frame = 0; };
const commit = () => {
pause();
if (toast.contains(document.activeElement)) root.querySelector<HTMLElement>("[data-undo-heading]")?.focus();
const ids = [...pending].map(row => row.dataset.key);
pending.forEach(row => row.remove());
pending.clear();
toast.removeAttribute("data-open");
root.dispatchEvent(new CustomEvent("haze:undo-commit", { bubbles: true, detail: { ids } }));
status.textContent = "Archive committed.";
};
const tick = (now: number) => {
remaining = Math.max(0, remaining - (now - last));
last = now;
time.textContent = `${Math.ceil(remaining / 1000)}s to undo`;
if (!remaining) commit(); else frame = requestAnimationFrame(tick);
};
const resume = () => {
if (frame || !pending.size || document.hidden || toast.matches(":hover") || toast.contains(document.activeElement)) return;
last = performance.now();
frame = requestAnimationFrame(tick);
};
root.addEventListener("click", event => {
const button = (event.target as Element).closest("[data-archive]");
const row = button?.closest<HTMLElement>("[data-undo-item]");
if (!row || row.hidden) return;
const visible = [...root.querySelectorAll<HTMLElement>("[data-undo-item]:not([hidden])")];
const index = visible.indexOf(row);
pending.add(row);
row.hidden = true;
row.inert = true;
toast.dispatchEvent(new CustomEvent("haze:toast-show", { detail: { message: `${pending.size} ${pending.size === 1 ? "item" : "items"} archived` } }));
const next = visible[index + 1] ?? visible[index - 1];
(next?.querySelector<HTMLButtonElement>("[data-archive]") ?? undo).focus();
status.textContent = `${pending.size} archived. Undo is available.`;
remaining = Number(root.dataset.timeout);
pause();
resume();
});
undo.addEventListener("click", () => {
pause();
const first = [...pending][0];
pending.forEach(row => { row.hidden = false; row.inert = false; });
const count = pending.size;
pending.clear();
toast.removeAttribute("data-open");
first?.querySelector<HTMLButtonElement>("[data-archive]")?.focus();
status.textContent = `${count} ${count === 1 ? "item" : "items"} restored.`;
});
toast.addEventListener("haze:toast-dismiss", commit);
toast.addEventListener("pointerenter", pause);
toast.addEventListener("pointerleave", resume);
toast.addEventListener("focusin", pause);
toast.addEventListener("focusout", () => queueMicrotask(resume));
root.addEventListener("haze:undo-visibility", () => document.hidden ? pause() : resume());
root.setAttribute("data-enhanced", "");
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-undo-toast]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-undo-toast-listener")) {
document.documentElement.setAttribute("data-haze-undo-toast-listener", "");
document.addEventListener("astro:page-load", init);
document.addEventListener("visibilitychange", () => document.querySelectorAll<HTMLElement>("[data-haze-undo-toast]").forEach(root => root.dispatchEvent(new Event("haze:undo-visibility"))));
}
</script>When to use
- Routine inbox triage should be reversible for a short period.
- Several rapid removals should be restored together with one action.
When not to use
- An irreversible operation needs explicit approval. Use confirm-popover.
Installation
Add the Haze registry to components.json once, then install Undo Toast with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/undo-toastnpx shadcn@latest add @haze/undo-toastyarn dlx shadcn@latest add @haze/undo-toastbunx --bun shadcn@latest add @haze/undo-toastFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Prefix for the notification ID. |
| label | string | – | Accessible and visible list name. |
| items | { id: string; title: string; detail?: string }[] | – | Stable identifiers and text of the initial rows. |
| timeout | number | – | Undo window in milliseconds. Defaults to 8000, with a 1000 minimum. |
| class | string | – | Additional classes on the component wrapper. |
Keyboard interactions
- EnterSpace
- Archive the focused row or restore every pending row with Undo.
Accessibility
- Archived rows become hidden and inert immediately. Focus advances to a remaining archive button or Undo when the list becomes empty.
- Hovering or focusing the notification pauses its shared timeout. Finalized IDs are emitted through haze:undo-commit for application persistence.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Undo Toast" with `npx shadcn@latest add @haze/undo-toast`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import UndoToast from "@/components/haze/ui/undo-toast.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/undo-toast.md
Customize with real content
Adapt the Haze undo-toast ui for our product. Replace the demo values of these props with our real content: id, label, items, timeout, class. Keep the layout, the heading level rules and these accessibility details: Archived rows become hidden and inert immediately. Focus advances to a remaining archive button or Undo when the list becomes empty. Hovering or focusing the notification pauses its shared timeout. Finalized IDs are emitted through haze:undo-commit for application persistence. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using undo-toast, check it fits: use it when routine inbox triage should be reversible for a short period.; several rapid removals should be restored together with one action.. Avoid it when an irreversible operation needs explicit approval. use confirm-popover.. Alternatives: @haze/toast, @haze/notification-stack, @haze/confirm-popover.
Dependencies
- npm: @lucide/astro
- @haze/button
- @haze/toast
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.