{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "modals",
  "title": "Modals",
  "description": "Promise-based modal registry: await openModal(key, props) for a typed result, with lazy-loaded contents and stacking.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "button",
    "dialog"
  ],
  "files": [
    {
      "path": "components/dentil/modals/contents/confirm.tsx",
      "content": "'use client';\n\nimport { Loader2 } from 'lucide-react';\nimport { useState, type ReactNode } from 'react';\n\nimport { Button } from '@/components/ui/button';\nimport { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';\n\nimport type { ModalContentProps } from '../types';\n\ntype ConfirmModalProps = ModalContentProps<boolean> & {\n  title: string;\n  description?: ReactNode;\n  confirmLabel?: string;\n  cancelLabel?: string;\n  destructive?: boolean;\n  /** Runs before the modal closes with `true`. While pending the buttons are disabled; a thrown error is shown inline. */\n  onConfirm?: () => Promise<void> | void;\n};\n\nexport default function ConfirmModal({\n  close,\n  title,\n  description,\n  confirmLabel = 'Confirm',\n  cancelLabel = 'Cancel',\n  destructive = false,\n  onConfirm,\n}: ConfirmModalProps) {\n  const [pending, setPending] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n\n  const confirm = async () => {\n    setError(null);\n    setPending(true);\n    try {\n      await onConfirm?.();\n      close(true);\n    } catch (err) {\n      setError(err instanceof Error ? err.message : String(err));\n    } finally {\n      setPending(false);\n    }\n  };\n\n  return (\n    <>\n      <DialogHeader>\n        <DialogTitle>{title}</DialogTitle>\n        {description && <DialogDescription>{description}</DialogDescription>}\n      </DialogHeader>\n      {error && <p className=\"text-destructive text-sm\">{error}</p>}\n      <DialogFooter>\n        <Button variant=\"outline\" onClick={() => close(false)} disabled={pending}>\n          {cancelLabel}\n        </Button>\n        <Button variant={destructive ? 'destructive' : 'default'} onClick={confirm} disabled={pending}>\n          {pending && <Loader2 className=\"animate-spin\" />}\n          {confirmLabel}\n        </Button>\n      </DialogFooter>\n    </>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/modals/contents/confirm.tsx"
    },
    {
      "path": "components/dentil/modals/context.tsx",
      "content": "'use client';\n\nimport { createContext, use, useEffect, useMemo, useState, type ReactNode } from 'react';\n\nimport { ModalHost } from './host';\nimport type { ModalKey, ModalPropsMap, ModalReturnMap } from './registry';\nimport type { ModalOptions, ModalSize } from './types';\n\n/** Matches the dialog's exit animation, so closing modals animate out before they unmount. */\nconst EXIT_DURATION_MS = 200;\n\nexport interface ModalDescriptor {\n  id: string;\n  key: ModalKey;\n  props: object;\n  size: ModalSize;\n  /** False while the modal plays its exit animation. */\n  open: boolean;\n  close: (value?: unknown) => void;\n}\n\n/** Props are optional when the modal has no required props. */\ntype OpenModalArgs<K extends ModalKey> =\n  Partial<ModalPropsMap[K]> extends ModalPropsMap[K]\n    ? [props?: ModalPropsMap[K], options?: ModalOptions]\n    : [props: ModalPropsMap[K], options?: ModalOptions];\n\nexport interface ModalContextValue {\n  /** Open (and closing) modals, bottom to top. */\n  stack: ModalDescriptor[];\n  /** Opens a modal on top of the stack. Resolves with the value it closes with, or `undefined` if dismissed. */\n  openModal<K extends ModalKey>(key: K, ...args: OpenModalArgs<K>): Promise<ModalReturnMap[K] | undefined>;\n  closeModal(id: string, value?: unknown): void;\n}\n\nexport interface ModalCloseInfo {\n  /** `undefined` when the modal was dismissed (Esc, overlay, close button or `close()`). */\n  value: unknown;\n  durationMs: number;\n}\n\nconst ModalContext = createContext<ModalContextValue | null>(null);\n\nexport function useModal(): ModalContextValue {\n  const context = use(ModalContext);\n  if (!context) {\n    throw new Error('useModal must be used within a ModalProvider');\n  }\n  return context;\n}\n\ninterface ModalProviderProps {\n  children: ReactNode;\n  /** Called whenever a modal opens, e.g. for analytics. */\n  onOpen?: (key: ModalKey) => void;\n  /** Called whenever a modal closes, e.g. for analytics. */\n  onClose?: (key: ModalKey, info: ModalCloseInfo) => void;\n}\n\ninterface PendingModal {\n  key: ModalKey;\n  openedAt: number;\n  resolve: (value: unknown) => void;\n}\n\ntype SetStack = (update: (prev: ModalDescriptor[]) => ModalDescriptor[]) => void;\ntype Callbacks = Pick<ModalProviderProps, 'onOpen' | 'onClose'>;\n\n// Created once per provider, so openModal and closeModal keep a stable identity.\nfunction createModalActions(setStack: SetStack) {\n  let callbacks: Callbacks = {};\n  const pending = new Map<string, PendingModal>();\n\n  const closeModal = (id: string, value?: unknown) => {\n    const modal = pending.get(id);\n    // Already closed: a second close (e.g. a button and Esc in the same tick) is a no-op.\n    if (!modal) return;\n    pending.delete(id);\n\n    modal.resolve(value);\n    callbacks.onClose?.(modal.key, { value, durationMs: Date.now() - modal.openedAt });\n\n    setStack((prev) => prev.map((descriptor) => (descriptor.id === id ? { ...descriptor, open: false } : descriptor)));\n    setTimeout(() => {\n      setStack((prev) => prev.filter((descriptor) => descriptor.id !== id));\n    }, EXIT_DURATION_MS);\n  };\n\n  const openModal = <K extends ModalKey>(key: K, ...args: OpenModalArgs<K>) =>\n    new Promise<ModalReturnMap[K] | undefined>((resolve) => {\n      const [props, options] = args;\n      const id = crypto.randomUUID();\n      pending.set(id, { key, openedAt: Date.now(), resolve: resolve as (value: unknown) => void });\n      callbacks.onOpen?.(key);\n\n      const descriptor: ModalDescriptor = {\n        id,\n        key,\n        props: props ?? {},\n        size: options?.size ?? 'default',\n        open: true,\n        close: (value) => closeModal(id, value),\n      };\n      setStack((prev) => [...prev, descriptor]);\n    });\n\n  const setCallbacks = (next: Callbacks) => {\n    callbacks = next;\n  };\n\n  return { openModal, closeModal, setCallbacks };\n}\n\nexport function ModalProvider({ children, onOpen, onClose }: ModalProviderProps) {\n  const [stack, setStack] = useState<ModalDescriptor[]>([]);\n  const [{ openModal, closeModal, setCallbacks }] = useState(() => createModalActions(setStack));\n\n  useEffect(() => {\n    setCallbacks({ onOpen, onClose });\n  }, [setCallbacks, onOpen, onClose]);\n\n  const value = useMemo<ModalContextValue>(() => ({ stack, openModal, closeModal }), [stack, openModal, closeModal]);\n\n  return (\n    <ModalContext value={value}>\n      {children}\n      <ModalHost stack={stack} />\n    </ModalContext>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/modals/context.tsx"
    },
    {
      "path": "components/dentil/modals/host.tsx",
      "content": "'use client';\n\nimport { Suspense } from 'react';\n\nimport type { ModalDescriptor } from './context';\nimport { modalRegistry } from './registry';\nimport { ModalLoading, ModalShell } from './shell';\n\nexport function ModalHost({ stack }: { stack: ModalDescriptor[] }) {\n  // Closing modals still render (for the exit animation) but don't count towards depth.\n  const open = stack.filter((descriptor) => descriptor.open);\n\n  return stack.map((descriptor) => {\n    const Content = modalRegistry[descriptor.key];\n    const index = open.indexOf(descriptor);\n    const depth = index === -1 ? 0 : open.length - 1 - index;\n\n    return (\n      <ModalShell\n        key={descriptor.id}\n        open={descriptor.open}\n        depth={depth}\n        size={descriptor.size}\n        onClose={() => descriptor.close()}>\n        <Suspense fallback={<ModalLoading />}>\n          <Content {...descriptor.props} modalId={descriptor.id} close={descriptor.close} />\n        </Suspense>\n      </ModalShell>\n    );\n  });\n}\n",
      "type": "registry:component",
      "target": "components/dentil/modals/host.tsx"
    },
    {
      "path": "components/dentil/modals/index.ts",
      "content": "export { ModalProvider, useModal } from './context';\nexport type { ModalCloseInfo, ModalContextValue, ModalDescriptor } from './context';\nexport { modalRegistry } from './registry';\nexport type { ModalKey, ModalPropsMap, ModalReturnMap } from './registry';\nexport type { ModalContentProps, ModalOptions, ModalSize } from './types';\n",
      "type": "registry:lib",
      "target": "components/dentil/modals/index.ts"
    },
    {
      "path": "components/dentil/modals/registry.tsx",
      "content": "import { lazy, type ComponentProps, type ComponentType, type LazyExoticComponent } from 'react';\n\n// Add a modal: write a component typed with ModalContentProps<TReturn> in ./contents, then add a loader here.\n// Each entry is code-split, so the modal's module is only downloaded when it's first opened.\nconst modalLoaders = {\n  confirm: () => import('./contents/confirm'),\n} as const;\n\n// Everything below is inferred from the loaders.\n\nexport type ModalKey = keyof typeof modalLoaders;\n\ntype ModalComponent<K extends ModalKey> = Awaited<ReturnType<(typeof modalLoaders)[K]>>['default'];\n\n/** Props you pass to `openModal(key, props)`: the component's props minus the injected ones. */\nexport type ModalPropsMap = {\n  [K in ModalKey]: Omit<ComponentProps<ModalComponent<K>>, 'modalId' | 'close'>;\n};\n\n/** What `openModal(key)` resolves to when the modal closes with a value. */\nexport type ModalReturnMap = {\n  [K in ModalKey]: ComponentProps<ModalComponent<K>> extends { close: (value?: infer R) => void } ? R : never;\n};\n\nexport const modalRegistry = Object.fromEntries(\n  Object.entries(modalLoaders).map(([key, loader]) => [\n    key,\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    lazy(loader as () => Promise<{ default: ComponentType<any> }>),\n  ])\n) as {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  [K in ModalKey]: LazyExoticComponent<ComponentType<any>>;\n};\n",
      "type": "registry:component",
      "target": "components/dentil/modals/registry.tsx"
    },
    {
      "path": "components/dentil/modals/shell.tsx",
      "content": "'use client';\n\nimport { AlertTriangle, Loader2, RefreshCw } from 'lucide-react';\nimport * as React from 'react';\n\nimport { Button } from '@/components/ui/button';\nimport { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';\n\nimport type { ModalSize } from './types';\n\n// `default` keeps the stock dialog width (sm:max-w-lg).\nconst sizeClasses: Record<ModalSize, string> = {\n  default: '',\n  md: 'sm:max-w-xl',\n  lg: 'sm:max-w-2xl',\n  xl: 'sm:max-w-3xl',\n  full: 'sm:max-w-4xl',\n};\n\ninterface ModalShellProps {\n  open: boolean;\n  onClose: () => void;\n  /** 0 for the top modal, 1 for the one beneath it, and so on. */\n  depth: number;\n  size: ModalSize;\n  children: React.ReactNode;\n}\n\nexport function ModalShell({ open, onClose, depth, size, children }: ModalShellProps) {\n  const interactive = open && depth === 0;\n\n  return (\n    <Dialog open={open} onOpenChange={(next) => !next && interactive && onClose()}>\n      <DialogContent\n        showCloseButton={interactive}\n        className={sizeClasses[size]}\n        // Modals beneath the top one recede. The stock content centers itself with the `translate` property and\n        // animates with `transform`, so this uses the separate `scale` property and a margin instead.\n        style={{\n          scale: depth > 0 ? 1 - depth * 0.03 : undefined,\n          marginTop: depth > 0 ? depth * -12 : undefined,\n          transformOrigin: 'top center',\n          transition: 'scale 200ms ease-out, margin-top 200ms ease-out',\n        }}>\n        <ModalErrorBoundary onClose={onClose}>{children}</ModalErrorBoundary>\n      </DialogContent>\n    </Dialog>\n  );\n}\n\n/** Suspense fallback while a modal's code loads. Includes a hidden title and description for screen readers. */\nexport function ModalLoading() {\n  return (\n    <div className=\"flex h-40 items-center justify-center\">\n      <DialogTitle className=\"sr-only\">Loading</DialogTitle>\n      <DialogDescription className=\"sr-only\">Loading dialog</DialogDescription>\n      <Loader2 className=\"text-muted-foreground size-5 animate-spin\" />\n    </div>\n  );\n}\n\ninterface ModalErrorBoundaryProps {\n  children: React.ReactNode;\n  onClose: () => void;\n}\n\nclass ModalErrorBoundary extends React.Component<ModalErrorBoundaryProps, { error: Error | null }> {\n  state: { error: Error | null } = { error: null };\n\n  static getDerivedStateFromError(error: Error) {\n    return { error };\n  }\n\n  componentDidCatch(error: Error, info: React.ErrorInfo) {\n    console.error('[Modal]', error, info.componentStack);\n  }\n\n  render() {\n    const { error } = this.state;\n    if (!error) return this.props.children;\n\n    return (\n      <div role=\"alert\" className=\"flex min-h-40 flex-col items-center justify-center gap-3 text-center\">\n        <div className=\"bg-destructive/10 text-destructive flex size-9 items-center justify-center rounded-full\">\n          <AlertTriangle className=\"size-4\" />\n        </div>\n        <div className=\"flex flex-col gap-1\">\n          <DialogTitle className=\"text-sm font-medium\">This dialog failed to render</DialogTitle>\n          <DialogDescription className=\"max-w-md text-xs\">\n            {error.message || 'An unexpected error occurred.'}\n          </DialogDescription>\n        </div>\n        <div className=\"flex items-center gap-2\">\n          <Button size=\"sm\" variant=\"outline\" onClick={() => this.setState({ error: null })}>\n            <RefreshCw className=\"size-3.5\" />\n            Try again\n          </Button>\n          <Button size=\"sm\" variant=\"ghost\" onClick={this.props.onClose}>\n            Dismiss\n          </Button>\n        </div>\n      </div>\n    );\n  }\n}\n",
      "type": "registry:component",
      "target": "components/dentil/modals/shell.tsx"
    },
    {
      "path": "components/dentil/modals/types.ts",
      "content": "export type ModalSize = 'default' | 'md' | 'lg' | 'xl' | 'full';\n\nexport interface ModalOptions {\n  /** Max width from the sm breakpoint up. `default` keeps the stock dialog width. */\n  size?: ModalSize;\n}\n\n/**\n * Props every modal content receives. Intersect with your own props; `TReturn` is what `openModal` resolves to.\n *\n * ```tsx\n * type Props = ModalContentProps<boolean> & { title: string };\n * ```\n */\nexport interface ModalContentProps<TReturn = void> {\n  modalId: string;\n  /** Closes this modal and resolves its `openModal` promise. Call with no value to cancel. */\n  close: (value?: TReturn) => void;\n}\n",
      "type": "registry:lib",
      "target": "components/dentil/modals/types.ts"
    }
  ],
  "type": "registry:block"
}
