{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "loupe",
  "type": "registry:ui",
  "title": "Loupe",
  "description": "Magnifier lens that turns any child — image, SVG, or subtree — into an inspectable surface. Spring-smoothed pointer follow or a pinned mode, a machined bezel with a velocity-driven specular arc, focus-blur on the surface behind, and full keyboard walking. Pure transform/clip compositing, zero canvas; a ghost lens drifts over the surface when untouched.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://crucibleui.com/r/use-reduced-motion.json",
    "https://crucibleui.com/r/use-visibility-pause.json"
  ],
  "files": [
    {
      "path": "registry/default/utility/loupe/loupe.tsx",
      "type": "registry:ui",
      "target": "components/crucible/loupe.tsx",
      "content": "\"use client\";\n\nimport {\n  AnimatePresence,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useSpring,\n  useTransform,\n  useVelocity,\n} from \"motion/react\";\nimport * as React from \"react\";\n\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { useVisibilityPause } from \"@/hooks/use-visibility-pause\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface LoupeProps extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"children\"> {\n  /** The surface to inspect — an image, an SVG, or any React subtree. */\n  children: React.ReactNode;\n  /** Magnification inside the lens. @default 1.6 */\n  zoom?: number;\n  /** Lens diameter, in px. @default 176 */\n  size?: number;\n  /** Pin the lens at a fixed spot instead of tracking the pointer. @default false */\n  pinned?: boolean;\n  /** Lens center as fractions of the surface (0–1) while `pinned`. @default { x: 0.5, y: 0.5 } */\n  pinnedPosition?: { x: number; y: number };\n  /** Controlled active state — when set, overrides internal hover/focus. */\n  active?: boolean;\n  /** Fires whenever the lens opens or closes (pointer, focus, or keyboard). */\n  onActiveChange?: (active: boolean) => void;\n  /** Softly blur + dim the surface outside the lens while it is active. @default true */\n  focusBlur?: boolean;\n  /** Blur radius, in px, applied behind an active lens. @default 2 */\n  focusBlurStrength?: number;\n  /** Play the fast scale-settle entrance when the lens appears. @default true */\n  animateEntrance?: boolean;\n  /** Pixels the lens walks per arrow-key press while focused. @default 24 */\n  keyboardStep?: number;\n  /** Rim + specular color of the machined bezel. @default \"rgba(255,255,255,0.72)\" */\n  rimColor?: string;\n  /**\n   * Idle autoplay: after 1.5s with no pointer or focus, a ghost lens drifts\n   * slowly over the surface (no focus-blur, no `onActiveChange`), so the\n   * effect sells itself in thumbnails and heroes. A real pointer or focus\n   * takes over instantly. Ignored while `pinned` or controlled via `active`;\n   * off under reduced motion; sleeps offscreen. Set `false` for zero idle\n   * work. @default true\n   */\n  idle?: boolean;\n}\n\nconst IDLE_MS = 1500;\n\nconst FOLLOW = { stiffness: 520, damping: 42, mass: 0.6 } as const;\n\nfunction clamp(v: number, lo: number, hi: number) {\n  return v < lo ? lo : v > hi ? hi : v;\n}\n\n/**\n * Loupe — a jeweler's magnifier for any child. Hovering summons a circular\n * lens that shows the underlying content enlarged; the lens follows the pointer\n * with a whisper of spring-smoothing, or sits pinned at a fixed coordinate.\n *\n * Crucible signature: a machined bezel, not a comedy magnifying glass —\n * neutral hue family. A hairline bright rim, a ground-glass edge falloff, and a\n * single almost-subliminal specular arc along the upper-left rim that drifts\n * with pointer velocity, selling curved glass with no rainbow fringing. While\n * active, the surface outside the lens softly blurs to concentrate attention.\n * Keyboard: focusing the wrapper opens the lens centered and arrow keys walk\n * it in steps. Reduced motion keeps full magnification (it is positional, not a\n * flourish) but drops the follow-smoothing, entrance scale, and rim-arc drift —\n * the lens simply snaps. Pure transform/clip compositing, zero canvas.\n * Untouched, a ghost lens idles across the surface (`idle`); with `idle={false}`\n * there is no work at all while unhovered.\n */\nexport function Loupe({\n  children,\n  className,\n  zoom = 1.6,\n  size = 176,\n  pinned = false,\n  pinnedPosition = { x: 0.5, y: 0.5 },\n  active: controlledActive,\n  onActiveChange,\n  focusBlur = true,\n  focusBlurStrength = 2,\n  animateEntrance = true,\n  keyboardStep = 24,\n  rimColor = \"rgba(255,255,255,0.72)\",\n  idle = true,\n  ...props\n}: LoupeProps) {\n  const reducedMotion = useReducedMotion();\n  const r = size / 2;\n\n  const [surface, setSurface] = React.useState({ w: 0, h: 0 });\n  const [internalActive, setInternalActive] = React.useState(false);\n  const [ghosting, setGhosting] = React.useState(false);\n  const isControlled = controlledActive !== undefined;\n  const userActive = pinned || (isControlled ? (controlledActive as boolean) : internalActive);\n  const active = userActive || ghosting;\n\n  const px = pinnedPosition.x;\n  const py = pinnedPosition.y;\n\n  // Raw pointer/keyboard center, in px within the surface.\n  const cx = useMotionValue(0);\n  const cy = useMotionValue(0);\n  // Spring-smoothed follow. Under reduced motion we read the raw value directly.\n  const scx = useSpring(cx, FOLLOW);\n  const scy = useSpring(cy, FOLLOW);\n  const posX = reducedMotion ? cx : scx;\n  const posY = reducedMotion ? cy : scy;\n\n  // Lens box (top-left) and the magnified copy's transform derive from the same\n  // smoothed center, so glass and content never disagree.\n  const lensLeft = useTransform(posX, (v) => v - r);\n  const lensTop = useTransform(posY, (v) => v - r);\n  const innerX = useTransform(posX, (v) => r - v * zoom);\n  const innerY = useTransform(posY, (v) => r - v * zoom);\n  const innerTransform = useMotionTemplate`translate(${innerX}px, ${innerY}px) scale(${zoom})`;\n\n  // Specular arc drifts a few degrees off horizontal pointer velocity.\n  const vx = useVelocity(scx);\n  const arcDrift = useTransform(vx, (v) => clamp(v * 0.012, -16, 16));\n  const arcAngle = useTransform(arcDrift, (d) => -132 + d);\n\n  // ---- idle ghost --------------------------------------------------------\n  const ghostEnabled = idle && !pinned && !isControlled && !reducedMotion;\n  const lastPointerRef = React.useRef(0);\n  const ghostOnRef = React.useRef(false);\n  const userActiveRef = React.useRef(userActive);\n  const surfaceRef = React.useRef(surface);\n  React.useEffect(() => {\n    userActiveRef.current = userActive;\n    surfaceRef.current = surface;\n  }, [userActive, surface]);\n\n  const wrapperRef = useVisibilityPause<HTMLDivElement>(\n    (elapsed) => {\n      const { w, h } = surfaceRef.current;\n      const want =\n        !userActiveRef.current && w > 0 && performance.now() - lastPointerRef.current > IDLE_MS;\n      if (!want) {\n        if (ghostOnRef.current) {\n          ghostOnRef.current = false;\n          setGhosting(false);\n        }\n        return;\n      }\n      // Slow Lissajous over the surface, kept a lens-radius-ish off the edges.\n      const mx = Math.min(r * 0.8, w * 0.3);\n      const my = Math.min(r * 0.8, h * 0.3);\n      const x = mx + (w - 2 * mx) * (0.5 + 0.5 * Math.sin(elapsed * 0.33 + 0.6));\n      const y = my + (h - 2 * my) * (0.5 + 0.5 * Math.sin(elapsed * 0.23 + 2.2));\n      cx.set(x);\n      cy.set(y);\n      if (!ghostOnRef.current) {\n        ghostOnRef.current = true;\n        // Appear in place rather than swooping in from the last position.\n        scx.jump(x);\n        scy.jump(y);\n        setGhosting(true);\n      }\n    },\n    { paused: !ghostEnabled }\n  );\n\n  React.useEffect(() => {\n    lastPointerRef.current = performance.now();\n    if (!ghostEnabled && ghostOnRef.current) {\n      ghostOnRef.current = false;\n      setGhosting(false);\n    }\n  }, [ghostEnabled]);\n\n  const markPointer = React.useCallback(() => {\n    lastPointerRef.current = performance.now();\n    if (ghostOnRef.current) {\n      ghostOnRef.current = false;\n      setGhosting(false);\n    }\n  }, []);\n\n  const emitActive = React.useCallback(\n    (next: boolean) => {\n      if (!isControlled) setInternalActive(next);\n      onActiveChange?.(next);\n    },\n    [isControlled, onActiveChange]\n  );\n\n  // Measure the surface so the magnified copy can be sized 1:1 to it.\n  React.useEffect(() => {\n    const el = wrapperRef.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) => {\n      const { width, height } = entry.contentRect;\n      setSurface({ w: width, h: height });\n    });\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [wrapperRef]);\n\n  // Keep the pinned lens parked on its coordinate as the surface resizes.\n  React.useEffect(() => {\n    if (!pinned || surface.w === 0) return;\n    cx.set(clamp(px, 0, 1) * surface.w);\n    cy.set(clamp(py, 0, 1) * surface.h);\n  }, [pinned, px, py, surface.w, surface.h, cx, cy]);\n\n  const setCenter = React.useCallback(\n    (nx: number, ny: number) => {\n      cx.set(clamp(nx, 0, surface.w));\n      cy.set(clamp(ny, 0, surface.h));\n    },\n    [cx, cy, surface.w, surface.h]\n  );\n\n  const handlePointerMove = React.useCallback(\n    (event: React.PointerEvent<HTMLDivElement>) => {\n      if (pinned || event.pointerType === \"touch\") return;\n      const node = wrapperRef.current;\n      if (!node) return;\n      const rect = node.getBoundingClientRect();\n      const x = event.clientX - rect.left;\n      const y = event.clientY - rect.top;\n      if (ghostOnRef.current) {\n        // Pointer began inside (no enter event): take over from the ghost.\n        scx.jump(x);\n        scy.jump(y);\n        if (!internalActive) emitActive(true);\n      }\n      markPointer();\n      cx.set(x);\n      cy.set(y);\n    },\n    [pinned, cx, cy, scx, scy, wrapperRef, markPointer, internalActive, emitActive]\n  );\n\n  const handlePointerEnter = React.useCallback(\n    (event: React.PointerEvent<HTMLDivElement>) => {\n      if (pinned || event.pointerType === \"touch\") return;\n      markPointer();\n      const node = wrapperRef.current;\n      if (node) {\n        const rect = node.getBoundingClientRect();\n        const x = event.clientX - rect.left;\n        const y = event.clientY - rect.top;\n        cx.set(x);\n        cy.set(y);\n        // Seat the smoothed follow at the entry point so the lens appears\n        // under the cursor instead of swooping in from its last position.\n        scx.jump(x);\n        scy.jump(y);\n      }\n      emitActive(true);\n    },\n    [pinned, cx, cy, scx, scy, emitActive, wrapperRef, markPointer]\n  );\n\n  const handlePointerLeave = React.useCallback(\n    (event: React.PointerEvent<HTMLDivElement>) => {\n      if (pinned || event.pointerType === \"touch\") return;\n      lastPointerRef.current = performance.now();\n      // Keep the lens up if focus is still driving it via keyboard.\n      if (wrapperRef.current?.contains(document.activeElement)) return;\n      emitActive(false);\n    },\n    [pinned, emitActive, wrapperRef]\n  );\n\n  const handleFocus = React.useCallback(() => {\n    if (pinned) return;\n    markPointer();\n    // Focusing places the lens dead-center, ready to walk with the arrows.\n    // Skip the re-centering when a hover already opened the lens (a click\n    // focuses the wrapper too — the lens must stay under the cursor).\n    if (userActive) return;\n    setCenter(surface.w / 2, surface.h / 2);\n    scx.jump(clamp(surface.w / 2, 0, surface.w));\n    scy.jump(clamp(surface.h / 2, 0, surface.h));\n    emitActive(true);\n  }, [pinned, userActive, setCenter, surface.w, surface.h, scx, scy, emitActive, markPointer]);\n\n  const handleBlur = React.useCallback(() => {\n    if (pinned) return;\n    lastPointerRef.current = performance.now();\n    emitActive(false);\n  }, [pinned, emitActive]);\n\n  const handleKeyDown = React.useCallback(\n    (event: React.KeyboardEvent<HTMLDivElement>) => {\n      if (pinned) return;\n      const step = keyboardStep;\n      let handled = true;\n      switch (event.key) {\n        case \"ArrowLeft\":\n          setCenter(cx.get() - step, cy.get());\n          break;\n        case \"ArrowRight\":\n          setCenter(cx.get() + step, cy.get());\n          break;\n        case \"ArrowUp\":\n          setCenter(cx.get(), cy.get() - step);\n          break;\n        case \"ArrowDown\":\n          setCenter(cx.get(), cy.get() + step);\n          break;\n        case \"Home\":\n          setCenter(0, 0);\n          break;\n        case \"End\":\n          setCenter(surface.w, surface.h);\n          break;\n        case \"Escape\":\n          (event.currentTarget as HTMLDivElement).blur();\n          break;\n        default:\n          handled = false;\n      }\n      if (handled) event.preventDefault();\n    },\n    [pinned, keyboardStep, setCenter, cx, cy, surface.w, surface.h]\n  );\n\n  const showLens = active && surface.w > 0;\n\n  return (\n    <div\n      ref={wrapperRef}\n      data-crucible=\"loupe\"\n      tabIndex={0}\n      role=\"group\"\n      aria-label=\"Magnifiable surface — focus and use arrow keys to inspect\"\n      className={cn(\n        \"relative isolate overflow-hidden rounded-xl outline-none\",\n        \"focus-visible:ring-2 focus-visible:ring-white/60 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-950\",\n        className\n      )}\n      onPointerMove={handlePointerMove}\n      onPointerEnter={handlePointerEnter}\n      onPointerLeave={handlePointerLeave}\n      onFocus={handleFocus}\n      onBlur={handleBlur}\n      onKeyDown={handleKeyDown}\n      {...props}\n    >\n      {/* Base surface — blurs and dims a touch while the lens is up. */}\n      <div\n        className=\"h-full w-full\"\n        style={{\n          filter: focusBlur && userActive ? `blur(${focusBlurStrength}px) brightness(0.82)` : \"none\",\n          transition: reducedMotion ? \"none\" : \"filter 0.28s ease\",\n          willChange: \"filter\",\n        }}\n      >\n        {children}\n      </div>\n\n      <AnimatePresence>\n        {showLens && (\n          <motion.div\n            key=\"lens\"\n            aria-hidden\n            initial={\n              !animateEntrance || reducedMotion\n                ? { opacity: 0, scale: 1 }\n                : { opacity: 0, scale: 0.92 }\n            }\n            animate={{ opacity: 1, scale: 1 }}\n            exit={{ opacity: 0, scale: reducedMotion ? 1 : 0.98 }}\n            transition={{\n              opacity: { duration: 0.14, ease: \"easeOut\" },\n              scale: reducedMotion\n                ? { duration: 0 }\n                : { type: \"spring\", stiffness: 520, damping: 30, mass: 0.6 },\n            }}\n            className=\"pointer-events-none absolute overflow-hidden rounded-full\"\n            style={{\n              left: lensLeft,\n              top: lensTop,\n              width: size,\n              height: size,\n              backgroundColor: \"rgb(10 10 12)\",\n              boxShadow:\n                \"0 12px 34px -10px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.06)\",\n            }}\n          >\n            {/* Magnified copy, sized 1:1 to the surface then scaled. */}\n            <motion.div\n              className=\"absolute top-0 left-0\"\n              style={{\n                width: surface.w,\n                height: surface.h,\n                transformOrigin: \"0 0\",\n                transform: innerTransform,\n              }}\n            >\n              {children}\n            </motion.div>\n\n            {/* Ground-glass edge falloff + a soft top-left sheen. */}\n            <div\n              className=\"pointer-events-none absolute inset-0 rounded-full\"\n              style={{\n                background:\n                  \"radial-gradient(circle at 50% 50%, transparent 54%, rgba(0,0,0,0.28) 100%), radial-gradient(circle at 32% 28%, rgba(255,255,255,0.10), transparent 46%)\",\n              }}\n            />\n\n            {/* Specular arc riding the upper-left rim; drifts with velocity. */}\n            <motion.div\n              className=\"pointer-events-none absolute inset-0 rounded-full\"\n              style={{\n                rotate: reducedMotion ? -132 : arcAngle,\n                background: `conic-gradient(from 0deg at 50% 50%, transparent 0deg, ${rimColor} 26deg, rgba(255,255,255,0.05) 70deg, transparent 120deg, transparent 360deg)`,\n                WebkitMask:\n                  \"radial-gradient(farthest-side, transparent calc(100% - 2.5px), #000 calc(100% - 2.5px))\",\n                mask: \"radial-gradient(farthest-side, transparent calc(100% - 2.5px), #000 calc(100% - 2.5px))\",\n                opacity: 0.9,\n              }}\n            />\n\n            {/* Hairline machined rim. */}\n            <div\n              className=\"pointer-events-none absolute inset-0 rounded-full\"\n              style={{\n                boxShadow: `inset 0 0 0 1px ${rimColor}, inset 0 0 12px rgba(0,0,0,0.35)`,\n              }}\n            />\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n"
    }
  ]
}