{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dialog",
  "type": "registry:ui",
  "title": "Dialog",
  "description": "Dialog is a modal overlay that interrupts workflow for focused attention, information, or a decision.",
  "author": "Skrewww",
  "dependencies": [
    "@phosphor-icons/react"
  ],
  "registryDependencies": [
    "@skrewww/foundation"
  ],
  "docs": "Host requirements (assumed already present, not installed by this command): react, react-dom.",
  "files": [
    {
      "path": "components/ui/Dialog.tsx",
      "content": "/** @skrewww-component dialog */\n\"use client\";\n\nimport {\n  createContext,\n  useContext,\n  useId,\n  useMemo,\n  useRef,\n  useCallback,\n  useState,\n  useEffect,\n  cloneElement,\n  isValidElement,\n  type ReactNode,\n  type RefObject,\n} from \"react\";\nimport { X } from \"@phosphor-icons/react\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable\";\nimport { Portal } from \"@/components/ui/internal/Portal\";\nimport { OverlayScopeProvider } from \"@/components/ui/internal/OverlayScopeContext\";\nimport { useBackgroundInert } from \"@/components/ui/internal/useBackgroundInert\";\nimport { useBodyScrollLock } from \"@/components/ui/internal/useBodyScrollLock\";\nimport { useOverlayEscape } from \"@/components/ui/internal/useOverlayEscape\";\nimport { useFocusTrap } from \"@/components/ui/internal/useFocusTrap\";\nimport { restoreFocusSafely } from \"@/components/ui/internal/focus-utils\";\nimport { mergeRefs } from \"@/components/ui/internal/assign-ref\";\nimport type { OverlayCloseReason } from \"@/components/ui/internal/overlay-types\";\nimport styles from \"@/components/ui/dialog.module.css\";\n\nexport type DialogCloseReason = OverlayCloseReason;\n\ntype DialogContextValue = {\n  open: boolean;\n  setOpen: (next: boolean) => void;\n  requestClose: (reason: DialogCloseReason) => void;\n  titleId: string;\n  hasAccessibleTitle: boolean;\n  registerAccessibleTitle: (present: boolean) => void;\n  descriptionId?: string;\n  setDescriptionId: (id: string | undefined) => void;\n  triggerRef: React.MutableRefObject<HTMLElement | null>;\n  closeOnOverlayClick: boolean;\n  overlayScopeId: string;\n  finalFocusRef: React.MutableRefObject<HTMLElement | null>;\n};\n\nconst DialogContext = createContext<DialogContextValue | null>(null);\n\nfunction useDialogContext(component: string): DialogContextValue {\n  const context = useContext(DialogContext);\n  if (!context) {\n    throw new Error(`${component} must be used within Dialog`);\n  }\n  return context;\n}\n\nexport type DialogProps = {\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean, reason?: DialogCloseReason) => void;\n  closeOnOverlayClick?: boolean;\n  children: ReactNode;\n};\n\nexport function Dialog({\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  closeOnOverlayClick = true,\n  children,\n}: DialogProps) {\n  const titleId = useId();\n  const overlayScopeId = useId();\n  const [descriptionId, setDescriptionId] = useState<string | undefined>();\n  const [accessibleTitleCount, setAccessibleTitleCount] = useState(0);\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const finalFocusRef = useRef<HTMLElement | null>(null);\n  const previousOpenRef = useRef(false);\n\n  const [isOpen, setIsOpen] = useControllableState({\n    value: open,\n    defaultValue: defaultOpen,\n  });\n\n  const registerAccessibleTitle = useCallback((present: boolean) => {\n    setAccessibleTitleCount((count) => Math.max(0, count + (present ? 1 : -1)));\n  }, []);\n\n  const requestClose = useCallback(\n    (reason: DialogCloseReason) => {\n      onOpenChange?.(false, reason);\n      setIsOpen(false);\n      restoreFocusSafely(finalFocusRef.current, triggerRef.current);\n    },\n    [onOpenChange, setIsOpen],\n  );\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (next) {\n        onOpenChange?.(true);\n        setIsOpen(true);\n        return;\n      }\n      requestClose(\"programmatic\");\n    },\n    [onOpenChange, requestClose, setIsOpen],\n  );\n\n  useEffect(() => {\n    const wasOpen = previousOpenRef.current;\n    previousOpenRef.current = Boolean(isOpen);\n    if (wasOpen && !isOpen) {\n      restoreFocusSafely(finalFocusRef.current, triggerRef.current);\n    }\n  }, [isOpen]);\n\n  const value = useMemo(\n    () => ({\n      open: Boolean(isOpen),\n      setOpen,\n      requestClose,\n      titleId,\n      hasAccessibleTitle: accessibleTitleCount > 0,\n      registerAccessibleTitle,\n      descriptionId,\n      setDescriptionId,\n      triggerRef,\n      closeOnOverlayClick,\n      overlayScopeId,\n      finalFocusRef,\n    }),\n    [\n      accessibleTitleCount,\n      closeOnOverlayClick,\n      descriptionId,\n      isOpen,\n      overlayScopeId,\n      registerAccessibleTitle,\n      requestClose,\n      setOpen,\n      titleId,\n    ],\n  );\n\n  return (\n    <OverlayScopeProvider scopeId={overlayScopeId}>\n      <DialogContext.Provider value={value}>{children}</DialogContext.Provider>\n    </OverlayScopeProvider>\n  );\n}\n\ntype DialogTriggerProps = {\n  children: React.ReactElement<{\n    onClick?: React.MouseEventHandler<HTMLElement>;\n    ref?: React.Ref<HTMLElement>;\n  }>;\n};\n\nexport function DialogTrigger({ children }: DialogTriggerProps) {\n  const { setOpen, triggerRef } = useDialogContext(\"DialogTrigger\");\n\n  if (!isValidElement(children)) return children;\n\n  const child = children as React.ReactElement<{\n    onClick?: React.MouseEventHandler<HTMLElement>;\n    ref?: React.Ref<HTMLElement>;\n  }>;\n\n  return cloneElement(child, {\n    ref: mergeRefs(triggerRef, child.props.ref),\n    onClick: (event: React.MouseEvent<HTMLElement>) => {\n      child.props.onClick?.(event);\n      if (event.defaultPrevented) return;\n      setOpen(true);\n    },\n  });\n}\n\nexport type DialogContentProps = {\n  children: ReactNode;\n  className?: string;\n  \"aria-label\"?: string;\n  initialFocusRef?: RefObject<HTMLElement | null>;\n  finalFocusRef?: RefObject<HTMLElement | null>;\n};\n\nexport function DialogContent({\n  children,\n  className,\n  \"aria-label\": ariaLabel,\n  initialFocusRef,\n  finalFocusRef,\n}: DialogContentProps) {\n  const {\n    open,\n    requestClose,\n    titleId,\n    hasAccessibleTitle,\n    descriptionId,\n    closeOnOverlayClick,\n    overlayScopeId,\n    finalFocusRef: dialogFinalFocusRef,\n  } = useDialogContext(\"DialogContent\");\n\n  const [contentNode, setContentNode] = useState<HTMLDivElement | null>(null);\n  const [viewportNode, setViewportNode] = useState<HTMLDivElement | null>(null);\n  const warnedMissingTitleRef = useRef(false);\n\n  const setContentRef = useCallback((node: HTMLDivElement | null) => {\n    setContentNode(node);\n  }, []);\n\n  const setViewportRef = useCallback((node: HTMLDivElement | null) => {\n    setViewportNode(node);\n  }, []);\n\n  useEffect(() => {\n    if (open && finalFocusRef?.current) {\n      dialogFinalFocusRef.current = finalFocusRef.current;\n    }\n  }, [dialogFinalFocusRef, finalFocusRef, open]);\n\n  useBodyScrollLock(open);\n  useBackgroundInert(open, viewportNode);\n  const stackZIndex = useOverlayEscape(open, () => requestClose(\"escape-key\"), { modal: true });\n  useFocusTrap(open, contentNode, { initialFocusRef, overlayScopeId });\n\n  useEffect(() => {\n    if (!open) {\n      warnedMissingTitleRef.current = false;\n      return;\n    }\n\n    if (\n      process.env.NODE_ENV === \"development\" &&\n      !ariaLabel &&\n      !hasAccessibleTitle &&\n      !warnedMissingTitleRef.current\n    ) {\n      warnedMissingTitleRef.current = true;\n      console.warn(\n        \"[Skrewww Dialog] Every modal Dialog requires DialogTitle or an explicit aria-label on DialogContent.\",\n      );\n    }\n  }, [ariaLabel, hasAccessibleTitle, open]);\n\n  if (!open) return null;\n\n  return (\n    <Portal>\n      <div\n        ref={setViewportRef}\n        className={styles.viewport}\n        style={{ zIndex: stackZIndex }}\n        onMouseDown={(event) => {\n          if (!closeOnOverlayClick) return;\n          if (event.target === event.currentTarget) {\n            requestClose(\"overlay-pointer\");\n          }\n        }}\n      >\n        <div\n          className={styles.overlayBackdrop}\n          aria-hidden=\"true\"\n          onMouseDown={() => {\n            if (closeOnOverlayClick) requestClose(\"overlay-pointer\");\n          }}\n        />\n        <div\n          ref={setContentRef}\n          role=\"dialog\"\n          aria-modal=\"true\"\n          aria-labelledby={ariaLabel ? undefined : titleId}\n          aria-describedby={descriptionId}\n          aria-label={ariaLabel}\n          className={cn(styles.content, className)}\n          tabIndex={-1}\n          onMouseDown={(event) => event.stopPropagation()}\n        >\n          {children}\n        </div>\n      </div>\n    </Portal>\n  );\n}\n\nexport type DialogTitleProps = {\n  children: ReactNode;\n  className?: string;\n  visuallyHidden?: boolean;\n};\n\nexport function DialogTitle({ children, className, visuallyHidden = false }: DialogTitleProps) {\n  const { titleId, registerAccessibleTitle } = useDialogContext(\"DialogTitle\");\n\n  useEffect(() => {\n    registerAccessibleTitle(true);\n    return () => registerAccessibleTitle(false);\n  }, [registerAccessibleTitle]);\n\n  return (\n    <h2 id={titleId} className={cn(styles.title, visuallyHidden && \"sr-only\", className)}>\n      {children}\n    </h2>\n  );\n}\n\nexport type DialogDescriptionProps = {\n  children: ReactNode;\n  className?: string;\n};\n\nexport function DialogDescription({ children, className }: DialogDescriptionProps) {\n  const { setDescriptionId } = useDialogContext(\"DialogDescription\");\n  const id = useId();\n\n  useEffect(() => {\n    setDescriptionId(id);\n    return () => setDescriptionId(undefined);\n  }, [id, setDescriptionId]);\n\n  return (\n    <p id={id} className={cn(styles.description, className)}>\n      {children}\n    </p>\n  );\n}\n\nexport type DialogCloseProps = {\n  className?: string;\n  label?: string;\n};\n\nexport function DialogClose({ className, label = \"Close dialog\" }: DialogCloseProps) {\n  const { requestClose } = useDialogContext(\"DialogClose\");\n  return (\n    <button\n      type=\"button\"\n      className={cn(styles.close, className)}\n      aria-label={label}\n      onClick={() => requestClose(\"close-button\")}\n    >\n      <X size={16} aria-hidden=\"true\" />\n    </button>\n  );\n}\n\nexport type DialogFooterProps = {\n  children: ReactNode;\n  className?: string;\n};\n\nexport function DialogFooter({ children, className }: DialogFooterProps) {\n  return <div className={cn(styles.footer, className)}>{children}</div>;\n}\n\nexport type DialogHeaderProps = {\n  children: ReactNode;\n  className?: string;\n};\n\nexport function DialogHeader({ children, className }: DialogHeaderProps) {\n  return <div className={cn(styles.header, className)}>{children}</div>;\n}\n\nexport type DialogBodyProps = {\n  children: ReactNode;\n  className?: string;\n};\n\nexport function DialogBody({ children, className }: DialogBodyProps) {\n  return <div className={cn(styles.body, className)}>{children}</div>;\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/Dialog.tsx"
    },
    {
      "path": "components/ui/dialog.module.css",
      "content": ".viewport {\n  position: fixed;\n  inset: 0;\n  z-index: var(--dialog-z-index);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  padding: var(--dialog-viewport-padding);\n}\n\n.overlayBackdrop {\n  position: absolute;\n  inset: 0;\n  background: var(--dialog-overlay-background);\n}\n\n.content {\n  position: relative;\n  z-index: 1;\n  display: flex;\n  flex-direction: column;\n  width: min(100%, var(--dialog-width));\n  max-height: min(var(--dialog-max-height), calc(100vh - 2rem));\n  overflow: hidden;\n  border: 1px solid transparent;\n  border-radius: var(--dialog-radius);\n  background:\n    var(--component-surface-gradient-overlay) padding-box,\n    linear-gradient(var(--component-card-surface), var(--component-card-surface)) padding-box,\n    var(--component-card-border-gradient) border-box;\n  color: var(--semantic-text-primary);\n  box-shadow: none;\n  backdrop-filter: var(--component-surface-backdrop-filter);\n  outline: none;\n}\n\n.header {\n  display: flex;\n  align-items: flex-start;\n  justify-content: space-between;\n  gap: var(--dialog-header-gap);\n  padding: var(--dialog-padding);\n  padding-bottom: 0;\n}\n\n.title {\n  margin: 0;\n  font-size: 1.125rem;\n  font-weight: 600;\n  line-height: 1.35;\n  color: var(--semantic-text-primary);\n}\n\n.close {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  width: var(--dialog-close-size);\n  height: var(--dialog-close-size);\n  border: 0;\n  border-radius: min(var(--shape-radius-control), 9999px);\n  background: transparent;\n  color: var(--component-surface-content-muted);\n  cursor: pointer;\n}\n\n.close:focus-visible {\n  outline: 2px solid var(--semantic-focus-ring);\n  outline-offset: 2px;\n}\n\n.description {\n  margin: 0;\n  padding: 0 var(--dialog-padding);\n  padding-top: var(--dialog-body-gap);\n  font-size: 0.875rem;\n  line-height: 1.5;\n  color: var(--semantic-text-secondary);\n}\n\n.body {\n  padding: var(--dialog-padding);\n  overflow-y: auto;\n  color: var(--semantic-text-secondary);\n}\n\n.footer {\n  display: flex;\n  flex-wrap: wrap;\n  justify-content: flex-end;\n  gap: 0.5rem;\n  padding: var(--dialog-padding);\n  border-top: 0;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .content {\n    animation: none;\n  }\n}\n\n@media (prefers-reduced-transparency: reduce) {\n  .overlayBackdrop {\n    background: var(--dialog-overlay-background-opaque);\n  }\n}\n\n[data-skrewww-shape=\"pill\"] .content {\n  border-radius: min(var(--dialog-radius), 1.5rem);\n}\n\n@keyframes dialog-enter {\n  from {\n    opacity: 0;\n    transform: translateY(8px) scale(0.98);\n  }\n\n  to {\n    opacity: 1;\n    transform: translateY(0) scale(1);\n  }\n}\n\n.content {\n  animation: dialog-enter var(--dialog-open-duration) var(--dialog-motion-easing);\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .content {\n    animation: none;\n  }\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/dialog.module.css"
    },
    {
      "path": "lib/cn.ts",
      "content": "export function cn(...classes: Array<string | false | null | undefined>): string {\n  return classes.filter(Boolean).join(\" \");\n}\n",
      "type": "registry:lib",
      "target": "~/lib/cn.ts"
    },
    {
      "path": "lib/use-controllable.ts",
      "content": "import { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport function useControllableState<T>({\n  value,\n  defaultValue,\n  onChange,\n  controlled: controlledProp,\n  valueProvided,\n}: {\n  value?: T;\n  defaultValue?: T;\n  onChange?: (next: T) => void;\n  /** Explicit controlled override — prefer `valueProvided` from the component root. */\n  controlled?: boolean;\n  /** True when the parent passed a `value` prop, including `undefined`. */\n  valueProvided?: boolean;\n}) {\n  const [uncontrolled, setUncontrolled] = useState(defaultValue as T);\n  const isControlled = controlledProp ?? valueProvided ?? value !== undefined;\n  const current = isControlled ? (value as T) : uncontrolled;\n  const wasControlledRef = useRef(isControlled);\n\n  useEffect(() => {\n    if (process.env.NODE_ENV !== \"development\") return;\n    if (wasControlledRef.current !== isControlled) {\n      console.warn(\n        \"[Skrewww] A component changed between controlled and uncontrolled modes. Keep `value` or `defaultValue` usage consistent across renders.\",\n      );\n    }\n    wasControlledRef.current = isControlled;\n  }, [isControlled]);\n\n  const setValue = useCallback(\n    (next: T) => {\n      if (!isControlled) setUncontrolled(next);\n      onChange?.(next);\n    },\n    [isControlled, onChange],\n  );\n\n  return [current, setValue] as const;\n}\n",
      "type": "registry:lib",
      "target": "~/lib/use-controllable.ts"
    },
    {
      "path": "components/ui/internal/Portal.tsx",
      "content": "\"use client\";\n\nimport { createPortal } from \"react-dom\";\nimport { useIsClient } from \"@/components/ui/internal/useIsClient\";\n\nexport type PortalProps = {\n  children: React.ReactNode;\n  container?: Element | DocumentFragment | null;\n};\n\nexport function Portal({ children, container }: PortalProps) {\n  const mounted = useIsClient();\n\n  if (!mounted) return null;\n\n  const target =\n    container ?? (typeof document !== \"undefined\" ? document.body : null);\n  if (!target) return null;\n\n  return createPortal(children, target);\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/internal/Portal.tsx"
    },
    {
      "path": "components/ui/internal/useIsClient.ts",
      "content": "import { useSyncExternalStore } from \"react\";\n\nconst subscribe = () => () => {};\n\n/**\n * Client-only gate for portals and browser APIs.\n * Hydration uses the server snapshot (`false`); the client snapshot is `true`.\n */\nexport function useIsClient() {\n  return useSyncExternalStore(subscribe, () => true, () => false);\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/useIsClient.ts"
    },
    {
      "path": "components/ui/internal/OverlayScopeContext.tsx",
      "content": "\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\nconst OverlayScopeContext = createContext<string | undefined>(undefined);\n\nexport function OverlayScopeProvider({\n  scopeId,\n  children,\n}: {\n  scopeId: string;\n  children: React.ReactNode;\n}) {\n  return <OverlayScopeContext.Provider value={scopeId}>{children}</OverlayScopeContext.Provider>;\n}\n\nexport function useOverlayScope(): string | undefined {\n  return useContext(OverlayScopeContext);\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/internal/OverlayScopeContext.tsx"
    },
    {
      "path": "components/ui/internal/useBackgroundInert.ts",
      "content": "import { useEffect } from \"react\";\n\ntype InertSnapshot = {\n  element: HTMLElement;\n  previous: boolean;\n};\n\nlet modalInertCount = 0;\nconst snapshots: InertSnapshot[] = [];\n\nexport function supportsInert(): boolean {\n  return typeof HTMLElement !== \"undefined\" && \"inert\" in HTMLElement.prototype;\n}\n\nfunction applyBackgroundInert(excludeElement: HTMLElement | null) {\n  if (!supportsInert()) return;\n\n  for (const child of Array.from(document.body.children)) {\n    if (!(child instanceof HTMLElement)) continue;\n    if (excludeElement && (child === excludeElement || child.contains(excludeElement))) continue;\n\n    snapshots.push({ element: child, previous: child.inert });\n    child.inert = true;\n  }\n}\n\nfunction restoreBackgroundInert() {\n  for (const snapshot of snapshots) {\n    snapshot.element.inert = snapshot.previous;\n  }\n  snapshots.length = 0;\n}\n\nexport function resetBackgroundInertForTests() {\n  modalInertCount = 0;\n  restoreBackgroundInert();\n}\n\nexport function useBackgroundInert(active: boolean, excludeElement: HTMLElement | null) {\n  useEffect(() => {\n    if (!active || !excludeElement) return;\n\n    modalInertCount += 1;\n    if (modalInertCount === 1) {\n      applyBackgroundInert(excludeElement);\n    }\n\n    return () => {\n      modalInertCount -= 1;\n      if (modalInertCount === 0) {\n        restoreBackgroundInert();\n      }\n    };\n  }, [active, excludeElement]);\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/useBackgroundInert.ts"
    },
    {
      "path": "components/ui/internal/useBodyScrollLock.ts",
      "content": "import { useEffect } from \"react\";\n\nexport function useBodyScrollLock(active: boolean) {\n  useEffect(() => {\n    if (!active) return;\n\n    const previousOverflow = document.body.style.overflow;\n    document.body.style.overflow = \"hidden\";\n\n    return () => {\n      document.body.style.overflow = previousOverflow;\n    };\n  }, [active]);\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/useBodyScrollLock.ts"
    },
    {
      "path": "components/ui/internal/useOverlayEscape.ts",
      "content": "import { useLayoutEffect, useState } from \"react\";\nimport { registerOverlay } from \"@/components/ui/internal/overlay-stack\";\nimport { useLatestRef } from \"@/components/ui/internal/useLatestRef\";\n\n/**\n * Base z-index for stacked overlay content (Popover/Dialog/Drawer/Tooltip). Each\n * overlay's actual z-index is this base plus its registration order in the shared\n * overlay stack, so an overlay opened later — e.g. a Popover opened from inside an\n * already-open Dialog — always renders above the ones already on screen, regardless\n * of which component type it is. Without this, a Popover's static z-index token could\n * be lower than a Dialog's/Drawer's, rendering it behind them even though it opened\n * on top of the stack (see docs/architecture nested-overlay notes).\n */\nconst OVERLAY_STACK_BASE_Z_INDEX = 60;\n\nexport function useOverlayEscape(\n  active: boolean,\n  onEscape: () => void,\n  options?: { modal?: boolean },\n): number | undefined {\n  const onEscapeRef = useLatestRef(onEscape);\n  const [zIndex, setZIndex] = useState<number | undefined>(undefined);\n\n  useLayoutEffect(() => {\n    // Skip when inactive: every consumer of this hook (Popover/Dialog/Drawer/Tooltip content)\n    // renders null while its own `open`/`active` state is false, so a stale zIndex from a prior\n    // open never reaches the DOM — it gets overwritten with a fresh order-derived value the next\n    // time this effect registers.\n    if (!active) return;\n    const { order, unregister } = registerOverlay(() => onEscapeRef.current(), {\n      modal: options?.modal,\n    });\n    setZIndex(OVERLAY_STACK_BASE_Z_INDEX + order);\n    return unregister;\n  }, [active, onEscapeRef, options?.modal]);\n\n  return zIndex;\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/useOverlayEscape.ts"
    },
    {
      "path": "components/ui/internal/overlay-stack.ts",
      "content": "type OverlayRegistration = {\n  id: symbol;\n  order: number;\n  onEscape: () => void;\n  modal: boolean;\n};\n\nexport type OverlayHandle = {\n  /** Monotonically increasing registration order — later-registered overlays get higher values. */\n  order: number;\n  unregister: () => void;\n};\n\nlet orderCounter = 0;\nconst overlayStack: OverlayRegistration[] = [];\nlet escapeListenerBound = false;\n\nfunction handleDocumentEscape(event: KeyboardEvent) {\n  if (event.key !== \"Escape\") return;\n  const top = overlayStack[overlayStack.length - 1];\n  if (!top) return;\n  event.preventDefault();\n  event.stopPropagation();\n  top.onEscape();\n}\n\nfunction ensureEscapeListener() {\n  if (escapeListenerBound || typeof document === \"undefined\") return;\n  document.addEventListener(\"keydown\", handleDocumentEscape);\n  escapeListenerBound = true;\n}\n\nexport function registerOverlay(\n  onEscape: () => void,\n  options?: { modal?: boolean },\n): OverlayHandle {\n  ensureEscapeListener();\n\n  const registration: OverlayRegistration = {\n    id: Symbol(\"overlay\"),\n    order: ++orderCounter,\n    onEscape,\n    modal: options?.modal ?? false,\n  };\n\n  overlayStack.push(registration);\n  overlayStack.sort((left, right) => left.order - right.order);\n\n  return {\n    order: registration.order,\n    unregister: () => {\n      const index = overlayStack.findIndex((entry) => entry.id === registration.id);\n      if (index >= 0) overlayStack.splice(index, 1);\n    },\n  };\n}\n\nexport function getTopOverlay(): OverlayRegistration | undefined {\n  return overlayStack[overlayStack.length - 1];\n}\n\nexport function clearOverlayStackForTests() {\n  overlayStack.length = 0;\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/overlay-stack.ts"
    },
    {
      "path": "components/ui/internal/useLatestRef.ts",
      "content": "import { useLayoutEffect, useRef } from \"react\";\n\n/**\n * Keep a ref pointed at the latest value without retriggering an effect that\n * only needs to read it later (event handlers, observers, overlay callbacks).\n * The write happens after commit so it does not read/write refs during render.\n */\nexport function useLatestRef<T>(value: T) {\n  const ref = useRef(value);\n  useLayoutEffect(() => {\n    ref.current = value;\n  }, [value]);\n  return ref;\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/useLatestRef.ts"
    },
    {
      "path": "components/ui/internal/useFocusTrap.ts",
      "content": "import { useEffect, useLayoutEffect } from \"react\";\nimport { useLatestRef } from \"@/components/ui/internal/useLatestRef\";\nimport {\n  getFocusableElementsForScope,\n  resolveInitialFocusTarget,\n} from \"@/components/ui/internal/focus-utils\";\n\ntype FocusTrapOptions = {\n  initialFocusRef?: React.RefObject<HTMLElement | null>;\n  overlayScopeId?: string;\n};\n\nexport function useFocusTrap(\n  active: boolean,\n  container: HTMLElement | null,\n  options?: FocusTrapOptions,\n) {\n  const optionsRef = useLatestRef(options);\n\n  useLayoutEffect(() => {\n    if (!active || !container) return;\n\n    const focusInitial = () => {\n      const target = resolveInitialFocusTarget(\n        container,\n        optionsRef.current?.initialFocusRef,\n        optionsRef.current?.overlayScopeId,\n      );\n      target.focus();\n    };\n\n    focusInitial();\n    const timer = window.setTimeout(focusInitial, 0);\n    return () => window.clearTimeout(timer);\n  }, [active, container, optionsRef]);\n\n  useEffect(() => {\n    if (!active || !container) return;\n\n    function handleKeyDown(event: KeyboardEvent) {\n      if (event.key !== \"Tab\" || !container) return;\n      const nodes = getFocusableElementsForScope(\n        container,\n        optionsRef.current?.overlayScopeId,\n      );\n      if (nodes.length === 0) {\n        event.preventDefault();\n        return;\n      }\n\n      const first = nodes[0];\n      const last = nodes[nodes.length - 1];\n      const activeElement = document.activeElement;\n\n      if (event.shiftKey && activeElement === first) {\n        event.preventDefault();\n        last.focus();\n      } else if (!event.shiftKey && activeElement === last) {\n        event.preventDefault();\n        first.focus();\n      }\n    }\n\n    document.addEventListener(\"keydown\", handleKeyDown);\n    return () => {\n      document.removeEventListener(\"keydown\", handleKeyDown);\n    };\n  }, [active, container, optionsRef]);\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/useFocusTrap.ts"
    },
    {
      "path": "components/ui/internal/focus-utils.ts",
      "content": "const FOCUSABLE_SELECTOR =\n  'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex=\"-1\"])';\n\nexport function getFocusableElements(container: HTMLElement): HTMLElement[] {\n  return Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(\n    (element) =>\n      !element.hasAttribute(\"disabled\") &&\n      element.getAttribute(\"aria-disabled\") !== \"true\" &&\n      element.tabIndex !== -1,\n  );\n}\n\nexport function getFocusableElementsForScope(\n  container: HTMLElement,\n  overlayScopeId?: string,\n): HTMLElement[] {\n  const focusables = getFocusableElements(container);\n\n  if (!overlayScopeId || typeof document === \"undefined\") {\n    return focusables;\n  }\n\n  const scopedNodes = Array.from(\n    document.querySelectorAll<HTMLElement>(\n      `[data-skrewww-overlay-scope=\"${overlayScopeId}\"]`,\n    ),\n  );\n\n  for (const scopedNode of scopedNodes) {\n    focusables.push(...getFocusableElements(scopedNode));\n  }\n\n  return focusables.filter(\n    (element, index, array) => array.indexOf(element) === index,\n  );\n}\n\nexport function resolveInitialFocusTarget(\n  container: HTMLElement,\n  initialFocusRef?: React.RefObject<HTMLElement | null>,\n  overlayScopeId?: string,\n): HTMLElement {\n  const initial = initialFocusRef?.current;\n  if (initial && container.contains(initial)) {\n    return initial;\n  }\n\n  const focusables = getFocusableElementsForScope(container, overlayScopeId);\n  return focusables[0] ?? container;\n}\n\nexport function restoreFocusSafely(\n  primary: HTMLElement | null | undefined,\n  fallback?: HTMLElement | null,\n) {\n  const target = primary && document.contains(primary) ? primary : fallback;\n  target?.focus?.();\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/focus-utils.ts"
    },
    {
      "path": "components/ui/internal/assign-ref.ts",
      "content": "import type { Ref } from \"react\";\n\n/** Write a value into a React ref prop (callback or object) without touching render. */\nexport function assignRef<T>(ref: Ref<T> | undefined | null, value: T) {\n  if (!ref) return;\n  if (typeof ref === \"function\") {\n    ref(value);\n    return;\n  }\n  ref.current = value;\n}\n\nexport function mergeRefs<T>(\n  ...refs: Array<Ref<T> | undefined | null>\n): (value: T) => void {\n  return (value) => {\n    for (const ref of refs) {\n      assignRef(ref, value);\n    }\n  };\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/assign-ref.ts"
    },
    {
      "path": "components/ui/internal/overlay-types.ts",
      "content": "export type OverlayCloseReason =\n  | \"escape-key\"\n  | \"close-button\"\n  | \"overlay-pointer\"\n  | \"programmatic\";\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/overlay-types.ts"
    }
  ]
}
