{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"dropdown-menu","type":"registry:component","title":"Dropdown Menu","description":"Composable dropdown menu that opens from its trigger, with a gliding highlight, submenus that stay open on a diagonal path, checkbox and radio items, shortcuts and full keyboard support.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["clsx","lucide-react","motion","tailwind-merge"],"registryDependencies":[],"files":[{"path":"components/motion/dropdown-menu.tsx","type":"registry:component","target":"@components/motion/dropdown-menu.tsx","content":"\"use client\";\n// beui.dev/components/motion/dropdown-menu\n\nimport { Check, ChevronRight } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion, type Variants } from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type MouseEvent as ReactMouseEvent,\n  type MutableRefObject,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_PANEL } from \"@/lib/ease\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { PresenceGate } from \"@/lib/presence-gate\";\nimport { cn } from \"@/lib/utils\";\n\nconst VIEWPORT_PADDING = 8;\n// The panel's border and padding, so a submenu's first row lines up with the\n// row that opened it.\nconst SUB_ALIGN_OFFSET = 5;\n// How far a submenu stacked under its row sits in, so it reads as nested.\nconst SUB_STACK_INDENT = 16;\n// Long enough to skip the submenus a pointer crosses on its way somewhere else.\nconst SUB_OPEN_DELAY = 100;\n// How long a pointer heading for an open submenu may cross sibling rows.\nconst SUB_GRACE = 300;\nconst TYPEAHEAD_RESET = 500;\nconst EXIT = { duration: 0.12, ease: EASE_OUT };\n// The panel grows out of its trigger from this scale and distance.\nconst OPEN_SCALE = 0.94;\nconst OPEN_TRAVEL = 6;\nconst OPEN = { duration: 0.2, ease: EASE_OUT };\n\ntype Side = \"top\" | \"bottom\" | \"left\" | \"right\";\ntype Align = \"start\" | \"center\" | \"end\";\ntype FocusTarget = \"first\" | \"last\" | \"panel\" | \"none\";\ntype Point = { x: number; y: number };\n\ntype TriggerElementProps = React.HTMLAttributes<HTMLElement> & {\n  ref?: Ref<HTMLElement>;\n  \"data-state\"?: \"open\" | \"closed\";\n};\n\ninterface RootContextValue {\n  open: boolean;\n  setOpen: (open: boolean, focus?: FocusTarget) => void;\n  focusTarget: FocusTarget;\n  menuId: string;\n  triggerId: string;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  reduce: boolean;\n  mounted: boolean;\n}\n\nconst RootContext = createContext<RootContextValue | null>(null);\n\nfunction useRoot(component: string) {\n  const context = useContext(RootContext);\n  if (!context) throw new Error(`${component} must be used within <DropdownMenu>`);\n  return context;\n}\n\n/** One open panel: the root menu or a submenu. */\ninterface LevelContextValue {\n  levelId: string;\n  present: boolean;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n  activeId: string | null;\n  setActiveId: (id: string | null) => void;\n  openSub: string | null;\n  setOpenSub: (id: string | null, focus?: FocusTarget) => void;\n  subFocus: FocusTarget;\n  /** A pointer on its way from a submenu trigger to the submenu it opened. */\n  grace: MutableRefObject<{ polygon: Point[]; until: number } | null>;\n}\n\nconst LevelContext = createContext<LevelContextValue | null>(null);\n\nfunction useLevel(component: string) {\n  const context = useContext(LevelContext);\n  if (!context) {\n    throw new Error(`${component} must be used within <DropdownMenuContent>`);\n  }\n  return context;\n}\n\nfunction assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) ref.current = value;\n}\n\nfunction clamp(value: number, min: number, max: number) {\n  return Math.min(Math.max(value, min), Math.max(min, max));\n}\n\nfunction enabledItems(panel: HTMLElement | null) {\n  if (!panel) return [];\n  return Array.from(\n    panel.querySelectorAll<HTMLElement>(\n      `[data-menu-item][data-level=\"${panel.dataset.level}\"]:not([data-disabled])`,\n    ),\n  );\n}\n\nfunction insidePolygon(point: Point, polygon: Point[]) {\n  let inside = false;\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const a = polygon[i];\n    const b = polygon[j];\n    if (\n      a.y > point.y !== b.y > point.y &&\n      point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x\n    ) {\n      inside = !inside;\n    }\n  }\n  return inside;\n}\n\ntype Placement = {\n  left: number;\n  top: number;\n  side: Side;\n  origin: string;\n  /** The room on the chosen side; a taller menu scrolls inside it. */\n  maxHeight: number;\n};\n\ntype Rect = { left: number; top: number; width: number; height: number };\n\nfunction placeVertical(\n  trigger: Rect,\n  size: { width: number; height: number },\n  side: \"top\" | \"bottom\",\n  align: Align,\n  offset: number,\n): Placement {\n  const viewWidth = document.documentElement.clientWidth;\n  const viewHeight = window.innerHeight;\n  const below = trigger.top + trigger.height + offset;\n  const roomBelow = viewHeight - VIEWPORT_PADDING - below;\n  const roomAbove = trigger.top - offset - VIEWPORT_PADDING;\n  // The preferred side when the menu fits there, otherwise the roomier one.\n  const used =\n    side === \"bottom\"\n      ? size.height <= roomBelow || roomBelow >= roomAbove\n        ? \"bottom\"\n        : \"top\"\n      : size.height <= roomAbove || roomAbove >= roomBelow\n        ? \"top\"\n        : \"bottom\";\n  const maxHeight = Math.max(used === \"bottom\" ? roomBelow : roomAbove, 0);\n  const height = Math.min(size.height, maxHeight);\n  const start =\n    align === \"start\"\n      ? trigger.left\n      : align === \"end\"\n        ? trigger.left + trigger.width - size.width\n        : trigger.left + trigger.width / 2 - size.width / 2;\n  const x = clamp(start, VIEWPORT_PADDING, viewWidth - size.width - VIEWPORT_PADDING);\n  const y = used === \"bottom\" ? below : trigger.top - offset - height;\n  // Grow from the aligned edge, so that edge holds still while the panel\n  // scales in instead of sliding sideways into place.\n  const anchorX =\n    align === \"start\"\n      ? trigger.left\n      : align === \"end\"\n        ? trigger.left + trigger.width\n        : trigger.left + trigger.width / 2;\n  const originX = clamp(anchorX - x, 0, size.width);\n  return {\n    left: x,\n    top: y,\n    side: used,\n    origin: `${originX}px ${used === \"bottom\" ? 0 : height}px`,\n    maxHeight,\n  };\n}\n\nfunction place(\n  trigger: Rect,\n  size: { width: number; height: number },\n  side: Side,\n  align: Align,\n  offset: number,\n): Placement {\n  if (side === \"top\" || side === \"bottom\") {\n    return placeVertical(trigger, size, side, align, offset);\n  }\n\n  const viewWidth = document.documentElement.clientWidth;\n  const viewHeight = window.innerHeight;\n  const right = trigger.left + trigger.width + offset;\n  const left = trigger.left - size.width - offset;\n  const fitsRight = right + size.width <= viewWidth - VIEWPORT_PADDING;\n  const fitsLeft = left >= VIEWPORT_PADDING;\n  // A narrow screen has room on neither side: drop below the row instead of\n  // covering it, the way a phone stacks a submenu.\n  if (!fitsRight && !fitsLeft) {\n    return placeVertical(\n      { ...trigger, left: trigger.left + SUB_STACK_INDENT, width: trigger.width - SUB_STACK_INDENT },\n      size,\n      \"bottom\",\n      \"start\",\n      2,\n    );\n  }\n  const used: Side = side === \"right\" ? (fitsRight ? \"right\" : \"left\") : fitsLeft ? \"left\" : \"right\";\n  const maxHeight = viewHeight - VIEWPORT_PADDING * 2;\n  const height = Math.min(size.height, maxHeight);\n  const x = used === \"right\" ? right : left;\n  const y = clamp(trigger.top - SUB_ALIGN_OFFSET, VIEWPORT_PADDING, viewHeight - height - VIEWPORT_PADDING);\n  const originY = clamp(trigger.top + trigger.height / 2 - y, 0, height);\n  return {\n    left: x,\n    top: y,\n    side: used,\n    origin: `${used === \"right\" ? 0 : size.width}px ${originY}px`,\n    maxHeight,\n  };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Root                                                                       */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuProps {\n  children: ReactNode;\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n}\n\nexport function DropdownMenu({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n}: DropdownMenuProps) {\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const [focusTarget, setFocusTarget] = useState<FocusTarget>(\"first\");\n  const [mounted, setMounted] = useState(false);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const menuId = useId();\n  const triggerId = useId();\n  const reduce = useReducedMotion() ?? false;\n\n  useEffect(() => setMounted(true), []);\n\n  const setOpen = useCallback(\n    (next: boolean, focus: FocusTarget = \"first\") => {\n      if (next) setFocusTarget(focus);\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n\n  // Focus goes back to the trigger when the menu closes from inside it, or\n  // with nothing focused. A click elsewhere keeps the focus it landed on.\n  const wasOpen = useRef(open);\n  useEffect(() => {\n    if (wasOpen.current === open) return;\n    wasOpen.current = open;\n    if (open) return;\n    const active = document.activeElement;\n    if (\n      !active ||\n      active === document.body ||\n      active.closest(`[data-menu-root=\"${CSS.escape(menuId)}\"]`)\n    ) {\n      triggerRef.current?.focus({ preventScroll: true });\n    }\n  }, [open, menuId]);\n\n  const value = useMemo<RootContextValue>(\n    () => ({\n      open,\n      setOpen,\n      focusTarget,\n      menuId,\n      triggerId,\n      triggerRef,\n      reduce,\n      mounted,\n    }),\n    [open, setOpen, focusTarget, menuId, triggerId, reduce, mounted],\n  );\n\n  return <RootContext.Provider value={value}>{children}</RootContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Trigger                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuTriggerProps {\n  /** A single focusable element, usually a button. */\n  children: ReactElement<TriggerElementProps>;\n  disabled?: boolean;\n}\n\nexport function DropdownMenuTrigger({ children, disabled = false }: DropdownMenuTriggerProps) {\n  const root = useRoot(\"DropdownMenuTrigger\");\n  if (!isValidElement(children)) {\n    throw new Error(\"<DropdownMenuTrigger> requires a single React element\");\n  }\n  const childProps = children.props;\n  const childRef = children.props.ref;\n\n  return cloneElement(children, {\n    ref: (node: HTMLElement | null) => {\n      root.triggerRef.current = node;\n      assignRef(childRef, node);\n    },\n    id: childProps.id ?? root.triggerId,\n    \"aria-haspopup\": \"menu\",\n    \"aria-expanded\": root.open,\n    \"aria-controls\": root.open ? root.menuId : undefined,\n    \"data-state\": root.open ? \"open\" : \"closed\",\n    onClick: (event: ReactMouseEvent<HTMLElement>) => {\n      childProps.onClick?.(event);\n      if (event.defaultPrevented || disabled) return;\n      // `detail` is 0 for a click the keyboard synthesized from Enter or Space:\n      // that opener wants the first row, a pointer wants no row picked yet.\n      root.setOpen(!root.open, event.detail === 0 ? \"first\" : \"panel\");\n    },\n    onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {\n      childProps.onKeyDown?.(event);\n      if (event.defaultPrevented || disabled) return;\n      if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n        event.preventDefault();\n        root.setOpen(true, event.key === \"ArrowDown\" ? \"first\" : \"last\");\n      }\n    },\n  });\n}\n\n/* -------------------------------------------------------------------------- */\n/* Panel (shared by the menu and its submenus)                                */\n/* -------------------------------------------------------------------------- */\n\ninterface PanelProps {\n  children: ReactNode;\n  className?: string;\n  id: string;\n  anchorRef: MutableRefObject<HTMLElement | null>;\n  side: Side;\n  align: Align;\n  sideOffset: number;\n  focus: FocusTarget;\n  present: boolean;\n  gate: { inert: boolean; style: { pointerEvents: \"auto\" | \"none\" } };\n  labelledBy: string;\n  onClose: () => void;\n  onKeyDown?: (event: ReactKeyboardEvent<HTMLDivElement>) => boolean;\n  onPointerEnter?: () => void;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n}\n\nfunction MenuPanel({\n  children,\n  className,\n  id,\n  anchorRef,\n  side,\n  align,\n  sideOffset,\n  focus,\n  present,\n  gate,\n  labelledBy,\n  onClose,\n  onKeyDown,\n  onPointerEnter,\n  panelRef,\n}: PanelProps) {\n  const root = useRoot(\"DropdownMenuContent\");\n  const parent = useContext(LevelContext);\n  const levelId = useId();\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [openSub, setOpenSubState] = useState<string | null>(null);\n  const [subFocus, setSubFocus] = useState<FocusTarget>(\"none\");\n  const grace = useRef<{ polygon: Point[]; until: number } | null>(null);\n  const typeahead = useRef(\"\");\n  const typeaheadTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  const layout = usePopoverPortalPosition(anchorRef, panelRef, true);\n  // Held once placed: an exiting panel stays where it was, even if the\n  // trigger scrolls away under it.\n  const [placement, setPlacement] = useState<Placement | null>(null);\n  useLayoutEffect(() => {\n    if (!layout || !present) return;\n    // A submenu measures its gap from the parent panel's edge, not from the\n    // row inside it, so the two panels never touch.\n    const edge = parent?.panelRef.current?.getBoundingClientRect();\n    const anchor = edge ? { ...layout.trigger, left: edge.left, width: edge.width } : layout.trigger;\n    setPlacement(place(anchor, layout.content, side, align, sideOffset));\n  }, [layout, present, side, align, sideOffset, parent]);\n\n  const setOpenSub = useCallback((next: string | null, nextFocus: FocusTarget = \"none\") => {\n    setSubFocus(nextFocus);\n    setOpenSubState(next);\n  }, []);\n\n  // Waits for the first placement: the panel is `visibility: hidden` until\n  // then, and the browser will not focus anything inside it.\n  const placed = placement !== null;\n  useEffect(() => {\n    const panel = panelRef.current;\n    // `present` too: reopening during the exit brings this same panel back.\n    if (!placed || !present || !panel || focus === \"none\") return;\n    if (focus === \"panel\") {\n      panel.focus({ preventScroll: true });\n      return;\n    }\n    const items = enabledItems(panel);\n    (focus === \"last\" ? items[items.length - 1] : items[0])?.focus({ preventScroll: true });\n  }, [placed, present, focus, panelRef]);\n\n  useEffect(\n    () => () => {\n      if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);\n    },\n    [],\n  );\n\n  const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n    // Submenus render inside this panel's React tree, so their keys bubble\n    // here too. Each panel answers only for its own rows.\n    const panel = panelRef.current;\n    const target = event.target as HTMLElement;\n    if (!panel || target.closest(\"[data-menu-panel]\") !== panel) return;\n    if (onKeyDown?.(event)) return;\n\n    const items = enabledItems(panel);\n    const index = items.indexOf(target);\n    if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n      event.preventDefault();\n      if (items.length === 0) return;\n      const step = event.key === \"ArrowDown\" ? 1 : -1;\n      const next = index < 0 ? (step === 1 ? 0 : items.length - 1) : (index + step + items.length) % items.length;\n      items[next]?.focus();\n      return;\n    }\n    if (event.key === \"Home\" || event.key === \"End\") {\n      event.preventDefault();\n      items[event.key === \"Home\" ? 0 : items.length - 1]?.focus();\n      return;\n    }\n    if (event.key === \"Tab\") {\n      event.preventDefault();\n      onClose();\n      return;\n    }\n    const typed = event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;\n    if (!typed || (event.key === \" \" && typeahead.current === \"\")) return;\n    typeahead.current += event.key.toLocaleLowerCase();\n    if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);\n    typeaheadTimer.current = setTimeout(() => {\n      typeahead.current = \"\";\n    }, TYPEAHEAD_RESET);\n    // Start after the current row, so repeating a letter cycles its matches.\n    const ordered = [...items.slice(index + 1), ...items.slice(0, index + 1)];\n    const query = typeahead.current;\n    const repeated = query.length > 1 && [...query].every((char) => char === query[0]);\n    const needle = repeated ? query[0] : query;\n    const match = ordered.find((item) =>\n      (item.dataset.textValue ?? item.textContent ?? \"\").trim().toLocaleLowerCase().startsWith(needle),\n    );\n    if (match) {\n      event.preventDefault();\n      match.focus();\n    }\n  };\n\n  const level = useMemo<LevelContextValue>(\n    () => ({\n      levelId,\n      present,\n      panelRef,\n      activeId,\n      setActiveId,\n      openSub,\n      setOpenSub,\n      subFocus,\n      grace,\n    }),\n    [levelId, present, panelRef, activeId, openSub, setOpenSub, subFocus],\n  );\n\n  // The panel starts tucked toward its trigger and springs out of it.\n  const used = placement?.side ?? side;\n  const toward = used === \"top\" || used === \"left\" ? 1 : -1;\n  const vertical = used === \"top\" || used === \"bottom\";\n  const offset = (distance: number) => (vertical ? { y: distance * toward } : { x: distance * toward });\n  const variants: Variants = root.reduce\n    ? {\n        hidden: { opacity: 0 },\n        shown: { opacity: 1, transition: { duration: 0.15, ease: EASE_OUT } },\n        gone: { opacity: 0, transition: EXIT },\n      }\n    : {\n        hidden: { opacity: 0, scale: OPEN_SCALE, ...offset(OPEN_TRAVEL) },\n        shown: {\n          opacity: 1,\n          scale: 1,\n          x: 0,\n          y: 0,\n          transition: {\n            ...OPEN,\n            opacity: { duration: 0.12, ease: EASE_OUT },\n          },\n        },\n        gone: { opacity: 0, scale: 0.97, ...offset(OPEN_TRAVEL / 2), transition: EXIT },\n      };\n\n  return createPortal(\n    <motion.div\n      {...gate}\n      ref={panelRef}\n      id={id}\n      role=\"menu\"\n      aria-labelledby={labelledBy}\n      aria-orientation=\"vertical\"\n      tabIndex={-1}\n      data-menu-panel=\"\"\n      data-menu-root={root.menuId}\n      data-level={levelId}\n      data-side={placement?.side ?? side}\n      variants={variants}\n      initial=\"hidden\"\n      animate=\"shown\"\n      exit=\"gone\"\n      onKeyDown={handleKeyDown}\n      onFocus={(event) => {\n        if (event.target === event.currentTarget) setActiveId(null);\n      }}\n      onPointerEnter={onPointerEnter}\n      onPointerLeave={(event) => {\n        // Leaving the panel drops the highlight, unless the row it sits on\n        // owns the open submenu the pointer is heading into.\n        if (event.pointerType === \"touch\" || openSub) return;\n        const panel = panelRef.current;\n        if (panel?.contains(document.activeElement)) panel.focus({ preventScroll: true });\n      }}\n      style={{\n        ...gate.style,\n        left: placement?.left ?? 0,\n        top: placement?.top ?? 0,\n        transformOrigin: placement?.origin,\n        maxHeight: placement?.maxHeight,\n        visibility: placement ? undefined : \"hidden\",\n      }}\n      className={cn(\n        \"fixed z-[100] min-w-48 overflow-y-auto overscroll-contain rounded-xl border border-border bg-background p-1 text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)] outline-none\",\n        parent && \"z-[101]\",\n        className,\n      )}\n    >\n      <LevelContext.Provider value={level}>{children}</LevelContext.Provider>\n    </motion.div>,\n    document.body,\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Content                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuContentProps {\n  children: ReactNode;\n  className?: string;\n  /** Preferred side. Flips when the viewport has no room. Default \"bottom\". */\n  side?: \"top\" | \"bottom\";\n  /** Default \"start\". */\n  align?: Align;\n  /** Gap between trigger and menu in px. Default 6. */\n  sideOffset?: number;\n}\n\nexport function DropdownMenuContent({\n  children,\n  className,\n  side = \"bottom\",\n  align = \"start\",\n  sideOffset = 6,\n}: DropdownMenuContentProps) {\n  const root = useRoot(\"DropdownMenuContent\");\n  const panelRef = useRef<HTMLDivElement | null>(null);\n\n  const { setOpen, triggerRef, menuId } = root;\n  const close = useCallback(() => setOpen(false), [setOpen]);\n  const ignore = useCallback(\n    (target: Element) =>\n      Boolean(triggerRef.current?.contains(target)) ||\n      Boolean(target.closest(`[data-menu-root=\"${CSS.escape(menuId)}\"]`)),\n    [triggerRef, menuId],\n  );\n  useDismiss(root.open, close, null, { ignore });\n\n  if (!root.mounted) return null;\n\n  return (\n    <AnimatePresence>\n      {root.open && (\n        <PresenceGate>\n          {({ isPresent, gate }) => (\n            <MenuPanel\n              id={root.menuId}\n              anchorRef={root.triggerRef}\n              panelRef={panelRef}\n              side={side}\n              align={align}\n              sideOffset={sideOffset}\n              focus={root.focusTarget}\n              present={isPresent}\n              gate={gate}\n              labelledBy={root.triggerRef.current?.id ?? root.triggerId}\n              onClose={close}\n              className={className}\n            >\n              {children}\n            </MenuPanel>\n          )}\n        </PresenceGate>\n      )}\n    </AnimatePresence>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Items                                                                      */\n/* -------------------------------------------------------------------------- */\n\ntype ItemTone = \"default\" | \"destructive\";\n\nexport interface DropdownMenuItemProps {\n  children: ReactNode;\n  onSelect?: () => void;\n  disabled?: boolean;\n  /** Close the whole menu after selecting. Default true. */\n  closeOnSelect?: boolean;\n  tone?: ItemTone;\n  /** Indent to line up with checkbox and radio rows. */\n  inset?: boolean;\n  /** Text matched by typeahead when the label is not plain text. */\n  textValue?: string;\n  className?: string;\n}\n\ninterface ItemBaseProps extends DropdownMenuItemProps {\n  role?: \"menuitem\" | \"menuitemcheckbox\" | \"menuitemradio\";\n  checked?: boolean;\n  subTrigger?: {\n    id: string;\n    open: boolean;\n    controls: string;\n    onPointerMove: (event: React.PointerEvent<HTMLButtonElement>) => void;\n    onPointerLeave: (event: React.PointerEvent<HTMLButtonElement>) => void;\n    onKeyDown: (event: ReactKeyboardEvent<HTMLButtonElement>) => void;\n    onClick: () => void;\n    ref: MutableRefObject<HTMLElement | null>;\n  };\n}\n\nfunction ItemBase({\n  children,\n  onSelect,\n  disabled = false,\n  closeOnSelect = true,\n  tone = \"default\",\n  inset = false,\n  textValue,\n  className,\n  role = \"menuitem\",\n  checked,\n  subTrigger,\n}: ItemBaseProps) {\n  const root = useRoot(\"DropdownMenuItem\");\n  const level = useLevel(\"DropdownMenuItem\");\n  const ownId = useId();\n  const id = subTrigger?.id ?? ownId;\n  const active = level.activeId === id;\n\n  return (\n    <button\n      type=\"button\"\n      ref={(node) => {\n        if (subTrigger) subTrigger.ref.current = node;\n      }}\n      id={id}\n      role={role}\n      {...(role === \"menuitem\" ? {} : { \"aria-checked\": checked })}\n      aria-haspopup={subTrigger ? \"menu\" : undefined}\n      aria-expanded={subTrigger ? subTrigger.open : undefined}\n      aria-controls={subTrigger?.open ? subTrigger.controls : undefined}\n      aria-disabled={disabled || undefined}\n      tabIndex={-1}\n      data-menu-item=\"\"\n      data-level={level.levelId}\n      data-disabled={disabled ? \"\" : undefined}\n      data-highlighted={active ? \"\" : undefined}\n      data-text-value={textValue}\n      onFocus={() => {\n        level.setActiveId(id);\n        // Moving to another row of this menu closes a submenu it does not own.\n        if (level.openSub && level.openSub !== subTrigger?.id) level.setOpenSub(null);\n      }}\n      onPointerMove={(event) => {\n        if (event.pointerType === \"touch\") return;\n        // On the way to an open submenu, crossing this row changes nothing.\n        const grace = level.grace.current;\n        if (grace && Date.now() < grace.until && insidePolygon({ x: event.clientX, y: event.clientY }, grace.polygon)) {\n          return;\n        }\n        level.grace.current = null;\n        if (subTrigger) {\n          subTrigger.onPointerMove(event);\n          return;\n        }\n        if (level.openSub) level.setOpenSub(null);\n        if (disabled) {\n          if (level.panelRef.current?.contains(document.activeElement)) {\n            level.panelRef.current.focus({ preventScroll: true });\n          }\n          return;\n        }\n        if (document.activeElement !== event.currentTarget) {\n          event.currentTarget.focus({ preventScroll: true });\n        }\n      }}\n      onPointerLeave={subTrigger?.onPointerLeave}\n      onKeyDown={subTrigger?.onKeyDown}\n      onClick={() => {\n        if (disabled) return;\n        if (subTrigger) {\n          subTrigger.onClick();\n          return;\n        }\n        onSelect?.();\n        if (closeOnSelect) root.setOpen(false);\n      }}\n      className={cn(\n        \"relative isolate flex w-full cursor-default select-none items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm outline-none\",\n        \"[&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0\",\n        inset && \"pl-8\",\n        disabled && \"opacity-50\",\n        tone === \"destructive\" ? \"text-destructive [&_svg]:text-destructive\" : \"[&_svg]:text-muted-foreground\",\n        className,\n      )}\n    >\n      {active && !disabled ? (\n        <motion.span\n          aria-hidden=\"true\"\n          layoutId={`${level.levelId}-highlight`}\n          className={cn(\n            \"absolute inset-0 -z-10 rounded-lg\",\n            tone === \"destructive\" ? \"bg-destructive/10\" : \"bg-foreground/[0.07]\",\n          )}\n          transition={root.reduce ? { duration: 0 } : SPRING_LAYOUT}\n        />\n      ) : null}\n      {children}\n    </button>\n  );\n}\n\nexport function DropdownMenuItem(props: DropdownMenuItemProps) {\n  return <ItemBase {...props} />;\n}\n\nexport interface DropdownMenuCheckboxItemProps extends Omit<DropdownMenuItemProps, \"onSelect\" | \"tone\" | \"inset\"> {\n  checked: boolean;\n  onCheckedChange?: (checked: boolean) => void;\n}\n\n/** Stays open after a toggle by default, so the check can be seen landing. */\nexport function DropdownMenuCheckboxItem({\n  checked,\n  onCheckedChange,\n  closeOnSelect = false,\n  children,\n  ...props\n}: DropdownMenuCheckboxItemProps) {\n  const root = useRoot(\"DropdownMenuCheckboxItem\");\n  return (\n    <ItemBase\n      {...props}\n      role=\"menuitemcheckbox\"\n      checked={checked}\n      closeOnSelect={closeOnSelect}\n      onSelect={() => onCheckedChange?.(!checked)}\n      inset\n    >\n      <span aria-hidden=\"true\" className=\"absolute left-2 flex size-4 items-center justify-center\">\n        <AnimatePresence initial={false}>\n          {checked ? (\n            <motion.span\n              key=\"check\"\n              initial={root.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n              animate={{ opacity: 1, scale: 1 }}\n              exit={root.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n              transition={root.reduce ? { duration: 0.1 } : SPRING_PANEL}\n              className=\"flex\"\n            >\n              <Check className=\"size-3.5 text-foreground\" strokeWidth={2.4} />\n            </motion.span>\n          ) : null}\n        </AnimatePresence>\n      </span>\n      {children}\n    </ItemBase>\n  );\n}\n\ninterface RadioGroupContextValue {\n  value: string;\n  onValueChange?: (value: string) => void;\n}\n\nconst RadioGroupContext = createContext<RadioGroupContextValue | null>(null);\n\nexport interface DropdownMenuRadioGroupProps {\n  value: string;\n  onValueChange?: (value: string) => void;\n  children: ReactNode;\n  className?: string;\n}\n\nexport function DropdownMenuRadioGroup({ value, onValueChange, children, className }: DropdownMenuRadioGroupProps) {\n  const context = useMemo(() => ({ value, onValueChange }), [value, onValueChange]);\n  return (\n    <RadioGroupContext.Provider value={context}>\n      <div className={className}>{children}</div>\n    </RadioGroupContext.Provider>\n  );\n}\n\nexport interface DropdownMenuRadioItemProps extends Omit<DropdownMenuItemProps, \"onSelect\" | \"tone\" | \"inset\"> {\n  value: string;\n}\n\n/** Stays open after a pick by default, so the dot can be seen moving. */\nexport function DropdownMenuRadioItem({ value, closeOnSelect = false, children, ...props }: DropdownMenuRadioItemProps) {\n  const root = useRoot(\"DropdownMenuRadioItem\");\n  const group = useContext(RadioGroupContext);\n  if (!group) throw new Error(\"DropdownMenuRadioItem must be used within <DropdownMenuRadioGroup>\");\n  const checked = group.value === value;\n  return (\n    <ItemBase\n      {...props}\n      role=\"menuitemradio\"\n      checked={checked}\n      closeOnSelect={closeOnSelect}\n      onSelect={() => group.onValueChange?.(value)}\n      inset\n    >\n      <span aria-hidden=\"true\" className=\"absolute left-2 flex size-4 items-center justify-center\">\n        <motion.span\n          initial={false}\n          animate={root.reduce ? { opacity: checked ? 1 : 0 } : { opacity: checked ? 1 : 0, scale: checked ? 1 : 0.4 }}\n          transition={root.reduce ? { duration: 0.1 } : SPRING_PANEL}\n          className=\"size-1.5 rounded-full bg-foreground\"\n        />\n      </span>\n      {children}\n    </ItemBase>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Submenus                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface SubContextValue {\n  id: string;\n  contentId: string;\n  open: boolean;\n  focus: FocusTarget;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n  setOpen: (open: boolean, focus?: FocusTarget) => void;\n}\n\nconst SubContext = createContext<SubContextValue | null>(null);\n\nfunction useSub(component: string) {\n  const context = useContext(SubContext);\n  if (!context) throw new Error(`${component} must be used within <DropdownMenuSub>`);\n  return context;\n}\n\nexport interface DropdownMenuSubProps {\n  children: ReactNode;\n}\n\nexport function DropdownMenuSub({ children }: DropdownMenuSubProps) {\n  const level = useLevel(\"DropdownMenuSub\");\n  const id = useId();\n  const contentId = useId();\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const panelRef = useRef<HTMLDivElement | null>(null);\n  // Closes with its parent: an exiting menu takes its submenu out with it.\n  const open = level.openSub === id && level.present;\n  const { setOpenSub } = level;\n  const setOpen = useCallback(\n    (next: boolean, focus: FocusTarget = \"none\") => setOpenSub(next ? id : null, focus),\n    [setOpenSub, id],\n  );\n  const value = useMemo(\n    () => ({ id, contentId, open, focus: level.subFocus, triggerRef, panelRef, setOpen }),\n    [id, contentId, open, level.subFocus, setOpen],\n  );\n  return <SubContext.Provider value={value}>{children}</SubContext.Provider>;\n}\n\nexport interface DropdownMenuSubTriggerProps {\n  children: ReactNode;\n  disabled?: boolean;\n  inset?: boolean;\n  textValue?: string;\n  className?: string;\n}\n\nexport function DropdownMenuSubTrigger({ children, disabled, inset, textValue, className }: DropdownMenuSubTriggerProps) {\n  const level = useLevel(\"DropdownMenuSubTrigger\");\n  const sub = useSub(\"DropdownMenuSubTrigger\");\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  const clearTimer = useCallback(() => {\n    if (timer.current) clearTimeout(timer.current);\n    timer.current = null;\n  }, []);\n  useEffect(() => clearTimer, [clearTimer]);\n\n  return (\n    <ItemBase\n      disabled={disabled}\n      inset={inset}\n      textValue={textValue}\n      className={className}\n      subTrigger={{\n        id: sub.id,\n        open: sub.open,\n        controls: sub.contentId,\n        ref: sub.triggerRef,\n        onPointerMove: (event) => {\n          if (document.activeElement !== event.currentTarget) {\n            event.currentTarget.focus({ preventScroll: true });\n          }\n          if (disabled || sub.open || timer.current) return;\n          // Another row's submenu closes as soon as the pointer settles here.\n          if (level.openSub) level.setOpenSub(null);\n          timer.current = setTimeout(() => {\n            timer.current = null;\n            sub.setOpen(true, \"none\");\n          }, SUB_OPEN_DELAY);\n        },\n        onPointerLeave: (event) => {\n          clearTimer();\n          const panel = sub.panelRef.current;\n          if (!sub.open || !panel || event.pointerType === \"touch\") return;\n          // Leave a corridor from the pointer to the submenu's near edge, so a\n          // diagonal path across the rows below does not close it.\n          const rect = panel.getBoundingClientRect();\n          const right = rect.left >= event.clientX;\n          const edge = right ? rect.left : rect.right;\n          const back = right ? -5 : 5;\n          level.grace.current = {\n            polygon: [\n              { x: event.clientX + back, y: event.clientY },\n              { x: edge, y: rect.top },\n              { x: edge, y: rect.bottom },\n            ],\n            until: Date.now() + SUB_GRACE,\n          };\n        },\n        onKeyDown: (event) => {\n          if (disabled) return;\n          if (event.key === \"ArrowRight\" || event.key === \"Enter\" || event.key === \" \") {\n            event.preventDefault();\n            event.stopPropagation();\n            sub.setOpen(true, \"first\");\n            // Already open from a hover: the panel's focus effect will not run\n            // again, so hand focus in here.\n            if (sub.open) enabledItems(sub.panelRef.current)[0]?.focus();\n          }\n        },\n        onClick: () => {\n          if (!disabled) sub.setOpen(true, \"first\");\n        },\n      }}\n    >\n      {children}\n      <ChevronRight aria-hidden=\"true\" className=\"ml-auto size-4\" />\n    </ItemBase>\n  );\n}\n\nexport interface DropdownMenuSubContentProps {\n  children: ReactNode;\n  className?: string;\n  /** Gap between the menu's edge and the submenu in px. Default 6. */\n  sideOffset?: number;\n}\n\nexport function DropdownMenuSubContent({ children, className, sideOffset = 6 }: DropdownMenuSubContentProps) {\n  const root = useRoot(\"DropdownMenuSubContent\");\n  const level = useLevel(\"DropdownMenuSubContent\");\n  const sub = useSub(\"DropdownMenuSubContent\");\n\n  return (\n    <AnimatePresence>\n      {sub.open && (\n        <PresenceGate>\n          {({ isPresent, gate }) => (\n            <MenuPanel\n              id={sub.contentId}\n              anchorRef={sub.triggerRef}\n              panelRef={sub.panelRef}\n              side=\"right\"\n              align=\"start\"\n              sideOffset={sideOffset}\n              focus={sub.focus}\n              present={isPresent}\n              gate={gate}\n              labelledBy={sub.id}\n              onClose={() => root.setOpen(false)}\n              onPointerEnter={() => {\n                level.grace.current = null;\n              }}\n              onKeyDown={(event) => {\n                if (event.key !== \"ArrowLeft\") return false;\n                event.preventDefault();\n                sub.setOpen(false);\n                sub.triggerRef.current?.focus({ preventScroll: true });\n                return true;\n              }}\n              className={className}\n            >\n              {children}\n            </MenuPanel>\n          )}\n        </PresenceGate>\n      )}\n    </AnimatePresence>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Decoration                                                                 */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuLabelProps {\n  children: ReactNode;\n  inset?: boolean;\n  className?: string;\n}\n\nexport function DropdownMenuLabel({ children, inset, className }: DropdownMenuLabelProps) {\n  return (\n    <div className={cn(\"px-2 py-1.5 text-xs font-medium text-muted-foreground\", inset && \"pl-8\", className)}>\n      {children}\n    </div>\n  );\n}\n\nexport interface DropdownMenuSeparatorProps {\n  className?: string;\n}\n\nexport function DropdownMenuSeparator({ className }: DropdownMenuSeparatorProps) {\n  return <hr className={cn(\"-mx-1 my-1 h-px border-0 bg-border\", className)} />;\n}\n\nexport interface DropdownMenuShortcutProps {\n  children: ReactNode;\n  className?: string;\n}\n\nexport function DropdownMenuShortcut({ children, className }: DropdownMenuShortcutProps) {\n  return (\n    <span aria-hidden=\"true\" className={cn(\"ml-auto pl-4 text-xs tracking-wide text-muted-foreground\", className)}>\n      {children}\n    </span>\n  );\n}\n"},{"path":"components/motion/popover-position.ts","type":"registry:component","target":"@components/motion/popover-position.ts","content":"\"use client\";\n// beui.dev/components/motion/dropdown-menu\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"},{"path":"lib/ease.ts","type":"registry:lib","target":"@lib/ease.ts","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps — label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances — modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides — pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) — critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n"},{"path":"lib/hooks/use-dismiss.ts","type":"registry:hook","target":"@lib/hooks/use-dismiss.ts","content":"\"use client\";\n\nimport { type RefObject, useEffect } from \"react\";\n\n/**\n * What the dismissing gesture does to the control it landed on.\n *\n * `\"pass-through\"` is the platform norm (native popover light-dismiss): the\n * tap closes the overlay *and* activates whatever was under it. Use\n * `\"consume\"` where the open overlay sits over or beside controls that would\n * be costly to trigger by accident — the dismissal then swallows the\n * activation too, so the gesture only closes.\n */\nexport type DismissBehavior = \"pass-through\" | \"consume\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Return true for an outside target that should *not* dismiss. Must be stable. */\n  ignore?: (target: Element) => boolean;\n}\n\n/**\n * What every currently open dismiss scope counts as inside itself. A consumed\n * dismissal reads this to tell a stray gesture from one that belongs to an\n * overlay in front of it: overlays have no shared z-order to consult, but the\n * one the gesture landed in has said as much by registering it.\n */\nconst openScopes = new Set<(target: Element) => boolean>();\n\nfunction claimedByAnotherScope(\n  self: (target: Element) => boolean,\n  target: Element,\n) {\n  for (const scope of openScopes) {\n    if (scope !== self && scope(target)) return true;\n  }\n  return false;\n}\n\n// preventDefault on pointerdown does not suppress the click that follows, so\n// consuming a gesture means swallowing that click itself. The swallower\n// deliberately outlives the effect that installed it — the dismissal it\n// belongs to has already unmounted or re-rendered by the time the click lands.\n// It releases on that click, or on the next gesture if the pointer is dragged\n// away and no click ever arrives, so it can never eat a later one. A keydown\n// releases it too: a gesture that ends with neither a click nor a cancel would\n// otherwise leave it armed, and the click Enter synthesizes on some focused\n// control is not the one this dismissal was owed.\nfunction consumeActivation(source: Event) {\n  const swallow = (event: MouseEvent) => {\n    event.preventDefault();\n    event.stopPropagation();\n    release();\n  };\n  const restart = (event: Event) => {\n    if (event !== source) release();\n  };\n  const release = () => {\n    window.removeEventListener(\"click\", swallow, true);\n    window.removeEventListener(\"pointerdown\", restart, true);\n    window.removeEventListener(\"pointercancel\", restart, true);\n    window.removeEventListener(\"keydown\", release, true);\n  };\n  window.addEventListener(\"click\", swallow, true);\n  window.addEventListener(\"pointerdown\", restart, true);\n  window.addEventListener(\"pointercancel\", restart, true);\n  window.addEventListener(\"keydown\", release, true);\n}\n\n/**\n * Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`\n * for `ref` when what counts as inside isn't one element, and say so with\n * `ignore` instead.\n *\n * The pointerdown listener is capture-phase: a bubble-phase one is blinded by\n * any handler in between that stops propagation, and an overlay cannot know\n * what it is layered over. `onDismiss` and `ignore` must be stable (wrap in\n * useCallback) so the listeners aren't re-bound every render while open.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: () => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Element) =>\n      Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));\n    const onKey = (event: KeyboardEvent) => {\n      if (dismissOnEscape && event.key === \"Escape\") onDismiss();\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // Outside this overlay, but inside one that is also open: the gesture is\n      // that overlay's to answer, and swallowing its click from behind would\n      // cost the user the control they actually aimed at.\n      if (behavior === \"consume\" && !claimedByAnotherScope(inside, target)) {\n        consumeActivation(event);\n      }\n      onDismiss();\n    };\n    openScopes.add(inside);\n    window.addEventListener(\"keydown\", onKey);\n    window.addEventListener(\"pointerdown\", onPointer, true);\n    return () => {\n      openScopes.delete(inside);\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n    };\n  }, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);\n}\n"},{"path":"lib/presence-gate.tsx","type":"registry:lib","target":"@lib/presence-gate.tsx","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport type { ReactNode } from \"react\";\n\nexport interface PresenceGateRenderProps {\n  /**\n   * False from the render that starts the exit animation onward. An overlay\n   * kept in the tree by `AnimatePresence` is still the topmost thing on the\n   * page, so anything it decides from `open` alone stays true for the whole\n   * exit — this is the boolean that already knows the overlay is leaving.\n   */\n  isPresent: boolean;\n  /**\n   * Spread onto every layer that takes pointer events while the overlay is\n   * open. Interaction releases in the same commit that starts the exit while\n   * the visual exit keeps playing: pointer events stop landing, and `inert`\n   * drops the subtree from focus order, from tab order and from the\n   * accessibility tree — an exiting dialog is not a dialog you can still type\n   * into. A layer that never takes pointer events (a wrapper that only centres\n   * the panel) takes `inert={!isPresent}` alone, so its own\n   * `pointer-events-none` is not overwritten.\n   */\n  gate: {\n    inert: boolean;\n    style: { pointerEvents: \"auto\" | \"none\" };\n  };\n}\n\nexport interface PresenceGateProps {\n  children: (props: PresenceGateRenderProps) => ReactNode;\n}\n\n/**\n * Reads the presence of the subtree it renders and hands it down.\n *\n * `useIsPresent` only answers inside the `AnimatePresence` subtree, and the\n * components that own an overlay render the `AnimatePresence` themselves, so\n * the boolean has to be read one component further down: this is that\n * component, and the render prop is how it reaches the layers.\n */\nexport function PresenceGate({ children }: PresenceGateProps) {\n  const isPresent = useIsPresent();\n\n  return children({\n    isPresent,\n    gate: {\n      inert: !isPresent,\n      style: { pointerEvents: isPresent ? \"auto\" : \"none\" },\n    },\n  });\n}\n"},{"path":"lib/utils.ts","type":"registry:lib","target":"@lib/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"}]}