{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pixel-dissolve-transition",
  "title": "Pixel Dissolve Transition",
  "description": "A slideshow that changes images block by block: the frame breaks into a grid, each block flashes to the new picture's colour and then resolves into it, in a random scatter, a diagonal sweep or a ripple from the centre, with dots, arrows and autoplay.",
  "dependencies": [
    "lucide-react",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/pixel-dissolve-transition/pixel-dissolve-transition.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport interface DissolveSlide {\n  src: string;\n  alt?: string;\n  title?: string;\n  meta?: string;\n}\n\nexport type DissolveOrder = \"random\" | \"diagonal\" | \"radial\";\n\nexport interface PixelDissolveTransitionProps extends Omit<React.ComponentPropsWithoutRef<\"section\">, \"onChange\"> {\n  slides?: DissolveSlide[];\n  /** Order the blocks switch in. */\n  order?: DissolveOrder;\n  /** Block size in px. */\n  block?: number;\n  /** Transition length in ms. */\n  duration?: number;\n  /** Advance on its own every n ms (0 = off). Pauses on hover and focus. */\n  autoPlay?: number;\n  /** Width / height of the frame. */\n  aspectRatio?: number;\n  radius?: number;\n  showControls?: boolean;\n  label?: string;\n  onChange?: (index: number) => void;\n}\n\nconst SLIDES: DissolveSlide[] = [\n  { src: \"/demo/19.webp\", title: \"Still House\", meta: \"Interiors · 2026\" },\n  { src: \"/demo/108.webp\", title: \"Fast Lane\", meta: \"Motion · 2025\" },\n  { src: \"/demo/38.webp\", title: \"Faces, slowly\", meta: \"Portraits · 2026\" },\n  { src: \"/demo/2.webp\", title: \"Long Hall\", meta: \"Architecture · 2024\" },\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\n/** Draw an image to fill a w×h area, cropping like object-fit: cover. */\nfunction cover(ctx: CanvasRenderingContext2D, img: HTMLImageElement, x: number, y: number, w: number, h: number, sx = 0, sy = 0, sw = w, sh = h) {\n  const scale = Math.max(w / img.naturalWidth, h / img.naturalHeight);\n  const iw = w / scale;\n  const ih = h / scale;\n  const ox = (img.naturalWidth - iw) / 2;\n  const oy = (img.naturalHeight - ih) / 2;\n  ctx.drawImage(img, ox + (sx / w) * iw, oy + (sy / h) * ih, (sw / w) * iw, (sh / h) * ih, x, y, sw, sh);\n}\n\nexport function PixelDissolveTransition({\n  slides = SLIDES,\n  order = \"random\",\n  block = 26,\n  duration = 1100,\n  autoPlay = 0,\n  aspectRatio = 16 / 10,\n  radius = 16,\n  showControls = true,\n  label = \"Gallery\",\n  onChange,\n  className,\n  ...props\n}: PixelDissolveTransitionProps) {\n  const reduce = useReducedMotion();\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const images = React.useRef<HTMLImageElement[]>([]);\n  const shown = React.useRef(0);\n  const raf = React.useRef(0);\n  const [index, setIndex] = React.useState(0);\n  const [paused, setPaused] = React.useState(false);\n  const opts = React.useRef({ order, block, duration });\n  React.useEffect(() => {\n    opts.current = { order, block, duration };\n  }, [order, block, duration]);\n\n  const size = () => {\n    const canvas = canvasRef.current!;\n    const box = boxRef.current!;\n    const dpr = Math.min(window.devicePixelRatio || 1, 2);\n    const w = Math.max(1, Math.round(box.clientWidth * dpr));\n    const h = Math.max(1, Math.round(box.clientHeight * dpr));\n    if (canvas.width !== w || canvas.height !== h) {\n      canvas.width = w;\n      canvas.height = h;\n    }\n    return { w, h, dpr };\n  };\n\n  const drawStill = React.useCallback((i: number) => {\n    const canvas = canvasRef.current;\n    const img = images.current[i];\n    if (!canvas || !img?.complete || !img.naturalWidth) return;\n    const { w, h } = size();\n    const ctx = canvas.getContext(\"2d\")!;\n    cover(ctx, img, 0, 0, w, h);\n  }, []);\n\n  // Load every slide once; draw the first as soon as it arrives.\n  React.useEffect(() => {\n    images.current = slides.map((s, i) => {\n      const img = new Image();\n      img.decoding = \"async\";\n      img.onload = () => i === shown.current && drawStill(i);\n      img.src = s.src;\n      return img;\n    });\n    const box = boxRef.current;\n    if (!box) return;\n    const ro = new ResizeObserver(() => drawStill(shown.current));\n    ro.observe(box);\n    return () => {\n      ro.disconnect();\n      cancelAnimationFrame(raf.current);\n    };\n  }, [slides, drawStill]);\n\n  const transition = React.useCallback(\n    (from: number, to: number) => {\n      const canvas = canvasRef.current;\n      const a = images.current[from];\n      const b = images.current[to];\n      shown.current = to;\n      cancelAnimationFrame(raf.current);\n      if (!canvas || !b?.complete || !b.naturalWidth || reduce || !a?.complete) {\n        drawStill(to);\n        return;\n      }\n      const { w, h, dpr } = size();\n      const ctx = canvas.getContext(\"2d\")!;\n      const { order: ord, block: bs, duration: ms } = opts.current;\n      const cell = bs * dpr;\n      const cols = Math.ceil(w / cell);\n      const rows = Math.ceil(h / cell);\n      // The average colour of each block of the new image, for the moment a block is mid-switch.\n      let avg: Uint8ClampedArray | null = null;\n      try {\n        const small = document.createElement(\"canvas\");\n        small.width = cols;\n        small.height = rows;\n        const sctx = small.getContext(\"2d\")!;\n        cover(sctx, b, 0, 0, cols, rows);\n        avg = sctx.getImageData(0, 0, cols, rows).data;\n      } catch {\n        avg = null; // Cross-origin image without CORS: skip the solid stage.\n      }\n      const times = new Float32Array(cols * rows);\n      for (let y = 0; y < rows; y++)\n        for (let x = 0; x < cols; x++) {\n          let t: number;\n          if (ord === \"diagonal\") t = ((x / cols + y / rows) / 2) * 0.8 + Math.random() * 0.12;\n          else if (ord === \"radial\") t = Math.hypot(x / cols - 0.5, (y / rows - 0.5) * (rows / cols)) * 1.35 * 0.8 + Math.random() * 0.1;\n          else t = Math.random() * 0.82;\n          times[y * cols + x] = t;\n        }\n      const start = performance.now();\n      const solid = 0.12;\n      const tick = (now: number) => {\n        const p = (now - start) / ms;\n        cover(ctx, a, 0, 0, w, h);\n        for (let i = 0; i < times.length; i++) {\n          const t = times[i];\n          if (p < t) continue;\n          const x = (i % cols) * cell;\n          const y = Math.floor(i / cols) * cell;\n          if (p < t + solid && avg) {\n            ctx.fillStyle = `rgb(${avg[i * 4]},${avg[i * 4 + 1]},${avg[i * 4 + 2]})`;\n            ctx.fillRect(x, y, cell + 0.5, cell + 0.5);\n          } else cover(ctx, b, 0, 0, w, h, x, y, Math.min(cell + 0.5, w - x), Math.min(cell + 0.5, h - y));\n        }\n        if (p < 1.0) raf.current = requestAnimationFrame(tick);\n        else cover(ctx, b, 0, 0, w, h);\n      };\n      raf.current = requestAnimationFrame(tick);\n    },\n    [reduce, drawStill],\n  );\n\n  const go = React.useCallback(\n    (to: number) => {\n      const n = slides.length;\n      if (!n) return;\n      const next = ((to % n) + n) % n;\n      if (next === shown.current) return;\n      transition(shown.current, next);\n      setIndex(next);\n      onChange?.(next);\n    },\n    [slides.length, transition, onChange],\n  );\n\n  React.useEffect(() => {\n    if (!autoPlay || paused || reduce || slides.length < 2) return;\n    const id = window.setInterval(() => go(shown.current + 1), Math.max(autoPlay, duration + 400));\n    return () => window.clearInterval(id);\n  }, [autoPlay, paused, reduce, slides.length, duration, go]);\n\n  const current = slides[index];\n  return (\n    <section\n      aria-roledescription=\"carousel\"\n      aria-label={label}\n      className={cn(\"relative w-full\", className)}\n      onPointerEnter={() => setPaused(true)}\n      onPointerLeave={() => setPaused(false)}\n      onFocus={() => setPaused(true)}\n      onBlur={(event) => !event.currentTarget.contains(event.relatedTarget) && setPaused(false)}\n      onKeyDown={(event) => {\n        if (event.key === \"ArrowRight\") go(index + 1);\n        else if (event.key === \"ArrowLeft\") go(index - 1);\n      }}\n      {...props}\n    >\n      <div ref={boxRef} className=\"relative w-full overflow-hidden bg-neutral-900\" style={{ aspectRatio, borderRadius: radius }}>\n        <canvas ref={canvasRef} role=\"img\" aria-label={current?.alt ?? current?.title ?? \"\"} className=\"absolute inset-0 h-full w-full\" />\n        {current && (current.title || current.meta) && (\n          <div className=\"pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/65 to-transparent p-5 pt-16 text-white\" aria-live=\"polite\">\n            {current.title && <p className=\"text-[20px] leading-tight font-medium\">{current.title}</p>}\n            {current.meta && <p className=\"mt-1 font-mono text-[11px] text-white/70\">{current.meta}</p>}\n          </div>\n        )}\n      </div>\n      {showControls && slides.length > 1 && (\n        <div className=\"mt-4 flex items-center justify-between gap-4\">\n          <div className=\"flex gap-1.5\">\n            {slides.map((s, i) => (\n              <button\n                key={s.src + i}\n                type=\"button\"\n                aria-label={`Show ${s.title ?? `slide ${i + 1}`}`}\n                aria-current={i === index ? \"true\" : undefined}\n                onClick={() => go(i)}\n                className=\"flex h-6 cursor-pointer items-center outline-none focus-visible:ring-2 focus-visible:ring-current\"\n              >\n                <span className=\"block h-[3px] rounded-full bg-current transition-all duration-500\" style={{ width: i === index ? 28 : 10, opacity: i === index ? 1 : 0.35 }} />\n              </button>\n            ))}\n          </div>\n          <div className=\"flex items-center gap-2\">\n            <span className=\"font-mono text-[11px] tabular-nums opacity-60\">\n              {String(index + 1).padStart(2, \"0\")} / {String(slides.length).padStart(2, \"0\")}\n            </span>\n            <button type=\"button\" aria-label=\"Previous\" onClick={() => go(index - 1)} className=\"flex size-9 cursor-pointer items-center justify-center rounded-full border border-current/20 outline-none focus-visible:ring-2 focus-visible:ring-current\">\n              <ChevronLeft size={16} />\n            </button>\n            <button type=\"button\" aria-label=\"Next\" onClick={() => go(index + 1)} className=\"flex size-9 cursor-pointer items-center justify-center rounded-full border border-current/20 outline-none focus-visible:ring-2 focus-visible:ring-current\">\n              <ChevronRight size={16} />\n            </button>\n          </div>\n        </div>\n      )}\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}