{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"bayer-dissolve","type":"registry:component","title":"Bayer Dissolve","description":"An ordered-dither transition: a new state prints in over the old one in 8x8 Bayer order while the screen refines from coarse cells to fine, or prints in from the ground on first view.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/bayer-dissolve.tsx","content":"\"use client\";\n\nimport { useEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport type { CSSProperties, ReactNode, RefObject } from \"react\";\n\n/**\n * BayerDissolve — changes state through an ordered-dither dissolve.\n *\n * Give it `items` and an `index`: when the index changes, the new state\n * prints in over the old one in 8x8 Bayer order (65 mask levels in about\n * 720ms) while the screen refines from coarse cells to fine. With `reveal`\n * it prints in from the ground on first view. Renders in place first; hides\n * only once it can animate. CSS masks, no canvas.\n *\n * Part of the Dither & ASCII kit: one ink, paper #f3f0e6, on a warm black\n * ground #0b0b0d, with vermillion #ff4f2b as a second ink inside the\n * pictures and for a live state. Cells snap to whole device pixels;\n * scenes dither in linear light, photographs on a gentler curve. Funnel Display through\n * var(--font-funnel) for display over Geist; Geist Mono for every glyph.\n * Respects prefers-reduced-motion. No dependencies beyond React.\n * Paste it as its own file: it repeats the kit's small helpers, which would\n * clash in one module. Load Funnel Display with next/font (variable:\n * \"--font-funnel\") on a parent, or from Google Fonts or @fontsource.\n */\n\nfunction clamp(v: number, lo: number, hi: number): number {\n  return v < lo ? lo : v > hi ? hi : v;\n}\n\nfunction smooth01(x: number): number {\n  const t = clamp(x, 0, 1);\n  return t * t * (3 - 2 * t);\n}\n\nfunction subscribeMotion(cb: () => void) {\n  const m = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n  m.addEventListener(\"change\", cb);\n  return () => m.removeEventListener(\"change\", cb);\n}\n\n/** True when the visitor asked for reduced motion. False on the server. */\nfunction useReducedMotion(): boolean {\n  return useSyncExternalStore(\n    subscribeMotion,\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/** The 8x8 Bayer index of a cell (0-63). Recursive, so every 2x2 and 4x4 block is itself in order. */\nfunction bayer8(x: number, y: number): number {\n  let v = 0;\n  for (let bit = 0; bit < 3; bit++) {\n    const xb = (x >> bit) & 1;\n    const yb = (y >> bit) & 1;\n    v |= (((xb ^ yb) << 1) | yb) << (2 * (2 - bit));\n  }\n  return v;\n}\n\nconst daMaskCache = new Map<number, string>();\n\n/** A mask tile with the first `level` of the 64 Bayer cells opaque: 0 shows nothing, 64 shows everything. */\nfunction daBayerMask(level: number): string {\n  const k = clamp(Math.round(level), 0, 64);\n  const hit = daMaskCache.get(k);\n  if (hit) return hit;\n  let d = \"\";\n  for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) if (bayer8(x, y) < k) d += `M${x} ${y}h1v1h-1z`;\n  const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8' shape-rendering='crispEdges'><path d='${d}'/></svg>`;\n  const url = `url(\"data:image/svg+xml,${encodeURIComponent(svg)}\")`;\n  daMaskCache.set(k, url);\n  return url;\n}\n\n/** The style that masks an element to a Bayer level, tiled at `px` CSS pixels a cell. */\nfunction daMaskStyle(level: number, px: number): CSSProperties {\n  const m = daBayerMask(level);\n  const s = `${px * 8}px ${px * 8}px`;\n  return { maskImage: m, WebkitMaskImage: m, maskSize: s, WebkitMaskSize: s, maskRepeat: \"repeat\", WebkitMaskRepeat: \"repeat\" };\n}\n\n/**\n * A cell size in CSS pixels snapped to whole device pixels for this element\n * (the screen's pixel ratio times any CSS scale on the way), so every dither\n * cell lands on the pixel grid and never blurs into grey.\n */\nfunction useSnappedCell(ref: RefObject<HTMLElement | null>, cell: number): number {\n  const [px, setPx] = useState(cell);\n  useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    let raf = 0;\n    const measure = () => {\n      const k = el.offsetWidth ? el.getBoundingClientRect().width / el.offsetWidth : 1;\n      const dev = (window.devicePixelRatio || 1) * (k || 1);\n      setPx(Math.max(1, Math.round(cell * dev)) / dev);\n    };\n    const ro = new ResizeObserver(() => {\n      measure();\n      cancelAnimationFrame(raf);\n      raf = requestAnimationFrame(measure);\n    });\n    ro.observe(el);\n    return () => {\n      ro.disconnect();\n      cancelAnimationFrame(raf);\n    };\n  }, [ref, cell]);\n  return px;\n}\n\n/**\n * BayerDissolve — changes state through an ordered-dither dissolve.\n *\n * Give it the states as `items` and the one to show as `index`. When the\n * index changes, the new state prints in over the old one cell by cell in\n * 8x8 Bayer order (65 mask levels in about 720ms) while the screen refines\n * from coarse cells to fine ones, then the old state is dropped. With\n * `reveal` it prints in from the ground the first time it comes into view;\n * it renders in place first and only hides once it can animate, so nothing\n * is lost without script. Reduced motion swaps at once. CSS masks, no canvas.\n */\nexport function BayerDissolve({\n  items,\n  index = 0,\n  reveal = false,\n  duration = 720,\n  cell = 3,\n  refine = true,\n  className = \"\",\n  style,\n}: {\n  items: ReactNode[];\n  index?: number;\n  /** Print in from the ground on first view. */\n  reveal?: boolean;\n  duration?: number;\n  /** CSS pixels a cell at the end (snapped to device pixels). */\n  cell?: number;\n  /** Start on cells four times as big and refine as it prints. */\n  refine?: boolean;\n  className?: string;\n  style?: CSSProperties;\n}) {\n  const wrapRef = useRef<HTMLDivElement>(null);\n  const topRef = useRef<HTMLDivElement>(null);\n  const px = useSnappedCell(wrapRef, cell);\n  const reduced = useReducedMotion();\n  const at = clamp(Math.round(index), 0, Math.max(0, items.length - 1));\n  const [s, setS] = useState({ cur: at, prev: -1, run: 0, hold: false, live: false });\n  // A new index: keep the old state underneath and print the new one over it.\n  // (A reveal still waiting for its first view keeps waiting.)\n  if (at !== s.cur) setS({ cur: at, prev: reduced ? -1 : s.cur, run: s.run + 1, hold: s.hold, live: !reduced });\n\n  // The reveal: once it can animate, hide it (level 0) until it comes into view.\n  useEffect(() => {\n    const el = wrapRef.current;\n    if (!reveal || reduced || !el) return;\n    const raf = requestAnimationFrame(() => setS((v) => (v.run === 0 ? { ...v, run: 1, hold: true, live: true } : v)));\n    const io = new IntersectionObserver(\n      (entries) => {\n        if (!entries.some((e) => e.isIntersecting)) return;\n        io.disconnect();\n        setS((v) => (v.hold ? { ...v, hold: false } : v));\n      },\n      { threshold: 0.3 },\n    );\n    io.observe(el);\n    return () => {\n      cancelAnimationFrame(raf);\n      io.disconnect();\n    };\n  }, [reveal, reduced]);\n\n  // The dissolve: level 0 to 64, the cell refining from 4x to 1x over the first 70%.\n  useEffect(() => {\n    const el = topRef.current;\n    if (!el || !s.live || s.hold) return;\n    let raf = 0;\n    let t0 = 0;\n    const tick = (now: number) => {\n      if (!t0) t0 = now;\n      const p = clamp((now - t0) / Math.max(1, duration), 0, 1);\n      const scale = refine ? Math.max(1, Math.round(4 - 3 * smooth01(p / 0.7))) : 1;\n      Object.assign(el.style, daMaskStyle(64 * p, px * scale));\n      if (p < 1) raf = requestAnimationFrame(tick);\n      else setS((v) => ({ ...v, prev: -1, live: false }));\n    };\n    raf = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(raf);\n  }, [s.run, s.live, s.hold, duration, px, refine]);\n\n  return (\n    <div ref={wrapRef} className={\"relative isolate \" + className} style={style}>\n      {s.prev >= 0 ? (\n        <div aria-hidden className=\"absolute inset-0\">\n          {items[s.prev]}\n        </div>\n      ) : null}\n      <div ref={topRef} key={s.run} className=\"relative h-full\" style={s.live ? daMaskStyle(0, px * (refine ? 4 : 1)) : undefined}>\n        {items[s.cur]}\n      </div>\n    </div>\n  );\n}\n","type":"registry:component","target":"components/viberdy/bayer-dissolve.tsx"}],"meta":{"tier":"free","tags":["animation","transition","dither","bayer","dissolve","mask","reveal"],"href":"https://viberdy.dev/library/bayer-dissolve","aiPrompt":"Build a React primitive, `BayerDissolve({ items, index, reveal, duration, cell, refine, className, style })`.\n\nBuild 65 mask tiles once: an 8x8 SVG (shape-rendering crispEdges) with the cells whose Bayer index is below the level filled, as data URIs. State: the current and previous index and a run counter, updated during render when index changes (the stored-previous-value pattern). Render the previous state absolutely underneath (aria-hidden) and the current one keyed by the run, starting masked at level 0. A requestAnimationFrame loop walks the level from 0 to 64 over duration and writes mask-image and mask-size straight to the element; with refine the tile starts at 4x the cell and rounds down to 1x over the first 70%. At the end, drop the previous state and the mask. reveal: once it can animate, mask the content at level 0 and run the loop when it is 30% in view. Cells snap to whole device pixels.\n\nDither & ASCII grammar: a warm black ground #0b0b0d (panels #121214, raised #19191c), one ink, paper #f3f0e6 (text at 92/60/38%, hairlines at 8% and 16%), and one signal colour, vermillion #ff4f2b, used as a second ink inside the pictures (the sun, a glint, a ball, a newly lit dot, a wordmark) and for a live state confined to a small mark (a square that lights, a peak character), never as a panel fill; a primary control's ink is paper, with signal kept for a momentary action. Every picture is computed and printed on purpose: rendered scenes dither in linear light and photographs on a gentler 1.5 curve so their midtones stay full, cells snap to whole device pixels (never blurred into grey), the 8x8 Bayer matrix for anything CSS, 64x64 void-and-cluster blue noise for the signature pictures, true error diffusion only on the CPU. Type stays crisp and undithered: Funnel Display through var(--font-funnel, \"Funnel Display\", ...) at 600-700 with -0.035em tracking for display, Geist for reading, Geist Mono uppercase with +0.14em tracking for labels and for every glyph an ASCII transform draws. Radii 10px controls, 14px cards, 18px panels. Motion: a transform change dissolves through blue noise in ~450ms, a fill prints in Bayer order in ~260ms and out in ~360ms, pictures print in on first view over ~900ms, ambient scenes loop over 30s or more. Respect prefers-reduced-motion (the picture still, changes instant). No dependencies beyond React.","license":"https://viberdy.dev/license"}}