{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"ascii-resolve-heading","type":"registry:component","title":"ASCII Resolve Heading","description":"A heading that resolves from ASCII into type: its own letterforms redrawn in shape-matched glyphs step from coarse to fine as it comes into view, then a lens under the pointer shows the glyphs again.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/ascii-resolve-heading.tsx","content":"\"use client\";\n\nimport { useEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport type { CSSProperties } from \"react\";\n\n/**\n * AsciiResolveHeading — a heading that resolves from ASCII into type.\n *\n * The heading's own letterforms are rasterised and redrawn in the page's\n * mono face, glyph by glyph, matched to the shape of each cell. On view it\n * steps from coarse glyphs to fine and lands on the crisp heading in about\n * 900ms; afterwards a lens under the pointer shows the glyphs underneath.\n * Real text, named once; crisp until it can animate. The default size reads\n * the nearest @container (7cqw) and falls back to the viewport.\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\nconst MONO = 'var(--font-mono, \"Geist Mono\", ui-monospace, \"SFMono-Regular\", Menlo, Consolas, monospace)';\n\nconst DISPLAY = 'var(--font-funnel, \"Funnel Display\", var(--font-sans, \"Geist\"), ui-sans-serif, system-ui, sans-serif)';\n\nconst EASE = \"cubic-bezier(0.22, 1, 0.36, 1)\";\n\n/** One ink on a warm black ground, and one signal colour. */\nconst SHEET = {\n  ground: \"#0b0b0d\",\n  panel: \"#121214\",\n  raised: \"#19191c\",\n  paper: \"#f3f0e6\",\n  ink: \"rgba(243,240,230,0.92)\",\n  ink2: \"rgba(243,240,230,0.6)\",\n  ink3: \"rgba(243,240,230,0.38)\",\n  line: \"rgba(243,240,230,0.08)\",\n  line2: \"rgba(243,240,230,0.16)\",\n  signal: \"#ff4f2b\",\n} as const;\n\nfunction clamp(v: number, lo: number, hi: number): number {\n  return v < lo ? lo : v > hi ? hi : v;\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/**\n * The glyph atlas for ASCII: the 95 printable characters of the mono face,\n * drawn once into cells of the stage's glyph size, and each glyph's coverage\n * in six regions (two across, three down), normalised so the densest region\n * of any glyph is 1. The shader matches cells against these.\n */\nfunction daAtlas(family: string, fontPx: number): { canvas: HTMLCanvasElement; sig: Uint8Array; n: number; cw: number; ch: number } {\n  const n = 95;\n  const probe = document.createElement(\"canvas\").getContext(\"2d\");\n  const font = `${fontPx}px ${family}`;\n  let adv = fontPx * 0.6;\n  if (probe) {\n    probe.font = font;\n    adv = probe.measureText(\"0\").width || adv;\n  }\n  const cw = Math.max(3, Math.round(adv));\n  const ch = Math.max(5, Math.round(fontPx * 1.3));\n  const canvas = document.createElement(\"canvas\");\n  canvas.width = cw * n;\n  canvas.height = ch;\n  const x = canvas.getContext(\"2d\", { willReadFrequently: true });\n  const sig = new Uint8Array(n * 2 * 4);\n  if (!x) return { canvas, sig, n, cw, ch };\n  x.fillStyle = \"#000\";\n  x.fillRect(0, 0, canvas.width, canvas.height);\n  x.fillStyle = \"#fff\";\n  x.font = font;\n  x.textAlign = \"center\";\n  x.textBaseline = \"middle\";\n  for (let i = 0; i < n; i++) x.fillText(String.fromCharCode(32 + i), i * cw + cw / 2, ch / 2 + fontPx * 0.04);\n  const data = x.getImageData(0, 0, canvas.width, canvas.height).data;\n  const raw = new Float32Array(n * 6);\n  let mx = 0;\n  for (let g = 0; g < n; g++) {\n    for (let r = 0; r < 3; r++) {\n      for (let q = 0; q < 2; q++) {\n        const x0 = g * cw + Math.floor((q * cw) / 2);\n        const x1 = g * cw + Math.floor(((q + 1) * cw) / 2);\n        const y0 = Math.floor((r * ch) / 3);\n        const y1 = Math.floor(((r + 1) * ch) / 3);\n        let s = 0;\n        for (let y = y0; y < y1; y++) for (let xx = x0; xx < x1; xx++) s += data[(y * canvas.width + xx) * 4];\n        const v = s / Math.max(1, (x1 - x0) * (y1 - y0) * 255);\n        raw[g * 6 + r * 2 + q] = v;\n        mx = Math.max(mx, v);\n      }\n    }\n  }\n  for (let g = 0; g < n; g++) {\n    for (let k = 0; k < 6; k++) {\n      const row = k < 3 ? 0 : 1;\n      const col = k % 3;\n      sig[(row * n + g) * 4 + col] = Math.round((raw[g * 6 + k] / (mx || 1)) * 255);\n    }\n    sig[g * 4 + 3] = 255;\n    sig[(n + g) * 4 + 3] = 255;\n  }\n  return { canvas, sig, n, cw, ch };\n}\n\n/**\n * Sets a raster (alpha 0-255, `w` x `h`) as ASCII at one glyph size: each\n * cell's coverage in six regions is sharpened and matched against the glyph\n * signatures of the mono face. Returns the lines and the cell size.\n */\nfunction daAsciiOf(alpha: Uint8ClampedArray, w: number, h: number, family: string, fontPx: number): { text: string; cw: number; ch: number; adv: number } {\n  const a = daAtlas(family, fontPx);\n  const n = a.n;\n  const sig: number[][] = [];\n  for (let g = 0; g < n; g++) {\n    const v: number[] = [];\n    for (let k = 0; k < 6; k++) v.push(a.sig[((k < 3 ? 0 : 1) * n + g) * 4 + (k % 3)] / 255);\n    sig.push(v);\n  }\n  const probe = document.createElement(\"canvas\").getContext(\"2d\");\n  let adv = a.cw;\n  if (probe) {\n    probe.font = `${fontPx}px ${family}`;\n    adv = probe.measureText(\"0\").width || adv;\n  }\n  const cols = Math.ceil(w / a.cw);\n  const rows = Math.ceil(h / a.ch);\n  const out: string[] = [];\n  const v = [0, 0, 0, 0, 0, 0];\n  for (let r = 0; r < rows; r++) {\n    let line = \"\";\n    for (let c = 0; c < cols; c++) {\n      let mx = 0;\n      for (let k = 0; k < 6; k++) {\n        const x0 = Math.floor(c * a.cw + ((k % 2) * a.cw) / 2);\n        const x1 = Math.floor(c * a.cw + (((k % 2) + 1) * a.cw) / 2);\n        const y0 = Math.floor(r * a.ch + (Math.floor(k / 2) * a.ch) / 3);\n        const y1 = Math.floor(r * a.ch + ((Math.floor(k / 2) + 1) * a.ch) / 3);\n        let s = 0;\n        let m = 0;\n        for (let y = y0; y < Math.min(y1, h); y += 1) {\n          for (let x = x0; x < Math.min(x1, w); x += 1) {\n            s += alpha[(y * w + x) * 4 + 3];\n            m++;\n          }\n        }\n        v[k] = m ? s / (m * 255) : 0;\n        mx = Math.max(mx, v[k]);\n      }\n      if (mx < 0.02) {\n        line += \" \";\n        continue;\n      }\n      for (let k = 0; k < 6; k++) v[k] = Math.pow(v[k] / mx, 1.6) * mx;\n      let best = Infinity;\n      let bi = 0;\n      for (let g = 0; g < n; g++) {\n        const s = sig[g];\n        let d = 0;\n        for (let k = 0; k < 6; k++) d += (s[k] - v[k]) * (s[k] - v[k]);\n        if (d < best) {\n          best = d;\n          bi = g;\n        }\n      }\n      line += String.fromCharCode(32 + bi);\n    }\n    out.push(line.replace(/\\s+$/, \"\"));\n  }\n  return { text: out.join(\"\\n\"), cw: a.cw, ch: a.ch, adv };\n}\n\ntype DaLevel = { text: string; cw: number; ch: number; adv: number; px: number };\n\n/** Writes one glyph level into a pre, sized so each glyph lands on its cell. */\nfunction daShowLevel(el: HTMLPreElement | null, L: DaLevel | undefined) {\n  if (!el || !L) return;\n  el.textContent = L.text;\n  el.style.fontSize = `${L.px}px`;\n  el.style.lineHeight = `${L.ch}px`;\n  el.style.letterSpacing = `${L.cw - L.adv}px`;\n}\n\n/**\n * AsciiResolveHeading — a heading that resolves from ASCII into type.\n *\n * The heading's own letterforms are rasterised and redrawn in the page's\n * mono face, glyph by glyph, matched to the shape of each cell. When it\n * comes into view it steps from coarse glyphs to fine ones and lands on the\n * crisp heading in about 900ms. Afterwards a lens follows the pointer across\n * it and shows the finest glyphs underneath. The heading is real text named\n * once for screen readers; it renders crisp first and only turns to glyphs\n * once it can animate. A `progress` prop (0-1) drives it by hand. Its\n * default size, clamp(40px, 7cqw, 92px), reads the nearest @container and\n * falls back to the viewport; pass fontSize in `style` to set your own.\n */\nexport function AsciiResolveHeading({\n  lines = \"Any image. / Any output.\",\n  as = \"h2\",\n  glyph = 7,\n  lens = true,\n  progress,\n  className = \"\",\n  style,\n}: {\n  /** \"/\" breaks a line. */\n  lines?: string;\n  as?: \"h1\" | \"h2\" | \"h3\";\n  /** The finest glyph size, in CSS pixels. */\n  glyph?: number;\n  /** A lens that shows the glyphs under the pointer once resolved. */\n  lens?: boolean;\n  /** 0 = coarsest glyphs, 1 = crisp; drives it by hand instead of on view. */\n  progress?: number;\n  className?: string;\n  style?: CSSProperties;\n}) {\n  const Tag = as;\n  const parts = lines.split(\"/\").map((l) => l.trim()).filter(Boolean);\n  const label = parts.join(\" \");\n  const hostRef = useRef<HTMLHeadingElement>(null);\n  const textRef = useRef<HTMLSpanElement>(null);\n  const preRef = useRef<HTMLPreElement>(null);\n  const lensRef = useRef<HTMLPreElement>(null);\n  const reduced = useReducedMotion();\n  const levels = useRef<DaLevel[]>([]);\n  const [phase, setPhase] = useState<\"static\" | \"armed\" | \"resolving\" | \"done\">(\"static\");\n  const [version, setVersion] = useState(0);\n  const ready = version > 0;\n  const driven = progress !== undefined;\n\n  // Rasterise the heading as laid out and set it at four glyph sizes, coarse to fine.\n  useEffect(() => {\n    const host = hostRef.current;\n    const text = textRef.current;\n    if (!host || !text) return;\n    let alive = true;\n    const build = () => {\n      if (!alive) return;\n      const w = Math.ceil(text.offsetWidth);\n      const h = Math.ceil(text.offsetHeight);\n      if (w < 4 || h < 4) return;\n      const c = document.createElement(\"canvas\");\n      c.width = w;\n      c.height = h;\n      const x = c.getContext(\"2d\", { willReadFrequently: true });\n      if (!x) return;\n      const cs = getComputedStyle(text);\n      x.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;\n      (x as CanvasRenderingContext2D & { letterSpacing?: string }).letterSpacing = cs.letterSpacing === \"normal\" ? \"0px\" : cs.letterSpacing;\n      x.textBaseline = \"middle\";\n      x.fillStyle = \"#fff\";\n      const box = text.getBoundingClientRect();\n      const k = text.offsetWidth ? box.width / text.offsetWidth : 1;\n      for (const span of Array.from(text.children) as HTMLElement[]) {\n        const r = span.getBoundingClientRect();\n        x.fillText(span.textContent ?? \"\", (r.left - box.left) / k, (r.top - box.top + r.height / 2) / k);\n      }\n      const data = x.getImageData(0, 0, w, h).data;\n      text.style.fontFamily = MONO;\n      const mono = getComputedStyle(text).fontFamily || \"monospace\";\n      text.style.fontFamily = \"\";\n      const sizes = [glyph * 3.4, glyph * 2.3, glyph * 1.5, glyph];\n      levels.current = sizes.map((px) => ({ ...daAsciiOf(data, w, h, mono, px), px }));\n      setVersion((n) => n + 1);\n    };\n    const ro = new ResizeObserver(() => build());\n    ro.observe(text);\n    document.fonts?.ready.then(() => build());\n    return () => {\n      alive = false;\n      ro.disconnect();\n    };\n  }, [glyph, lines]);\n\n\n  // On view: arm (glyphs, text hidden), then step coarse to fine and land on the type.\n  useEffect(() => {\n    const host = hostRef.current;\n    if (!host || !ready || driven || reduced) return;\n    let stage = \"static\";\n    const timers: number[] = [];\n    const raf = requestAnimationFrame(() => {\n      if (stage !== \"static\") return;\n      stage = \"armed\";\n      daShowLevel(preRef.current, levels.current[0]);\n      setPhase(\"armed\");\n    });\n    const io = new IntersectionObserver(\n      (entries) => {\n        if (!entries.some((e) => e.isIntersecting) || stage === \"resolving\") return;\n        io.disconnect();\n        if (stage === \"static\") daShowLevel(preRef.current, levels.current[0]);\n        stage = \"resolving\";\n        setPhase(\"resolving\");\n        [1, 2, 3].forEach((i, n) => timers.push(window.setTimeout(() => daShowLevel(preRef.current, levels.current[i]), 150 * (n + 1))));\n        timers.push(window.setTimeout(() => setPhase(\"done\"), 620));\n      },\n      { threshold: 0.45 },\n    );\n    io.observe(host);\n    return () => {\n      cancelAnimationFrame(raf);\n      io.disconnect();\n      timers.forEach((t) => clearTimeout(t));\n    };\n  }, [ready, driven, reduced]);\n\n  // Driven by hand: the level follows the prop.\n  useEffect(() => {\n    if (progress === undefined || !ready) return;\n    const i = Math.min(3, Math.floor(clamp(progress, 0, 1) * 4.999));\n    if (progress < 0.96) daShowLevel(preRef.current, levels.current[i]);\n  }, [progress, ready, version]);\n\n  // The lens: the finest glyphs under the pointer, the type masked away there.\n  useEffect(() => {\n    const host = hostRef.current;\n    if (!host || !lens || !ready) return;\n    daShowLevel(lensRef.current, levels.current[3]);\n    const move = (e: PointerEvent) => {\n      const r = host.getBoundingClientRect();\n      const k = host.offsetWidth ? r.width / host.offsetWidth : 1;\n      host.style.setProperty(\"--da-lx\", `${(e.clientX - r.left) / k}px`);\n      host.style.setProperty(\"--da-ly\", `${(e.clientY - r.top) / k}px`);\n      host.style.setProperty(\"--da-lr\", \"74px\");\n    };\n    const leave = () => host.style.setProperty(\"--da-lr\", \"0px\");\n    host.addEventListener(\"pointermove\", move);\n    host.addEventListener(\"pointerleave\", leave);\n    return () => {\n      host.removeEventListener(\"pointermove\", move);\n      host.removeEventListener(\"pointerleave\", leave);\n    };\n  }, [lens, ready, version]);\n\n  const crisp = driven ? clamp(progress, 0, 1) >= 0.96 : phase === \"static\" || phase === \"done\";\n  const glyphs = driven ? !crisp : phase === \"armed\" || phase === \"resolving\";\n  const lensOn = lens && ready && crisp;\n  const hole = \"radial-gradient(circle var(--da-lr, 0px) at var(--da-lx, 50%) var(--da-ly, 50%), transparent 97%, #000 100%)\";\n  const spot = \"radial-gradient(circle var(--da-lr, 0px) at var(--da-lx, 50%) var(--da-ly, 50%), #000 97%, transparent 100%)\";\n\n  return (\n    <Tag\n      ref={hostRef}\n      aria-label={label}\n      className={\"relative m-0 font-bold leading-[0.96] \" + className}\n      style={{ fontFamily: DISPLAY, letterSpacing: \"-0.035em\", color: SHEET.paper, fontSize: \"clamp(40px, 7cqw, 92px)\", ...style }}\n    >\n      <span\n        ref={textRef}\n        aria-hidden\n        className=\"block\"\n        style={{\n          opacity: glyphs ? 0 : 1,\n          transition: reduced ? \"none\" : `opacity 280ms ${EASE}`,\n          maskImage: lensOn ? hole : undefined,\n          WebkitMaskImage: lensOn ? hole : undefined,\n        }}\n      >\n        {parts.map((p, i) => (\n          <span key={i} className=\"block w-max max-w-full\">\n            {p}\n          </span>\n        ))}\n      </span>\n      <pre\n        ref={preRef}\n        aria-hidden\n        className=\"pointer-events-none absolute left-0 top-0 m-0 overflow-hidden whitespace-pre\"\n        style={{ fontFamily: MONO, color: SHEET.paper, opacity: glyphs ? 1 : 0, transition: reduced ? \"none\" : `opacity 280ms ${EASE}`, letterSpacing: 0 }}\n      />\n      <pre\n        ref={lensRef}\n        aria-hidden\n        className=\"pointer-events-none absolute left-0 top-0 m-0 overflow-hidden whitespace-pre\"\n        style={{ fontFamily: MONO, color: SHEET.paper, opacity: lensOn ? 1 : 0, maskImage: spot, WebkitMaskImage: spot }}\n      />\n    </Tag>\n  );\n}\n","type":"registry:component","target":"components/viberdy/ascii-resolve-heading.tsx"}],"meta":{"tier":"free","tags":["text effect","ascii","heading","reveal","scroll","hover","typography"],"href":"https://viberdy.dev/library/ascii-resolve-heading","aiPrompt":"Build a React + Tailwind heading, `AsciiResolveHeading({ lines, as, glyph, lens, progress, className, style })`.\n\nRender each line as a block span inside an aria-hidden span, the heading named by aria-label. After layout (and on resize and font load), draw the lines into a 2D canvas at their laid-out positions in the computed font, with its letter-spacing. Measure the mono face's 95 printable glyphs: each one's coverage in six regions (two across, three down), normalised so the densest region of any glyph is 1. Then set the raster as ASCII at glyph sizes glyph x 3.4, 2.3, 1.5 and 1: per cell, the six region averages, each raised to the power 1.6 relative to the cell's brightest, matched to the nearest glyph signature (empty cells are spaces). Show a level in an absolutely positioned pre whose font-size, line-height and letter-spacing make each glyph land on its cell. On mount (not reduced motion) show the coarsest level with the type hidden; when 45% in view, step to the next level every 150ms and then fade the type back in over 280ms. Afterwards, a lens: CSS variables from the pointer drive a 74px radial mask that shows the finest level and punches a hole in the type.\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"}}