{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"dropdown-menu","type":"registry:component","title":"Dropdown Menu","description":"Composable WAI-ARIA dropdown menu that springs open with a scale and fade from the trigger side, with a gliding active-row highlight, checkbox and radio items, icons and shortcuts, a destructive variant, hover-intent submenus, typeahead, full arrow/Home/End/Escape keyboard support and viewport-aware flipping.","author":"kara <ztzyrant@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// karaui.kamisama-v0.my.id/components/motion/dropdown-menu\n\nimport { Check, ChevronRight } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type MutableRefObject,\n  type ReactElement,\n  type FocusEvent as ReactFocusEvent,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type MouseEvent as ReactMouseEvent,\n  type ReactNode,\n  type PointerEvent as ReactPointerEvent,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n  type PlacementAlign,\n  type PlacementSide,\n  resolvePlacement,\n} from \"@/components/motion/anchored-placement\";\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 { cn } from \"@/lib/utils\";\n\n/* -------------------------------------------------------------------------- */\n/*                                   Levels                                   */\n/* -------------------------------------------------------------------------- */\n\n/** Where focus lands when a panel opens. */\ntype FocusIntent = \"first\" | \"last\" | \"content\" | \"none\";\n\n// Hovering a sub trigger waits this long before opening, so a pointer just\n// passing over the row on its way down the list doesn't flash a submenu.\nconst SUB_OPEN_DELAY = 100;\n// Leaving the sub trigger (or hovering a sibling) closes the submenu only\n// after this grace, so a diagonal move toward the submenu that clips a\n// neighbouring row doesn't snap it shut.\nconst SUB_CLOSE_DELAY = 220;\nconst TYPEAHEAD_RESET = 500;\n\n/**\n * One open panel: the root menu or a submenu. Items, the active-row\n * highlight and keyboard navigation all read the nearest level, so a submenu\n * is the same machinery one step down.\n */\ninterface MenuLevel {\n  /** Shared by every panel and the trigger of one menu tree (dismissal scope). */\n  rootId: string;\n  /** Scope for this panel's layoutId highlight. */\n  levelId: string;\n  open: boolean;\n  isSub: boolean;\n  triggerId: string;\n  contentId: string;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  contentRef: MutableRefObject<HTMLDivElement | null>;\n  focusIntent: MutableRefObject<FocusIntent>;\n  activeId: string | null;\n  setActiveId: (id: string | null) => void;\n  /** Id of the child submenu currently open from this panel. */\n  openSub: string | null;\n  setOpenSub: (id: string | null) => void;\n  scheduleSubClose: () => void;\n  cancelSubClose: () => void;\n  /** Close this panel only (root: the whole menu). */\n  close: (restoreFocus: boolean) => void;\n  /** Close the whole menu tree. */\n  closeAll: (restoreFocus: boolean) => void;\n  /** Open the root menu (used by the trigger). */\n  openRoot: () => void;\n  reduce: boolean;\n}\n\nconst MenuLevelContext = createContext<MenuLevel | null>(null);\n\nfunction useMenuLevel(component: string) {\n  const level = useContext(MenuLevelContext);\n  if (!level) throw new Error(`${component} must be used within <DropdownMenu>`);\n  return level;\n}\n\n/** Per-panel state shared by the root and every submenu. */\nfunction useLevelCore(open: boolean) {\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [openSub, setOpenSubState] = useState<string | null>(null);\n  const subCloseTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  const cancelSubClose = useCallback(() => {\n    if (subCloseTimer.current) clearTimeout(subCloseTimer.current);\n    subCloseTimer.current = null;\n  }, []);\n\n  const setOpenSub = useCallback(\n    (id: string | null) => {\n      cancelSubClose();\n      setOpenSubState(id);\n    },\n    [cancelSubClose],\n  );\n\n  const scheduleSubClose = useCallback(() => {\n    cancelSubClose();\n    subCloseTimer.current = setTimeout(() => {\n      subCloseTimer.current = null;\n      setOpenSubState(null);\n    }, SUB_CLOSE_DELAY);\n  }, [cancelSubClose]);\n\n  // Reset the highlight when the panel opens, not when it closes: removing\n  // the layoutId highlight while the panel is still animating out leaves\n  // motion waiting on it forever, so the closed panel never unmounts.\n  useEffect(() => {\n    if (open) {\n      setActiveId(null);\n      return;\n    }\n    cancelSubClose();\n    setOpenSubState(null);\n  }, [open, cancelSubClose]);\n\n  useEffect(() => cancelSubClose, [cancelSubClose]);\n\n  return useMemo(\n    () => ({\n      activeId,\n      setActiveId,\n      openSub,\n      setOpenSub,\n      scheduleSubClose,\n      cancelSubClose,\n    }),\n    [activeId, openSub, setOpenSub, scheduleSubClose, cancelSubClose],\n  );\n}\n\nfunction getItems(container: HTMLElement | null) {\n  if (!container) return [];\n  return Array.from(\n    container.querySelectorAll<HTMLElement>(\n      '[data-dropdown-menu-item]:not([data-disabled=\"true\"])',\n    ),\n  );\n}\n\nfunction focusByIntent(container: HTMLElement | null, intent: FocusIntent) {\n  if (!container || intent === \"none\") return;\n  const items = getItems(container);\n  const target =\n    intent === \"first\"\n      ? items[0]\n      : intent === \"last\"\n        ? items[items.length - 1]\n        : container;\n  (target ?? container).focus({ preventScroll: true });\n}\n\nfunction assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) (ref as MutableRefObject<T | null>).current = value;\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    Root                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuProps {\n  children: ReactNode;\n  /** Controlled open state. */\n  open?: boolean;\n  /** Uncontrolled initial open state. */\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  className?: string;\n}\n\n/**\n * Composable dropdown menu following the WAI-ARIA menu button pattern. The\n * panel scales out of the trigger side, an active-row highlight glides\n * between items, and submenus open on hover intent or ArrowRight.\n */\nexport function DropdownMenu({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  className,\n}: DropdownMenuProps) {\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n  const baseId = useId();\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const focusIntent = useRef<FocusIntent>(\"content\");\n  const reduce = useReducedMotion() ?? false;\n  const core = useLevelCore(open);\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n\n  const closeAll = useCallback(\n    (restoreFocus: boolean) => {\n      setOpen(false);\n      if (restoreFocus) triggerRef.current?.focus({ preventScroll: true });\n    },\n    [setOpen],\n  );\n\n  const dismiss = useCallback(() => setOpen(false), [setOpen]);\n  const openRoot = useCallback(() => setOpen(true), [setOpen]);\n  const insideTree = useCallback(\n    (target: Element) =>\n      Boolean(target.closest(`[data-dropdown-menu=\"${baseId}\"]`)),\n    [baseId],\n  );\n  // Escape is handled by the focused panel, which knows whether it is a\n  // submenu (close one level) or the root (close and refocus the trigger).\n  useDismiss(open, dismiss, null, { escape: false, ignore: insideTree });\n\n  // Focus moves into the panel on open: the first/last item for keyboard\n  // opens, the panel itself for pointer opens so arrows work immediately.\n  useEffect(() => {\n    if (!open) return;\n    const frame = requestAnimationFrame(() =>\n      focusByIntent(contentRef.current, focusIntent.current),\n    );\n    return () => cancelAnimationFrame(frame);\n  }, [open]);\n\n  const level = useMemo<MenuLevel>(\n    () => ({\n      rootId: baseId,\n      levelId: `${baseId}-root`,\n      open,\n      isSub: false,\n      triggerId: `${baseId}-trigger`,\n      contentId: `${baseId}-content`,\n      triggerRef,\n      contentRef,\n      focusIntent,\n      ...core,\n      close: closeAll,\n      closeAll,\n      openRoot,\n      reduce,\n    }),\n    [baseId, open, core, closeAll, openRoot, reduce],\n  );\n\n  return (\n    <MenuLevelContext.Provider value={level}>\n      <div className={cn(\"relative inline-flex\", className)}>{children}</div>\n    </MenuLevelContext.Provider>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Trigger                                   */\n/* -------------------------------------------------------------------------- */\n\ntype TriggerChildProps = React.HTMLAttributes<HTMLElement> & {\n  ref?: Ref<HTMLElement>;\n  [key: `data-${string}`]: string | undefined;\n};\n\nexport interface DropdownMenuTriggerProps {\n  /** A single element, normally a `<button>`. Its own handlers still run. */\n  children: ReactElement<TriggerChildProps>;\n  className?: string;\n}\n\nexport function DropdownMenuTrigger({\n  children,\n  className,\n}: DropdownMenuTriggerProps) {\n  const level = useMenuLevel(\"DropdownMenuTrigger\");\n  if (!isValidElement(children)) {\n    throw new Error(\"<DropdownMenuTrigger> requires a single React element\");\n  }\n  const childProps = children.props;\n  const childRef = childProps.ref;\n\n  const openWith = (intent: FocusIntent) => {\n    level.focusIntent.current = intent;\n    if (!level.open) {\n      level.openRoot();\n    } else {\n      focusByIntent(level.contentRef.current, intent);\n    }\n  };\n\n  return cloneElement(children, {\n    ref: (node: HTMLElement | null) => {\n      level.triggerRef.current = node;\n      assignRef(childRef, node);\n    },\n    id: level.triggerId,\n    \"aria-haspopup\": \"menu\",\n    \"aria-expanded\": level.open,\n    \"aria-controls\": level.open ? level.contentId : undefined,\n    \"data-state\": level.open ? \"open\" : \"closed\",\n    \"data-dropdown-menu\": level.rootId,\n    className: cn(childProps.className, className),\n    onClick: (event: ReactMouseEvent<HTMLElement>) => {\n      childProps.onClick?.(event);\n      if (event.defaultPrevented) return;\n      if (level.open) {\n        level.closeAll(false);\n        return;\n      }\n      // `detail` is 0 for a click synthesized by the keyboard.\n      openWith(event.detail === 0 ? \"first\" : \"content\");\n    },\n    onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {\n      childProps.onKeyDown?.(event);\n      if (event.defaultPrevented) return;\n      if (\n        event.key === \"ArrowDown\" ||\n        event.key === \"Enter\" ||\n        event.key === \" \"\n      ) {\n        event.preventDefault();\n        openWith(\"first\");\n      } else if (event.key === \"ArrowUp\") {\n        event.preventDefault();\n        openWith(\"last\");\n      }\n    },\n  });\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Panel                                    */\n/* -------------------------------------------------------------------------- */\n\ninterface MenuPanelProps {\n  level: MenuLevel;\n  children: ReactNode;\n  side: PlacementSide;\n  align: PlacementAlign;\n  sideOffset: number;\n  alignOffset: number;\n  className?: string;\n  ariaLabel?: string;\n  onPanelEnter?: () => void;\n}\n\nfunction MenuPanel({\n  level,\n  children,\n  side,\n  align,\n  sideOffset,\n  alignOffset,\n  className,\n  ariaLabel,\n  onPanelEnter,\n}: MenuPanelProps) {\n  const [portalReady, setPortalReady] = useState(false);\n  const typeahead = useRef(\"\");\n  const typeaheadTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const layout = usePopoverPortalPosition(\n    level.triggerRef,\n    level.contentRef,\n    portalReady && level.open,\n  );\n\n  useEffect(() => setPortalReady(true), []);\n  useEffect(\n    () => () => {\n      if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);\n    },\n    [],\n  );\n\n  const moveFocus = (direction: 1 | -1) => {\n    const items = getItems(level.contentRef.current);\n    if (items.length === 0) return;\n    const current = items.indexOf(document.activeElement as HTMLElement);\n    const next =\n      current < 0\n        ? direction === 1\n          ? 0\n          : items.length - 1\n        : (current + direction + items.length) % items.length;\n    items[next]?.focus();\n  };\n\n  const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n    // React bubbles events through portals: a submenu's keys would reach its\n    // parent panel too. Only answer keys pressed inside this panel's DOM.\n    if (!event.currentTarget.contains(event.target as Node)) return;\n    if (event.defaultPrevented) return;\n    const { key } = event;\n\n    if (key === \"Escape\") {\n      event.preventDefault();\n      level.close(true);\n      return;\n    }\n    if (key === \"ArrowLeft\" && level.isSub) {\n      event.preventDefault();\n      level.close(true);\n      return;\n    }\n    if (key === \"Tab\") {\n      event.preventDefault();\n      level.closeAll(true);\n      return;\n    }\n    if (key === \"ArrowDown\" || key === \"ArrowUp\") {\n      event.preventDefault();\n      moveFocus(key === \"ArrowDown\" ? 1 : -1);\n      return;\n    }\n    if (key === \"Home\" || key === \"End\") {\n      event.preventDefault();\n      const items = getItems(level.contentRef.current);\n      items[key === \"Home\" ? 0 : items.length - 1]?.focus();\n      return;\n    }\n    const printable =\n      key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;\n    // A leading space is activation, not a search character.\n    if (!printable || (key === \" \" && typeahead.current === \"\")) return;\n    event.preventDefault();\n    typeahead.current += key.toLocaleLowerCase();\n    if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);\n    typeaheadTimer.current = setTimeout(() => {\n      typeahead.current = \"\";\n    }, TYPEAHEAD_RESET);\n    const items = getItems(level.contentRef.current);\n    const start = items.indexOf(document.activeElement as HTMLElement);\n    // Search from the row after the current one so repeating a letter cycles.\n    const ordered =\n      typeahead.current.length === 1 && start >= 0\n        ? [...items.slice(start + 1), ...items.slice(0, start + 1)]\n        : items;\n    const match = ordered.find((item) =>\n      (item.dataset.label ?? item.textContent ?? \"\")\n        .trim()\n        .toLocaleLowerCase()\n        .startsWith(typeahead.current),\n    );\n    match?.focus();\n  };\n\n  if (!portalReady) return null;\n\n  const placement = layout\n    ? resolvePlacement(layout, { side, align, sideOffset, alignOffset })\n    : null;\n\n  return createPortal(\n    <AnimatePresence>\n      {level.open ? (\n        <motion.div\n          ref={level.contentRef}\n          id={level.contentId}\n          role=\"menu\"\n          aria-label={ariaLabel}\n          aria-labelledby={ariaLabel ? undefined : level.triggerId}\n          aria-orientation=\"vertical\"\n          tabIndex={-1}\n          data-dropdown-menu={level.rootId}\n          data-side={placement?.side ?? side}\n          initial={level.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.94 }}\n          animate={{ opacity: 1, scale: 1 }}\n          // pointerEvents flips at the start of the exit, so a closing panel\n          // can never be hovered or clicked through.\n          exit={\n            level.reduce\n              ? { opacity: 0, pointerEvents: \"none\", transition: { duration: 0.1 } }\n              : {\n                  opacity: 0,\n                  scale: 0.96,\n                  pointerEvents: \"none\",\n                  transition: { duration: 0.12, ease: EASE_OUT },\n                }\n          }\n          transition={\n            level.reduce\n              ? { duration: 0.12, ease: EASE_OUT }\n              : { ...SPRING_PANEL, opacity: { duration: 0.16, ease: EASE_OUT } }\n          }\n          style={{\n            left: placement?.left ?? 0,\n            top: placement?.top ?? 0,\n            // The panel grows out of the trigger's side — transform-origin on\n            // an HTML element is safe for motion's scale.\n            transformOrigin: placement?.origin ?? \"50% 0%\",\n            visibility: placement ? \"visible\" : \"hidden\",\n          }}\n          onKeyDown={onKeyDown}\n          onFocus={(event: ReactFocusEvent<HTMLDivElement>) => {\n            if (event.target === event.currentTarget) level.setActiveId(null);\n            else onPanelEnter?.();\n          }}\n          onPointerEnter={onPanelEnter}\n          className={cn(\n            \"fixed z-[100] min-w-52 rounded-xl border border-border bg-card p-1.5 text-foreground shadow-[0_18px_40px_-12px_rgba(0,0,0,0.28)] outline-none\",\n            className,\n          )}\n        >\n          {children}\n        </motion.div>\n      ) : null}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n\nexport interface DropdownMenuContentProps {\n  children: ReactNode;\n  /** Preferred side; flips when the viewport lacks room. Default \"bottom\". */\n  side?: \"bottom\" | \"top\";\n  /** Alignment against the trigger. Default \"start\". */\n  align?: PlacementAlign;\n  /** Gap between trigger and panel, in px. Default 6. */\n  sideOffset?: number;\n  alignOffset?: number;\n  /** Accessible name; defaults to the trigger's text via aria-labelledby. */\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuContent({\n  children,\n  side = \"bottom\",\n  align = \"start\",\n  sideOffset = 6,\n  alignOffset = 0,\n  ariaLabel,\n  className,\n}: DropdownMenuContentProps) {\n  const level = useMenuLevel(\"DropdownMenuContent\");\n  return (\n    <MenuPanel\n      level={level}\n      side={side}\n      align={align}\n      sideOffset={sideOffset}\n      alignOffset={alignOffset}\n      ariaLabel={ariaLabel}\n      className={className}\n    >\n      {children}\n    </MenuPanel>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Items                                    */\n/* -------------------------------------------------------------------------- */\n\ntype ItemVariant = \"default\" | \"destructive\";\n\ninterface ItemBaseProps {\n  children: ReactNode;\n  itemId?: string;\n  role?: \"menuitem\" | \"menuitemcheckbox\" | \"menuitemradio\";\n  ariaChecked?: boolean;\n  disabled?: boolean;\n  variant?: ItemVariant;\n  inset?: boolean;\n  textValue?: string;\n  className?: string;\n  closeOnSelect: boolean;\n  onActivate?: (event: ReactMouseEvent<HTMLButtonElement>) => void;\n  isSubTrigger?: boolean;\n  extraProps?: React.ButtonHTMLAttributes<HTMLButtonElement> & {\n    ref?: Ref<HTMLButtonElement>;\n    [key: `data-${string}`]: string | undefined;\n  };\n}\n\nfunction ItemBase({\n  children,\n  itemId,\n  role = \"menuitem\",\n  ariaChecked,\n  disabled = false,\n  variant = \"default\",\n  inset = false,\n  textValue,\n  className,\n  closeOnSelect,\n  onActivate,\n  isSubTrigger = false,\n  extraProps,\n}: ItemBaseProps) {\n  const level = useMenuLevel(\"DropdownMenuItem\");\n  const autoId = useId();\n  const id = itemId ?? autoId;\n  const highlighted = level.activeId === id;\n  const checkedProps =\n    role === \"menuitem\" ? {} : { \"aria-checked\": ariaChecked ?? false };\n  const { onPointerEnter, onPointerLeave, onKeyDown, ref, ...rest } =\n    extraProps ?? {};\n\n  return (\n    <button\n      {...rest}\n      ref={ref}\n      type=\"button\"\n      id={id}\n      role={role}\n      {...checkedProps}\n      disabled={disabled}\n      tabIndex={-1}\n      data-dropdown-menu-item=\"\"\n      data-disabled={disabled ? \"true\" : undefined}\n      data-highlighted={highlighted ? \"\" : undefined}\n      data-label={textValue}\n      onFocus={() => level.setActiveId(id)}\n      onPointerEnter={(event: ReactPointerEvent<HTMLButtonElement>) => {\n        onPointerEnter?.(event);\n        if (!isSubTrigger && event.pointerType !== \"touch\") {\n          level.scheduleSubClose();\n        }\n      }}\n      onPointerMove={(event: ReactPointerEvent<HTMLButtonElement>) => {\n        if (disabled || event.pointerType === \"touch\") return;\n        if (document.activeElement !== event.currentTarget) {\n          event.currentTarget.focus({ preventScroll: true });\n        }\n      }}\n      onPointerLeave={(event: ReactPointerEvent<HTMLButtonElement>) => {\n        onPointerLeave?.(event);\n        if (event.pointerType === \"touch\" || isSubTrigger) return;\n        // Clearing focus to the panel drops the highlight when the pointer\n        // leaves the rows, the way native menus behave.\n        if (document.activeElement === event.currentTarget) {\n          level.contentRef.current?.focus({ preventScroll: true });\n        }\n      }}\n      onKeyDown={onKeyDown}\n      onClick={(event) => {\n        if (disabled) return;\n        onActivate?.(event);\n        if (closeOnSelect && !event.defaultPrevented) level.closeAll(true);\n      }}\n      className={cn(\n        \"relative isolate flex w-full select-none items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left text-[13px] outline-none\",\n        \"disabled:pointer-events-none disabled:opacity-40\",\n        \"[&_svg]:size-4 [&_svg]:shrink-0\",\n        inset && \"pl-8\",\n        variant === \"destructive\"\n          ? \"text-destructive [&_svg]:text-destructive\"\n          : \"text-foreground [&_svg]:text-muted-foreground\",\n        className,\n      )}\n    >\n      {/* Its own presence boundary: a layoutId element registers with the\n          nearest AnimatePresence, and the panel's exit would otherwise wait\n          on the highlight's layout animation and never unmount. */}\n      <AnimatePresence initial={false}>\n        {highlighted ? (\n          <motion.span\n            aria-hidden=\"true\"\n            layoutId={`${level.levelId}-highlight`}\n            className={cn(\n              \"absolute inset-0 -z-10 rounded-lg\",\n              variant === \"destructive\"\n                ? \"bg-destructive/10\"\n                : \"bg-foreground/[0.07]\",\n            )}\n            transition={level.reduce ? { duration: 0 } : SPRING_LAYOUT}\n          />\n        ) : null}\n      </AnimatePresence>\n      {children}\n    </button>\n  );\n}\n\nfunction Shortcut({ children }: { children: ReactNode }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"ml-auto pl-4 font-mono text-[11px] tracking-wide text-muted-foreground\"\n    >\n      {children}\n    </span>\n  );\n}\n\nexport interface DropdownMenuItemProps {\n  children: ReactNode;\n  /** Leading icon (sized to 16px). */\n  icon?: ReactNode;\n  /** Trailing shortcut hint, e.g. \"⌘K\" or a `KbdCombo`. Decorative. */\n  shortcut?: ReactNode;\n  variant?: ItemVariant;\n  disabled?: boolean;\n  /** Indent to line up with checkbox/radio rows. */\n  inset?: boolean;\n  /** Text used by typeahead when children aren't plain text. */\n  textValue?: string;\n  /** Call `event.preventDefault()` to keep the menu open. */\n  onSelect?: (event: ReactMouseEvent<HTMLButtonElement>) => void;\n  /** Default true. */\n  closeOnSelect?: boolean;\n  className?: string;\n}\n\nexport function DropdownMenuItem({\n  children,\n  icon,\n  shortcut,\n  onSelect,\n  closeOnSelect = true,\n  ...props\n}: DropdownMenuItemProps) {\n  return (\n    <ItemBase {...props} closeOnSelect={closeOnSelect} onActivate={onSelect}>\n      {icon}\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      {shortcut ? <Shortcut>{shortcut}</Shortcut> : null}\n    </ItemBase>\n  );\n}\n\nfunction Indicator({\n  checked,\n  kind,\n  reduce,\n}: {\n  checked: boolean;\n  kind: \"check\" | \"dot\";\n  reduce: boolean;\n}) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"absolute left-2.5 flex size-4 items-center justify-center\"\n    >\n      <AnimatePresence initial={false}>\n        {checked ? (\n          <motion.span\n            key={kind}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n            animate={{ opacity: 1, scale: 1 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n            transition={reduce ? { duration: 0.08 } : SPRING_PANEL}\n            className=\"flex items-center justify-center text-foreground\"\n          >\n            {kind === \"check\" ? (\n              <Check className=\"size-3.5! text-foreground!\" strokeWidth={2.6} />\n            ) : (\n              <span className=\"size-1.5 rounded-full bg-current\" />\n            )}\n          </motion.span>\n        ) : null}\n      </AnimatePresence>\n    </span>\n  );\n}\n\nexport interface DropdownMenuCheckboxItemProps\n  extends Omit<DropdownMenuItemProps, \"onSelect\" | \"inset\" | \"icon\"> {\n  checked?: boolean;\n  defaultChecked?: boolean;\n  onCheckedChange?: (checked: boolean) => void;\n}\n\n/** A toggle row. Stays open on select by default so several can be flipped. */\nexport function DropdownMenuCheckboxItem({\n  children,\n  checked: controlledChecked,\n  defaultChecked = false,\n  onCheckedChange,\n  shortcut,\n  closeOnSelect = false,\n  ...props\n}: DropdownMenuCheckboxItemProps) {\n  const level = useMenuLevel(\"DropdownMenuCheckboxItem\");\n  const [internal, setInternal] = useState(defaultChecked);\n  const checked = controlledChecked ?? internal;\n  return (\n    <ItemBase\n      {...props}\n      inset\n      role=\"menuitemcheckbox\"\n      ariaChecked={checked}\n      closeOnSelect={closeOnSelect}\n      onActivate={() => {\n        if (controlledChecked === undefined) setInternal(!checked);\n        onCheckedChange?.(!checked);\n      }}\n    >\n      <Indicator checked={checked} kind=\"check\" reduce={level.reduce} />\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      {shortcut ? <Shortcut>{shortcut}</Shortcut> : null}\n    </ItemBase>\n  );\n}\n\ninterface RadioGroupContextValue {\n  value: string | undefined;\n  select: (value: string) => void;\n}\n\nconst RadioGroupContext = createContext<RadioGroupContextValue | null>(null);\n\nexport interface DropdownMenuRadioGroupProps {\n  children: ReactNode;\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Accessible name for the group. */\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuRadioGroup({\n  children,\n  value: controlledValue,\n  defaultValue,\n  onValueChange,\n  ariaLabel,\n  className,\n}: DropdownMenuRadioGroupProps) {\n  const [internal, setInternal] = useState(defaultValue);\n  const value = controlledValue ?? internal;\n  const ctx = useMemo<RadioGroupContextValue>(\n    () => ({\n      value,\n      select: (next) => {\n        if (controlledValue === undefined) setInternal(next);\n        onValueChange?.(next);\n      },\n    }),\n    [value, controlledValue, onValueChange],\n  );\n  return (\n    <RadioGroupContext.Provider value={ctx}>\n      <fieldset\n        aria-label={ariaLabel}\n        className={cn(\"m-0 min-w-0 border-0 p-0\", className)}\n      >\n        {children}\n      </fieldset>\n    </RadioGroupContext.Provider>\n  );\n}\n\nexport interface DropdownMenuRadioItemProps\n  extends Omit<DropdownMenuItemProps, \"onSelect\" | \"inset\" | \"icon\"> {\n  value: string;\n}\n\nexport function DropdownMenuRadioItem({\n  children,\n  value,\n  shortcut,\n  closeOnSelect = false,\n  ...props\n}: DropdownMenuRadioItemProps) {\n  const level = useMenuLevel(\"DropdownMenuRadioItem\");\n  const group = useContext(RadioGroupContext);\n  if (!group) {\n    throw new Error(\n      \"DropdownMenuRadioItem must be used within <DropdownMenuRadioGroup>\",\n    );\n  }\n  const checked = group.value === value;\n  return (\n    <ItemBase\n      {...props}\n      inset\n      role=\"menuitemradio\"\n      ariaChecked={checked}\n      closeOnSelect={closeOnSelect}\n      onActivate={() => group.select(value)}\n    >\n      <Indicator checked={checked} kind=\"dot\" reduce={level.reduce} />\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      {shortcut ? <Shortcut>{shortcut}</Shortcut> : null}\n    </ItemBase>\n  );\n}\n\nexport interface DropdownMenuLabelProps {\n  children: ReactNode;\n  inset?: boolean;\n  className?: string;\n}\n\nexport function DropdownMenuLabel({\n  children,\n  inset = false,\n  className,\n}: DropdownMenuLabelProps) {\n  return (\n    <div\n      className={cn(\n        \"px-2.5 pb-1 pt-1.5 text-[11px] font-medium text-muted-foreground\",\n        inset && \"pl-8\",\n        className,\n      )}\n    >\n      {children}\n    </div>\n  );\n}\n\nexport interface DropdownMenuGroupProps {\n  children: ReactNode;\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuGroup({\n  children,\n  ariaLabel,\n  className,\n}: DropdownMenuGroupProps) {\n  return (\n    <fieldset\n        aria-label={ariaLabel}\n        className={cn(\"m-0 min-w-0 border-0 p-0\", className)}\n      >\n      {children}\n    </fieldset>\n  );\n}\n\nexport function DropdownMenuSeparator({ className }: { className?: string }) {\n  return <hr className={cn(\"-mx-1.5 my-1.5 h-px border-0 bg-border\", className)} />;\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Submenus                                  */\n/* -------------------------------------------------------------------------- */\n\ninterface SubContextValue {\n  level: MenuLevel;\n  parent: MenuLevel;\n  triggerItemId: string;\n  openTimer: MutableRefObject<ReturnType<typeof setTimeout> | null>;\n  openWith: (intent: FocusIntent) => void;\n}\n\nconst SubContext = createContext<SubContextValue | null>(null);\n\nfunction useSub(component: string) {\n  const sub = useContext(SubContext);\n  if (!sub) throw new Error(`${component} must be used within <DropdownMenuSub>`);\n  return sub;\n}\n\nexport interface DropdownMenuSubProps {\n  children: ReactNode;\n}\n\n/** A nested menu opened from a `DropdownMenuSubTrigger` row. */\nexport function DropdownMenuSub({ children }: DropdownMenuSubProps) {\n  const parent = useMenuLevel(\"DropdownMenuSub\");\n  const subId = useId();\n  const open = parent.open && parent.openSub === subId;\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const focusIntent = useRef<FocusIntent>(\"none\");\n  const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const core = useLevelCore(open);\n  const triggerItemId = `${subId}-trigger`;\n\n  useEffect(\n    () => () => {\n      if (openTimer.current) clearTimeout(openTimer.current);\n    },\n    [],\n  );\n\n  // Open submenus take focus only when asked to (keyboard); a hover open\n  // leaves it on the trigger row.\n  useEffect(() => {\n    if (!open) return;\n    const frame = requestAnimationFrame(() =>\n      focusByIntent(contentRef.current, focusIntent.current),\n    );\n    return () => cancelAnimationFrame(frame);\n  }, [open]);\n\n  const { setOpenSub } = parent;\n  const close = useCallback(\n    (restoreFocus: boolean) => {\n      setOpenSub(null);\n      if (restoreFocus) triggerRef.current?.focus({ preventScroll: true });\n    },\n    [setOpenSub],\n  );\n\n  const openWith = useCallback(\n    (intent: FocusIntent) => {\n      if (openTimer.current) clearTimeout(openTimer.current);\n      openTimer.current = null;\n      focusIntent.current = intent;\n      if (open) focusByIntent(contentRef.current, intent);\n      else setOpenSub(subId);\n    },\n    [open, setOpenSub, subId],\n  );\n\n  const level = useMemo<MenuLevel>(\n    () => ({\n      rootId: parent.rootId,\n      levelId: `${subId}-level`,\n      open,\n      isSub: true,\n      triggerId: triggerItemId,\n      contentId: `${subId}-content`,\n      triggerRef,\n      contentRef,\n      focusIntent,\n      ...core,\n      close,\n      closeAll: parent.closeAll,\n      openRoot: parent.openRoot,\n      reduce: parent.reduce,\n    }),\n    [\n      parent.rootId,\n      parent.closeAll,\n      parent.openRoot,\n      parent.reduce,\n      subId,\n      open,\n      triggerItemId,\n      core,\n      close,\n    ],\n  );\n\n  const ctx = useMemo<SubContextValue>(\n    () => ({ level, parent, triggerItemId, openTimer, openWith }),\n    [level, parent, triggerItemId, openWith],\n  );\n\n  return <SubContext.Provider value={ctx}>{children}</SubContext.Provider>;\n}\n\nexport interface DropdownMenuSubTriggerProps {\n  children: ReactNode;\n  icon?: ReactNode;\n  disabled?: boolean;\n  inset?: boolean;\n  textValue?: string;\n  className?: string;\n}\n\nexport function DropdownMenuSubTrigger({\n  children,\n  icon,\n  ...props\n}: DropdownMenuSubTriggerProps) {\n  const { level, parent, triggerItemId, openTimer, openWith } = useSub(\n    \"DropdownMenuSubTrigger\",\n  );\n\n  const clearOpenTimer = () => {\n    if (openTimer.current) clearTimeout(openTimer.current);\n    openTimer.current = null;\n  };\n\n  return (\n    <ItemBase\n      {...props}\n      itemId={triggerItemId}\n      isSubTrigger\n      closeOnSelect={false}\n      onActivate={(event) => openWith(event.detail === 0 ? \"first\" : \"none\")}\n      extraProps={{\n        ref: (node: HTMLButtonElement | null) => {\n          level.triggerRef.current = node;\n        },\n        \"aria-haspopup\": \"menu\",\n        \"aria-expanded\": level.open,\n        \"aria-controls\": level.open ? level.contentId : undefined,\n        \"data-state\": level.open ? \"open\" : \"closed\",\n        onPointerEnter: (event) => {\n          if (event.pointerType === \"touch\" || props.disabled) return;\n          parent.cancelSubClose();\n          if (level.open) return;\n          clearOpenTimer();\n          openTimer.current = setTimeout(() => {\n            openTimer.current = null;\n            openWith(\"none\");\n          }, SUB_OPEN_DELAY);\n        },\n        onPointerLeave: (event) => {\n          if (event.pointerType === \"touch\") return;\n          clearOpenTimer();\n          parent.scheduleSubClose();\n        },\n        onKeyDown: (event) => {\n          if (event.key === \"ArrowRight\") {\n            event.preventDefault();\n            openWith(\"first\");\n          }\n        },\n      }}\n    >\n      {icon}\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      <ChevronRight\n        aria-hidden=\"true\"\n        className=\"-mr-1 ml-auto size-3.5! text-muted-foreground\"\n      />\n    </ItemBase>\n  );\n}\n\nexport interface DropdownMenuSubContentProps {\n  children: ReactNode;\n  /** Preferred side; flips when the viewport lacks room. Default \"right\". */\n  side?: \"right\" | \"left\";\n  /** Gap from the parent panel, in px. Default 8. */\n  sideOffset?: number;\n  /** Shift so the first row lines up with the trigger row. Default -7. */\n  alignOffset?: number;\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuSubContent({\n  children,\n  side = \"right\",\n  sideOffset = 8,\n  alignOffset = -7,\n  ariaLabel,\n  className,\n}: DropdownMenuSubContentProps) {\n  const { level, parent, triggerItemId } = useSub(\"DropdownMenuSubContent\");\n  const { cancelSubClose, setActiveId } = parent;\n  // While the pointer or focus is in the submenu, its trigger row keeps the\n  // parent's highlight and the pending close is called off.\n  const onPanelEnter = useCallback(() => {\n    cancelSubClose();\n    setActiveId(triggerItemId);\n  }, [cancelSubClose, setActiveId, triggerItemId]);\n\n  return (\n    <MenuLevelContext.Provider value={level}>\n      <MenuPanel\n        level={level}\n        side={side}\n        align=\"start\"\n        sideOffset={sideOffset}\n        alignOffset={alignOffset}\n        ariaLabel={ariaLabel}\n        className={cn(\"min-w-44\", className)}\n        onPanelEnter={onPanelEnter}\n      >\n        {children}\n      </MenuPanel>\n    </MenuLevelContext.Provider>\n  );\n}\n"},{"path":"components/motion/anchored-placement.ts","type":"registry:component","target":"@components/motion/anchored-placement.ts","content":"import type { PortalLayout } from \"@/components/motion/popover-position\";\n\nexport type PlacementSide = \"top\" | \"right\" | \"bottom\" | \"left\";\nexport type PlacementAlign = \"start\" | \"center\" | \"end\";\n\nexport interface PlacementOptions {\n  side: PlacementSide;\n  align: PlacementAlign;\n  /** Gap between trigger and panel along the side axis, in px. */\n  sideOffset?: number;\n  /** Shift along the align axis, in px. */\n  alignOffset?: number;\n  /** Minimum distance kept from the viewport edges, in px. */\n  padding?: number;\n}\n\nexport interface Placement {\n  left: number;\n  top: number;\n  /** The side actually used — differs from the requested one after a flip. */\n  side: PlacementSide;\n  /** Trigger-facing point of the panel, as a CSS transform-origin (px). */\n  origin: string;\n}\n\nconst OPPOSITE: Record<PlacementSide, PlacementSide> = {\n  top: \"bottom\",\n  bottom: \"top\",\n  left: \"right\",\n  right: \"left\",\n};\n\nfunction clamp(value: number, min: number, max: number) {\n  return Math.min(Math.max(value, min), Math.max(min, max));\n}\n\n/**\n * Places a portalled panel against its trigger in viewport coordinates\n * (pair with `usePopoverPortalPosition`). Flips to the opposite side when the\n * requested one lacks room and the other has more, then clamps the panel into\n * the viewport on both axes. The returned origin is the trigger's center\n * projected onto the panel's facing edge, so a scale entrance grows out of the\n * trigger even after a flip or a clamp.\n */\nexport function resolvePlacement(\n  layout: PortalLayout,\n  {\n    side: requested,\n    align,\n    sideOffset = 6,\n    alignOffset = 0,\n    padding = 8,\n  }: PlacementOptions,\n): Placement {\n  const { trigger, content } = layout;\n  const vw = window.innerWidth;\n  const vh = window.innerHeight;\n  const space: Record<PlacementSide, number> = {\n    top: trigger.top - sideOffset - padding,\n    bottom: vh - (trigger.top + trigger.height) - sideOffset - padding,\n    left: trigger.left - sideOffset - padding,\n    right: vw - (trigger.left + trigger.width) - sideOffset - padding,\n  };\n  const vertical = requested === \"top\" || requested === \"bottom\";\n  const need = vertical ? content.height : content.width;\n  const opposite = OPPOSITE[requested];\n  const side =\n    space[requested] < need && space[opposite] > space[requested]\n      ? opposite\n      : requested;\n\n  let left: number;\n  let top: number;\n  if (vertical) {\n    top =\n      side === \"bottom\"\n        ? trigger.top + trigger.height + sideOffset\n        : trigger.top - content.height - sideOffset;\n    left =\n      align === \"start\"\n        ? trigger.left\n        : align === \"end\"\n          ? trigger.left + trigger.width - content.width\n          : trigger.left + trigger.width / 2 - content.width / 2;\n    left = clamp(left + alignOffset, padding, vw - content.width - padding);\n    top = clamp(top, padding, vh - content.height - padding);\n  } else {\n    left =\n      side === \"right\"\n        ? trigger.left + trigger.width + sideOffset\n        : trigger.left - content.width - sideOffset;\n    top =\n      align === \"start\"\n        ? trigger.top\n        : align === \"end\"\n          ? trigger.top + trigger.height - content.height\n          : trigger.top + trigger.height / 2 - content.height / 2;\n    top = clamp(top + alignOffset, padding, vh - content.height - padding);\n    left = clamp(left, padding, vw - content.width - padding);\n  }\n\n  const cx = clamp(trigger.left + trigger.width / 2 - left, 0, content.width);\n  const cy = clamp(trigger.top + trigger.height / 2 - top, 0, content.height);\n  const origin =\n    side === \"bottom\"\n      ? `${cx}px 0px`\n      : side === \"top\"\n        ? `${cx}px ${content.height}px`\n        : side === \"right\"\n          ? `0px ${cy}px`\n          : `${content.width}px ${cy}px`;\n\n  return { left, top, side, origin };\n}\n"},{"path":"components/motion/popover-position.ts","type":"registry:component","target":"@components/motion/popover-position.ts","content":"\"use client\";\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;\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 | 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/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"}]}