{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"undo-toast","type":"registry:component","title":"Undo toast","description":"Deletes instantly and gives you five seconds to change your mind.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/undo-toast.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type UndoItem = { id: string; name: string; meta: string };\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// Survivors slide over 250ms while the leaver is gone in 150ms, so the gap\n// never stands empty. Exits are softer and faster than entrances.\nconst SLIDE = { duration: 0.25, ease: EASE_OUT };\nconst LEAVE = { duration: 0.15, ease: EASE_OUT };\n// A restored row waits 50ms for its neighbours to open the gap first.\nconst RESTORE = { duration: 0.25, ease: EASE_OUT, delay: 0.05 };\nconst INSTANT = { duration: 0 };\n// r=8 in a 20px box leaves room for the 2px stroke; 2 * PI * 8.\nconst RING = 50.27;\n\nconst CSS = `\n.undo-ring {\n  stroke-dasharray: ${RING};\n  animation-name: undo-countdown;\n  /* Linear because it is a clock: every second must look the same. */\n  animation-timing-function: linear;\n  animation-fill-mode: forwards;\n}\n@keyframes undo-countdown {\n  to { stroke-dashoffset: ${RING}; }\n}\n/* The ring is the timer itself, so pausing it pauses the delete. Focus\n   pauses it too, so keyboard users are never raced. */\n.undo-snackbar:focus-within .undo-ring,\n[data-hidden] .undo-ring { animation-play-state: paused; }\n@media (hover: hover) {\n  .undo-snackbar:hover .undo-ring { animation-play-state: paused; }\n}\n`;\n\nfunction isEditable(el: EventTarget | null) {\n  return (\n    el instanceof HTMLElement &&\n    (el.isContentEditable || el.tagName === \"INPUT\" || el.tagName === \"TEXTAREA\")\n  );\n}\n\nfunction shortcutName() {\n  return /Mac|iPhone|iPad/.test(navigator.platform) ? \"Command Z\" : \"Control Z\";\n}\n\nexport function UndoToast({\n  items,\n  // Long enough to notice the mistake and reach for Undo, short enough that\n  // the snackbar doesn't linger over the list.\n  duration = 5000,\n  onDelete,\n  className,\n}: {\n  items: UndoItem[];\n  duration?: number;\n  onDelete?: (items: UndoItem[]) => void;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  // Deleted but still undoable. A second delete stacks into this batch\n  // instead of replacing it: replacing would make the first delete permanent\n  // without the user ever seeing its timer run out.\n  const [pending, setPending] = useState<string[]>([]);\n  const [gone, setGone] = useState<string[]>([]);\n  // Bumped on every delete: restarts the ring and crossfades the message.\n  const [batch, setBatch] = useState(0);\n  const [announcement, setAnnouncement] = useState(\"\");\n  // Stored rather than derived, so the snackbar keeps its last words while\n  // it fades out instead of flashing \"0 items deleted\".\n  const [message, setMessage] = useState(\"\");\n\n  const rootRef = useRef<HTMLDivElement>(null);\n  const undoRef = useRef<HTMLButtonElement>(null);\n  const deleteRefs = useRef(new Map<string, HTMLButtonElement>());\n  const focusTarget = useRef<string | null>(null);\n\n  const visible = items.filter(\n    (i) => !pending.includes(i.id) && !gone.includes(i.id),\n  );\n  const pendingItems = items.filter((i) => pending.includes(i.id));\n\n  const focusInside = () =>\n    !!rootRef.current?.contains(document.activeElement);\n\n  const remove = (item: UndoItem) => {\n    // Hand focus to a neighbour so it isn't dropped on the body when the\n    // focused button unmounts.\n    if (focusInside()) {\n      const index = visible.findIndex((i) => i.id === item.id);\n      const next = visible[index + 1] ?? visible[index - 1];\n      focusTarget.current = next ? next.id : \"undo\";\n    }\n    setPending((p) => [...p, item.id]);\n    setBatch((b) => b + 1);\n    setMessage(\n      pending.length === 0\n        ? `Deleted \\u2018${item.name}\\u2019`\n        : `${pending.length + 1} items deleted`,\n    );\n    setAnnouncement(\n      `Deleted ${item.name}. Press Undo or ${shortcutName()} to restore.`,\n    );\n  };\n\n  const undo = () => {\n    if (pending.length === 0) return;\n    if (focusInside()) focusTarget.current = pending[0];\n    setPending([]);\n    setAnnouncement(\n      pending.length === 1 ? \"Restored\" : `Restored ${pending.length} items`,\n    );\n  };\n\n  const commit = () => {\n    if (pending.length === 0) return;\n    if (focusInside()) focusTarget.current = visible[0]?.id ?? null;\n    setGone((g) => [...g, ...pending]);\n    setPending([]);\n    onDelete?.(pendingItems);\n  };\n\n  useEffect(() => {\n    const target = focusTarget.current;\n    if (target === null) return;\n    focusTarget.current = null;\n    (target === \"undo\"\n      ? undoRef.current\n      : deleteRefs.current.get(target)\n    )?.focus();\n  }, [pending, gone]);\n\n  // Ctrl/Cmd+Z undoes while the snackbar shows, unless a text field wants\n  // the shortcut for its own undo. Same animation as clicking Undo: this is\n  // an occasional action, not a constant one.\n  useEffect(() => {\n    if (pending.length === 0) return;\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key.toLowerCase() !== \"z\" || !(e.metaKey || e.ctrlKey)) return;\n      if (e.shiftKey || e.altKey || isEditable(e.target)) return;\n      // Inert copies, like the index preview, stay quiet.\n      if (rootRef.current?.closest(\"[inert]\")) return;\n      e.preventDefault();\n      undo();\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  });\n\n  // A hidden tab pauses the countdown, so nobody comes back to an undo that\n  // expired unseen. Set on the DOM directly to skip a re-render.\n  useEffect(() => {\n    const sync = () =>\n      rootRef.current?.toggleAttribute(\"data-hidden\", document.hidden);\n    sync();\n    document.addEventListener(\"visibilitychange\", sync);\n    return () => document.removeEventListener(\"visibilitychange\", sync);\n  }, []);\n\n  const empty = visible.length === 0 && pending.length === 0;\n\n  return (\n    <div\n      ref={rootRef}\n      className={cn(\"flex w-[min(440px,100%)] flex-col gap-3\", className)}\n    >\n      <style href=\"undo-toast\" precedence=\"default\">\n        {CSS}\n      </style>\n\n      {/* Fixed height, so deleting and restoring never resize the demo.\n          24px radius around 8px padding leaves 16px for the rows. */}\n      <div className=\"relative h-60 rounded-[24px] bg-muted p-2 shadow-raised\">\n        <ul aria-label=\"Files\" className=\"relative\">\n          <AnimatePresence mode=\"popLayout\" initial={false}>\n            {visible.map((item) => (\n              <motion.li\n                key={item.id}\n                // Rows only change place, never size, so \"position\" keeps the\n                // text from stretching as they slide.\n                layout=\"position\"\n                initial={\n                  reduceMotion\n                    ? { opacity: 0 }\n                    : { opacity: 0, scale: 0.98, filter: \"blur(4px)\" }\n                }\n                animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n                exit={\n                  reduceMotion\n                    ? { opacity: 0, transition: LEAVE }\n                    : { opacity: 0, scale: 0.98, transition: LEAVE }\n                }\n                transition={{\n                  ...RESTORE,\n                  layout: reduceMotion ? INSTANT : SLIDE,\n                }}\n                className=\"flex h-14 items-center gap-3 rounded-2xl pr-2.5 pl-3.5 transition-[background-color] duration-150 ease-out hover:bg-background\"\n              >\n                <div className=\"flex min-w-0 flex-1 flex-col\">\n                  <span className=\"truncate text-[15px] leading-5 font-medium text-foreground\">\n                    {item.name}\n                  </span>\n                  <span className=\"truncate text-[13px] leading-5 text-muted-foreground\">\n                    {item.meta}\n                  </span>\n                </div>\n                <button\n                  ref={(el) => {\n                    if (el) deleteRefs.current.set(item.id, el);\n                    else deleteRefs.current.delete(item.id);\n                  }}\n                  type=\"button\"\n                  aria-label={`Delete ${item.name}`}\n                  onClick={() => remove(item)}\n                  className=\"flex size-9 shrink-0 touch-manipulation items-center justify-center rounded-full text-muted-foreground outline-hidden transition-[scale,color,background-color] duration-150 ease-out select-none hover:bg-foreground/5 hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color]\"\n                >\n                  <svg\n                    viewBox=\"0 0 16 16\"\n                    className=\"size-4\"\n                    fill=\"none\"\n                    stroke=\"currentColor\"\n                    strokeWidth={1.5}\n                    strokeLinecap=\"round\"\n                    strokeLinejoin=\"round\"\n                    aria-hidden\n                  >\n                    <path d=\"M2.75 4.25h10.5M6.25 4.25v-1.5h3.5v1.5M4 4.25l.6 8.1a1 1 0 0 0 1 .9h4.8a1 1 0 0 0 1-.9l.6-8.1M6.75 7v3.75M9.25 7v3.75\" />\n                  </svg>\n                </button>\n              </motion.li>\n            ))}\n          </AnimatePresence>\n        </ul>\n\n        <AnimatePresence initial={false}>\n          {empty && (\n            <motion.div\n              key=\"empty\"\n              initial={{ opacity: 0, filter: \"blur(4px)\" }}\n              animate={{ opacity: 1, filter: \"blur(0px)\" }}\n              exit={{ opacity: 0, transition: INSTANT }}\n              transition={RESTORE}\n              className=\"absolute inset-0 flex flex-col items-center justify-center gap-3 text-center\"\n            >\n              <span className=\"text-[15px] text-muted-foreground\">No files left</span>\n              <button\n                type=\"button\"\n                onClick={() => setGone([])}\n                className=\"h-9 touch-manipulation rounded-full bg-background px-4 text-sm font-medium text-foreground shadow-raised outline-hidden transition-[scale] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-none\"\n              >\n                Restore demo\n              </button>\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n\n      {/* Reserved slot, so the snackbar appearing never moves the list. */}\n      <div className=\"relative h-12\">\n        <AnimatePresence initial={false}>\n          {pending.length > 0 && (\n            <motion.div\n              key=\"snackbar\"\n              initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 12 }}\n              animate={{\n                opacity: 1,\n                y: 0,\n                transition: { duration: 0.25, ease: EASE_OUT },\n              }}\n              exit={\n                reduceMotion\n                  ? { opacity: 0, transition: LEAVE }\n                  : { opacity: 0, y: 6, transition: LEAVE }\n              }\n              className=\"undo-snackbar absolute inset-0 flex items-center gap-3 rounded-full bg-foreground pr-1.5 pl-3.5 text-background shadow-raised\"\n            >\n              <svg\n                viewBox=\"0 0 20 20\"\n                className=\"size-5 shrink-0 -rotate-90\"\n                fill=\"none\"\n                stroke=\"currentColor\"\n                strokeWidth={2}\n                aria-hidden\n              >\n                <circle cx=\"10\" cy=\"10\" r=\"8\" className=\"opacity-20\" />\n                <circle\n                  // A fresh element restarts the CSS animation from full.\n                  key={batch}\n                  cx=\"10\"\n                  cy=\"10\"\n                  r=\"8\"\n                  strokeLinecap=\"round\"\n                  className=\"undo-ring\"\n                  style={{ animationDuration: `${duration}ms` }}\n                  onAnimationEnd={(e) => {\n                    if (e.animationName === \"undo-countdown\") commit();\n                  }}\n                />\n              </svg>\n\n              {/* Old and new messages share this cell and crossfade, so a\n                  second delete reads as an update, not a new toast. */}\n              <span className=\"relative flex min-w-0 flex-1 items-center\">\n                <AnimatePresence mode=\"popLayout\" initial={false}>\n                  <motion.span\n                    key={batch}\n                    initial={\n                      reduceMotion\n                        ? { opacity: 0 }\n                        : { opacity: 0, y: 4, filter: \"blur(4px)\" }\n                    }\n                    animate={{\n                      opacity: 1,\n                      y: 0,\n                      filter: \"blur(0px)\",\n                      transition: { duration: 0.2, ease: EASE_OUT },\n                    }}\n                    exit={{ opacity: 0, transition: { duration: 0.12 } }}\n                    className=\"truncate text-[15px] font-medium\"\n                  >\n                    {message}\n                  </motion.span>\n                </AnimatePresence>\n              </span>\n\n              {/* 36px inside a 48px pill with 6px padding: both fully round,\n                  so the radii stay concentric. */}\n              <button\n                ref={undoRef}\n                type=\"button\"\n                onClick={undo}\n                aria-keyshortcuts=\"Control+Z Meta+Z\"\n                className=\"h-9 shrink-0 touch-manipulation rounded-full px-3.5 text-[15px] font-semibold outline-hidden transition-[scale,background-color] duration-150 ease-out select-none hover:bg-background/15 focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-background active:scale-[0.96] motion-reduce:transition-[background-color]\"\n              >\n                Undo\n              </button>\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {announcement}\n      </span>\n    </div>\n  );\n}\n\nconst FILES: UndoItem[] = [\n  { id: \"roadmap\", name: \"Q3 roadmap.pdf\", meta: \"2.4 MB, edited 2h ago\" },\n  { id: \"invoice\", name: \"Invoice 0142.pdf\", meta: \"86 KB, edited yesterday\" },\n  { id: \"offsite\", name: \"Team offsite.jpg\", meta: \"4.1 MB, edited Monday\" },\n  { id: \"notes\", name: \"Interview notes.md\", meta: \"12 KB, edited Aug 29\" },\n];\n\nexport default function UndoToastDemo() {\n  return <UndoToast items={FILES} />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["feedback"],"docs":"From ui lab: https://lab.xevrion.dev/lab/undo-toast"}