{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"react-toast-notification-system-with-undo-stacking-and-swipe-to-dismiss","type":"registry:component","title":"React Toast Notification System with Undo, Stacking and Swipe to Dismiss","description":"Free React toast in one file: toast() function, success, error, info and loading states, undo button, stacked cards that fan out, swipe to dismiss.","dependencies":["framer-motion"],"files":[{"path":"components/we-inc/react-toast-notification-system-with-undo-stacking-and-swipe-to-dismiss.tsx","type":"registry:component","content":"import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport { AnimatePresence, motion, useReducedMotion, type PanInfo } from \"framer-motion\";\n\n/* ------------------------------------------------------------------ */\n/* 1. The toast store. Copy this block into lib/toast.ts in your app.  */\n/* ------------------------------------------------------------------ */\n\ntype ToastType = \"success\" | \"error\" | \"info\" | \"loading\";\ntype ToastAction = { label: string; onClick: () => void };\ntype ToastItem = {\n  id: number;\n  type: ToastType;\n  title: string;\n  description?: string;\n  action?: ToastAction;\n  duration: number;\n};\ntype ToastOptions = Partial<Omit<ToastItem, \"id\" | \"title\" | \"type\">>;\n\nconst DEFAULT_DURATION = 5000;\nconst MAX_TOASTS = 5;\nconst VISIBLE_WHEN_STACKED = 3;\n\nlet toasts: ToastItem[] = [];\nlet nextId = 1;\nconst listeners = new Set<() => void>();\nconst emit = () => listeners.forEach((l) => l());\nconst subscribe = (l: () => void) => {\n  listeners.add(l);\n  return () => listeners.delete(l);\n};\nconst getSnapshot = () => toasts;\n\nfunction push(type: ToastType, title: string, opts: ToastOptions = {}) {\n  const id = nextId++;\n  const duration = opts.duration ?? (type === \"loading\" ? Infinity : type === \"error\" ? 8000 : DEFAULT_DURATION);\n  toasts = [{ id, type, title, ...opts, duration }, ...toasts].slice(0, MAX_TOASTS);\n  emit();\n  return id;\n}\n\nfunction update(id: number, type: ToastType, title: string, opts: ToastOptions = {}) {\n  toasts = toasts.map((t) =>\n    t.id === id ? { ...t, type, title, description: opts.description, action: opts.action, duration: opts.duration ?? DEFAULT_DURATION } : t,\n  );\n  emit();\n}\n\nfunction dismiss(id?: number) {\n  toasts = id === undefined ? [] : toasts.filter((t) => t.id !== id);\n  emit();\n}\n\nexport const toast = Object.assign((title: string, opts?: ToastOptions) => push(\"info\", title, opts), {\n  success: (title: string, opts?: ToastOptions) => push(\"success\", title, opts),\n  error: (title: string, opts?: ToastOptions) => push(\"error\", title, opts),\n  info: (title: string, opts?: ToastOptions) => push(\"info\", title, opts),\n  loading: (title: string, opts?: ToastOptions) => push(\"loading\", title, opts),\n  dismiss,\n  promise<T>(work: Promise<T>, msg: { loading: string; success: string; error: string }) {\n    const id = push(\"loading\", msg.loading);\n    work.then(\n      () => update(id, \"success\", msg.success),\n      () => update(id, \"error\", msg.error),\n    );\n    return work;\n  },\n});\n\n/* ------------------------------------------------------------------ */\n/* 2. Icons and colours per type                                       */\n/* ------------------------------------------------------------------ */\n\nfunction TypeIcon({ type }: { type: ToastType }) {\n  if (type === \"loading\") {\n    return (\n      <svg viewBox=\"0 0 20 20\" className=\"h-5 w-5 animate-spin motion-reduce:animate-none\" aria-hidden=\"true\">\n        <circle cx=\"10\" cy=\"10\" r=\"7.5\" fill=\"none\" stroke=\"currentColor\" strokeOpacity=\"0.2\" strokeWidth=\"2\" />\n        <path d=\"M17.5 10a7.5 7.5 0 0 0-7.5-7.5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" />\n      </svg>\n    );\n  }\n  const paths: Record<Exclude<ToastType, \"loading\">, string> = {\n    success: \"M6.5 10.5l2.4 2.4 4.6-5.3\",\n    error: \"M10 6.2v4.6M10 13.6v.1\",\n    info: \"M10 9.2v4.6M10 6.4v.1\",\n  };\n  return (\n    <svg viewBox=\"0 0 20 20\" className=\"h-5 w-5\" aria-hidden=\"true\">\n      <circle cx=\"10\" cy=\"10\" r=\"8.25\" fill=\"currentColor\" />\n      <path d={paths[type]} fill=\"none\" stroke=\"white\" strokeWidth=\"1.9\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n\nconst ICON_COLOUR: Record<ToastType, string> = {\n  success: \"text-emerald-600\",\n  error: \"text-red-600\",\n  info: \"text-sky-600\",\n  loading: \"text-slate-500\",\n};\nconst ICON_COLOUR_DARK: Record<ToastType, string> = {\n  success: \"text-emerald-400\",\n  error: \"text-red-400\",\n  info: \"text-sky-400\",\n  loading: \"text-slate-400\",\n};\n\n/* ------------------------------------------------------------------ */\n/* 3. One toast: its own timer, swipe and close button                 */\n/* ------------------------------------------------------------------ */\n\ntype ToastCardProps = {\n  item: ToastItem;\n  index: number;\n  offset: number;\n  frontHeight: number;\n  expanded: boolean;\n  paused: boolean;\n  dark: boolean;\n  reduced: boolean;\n  onHeight: (id: number, h: number) => void;\n};\n\nfunction ToastCard({ item, index, offset, frontHeight, expanded, paused, dark, reduced, onHeight }: ToastCardProps) {\n  const ref = useRef<HTMLLIElement>(null);\n  const remaining = useRef(item.duration);\n  const [progressKey, setProgressKey] = useState(0);\n\n  // Reset the clock when the toast changes type (loading -> success).\n  useEffect(() => {\n    remaining.current = item.duration;\n    setProgressKey((k) => k + 1);\n  }, [item.type, item.duration]);\n\n  useEffect(() => {\n    if (paused || !Number.isFinite(item.duration)) return;\n    const started = Date.now();\n    const timer = window.setTimeout(() => dismiss(item.id), remaining.current);\n    return () => {\n      window.clearTimeout(timer);\n      remaining.current -= Date.now() - started;\n    };\n  }, [paused, item.id, item.duration, progressKey]);\n\n  useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(() => onHeight(item.id, el.offsetHeight));\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [item.id, onHeight]);\n\n  const hidden = index >= VISIBLE_WHEN_STACKED && !expanded;\n  const behind = index > 0 && !expanded;\n  const y = expanded ? -offset : -index * 14;\n  const scale = expanded ? 1 : 1 - index * 0.05;\n\n  const onDragEnd = (_: unknown, info: PanInfo) => {\n    if (Math.abs(info.offset.x) > 90 || Math.abs(info.velocity.x) > 600) dismiss(item.id);\n  };\n\n  const surface = dark\n    ? \"bg-zinc-900 text-zinc-50 ring-1 ring-white/10 shadow-[0_12px_32px_-12px_rgba(0,0,0,0.7)]\"\n    : \"bg-white text-zinc-900 ring-1 ring-zinc-900/[0.07] shadow-[0_1px_2px_rgba(16,24,40,0.05),0_12px_32px_-12px_rgba(16,24,40,0.22)]\";\n  const muted = dark ? \"text-zinc-400\" : \"text-zinc-600\";\n\n  return (\n    <motion.li\n      ref={ref}\n      role={item.type === \"error\" ? \"alert\" : \"status\"}\n      aria-atomic=\"true\"\n      tabIndex={-1}\n      layout={false}\n      initial={reduced ? { opacity: 0 } : { opacity: 0, y: 40, scale: 0.96 }}\n      animate={{ opacity: hidden ? 0 : 1, y: reduced ? (expanded ? -offset : 0) : y, scale: reduced ? 1 : scale }}\n      exit={reduced ? { opacity: 0 } : { opacity: 0, scale: 0.96, transition: { duration: 0.18 } }}\n      transition={reduced ? { duration: 0 } : { type: \"spring\", stiffness: 420, damping: 36, mass: 0.8 }}\n      drag={reduced ? false : \"x\"}\n      dragSnapToOrigin\n      dragElastic={0.5}\n      onDragEnd={onDragEnd}\n      style={{\n        zIndex: MAX_TOASTS - index,\n        height: behind && frontHeight ? frontHeight : undefined,\n        pointerEvents: hidden ? \"none\" : \"auto\",\n        transformOrigin: \"bottom center\",\n      }}\n      aria-hidden={hidden || undefined}\n      className={`absolute bottom-0 left-0 right-0 cursor-grab touch-pan-y select-none overflow-hidden rounded-2xl active:cursor-grabbing ${surface}`}\n    >\n      <div\n        className={`flex items-start gap-3 p-4 pr-3 transition-opacity duration-200 ${behind ? \"opacity-0\" : \"opacity-100\"}`}\n      >\n        <span className={`mt-px shrink-0 ${dark ? ICON_COLOUR_DARK[item.type] : ICON_COLOUR[item.type]}`}>\n          <TypeIcon type={item.type} />\n        </span>\n        <div className=\"min-w-0 flex-1\">\n          <p className=\"text-[14px] font-semibold leading-5 tracking-[-0.01em]\">{item.title}</p>\n          {item.description && <p className={`mt-0.5 text-[13px] leading-5 ${muted}`}>{item.description}</p>}\n        </div>\n        {item.action && (\n          <button\n            type=\"button\"\n            tabIndex={behind ? -1 : 0}\n            onClick={() => {\n              item.action?.onClick();\n              dismiss(item.id);\n            }}\n            className={`shrink-0 self-center rounded-lg px-3 py-1.5 text-[13px] font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500 ${\n              dark ? \"bg-white text-zinc-900 hover:bg-zinc-200\" : \"bg-zinc-900 text-white hover:bg-zinc-700\"\n            }`}\n          >\n            {item.action.label}\n          </button>\n        )}\n        <button\n          type=\"button\"\n          tabIndex={behind ? -1 : 0}\n          aria-label={`Dismiss: ${item.title}`}\n          onClick={() => dismiss(item.id)}\n          className={`-my-1 grid h-8 w-8 shrink-0 place-items-center self-center rounded-lg transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500 ${\n            dark ? \"text-zinc-400 hover:bg-white/10 hover:text-white\" : \"text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900\"\n          }`}\n        >\n          <svg viewBox=\"0 0 20 20\" className=\"h-4 w-4\" aria-hidden=\"true\">\n            <path d=\"M5.5 5.5l9 9M14.5 5.5l-9 9\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" />\n          </svg>\n        </button>\n      </div>\n      {Number.isFinite(item.duration) && !behind && (\n        <span\n          key={progressKey}\n          aria-hidden=\"true\"\n          className={`absolute bottom-0 left-0 h-[2px] w-full origin-left motion-reduce:hidden ${dark ? \"bg-white/25\" : \"bg-zinc-900/15\"}`}\n          style={{\n            animation: `rtn-shrink ${item.duration}ms linear forwards`,\n            animationPlayState: paused ? \"paused\" : \"running\",\n          }}\n        />\n      )}\n    </motion.li>\n  );\n}\n\n/* ------------------------------------------------------------------ */\n/* 4. The viewport. Render once near the root of your app.             */\n/* ------------------------------------------------------------------ */\n\nfunction Toaster({ dark, className = \"\", holdOpenFor = 0 }: { dark: boolean; className?: string; holdOpenFor?: number }) {\n  const items = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n  const reduced = useReducedMotion() ?? false;\n  const [hovered, setHovered] = useState(false);\n  const [focused, setFocused] = useState(false);\n  const [heights, setHeights] = useState<Record<number, number>>({});\n  // Optional: start fanned out (used by the demo so every type is visible), then fold away.\n  const [held, setHeld] = useState(holdOpenFor > 0);\n  useEffect(() => {\n    if (!held) return;\n    const t = window.setTimeout(() => setHeld(false), holdOpenFor);\n    return () => window.clearTimeout(t);\n  }, [held, holdOpenFor]);\n  const expanded = hovered || focused || held;\n\n  const onHeight = useCallback((id: number, h: number) => {\n    setHeights((prev) => (prev[id] === h ? prev : { ...prev, [id]: h }));\n  }, []);\n\n  useEffect(() => {\n    if (items.length === 0) {\n      setHovered(false);\n      setFocused(false);\n    }\n  }, [items.length]);\n\n  const GAP = 10;\n  const offsets = items.map((_, i) => items.slice(0, i).reduce((sum, t) => sum + (heights[t.id] ?? 72) + GAP, 0));\n  const frontHeight = items[0] ? heights[items[0].id] ?? 0 : 0;\n  const stackHeight = expanded ? offsets[items.length - 1] + (heights[items[items.length - 1]?.id] ?? 0) : frontHeight + 28;\n\n  return (\n    <section\n      aria-label=\"Notifications\"\n      onMouseEnter={() => {\n        setHeld(false);\n        setHovered(true);\n      }}\n      onMouseLeave={() => setHovered(false)}\n      onFocus={() => setFocused(true)}\n      onBlur={(e) => {\n        if (!e.currentTarget.contains(e.relatedTarget as Node)) setFocused(false);\n      }}\n      onKeyDown={(e) => {\n        if (e.key === \"Escape\" && items[0]) dismiss(items[0].id);\n      }}\n      className={className}\n    >\n      <ol className=\"relative w-full\" style={{ height: items.length ? stackHeight : 0 }}>\n        <AnimatePresence initial={false}>\n          {items.map((item, i) => (\n            <ToastCard\n              key={item.id}\n              item={item}\n              index={i}\n              offset={offsets[i]}\n              frontHeight={frontHeight}\n              expanded={expanded}\n              paused={expanded}\n              dark={dark}\n              reduced={reduced}\n              onHeight={onHeight}\n            />\n          ))}\n        </AnimatePresence>\n      </ol>\n    </section>\n  );\n}\n\n/* ------------------------------------------------------------------ */\n/* 5. Demo: buttons that fire each kind of toast                       */\n/* ------------------------------------------------------------------ */\n\nconst wait = (ms: number, fail = false) =>\n  new Promise<void>((resolve, reject) => window.setTimeout(fail ? reject : resolve, ms));\n\nconst demos: { label: string; code: string; dot: string; run: () => void }[] = [\n  {\n    label: \"Success\",\n    code: 'toast.success(\"Invoice sent\")',\n    dot: \"bg-emerald-500\",\n    run: () => toast.success(\"Invoice sent\", { description: \"Maple & Rye Bakery will get it in a minute.\" }),\n  },\n  {\n    label: \"Error\",\n    code: 'toast.error(\"Card declined\")',\n    dot: \"bg-red-500\",\n    run: () =>\n      toast.error(\"Card declined\", {\n        description: \"The bank refused the charge. Try another card.\",\n        action: { label: \"Retry\", onClick: () => toast.promise(wait(1400), { loading: \"Charging card\", success: \"Payment received\", error: \"Still declined\" }) },\n      }),\n  },\n  {\n    label: \"Info\",\n    code: 'toast.info(\"New version ready\")',\n    dot: \"bg-sky-500\",\n    run: () => toast.info(\"New version ready\", { description: \"Reload when it suits you to get the latest changes.\" }),\n  },\n  {\n    label: \"Loading\",\n    code: \"toast.promise(save(), {...})\",\n    dot: \"bg-zinc-400\",\n    run: () => toast.promise(wait(1800), { loading: \"Uploading 4 photos\", success: \"4 photos uploaded\", error: \"Upload failed\" }),\n  },\n  {\n    label: \"With undo\",\n    code: 'toast(\"Moved to bin\", { action })',\n    dot: \"bg-amber-500\",\n    run: () =>\n      toast(\"Project moved to bin\", {\n        description: \"Harbour Street refit\",\n        action: { label: \"Undo\", onClick: () => toast.success(\"Project restored\") },\n      }),\n  },\n];\n\nexport default function ReactToastNotificationSystem() {\n  const [dark, setDark] = useState(false);\n  const [lastCode, setLastCode] = useState(demos[3].code);\n\n  // Start with a full stack so the preview shows the finished state, then hold it.\n  useEffect(() => {\n    toast.dismiss();\n    toast.promise(wait(2600), { loading: \"Uploading 4 photos\", success: \"4 photos uploaded\", error: \"Upload failed\" });\n    toast.error(\"Card declined\", {\n      description: \"The bank refused the charge.\",\n      duration: 20000,\n      action: { label: \"Retry\", onClick: () => toast.success(\"Payment received\") },\n    });\n    toast.success(\"Invoice sent\", { description: \"Maple & Rye Bakery will get it in a minute.\", duration: 20000 });\n    toast(\"Project moved to bin\", {\n      description: \"Harbour Street refit\",\n      duration: 20000,\n      action: { label: \"Undo\", onClick: () => toast.success(\"Project restored\") },\n    });\n    return () => toast.dismiss();\n  }, []);\n\n  const stage = dark ? \"bg-zinc-950\" : \"bg-stone-100\";\n  const panel = dark ? \"bg-zinc-900 ring-white/10\" : \"bg-white ring-zinc-900/[0.06]\";\n  const heading = dark ? \"text-zinc-50\" : \"text-zinc-900\";\n  const body = dark ? \"text-zinc-400\" : \"text-zinc-600\";\n\n  return (\n    <div\n      className={`relative min-h-[880px] w-full sm:min-h-[640px] lg:flex lg:items-center overflow-hidden px-4 py-10 transition-colors duration-300 sm:px-8 ${stage}`}\n      style={{ fontFamily: '\"Inter Tight\", Inter, ui-sans-serif, system-ui, sans-serif' }}\n    >\n      <style>{`\n        @keyframes rtn-shrink { from { transform: scaleX(1); } to { transform: scaleX(0); } }\n      `}</style>\n\n      <div className=\"mx-auto flex w-full max-w-5xl flex-col gap-8 lg:flex-row lg:items-start lg:justify-between\">\n        <div className={`w-full max-w-md rounded-3xl p-6 ring-1 ${panel}`}>\n          <div className=\"flex items-center justify-between gap-4\">\n            <h2 className={`text-lg font-semibold tracking-[-0.02em] ${heading}`}>Toasts</h2>\n            <button\n              type=\"button\"\n              role=\"switch\"\n              aria-checked={dark}\n              onClick={() => setDark((d) => !d)}\n              className={`flex h-10 items-center gap-2 rounded-full px-3 text-[13px] font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500 ${\n                dark ? \"bg-white/10 text-zinc-100\" : \"bg-zinc-100 text-zinc-700\"\n              }`}\n            >\n              <span className={`relative h-4 w-7 rounded-full transition-colors ${dark ? \"bg-sky-500\" : \"bg-zinc-300\"}`}>\n                <span className={`absolute left-0 top-0.5 h-3 w-3 rounded-full bg-white transition-transform ${dark ? \"translate-x-3.5\" : \"translate-x-0.5\"}`} />\n              </span>\n              Dark\n            </button>\n          </div>\n          <p className={`mt-1 text-[14px] leading-6 ${body}`}>Fire one, hover the stack to fan it out, drag a toast sideways to throw it away.</p>\n\n          <div className=\"mt-5 grid grid-cols-2 gap-2 sm:grid-cols-3\">\n            {demos.map((d) => (\n              <button\n                key={d.label}\n                type=\"button\"\n                onClick={() => {\n                  d.run();\n                  setLastCode(d.code);\n                }}\n                className={`flex h-11 items-center gap-2 rounded-xl px-3 text-[14px] font-medium ring-1 transition active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500 motion-reduce:active:scale-100 ${\n                  dark ? \"bg-zinc-800 text-zinc-100 ring-white/10 hover:bg-zinc-700\" : \"bg-white text-zinc-800 ring-zinc-200 hover:bg-zinc-50\"\n                }`}\n              >\n                <span className={`h-2 w-2 rounded-full ${d.dot}`} aria-hidden=\"true\" />\n                {d.label}\n              </button>\n            ))}\n            <button\n              type=\"button\"\n              onClick={() => toast.dismiss()}\n              className={`flex h-11 items-center justify-center rounded-xl px-3 text-[14px] font-medium transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500 ${\n                dark ? \"text-zinc-300 hover:bg-white/5\" : \"text-zinc-600 hover:bg-zinc-100\"\n              }`}\n            >\n              Clear all\n            </button>\n          </div>\n\n          <pre\n            className={`mt-5 overflow-x-auto rounded-xl px-4 py-3 text-[13px] leading-6 ${\n              dark ? \"bg-black/40 text-zinc-300\" : \"bg-zinc-950 text-zinc-200\"\n            }`}\n          >\n            <code style={{ fontFamily: \"ui-monospace, SFMono-Regular, Menlo, monospace\" }}>{lastCode}</code>\n          </pre>\n        </div>\n\n        \n      </div>\n\n      <Toaster dark={dark} holdOpenFor={6000} className=\"absolute bottom-6 left-4 right-4 sm:left-auto sm:right-8 sm:w-[380px]\" />\n    </div>\n  );\n}\n"}]}
