{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dialog",
  "title": "Dialog & Sheet",
  "description": "Modal dialog, alert dialog and sheet in one: default, soft, glass and neo surfaces in six tones; center, top, start/end/left/right and draggable bottom sheets, fullscreen, and a phone override to fullscreen or sheet; scale, slide, blur, fade or morph-from-trigger entrances; async confirm with spinner and inline error, type-to-confirm, nested dialogs that step back, focus trap and restore, and scroll lock without layout shift.",
  "dependencies": [],
  "registryDependencies": [
    "https://goodui.dev/r/button.json",
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json",
    "https://goodui.dev/r/sounds.json"
  ],
  "files": [
    {
      "path": "registry/components/core/dialog.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { createPortal } from \"react-dom\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport type { SoundName } from \"@/lib/goodui-sounds\"\nimport { Button, type ButtonTone } from \"@/components/goodui/button\"\nimport { GooduiTokens, ease } from \"@/lib/goodui-motion\"\n\n/*\n * Modal dialog, alert dialog and sheet in one component, independent layers: every axis combines with every other.\n *   variant    default, soft, glass, neo                       tone       icon tile, confirm button, focus ring, soft tint\n *   placement  center, top, start, end, left, right, bottom, fullscreen      mobile     same, fullscreen or bottom sheet under 640px\n *   size       sm → xl, full                                    radius     none → xl (sheets round only their inner edge)\n *   shadow     none → xl                                        overlay    dim, blur, none\n *   animation  none, fade, scale, slide, morph (grows out of the trigger), blur\n *   role       dialog or alertdialog (no outside-click close, focus starts on Cancel)\n *   confirm    onConfirm may return a promise: the button spins, the dialog stays until it resolves and shows the error if it throws\n * Focus is trapped (Tab cycles) and returns to the trigger; the page scroll is locked without the layout jumping;\n * nested dialogs stack, and the one behind steps back. Esc and outside click are configurable.\n */\n\nexport type DialogVariant = \"default\" | \"soft\" | \"glass\" | \"neo\"\nexport type DialogTone = \"primary\" | \"neutral\" | \"success\" | \"warning\" | \"danger\" | \"info\"\n/** center and top are dialogs; start/end/left/right/bottom are sheets; start and end follow the reading direction. */\nexport type DialogPlacement = \"center\" | \"top\" | \"start\" | \"end\" | \"left\" | \"right\" | \"bottom\" | \"fullscreen\"\nexport type DialogMobile = \"same\" | \"fullscreen\" | \"sheet\"\nexport type DialogSize = \"sm\" | \"md\" | \"lg\" | \"xl\" | \"full\"\nexport type DialogRadius = \"none\" | \"sm\" | \"md\" | \"lg\" | \"xl\"\nexport type DialogShadow = \"none\" | \"sm\" | \"md\" | \"lg\" | \"xl\"\nexport type DialogAnimation = \"none\" | \"fade\" | \"scale\" | \"slide\" | \"morph\" | \"blur\"\nexport type DialogOverlay = \"dim\" | \"blur\" | \"none\"\nexport type DialogApi = { close: () => void }\n\nexport type DialogLabels = {\n  close: string\n  cancel: string\n  confirm: string\n  /** Label of the type-to-confirm field. */\n  typeToConfirm: (phrase: string) => string\n  /** Shown when onConfirm throws something that is not an Error with a message. */\n  error: string\n}\nconst DEFAULT_LABELS: DialogLabels = {\n  close: \"Close\",\n  cancel: \"Cancel\",\n  confirm: \"Confirm\",\n  typeToConfirm: (phrase) => `Type \"${phrase}\" to confirm`,\n  error: \"Something went wrong. Please try again.\",\n}\n\ntype TriggerProps = React.HTMLAttributes<HTMLElement> & { ref?: React.Ref<HTMLElement> }\n\nexport type DialogProps = Omit<React.ComponentProps<\"div\">, \"title\" | \"children\" | \"role\"> & {\n  /** Element that opens the dialog (a button). It gets aria-haspopup, aria-expanded and aria-controls, and morph grows out of it. */\n  trigger?: React.ReactElement<TriggerProps>\n  /** Open state (controlled). */\n  open?: boolean\n  /** Initial open state when uncontrolled. */\n  defaultOpen?: boolean\n  onOpenChange?: (open: boolean) => void\n  /** alertdialog: for confirmations that interrupt. Outside click does not close it, there is no × by default, and focus starts on Cancel. */\n  role?: \"dialog\" | \"alertdialog\"\n  /** Heading; names the dialog for screen readers. Without it, pass aria-label. */\n  title?: React.ReactNode\n  /** Muted text under the title; describes the dialog for screen readers. */\n  description?: React.ReactNode\n  /** Icon in a tone-tinted tile above or beside the title. */\n  icon?: React.ReactNode\n  /** Body. A function receives { close }. */\n  children?: React.ReactNode | ((api: DialogApi) => React.ReactNode)\n  /** Custom footer; replaces the built-in Cancel / Confirm buttons. A function receives { close }. */\n  footer?: React.ReactNode | ((api: DialogApi) => React.ReactNode)\n  /** Surface: default, soft (tone tint), glass (frosted) or neo (thick border, hard shadow). */\n  variant?: DialogVariant\n  /** Accent for the icon tile, confirm button, soft tint and focus ring. */\n  tone?: DialogTone\n  /** Where it appears. Sheets slide from their edge with any animation except fade, blur and none. */\n  placement?: DialogPlacement\n  /** Below 640px, a center or top dialog can become fullscreen or a bottom sheet. */\n  mobile?: DialogMobile\n  /** Width for dialogs and side sheets, max width for the bottom sheet. full fills the screen. */\n  size?: DialogSize\n  radius?: DialogRadius\n  /** Drop shadow. Ignored by neo, which has its own offset shadow. */\n  shadow?: DialogShadow\n  /** How it enters and leaves. morph grows out of the trigger (falls back to scale without one). Reduced motion uses a short fade. */\n  animation?: DialogAnimation\n  /** Backdrop: dim (default), blur (frosted page) or none (transparent, still blocks the page). */\n  overlay?: DialogOverlay\n  /** × button in the corner. Default: true for dialog, false for alertdialog. */\n  showClose?: boolean\n  /** Esc closes. When false (or while confirming), Esc gives a small bump instead. */\n  closeOnEsc?: boolean\n  /** Click on the backdrop closes. Default: true for dialog, false for alertdialog. */\n  closeOnOutsideClick?: boolean\n  /** Bottom sheet: drag the handle down to close. */\n  dragToClose?: boolean\n  /** While open, the page behind steps back: it scales to .98 and rounds its corners. Skipped for nested dialogs and reduced motion. */\n  scaleBackground?: boolean\n  /** Shows Cancel and Confirm. May return a promise: the button shows a spinner and the dialog waits; a throw keeps it open and shows the error. */\n  onConfirm?: () => unknown\n  /** Confirm button text (default labels.confirm). */\n  confirmText?: React.ReactNode\n  /** Cancel button text (default labels.cancel). */\n  cancelText?: React.ReactNode\n  /** Confirm button tone; defaults to tone. */\n  confirmTone?: DialogTone\n  /** Close after onConfirm succeeds. */\n  closeOnConfirm?: boolean\n  /** The user must type this exact text before Confirm is enabled (deleting a workspace). */\n  confirmPhrase?: string\n  /** Element to focus on open. Default: an autoFocus element, Cancel for alertdialog, the first field or button, else the panel. */\n  initialFocus?: React.RefObject<HTMLElement | null>\n  /** Return focus to the element that had it before opening. */\n  returnFocus?: boolean\n  /** Plays \"open\" and \"close\" when the visitor has sounds on (lib/goodui-sounds); a sound name replaces the open sound. Off by default. */\n  sound?: boolean | SoundName\n  /** Text for built-in controls; pass translations here. */\n  labels?: Partial<DialogLabels>\n}\n\n/* ---------- shared across every open dialog ---------- */\n\nlet locks = 0\nlet unlock: (() => void) | null = null\n/** Locks page scroll. A stable scrollbar gutter (or padding where unsupported) keeps the layout from shifting. */\nfunction lockScroll() {\n  if (locks++ > 0) return\n  const html = document.documentElement\n  const body = document.body\n  const bar = window.innerWidth - html.clientWidth\n  const prev = { overflow: html.style.overflow, gutter: html.style.scrollbarGutter, pad: body.style.paddingInlineEnd }\n  html.style.setProperty(\"--pc-scrollbar\", `${bar}px`)\n  if (bar > 0) {\n    if (window.CSS?.supports(\"scrollbar-gutter\", \"stable\")) html.style.scrollbarGutter = \"stable\"\n    else body.style.paddingInlineEnd = `calc(${getComputedStyle(body).paddingInlineEnd} + ${bar}px)`\n  }\n  html.style.overflow = \"hidden\"\n  unlock = () => {\n    html.style.overflow = prev.overflow\n    html.style.scrollbarGutter = prev.gutter\n    body.style.paddingInlineEnd = prev.pad\n    html.style.removeProperty(\"--pc-scrollbar\")\n  }\n}\nfunction unlockScroll() {\n  if (--locks > 0) return\n  locks = 0\n  unlock?.()\n  unlock = null\n}\n/** Open dialogs, top last; only the top one reacts to Esc when focus is outside every dialog. */\nconst stack: symbol[] = []\n\ntype Nest = { depth: number; setChildOpen: (open: boolean) => void }\nconst NestContext = React.createContext<Nest | null>(null)\n\nconst TABBABLE =\n  'a[href],button:not([disabled]),input:not([disabled]):not([type=\"hidden\"]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex=\"-1\"]),[contenteditable=\"true\"],summary,audio[controls],video[controls]'\nfunction tabbables(root: ParentNode) {\n  return Array.from(root.querySelectorAll<HTMLElement>(TABBABLE)).filter((el) => el.tabIndex >= 0 && !el.closest(\"[inert]\") && el.getClientRects().length > 0)\n}\n\nfunction mergeRefs<T>(...refs: (React.Ref<T> | undefined)[]) {\n  return (el: T | null) => {\n    for (const r of refs) {\n      if (typeof r === \"function\") r(el)\n      else if (r) (r as React.RefObject<T | null>).current = el\n    }\n  }\n}\n\nconst isThenable = (v: unknown): v is PromiseLike<unknown> => !!v && typeof (v as { then?: unknown }).then === \"function\"\n\n/* ---------- motion: Web Animations, so morph can measure the real panel before the first frame ---------- */\n\ntype Phys = \"center\" | \"top\" | \"fullscreen\" | \"left\" | \"right\" | \"bottom\"\nconst SHEETS: Phys[] = [\"left\", \"right\", \"bottom\"]\n// Web Animations cannot read CSS variables, so the curves are spelled out from the shared tokens.\nconst css = (c: readonly number[]) => `cubic-bezier(${c.join(\",\")})`\nconst EASE = css(ease.out)\nconst EASE_SHEET = css(ease.drawer)\n\nfunction frames(kind: DialogAnimation, place: Phys, morph: string | null): { k: Keyframe[]; ms: number } {\n  const sheet = SHEETS.includes(place)\n  if (kind === \"fade\") return { k: [{ opacity: 0 }, { opacity: 1 }], ms: 180 }\n  if (kind === \"blur\") {\n    const shift = place === \"left\" ? \"translateX(-6%)\" : place === \"right\" ? \"translateX(6%)\" : place === \"bottom\" ? \"translateY(6%)\" : \"scale(1.04)\"\n    return { k: [{ opacity: 0, filter: \"blur(14px)\", transform: shift }, { opacity: 1, filter: \"blur(0)\", transform: \"none\" }], ms: 320 }\n  }\n  if (sheet) {\n    const off = place === \"left\" ? \"translateX(-100%)\" : place === \"right\" ? \"translateX(100%)\" : \"translateY(100%)\"\n    return { k: [{ transform: off }, { transform: \"none\" }], ms: 420 }\n  }\n  if (kind === \"morph\" && morph)\n    return {\n      k: [\n        { transform: morph, opacity: 0 },\n        { opacity: 1, offset: 0.35 },\n        { transform: \"none\", opacity: 1 },\n      ],\n      ms: 420,\n    }\n  if (kind === \"slide\" || place === \"fullscreen\") return { k: [{ opacity: 0, transform: \"translateY(24px)\" }, { opacity: 1, transform: \"none\" }], ms: 300 }\n  return { k: [{ opacity: 0, transform: \"scale(.96)\" }, { opacity: 1, transform: \"none\" }], ms: 240 }\n}\n\n/* ---------- look ---------- */\n\nconst CSS = `\n.pc-dialog{--pc-c:var(--primary);--pc-fg:var(--primary-foreground)}\n.pc-dialog[data-tone=neutral]{--pc-c:var(--foreground);--pc-fg:var(--background)}\n.pc-dialog[data-tone=success]{--pc-c:oklch(0.53 0.13 155);--pc-fg:#fff}\n.pc-dialog[data-tone=warning]{--pc-c:oklch(0.75 0.16 70);--pc-fg:oklch(0.25 0.05 70)}\n.pc-dialog[data-tone=danger]{--pc-c:oklch(0.56 0.21 27);--pc-fg:#fff}\n.pc-dialog[data-tone=info]{--pc-c:oklch(0.55 0.17 250);--pc-fg:#fff}\n.dark .pc-dialog[data-tone=success]{--pc-c:oklch(0.7 0.16 155);--pc-fg:oklch(0.2 0.05 155)}\n.dark .pc-dialog[data-tone=danger]{--pc-c:oklch(0.68 0.2 25);--pc-fg:oklch(0.2 0.05 25)}\n.dark .pc-dialog[data-tone=info]{--pc-c:oklch(0.7 0.15 245);--pc-fg:oklch(0.2 0.05 245)}\n.pc-dialog{--pc-tint:color-mix(in oklab,var(--pc-c) 14%,transparent);--pc-ink:color-mix(in oklab,var(--pc-c) 82%,var(--foreground))}\n.pc-dialog[data-tone=warning]{--pc-ink:color-mix(in oklab,var(--pc-c) 62%,var(--foreground))}\n\n.pc-dialog-overlay{background:radial-gradient(120% 120% at 50% 42%,hsl(var(--pc-sh)/.36),hsl(var(--pc-sh)/.58))}\n.dark .pc-dialog-overlay{background:radial-gradient(120% 120% at 50% 42%,rgb(0 0 0/.52),rgb(0 0 0/.74))}\n.pc-dialog[data-overlay=blur] .pc-dialog-overlay{background:rgb(9 9 11/.28);-webkit-backdrop-filter:blur(6px) saturate(1.2);backdrop-filter:blur(6px) saturate(1.2)}\n.dark .pc-dialog[data-overlay=blur] .pc-dialog-overlay{background:rgb(0 0 0/.42)}\n.pc-dialog[data-overlay=none] .pc-dialog-overlay{background:transparent}\n.pc-dialog[data-nested] .pc-dialog-overlay{background:rgb(9 9 11/.2);-webkit-backdrop-filter:none;backdrop-filter:none}\n\n.pc-dialog-panel{--pc-r:14px;--pc-bd:color-mix(in oklab,var(--foreground) 9%,transparent);position:relative;background:var(--background);color:var(--foreground);border:1px solid var(--pc-bd);border-radius:var(--pc-r);outline:none;transition:transform .32s var(--pc-ease-out),opacity .32s}\n.dark .pc-dialog-panel{--pc-bd:color-mix(in oklab,var(--foreground) 13%,transparent)}\n.pc-dialog[data-radius=none] .pc-dialog-panel{--pc-r:0px}\n.pc-dialog[data-radius=sm] .pc-dialog-panel{--pc-r:6px}\n.pc-dialog[data-radius=md] .pc-dialog-panel{--pc-r:10px}\n.pc-dialog[data-radius=xl] .pc-dialog-panel{--pc-r:22px}\n.pc-dialog[data-place=left] .pc-dialog-panel{border-radius:0 var(--pc-r) var(--pc-r) 0;border-block-width:0;border-left-width:0}\n.pc-dialog[data-place=right] .pc-dialog-panel{border-radius:var(--pc-r) 0 0 var(--pc-r);border-block-width:0;border-right-width:0}\n.pc-dialog[data-place=bottom] .pc-dialog-panel{border-radius:var(--pc-r) var(--pc-r) 0 0;border-bottom-width:0}\n.pc-dialog[data-place=fullscreen] .pc-dialog-panel{border-radius:0;border-width:0}\n.pc-dialog[data-variant=soft] .pc-dialog-panel{background:color-mix(in oklab,var(--pc-c) 5%,var(--background));--pc-bd:color-mix(in oklab,var(--pc-c) 22%,transparent)}\n.pc-dialog[data-variant=glass] .pc-dialog-panel{background:color-mix(in oklab,var(--background) 62%,transparent);--pc-bd:color-mix(in oklab,var(--foreground) 15%,transparent);-webkit-backdrop-filter:blur(24px) saturate(1.7);backdrop-filter:blur(24px) saturate(1.7)}\n.pc-dialog[data-variant=neo] .pc-dialog-panel{--pc-bd:var(--foreground);border-width:2px;box-shadow:7px 7px 0 var(--foreground)}\n.pc-dialog[data-variant=neo][data-place=left] .pc-dialog-panel{border-width:0 2px 0 0;box-shadow:6px 0 0 var(--foreground)}\n.pc-dialog[data-variant=neo][data-place=right] .pc-dialog-panel{border-width:0 0 0 2px;box-shadow:-6px 0 0 var(--foreground)}\n.pc-dialog[data-variant=neo][data-place=bottom] .pc-dialog-panel{border-width:2px 0 0;box-shadow:0 -6px 0 var(--foreground)}\n.pc-dialog[data-variant=neo][data-place=fullscreen] .pc-dialog-panel{box-shadow:none}\n/* The elevation token already draws the hairline, so the border steps aside and keeps its width (no layout shift). */\n.pc-dialog:is([data-variant=default],[data-variant=soft]):not([data-shadow=none]) .pc-dialog-panel{border-color:transparent}\n.pc-dialog:not([data-variant=neo])[data-shadow=sm] .pc-dialog-panel{box-shadow:var(--pc-e1)}\n.pc-dialog:not([data-variant=neo])[data-shadow=md] .pc-dialog-panel{box-shadow:var(--pc-e2)}\n.pc-dialog:not([data-variant=neo])[data-shadow=lg] .pc-dialog-panel{box-shadow:var(--pc-e3)}\n.pc-dialog:not([data-variant=neo])[data-shadow=xl] .pc-dialog-panel{box-shadow:var(--pc-e3),0 48px 80px -24px hsl(var(--pc-sh)/.3)}\n.pc-dialog[data-variant=glass] .pc-dialog-panel{box-shadow:inset 0 1px 0 color-mix(in oklab,white 40%,transparent),0 24px 60px -16px rgb(0 0 0/.36)}\n.pc-dialog-panel[data-behind]{transform:translateY(-14px) scale(.94);opacity:.92}\n.pc-dialog:is([data-place=left],[data-place=right],[data-place=bottom]) .pc-dialog-panel[data-behind]{transform:scale(.97);opacity:.9}\n.pc-dialog-icon{background:var(--pc-tint);color:var(--pc-ink)}\n.pc-dialog[data-variant=neo] .pc-dialog-icon{background:color-mix(in oklab,var(--pc-c) 20%,var(--background));color:var(--foreground);border:2px solid var(--foreground)}\n.pc-dialog-muted{color:var(--muted-foreground)}\n.pc-dialog-x{color:var(--muted-foreground)}\n.pc-dialog-x:hover{background:color-mix(in oklab,var(--foreground) 8%,transparent);color:var(--foreground)}\n.pc-dialog-x:focus-visible,.pc-dialog-field:focus-visible{box-shadow:0 0 0 3px color-mix(in oklab,var(--pc-c) 40%,transparent)}\n.pc-dialog-field{background:var(--background);border:1px solid var(--input)}\n.pc-dialog-field:focus-visible{border-color:color-mix(in oklab,var(--pc-c) 55%,var(--border))}\n.pc-dialog-foot{border-top:1px solid color-mix(in oklab,var(--pc-bd) 80%,transparent)}\n.pc-dialog[data-variant=neo] .pc-dialog-foot{border-top:2px solid var(--foreground)}\n.pc-dialog-handle{background:color-mix(in oklab,var(--foreground) 18%,transparent)}\n.pc-dialog-error{color:oklch(0.56 0.21 27);background:color-mix(in oklab,oklch(0.56 0.21 27) 9%,transparent)}\n.dark .pc-dialog-error{color:oklch(0.72 0.17 25)}\n@media (prefers-reduced-motion:reduce){.pc-dialog-panel{transition:none!important}}\n`\n\nconst WIDTH: Record<DialogSize, { dialog: string; side: string; bottom: string }> = {\n  sm: { dialog: \"24rem\", side: \"20rem\", bottom: \"32rem\" },\n  md: { dialog: \"32rem\", side: \"24rem\", bottom: \"42rem\" },\n  lg: { dialog: \"42rem\", side: \"30rem\", bottom: \"56rem\" },\n  xl: { dialog: \"56rem\", side: \"40rem\", bottom: \"72rem\" },\n  full: { dialog: \"100%\", side: \"100vw\", bottom: \"100%\" },\n}\n\n// Optional UI sound: the sound module is loaded only when `sound` is on, so silent apps pay nothing.\nfunction useCue(sound: boolean | SoundName | undefined) {\n  React.useEffect(() => {\n    if (sound) void import(\"@/lib/goodui-sounds\")\n  }, [sound])\n  return React.useCallback(\n    (fallback: SoundName, o?: { rate?: number; exact?: boolean }) => {\n      if (!sound) return\n      void import(\"@/lib/goodui-sounds\").then((m) => m.play(sound === true || o?.exact ? fallback : sound, { rate: o?.rate }))\n    },\n    [sound],\n  )\n}\n\nexport function Dialog({\n  trigger: triggerNode,\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  role = \"dialog\",\n  title,\n  description,\n  icon,\n  children,\n  footer,\n  variant = \"default\",\n  tone = \"primary\",\n  placement = \"center\",\n  mobile = \"same\",\n  size = \"md\",\n  radius = \"lg\",\n  shadow = \"lg\",\n  animation = \"scale\",\n  overlay = \"dim\",\n  showClose,\n  closeOnEsc = true,\n  closeOnOutsideClick,\n  dragToClose = true,\n  scaleBackground = false,\n  onConfirm,\n  confirmText,\n  cancelText,\n  confirmTone,\n  closeOnConfirm = true,\n  confirmPhrase,\n  initialFocus,\n  returnFocus = true,\n  sound,\n  labels,\n  className,\n  style,\n  ...props\n}: DialogProps) {\n  const l = useLabels(\"dialog\", DEFAULT_LABELS, labels)\n  const alert = role === \"alertdialog\"\n  const outsideCloses = closeOnOutsideClick ?? !alert\n  const withClose = showClose ?? !alert\n\n  const [mounted, setMounted] = React.useState(false)\n  const [mobileView, setMobileView] = React.useState(false)\n  const [rtl, setRtl] = React.useState(false)\n  React.useEffect(() => {\n    setMounted(true)\n    const mq = window.matchMedia(\"(max-width: 639px)\")\n    const on = () => setMobileView(mq.matches)\n    on()\n    mq.addEventListener(\"change\", on)\n    return () => mq.removeEventListener(\"change\", on)\n  }, [])\n\n  const id = React.useId()\n  const panelId = id + \"-dialog\"\n  const titleId = id + \"-title\"\n  const descId = id + \"-desc\"\n\n  const [inner, setInner] = React.useState(defaultOpen)\n  const open = openProp ?? inner\n  const [present, setPresent] = React.useState(open)\n  if (open && !present) setPresent(true)\n\n  const cue = useCue(sound)\n  const prevOpen = React.useRef(open)\n  React.useEffect(() => {\n    if (prevOpen.current === open) return\n    prevOpen.current = open\n    cue(open ? \"open\" : \"close\", { exact: !open })\n  }, [open, cue])\n\n  const [pending, setPending] = React.useState(false)\n  const [error, setError] = React.useState<string | null>(null)\n  const [typed, setTyped] = React.useState(\"\")\n  const [childOpen, setChildOpen] = React.useState(false)\n\n  const parent = React.useContext(NestContext)\n  const nest = React.useMemo<Nest>(() => ({ depth: (parent?.depth ?? 0) + 1, setChildOpen }), [parent])\n\n  const trigger = React.useRef<HTMLElement | null>(null)\n  const prevFocus = React.useRef<HTMLElement | null>(null)\n  const panel = React.useRef<HTMLDivElement>(null)\n  const overlayEl = React.useRef<HTMLDivElement>(null)\n  const cancelBtn = React.useRef<HTMLButtonElement>(null)\n  const me = React.useRef(Symbol(\"dialog\"))\n  const dragOut = React.useRef<Animation | null>(null)\n  const live = React.useRef({ open, openProp, onOpenChange, pending })\n  React.useLayoutEffect(() => {\n    live.current = { open, openProp, onOpenChange, pending }\n  })\n\n  const setOpen = React.useCallback((o: boolean) => {\n    const c = live.current\n    if (c.open === o) return\n    if (c.openProp === undefined) setInner(o)\n    c.onOpenChange?.(o)\n  }, [])\n  const close = React.useCallback(() => setOpen(false), [setOpen])\n  const api = React.useMemo<DialogApi>(() => ({ close }), [close])\n\n  // Effective placement: mobile override, then logical sides resolved to physical ones.\n  const centered = placement === \"center\" || placement === \"top\"\n  const eff: DialogPlacement = mobileView && centered && mobile !== \"same\" ? (mobile === \"fullscreen\" ? \"fullscreen\" : \"bottom\") : placement\n  const phys: Phys = eff === \"start\" ? (rtl ? \"right\" : \"left\") : eff === \"end\" ? (rtl ? \"left\" : \"right\") : eff\n  const sheet = SHEETS.includes(phys)\n\n  const reduced = () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n  const originEl = () => trigger.current ?? prevFocus.current\n  const morphFrom = (el: HTMLElement) => {\n    const o = originEl()\n    if (!o || !o.isConnected) return null\n    const a = o.getBoundingClientRect()\n    const b = el.getBoundingClientRect()\n    if (!a.width || !b.width) return null\n    const dx = a.left + a.width / 2 - (b.left + b.width / 2)\n    const dy = a.top + a.height / 2 - (b.top + b.height / 2)\n    return `translate(${dx}px,${dy}px) scale(${a.width / b.width},${a.height / b.height})`\n  }\n  const bump = () => {\n    const el = panel.current\n    if (!el || animation === \"none\" || reduced() || typeof el.animate !== \"function\") return\n    el.animate([{ transform: \"scale(1)\" }, { transform: sheet ? \"scale(1.01)\" : \"scale(1.025)\" }, { transform: \"scale(1)\" }], { duration: 240, easing: EASE })\n  }\n\n  // Remember what had focus (and its direction) before the dialog takes it.\n  React.useLayoutEffect(() => {\n    if (!open) return\n    const a = document.activeElement\n    prevFocus.current = a instanceof HTMLElement && a !== document.body ? a : null\n    const from = trigger.current ?? prevFocus.current ?? document.documentElement\n    setRtl(getComputedStyle(from).direction === \"rtl\")\n    setError(null)\n    setTyped(\"\")\n  }, [open])\n\n  // Enter and exit animations.\n  React.useLayoutEffect(() => {\n    if (!mounted || !present) return\n    const el = panel.current\n    const ov = overlayEl.current\n    if (!el) return\n    const can = typeof el.animate === \"function\"\n    const dragged = !open ? dragOut.current : null\n    dragOut.current = null\n    for (const a of can ? el.getAnimations() : []) if (a !== dragged) a.cancel()\n    for (const a of ov && can ? ov.getAnimations() : []) a.cancel()\n    const still = animation === \"none\" || !can\n    const calm = reduced()\n    if (open) {\n      if (still) return\n      if (calm) {\n        el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 140 })\n        ov?.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 140 })\n        return\n      }\n      const f = frames(animation, phys, animation === \"morph\" ? morphFrom(el) : null)\n      el.animate(f.k, { duration: f.ms, easing: sheet ? EASE_SHEET : EASE })\n      ov?.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 220, easing: EASE })\n      return\n    }\n    if (still) {\n      setPresent(false)\n      return\n    }\n    const f = calm ? { k: [{ opacity: 0 }, { opacity: 1 }], ms: 100 } : frames(animation, phys, animation === \"morph\" ? morphFrom(el) : null)\n    const out = { duration: calm ? 100 : Math.round(f.ms * 0.7), easing: sheet ? EASE_SHEET : EASE, fill: \"forwards\" as const }\n    // After a drag-to-close the panel is already sliding out from under the finger; keep that animation.\n    const runs = [dragged ?? el.animate([...f.k].reverse().map((k) => (typeof k.offset === \"number\" ? { ...k, offset: 1 - k.offset } : k)), out)]\n    if (ov) runs.push(ov.animate([{ opacity: 1 }, { opacity: 0 }], { ...out, easing: \"ease\" }))\n    let done = false\n    Promise.all(runs.map((r) => r.finished))\n      .then(() => {\n        if (!done) setPresent(false)\n      })\n      .catch(() => {})\n    return () => {\n      done = true\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [open, present, mounted])\n\n  // Height morph: when the content changes size (next step, an error appears), the panel eases from the old height.\n  React.useLayoutEffect(() => {\n    const el = panel.current\n    if (!mounted || !present || !el || animation === \"none\" || typeof ResizeObserver === \"undefined\" || typeof el.animate !== \"function\") return\n    let h = el.offsetHeight\n    let w = el.offsetWidth\n    let run: Animation | null = null\n    const ro = new ResizeObserver(() => {\n      const from = run?.playState === \"running\" ? parseFloat(getComputedStyle(el).height) : h\n      run?.cancel()\n      run = null\n      const to = el.offsetHeight\n      const width = el.offsetWidth\n      const same = width === w\n      h = to\n      w = width\n      if (!same || Math.abs(to - from) < 2 || reduced() || !live.current.open) return\n      run = el.animate([{ height: `${from}px` }, { height: `${to}px` }], { duration: 260, easing: EASE })\n    })\n    for (const n of el.querySelectorAll(\"[data-slot=dialog-measure],[data-slot=dialog-header],[data-slot=dialog-footer]\")) ro.observe(n)\n    return () => {\n      ro.disconnect()\n      run?.cancel()\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [mounted, present, animation])\n\n  // The page steps back behind the dialog. Every direct child of <body> moves, except the dialog layers themselves.\n  React.useEffect(() => {\n    if (!open || !mounted || !scaleBackground || parent || animation === \"none\" || reduced()) return\n    const els = Array.from(document.body.children).filter((n): n is HTMLElement => n instanceof HTMLElement && !n.matches(\"script,style,link,[data-slot=dialog-root]\"))\n    const prior = els.map((n) => n.style.cssText)\n    const y = window.scrollY + window.innerHeight / 2\n    const motion = `transform ${240}ms ${EASE},border-radius ${240}ms ${EASE}`\n    for (const n of els) {\n      n.style.transition = motion\n      n.style.transformOrigin = `50% ${y}px`\n      n.style.transform = \"scale(.98)\"\n      n.style.borderRadius = \"14px\"\n      n.style.overflow = \"clip\"\n    }\n    return () => {\n      for (const n of els) {\n        n.style.transform = \"\"\n        n.style.borderRadius = \"\"\n      }\n      window.setTimeout(() => els.forEach((n, i) => (n.style.cssText = prior[i] ?? \"\")), 260)\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [open, mounted, scaleBackground])\n\n  // Scroll lock for as long as the dialog is on screen (including its exit).\n  React.useEffect(() => {\n    if (!mounted || !present) return\n    lockScroll()\n    return unlockScroll\n  }, [mounted, present])\n\n  // Tell the parent dialog to step back while this one is open.\n  React.useEffect(() => {\n    if (!parent || !open) return\n    parent.setChildOpen(true)\n    return () => parent.setChildOpen(false)\n  }, [parent, open])\n\n  // Focus in on open; focus back on close. Esc fallback when focus is outside every dialog.\n  React.useEffect(() => {\n    if (!open || !mounted) return\n    const p = panel.current\n    if (!p) return\n    const self = me.current\n    stack.push(self)\n    if (!p.contains(document.activeElement) || document.activeElement === p) {\n      const body = p.querySelector<HTMLElement>(\"[data-slot=dialog-body]\")\n      const target =\n        initialFocus?.current ??\n        p.querySelector<HTMLElement>(\"[data-autofocus]\") ??\n        (confirmPhrase ? p.querySelector<HTMLElement>(\"[data-slot=dialog-phrase]\") : null) ??\n        (alert ? cancelBtn.current : null) ??\n        (body ? tabbables(body)[0] : undefined) ??\n        tabbables(p).find((el) => !el.hasAttribute(\"data-close\")) ??\n        p\n      target.focus({ preventScroll: true })\n    }\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key !== \"Escape\" || stack[stack.length - 1] !== self || p.closest(\"[data-slot=dialog-root]\")?.contains(document.activeElement)) return\n      if (closeOnEsc && !live.current.pending) close()\n      else bump()\n    }\n    document.addEventListener(\"keydown\", onKey)\n    const back = prevFocus.current\n    return () => {\n      document.removeEventListener(\"keydown\", onKey)\n      const i = stack.lastIndexOf(self)\n      if (i >= 0) stack.splice(i, 1)\n      if (returnFocus && back?.isConnected) back.focus({ preventScroll: true })\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [open, mounted])\n\n  const confirm = async () => {\n    setError(null)\n    try {\n      const r = onConfirm?.()\n      if (isThenable(r)) {\n        setPending(true)\n        await r\n      }\n      if (closeOnConfirm) close()\n    } catch (err) {\n      setError(err instanceof Error && err.message ? err.message : l.error)\n    } finally {\n      setPending(false)\n    }\n  }\n\n  const onRootKey = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    if (e.key === \"Escape\") {\n      e.stopPropagation()\n      if (closeOnEsc && !pending) close()\n      else bump()\n      return\n    }\n    const p = panel.current\n    if (e.key !== \"Tab\" || !p || !p.contains(e.target as Node)) return\n    const items = tabbables(p)\n    const first = items[0]\n    const last = items[items.length - 1]\n    const active = document.activeElement\n    if (!first || !last) {\n      e.preventDefault()\n      p.focus()\n    } else if (e.shiftKey && (active === first || active === p)) {\n      e.preventDefault()\n      last.focus()\n    } else if (!e.shiftKey && active === last) {\n      e.preventDefault()\n      first.focus()\n    }\n  }\n\n  // Bottom sheet: drag the handle down to close.\n  const drag = React.useRef<{ y: number; t: number; dy: number } | null>(null)\n  const canDrag = phys === \"bottom\" && dragToClose && !pending\n  const onDragStart = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (!canDrag) return\n    e.currentTarget.setPointerCapture(e.pointerId)\n    drag.current = { y: e.clientY, t: e.timeStamp, dy: 0 }\n    if (panel.current) panel.current.style.transition = \"none\"\n  }\n  const onDragMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current\n    if (!d || !panel.current) return\n    d.dy = Math.max(0, e.clientY - d.y)\n    panel.current.style.transform = d.dy ? `translateY(${d.dy}px)` : \"\"\n  }\n  const onDragEnd = (e: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current\n    const el = panel.current\n    drag.current = null\n    if (!d || !el) return\n    const fast = d.dy / Math.max(1, e.timeStamp - d.t) > 0.6\n    el.style.transition = \"\"\n    if (d.dy > Math.min(140, el.offsetHeight * 0.35) || (fast && d.dy > 30)) {\n      el.style.transform = \"\"\n      if (typeof el.animate === \"function\" && animation !== \"none\" && !reduced()) {\n        // Finish the slide from where the finger let go; the exit effect reuses this animation.\n        dragOut.current = el.animate([{ transform: `translateY(${d.dy}px)` }, { transform: \"translateY(100%)\" }], { duration: 200, easing: \"ease\", fill: \"forwards\" })\n      }\n      close()\n    } else el.style.transform = \"\"\n  }\n\n  /* trigger wiring */\n  const triggerEl = triggerNode\n    ? React.cloneElement(triggerNode, {\n        ref: mergeRefs(triggerNode.props.ref, (el: HTMLElement | null) => {\n          trigger.current = el\n        }),\n        \"aria-haspopup\": \"dialog\",\n        \"aria-expanded\": open,\n        \"aria-controls\": open ? panelId : undefined,\n        \"data-state\": open ? \"open\" : \"closed\",\n        onClick: (e: React.MouseEvent<HTMLElement>) => {\n          triggerNode.props.onClick?.(e)\n          if (!e.defaultPrevented) setOpen(true)\n        },\n      } as Partial<TriggerProps>)\n    : null\n\n  const hasTitle = title !== undefined && title !== null\n  const hasDesc = description !== undefined && description !== null\n  const body = typeof children === \"function\" ? children(api) : children\n  const foot = typeof footer === \"function\" ? footer(api) : footer\n  const buttons = onConfirm !== undefined && foot === undefined\n  const phraseOk = !confirmPhrase || typed.trim() === confirmPhrase\n  const btnVariant = variant === \"neo\" ? \"neo\" : \"solid\"\n  const w = WIDTH[size]\n\n  const panelStyle: React.CSSProperties =\n    phys === \"left\" || phys === \"right\"\n      ? { width: size === \"full\" ? \"100vw\" : `min(${w.side}, calc(100vw - 2.5rem))` }\n      : phys === \"bottom\"\n        ? { width: \"100%\", maxWidth: w.bottom, maxHeight: size === \"full\" ? \"100dvh\" : \"min(88dvh, 100dvh - 2rem)\" }\n        : phys === \"fullscreen\"\n          ? { width: \"100%\", height: \"100%\" }\n          : size === \"full\"\n            ? { width: \"100%\", height: \"100%\" }\n            : { width: `min(${w.dialog}, 100%)`, maxHeight: phys === \"top\" ? \"calc(100dvh - 12vh - 1rem)\" : \"calc(100dvh - 2rem)\" }\n\n  const layer = (\n    <NestContext.Provider value={nest}>\n      <div\n        data-slot=\"dialog-root\"\n        className=\"pc-dialog fixed inset-0 z-50\"\n        data-variant={variant}\n        data-tone={tone}\n        data-place={phys}\n        data-radius={radius}\n        data-shadow={shadow}\n        data-overlay={overlay}\n        data-nested={parent ? \"\" : undefined}\n        data-state={open ? \"open\" : \"closed\"}\n        dir={rtl ? \"rtl\" : \"ltr\"}\n        onKeyDown={onRootKey}\n        style={{ pointerEvents: open ? undefined : \"none\" }}\n      >\n        <div ref={overlayEl} aria-hidden=\"true\" data-slot=\"dialog-overlay\" className=\"pc-dialog-overlay absolute inset-0\" />\n        <div\n          data-slot=\"dialog-viewport\"\n          className={cn(\n            \"absolute inset-0 flex\",\n            phys === \"center\" && \"items-center justify-center p-4\",\n            phys === \"top\" && \"items-start justify-center px-4 pt-[12vh] pb-4\",\n            phys === \"fullscreen\" && \"items-stretch justify-stretch\",\n            phys === \"left\" && \"items-stretch justify-start\",\n            phys === \"right\" && \"items-stretch justify-end\",\n            phys === \"bottom\" && \"items-end justify-center\",\n            size === \"full\" && centered && phys !== \"fullscreen\" && \"items-stretch\",\n          )}\n          // The viewport is laid out left to right so left and right sheets are physical; the panel restores the direction.\n          dir=\"ltr\"\n          onMouseDown={(e) => {\n            if (e.target === e.currentTarget) e.preventDefault()\n          }}\n          onPointerDown={(e) => {\n            if (e.target !== e.currentTarget) return\n            if (outsideCloses && !pending) close()\n            else bump()\n          }}\n        >\n          <div\n            {...props}\n            ref={panel}\n            id={panelId}\n            role={role}\n            aria-modal=\"true\"\n            aria-labelledby={hasTitle ? titleId : props[\"aria-labelledby\"]}\n            aria-describedby={hasDesc ? descId : props[\"aria-describedby\"]}\n            aria-busy={pending || undefined}\n            tabIndex={-1}\n            dir={rtl ? \"rtl\" : \"ltr\"}\n            data-slot=\"dialog\"\n            data-behind={childOpen ? \"\" : undefined}\n            style={{ ...panelStyle, ...style }}\n            className={cn(\"pc-dialog-panel flex min-h-0 flex-col overflow-hidden\", className)}\n          >\n            {phys === \"bottom\" && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"dialog-handle\"\n                className={cn(\"flex shrink-0 justify-center pt-2.5 pb-1\", canDrag && \"cursor-grab touch-none active:cursor-grabbing\")}\n                onPointerDown={onDragStart}\n                onPointerMove={onDragMove}\n                onPointerUp={onDragEnd}\n                onPointerCancel={onDragEnd}\n              >\n                <span className=\"pc-dialog-handle h-1.5 w-10 rounded-full\" />\n              </div>\n            )}\n            {(hasTitle || hasDesc || icon) && (\n              <div\n                data-slot=\"dialog-header\"\n                className={cn(\"flex shrink-0 gap-4 px-5 pt-5 sm:px-6 sm:pt-6\", phys === \"bottom\" && \"pt-2 sm:pt-3\", alert && icon ? \"flex-col items-start sm:flex-row\" : \"items-start\", withClose && \"pe-12 sm:pe-14\")}\n              >\n                {icon && <span className=\"pc-dialog-icon grid size-10 shrink-0 place-items-center rounded-full [&_svg]:size-5\">{icon}</span>}\n                <div className=\"flex min-w-0 flex-1 flex-col gap-1.5\">\n                  {hasTitle && (\n                    <h2 id={titleId} className=\"text-lg leading-tight font-semibold tracking-tight\">\n                      {title}\n                    </h2>\n                  )}\n                  {hasDesc && (\n                    <div id={descId} className=\"pc-dialog-muted text-sm leading-relaxed\">\n                      {description}\n                    </div>\n                  )}\n                </div>\n              </div>\n            )}\n            {withClose && (\n              <button\n                type=\"button\"\n                data-close=\"\"\n                aria-label={l.close}\n                onClick={close}\n                className={cn(\"pc-press pc-dialog-x absolute end-3 z-10 grid size-8 cursor-pointer place-items-center rounded-lg outline-none transition-colors\", phys === \"bottom\" ? \"top-4\" : \"top-3\")}\n              >\n                <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\" className=\"size-4\">\n                  <path d=\"M4.5 4.5 11.5 11.5M11.5 4.5 4.5 11.5\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" />\n                </svg>\n              </button>\n            )}\n            {(body !== undefined && body !== null && body !== false) || confirmPhrase || error ? (\n              <div data-slot=\"dialog-body\" className={cn(\"min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 py-4 text-sm sm:px-6\", !(hasTitle || hasDesc || icon) && \"pt-5 sm:pt-6\")}>\n                <div data-slot=\"dialog-measure\">\n                {body}\n                {confirmPhrase && (\n                  <label className={cn(\"flex flex-col gap-1.5\", body !== undefined && body !== null && \"mt-4\")}>\n                    <span className=\"text-sm font-medium\">{l.typeToConfirm(confirmPhrase)}</span>\n                    <input\n                      data-slot=\"dialog-phrase\"\n                      value={typed}\n                      onChange={(e) => setTyped(e.target.value)}\n                      autoComplete=\"off\"\n                      spellCheck={false}\n                      disabled={pending}\n                      className=\"pc-dialog-field h-10 w-full rounded-lg px-3 text-sm outline-none\"\n                      onKeyDown={(e) => {\n                        if (e.key === \"Enter\" && phraseOk && !pending) {\n                          e.preventDefault()\n                          void confirm()\n                        }\n                      }}\n                    />\n                  </label>\n                )}\n                {error && (\n                  <p role=\"alert\" className=\"pc-dialog-error mt-3 rounded-lg px-3 py-2 text-sm\">\n                    {error}\n                  </p>\n                )}\n                </div>\n              </div>\n            ) : (\n              <div className=\"h-4 shrink-0\" />\n            )}\n            {(buttons || (foot !== undefined && foot !== null && foot !== false)) && (\n              <div\n                data-slot=\"dialog-footer\"\n                className={cn(\n                  \"flex shrink-0 flex-col-reverse gap-2 px-5 py-4 sm:flex-row sm:items-center sm:justify-end sm:px-6\",\n                  (sheet || phys === \"fullscreen\") && \"pc-dialog-foot\",\n                  phys === \"bottom\" && \"pb-[max(1rem,env(safe-area-inset-bottom))]\",\n                )}\n              >\n                {buttons ? (\n                  <>\n                    <Button ref={cancelBtn} type=\"button\" variant=\"outline\" tone=\"neutral\" disabled={pending} onClick={close} className=\"w-full sm:w-auto\">\n                      {cancelText ?? l.cancel}\n                    </Button>\n                    <Button\n                      type=\"button\"\n                      variant={btnVariant}\n                      tone={(confirmTone ?? tone) as ButtonTone}\n                      loading={pending}\n                      disabled={!phraseOk}\n                      animation={animation === \"none\" ? \"none\" : \"press\"}\n                      onClick={() => void confirm()}\n                      className=\"w-full sm:w-auto\"\n                    >\n                      {confirmText ?? l.confirm}\n                    </Button>\n                  </>\n                ) : (\n                  foot\n                )}\n              </div>\n            )}\n          </div>\n        </div>\n      </div>\n    </NestContext.Provider>\n  )\n\n  return (\n    <>\n      <GooduiTokens />\n      <style href=\"pc-dialog\" precedence=\"default\">\n        {CSS}\n      </style>\n      {triggerEl}\n      {mounted && present ? createPortal(layer, document.body) : null}\n    </>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/dialog.tsx"
    }
  ],
  "categories": [
    "components",
    "core"
  ],
  "type": "registry:component"
}
