{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"lens-reveal","type":"registry:component","title":"Lens reveal","description":"A lens follows your cursor and shows the specs hidden under a card.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/lens-reveal.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport {\n  animate,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useSpring,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// Resting lens, the slightly larger one while hovering, and the big one a\n// click toggles. Entering grows 56 to 72 rather than from nothing, so the\n// lens arrives like a material, not a point.\nconst R_ENTER = 56;\nconst R_HOVER = 72;\nconst R_BIG = 118;\n// Trails the pointer by a hair: enough to feel like a physical lens with\n// weight, never enough to feel laggy. Critically damped, it never overshoots\n// the thing it is following.\nconst FOLLOW = { stiffness: 520, damping: 46 };\nconst GROW = { type: \"spring\", visualDuration: 0.3, bounce: 0 } as const;\nconst SHRINK = { type: \"spring\", visualDuration: 0.2, bounce: 0 } as const;\n// Leaves faster than it arrives: the exit should never hold the eye.\nconst FADE_IN = { duration: 0.18, ease: [0.23, 1, 0.32, 1] } as const;\nconst FADE_OUT = { duration: 0.12, ease: [0.23, 1, 0.32, 1] } as const;\n// Arrow keys move the lens this far; Shift moves it further.\nconst KEY_STEP = 24;\nconst KEY_STEP_FAR = 72;\n\nexport function LensReveal({\n  base,\n  hidden,\n  label,\n  description,\n  className,\n}: {\n  base: React.ReactNode;\n  hidden: React.ReactNode;\n  label: string;\n  // Spoken to screen readers, since the hidden layer can't be seen by them.\n  description: string;\n  className?: string;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  const hintId = useId();\n  const ref = useRef<HTMLDivElement>(null);\n  // Where the lens should be; the springs below chase it.\n  const aimX = useMotionValue(0);\n  const aimY = useMotionValue(0);\n  const x = useSpring(aimX, FOLLOW);\n  const y = useSpring(aimY, FOLLOW);\n  const radius = useMotionValue(R_ENTER);\n  const shown = useMotionValue(0);\n  const [big, setBig] = useState(false);\n  const bigRef = useRef(false);\n  const inside = useRef(false);\n  const touch = useRef<number | null>(null);\n  // Where the press started, so a drag that ends on the surface isn't also\n  // read as a click that resizes the lens.\n  const press = useRef<[number, number] | null>(null);\n\n  const clip = useMotionTemplate`circle(${radius}px at ${x}px ${y}px)`;\n\n  useEffect(\n    () => () => {\n      radius.stop();\n      shown.stop();\n    },\n    [radius, shown],\n  );\n\n  const restRadius = () => (bigRef.current ? R_BIG : R_HOVER);\n\n  const moveTo = (px: number, py: number, instant: boolean) => {\n    aimX.set(px);\n    aimY.set(py);\n    // Jumping on entry keeps the lens from sweeping in from its last spot.\n    if (instant || reduce) {\n      x.jump(px);\n      y.jump(py);\n    }\n  };\n\n  const show = () => {\n    if (inside.current) return;\n    inside.current = true;\n    if (reduce) {\n      radius.jump(restRadius());\n    } else {\n      radius.jump(R_ENTER);\n      animate(radius, restRadius(), GROW);\n    }\n    animate(shown, 1, FADE_IN);\n  };\n\n  const hide = () => {\n    if (!inside.current) return;\n    inside.current = false;\n    if (!reduce) animate(radius, R_ENTER, SHRINK);\n    animate(shown, 0, FADE_OUT);\n  };\n\n  const toggleBig = () => {\n    bigRef.current = !bigRef.current;\n    setBig(bigRef.current);\n    if (!inside.current) return;\n    if (reduce) radius.jump(restRadius());\n    else animate(radius, restRadius(), bigRef.current ? GROW : SHRINK);\n  };\n\n  const local = (e: React.PointerEvent) => {\n    const box = ref.current!.getBoundingClientRect();\n    return [e.clientX - box.left, e.clientY - box.top] as const;\n  };\n\n  return (\n    <div\n      ref={ref}\n      role=\"group\"\n      aria-roledescription=\"lens\"\n      aria-label={label}\n      aria-describedby={hintId}\n      tabIndex={0}\n      className={cn(\n        // touch-none: a finger on the surface steers the lens, so the page\n        // shouldn't scroll out from under it.\n        \"relative h-[300px] w-[min(480px,100%)] touch-none overflow-hidden rounded-2xl shadow-raised outline-hidden select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground\",\n        className,\n      )}\n      onPointerEnter={(e) => {\n        if (e.pointerType === \"touch\") return;\n        const [px, py] = local(e);\n        moveTo(px, py, true);\n        show();\n      }}\n      onPointerMove={(e) => {\n        if (e.pointerType === \"touch\" && touch.current !== e.pointerId) return;\n        const [px, py] = local(e);\n        moveTo(px, py, false);\n        show();\n      }}\n      onPointerLeave={(e) => {\n        if (e.pointerType !== \"touch\") hide();\n      }}\n      onPointerDown={(e) => {\n        press.current = [e.clientX, e.clientY];\n        if (e.pointerType !== \"touch\" || touch.current !== null) return;\n        touch.current = e.pointerId;\n        e.currentTarget.setPointerCapture(e.pointerId);\n        const [px, py] = local(e);\n        moveTo(px, py, true);\n        show();\n      }}\n      onPointerUp={(e) => {\n        if (touch.current === e.pointerId) touch.current = null;\n      }}\n      onPointerCancel={(e) => {\n        if (touch.current !== e.pointerId) return;\n        touch.current = null;\n        hide();\n      }}\n      onClick={(e) => {\n        const p = press.current;\n        press.current = null;\n        // Past 6px the finger was steering the lens, not tapping it.\n        if (p && Math.hypot(e.clientX - p[0], e.clientY - p[1]) > 6) return;\n        toggleBig();\n      }}\n      onFocus={(e) => {\n        // Keyboard arrival: open the lens in the middle so arrows have\n        // something to move. Mouse focus already has one under the pointer.\n        if (inside.current || !e.currentTarget.matches(\":focus-visible\")) return;\n        const box = e.currentTarget.getBoundingClientRect();\n        moveTo(box.width / 2, box.height / 2, true);\n        show();\n      }}\n      onBlur={() => {\n        if (touch.current === null) hide();\n      }}\n      onKeyDown={(e) => {\n        if (e.key === \"Enter\" || e.key === \" \") {\n          e.preventDefault();\n          if (!inside.current) show();\n          toggleBig();\n          return;\n        }\n        if (e.key === \"Escape\") {\n          hide();\n          return;\n        }\n        const delta = {\n          ArrowLeft: [-1, 0],\n          ArrowRight: [1, 0],\n          ArrowUp: [0, -1],\n          ArrowDown: [0, 1],\n        }[e.key];\n        if (!delta) return;\n        e.preventDefault();\n        const box = e.currentTarget.getBoundingClientRect();\n        const step = e.shiftKey ? KEY_STEP_FAR : KEY_STEP;\n        // Starts from the aim, not the trailing spring, so held keys glide\n        // at a steady pace instead of stalling behind the lens.\n        const px = Math.min(Math.max(aimX.get() + delta[0] * step, 0), box.width);\n        const py = Math.min(Math.max(aimY.get() + delta[1] * step, 0), box.height);\n        moveTo(px, py, false);\n        show();\n      }}\n    >\n      <div className=\"absolute inset-0\">{base}</div>\n      <motion.div\n        aria-hidden\n        className=\"absolute inset-0\"\n        style={{ clipPath: clip, opacity: shown }}\n      >\n        {hidden}\n      </motion.div>\n      {/* The rim sells it as glass sitting over the page, not a hole cut in\n          it. Drawn in SVG so its stroke stays 1px at every radius. */}\n      <motion.svg\n        aria-hidden\n        className=\"pointer-events-none absolute inset-0 size-full overflow-visible text-foreground\"\n        style={{ opacity: shown }}\n      >\n        <motion.circle\n          cx={x}\n          cy={y}\n          r={radius}\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeOpacity={0.18}\n          strokeWidth={1}\n        />\n      </motion.svg>\n      <span id={hintId} className=\"sr-only\">\n        {description} Arrow keys move the lens, Enter makes it larger.\n      </span>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {big ? \"Large lens\" : \"\"}\n      </span>\n    </div>\n  );\n}\n\n// The same card drawn twice. The annotated copy only adds absolutely\n// positioned marks on top, so both layers line up to the pixel.\nfunction Specimen({ annotated = false }: { annotated?: boolean }) {\n  return (\n    <div\n      className={cn(\n        \"flex size-full items-center justify-center p-6\",\n        annotated ? \"bg-foreground text-background\" : \"bg-muted text-foreground\",\n      )}\n    >\n      <div\n        className={cn(\n          \"relative w-[min(300px,100%)] rounded-2xl p-5\",\n          annotated\n            ? \"outline outline-1 -outline-offset-1 outline-background/40 outline-dashed\"\n            : \"bg-background shadow-raised\",\n        )}\n      >\n        {annotated && (\n          <>\n            <Spec className=\"-top-5 left-0\">radius 16 / padding 20</Spec>\n            {/* Padding bands, shaded where the content can't go. */}\n            <span className=\"absolute inset-x-0 top-0 h-5 rounded-t-2xl bg-background/10\" />\n            <span className=\"absolute inset-x-0 bottom-0 h-5 rounded-b-2xl bg-background/10\" />\n            <span className=\"absolute inset-y-5 left-0 w-5 bg-background/10\" />\n            <span className=\"absolute inset-y-5 right-0 w-5 bg-background/10\" />\n          </>\n        )}\n        <div className=\"relative flex items-center gap-3\">\n          <span\n            className={cn(\n              \"relative size-9 shrink-0 rounded-full\",\n              annotated\n                ? \"outline outline-1 -outline-offset-1 outline-background/50 outline-dashed\"\n                : \"bg-foreground/10\",\n            )}\n          >\n            {annotated && <Spec className=\"top-full left-0 mt-1\">36</Spec>}\n          </span>\n          <span className=\"relative\">\n            <span className=\"block text-sm font-medium\">Ada Sørensen</span>\n            <span\n              className={cn(\n                \"block text-xs\",\n                annotated ? \"text-background/60\" : \"text-muted-foreground\",\n              )}\n            >\n              2 min read\n            </span>\n            {annotated && <Spec className=\"top-0 left-full ml-3\">gap 12</Spec>}\n          </span>\n        </div>\n        <p className=\"relative mt-4 text-lg leading-snug font-semibold tracking-tight text-balance\">\n          Springs are behaviour, not a timeline.\n          {annotated && <Mark>18 / 1.375 / 600</Mark>}\n        </p>\n        <p\n          className={cn(\n            \"relative mt-1.5 text-sm leading-normal text-pretty\",\n            annotated ? \"text-background/70\" : \"text-muted-foreground\",\n          )}\n        >\n          A target that moves mid-flight bends the path instead of restarting\n          it.\n          {annotated && <Mark below>14 / 1.5 / 400</Mark>}\n        </p>\n      </div>\n    </div>\n  );\n}\n\nfunction Spec({\n  className,\n  children,\n}: {\n  className?: string;\n  children: React.ReactNode;\n}) {\n  return (\n    <span\n      className={cn(\n        \"absolute font-mono text-xs whitespace-nowrap text-background/70\",\n        className,\n      )}\n    >\n      {children}\n    </span>\n  );\n}\n\n// Outlines the text block and tags its type spec on the edge facing open\n// space, so the tag never covers a neighbouring line.\nfunction Mark({\n  below = false,\n  children,\n}: {\n  below?: boolean;\n  children: React.ReactNode;\n}) {\n  return (\n    <span className=\"absolute -inset-1 rounded-md outline outline-1 outline-background/40 outline-dashed\">\n      <span\n        className={cn(\n          \"absolute right-1 bg-foreground px-1 font-mono text-xs leading-4 font-normal tracking-normal text-background/70\",\n          below ? \"top-full -translate-y-1/2\" : \"top-0 -translate-y-1/2\",\n        )}\n      >\n        {children}\n      </span>\n    </span>\n  );\n}\n\nexport default function LensRevealDemo() {\n  return (\n    <LensReveal\n      label=\"Card specimen\"\n      description=\"Under the lens, the card shows its specs: 16px radius, 20px padding, a 36px avatar, 18px semibold title and 14px body.\"\n      base={<Specimen />}\n      hidden={<Specimen annotated />}\n    />\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["cards"],"docs":"From ui lab: https://lab.xevrion.dev/lab/lens-reveal"}