{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"alert-dialog","type":"registry:ui","title":"Alert Dialog","description":"Confirmation modal on the native <dialog> with a springy scale-in, focus starting on Cancel, async confirm with spinner and destructive styling.","dependencies":["lucide-react"],"registryDependencies":["utils"],"files":[{"path":"registry/ui/alert-dialog.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from \"react\";\nimport { Loader2, TriangleAlert } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\n// Enter/exit is pure CSS on the native <dialog>: [open] + @starting-style for the\n// entrance and `allow-discrete` on display/overlay to keep it painted while it fades out.\nconst css = `\n.ui-alert{opacity:0;scale:.94;transition:opacity .16s ease-in,scale .16s ease-in,display .16s allow-discrete,overlay .16s allow-discrete}\n.ui-alert[open]{opacity:1;scale:1;transition-timing-function:cubic-bezier(.2,.9,.25,1.2);transition-duration:.26s}\n@starting-style{.ui-alert[open]{opacity:0;scale:.94}}\n.ui-alert::backdrop{background:rgb(0 0 0/0);backdrop-filter:blur(0);transition:background .22s,backdrop-filter .22s,display .22s allow-discrete,overlay .22s allow-discrete}\n.ui-alert[open]::backdrop{background:rgb(0 0 0/.55);backdrop-filter:blur(4px)}\n@starting-style{.ui-alert[open]::backdrop{background:rgb(0 0 0/0);backdrop-filter:blur(0)}}\nhtml:has(.ui-alert:modal){overflow:hidden}\n@media (prefers-reduced-motion:reduce){.ui-alert,.ui-alert::backdrop{transition-duration:0s!important}}\n`;\n\nconst btn =\n  \"inline-flex h-10 items-center justify-center gap-2 rounded-lg px-4 text-sm font-medium outline-none transition-[background-color,scale,opacity] focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-card active:scale-[0.97] disabled:pointer-events-none disabled:opacity-60\";\n\nexport interface AlertDialogProps {\n  title: ReactNode;\n  description?: ReactNode;\n  /** Label of the built-in trigger button. Omit to control the dialog yourself via `open`. */\n  trigger?: ReactNode;\n  confirmLabel?: ReactNode;\n  cancelLabel?: ReactNode;\n  /** Red confirm button, warning icon and red trigger. */\n  destructive?: boolean;\n  /** Return a promise to show a spinner and keep the dialog open until it resolves. */\n  onConfirm?: () => void | Promise<unknown>;\n  onCancel?: () => void;\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /** `fixed` = true modal via showModal(); `absolute` = contained in the nearest positioned parent. */\n  position?: \"fixed\" | \"absolute\";\n  className?: string;\n}\n\nexport function AlertDialog({\n  title,\n  description,\n  trigger,\n  confirmLabel = \"Continue\",\n  cancelLabel = \"Cancel\",\n  destructive = false,\n  onConfirm,\n  onCancel,\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  position = \"fixed\",\n  className,\n}: AlertDialogProps) {\n  const [inner, setInner] = useState(defaultOpen);\n  const [busy, setBusy] = useState(false);\n  const open = openProp ?? inner;\n  const modal = position === \"fixed\";\n  const ref = useRef<HTMLDialogElement>(null);\n  const cancelRef = useRef<HTMLButtonElement>(null);\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const returnTo = useRef<HTMLElement | null>(null);\n  const mounted = useRef(false);\n  const id = useId();\n\n  const setOpen = (next: boolean) => {\n    if (openProp === undefined) setInner(next);\n    onOpenChange?.(next);\n  };\n\n  useEffect(() => {\n    const d = ref.current;\n    const firstRun = !mounted.current;\n    mounted.current = true;\n    if (!d) return;\n    if (open && !d.open) {\n      returnTo.current = document.activeElement as HTMLElement | null;\n      if (modal) d.showModal();\n      else d.open = true; // attribute only: no focus steal when rendered open on page load\n      // WAI-ARIA alertdialog: start on the least destructive action.\n      if (modal || !firstRun) cancelRef.current?.focus();\n    } else if (!open && d.open) {\n      d.close();\n      const back = returnTo.current?.isConnected && returnTo.current !== document.body ? returnTo.current : triggerRef.current;\n      back?.focus({ preventScroll: true });\n    }\n  }, [open, modal]);\n\n  const cancel = () => {\n    if (busy) return;\n    onCancel?.();\n    setOpen(false);\n  };\n\n  const confirm = async () => {\n    const result = onConfirm?.();\n    if (result instanceof Promise) {\n      setBusy(true);\n      try {\n        await result;\n        setOpen(false);\n      } catch {\n        // Stay open so the user can retry.\n      } finally {\n        setBusy(false);\n      }\n    } else setOpen(false);\n  };\n\n  // Clicking outside an alert dialog must not dismiss it: nudge it instead.\n  const nudge = () => {\n    cancelRef.current?.focus({ preventScroll: true });\n    if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) return;\n    ref.current?.animate([{ scale: 1 }, { scale: 1.03 }, { scale: 1 }], { duration: 220, easing: \"ease-out\" });\n  };\n\n  const onKey = (e: KeyboardEvent<HTMLDialogElement>) => {\n    if (modal) return;\n    // Non-modal (absolute) mode: emulate Escape and trap Tab between the two buttons.\n    if (e.key === \"Escape\") {\n      e.stopPropagation();\n      cancel();\n    } else if (e.key === \"Tab\") {\n      const items = [...e.currentTarget.querySelectorAll<HTMLElement>(\"button:not(:disabled)\")];\n      const edge = e.shiftKey ? items[0] : items[items.length - 1];\n      if (document.activeElement === edge) {\n        e.preventDefault();\n        (e.shiftKey ? items[items.length - 1] : items[0])?.focus();\n      }\n    }\n  };\n\n  const tone = destructive\n    ? \"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/60\"\n    : \"bg-primary text-primary-foreground hover:bg-primary/90 focus-visible:ring-ring/60\";\n\n  return (\n    <>\n      <style href=\"ui-alert-dialog\" precedence=\"default\">\n        {css}\n      </style>\n      {trigger !== undefined && (\n        <button\n          ref={triggerRef}\n          type=\"button\"\n          aria-haspopup=\"dialog\"\n          aria-expanded={open}\n          aria-controls={id}\n          onClick={() => setOpen(true)}\n          className={cn(\n            btn,\n            destructive\n              ? \"border border-destructive/40 bg-destructive/10 text-destructive hover:bg-destructive/15 focus-visible:ring-destructive/60\"\n              : \"border border-border bg-card text-foreground hover:bg-muted focus-visible:ring-ring/60\",\n          )}\n        >\n          {trigger}\n        </button>\n      )}\n      {!modal && (\n        <div\n          aria-hidden\n          onClick={nudge}\n          className={cn(\n            \"absolute inset-0 z-40 bg-black/55 backdrop-blur-[4px] transition-opacity duration-200 motion-reduce:transition-none\",\n            open ? \"opacity-100\" : \"pointer-events-none opacity-0\",\n          )}\n        />\n      )}\n      <dialog\n        ref={ref}\n        id={id}\n        role=\"alertdialog\"\n        aria-modal={modal ? undefined : true}\n        aria-labelledby={`${id}-t`}\n        aria-describedby={description ? `${id}-d` : undefined}\n        onCancel={(e) => {\n          e.preventDefault(); // state drives the close so the exit animation runs\n          cancel();\n        }}\n        onClick={(e) => {\n          if (e.target === e.currentTarget) {\n            const r = e.currentTarget.getBoundingClientRect();\n            if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) nudge();\n          }\n        }}\n        onKeyDown={onKey}\n        className={cn(\n          \"ui-alert z-50 m-auto h-fit w-[calc(100%-2rem)] max-w-md rounded-2xl border border-border bg-card p-6 text-card-foreground shadow-2xl outline-none\",\n          modal ? \"fixed inset-0\" : \"absolute inset-0\",\n          className,\n        )}\n      >\n        <div className=\"flex gap-4\">\n          {destructive && (\n            <span aria-hidden className=\"grid size-10 shrink-0 place-items-center rounded-full bg-destructive/15 text-destructive\">\n              <TriangleAlert className=\"size-5\" />\n            </span>\n          )}\n          <div className=\"grid gap-1.5\">\n            <h2 id={`${id}-t`} className=\"text-lg font-semibold leading-tight tracking-tight\">\n              {title}\n            </h2>\n            {description && (\n              <p id={`${id}-d`} className=\"text-sm leading-relaxed text-muted-foreground\">\n                {description}\n              </p>\n            )}\n          </div>\n        </div>\n        <div className=\"mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end\">\n          <button\n            ref={cancelRef}\n            type=\"button\"\n            onClick={cancel}\n            disabled={busy}\n            className={cn(btn, \"border border-border bg-transparent text-foreground hover:bg-muted focus-visible:ring-ring/60\")}\n          >\n            {cancelLabel}\n          </button>\n          <button type=\"button\" onClick={confirm} disabled={busy} aria-busy={busy} className={cn(btn, tone)}>\n            {busy && <Loader2 aria-hidden className=\"size-4 animate-spin\" />}\n            {confirmLabel}\n          </button>\n        </div>\n      </dialog>\n    </>\n  );\n}\n"}]}