{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pixelate-hover-card",
  "title": "Pixelate Hover Card",
  "description": "A photo card that breaks into a chunky pixel mosaic on hover and resolves into a second photo, or comes into focus from pixels, drawn on a canvas in stepped block sizes with a live pixel-size readout, touch and keyboard support and a reduced-motion crossfade.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/pixelate-hover-card/pixelate-hover-card.tsx",
      "content": "\"use client\";\n/* eslint-disable @next/next/no-img-element -- Registry components work in any React app. */\n\nimport * as React from \"react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\n/**\n * swap: the photo breaks into pixels and resolves into hoverImage.\n * sharpen: the photo rests pixelated and comes into focus on hover.\n * pixelate: the photo rests sharp and breaks into pixels on hover.\n */\nexport type PixelateMode = \"swap\" | \"sharpen\" | \"pixelate\";\nexport type PixelateTheme = \"dark\" | \"light\";\n\nexport interface PixelateHoverCardProps extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"title\" | \"children\"> {\n  image?: string;\n  hoverImage?: string;\n  imageAlt?: string;\n  mode?: PixelateMode;\n  title?: string;\n  subtitle?: string;\n  /** Small mono label top-left, e.g. \"Series 01\". */\n  label?: string;\n  href?: string;\n  /** Largest pixel size in CSS px. */\n  maxBlock?: number;\n  /** Full transition time in ms. */\n  duration?: number;\n  /** Show the live pixel-size readout. */\n  showReadout?: boolean;\n  /** Width / height of the card. */\n  aspectRatio?: number;\n  radius?: number;\n  theme?: PixelateTheme;\n}\n\nconst STEPS = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64];\n\n/** Progress 0..1 → a pixel size snapped to a chunky step, so it reads as discrete mosaic levels. */\nfunction blockAt(amount: number, maxBlock: number) {\n  if (amount <= 0) return 1;\n  const raw = 1 + Math.pow(amount, 1.6) * (maxBlock - 1);\n  let best = 1;\n  for (const step of STEPS) if (step <= raw && step <= maxBlock) best = step;\n  return best;\n}\n\nfunction drawCover(ctx: CanvasRenderingContext2D, img: HTMLImageElement, w: number, h: number) {\n  const scale = Math.max(w / img.naturalWidth, h / img.naturalHeight);\n  const sw = w / scale;\n  const sh = h / scale;\n  ctx.drawImage(img, (img.naturalWidth - sw) / 2, (img.naturalHeight - sh) / 2, sw, sh, 0, 0, w, h);\n}\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nexport function PixelateHoverCard({\n  image = \"/demo/5.webp\",\n  hoverImage = \"/demo/8.webp\",\n  imageAlt = \"\",\n  mode = \"swap\",\n  title = \"Quiet rooms\",\n  subtitle = \"Interiors · 12 frames\",\n  label = \"Series 01\",\n  href,\n  maxBlock = 32,\n  duration = 640,\n  showReadout = true,\n  aspectRatio = 4 / 5,\n  radius = 18,\n  theme = \"dark\",\n  className,\n  style,\n  ...props\n}: PixelateHoverCardProps) {\n  const reduce = useReducedMotion();\n  const swap = mode === \"swap\" && Boolean(hoverImage);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const readoutRef = React.useRef<HTMLSpanElement>(null);\n  const frameRef = React.useRef<HTMLSpanElement>(null);\n  const images = React.useRef<(HTMLImageElement | null)[]>([null, null]);\n  const progress = React.useRef(0);\n  const target = React.useRef(0);\n  const raf = React.useRef(0);\n  const last = React.useRef(0);\n  const drawRef = React.useRef<() => void>(() => {});\n  const [ready, setReady] = React.useState(false);\n  const [active, setActive] = React.useState(false);\n\n  // What the canvas should show for the current progress: which photo, and how big its pixels are.\n  const state = React.useCallback(\n    (p: number) => {\n      if (swap) return p < 0.5 ? { index: 0, block: blockAt(p * 2, maxBlock) } : { index: 1, block: blockAt((1 - p) * 2, maxBlock) };\n      if (mode === \"sharpen\") return { index: 0, block: blockAt(1 - p, maxBlock) };\n      return { index: 0, block: blockAt(p, maxBlock) };\n    },\n    [swap, mode, maxBlock],\n  );\n\n  React.useEffect(() => {\n    const canvas = canvasRef.current;\n    const box = boxRef.current;\n    if (!canvas || !box) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n    const small = document.createElement(\"canvas\");\n    const sctx = small.getContext(\"2d\");\n    let drawn = \"\";\n\n    const draw = () => {\n      const { index, block } = state(progress.current);\n      const img = images.current[index] ?? images.current[0];\n      if (readoutRef.current) readoutRef.current.textContent = block.toString().padStart(2, \"0\");\n      if (frameRef.current) frameRef.current.textContent = `0${index + 1}`;\n      if (!img || !img.complete || !img.naturalWidth) return;\n      const w = canvas.width;\n      const h = canvas.height;\n      const key = `${index}:${block}:${w}x${h}`;\n      if (key === drawn) return;\n      drawn = key;\n      const dpr = w / Math.max(1, box.clientWidth);\n      if (block <= 1 || !sctx) {\n        ctx.imageSmoothingEnabled = true;\n        drawCover(ctx, img, w, h);\n        return;\n      }\n      // Draw the photo tiny, then blow it up with smoothing off: every source pixel becomes one square block.\n      const px = block * dpr;\n      small.width = Math.max(1, Math.ceil(w / px));\n      small.height = Math.max(1, Math.ceil(h / px));\n      sctx.imageSmoothingEnabled = true;\n      drawCover(sctx, img, small.width, small.height);\n      ctx.imageSmoothingEnabled = false;\n      ctx.clearRect(0, 0, w, h);\n      ctx.drawImage(small, 0, 0, small.width, small.height, 0, 0, small.width * px, small.height * px);\n    };\n    drawRef.current = draw;\n\n    const resize = () => {\n      const dpr = Math.min(window.devicePixelRatio || 1, 2);\n      canvas.width = Math.max(1, Math.round(box.clientWidth * dpr));\n      canvas.height = Math.max(1, Math.round(box.clientHeight * dpr));\n      drawn = \"\";\n      draw();\n    };\n    const observer = new ResizeObserver(resize);\n    observer.observe(box);\n\n    let alive = true;\n    const sources = swap ? [image, hoverImage] : [image];\n    images.current = [null, null];\n    let loaded = 0;\n    sources.forEach((src, i) => {\n      const img = new Image();\n      img.decoding = \"async\";\n      img.onload = () => {\n        if (!alive) return;\n        images.current[i] = img;\n        loaded += 1;\n        drawn = \"\";\n        draw();\n        if (loaded === sources.length) setReady(true);\n      };\n      img.src = src!;\n    });\n    resize();\n    return () => {\n      alive = false;\n      observer.disconnect();\n      cancelAnimationFrame(raf.current);\n    };\n  }, [image, hoverImage, swap, state]);\n\n  const animate = React.useCallback(() => {\n    cancelAnimationFrame(raf.current);\n    last.current = performance.now();\n    const tick = (now: number) => {\n      const dt = Math.min(64, now - last.current);\n      last.current = now;\n      const step = dt / Math.max(1, duration);\n      const p = progress.current;\n      progress.current = target.current > p ? Math.min(target.current, p + step) : Math.max(target.current, p - step);\n      drawRef.current();\n      if (progress.current !== target.current) raf.current = requestAnimationFrame(tick);\n    };\n    raf.current = requestAnimationFrame(tick);\n  }, [duration]);\n\n  const setHover = (on: boolean) => {\n    setActive(on);\n    target.current = on ? 1 : 0;\n    if (reduce) {\n      progress.current = target.current;\n      drawRef.current();\n    } else animate();\n  };\n\n  // The resting state for \"sharpen\" is pixelated, so the first paint has to start there too.\n  const restingPixelated = mode === \"sharpen\";\n  const Root = href ? \"a\" : \"div\";\n\n  return (\n    <div className={cn(\"relative w-full\", className)} style={{ aspectRatio, ...style }} {...props}>\n      <Root\n        {...(href ? { href } : { tabIndex: 0, role: \"group\", \"aria-label\": title })}\n        className=\"group/px absolute inset-0 block cursor-pointer overflow-hidden outline-none select-none focus-visible:ring-2 focus-visible:ring-offset-2\"\n        style={{\n          borderRadius: radius,\n          background: theme === \"light\" ? \"#e9e9e6\" : \"#151515\",\n          [\"--tw-ring-color\" as string]: theme === \"light\" ? \"#141414\" : \"#f4f4f2\",\n          [\"--tw-ring-offset-color\" as string]: theme === \"light\" ? \"#f1f1ef\" : \"#0a0a0a\",\n        }}\n        onPointerEnter={(event: React.PointerEvent) => event.pointerType === \"mouse\" && setHover(true)}\n        onPointerLeave={(event: React.PointerEvent) => event.pointerType === \"mouse\" && setHover(false)}\n        onPointerDown={(event: React.PointerEvent) => {\n          if (event.pointerType !== \"mouse\") setHover(target.current < 0.5);\n        }}\n        onFocus={(event: React.FocusEvent<HTMLElement>) => event.currentTarget.matches(\":focus-visible\") && setHover(true)}\n        onBlur={() => setHover(false)}\n      >\n        <div ref={boxRef} className=\"absolute inset-0\">\n          {/* Plain images under the canvas: what shows before it is ready, and the reduced-motion crossfade. */}\n          <img src={image} alt={imageAlt} draggable={false} className=\"absolute inset-0 h-full w-full object-cover\" style={restingPixelated && !reduce ? { filter: \"blur(12px)\", transform: \"scale(1.08)\" } : undefined} />\n          {swap && reduce && <img src={hoverImage} alt=\"\" draggable={false} className=\"absolute inset-0 h-full w-full object-cover transition-opacity duration-500\" style={{ opacity: active ? 1 : 0 }} />}\n          <canvas ref={canvasRef} aria-hidden=\"true\" className=\"absolute inset-0 h-full w-full transition-opacity duration-300\" style={{ opacity: ready && !reduce ? 1 : 0 }} />\n        </div>\n        <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/25\" />\n\n        <div className=\"pointer-events-none absolute inset-x-0 top-0 flex items-center justify-between p-4 font-mono text-[10px] text-white\">\n          {label && <span className=\"rounded-full bg-black/35 px-2.5 py-1 backdrop-blur-md\">{label}</span>}\n          {showReadout && (\n            <span aria-hidden=\"true\" className=\"flex items-center gap-2 rounded-full bg-black/35 px-2.5 py-1 tabular-nums backdrop-blur-md\">\n              <span className=\"grid grid-cols-2 gap-px\">\n                {[0, 1, 2, 3].map((i) => (\n                  <span key={i} className={cn(\"size-[3px] bg-white\", i % 3 === 0 ? \"opacity-100\" : \"opacity-40\")} />\n                ))}\n              </span>\n              PX <span ref={readoutRef}>{restingPixelated ? blockAt(1, maxBlock).toString().padStart(2, \"0\") : \"01\"}</span>\n              {swap && (\n                <>\n                  <span className=\"text-white/40\">/</span>\n                  <span ref={frameRef}>01</span>\n                </>\n              )}\n            </span>\n          )}\n        </div>\n\n        <div className=\"pointer-events-none absolute inset-x-0 bottom-0 p-5 text-white\">\n          <h3 className=\"text-[20px] leading-tight font-medium tracking-[-0.01em]\">{title}</h3>\n          {subtitle && <p className=\"mt-1 text-[12.5px] text-white/70\">{subtitle}</p>}\n        </div>\n      </Root>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}