{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"toast","type":"registry:ui","title":"Toast","description":"Toast system (provider + useToast hook) with variants, actions, in-place updates, a collapsed stack that fans out on hover, swipe to dismiss and a pausable countdown bar.","dependencies":["motion","lucide-react"],"registryDependencies":["utils"],"files":[{"path":"registry/ui/toast.tsx","type":"registry:ui","content":"\"use client\";\n\nimport {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ReactNode,\n} from \"react\";\nimport { AnimatePresence, MotionConfig, motion } from \"motion/react\";\nimport { CircleAlert, CircleCheck, Info, Loader2, TriangleAlert, X } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\n// The countdown is a CSS animation on the progress bar: pausing it (hover, focus, hidden tab)\n// pauses the timer for free, and `animationend` is the dismiss signal.\nconst css = `\n@keyframes ui-toast-timer{from{scale:1 1}to{scale:0 1}}\n.ui-toast-bar{animation:ui-toast-timer var(--ui-toast-ms) linear forwards;transform-origin:left}\n[data-paused] .ui-toast-bar{animation-play-state:paused}\n@keyframes ui-toast-icon{0%{scale:.3;rotate:-30deg;opacity:0}60%{scale:1.15}100%{scale:1;rotate:0;opacity:1}}\n.ui-toast-icon{animation:ui-toast-icon .45s cubic-bezier(.3,1.4,.5,1) .08s both}\n@media (prefers-reduced-motion:reduce){.ui-toast-bar{opacity:0}.ui-toast-icon{animation:none}}\n`;\n\nexport type ToastVariant = \"default\" | \"success\" | \"error\" | \"warning\" | \"info\" | \"loading\";\nexport type ToastPlacement = \"top-left\" | \"top-center\" | \"top-right\" | \"bottom-left\" | \"bottom-center\" | \"bottom-right\";\n\nexport interface ToastOptions {\n  /** Reuse an id to update a toast in place (e.g. loading -> success). */\n  id?: string;\n  title: ReactNode;\n  description?: ReactNode;\n  variant?: ToastVariant;\n  /** ms before auto-dismiss; Infinity keeps it until closed. Loading toasts never auto-dismiss. */\n  duration?: number;\n  action?: { label: string; onClick: () => void };\n}\n\ntype ToastItem = ToastOptions & { id: string; variant: ToastVariant; duration: number };\n\ntype Ctx = { toast: (t: ToastOptions) => string; dismiss: (id?: string) => void };\nconst ToastContext = createContext<Ctx | null>(null);\n\nexport function useToast() {\n  const ctx = useContext(ToastContext);\n  if (!ctx) throw new Error(\"useToast must be used inside <ToastProvider>.\");\n  return ctx;\n}\n\nconst icons: Record<ToastVariant, ReactNode> = {\n  default: null,\n  success: <CircleCheck className=\"text-emerald-500\" />,\n  error: <CircleAlert className=\"text-destructive\" />,\n  warning: <TriangleAlert className=\"text-amber-500\" />,\n  info: <Info className=\"text-sky-500\" />,\n  loading: <Loader2 className=\"animate-spin text-muted-foreground\" />,\n};\n\nconst GAP = 10;\nconst PEEK = 12; // px each stacked toast peeks out behind the one in front\nconst VISIBLE = 3;\n\nexport interface ToastProviderProps {\n  children?: ReactNode;\n  placement?: ToastPlacement;\n  /** `fixed` pins to the viewport; `absolute` stays inside the nearest positioned ancestor. */\n  position?: \"fixed\" | \"absolute\";\n  /** Default auto-dismiss time, ms. */\n  duration?: number;\n  /** Always show the full list instead of a collapsed stack. */\n  expand?: boolean;\n}\n\nlet seq = 0;\n\nexport function ToastProvider({\n  children,\n  placement = \"bottom-right\",\n  position = \"fixed\",\n  duration = 4000,\n  expand = false,\n}: ToastProviderProps) {\n  const [toasts, setToasts] = useState<ToastItem[]>([]);\n  const [heights, setHeights] = useState<Record<string, number>>({});\n  const [hovered, setHovered] = useState(false);\n  const [focused, setFocused] = useState(false);\n\n  const dismiss = useCallback((id?: string) => {\n    setToasts((all) => (id === undefined ? [] : all.filter((t) => t.id !== id)));\n  }, []);\n\n  const toast = useCallback(\n    (o: ToastOptions) => {\n      const id = o.id ?? `toast-${++seq}`;\n      const variant = o.variant ?? \"default\";\n      const item: ToastItem = { ...o, id, variant, duration: variant === \"loading\" ? Infinity : (o.duration ?? duration) };\n      setToasts((all) => (all.some((t) => t.id === id) ? all.map((t) => (t.id === id ? item : t)) : [item, ...all]));\n      return id;\n    },\n    [duration],\n  );\n\n  const ctx = useMemo(() => ({ toast, dismiss }), [toast, dismiss]);\n  const measure = useCallback((id: string, h: number) => setHeights((m) => (m[id] === h ? m : { ...m, [id]: h })), []);\n\n  const top = placement.startsWith(\"top\");\n  const open = expand || hovered || focused;\n  const frontHeight = heights[toasts[0]?.id] ?? 0;\n\n  return (\n    <ToastContext value={ctx}>\n      {children}\n      <style href=\"ui-toast\" precedence=\"default\">\n        {css}\n      </style>\n      <MotionConfig reducedMotion=\"user\">\n        <section\n          aria-label=\"Notifications\"\n          tabIndex={-1}\n          onPointerEnter={() => setHovered(true)}\n          onPointerLeave={() => setHovered(false)}\n          onFocus={() => setFocused(true)}\n          onBlur={(e) => !e.currentTarget.contains(e.relatedTarget) && setFocused(false)}\n          className={cn(\n            \"pointer-events-none z-[100] w-[calc(100%-2rem)] max-w-sm outline-none\",\n            position === \"fixed\" ? \"fixed\" : \"absolute\",\n            top ? \"top-4\" : \"bottom-4\",\n            placement.endsWith(\"left\") && \"left-4\",\n            placement.endsWith(\"right\") && \"right-4\",\n            placement.endsWith(\"center\") && \"left-1/2 -translate-x-1/2\",\n          )}\n        >\n          <ol\n            className=\"pointer-events-auto relative\"\n            // Reserve room for the stack (or the full list when expanded) so hover keeps working in the gaps.\n            style={{\n              height: toasts.length\n                ? open\n                  ? toasts.reduce((s, t) => s + (heights[t.id] ?? 0), 0) + GAP * (toasts.length - 1)\n                  : frontHeight + PEEK * Math.min(toasts.length - 1, VISIBLE - 1)\n                : 0,\n            }}\n          >\n            <AnimatePresence initial={false}>\n              {toasts.map((t, i) => {\n                const before = toasts.slice(0, i).reduce((s, x) => s + (heights[x.id] ?? 0) + GAP, 0);\n                const offset = open ? before : i * PEEK;\n                return (\n                  <Toast\n                    key={t.id}\n                    item={t}\n                    index={i}\n                    top={top}\n                    y={top ? offset : -offset}\n                    scale={open ? 1 : 1 - i * 0.05}\n                    hidden={!open && i >= VISIBLE}\n                    collapsedHeight={!open && i > 0 ? frontHeight : undefined}\n                    paused={open}\n                    onHeight={measure}\n                    onDismiss={dismiss}\n                  />\n                );\n              })}\n            </AnimatePresence>\n          </ol>\n        </section>\n      </MotionConfig>\n    </ToastContext>\n  );\n}\n\ninterface ToastProps {\n  item: ToastItem;\n  index: number;\n  top: boolean;\n  y: number;\n  scale: number;\n  hidden: boolean;\n  /** When collapsed, back toasts take the front toast's height so only their edge peeks out. */\n  collapsedHeight?: number;\n  paused: boolean;\n  onHeight: (id: string, h: number) => void;\n  onDismiss: (id: string) => void;\n}\n\nfunction Toast({ item, index, top, y, scale, hidden, collapsedHeight, paused, onHeight, onDismiss }: ToastProps) {\n  const inner = useRef<HTMLDivElement>(null);\n  const [tabHidden, setTabHidden] = useState(false);\n\n  useLayoutEffect(() => {\n    const el = inner.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  useEffect(() => {\n    const sync = () => setTabHidden(document.hidden);\n    document.addEventListener(\"visibilitychange\", sync);\n    return () => document.removeEventListener(\"visibilitychange\", sync);\n  }, []);\n\n  const icon = icons[item.variant];\n  const timed = Number.isFinite(item.duration);\n  const alert = item.variant === \"error\" || item.variant === \"warning\";\n\n  return (\n    <motion.li\n      role={alert ? \"alert\" : \"status\"}\n      aria-live={alert ? \"assertive\" : \"polite\"}\n      aria-atomic\n      data-paused={paused || tabHidden || undefined}\n      initial={{ opacity: 0, y: top ? -40 : 40, scale: 0.92 }}\n      animate={{ opacity: hidden ? 0 : 1, y, scale, height: collapsedHeight ?? \"auto\" }}\n      exit={{ opacity: 0, scale: 0.9, transition: { duration: 0.2 } }}\n      transition={{ type: \"spring\", stiffness: 380, damping: 32 }}\n      drag=\"x\"\n      dragSnapToOrigin\n      dragElastic={0.6}\n      onDragEnd={(_, info) => Math.abs(info.offset.x) > 80 && onDismiss(item.id)}\n      onKeyDown={(e) => e.key === \"Escape\" && onDismiss(item.id)}\n      style={{ zIndex: 100 - index, transformOrigin: top ? \"bottom center\" : \"top center\" }}\n      className={cn(\n        \"absolute inset-x-0 cursor-grab touch-pan-y overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-lg shadow-black/15 active:cursor-grabbing\",\n        top ? \"top-0\" : \"bottom-0\",\n        hidden && \"pointer-events-none\",\n      )}\n      inert={hidden || undefined}\n    >\n      <div\n        ref={inner}\n        className={cn(\n          \"flex items-start gap-3 p-4 pr-10 transition-opacity duration-200\",\n          collapsedHeight !== undefined && \"opacity-0\",\n        )}\n      >\n        {icon && (\n          <span key={item.variant} className=\"ui-toast-icon mt-0.5 shrink-0 [&_svg]:size-[18px]\">\n            {icon}\n          </span>\n        )}\n        <div className=\"grid min-w-0 flex-1 gap-1\">\n          <p className=\"text-sm leading-tight font-semibold\">{item.title}</p>\n          {item.description && <p className=\"text-sm leading-snug text-muted-foreground\">{item.description}</p>}\n          {item.action && (\n            <button\n              type=\"button\"\n              onClick={() => {\n                item.action!.onClick();\n                onDismiss(item.id);\n              }}\n              className=\"mt-1.5 inline-flex h-7 w-fit items-center rounded-md bg-primary px-2.5 text-xs font-medium text-primary-foreground outline-none transition-[background-color,scale] hover:bg-primary/90 focus-visible:ring-2 focus-visible:ring-ring/60 active:scale-95\"\n            >\n              {item.action.label}\n            </button>\n          )}\n        </div>\n        <button\n          type=\"button\"\n          aria-label=\"Dismiss notification\"\n          onClick={() => onDismiss(item.id)}\n          className=\"absolute top-3 right-3 grid size-6 place-items-center rounded-md text-muted-foreground outline-none transition-[background-color,color,rotate] duration-200 hover:rotate-90 hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 motion-reduce:transition-none\"\n        >\n          <X className=\"size-3.5\" />\n        </button>\n      </div>\n      {timed && (\n        <span\n          key={`${item.variant}-${item.duration}-${String(item.title)}`}\n          aria-hidden\n          className=\"ui-toast-bar absolute inset-x-0 bottom-0 h-0.5 bg-primary/60\"\n          style={{ [\"--ui-toast-ms\" as string]: `${item.duration}ms` }}\n          onAnimationEnd={() => onDismiss(item.id)}\n        />\n      )}\n    </motion.li>\n  );\n}\n"}]}