{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "alert-dialog",
  "type": "registry:component",
  "title": "Alert Dialog",
  "description": "A question that must be answered before the page can be used again, with the answers side by side under it.",
  "dependencies": [
    "@base-ui/react",
    "tailwind-variants"
  ],
  "registryDependencies": [
    "https://panelui.dev/r/web/button.json"
  ],
  "cssVars": {
    "light": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    },
    "dark": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    }
  },
  "files": [
    {
      "path": "components/panelui/alert-dialog.tsx",
      "type": "registry:component",
      "target": "@components/panelui/alert-dialog.tsx",
      "content": "'use client';\n\n/**\n * AlertDialog — a question that has to be answered before anything else on\n * the page can be done: delete this, discard that, sign out everywhere.\n *\n * ```tsx\n * <AlertDialog>\n *   <AlertDialog.Trigger render={<Button variant=\"destructive\" />}>Delete project</AlertDialog.Trigger>\n *   <AlertDialog.Content tone=\"destructive\">\n *     <AlertDialog.Title>Delete Orchard?</AlertDialog.Title>\n *     <AlertDialog.Description>Its 14 boards and their history go with it.</AlertDialog.Description>\n *     <AlertDialog.Footer>\n *       <AlertDialog.Cancel />\n *       <AlertDialog.Action onClick={remove}>Delete project</AlertDialog.Action>\n *     </AlertDialog.Footer>\n *   </AlertDialog.Content>\n * </AlertDialog>\n * ```\n *\n * ## A press outside is Cancel\n *\n * A press anywhere outside the dialog, Escape and `AlertDialog.Cancel` all\n * close it without doing anything; an action closes it once it has done its\n * work. `dismissible={false}` takes the outside press away, for a question\n * that should not be waved off by a stray click. While an action is running,\n * nothing closes it.\n *\n * ## The question, then the answers\n *\n * It is drawn as a panel in a darker band, the way Feedback is: the panel\n * holds the question, and `AlertDialog.Footer` moves out of it into the band\n * underneath, where the answers sit side by side at equal widths. Neither\n * answer is made to look like the default by being bigger.\n *\n * ## Actions that take time, or nerve\n *\n * An action whose `onClick` returns a promise shows a spinner and keeps the\n * dialog open, and unclosable, until the promise settles: closed if it\n * resolved, still open if it failed, so the failure can be shown in it.\n * `hold` makes an action one that must be pressed and held while a fill\n * runs across it, for a step that cannot be undone.\n */\n// The dialog primitive rather than the alert-dialog one, which refuses every\n// press outside; the role is still `alertdialog`, set on the popup.\nimport { Dialog as Primitive } from '@base-ui/react/dialog';\nimport {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type KeyboardEvent,\n  type MouseEvent,\n  type PointerEvent,\n  type ReactElement,\n  type ReactNode,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { tv } from 'tailwind-variants';\nimport { Button, type ButtonProps } from '@/components/panelui/button';\nimport { mergeProps } from '@base-ui/react/merge-props';\nimport { useRender } from '@base-ui/react/use-render';\nimport type { ElementType as RenderElementType } from 'react';\n\n/** Draws a part as another element, or composes it with a component: `render={<a href=\"/\" />}`. */\ntype RenderProp<Tag extends RenderElementType> = { render?: useRender.ComponentProps<Tag>['render'] };\n\n/** The theme role the dialog's media is drawn in, which also sets its action's default colour. */\nexport type AlertDialogTone = 'neutral' | 'info' | 'success' | 'warning' | 'destructive';\n\nconst alertDialogVariants = tv({\n  slots: {\n    backdrop:\n      'fixed inset-0 z-50 bg-black/40 transition-opacity duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0 motion-reduce:transition-none',\n    viewport: 'fixed inset-0 z-50 grid place-items-center overflow-y-auto p-4',\n    /*\n     * The band is the popover surface with black mixed in, so it is the\n     * darker of the two in a light theme and a dark one alike. 38 and 30 are\n     * one corner: the panel's radius is the band's less the 8px between them.\n     */\n    shell:\n      'relative flex w-full flex-col rounded-[38px] bg-[color-mix(in_oklab,var(--popover),black_5%)] p-2 text-popover-foreground shadow-xl outline-none ring-1 ring-foreground/[0.06] dark:bg-[color-mix(in_oklab,var(--popover),black_14%)]',\n    popup:\n      'transition-[opacity,scale,translate] duration-200 ease-[cubic-bezier(0.2,0,0,1)] data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:translate-y-2 data-starting-style:scale-95 data-starting-style:opacity-0 motion-reduce:transition-none',\n    panel: 'flex flex-col gap-2 rounded-[30px] bg-popover p-5 shadow-xs',\n    media: [\n      'mb-2 flex size-12 shrink-0 items-center justify-center rounded-full',\n      'bg-[color-mix(in_oklab,var(--pu-tone)_14%,transparent)] text-[var(--pu-tone)] [&_svg:not([class*=size-])]:size-6',\n    ],\n    title: 'text-[19px] font-semibold leading-6 tracking-[-0.01em]',\n    description: 'text-[15px] leading-[22px] text-muted-foreground',\n    // Held in from the band's edge further than the panel is, so the row of\n    // answers does not read as a third edge of the dialog.\n    footer: 'flex items-center gap-3 px-[18px] pb-2.5 pt-4',\n    action: 'relative isolate h-11 min-w-0 flex-1 overflow-hidden rounded-full px-4 text-[15px]',\n    // Drawn under the label and over the button's own fill, from the start edge.\n    fill: 'pointer-events-none absolute inset-0 -z-10 origin-left scale-x-0 bg-[color-mix(in_oklab,currentColor_24%,transparent)] rtl:origin-right',\n  },\n  variants: {\n    palette: {\n      neutral: { shell: '[--pu-tone:var(--muted-foreground)]' },\n      info: { shell: '[--pu-tone:var(--info)]' },\n      success: { shell: '[--pu-tone:var(--success)]' },\n      warning: { shell: '[--pu-tone:var(--warning)]' },\n      destructive: { shell: '[--pu-tone:var(--destructive)]' },\n    },\n    size: {\n      default: { shell: 'max-w-md' },\n      // Narrow, so the question is centred over the two answers.\n      sm: { shell: 'max-w-xs', panel: 'items-center text-center' },\n    },\n    blur: {\n      true: { backdrop: 'bg-black/20 backdrop-blur-md' },\n    },\n    /** How much an answer asks to be pressed: filled, or a tint of its colour. */\n    weight: {\n      solid: {},\n      soft: {},\n    },\n    actionTone: {\n      primary: {},\n      destructive: {},\n      neutral: {},\n    },\n  },\n  compoundVariants: [\n    {\n      weight: 'soft',\n      actionTone: 'primary',\n      className: {\n        action:\n          'bg-foreground/10 text-foreground hover:not-disabled:bg-foreground/15 hover:not-disabled:text-foreground',\n      },\n    },\n    {\n      weight: 'soft',\n      actionTone: 'neutral',\n      className: {\n        action:\n          'bg-foreground/10 text-muted-foreground hover:not-disabled:bg-foreground/15 hover:not-disabled:text-foreground',\n      },\n    },\n    {\n      weight: 'soft',\n      actionTone: 'destructive',\n      className: {\n        action:\n          'bg-[color-mix(in_oklab,var(--destructive)_12%,transparent)] text-destructive hover:not-disabled:bg-[color-mix(in_oklab,var(--destructive)_18%,transparent)] hover:not-disabled:text-destructive',\n      },\n    },\n  ],\n  defaultVariants: { palette: 'neutral', size: 'default' },\n});\n\ninterface AlertDialogContextValue {\n  open: boolean;\n  setOpen(open: boolean): void;\n  /** An action is running; nothing may close the dialog until it settles. */\n  busy: boolean;\n  setBusy(busy: boolean): void;\n  tone: AlertDialogTone;\n  /** Set by `AlertDialog.Content`. */\n  inline: boolean;\n  /** Where the footer portals to. `undefined` outside `AlertDialog.Content`. */\n  band?: HTMLElement | null;\n}\n\nconst AlertDialogContext = createContext<AlertDialogContextValue | null>(null);\n\nfunction useAlertDialog(part: string): AlertDialogContextValue {\n  const context = useContext(AlertDialogContext);\n  if (!context) throw new Error(`${part} must be used inside an <AlertDialog>.`);\n  return context;\n}\n\nexport interface AlertDialogProps {\n  children?: ReactNode;\n  /** Whether it is open, when the caller holds that. */\n  open?: boolean;\n  /** Whether it starts open, when the caller does not hold it. */\n  defaultOpen?: boolean;\n  /** Called when it opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /**\n   * Called once it has finished opening or closing, after its transition has\n   * ended. `false` means the exit is over, so a dialog mounted from state can\n   * be unmounted.\n   */\n  onOpenChangeComplete?: (open: boolean) => void;\n  /** Whether a press outside it closes it, as Cancel would. Escape always does. Default `true`. */\n  dismissible?: boolean;\n}\n\nfunction AlertDialogRoot({\n  children,\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  onOpenChangeComplete,\n  dismissible = true,\n}: AlertDialogProps) {\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const resolvedOpen = open ?? internalOpen;\n  const [busy, setBusy] = useState(false);\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (open === undefined) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [open, onOpenChange]\n  );\n  const context = useMemo<AlertDialogContextValue>(\n    () => ({ open: resolvedOpen, setOpen, busy, setBusy, tone: 'neutral', inline: false }),\n    [resolvedOpen, setOpen, busy]\n  );\n\n  return (\n    <AlertDialogContext.Provider value={context}>\n      <Primitive.Root\n        open={resolvedOpen}\n        disablePointerDismissal={!dismissible}\n        onOpenChangeComplete={onOpenChangeComplete}\n        onOpenChange={(next) => {\n          // While an action runs, the answer is already being acted on.\n          if (!next && busy) return;\n          setOpen(next);\n        }}\n      >\n        {children}\n      </Primitive.Root>\n    </AlertDialogContext.Provider>\n  );\n}\nAlertDialogRoot.displayName = 'AlertDialog';\n\nexport interface AlertDialogTriggerProps extends Omit<ComponentProps<'button'>, 'children'> {\n  children?: ReactNode;\n  /**\n   * Your own element to be the trigger, such as a styled button. It is given\n   * the click handler and the attributes that tie it to the dialog.\n   */\n  render?: ReactElement;\n}\n\n/** What opens the dialog. A plain button unless `render` supplies one. */\nfunction AlertDialogTrigger({ render, children, ...props }: AlertDialogTriggerProps) {\n  return (\n    <Primitive.Trigger render={render} {...props}>\n      {children}\n    </Primitive.Trigger>\n  );\n}\nAlertDialogTrigger.displayName = 'AlertDialog.Trigger';\n\nexport interface AlertDialogContentProps extends Omit<ComponentProps<'div'>, 'children'> {\n  children?: ReactNode;\n  /**\n   * The theme role it is drawn in: the colour of `AlertDialog.Media`, and of\n   * an action that is not given its own. `destructive` makes the action red.\n   * Default `neutral`.\n   */\n  tone?: AlertDialogTone;\n  /** `sm` is narrower, with the question centred over the answers. Default `default`. */\n  size?: 'default' | 'sm';\n  /** Frost the page behind the dialog instead of only dimming it. */\n  blur?: boolean;\n  /**\n   * Draw it in the page instead of over it: no backdrop, no trigger, always\n   * there. For previews; `open` is ignored.\n   */\n  inline?: boolean;\n}\n\n/** The dialog: the panel with the question, in a band that holds the answers. */\nfunction AlertDialogContent({\n  tone = 'neutral',\n  size = 'default',\n  blur = false,\n  inline = false,\n  className,\n  children,\n  ...props\n}: AlertDialogContentProps) {\n  const dialog = useAlertDialog('AlertDialog.Content');\n  const slots = alertDialogVariants({ palette: tone, size, blur });\n  const [band, setBand] = useState<HTMLElement | null>(null);\n  const context = useMemo(() => ({ ...dialog, tone, inline, band }), [dialog, tone, inline, band]);\n\n  // The footer leaves the panel for the band under it, from any depth.\n  const inside = (\n    <AlertDialogContext.Provider value={context}>\n      <div data-slot=\"alert-dialog-panel\" className={slots.panel()}>\n        {children}\n      </div>\n      <div data-slot=\"alert-dialog-band\" className=\"contents\" ref={setBand} />\n    </AlertDialogContext.Provider>\n  );\n\n  if (inline) {\n    return (\n      <div data-slot=\"alert-dialog-content\" data-tone={tone} className={slots.shell({ className })} {...props}>\n        {inside}\n      </div>\n    );\n  }\n\n  return (\n    <Primitive.Portal>\n      <Primitive.Backdrop className={slots.backdrop()} />\n      <Primitive.Viewport className={slots.viewport()}>\n        <Primitive.Popup\n          role=\"alertdialog\"\n          data-slot=\"alert-dialog-content\"\n          data-tone={tone}\n          className={slots.shell({ className: [slots.popup(), className] })}\n          {...props}\n        >\n          {inside}\n        </Primitive.Popup>\n      </Primitive.Viewport>\n    </Primitive.Portal>\n  );\n}\nAlertDialogContent.displayName = 'AlertDialog.Content';\n\nexport interface AlertDialogMediaProps extends ComponentProps<'div'> {}\n\n/** A glyph in a disc of the dialog's tone, above the title. */\nfunction AlertDialogMedia({ className, render, ...props }: AlertDialogMediaProps & RenderProp<'div'>) {\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'data-slot': 'alert-dialog-media',\n        'aria-hidden': 'true',\n        className: alertDialogVariants().media({ className }),\n      },\n      props\n    ),\n  });\n}\nAlertDialogMedia.displayName = 'AlertDialog.Media';\n\nexport interface AlertDialogTitleProps extends ComponentProps<'h2'> {}\n\n/** The question. It is what the dialog is announced as. */\nfunction AlertDialogTitle({ className, ...props }: AlertDialogTitleProps) {\n  const { inline } = useAlertDialog('AlertDialog.Title');\n  const slots = alertDialogVariants();\n  if (inline) return <h2 data-slot=\"alert-dialog-title\" className={slots.title({ className })} {...props} />;\n  return <Primitive.Title data-slot=\"alert-dialog-title\" className={slots.title({ className })} {...props} />;\n}\nAlertDialogTitle.displayName = 'AlertDialog.Title';\n\nexport interface AlertDialogDescriptionProps extends ComponentProps<'p'> {}\n\n/** What follows from each answer, read out after the title. */\nfunction AlertDialogDescription({ className, ...props }: AlertDialogDescriptionProps) {\n  const { inline } = useAlertDialog('AlertDialog.Description');\n  const slots = alertDialogVariants();\n  if (inline) return <p data-slot=\"alert-dialog-description\" className={slots.description({ className })} {...props} />;\n  return (\n    <Primitive.Description\n      data-slot=\"alert-dialog-description\"\n      className={slots.description({ className })}\n      {...props}\n    />\n  );\n}\nAlertDialogDescription.displayName = 'AlertDialog.Description';\n\nexport interface AlertDialogFooterProps extends ComponentProps<'div'> {}\n\n/**\n * The answers, side by side at equal widths in the band under the panel,\n * wherever they are written inside `AlertDialog.Content`.\n */\nfunction AlertDialogFooter({ className, render, ...props }: AlertDialogFooterProps & RenderProp<'div'>) {\n  const band = useContext(AlertDialogContext)?.band;\n  const footer = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      { 'data-slot': 'alert-dialog-footer', className: alertDialogVariants().footer({ className }) },\n      props\n    ),\n  });\n  if (band === undefined) return footer;\n  return band ? createPortal(footer, band) : null;\n}\nAlertDialogFooter.displayName = 'AlertDialog.Footer';\n\nexport interface AlertDialogCancelProps extends Omit<ButtonProps, 'variant' | 'size'> {}\n\n/** Closes the dialog without doing anything. It reads \"Cancel\" unless given children. */\nfunction AlertDialogCancel({ className, children = 'Cancel', disabled, ...props }: AlertDialogCancelProps) {\n  const dialog = useAlertDialog('AlertDialog.Cancel');\n  const slots = alertDialogVariants({ weight: 'soft', actionTone: 'neutral' });\n  const button = (\n    <Button\n      variant=\"ghost\"\n      data-slot=\"alert-dialog-cancel\"\n      disabled={disabled || dialog.busy}\n      className={slots.action({ className })}\n      {...props}\n    />\n  );\n  if (dialog.inline) return <Button {...button.props}>{children}</Button>;\n  return <Primitive.Close render={button}>{children}</Primitive.Close>;\n}\nAlertDialogCancel.displayName = 'AlertDialog.Cancel';\n\nexport interface AlertDialogActionProps extends Omit<ButtonProps, 'variant' | 'size' | 'onClick'> {\n  /**\n   * What it does. When it returns a promise, the button shows a spinner and\n   * the dialog stays open, and cannot be closed, until it settles: it closes\n   * when the promise resolves and stays open when it rejects. Call\n   * `event.preventDefault()` to keep the dialog open after a plain handler.\n   */\n  onClick?: (event: MouseEvent<HTMLButtonElement>) => void | Promise<unknown>;\n  /** Its colour. Default: `destructive` in a destructive dialog, `primary` otherwise. */\n  tone?: 'primary' | 'destructive';\n  /** `solid` is filled; `soft` is a tint of its colour, for an answer that is not the main one. Default `solid`. */\n  variant?: 'solid' | 'soft';\n  /**\n   * Makes it an action that must be pressed and held, for this many\n   * milliseconds, while a fill runs across it. Letting go early drains the\n   * fill. Space and Enter can be held the same way.\n   */\n  hold?: number;\n}\n\n/** Holding starts on a press and ends on a release; a click on its own does nothing. */\nfunction useHold(duration: number | undefined, onDone: () => void) {\n  const [holding, setHolding] = useState(false);\n  const timer = useRef<number | undefined>(undefined);\n  // When the last press or key went down, so a click that no press preceded,\n  // as a screen reader sends, can be told apart.\n  const pressedAt = useRef(0);\n  const done = useRef(onDone);\n  done.current = onDone;\n\n  const stop = useCallback(() => {\n    window.clearTimeout(timer.current);\n    setHolding(false);\n  }, []);\n  const start = useCallback(() => {\n    if (duration === undefined) return;\n    pressedAt.current = Date.now();\n    window.clearTimeout(timer.current);\n    setHolding(true);\n    timer.current = window.setTimeout(() => {\n      setHolding(false);\n      done.current();\n    }, duration);\n  }, [duration]);\n  useEffect(() => () => window.clearTimeout(timer.current), []);\n\n  return {\n    holding,\n    pressed: () => Date.now() - pressedAt.current < (duration ?? 0) + 1000,\n    handlers:\n      duration === undefined\n        ? {}\n        : {\n            onPointerDown: (event: PointerEvent<HTMLButtonElement>) => {\n              if (event.button === 0) start();\n            },\n            onPointerUp: stop,\n            onPointerLeave: stop,\n            onPointerCancel: stop,\n            onKeyDown: (event: KeyboardEvent<HTMLButtonElement>) => {\n              if ((event.key === ' ' || event.key === 'Enter') && !event.repeat) {\n                // Enter would click at once; the hold decides instead.\n                event.preventDefault();\n                start();\n              }\n            },\n            onKeyUp: (event: KeyboardEvent<HTMLButtonElement>) => {\n              if (event.key === ' ' || event.key === 'Enter') {\n                event.preventDefault();\n                stop();\n              }\n            },\n            onContextMenu: (event: MouseEvent<HTMLButtonElement>) => event.preventDefault(),\n          },\n  };\n}\n\n/** Does what the dialog asks about, then closes it. */\nfunction AlertDialogAction({\n  onClick,\n  tone,\n  variant = 'solid',\n  hold,\n  loading,\n  disabled,\n  className,\n  children,\n  ...props\n}: AlertDialogActionProps) {\n  const dialog = useAlertDialog('AlertDialog.Action');\n  const resolvedTone = tone ?? (dialog.tone === 'destructive' ? 'destructive' : 'primary');\n  const slots = alertDialogVariants({ weight: variant, actionTone: resolvedTone });\n  const [pending, setPending] = useState(false);\n  const hintId = useId();\n\n  const run = (event: MouseEvent<HTMLButtonElement>) => {\n    const result = onClick?.(event);\n    if (event.defaultPrevented) return;\n    if (result && typeof (result as Promise<unknown>).then === 'function') {\n      setPending(true);\n      dialog.setBusy(true);\n      (result as Promise<unknown>).then(\n        () => {\n          setPending(false);\n          dialog.setBusy(false);\n          dialog.setOpen(false);\n        },\n        () => {\n          setPending(false);\n          dialog.setBusy(false);\n        }\n      );\n      return;\n    }\n    dialog.setOpen(false);\n  };\n\n  // A hold that completes acts as a click on the button would.\n  const button = useRef<HTMLButtonElement>(null);\n  const confirmed = useRef(false);\n  const { holding, pressed, handlers } = useHold(hold, () => {\n    confirmed.current = true;\n    button.current?.click();\n  });\n\n  return (\n    <Button\n      ref={button}\n      data-slot=\"alert-dialog-action\"\n      data-holding={holding ? '' : undefined}\n      variant={variant === 'solid' ? (resolvedTone === 'destructive' ? 'destructive' : 'default') : 'ghost'}\n      loading={loading || pending}\n      disabled={disabled || (dialog.busy && !pending)}\n      aria-describedby={hold !== undefined ? hintId : undefined}\n      className={slots.action({ className })}\n      {...handlers}\n      onClick={(event) => {\n        if (hold !== undefined) {\n          const wasHeld = confirmed.current;\n          confirmed.current = false;\n          // A click no press or key preceded comes from assistive technology,\n          // which cannot hold; it confirms. Any other click must be a hold.\n          if (!wasHeld && pressed()) return;\n        }\n        run(event);\n      }}\n      {...props}\n    >\n      {hold !== undefined ? (\n        <>\n          <span\n            aria-hidden=\"true\"\n            data-slot=\"alert-dialog-action-fill\"\n            className={slots.fill({ className: holding ? 'scale-x-100' : undefined })}\n            style={{\n              transitionProperty: 'scale, transform',\n              transitionDuration: holding ? `${hold}ms` : '250ms',\n              transitionTimingFunction: holding ? 'linear' : 'cubic-bezier(0.2,0,0,1)',\n            }}\n          />\n          <span id={hintId} className=\"sr-only\">\n            Press and hold to confirm\n          </span>\n        </>\n      ) : null}\n      {children}\n    </Button>\n  );\n}\nAlertDialogAction.displayName = 'AlertDialog.Action';\n\nexport const AlertDialog = Object.assign(AlertDialogRoot, {\n  Trigger: AlertDialogTrigger,\n  Content: AlertDialogContent,\n  Media: AlertDialogMedia,\n  Title: AlertDialogTitle,\n  Description: AlertDialogDescription,\n  Footer: AlertDialogFooter,\n  Cancel: AlertDialogCancel,\n  Action: AlertDialogAction,\n});\n\nexport {\n  AlertDialogTrigger,\n  AlertDialogContent,\n  AlertDialogMedia,\n  AlertDialogTitle,\n  AlertDialogDescription,\n  AlertDialogFooter,\n  AlertDialogCancel,\n  AlertDialogAction,\n};\n"
    }
  ]
}
