{"slug":"context-menu","name":"Animated Context Menu","description":"Composable context-menu primitives with a pointer-origin clip morph, a gliding active row, checkbox and radio choices, keyboard navigation, typeahead, and long-press support.","category":"motion","source_url":"https://beui.dev/r/context-menu/raw","detail_url":"https://beui.dev/r/context-menu","raw_url":"https://beui.dev/r/context-menu/raw","page_url":"https://beui.dev/components/motion/context-menu","markdown_url":"https://beui.dev/components/motion/context-menu.md","published_at":"2026-07-27","updated_at":"2026-11-28","dependencies":["clsx","lucide-react","motion","react","react-dom","tailwind-merge"],"internal":["@/components/motion/context-menu","@/components/motion/menu/menu-item-highlight","@/components/motion/menu/use-menu-navigation","@/lib/ease","@/lib/hooks/use-dismiss","@/lib/i18n","@/lib/layers","@/lib/merge-refs","@/lib/presence-gate","@/lib/touch","@/lib/utils"],"install_slugs":["context-menu"],"requires_theme":true,"props":[{"displayName":"ContextMenu","props":[{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Whether the menu is open, for controlled use."},{"name":"defaultOpen","type":"boolean","required":false,"defaultValue":"false","description":"Whether the menu starts open when uncontrolled. Default: false"},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the new open state when the menu opens or closes."},{"name":"labels","type":"Partial<{ label: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the wrapper around the trigger and menu."}]},{"displayName":"ContextMenuTrigger","props":[{"name":"disabled","type":"boolean","required":false,"defaultValue":"false","description":"Stops right-click, long press and the keyboard from opening the menu. Default: false"},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the child element."}]},{"displayName":"ContextMenuContent","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the menu panel."},{"name":"ariaLabel","type":"string","required":false,"defaultValue":null,"description":"Accessible name for the menu. Default: \"Context menu\""}]},{"displayName":"ContextMenuItem","props":[{"name":"onSelect","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the item is clicked or chosen with the keyboard."},{"name":"disabled","type":"boolean","required":false,"defaultValue":null,"description":"Dims the item and skips it in keyboard navigation. Default: false"},{"name":"closeOnSelect","type":"boolean","required":false,"defaultValue":null,"description":"Closes the menu after the item is chosen. Default: true"},{"name":"tone","type":"\"default\" | \"destructive\"","required":false,"defaultValue":null,"description":"Colors the item red for destructive actions. Default: \"default\""},{"name":"inset","type":"boolean","required":false,"defaultValue":null,"description":"Adds left padding so the text lines up with items that have an icon. Default: false"},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the item button."},{"name":"textValue","type":"string","required":false,"defaultValue":null,"description":"Text matched by typeahead, when the item's own text is not plain."}]},{"displayName":"ContextMenuCheckboxItem","props":[{"name":"checked","type":"boolean","required":true,"defaultValue":null,"description":"Whether the item shows its check mark."},{"name":"onCheckedChange","type":"((checked: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the new checked state when the item is chosen."},{"name":"tone","type":"\"default\" | \"destructive\"","required":false,"defaultValue":null,"description":"Colors the item red for destructive actions. Default: \"default\""},{"name":"inset","type":"boolean","required":false,"defaultValue":null,"description":"Adds left padding so the text lines up with items that have an icon. Default: false"},{"name":"disabled","type":"boolean","required":false,"defaultValue":null,"description":"Dims the item and skips it in keyboard navigation. Default: false"},{"name":"closeOnSelect","type":"boolean","required":false,"defaultValue":null,"description":"Closes the menu after the item is chosen. Default: true"},{"name":"textValue","type":"string","required":false,"defaultValue":null,"description":"Text matched by typeahead, when the item's own text is not plain."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the item button."}]},{"displayName":"ContextMenuRadioGroup","props":[{"name":"value","type":"string","required":true,"defaultValue":null,"description":"The value of the checked radio item."},{"name":"onValueChange","type":"((value: string) => void)","required":false,"defaultValue":null,"description":"Called with the item's value when a radio item is chosen."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the group element."}]},{"displayName":"ContextMenuRadioItem","props":[{"name":"value","type":"string","required":true,"defaultValue":null,"description":"The value this item sets on its radio group."},{"name":"tone","type":"\"default\" | \"destructive\"","required":false,"defaultValue":null,"description":"Colors the item red for destructive actions. Default: \"default\""},{"name":"inset","type":"boolean","required":false,"defaultValue":null,"description":"Adds left padding so the text lines up with items that have an icon. Default: false"},{"name":"disabled","type":"boolean","required":false,"defaultValue":null,"description":"Dims the item and skips it in keyboard navigation. Default: false"},{"name":"closeOnSelect","type":"boolean","required":false,"defaultValue":null,"description":"Closes the menu after the item is chosen. Default: true"},{"name":"textValue","type":"string","required":false,"defaultValue":null,"description":"Text matched by typeahead, when the item's own text is not plain."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the item button."}]},{"displayName":"ContextMenuLabel","props":[{"name":"inset","type":"boolean","required":false,"defaultValue":"false","description":"Adds left padding to line up with inset items. Default: false"},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the label element."}]},{"displayName":"ContextMenuSeparator","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the separator line."}]},{"displayName":"ContextMenuShortcut","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the shortcut text."}]}],"types":[],"files":[{"path":"components/motion/context-menu.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/motion/context-menu\n\nimport { Check } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\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  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { MENU_ITEM_CLASS, MenuItemHighlight } from \"@/components/motion/menu/menu-item-highlight\";\nimport { enabledItems, useMenuNavigation } from \"@/components/motion/menu/use-menu-navigation\";\nimport { EASE_OUT, SPRING_PANEL } from \"@/lib/ease\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { assignRef } from \"@/lib/merge-refs\";\nimport { PresenceGate, type PresenceGateRenderProps } from \"@/lib/presence-gate\";\nimport { holdSelection, TOUCH_GESTURE_CONTENT_CLASS } from \"@/lib/touch\";\nimport { cn } from \"@/lib/utils\";\n\ntype OpenModality = \"pointer\" | \"keyboard\" | \"touch\";\ntype MenuPoint = { x: number; y: number };\n\nconst VIEWPORT_PADDING = 8;\nconst LONG_PRESS_DELAY = 520;\nconst LONG_PRESS_TOLERANCE = 10;\nconst MORPH_DURATION = 0.3;\nconst EXIT_DURATION = 0.2;\n\ntype TriggerElementProps = React.HTMLAttributes<HTMLElement> & {\n  ref?: Ref<HTMLElement>;\n};\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const contextMenuMessages = {\n  label: \"Context menu\",\n};\n\nexport type ContextMenuMessages = typeof contextMenuMessages;\n\ninterface ContextMenuContextValue {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  openAt: (point: MenuPoint, modality: OpenModality) => void;\n  point: MenuPoint;\n  modality: OpenModality;\n  menuId: string;\n  triggerRef: React.MutableRefObject<HTMLElement | null>;\n  contentRef: React.MutableRefObject<HTMLDivElement | null>;\n  activeId: string | null;\n  setActiveId: (id: string | null) => void;\n  /** The highlight glides after the pointer, and jumps after a key. */\n  glide: boolean;\n  setGlide: (glide: boolean) => void;\n  /** Close from a key press (Escape, Tab): no exit animation. */\n  closeFromKey: () => void;\n  reduce: boolean;\n  t: (key: keyof ContextMenuMessages) => string;\n}\n\nconst ContextMenuContext = createContext<ContextMenuContextValue | null>(null);\n\nfunction useContextMenuContext(component: string) {\n  const context = useContext(ContextMenuContext);\n  if (!context) {\n    throw new Error(`${component} must be used within <ContextMenu>`);\n  }\n  return context;\n}\n\nfunction clamp(value: number, min: number, max: number) {\n  return Math.min(Math.max(value, min), max);\n}\n\nfunction collapsedClip(\n  origin: MenuPoint,\n  size: { width: number; height: number },\n) {\n  const half = 8;\n  const top = clamp(origin.y - half, 0, size.height);\n  const right = clamp(size.width - origin.x - half, 0, size.width);\n  const bottom = clamp(size.height - origin.y - half, 0, size.height);\n  const left = clamp(origin.x - half, 0, size.width);\n  return `inset(${top}px ${right}px ${bottom}px ${left}px round 10px)`;\n}\n\nexport interface ContextMenuProps {\n  children: ReactNode;\n  /** Whether the menu is open, for controlled use. */\n  open?: boolean;\n  /** Whether the menu starts open when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new open state when the menu opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /** Override any built-in string. */\n  labels?: Partial<ContextMenuMessages>;\n  /** Classes merged onto the wrapper around the trigger and menu. */\n  className?: string;\n}\n\nexport function ContextMenu({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  labels,\n  className,\n}: ContextMenuProps) {\n  const t = useMessages(\"contextMenu\", contextMenuMessages, labels);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const [point, setPoint] = useState<MenuPoint>({ x: 0, y: 0 });\n  const [modality, setModality] = useState<OpenModality>(\"pointer\");\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [glide, setGlide] = useState(true);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const menuId = useId();\n  const reduce = useReducedMotion() ?? false;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n      if (!next) setActiveId(null);\n    },\n    [controlled, onOpenChange],\n  );\n\n  const openAt = useCallback(\n    (nextPoint: MenuPoint, nextModality: OpenModality) => {\n      setPoint(nextPoint);\n      setModality(nextModality);\n      setGlide(nextModality !== \"keyboard\");\n      setActiveId(null);\n      setOpen(true);\n    },\n    [setOpen],\n  );\n\n  // The exit times itself by modality, so a key press closes without one.\n  const closeFromKey = useCallback(() => {\n    setModality(\"keyboard\");\n    setOpen(false);\n  }, [setOpen]);\n\n  // A focused panel answers Escape itself; this covers a menu opened by\n  // pointer that never took focus. Either way focus goes back to the trigger.\n  const dismiss = useCallback(\n    (reason: DismissReason) => {\n      if (reason === \"escape\") {\n        closeFromKey();\n        triggerRef.current?.focus();\n      } else setOpen(false);\n    },\n    [setOpen, closeFromKey],\n  );\n  useDismiss(open, dismiss, contentRef);\n\n  useEffect(() => {\n    if (!open) return;\n    const onWindowChange = () => setOpen(false);\n    window.addEventListener(\"resize\", onWindowChange);\n    window.addEventListener(\"scroll\", onWindowChange);\n    return () => {\n      window.removeEventListener(\"resize\", onWindowChange);\n      window.removeEventListener(\"scroll\", onWindowChange);\n    };\n  }, [open, setOpen]);\n\n  const value = useMemo<ContextMenuContextValue>(\n    () => ({\n      open,\n      setOpen,\n      openAt,\n      point,\n      modality,\n      menuId,\n      triggerRef,\n      contentRef,\n      activeId,\n      setActiveId,\n      glide,\n      setGlide,\n      closeFromKey,\n      reduce,\n      t,\n    }),\n    [\n      open,\n      setOpen,\n      openAt,\n      point,\n      modality,\n      menuId,\n      activeId,\n      glide,\n      closeFromKey,\n      reduce,\n      t,\n    ],\n  );\n\n  return (\n    <ContextMenuContext.Provider value={value}>\n      <div className={cn(\"contents\", className)}>{children}</div>\n    </ContextMenuContext.Provider>\n  );\n}\n\nexport interface ContextMenuTriggerProps {\n  children: ReactElement<TriggerElementProps>;\n  /** Stops right-click, long press and the keyboard from opening the menu. Default: false */\n  disabled?: boolean;\n  /** Classes merged onto the child element. */\n  className?: string;\n}\n\nexport function ContextMenuTrigger({\n  children,\n  disabled = false,\n  className,\n}: ContextMenuTriggerProps) {\n  const context = useContextMenuContext(\"ContextMenuTrigger\");\n  const longPressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const touchOrigin = useRef<MenuPoint | null>(null);\n  const releaseSelection = useRef<(() => void) | null>(null);\n\n  const cancelLongPress = useCallback(() => {\n    if (longPressTimer.current) {\n      clearTimeout(longPressTimer.current);\n      longPressTimer.current = null;\n    }\n    touchOrigin.current = null;\n  }, []);\n\n  // Held for the whole press, not just the timer: a gesture that turned into a\n  // drag must not paint a selection under the finger either.\n  const endPress = useCallback(() => {\n    cancelLongPress();\n    releaseSelection.current?.();\n    releaseSelection.current = null;\n  }, [cancelLongPress]);\n\n  useEffect(() => endPress, [endPress]);\n\n  if (!isValidElement(children)) {\n    throw new Error(\"<ContextMenuTrigger> requires a single React element\");\n  }\n\n  const childProps = children.props;\n  const childRef = children.props.ref;\n\n  const onPointerDown = (event: ReactPointerEvent<HTMLElement>) => {\n    childProps.onPointerDown?.(event);\n    // A pen presses the same way a finger does and gets no `contextmenu` out\n    // of the platform for it, so it holds to open too. A mouse has the right\n    // button and is left to `onContextMenu`.\n    const pressToOpen =\n      event.pointerType === \"touch\" || event.pointerType === \"pen\";\n    if (event.defaultPrevented || disabled || !pressToOpen) return;\n\n    // `pointer-coarse:select-none` misses this press on a laptop whose mouse\n    // is the primary pointer and whose touchscreen is not, and the platform's\n    // own long-press selection then claims the gesture and cancels ours. The\n    // press is the only thing that knows which input is on the glass, so it\n    // takes selection away itself - for its own duration, and no longer.\n    releaseSelection.current?.();\n    releaseSelection.current = holdSelection(event.currentTarget);\n\n    const origin = { x: event.clientX, y: event.clientY };\n    touchOrigin.current = origin;\n    longPressTimer.current = setTimeout(() => {\n      context.openAt(origin, \"touch\");\n      longPressTimer.current = null;\n      touchOrigin.current = null;\n    }, LONG_PRESS_DELAY);\n  };\n\n  const onPointerMove = (event: ReactPointerEvent<HTMLElement>) => {\n    childProps.onPointerMove?.(event);\n    const origin = touchOrigin.current;\n    if (\n      origin &&\n      Math.hypot(event.clientX - origin.x, event.clientY - origin.y) >\n        LONG_PRESS_TOLERANCE\n    ) {\n      cancelLongPress();\n    }\n  };\n\n  const onKeyDown = (event: ReactKeyboardEvent<HTMLElement>) => {\n    childProps.onKeyDown?.(event);\n    if (event.defaultPrevented || disabled) return;\n    if (event.key !== \"ContextMenu\" && !(event.shiftKey && event.key === \"F10\"))\n      return;\n\n    event.preventDefault();\n    const rect = event.currentTarget.getBoundingClientRect();\n    context.openAt(\n      { x: rect.left + Math.min(24, rect.width / 2), y: rect.top + rect.height / 2 },\n      \"keyboard\",\n    );\n  };\n\n  return cloneElement(children, {\n    ref: (node: HTMLElement | null) => {\n      context.triggerRef.current = node;\n      assignRef(childRef, node);\n    },\n    \"aria-controls\": context.open ? context.menuId : undefined,\n    \"aria-haspopup\": \"menu\",\n    \"aria-expanded\": context.open,\n    // The long press is ours: without this iOS runs its own on the same\n    // gesture and drops the selection callout and its handles on top of the\n    // menu we just opened. Only the press gesture is ours though - the child\n    // is the consumer's content, so a mouse can still select the text in it\n    // and right-click the selection. `touch-none` stays off too: the page\n    // still has to scroll from the trigger.\n    className: cn(TOUCH_GESTURE_CONTENT_CLASS, childProps.className, className),\n    onContextMenu: (event: ReactMouseEvent<HTMLElement>) => {\n      childProps.onContextMenu?.(event);\n      if (event.defaultPrevented || disabled) return;\n      event.preventDefault();\n      endPress();\n      context.openAt({ x: event.clientX, y: event.clientY }, \"pointer\");\n    },\n    onKeyDown,\n    onPointerDown,\n    onPointerMove,\n    onPointerUp: (event: ReactPointerEvent<HTMLElement>) => {\n      childProps.onPointerUp?.(event);\n      endPress();\n    },\n    onPointerCancel: (event: ReactPointerEvent<HTMLElement>) => {\n      childProps.onPointerCancel?.(event);\n      endPress();\n    },\n  });\n}\n\nexport interface ContextMenuContentProps {\n  children: ReactNode;\n  /** Classes merged onto the menu panel. */\n  className?: string;\n  /** Accessible name for the menu. Default: \"Context menu\" */\n  ariaLabel?: string;\n}\n\nexport function ContextMenuContent({\n  children,\n  className,\n  ariaLabel,\n}: ContextMenuContentProps) {\n  const context = useContextMenuContext(\"ContextMenuContent\");\n  const [mounted, setMounted] = useState(false);\n\n  useEffect(() => setMounted(true), []);\n\n  if (!mounted) return null;\n\n  // Mounted only while open: a closed menu leaves nothing on the page.\n  return createPortal(\n    <AnimatePresence>\n      {context.open && (\n        <PresenceGate>\n          {({ isPresent, gate }) => (\n            <ContextMenuPanel\n              present={isPresent}\n              gate={gate}\n              ariaLabel={ariaLabel}\n              className={className}\n            >\n              {children}\n            </ContextMenuPanel>\n          )}\n        </PresenceGate>\n      )}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n\nfunction ContextMenuPanel({\n  children,\n  className,\n  ariaLabel,\n  present,\n  gate,\n}: ContextMenuContentProps & {\n  present: boolean;\n  gate: PresenceGateRenderProps[\"gate\"];\n}) {\n  const context = useContextMenuContext(\"ContextMenuContent\");\n  const { point, modality, reduce, contentRef } = context;\n  const [position, setPosition] = useState<MenuPoint>(point);\n  const [origin, setOrigin] = useState<MenuPoint>({ x: 0, y: 0 });\n  const [size, setSize] = useState({ width: 0, height: 0 });\n  const [morphReady, setMorphReady] = useState(false);\n  const navigate = useMenuNavigation();\n  const instant = reduce || modality === \"keyboard\";\n\n  // Runs again for a new invocation, and when the menu reopens during its exit.\n  useLayoutEffect(() => {\n    if (!present) return;\n    const content = contentRef.current;\n    if (!content) return;\n\n    const rect = content.getBoundingClientRect();\n    const left = Math.max(\n      VIEWPORT_PADDING,\n      Math.min(\n        Math.max(point.x, VIEWPORT_PADDING),\n        window.innerWidth - rect.width - VIEWPORT_PADDING,\n      ),\n    );\n    const top = Math.max(\n      VIEWPORT_PADDING,\n      Math.min(\n        Math.max(point.y, VIEWPORT_PADDING),\n        window.innerHeight - rect.height - VIEWPORT_PADDING,\n      ),\n    );\n\n    setPosition({ x: left, y: top });\n    setSize({ width: rect.width, height: rect.height });\n    setOrigin({\n      x: clamp(point.x - left, 12, Math.max(12, rect.width - 12)),\n      y: clamp(point.y - top, 12, Math.max(12, rect.height - 12)),\n    });\n    setMorphReady(false);\n\n    if (instant) {\n      setMorphReady(true);\n      return;\n    }\n\n    // Let the measured collapsed clip paint once before expanding it. Without\n    // this preparation frame, the first invocation can batch both states and\n    // appear at full size without the morph.\n    let openFrame = 0;\n    const prepareFrame = requestAnimationFrame(() => {\n      openFrame = requestAnimationFrame(() => setMorphReady(true));\n    });\n    return () => {\n      cancelAnimationFrame(prepareFrame);\n      cancelAnimationFrame(openFrame);\n    };\n    // Every invocation sets a new `point` object, even at the same spot.\n  }, [present, point, instant, contentRef]);\n\n  useEffect(() => {\n    if (!present) return;\n    const frame = requestAnimationFrame(() => {\n      const first = enabledItems(contentRef.current)[0];\n      first?.focus({ preventScroll: true });\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [present, contentRef]);\n\n  const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n    // Set before the key moves focus, so the highlight it lands on jumps.\n    context.setGlide(false);\n    if (event.key === \"Escape\") {\n      event.preventDefault();\n      context.closeFromKey();\n      context.triggerRef.current?.focus();\n      return;\n    }\n    if (event.key === \"Tab\") {\n      context.closeFromKey();\n      return;\n    }\n    navigate(event, contentRef.current);\n  };\n\n  const clipHidden = collapsedClip(origin, size);\n  const clipShown = \"inset(0px 0px 0px 0px round 12px)\";\n  const timing = (duration: number) =>\n    modality === \"keyboard\"\n      ? { duration: 0 }\n      : reduce\n        ? { duration: 0.1, ease: EASE_OUT }\n        : { duration, ease: EASE_OUT };\n\n  return (\n    <div\n      {...gate}\n      data-context-menu-portal=\"\"\n      style={{ ...gate.style, left: position.x, top: position.y }}\n      // The panel's clip-path would cut a box-shadow, so the wrapper draws the\n      // system's one panel shadow as a drop-shadow instead.\n      className=\"fixed z-[100] [filter:drop-shadow(0_8px_12px_rgb(0_0_0/0.12))]\"\n    >\n      <motion.div\n        ref={contentRef}\n        id={context.menuId}\n        data-level={context.menuId}\n        role=\"menu\"\n        aria-label={ariaLabel ?? context.t(\"label\")}\n        data-morph-ready={morphReady ? \"true\" : \"false\"}\n        tabIndex={-1}\n        initial={false}\n        animate={{\n          opacity: morphReady ? 1 : 0,\n          clipPath: instant || morphReady ? clipShown : clipHidden,\n        }}\n        // Folds back into the point it opened from, faster than it grew.\n        exit={{\n          opacity: 0,\n          clipPath: instant ? clipShown : clipHidden,\n          transition: timing(EXIT_DURATION),\n        }}\n        transition={timing(MORPH_DURATION)}\n        onKeyDown={onKeyDown}\n        onPointerMove={(event) => {\n          if (event.pointerType !== \"touch\") context.setGlide(true);\n        }}\n        onContextMenu={(event) => event.preventDefault()}\n        className={cn(\n          \"min-w-56 overflow-hidden rounded-2xl border border-border bg-background p-2 text-foreground outline-none\",\n          className,\n        )}\n      >\n        {children}\n      </motion.div>\n    </div>\n  );\n}\n\ntype ContextMenuItemTone = \"default\" | \"destructive\";\n\nexport interface ContextMenuItemProps {\n  children: ReactNode;\n  /** Called when the item is clicked or chosen with the keyboard. */\n  onSelect?: () => void;\n  /** Dims the item and skips it in keyboard navigation. Default: false */\n  disabled?: boolean;\n  /** Closes the menu after the item is chosen. Default: true */\n  closeOnSelect?: boolean;\n  /** Colors the item red for destructive actions. Default: \"default\" */\n  tone?: ContextMenuItemTone;\n  /** Adds left padding so the text lines up with items that have an icon. Default: false */\n  inset?: boolean;\n  /** Classes merged onto the item button. */\n  className?: string;\n  /** Text matched by typeahead, when the item's own text is not plain. */\n  textValue?: string;\n}\n\nfunction ContextMenuItemBase({\n  children,\n  onSelect,\n  disabled = false,\n  closeOnSelect = true,\n  tone = \"default\",\n  inset = false,\n  className,\n  textValue,\n  role = \"menuitem\",\n  ariaChecked,\n}: ContextMenuItemProps & {\n  role?: \"menuitem\" | \"menuitemcheckbox\" | \"menuitemradio\";\n  ariaChecked?: boolean;\n}) {\n  const context = useContextMenuContext(\"ContextMenuItem\");\n  const id = useId();\n  const active = context.activeId === id;\n  const checkedProps =\n    role === \"menuitem\" ? {} : { \"aria-checked\": ariaChecked };\n\n  return (\n    <button\n      type=\"button\"\n      id={id}\n      role={role}\n      {...checkedProps}\n      disabled={disabled}\n      data-menu-item=\"\"\n      data-level={context.menuId}\n      data-disabled={disabled ? \"\" : undefined}\n      data-text-value={textValue}\n      tabIndex={-1}\n      onFocus={() => context.setActiveId(id)}\n      onPointerMove={(event) => {\n        if (!disabled && event.pointerType !== \"touch\") event.currentTarget.focus();\n      }}\n      onClick={() => {\n        if (disabled) return;\n        onSelect?.();\n        if (closeOnSelect) context.setOpen(false);\n      }}\n      className={cn(\n        MENU_ITEM_CLASS,\n        \"gap-2.5\",\n        \"focus-visible:ring-2 focus-visible:ring-foreground/15\",\n        \"disabled:pointer-events-none disabled:opacity-40\",\n        inset && \"pl-9\",\n        tone === \"destructive\" ? \"text-destructive\" : \"text-foreground\",\n        className,\n      )}\n    >\n      {active ? (\n        <MenuItemHighlight\n          layoutId={`${context.menuId}-active`}\n          tone={tone}\n          reduce={context.reduce}\n          instant={!context.glide}\n        />\n      ) : null}\n      {children}\n    </button>\n  );\n}\n\nexport function ContextMenuItem(props: ContextMenuItemProps) {\n  return <ContextMenuItemBase {...props} />;\n}\n\nexport interface ContextMenuCheckboxItemProps\n  extends Omit<ContextMenuItemProps, \"onSelect\"> {\n  /** Whether the item shows its check mark. */\n  checked: boolean;\n  /** Called with the new checked state when the item is chosen. */\n  onCheckedChange?: (checked: boolean) => void;\n}\n\nexport function ContextMenuCheckboxItem({\n  checked,\n  onCheckedChange,\n  children,\n  ...props\n}: ContextMenuCheckboxItemProps) {\n  const context = useContextMenuContext(\"ContextMenuCheckboxItem\");\n  return (\n    <ContextMenuItemBase\n      {...props}\n      role=\"menuitemcheckbox\"\n      ariaChecked={checked}\n      onSelect={() => onCheckedChange?.(!checked)}\n    >\n      {children}\n      {/* The mark sits at the end of the row, never before the label. */}\n      <span aria-hidden=\"true\" className=\"ml-auto flex h-4 w-4 shrink-0 items-center justify-center\">\n        <AnimatePresence initial={false}>\n          {checked ? (\n            <motion.span\n              key=\"check\"\n              initial={context.reduce ? false : { opacity: 0, scale: 0.75 }}\n              animate={{ opacity: 1, scale: 1 }}\n              exit={{ opacity: 0, scale: context.reduce ? 1 : 0.75 }}\n              transition={context.reduce ? { duration: 0.08 } : SPRING_PANEL}\n            >\n              <Check aria-hidden=\"true\" className=\"h-3.5 w-3.5\" strokeWidth={2.4} />\n            </motion.span>\n          ) : null}\n        </AnimatePresence>\n      </span>\n    </ContextMenuItemBase>\n  );\n}\n\ninterface ContextMenuRadioGroupContextValue {\n  value: string;\n  onValueChange?: (value: string) => void;\n}\n\nconst ContextMenuRadioGroupContext =\n  createContext<ContextMenuRadioGroupContextValue | null>(null);\n\nexport interface ContextMenuRadioGroupProps {\n  /** The value of the checked radio item. */\n  value: string;\n  /** Called with the item's value when a radio item is chosen. */\n  onValueChange?: (value: string) => void;\n  children: ReactNode;\n  /** Classes merged onto the group element. */\n  className?: string;\n}\n\nexport function ContextMenuRadioGroup({\n  value,\n  onValueChange,\n  children,\n  className,\n}: ContextMenuRadioGroupProps) {\n  const context = useMemo(\n    () => ({ value, onValueChange }),\n    [value, onValueChange],\n  );\n  return (\n    <ContextMenuRadioGroupContext.Provider value={context}>\n      <div className={className}>{children}</div>\n    </ContextMenuRadioGroupContext.Provider>\n  );\n}\n\nexport interface ContextMenuRadioItemProps\n  extends Omit<ContextMenuItemProps, \"onSelect\"> {\n  /** The value this item sets on its radio group. */\n  value: string;\n}\n\nexport function ContextMenuRadioItem({\n  value,\n  children,\n  ...props\n}: ContextMenuRadioItemProps) {\n  const group = useContext(ContextMenuRadioGroupContext);\n  if (!group) {\n    throw new Error(\n      \"ContextMenuRadioItem must be used within <ContextMenuRadioGroup>\",\n    );\n  }\n  const checked = group.value === value;\n  return (\n    <ContextMenuItemBase\n      {...props}\n      role=\"menuitemradio\"\n      ariaChecked={checked}\n      onSelect={() => group.onValueChange?.(value)}\n    >\n      {children}\n      {/* The mark sits at the end of the row, never before the label. */}\n      <span aria-hidden=\"true\" className=\"ml-auto flex h-4 w-4 shrink-0 items-center justify-center\">\n        <Check\n          aria-hidden=\"true\"\n          className={cn(\n            \"h-3.5 w-3.5 transition-opacity\",\n            checked ? \"opacity-100\" : \"opacity-0\",\n          )}\n          strokeWidth={2.4}\n        />\n      </span>\n    </ContextMenuItemBase>\n  );\n}\n\nexport interface ContextMenuLabelProps {\n  children: ReactNode;\n  /** Adds left padding to line up with inset items. Default: false */\n  inset?: boolean;\n  /** Classes merged onto the label element. */\n  className?: string;\n}\n\nexport function ContextMenuLabel({\n  children,\n  inset = false,\n  className,\n}: ContextMenuLabelProps) {\n  return (\n    <div\n      className={cn(\n        \"px-3 pb-1 pt-1.5 text-[11px] font-medium uppercase tracking-[0.12em] text-muted-foreground\",\n        inset && \"pl-9\",\n        className,\n      )}\n    >\n      {children}\n    </div>\n  );\n}\n\nexport interface ContextMenuSeparatorProps {\n  /** Classes merged onto the separator line. */\n  className?: string;\n}\n\nexport function ContextMenuSeparator({\n  className,\n}: ContextMenuSeparatorProps) {\n  return (\n    <hr className={cn(\"-mx-2 my-1 h-px border-0 bg-border\", className)} />\n  );\n}\n\nexport interface ContextMenuShortcutProps {\n  children: ReactNode;\n  /** Classes merged onto the shortcut text. */\n  className?: string;\n}\n\nexport function ContextMenuShortcut({\n  children,\n  className,\n}: ContextMenuShortcutProps) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cn(\n        \"ml-auto pl-4 text-[11px] font-medium tracking-wide text-muted-foreground\",\n        className,\n      )}\n    >\n      {children}\n    </span>\n  );\n}\n"},{"path":"components/motion/menu/menu-item-highlight.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\n/** The row shape every menu item shares. Menus add their own gap and states. */\nexport const MENU_ITEM_CLASS =\n  \"relative isolate flex w-full select-none items-center rounded-lg px-3 py-1.5 text-left text-sm outline-none\";\n\nexport interface MenuItemHighlightProps {\n  /** Shared by every row of one panel, so the highlight glides between them. */\n  layoutId: string;\n  tone?: \"default\" | \"destructive\";\n  reduce: boolean;\n  /**\n   * Jump instead of gliding: the highlight was moved by the keyboard, where a\n   * spring only trails behind fast arrowing.\n   */\n  instant?: boolean;\n}\n\n/** The highlight behind the active row. Render it only inside the active row. */\nexport function MenuItemHighlight({\n  layoutId,\n  tone = \"default\",\n  reduce,\n  instant = false,\n}: MenuItemHighlightProps) {\n  return (\n    <motion.span\n      aria-hidden=\"true\"\n      layoutId={layoutId}\n      className={cn(\n        \"absolute inset-0 -z-10 rounded-lg\",\n        tone === \"destructive\" ? \"bg-destructive/10\" : \"bg-foreground/[0.07]\",\n      )}\n      transition={reduce || instant ? { duration: 0 } : SPRING_LAYOUT}\n    />\n  );\n}\n"},{"path":"components/motion/menu/use-menu-navigation.ts","type":"util","content":"\"use client\";\n\nimport { type KeyboardEvent, useCallback, useEffect, useRef } from \"react\";\n\nconst TYPEAHEAD_RESET = 500;\n\n/**\n * The enabled rows of one menu panel, in order. Rows carry `data-menu-item`\n * and the panel's `data-level`, so a submenu rendered inside the panel keeps\n * its own rows to itself.\n */\nexport function 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\n/**\n * Arrow keys, Home, End and typeahead for a menu panel. The returned handler\n * moves focus between the panel's rows and says whether it used the key.\n * Typeahead matches a row's `data-text-value`, or its text.\n */\nexport function useMenuNavigation() {\n  const query = useRef(\"\");\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  useEffect(\n    () => () => {\n      if (timer.current) clearTimeout(timer.current);\n    },\n    [],\n  );\n\n  return useCallback((event: KeyboardEvent<HTMLElement>, panel: HTMLElement | null) => {\n    const items = enabledItems(panel);\n    const index = items.indexOf(event.target as HTMLElement);\n    if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n      event.preventDefault();\n      if (items.length === 0) return true;\n      const step = event.key === \"ArrowDown\" ? 1 : -1;\n      const next =\n        index < 0\n          ? step === 1\n            ? 0\n            : items.length - 1\n          : (index + step + items.length) % items.length;\n      items[next]?.focus();\n      return true;\n    }\n    if (event.key === \"Home\" || event.key === \"End\") {\n      event.preventDefault();\n      items[event.key === \"Home\" ? 0 : items.length - 1]?.focus();\n      return true;\n    }\n    const typed = event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;\n    // A space with nothing typed yet presses the row instead.\n    if (!typed || (event.key === \" \" && query.current === \"\")) return false;\n    query.current += event.key.toLocaleLowerCase();\n    if (timer.current) clearTimeout(timer.current);\n    timer.current = setTimeout(() => {\n      query.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 typedSoFar = query.current;\n    const repeated = typedSoFar.length > 1 && [...typedSoFar].every((char) => char === typedSoFar[0]);\n    const needle = repeated ? typedSoFar[0] : typedSoFar;\n    const match = ordered.find((item) =>\n      (item.dataset.textValue ?? item.textContent ?? \"\").trim().toLocaleLowerCase().startsWith(needle),\n    );\n    if (!match) return false;\n    event.preventDefault();\n    match.focus();\n    return true;\n  }, []);\n}\n"},{"path":"lib/ease.ts","type":"util","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\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/hooks/use-dismiss.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport {\n  inLayerAbove,\n  inOtherLayer,\n  type Layer,\n  openLayer,\n  ownsEscape,\n} from \"@/lib/layers\";\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\n/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */\nexport type DismissReason = \"escape\" | \"pointer\" | \"focus\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */\n  focusOutside?: boolean;\n  /**\n   * Dismiss on a pointerdown outside. Default true. Turn it off for an overlay\n   * whose own backdrop handles presses and only needs Escape and layering.\n   */\n  outsidePress?: boolean;\n  /** Return true for an outside target that should *not* dismiss. */\n  ignore?: (target: Element) => boolean;\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.\n *\n * Each open dismissal is a layer in `lib/layers.ts`, so only the innermost\n * open overlay answers Escape (a menu inside a drawer closes, the drawer\n * stays), and a drawer's focus trap leaves focus in a menu it portaled out.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: (reason: DismissReason) => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    focusOutside = false,\n    outsidePress = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  // Read through refs, so a callback rebuilt each render neither re-binds the\n  // listeners nor moves this layer to the top of the stack.\n  const dismissRef = useRef(onDismiss);\n  const ignoreRef = useRef(ignore);\n  useLayoutEffect(() => {\n    dismissRef.current = onDismiss;\n    ignoreRef.current = ignore;\n  });\n\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Node) =>\n      Boolean(ref?.current?.contains(target)) ||\n      (target instanceof Element && Boolean(ignoreRef.current?.(target)));\n    const layer: Layer = { contains: inside, escape: dismissOnEscape };\n    const closeLayer = openLayer(layer);\n    const onKey = (event: KeyboardEvent) => {\n      if (!dismissOnEscape || event.key !== \"Escape\" || !ownsEscape(layer, event)) return;\n      event.preventDefault();\n      dismissRef.current(\"escape\");\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // A press in an overlay opened on top of this one (a tooltip or menu\n      // portaled to the body) belongs to that overlay, not outside this one.\n      if (inLayerAbove(layer, target)) return;\n      // Outside this overlay, but inside another open one: 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\" && !inOtherLayer(layer, target, { traps: false })) {\n        consumeActivation(event);\n      }\n      dismissRef.current(\"pointer\");\n    };\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (target instanceof Node && !inside(target)) dismissRef.current(\"focus\");\n    };\n    window.addEventListener(\"keydown\", onKey);\n    if (outsidePress) window.addEventListener(\"pointerdown\", onPointer, true);\n    if (focusOutside) window.addEventListener(\"focusin\", onFocus);\n    return () => {\n      closeLayer();\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n      window.removeEventListener(\"focusin\", onFocus);\n    };\n  }, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/merge-refs.ts","type":"util","content":"import type { Ref } from \"react\";\n\n/** Points a callback or object ref at `value`. */\nexport function 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\n/** One callback ref that sets every ref it is given. */\nexport function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) assignRef(ref, node);\n  };\n}\n"},{"path":"lib/presence-gate.tsx","type":"util","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/touch.ts","type":"util","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page - the long-press selection callout and the selection it drags in with\n// it - and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant - which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing - the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis - leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures - a coarse\n * pointer - so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction - the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal - a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs - routine on iOS, where the\n * system can claim the touch first - and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active - implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer - a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger - so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it - `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"},{"path":"lib/utils.ts","type":"util","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"},{"path":"lib/layers.ts","type":"util","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer (its panel, portals, trigger). */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"components/previews/motion/context-menu.preview.tsx","type":"preview","content":"\"use client\";\n\nimport {\n  Check,\n  CloudOff,\n  Copy,\n  Download,\n  Eye,\n  Pencil,\n  Trash2,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { useState } from \"react\";\nimport {\n  ContextMenu,\n  ContextMenuCheckboxItem,\n  ContextMenuContent,\n  ContextMenuItem,\n  ContextMenuLabel,\n  ContextMenuSeparator,\n  ContextMenuShortcut,\n  ContextMenuTrigger,\n} from \"@/components/motion/context-menu\";\nimport { SPRING_SWAP } from \"@/lib/ease\";\n\nexport function ContextMenuPreview() {\n  const reduce = useReducedMotion() ?? false;\n  const [message, setMessage] = useState<string | null>(null);\n  const [offline, setOffline] = useState(false);\n\n  return (\n    <div className=\"flex min-h-[360px] w-full items-center justify-center\">\n      <ContextMenu>\n        <ContextMenuTrigger>\n          <button\n            type=\"button\"\n            className=\"group flex flex-col items-center outline-none\"\n          >\n            <div className=\"relative h-24 w-32 transition-transform duration-150 group-active:scale-[0.98] group-focus-visible:rounded-2xl group-focus-visible:ring-2 group-focus-visible:ring-foreground/20 group-focus-visible:ring-offset-4 group-focus-visible:ring-offset-background\">\n              <div className=\"absolute left-1 top-1 h-7 w-14 rounded-t-[10px] bg-[#d4a84f] dark:bg-[#a77d2f]\" />\n              <div className=\"absolute inset-x-0 bottom-0 top-5 rounded-[14px] bg-[#e7bb61] shadow-[0_14px_24px_-16px_rgba(90,58,8,0.75)] dark:bg-[#bd8d36]\" />\n              <div className=\"absolute inset-x-0 bottom-0 top-9 rounded-[14px] bg-[#efc86f] dark:bg-[#cb9a41]\" />\n              <div className=\"absolute inset-x-5 bottom-4 h-px bg-black/10 dark:bg-white/10\" />\n            </div>\n\n            <span className=\"mt-4 text-sm font-medium text-foreground\">\n              Right click on me\n            </span>\n\n            <div className=\"mt-1 h-4\">\n              <AnimatePresence mode=\"wait\" initial={false}>\n                {message ? (\n                  <motion.span\n                    key={message}\n                    initial={\n                      reduce\n                        ? { opacity: 0 }\n                        : { opacity: 0, y: 3, filter: \"blur(2px)\" }\n                    }\n                    animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n                    exit={\n                      reduce\n                        ? { opacity: 0 }\n                        : { opacity: 0, y: -2, filter: \"blur(2px)\" }\n                    }\n                    transition={reduce ? { duration: 0.1 } : SPRING_SWAP}\n                    className=\"flex items-center gap-1 text-[11px] text-muted-foreground\"\n                  >\n                    <Check aria-hidden=\"true\" className=\"h-3 w-3 text-success\" />\n                    {message}\n                  </motion.span>\n                ) : (\n                  <span className=\"text-[11px] text-muted-foreground\">\n                    or long-press · Shift + F10\n                  </span>\n                )}\n              </AnimatePresence>\n            </div>\n          </button>\n        </ContextMenuTrigger>\n\n        <ContextMenuContent ariaLabel=\"Folder actions\" className=\"w-60\">\n          <ContextMenuLabel>Project files</ContextMenuLabel>\n          <ContextMenuItem\n            textValue=\"Open\"\n            onSelect={() => setMessage(\"Folder opened\")}\n          >\n            <Eye aria-hidden=\"true\" className=\"h-4 w-4\" />\n            Open\n            <ContextMenuShortcut>↵</ContextMenuShortcut>\n          </ContextMenuItem>\n          <ContextMenuItem\n            textValue=\"Rename\"\n            onSelect={() => setMessage(\"Ready to rename\")}\n          >\n            <Pencil aria-hidden=\"true\" className=\"h-4 w-4\" />\n            Rename\n            <ContextMenuShortcut>R</ContextMenuShortcut>\n          </ContextMenuItem>\n          <ContextMenuItem\n            textValue=\"Duplicate\"\n            onSelect={() => setMessage(\"Folder duplicated\")}\n          >\n            <Copy aria-hidden=\"true\" className=\"h-4 w-4\" />\n            Duplicate\n            <ContextMenuShortcut>⌘D</ContextMenuShortcut>\n          </ContextMenuItem>\n          <ContextMenuItem\n            textValue=\"Download\"\n            onSelect={() => setMessage(\"Download started\")}\n          >\n            <Download aria-hidden=\"true\" className=\"h-4 w-4\" />\n            Download\n          </ContextMenuItem>\n\n          <ContextMenuSeparator />\n\n          <ContextMenuCheckboxItem\n            textValue=\"Keep offline\"\n            checked={offline}\n            closeOnSelect={false}\n            onCheckedChange={(checked) => {\n              setOffline(checked);\n              setMessage(checked ? \"Available offline\" : \"Online only\");\n            }}\n          >\n            <CloudOff aria-hidden=\"true\" className=\"h-4 w-4\" />\n            Keep offline\n          </ContextMenuCheckboxItem>\n\n          <ContextMenuSeparator />\n\n          <ContextMenuItem\n            tone=\"destructive\"\n            textValue=\"Move to trash\"\n            onSelect={() => setMessage(\"Moved to trash\")}\n          >\n            <Trash2 aria-hidden=\"true\" className=\"h-4 w-4\" />\n            Move to trash\n            <ContextMenuShortcut>⌘⌫</ContextMenuShortcut>\n          </ContextMenuItem>\n        </ContextMenuContent>\n      </ContextMenu>\n    </div>\n  );\n}\n"}]}