{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dither-scan",
  "title": "Dither Scan",
  "description": "An image that starts as a 1-bit ordered dither. A diagonal scan line sweeps it a set number of times, and each pass sharpens the cells and brings back tone and color until the source is clean.",
  "files": [
    {
      "path": "registry/dither-scan/dither-scan.tsx",
      "content": "\"use client\"\n\nimport { useEffect, useRef, useState, type CSSProperties } from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport type DitherScanTheme = \"light\" | \"dark\" | \"auto\"\n\nexport type DitherScanFit = \"cover\" | \"contain\"\n\nexport type DitherScanOptions = {\n  /** Image URL. Remote images need CORS (`Access-Control-Allow-Origin`). */\n  src: string\n  /** Sweeps it takes to clear the dither. Default `4`, clamped to 1–12 */\n  passes?: number\n  /** Milliseconds per sweep. Default `1400` */\n  duration?: number\n  /** Milliseconds between sweeps. Default `280` */\n  pause?: number\n  /** Direction the line travels, in degrees (0 = left to right). Default `45` */\n  angle?: number\n  /** Every other sweep runs back the way it came. Default `true` */\n  alternate?: boolean\n  /** Dither cell size of the first pass, in CSS px. Default `6` */\n  pixelSize?: number\n  /** `[shadow, highlight]` for the 1-bit print. Default follows theme. */\n  colors?: readonly [string, string]\n  /** Blur in CSS px that follows the line while it settles. `0` turns it off. Default `6` */\n  blur?: number\n  /** Scan line color. Default inverts whatever is under it. */\n  lineColor?: string\n  /** How the image fills the frame. Default `cover` */\n  fit?: DitherScanFit\n  /** Start once the frame scrolls into view. Default `true` */\n  autoPlay?: boolean\n  /** Re-dither and scan again after a hold. Default `false` */\n  loop?: boolean\n  /** Hold on the clean image before a loop, in ms. Default `2400` */\n  loopDelay?: number\n  /**\n   * Palette mode. Default `auto` follows shadcn / next-themes\n   * (`html.dark` class).\n   */\n  theme?: DitherScanTheme\n  /** Fires with the image's natural size once it loads. */\n  onLoad?: (width: number, height: number) => void\n  /** Fires when the first sweep starts, including each loop. */\n  onStart?: () => void\n  /** Fires after each sweep, 1-based. */\n  onPass?: (pass: number, passes: number) => void\n  /** Fires when the image is clean. */\n  onComplete?: () => void\n  /** Fires when a scan starts or settles. */\n  onScanningChange?: (scanning: boolean) => void\n}\n\nexport type DitherScanInstance = {\n  setOptions: (options: Partial<DitherScanOptions>) => void\n  /** Re-dither and scan from the first pass. */\n  replay: () => void\n  destroy: () => void\n}\n\n/** Ink and paper for the 1-bit print on a light page */\nexport const LIGHT_COLORS = [\"#18181B\", \"#F4F4F5\"] as const\n/** Ink and paper for the 1-bit print on a dark page */\nexport const DARK_COLORS = [\"#09090B\", \"#D4D4D8\"] as const\n\nconst MAX_PASSES = 12\nconst MAX_LEVELS = 12\nconst LINE_WIDTH = 1.5\nconst TRAIL = 56\nconst BLUR_BEHIND = 128\nconst BLUR_AHEAD = 36\n/** Gradient stops sampled from smoothstep; a linear ramp shows bands. */\nconst BLUR_STOPS = 12\nconst RESET_MS = 520\nconst REBUILD_DELAY_MS = 120\n\nconst BAYER8 = [\n  [0, 32, 8, 40, 2, 34, 10, 42],\n  [48, 16, 56, 24, 50, 18, 58, 26],\n  [12, 44, 4, 36, 14, 46, 6, 38],\n  [60, 28, 52, 20, 62, 30, 54, 22],\n  [3, 35, 11, 43, 1, 33, 9, 41],\n  [51, 19, 59, 27, 49, 17, 57, 25],\n  [15, 47, 7, 39, 13, 45, 5, 37],\n  [63, 31, 55, 23, 61, 29, 53, 21],\n] as const\n\n/** Resolves shadcn / next-themes dark mode (`attribute=\"class\"` → `html.dark`). */\nexport function isDarkTheme(): boolean {\n  if (typeof document === \"undefined\") return false\n  const root = document.documentElement\n  if (root.classList.contains(\"dark\")) return true\n  if (root.classList.contains(\"light\")) return false\n  const dataTheme = root.getAttribute(\"data-theme\")\n  if (dataTheme === \"dark\") return true\n  if (dataTheme === \"light\") return false\n  return window.matchMedia(\"(prefers-color-scheme: dark)\").matches\n}\n\nexport function resolveDark(theme: DitherScanTheme): boolean {\n  if (theme === \"dark\") return true\n  if (theme === \"light\") return false\n  return isDarkTheme()\n}\n\nfunction hexRgb(hex: string): [number, number, number] {\n  const h = hex.replace(\"#\", \"\").trim()\n  const full =\n    h.length === 3\n      ? h\n          .split(\"\")\n          .map((c) => c + c)\n          .join(\"\")\n      : h.padEnd(6, \"0\").slice(0, 6)\n  const n = Number.parseInt(full, 16)\n  if (Number.isNaN(n)) return [0, 0, 0]\n  return [(n >> 16) & 255, (n >> 8) & 255, n & 255]\n}\n\nfunction clampPasses(passes: number | undefined) {\n  const n = Math.round(passes ?? 4)\n  if (!Number.isFinite(n)) return 4\n  return Math.min(MAX_PASSES, Math.max(1, n))\n}\n\nfunction smoothstep(t: number) {\n  return t * t * (3 - 2 * t)\n}\n\nfunction easeInOutSine(t: number) {\n  return -(Math.cos(Math.PI * t) - 1) / 2\n}\n\n/**\n * How a pass level looks. Level 0 is the 1-bit print; level `passes` is the\n * source. Cells shrink geometrically, tones and color return linearly.\n */\nexport function levelSpec(level: number, passes: number, pixelSize: number) {\n  const t = level / passes\n  return {\n    cell: Math.max(1, Math.round(Math.max(1, pixelSize) ** (1 - t))),\n    tones: 2 + Math.round(t * (MAX_LEVELS - 2)),\n    color: t,\n  }\n}\n\ntype Fit = { x: number; y: number; w: number; h: number }\n\nfunction fitRect(\n  iw: number,\n  ih: number,\n  w: number,\n  h: number,\n  fit: DitherScanFit\n): Fit {\n  const scale =\n    fit === \"contain\" ? Math.min(w / iw, h / ih) : Math.max(w / iw, h / ih)\n  const dw = iw * scale\n  const dh = ih * scale\n  return { x: (w - dw) / 2, y: (h - dh) / 2, w: dw, h: dh }\n}\n\n/**\n * Ordered-dither the image at one pass level into a small canvas, one pixel\n * per cell. Drawn back up with smoothing off, each pixel is a crisp cell.\n * Returns null if the image taints the canvas (no CORS).\n */\nfunction renderLevel(\n  image: HTMLImageElement,\n  w: number,\n  h: number,\n  fit: DitherScanFit,\n  spec: ReturnType<typeof levelSpec>,\n  shadow: [number, number, number],\n  highlight: [number, number, number]\n): HTMLCanvasElement | null {\n  const sw = Math.max(1, Math.ceil(w / spec.cell))\n  const sh = Math.max(1, Math.ceil(h / spec.cell))\n  const out = document.createElement(\"canvas\")\n  out.width = sw\n  out.height = sh\n  const ctx = out.getContext(\"2d\", { willReadFrequently: true })\n  if (!ctx) return null\n\n  const r = fitRect(image.naturalWidth, image.naturalHeight, w, h, fit)\n  ctx.imageSmoothingEnabled = true\n  ctx.imageSmoothingQuality = \"high\"\n  ctx.drawImage(\n    image,\n    r.x / spec.cell,\n    r.y / spec.cell,\n    r.w / spec.cell,\n    r.h / spec.cell\n  )\n\n  let data: ImageData\n  try {\n    data = ctx.getImageData(0, 0, sw, sh)\n  } catch {\n    return null\n  }\n\n  const px = data.data\n  const steps = spec.tones - 1\n  const mix = spec.color\n  const keep = 1 - mix\n  const [sr, sg, sb] = shadow\n  const dr = highlight[0] - sr\n  const dg = highlight[1] - sg\n  const db = highlight[2] - sb\n\n  for (let y = 0; y < sh; y++) {\n    const row = BAYER8[y & 7]!\n    for (let x = 0; x < sw; x++) {\n      const i = (y * sw + x) * 4\n      if (px[i + 3]! === 0) continue\n      const bias = (row[x & 7]! + 0.5) / 64 - 0.5\n      const r8 = px[i]!\n      const g8 = px[i + 1]!\n      const b8 = px[i + 2]!\n\n      const lum = (0.2126 * r8 + 0.7152 * g8 + 0.0722 * b8) / 255\n      let tone = Math.round(lum * steps + bias) / steps\n      tone = tone < 0 ? 0 : tone > 1 ? 1 : tone\n\n      let qr = r8\n      let qg = g8\n      let qb = b8\n      if (mix > 0) {\n        qr = Math.round((r8 / 255) * steps + bias) / steps\n        qg = Math.round((g8 / 255) * steps + bias) / steps\n        qb = Math.round((b8 / 255) * steps + bias) / steps\n        qr = (qr < 0 ? 0 : qr > 1 ? 1 : qr) * 255\n        qg = (qg < 0 ? 0 : qg > 1 ? 1 : qg) * 255\n        qb = (qb < 0 ? 0 : qb > 1 ? 1 : qb) * 255\n      }\n\n      px[i] = (sr + dr * tone) * keep + qr * mix\n      px[i + 1] = (sg + dg * tone) * keep + qg * mix\n      px[i + 2] = (sb + db * tone) * keep + qb * mix\n      px[i + 3] = 255\n    }\n  }\n\n  ctx.putImageData(data, 0, 0)\n  return out\n}\n\nconst IDLE = 0\nconst SWEEP = 1\nconst HOLD = 2\nconst DONE = 3\nconst RESET = 4\n\nexport function createDitherScan(\n  wrap: HTMLElement,\n  canvas: HTMLCanvasElement,\n  initial: DitherScanOptions\n): DitherScanInstance | null {\n  let options: DitherScanOptions = {\n    passes: 4,\n    duration: 1400,\n    pause: 280,\n    angle: 45,\n    alternate: true,\n    pixelSize: 6,\n    blur: 6,\n    fit: \"cover\",\n    autoPlay: true,\n    loop: false,\n    loopDelay: 2400,\n    theme: \"auto\",\n    ...initial,\n  }\n\n  const ctx = canvas.getContext(\"2d\")\n  if (!ctx) return null\n\n  let running = true\n  let raf = 0\n  let rebuildTimer = 0\n  let loopTimer = 0\n  let cssW = 0\n  let cssH = 0\n  let dpr = 1\n  let reduce = false\n  let dark = resolveDark(options.theme ?? \"auto\")\n  let visible = false\n  let image: HTMLImageElement | null = null\n  let loadedSrc = \"\"\n  /** `levels[k]` is pass level k; the last is null and draws the source. */\n  let levels: (HTMLCanvasElement | null)[] = []\n  /** CSS px per level pixel, matching `levels`. */\n  let cells: number[] = []\n  let levelsW = 0\n  let levelsH = 0\n  /** Blurred copies of levels, made the first time a sweep needs one. */\n  const blurred = new Map<number, HTMLCanvasElement | null>()\n  let scratch: HTMLCanvasElement | null = null\n  let warmTimer = 0\n  let tainted = false\n\n  let state = IDLE\n  /** Sweeps finished; the frame shows `levels[pass]`. */\n  let pass = 0\n  let phaseStart = 0\n  let wantsPlay = false\n  let scanning = false\n\n  const passes = () => clampPasses(options.passes)\n\n  const setScanning = (next: boolean) => {\n    if (scanning === next) return\n    scanning = next\n    options.onScanningChange?.(next)\n  }\n\n  const palette = () => {\n    const pair = options.colors ?? (dark ? DARK_COLORS : LIGHT_COLORS)\n    return [hexRgb(pair[0]), hexRgb(pair[1])] as const\n  }\n\n  const rebuild = () => {\n    window.clearTimeout(rebuildTimer)\n    rebuildTimer = 0\n    if (!image || cssW <= 0 || cssH <= 0) return\n    const n = passes()\n    const [shadow, highlight] = palette()\n    const fit = options.fit ?? \"cover\"\n    const pixelSize = options.pixelSize ?? 6\n    const next: (HTMLCanvasElement | null)[] = []\n    const nextCells: number[] = []\n    tainted = false\n    for (let k = 0; k < n; k++) {\n      const spec = levelSpec(k, n, pixelSize)\n      const level = renderLevel(\n        image,\n        cssW,\n        cssH,\n        fit,\n        spec,\n        shadow,\n        highlight\n      )\n      if (!level) {\n        tainted = true\n        break\n      }\n      next.push(level)\n      nextCells.push(spec.cell)\n    }\n    // A cross-origin image without CORS can't be read: show it as is.\n    levels = tainted ? [null] : [...next, null]\n    cells = tainted ? [1] : [...nextCells, 1]\n    levelsW = cssW\n    levelsH = cssH\n    blurred.clear()\n    warmBlur()\n    if (pass > levels.length - 1) pass = levels.length - 1\n  }\n\n  const drawLevel = (k: number, target: CanvasRenderingContext2D = ctx) => {\n    const level = levels[k]\n    if (level === undefined) return\n    if (level === null) {\n      if (!image) return\n      const r = fitRect(\n        image.naturalWidth,\n        image.naturalHeight,\n        cssW,\n        cssH,\n        options.fit ?? \"cover\"\n      )\n      target.imageSmoothingEnabled = true\n      target.imageSmoothingQuality = \"high\"\n      target.drawImage(image, r.x, r.y, r.w, r.h)\n      return\n    }\n    // Stretch to the current size; a resize rebuilds after it settles.\n    const cell = cells[k] ?? 1\n    target.imageSmoothingEnabled = false\n    target.drawImage(\n      level,\n      0,\n      0,\n      level.width * cell * (cssW / levelsW),\n      level.height * cell * (cssH / levelsH)\n    )\n  }\n\n  /**\n   * Level `k` at CSS size, blurred. The sharp copy goes under it so the\n   * frame's edges don't blur into transparency. Null where canvas filters\n   * are unsupported.\n   */\n  const blurredLevel = (k: number) => {\n    if (blurred.has(k)) return blurred.get(k)!\n    const out = document.createElement(\"canvas\")\n    out.width = Math.max(1, Math.round(cssW))\n    out.height = Math.max(1, Math.round(cssH))\n    const bctx = out.getContext(\"2d\")\n    let result: HTMLCanvasElement | null = null\n    if (bctx && typeof bctx.filter === \"string\") {\n      drawLevel(k, bctx)\n      bctx.filter = `blur(${options.blur ?? 6}px)`\n      drawLevel(k, bctx)\n      bctx.filter = \"none\"\n      result = out\n    }\n    blurred.set(k, result)\n    return result\n  }\n\n  /**\n   * Blur every level ahead of time, one per task, so a sweep never stalls a\n   * frame making the copy it needs.\n   */\n  const warmBlur = () => {\n    window.clearTimeout(warmTimer)\n    if ((options.blur ?? 6) <= 0 || reduce) return\n    const step = (k: number) => {\n      if (!running || k >= levels.length) return\n      blurredLevel(k)\n      warmTimer = window.setTimeout(() => step(k + 1), 0)\n    }\n    warmTimer = window.setTimeout(() => step(0), 0)\n  }\n\n  /**\n   * A feathered band of blur riding the line: the incoming level softens\n   * behind it and sharpens as the line moves on, the outgoing one just ahead.\n   */\n  const drawScanBlur = (a: number, u: number, e: number, f: number) => {\n    if ((options.blur ?? 6) <= 0) return\n    const ahead = blurredLevel(pass)\n    const behind = blurredLevel(pass + 1)\n    if (!ahead || !behind) return\n\n    if (!scratch) scratch = document.createElement(\"canvas\")\n    const w = Math.max(1, Math.round(cssW))\n    const h = Math.max(1, Math.round(cssH))\n    if (scratch.width !== w || scratch.height !== h) {\n      scratch.width = w\n      scratch.height = h\n    }\n    const sctx = scratch.getContext(\"2d\")\n    if (!sctx) return\n\n    sctx.setTransform(1, 0, 0, 1, 0, 0)\n    sctx.globalCompositeOperation = \"source-over\"\n    sctx.clearRect(0, 0, w, h)\n    sctx.drawImage(ahead, 0, 0)\n\n    sctx.save()\n    sctx.translate(cssW / 2, cssH / 2)\n    sctx.rotate(a)\n    sctx.beginPath()\n    sctx.rect(-e - 2, -f, u + e + 2, f * 2)\n    sctx.clip()\n    sctx.setTransform(1, 0, 0, 1, 0, 0)\n    sctx.drawImage(behind, 0, 0)\n    sctx.restore()\n\n    // Keep only the band. The fill covers the whole frame, so the mask\n    // doesn't depend on how a browser bounds `destination-in`.\n    sctx.save()\n    sctx.translate(cssW / 2, cssH / 2)\n    sctx.rotate(a)\n    const band = BLUR_BEHIND + BLUR_AHEAD\n    const peak = BLUR_BEHIND / band\n    const mask = sctx.createLinearGradient(u - BLUR_BEHIND, 0, u + BLUR_AHEAD, 0)\n    for (let i = 0; i <= BLUR_STOPS; i++) {\n      const x = i / BLUR_STOPS\n      const rise = x * peak\n      const fall = peak + x * (1 - peak)\n      mask.addColorStop(rise, `rgba(0,0,0,${smoothstep(x)})`)\n      mask.addColorStop(fall, `rgba(0,0,0,${smoothstep(1 - x)})`)\n    }\n    sctx.globalCompositeOperation = \"destination-in\"\n    sctx.fillStyle = mask\n    sctx.fillRect(-e - band - 4, -f, (e + band + 4) * 2, f * 2)\n    sctx.restore()\n\n    ctx.drawImage(scratch, 0, 0, cssW, cssH)\n  }\n\n  /** Draw the line and its trail, rotated to the travel direction. */\n  const drawLine = (u: number, f: number) => {\n    const color = options.lineColor\n    const trail = ctx.createLinearGradient(u - TRAIL, 0, u, 0)\n    if (color) {\n      const [r, g, b] = hexRgb(color)\n      trail.addColorStop(0, `rgba(${r},${g},${b},0)`)\n      trail.addColorStop(1, `rgba(${r},${g},${b},0.28)`)\n    } else {\n      trail.addColorStop(0, \"rgba(255,255,255,0)\")\n      trail.addColorStop(1, \"rgba(255,255,255,0.22)\")\n    }\n    ctx.globalCompositeOperation = color ? \"source-over\" : \"soft-light\"\n    ctx.fillStyle = trail\n    ctx.fillRect(u - TRAIL, -f, TRAIL, f * 2)\n\n    ctx.globalCompositeOperation = color ? \"source-over\" : \"difference\"\n    ctx.fillStyle = color ?? \"#FFFFFF\"\n    ctx.fillRect(u - LINE_WIDTH / 2, -f, LINE_WIDTH, f * 2)\n    ctx.globalCompositeOperation = \"source-over\"\n  }\n\n  const draw = (now: number) => {\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n    ctx.clearRect(0, 0, cssW, cssH)\n    if (!image || levels.length === 0) return\n\n    if (state === RESET) {\n      const t = Math.min(1, (now - phaseStart) / RESET_MS)\n      drawLevel(levels.length - 1)\n      ctx.globalAlpha = easeInOutSine(t)\n      drawLevel(0)\n      ctx.globalAlpha = 1\n      return\n    }\n\n    drawLevel(pass)\n    if (state !== SWEEP) return\n\n    const t = easeInOutSine(\n      Math.min(1, (now - phaseStart) / Math.max(1, options.duration ?? 1400))\n    )\n    const flip = options.alternate !== false && pass % 2 === 1\n    const a = (((options.angle ?? 45) + (flip ? 180 : 0)) * Math.PI) / 180\n    const cos = Math.abs(Math.cos(a))\n    const sin = Math.abs(Math.sin(a))\n    // Half-extents of the frame along the travel axis (e) and across it (f).\n    const e = (cos * cssW + sin * cssH) / 2\n    const f = (sin * cssW + cos * cssH) / 2 + 2\n    // With blur on, travel until the band has fully entered and left the\n    // frame, so it never pops in or out at a pass boundary.\n    const soft = (options.blur ?? 6) > 0\n    const from = -e - LINE_WIDTH - (soft ? BLUR_AHEAD : 0)\n    const to = e + LINE_WIDTH + (soft ? BLUR_BEHIND : 0)\n    const u = from + (to - from) * t\n\n    ctx.save()\n    ctx.translate(cssW / 2, cssH / 2)\n    ctx.rotate(a)\n    ctx.beginPath()\n    ctx.rect(-e - 2, -f, u + e + 2, f * 2)\n    ctx.clip()\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n    drawLevel(pass + 1)\n    ctx.restore()\n\n    drawScanBlur(a, u, e, f)\n\n    ctx.save()\n    ctx.translate(cssW / 2, cssH / 2)\n    ctx.rotate(a)\n    drawLine(u, f)\n    ctx.restore()\n  }\n\n  const scheduleLoop = () => {\n    window.clearTimeout(loopTimer)\n    if (!options.loop || reduce || levels.length < 2) return\n    loopTimer = window.setTimeout(() => {\n      if (!running || state !== DONE) return\n      state = RESET\n      phaseStart = performance.now()\n      setScanning(true)\n      startLoop()\n    }, Math.max(0, options.loopDelay ?? 2400))\n  }\n\n  const finish = () => {\n    state = DONE\n    pass = levels.length - 1\n    setScanning(false)\n    options.onComplete?.()\n    scheduleLoop()\n  }\n\n  const tick = (now: number) => {\n    raf = 0\n    if (!running) return\n    const last = levels.length - 1\n\n    if (state === SWEEP) {\n      if (now - phaseStart >= Math.max(1, options.duration ?? 1400)) {\n        pass += 1\n        options.onPass?.(pass, last)\n        if (pass >= last) {\n          finish()\n        } else {\n          state = HOLD\n          phaseStart = now\n        }\n      }\n    } else if (state === HOLD) {\n      if (now - phaseStart >= Math.max(0, options.pause ?? 280)) {\n        state = SWEEP\n        phaseStart = now\n      }\n    } else if (state === RESET) {\n      if (now - phaseStart >= RESET_MS) {\n        state = IDLE\n        pass = 0\n        begin(now)\n      }\n    }\n\n    draw(now)\n    if (state === SWEEP || state === HOLD || state === RESET) {\n      raf = requestAnimationFrame(tick)\n    }\n  }\n\n  const startLoop = () => {\n    if (!raf && running) raf = requestAnimationFrame(tick)\n  }\n\n  const redraw = () => {\n    if (raf) return\n    draw(performance.now())\n  }\n\n  /** Start sweeping from the current level, once there is something to show. */\n  const begin = (now = performance.now()) => {\n    wantsPlay = false\n    const last = levels.length - 1\n    if (last <= 0 || reduce) {\n      pass = Math.max(0, last)\n      state = DONE\n      redraw()\n      if (last >= 0) options.onComplete?.()\n      return\n    }\n    if (pass === 0) options.onStart?.()\n    state = SWEEP\n    phaseStart = now\n    setScanning(true)\n    startLoop()\n  }\n\n  const requestPlay = () => {\n    if (!image || levels.length === 0 || !visible) {\n      wantsPlay = true\n      return\n    }\n    begin()\n  }\n\n  const restart = (play: boolean) => {\n    window.clearTimeout(loopTimer)\n    cancelAnimationFrame(raf)\n    raf = 0\n    state = IDLE\n    pass = 0\n    setScanning(false)\n    redraw()\n    if (play) requestPlay()\n  }\n\n  /** Returns whether the CSS size changed. */\n  const resize = () => {\n    dpr = Math.min(window.devicePixelRatio || 1, 2)\n    const w = wrap.clientWidth\n    const h = wrap.clientHeight\n    if (w <= 0 || h <= 0) return false\n    const changed = w !== cssW || h !== cssH\n    cssW = w\n    cssH = h\n    const bw = Math.max(1, Math.floor(w * dpr))\n    const bh = Math.max(1, Math.floor(h * dpr))\n    if (bw !== canvas.width || bh !== canvas.height) {\n      canvas.width = bw\n      canvas.height = bh\n    }\n    canvas.style.width = `${w}px`\n    canvas.style.height = `${h}px`\n    return changed\n  }\n\n  const load = (src: string) => {\n    loadedSrc = src\n    levels = []\n    image = null\n    restart(false)\n    if (!src) return\n    const img = new Image()\n    img.crossOrigin = \"anonymous\"\n    img.decoding = \"async\"\n    img.onload = () => {\n      if (!running || loadedSrc !== src) return\n      image = img\n      options.onLoad?.(img.naturalWidth, img.naturalHeight)\n      resize()\n      rebuild()\n      redraw()\n      if (options.autoPlay !== false || wantsPlay) requestPlay()\n    }\n    img.src = src\n  }\n\n  resize()\n\n  const ro = new ResizeObserver(() => {\n    if (!resize() || !image) return\n    if (levels.length === 0) rebuild()\n    redraw()\n    window.clearTimeout(rebuildTimer)\n    rebuildTimer = window.setTimeout(() => {\n      rebuild()\n      redraw()\n      if (wantsPlay) requestPlay()\n    }, REBUILD_DELAY_MS)\n  })\n  ro.observe(wrap)\n\n  const io = new IntersectionObserver(\n    (entries) => {\n      visible = entries.some((entry) => entry.isIntersecting)\n      if (visible && wantsPlay) requestPlay()\n    },\n    { threshold: 0.35 }\n  )\n  io.observe(wrap)\n\n  const mqReduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n  const onReduce = () => {\n    reduce = mqReduce.matches\n  }\n  onReduce()\n  mqReduce.addEventListener(\"change\", onReduce)\n\n  const syncTheme = () => {\n    const next = resolveDark(options.theme ?? \"auto\")\n    if (next === dark) return\n    dark = next\n    if (!options.colors) {\n      rebuild()\n      redraw()\n    }\n  }\n  const mo = new MutationObserver(syncTheme)\n  mo.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: [\"class\", \"data-theme\", \"style\"],\n  })\n  const mqDark = window.matchMedia(\"(prefers-color-scheme: dark)\")\n  mqDark.addEventListener(\"change\", syncTheme)\n\n  wantsPlay = options.autoPlay !== false\n  load(options.src)\n\n  return {\n    setOptions(next) {\n      const prev = options\n      options = { ...options, ...next }\n      if (options.src !== loadedSrc) {\n        wantsPlay = options.autoPlay !== false\n        load(options.src)\n        return\n      }\n      const passesChanged = clampPasses(prev.passes) !== passes()\n      const looks =\n        passesChanged ||\n        prev.pixelSize !== options.pixelSize ||\n        prev.fit !== options.fit ||\n        prev.colors?.[0] !== options.colors?.[0] ||\n        prev.colors?.[1] !== options.colors?.[1]\n      if (prev.theme !== options.theme) {\n        dark = resolveDark(options.theme ?? \"auto\")\n      }\n      if (looks || prev.theme !== options.theme) rebuild()\n      else if (prev.blur !== options.blur) {\n        blurred.clear()\n        warmBlur()\n      }\n      if (passesChanged) {\n        restart(options.autoPlay !== false)\n        return\n      }\n      if (prev.loop !== options.loop && state === DONE) scheduleLoop()\n      if (prev.autoPlay === false && options.autoPlay !== false && state === IDLE) {\n        requestPlay()\n      }\n      redraw()\n    },\n    replay() {\n      restart(true)\n    },\n    destroy() {\n      running = false\n      cancelAnimationFrame(raf)\n      window.clearTimeout(rebuildTimer)\n      window.clearTimeout(loopTimer)\n      window.clearTimeout(warmTimer)\n      ro.disconnect()\n      io.disconnect()\n      mo.disconnect()\n      mqReduce.removeEventListener(\"change\", onReduce)\n      mqDark.removeEventListener(\"change\", syncTheme)\n      options.onScanningChange?.(false)\n    },\n  }\n}\n\nexport type DitherScanProps = Omit<\n  DitherScanOptions,\n  \"onLoad\" | \"onScanningChange\"\n> & {\n  /** Accessible description of the image. */\n  alt?: string\n  /** Increment to re-dither and scan again. */\n  replayKey?: number\n  className?: string\n}\n\n/**\n * An image that starts as a 1-bit ordered dither. A diagonal scan line\n * sweeps it `passes` times; each sweep sharpens the cells and returns tone\n * and color, and the last one leaves the source image.\n */\nexport function DitherScan({\n  src,\n  alt = \"\",\n  passes = 4,\n  duration = 1400,\n  pause = 280,\n  angle = 45,\n  alternate = true,\n  pixelSize = 6,\n  blur = 6,\n  colors,\n  lineColor,\n  fit = \"cover\",\n  autoPlay = true,\n  loop = false,\n  loopDelay = 2400,\n  theme = \"auto\",\n  replayKey = 0,\n  onStart,\n  onPass,\n  onComplete,\n  className,\n}: DitherScanProps) {\n  const wrapRef = useRef<HTMLDivElement>(null)\n  const canvasRef = useRef<HTMLCanvasElement>(null)\n  const instanceRef = useRef<DitherScanInstance | null>(null)\n  const replayKeyRef = useRef(replayKey)\n  const callbacksRef = useRef({ onStart, onPass, onComplete })\n  const [ratio, setRatio] = useState<string | null>(null)\n  const [scanning, setScanning] = useState(false)\n\n  useEffect(() => {\n    callbacksRef.current = { onStart, onPass, onComplete }\n  }, [onStart, onPass, onComplete])\n\n  const shadow = colors?.[0]\n  const highlight = colors?.[1]\n\n  const options = {\n    src,\n    passes,\n    duration,\n    pause,\n    angle,\n    alternate,\n    pixelSize,\n    blur,\n    colors,\n    lineColor,\n    fit,\n    autoPlay,\n    loop,\n    loopDelay,\n    theme,\n  }\n\n  useEffect(() => {\n    const wrap = wrapRef.current\n    const canvas = canvasRef.current\n    if (!wrap || !canvas) return\n    instanceRef.current = createDitherScan(wrap, canvas, {\n      ...options,\n      onLoad: (w, h) => setRatio(`${w} / ${h}`),\n      onScanningChange: setScanning,\n      onStart: () => callbacksRef.current.onStart?.(),\n      onPass: (pass, total) => callbacksRef.current.onPass?.(pass, total),\n      onComplete: () => callbacksRef.current.onComplete?.(),\n    })\n    return () => {\n      instanceRef.current?.destroy()\n      instanceRef.current = null\n    }\n    // Engine reads live options via setOptions; mount once.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [])\n\n  useEffect(() => {\n    instanceRef.current?.setOptions(options)\n    // `options` is rebuilt every render; its fields are the real deps.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [\n    src,\n    passes,\n    duration,\n    pause,\n    angle,\n    alternate,\n    pixelSize,\n    blur,\n    shadow,\n    highlight,\n    lineColor,\n    fit,\n    autoPlay,\n    loop,\n    loopDelay,\n    theme,\n  ])\n\n  useEffect(() => {\n    if (replayKeyRef.current === replayKey) return\n    replayKeyRef.current = replayKey\n    instanceRef.current?.replay()\n  }, [replayKey])\n\n  return (\n    <div\n      ref={wrapRef}\n      data-slot=\"dither-scan\"\n      data-scanning={scanning || undefined}\n      role=\"img\"\n      aria-label={alt || undefined}\n      aria-busy={scanning || undefined}\n      style={{ \"--dither-scan-ratio\": ratio ?? \"4 / 3\" } as CSSProperties}\n      className={cn(\n        \"relative aspect-(--dither-scan-ratio) w-full overflow-hidden\",\n        className\n      )}\n    >\n      <canvas ref={canvasRef} className=\"absolute inset-0 size-full\" />\n    </div>\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/ui/dither-scan.tsx"
    }
  ],
  "type": "registry:ui"
}