{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "glyph-field",
  "type": "registry:ui",
  "title": "Glyph Field",
  "description": "Your mark drawn in type. A word, an SVG path or a photo is printed as a grid of monospace glyphs that run from bare paper through dots to a dense @. It prints left to right the first time it scrolls into view, and the pointer inks the glyphs it passes over in your accent, which then dry back to their resting weight.",
  "author": "KeyframeUI <https://keyframeui.com>",
  "categories": [
    "canvas",
    "hero",
    "hover",
    "text"
  ],
  "docs": "Live preview, examples and props: https://keyframeui.com/components/glyph-field",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "components/ui/glyph-field.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { useReducedMotion } from \"motion/react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/**\n * Keep:\n * - Each glyph and color step is drawn once into an atlas, and a frame redraws only the cells whose\n *   glyph or shade changed, each with a single `drawImage`.\n * - One rAF loop runs only while something moves (the print, the brush, wet ink) and stops off\n *   screen, on a hidden tab or once the ink has dried; drift runs on a slow interval instead.\n * - The print runs once per mark, the first time it scrolls into view; a resize resets the grid\n *   without reprinting.\n * - The brush lands where the pointer enters instead of gliding in, and stamps along its path so a\n *   fast stroke stays unbroken.\n * - Under reduced motion it prints at once with no drift, the brush follows the pointer exactly,\n *   and ink dries on the short `dryReduced`.\n */\nconst TIMING = {\n  /**\n   * The print head, in seconds: the wait after it scrolls into view, crossing the mark (the\n   * `printDuration` prop) and the flickering band at its edge. `fps` is the flicker's rate.\n   */\n  print: { delay: 0.12, duration: 0.75, band: 0.28, fps: 30 },\n  /** The ink drying back, as a time constant in seconds (the `dry` prop). */\n  dry: 0.42,\n  /** The same under reduced motion, in seconds. */\n  dryReduced: 0.1,\n  /** The spring smoothing the pointer. */\n  brush: { stiffness: 320, damping: 34 },\n  /** Drift: ms between slips, and the range in seconds a slipped glyph holds. */\n  drift: { every: 140, hold: [0.6, 1.4] },\n} as const;\n\n/* ─────────────────────────────────────────────────────────\n * GLYPH FIELD STORYBOARD\n *\n *  rest     your mark set in type. Every cell of a monospace\n *           grid holds the glyph whose weight matches the shape\n *           under it, from bare paper through . : - = + to a\n *           dense @. A word, an SVG path or a photo; with none\n *           of them, a lit orbit\n *  print    the first time it scrolls into view, a print head\n *           runs left to right. Ahead of it the paper is blank;\n *           in a 0.28s band at its edge each cell flickers\n *           through random glyphs at 30fps; behind it every\n *           cell has settled. 0.75s across, about 1.1s in all\n *  ink      the pointer is a wet brush, smoothed by a spring\n *           (320 / 34). Cells under it gain weight (up to a full\n *           @ on the shape, a faint mark on bare paper) and take\n *           the accent color, then dry back to their resting\n *           glyph over about 1.2s (time constant 0.42s)\n *  touch    a tap or a drag inks the same way; the page still\n *           scrolls\n *  drift    at idle a few glyphs (0.4% of the mark every 140ms)\n *           slip one step lighter or heavier for about a second,\n *           like ink settling into paper\n *  again    a new word, path or photo prints again; a resize\n *           only resets the grid, it doesn't reprint\n *  sleep    nothing runs off screen, on a hidden tab, or once\n *           the ink has dried and the pointer is still\n *  reduced  printed at once and no drift; the brush follows the\n *           pointer exactly and dries in about 0.3s\n * ───────────────────────────────────────────────────────── */\n\nconst GLYPH = {\n  lineHeight: 1.2, // cell height, as a share of `cellSize`; the width is the font's own advance\n  supersample: 3, // samples per cell side when the shape is read\n  print: { scatter: 0.14, slant: 0.12 }, // share of the sweep, share of the height\n  ink: { radius: 88, paper: 0.4, shape: 0.55, grain: 0.25 }, // px, weight gained on bare paper, on the shape (× its weight), brush edge noise\n  drift: { share: 0.004 }, // share of the mark per slip\n  alpha: [0.38, 1], // glyph opacity, from the lightest mark to the densest\n  floor: 0.05, // weight under which a cell is bare paper\n  shades: 6, // color steps from the glyph color to the accent\n  maxDpr: 2,\n} as const;\n\n// The default shape: an orbit seen from a little above, lit from the upper left.\nconst ORBIT = {\n  margin: 0.94, // share of the box the outer orbit reaches, at `fit=\"contain\"`\n  squash: 0.6, // height of the ellipse, as a share of its width\n  tilt: -0.22, // rad\n  thin: 0.028, // band width at the back, share of the radius\n  thick: 0.1, // and at the front\n  front: 2.2, // rad, where the band is widest\n  light: -2.3, // rad, where it's lit\n  halo: 1.16, // a faint outer orbit, as a share of the radius\n  haloWeight: 0.3,\n} as const;\n\ntype Tone = \"auto\" | \"dark\" | \"light\";\ntype Fit = \"contain\" | \"cover\";\n\ntype Source =\n  | { kind: \"orbit\" }\n  | { kind: \"text\"; text: string; font: string }\n  | { kind: \"path\"; d: string; box: [number, number, number, number] }\n  | { kind: \"image\"; src: string };\n\ntype Options = {\n  cellSize: number;\n  glyphs: string;\n  tone: Tone;\n  fit: Fit;\n  softness: number;\n  radius: number;\n  decode: boolean;\n  drift: boolean;\n  sweep: number;\n  dry: number;\n  reduced: boolean;\n};\n\nconst DEFAULT_GLYPHS = \" .:-=+*#%@\";\n\nconst clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v);\nconst smoothstep = (a: number, b: number, x: number) => {\n  const t = clamp01((x - a) / (b - a));\n  return t * t * (3 - 2 * t);\n};\n/** A stable 0…1 value for a cell and a tick, so a flicker frame looks the same every time it's drawn. */\nconst hash = (i: number, tick: number) => (Math.imul(i ^ Math.imul(tick, 40503), 2654435761) >>> 0) / 4294967296;\n\nfunction sourceKey(s: Source) {\n  switch (s.kind) {\n    case \"orbit\":\n      return \"orbit\";\n    case \"text\":\n      return `text:${s.font}:${s.text}`;\n    case \"path\":\n      return `path:${s.box.join(\",\")}:${s.d}`;\n    case \"image\":\n      return `image:${s.src}`;\n  }\n}\n\n/** Box blur along rows and columns, in place. Radii are in cells. */\nfunction blur(values: Float32Array, cols: number, rows: number, rx: number, ry: number) {\n  const tmp = new Float32Array(values.length);\n  if (rx > 0) {\n    for (let r = 0; r < rows; r++) {\n      const o = r * cols;\n      for (let c = 0; c < cols; c++) {\n        let sum = 0;\n        let n = 0;\n        for (let k = Math.max(0, c - rx); k <= Math.min(cols - 1, c + rx); k++) {\n          sum += values[o + k];\n          n++;\n        }\n        tmp[o + c] = sum / n;\n      }\n    }\n    values.set(tmp);\n  }\n  if (ry > 0) {\n    for (let c = 0; c < cols; c++) {\n      for (let r = 0; r < rows; r++) {\n        let sum = 0;\n        let n = 0;\n        for (let k = Math.max(0, r - ry); k <= Math.min(rows - 1, r + ry); k++) {\n          sum += values[k * cols + c];\n          n++;\n        }\n        tmp[r * cols + c] = sum / n;\n      }\n    }\n    values.set(tmp);\n  }\n}\n\nfunction percentile(values: Float32Array, p: number) {\n  const sorted = Float32Array.from(values).sort();\n  return sorted[Math.min(sorted.length - 1, Math.max(0, Math.round(p * (sorted.length - 1))))];\n}\n\nfunction createField() {\n  let root: HTMLElement | null = null;\n  let canvas: HTMLCanvasElement | null = null;\n  let ctx: CanvasRenderingContext2D | null = null;\n  let probes: { glyph: HTMLElement; accent: HTMLElement } | null = null;\n\n  let options: Options = {\n    cellSize: 12,\n    glyphs: DEFAULT_GLYPHS,\n    tone: \"auto\",\n    fit: \"contain\",\n    softness: 0.4,\n    radius: GLYPH.ink.radius,\n    decode: true,\n    drift: true,\n    sweep: TIMING.print.duration,\n    dry: TIMING.dry,\n    reduced: false,\n  };\n  let source: Source = { kind: \"orbit\" };\n  let image: HTMLImageElement | null = null; // loaded and ready to read\n  let warned = false;\n\n  // The grid, in device pixels.\n  let dpr = 1;\n  let width = 0;\n  let height = 0;\n  let cw = 1;\n  let ch = 1;\n  let cols = 0;\n  let rows = 0;\n  let ox = 0;\n  let oy = 0;\n  let count = 0;\n\n  let weight = new Float32Array(0); // 0…1, the shape under each cell\n  let ink = new Float32Array(0); // 0…1, wet ink on each cell\n  let prevInk = new Float32Array(0);\n  let grain = new Float32Array(0); // 0…1 per cell, a seeded random\n  let settle = new Float32Array(0); // s after the print starts when a cell lands\n  let drawn = new Int16Array(0); // atlas slot drawn in each cell, -1 for bare paper\n  let slip = new Int8Array(0); // drift: -1, 0 or +1 glyph steps\n  let marked = new Int32Array(0); // cells with a glyph at rest, for drift to pick from\n  const slips: { i: number; until: number }[] = [];\n\n  let atlas: HTMLCanvasElement | null = null;\n  let colors: string[] = [];\n\n  let printing = false;\n  let printStart = 0;\n  let printEnd = 0;\n  let printed = false; // the print has run (or was skipped) for the current source\n  let ready = false; // the source has been read into `weight`\n\n  const brush = { x: 0, y: 0, vx: 0, vy: 0, tx: 0, ty: 0, lx: 0, ly: 0, inside: false, down: false };\n\n  let raf = 0;\n  let last = 0;\n  let visible = false;\n  let driftTimer = 0;\n  const cleanups: (() => void)[] = [];\n\n  const now = () => performance.now() / 1000;\n  const glyphCount = () => options.glyphs.length;\n\n  function readColors() {\n    if (!probes) return;\n    const glyph = getComputedStyle(probes.glyph).color;\n    const accent = getComputedStyle(probes.accent).color;\n    colors = [];\n    for (let i = 0; i < GLYPH.shades; i++) {\n      const share = Math.round((i / (GLYPH.shades - 1)) * 100);\n      probes.glyph.style.color = `color-mix(in oklab, ${glyph}, ${accent} ${share}%)`;\n      colors.push(getComputedStyle(probes.glyph).color);\n    }\n    probes.glyph.style.color = \"\";\n  }\n\n  /** The glyph font comes from the canvas, which is `font-mono` unless `canvasClassName` says otherwise. */\n  function font(px: number) {\n    const style = canvas ? getComputedStyle(canvas) : null;\n    return `${style?.fontWeight ?? 400} ${px}px ${style?.fontFamily || \"ui-monospace, monospace\"}`;\n  }\n\n  /** One slot per glyph and color step, drawn once, so each cell is a single drawImage. */\n  function buildAtlas() {\n    const n = glyphCount();\n    atlas ??= document.createElement(\"canvas\");\n    atlas.width = n * cw;\n    atlas.height = GLYPH.shades * ch;\n    const a = atlas.getContext(\"2d\");\n    if (!a) return;\n    a.clearRect(0, 0, atlas.width, atlas.height);\n    a.font = font(options.cellSize * dpr);\n    a.textAlign = \"center\";\n    a.textBaseline = \"middle\";\n    for (let s = 0; s < GLYPH.shades; s++) {\n      a.fillStyle = colors[s] ?? \"#71717a\";\n      for (let g = 1; g < n; g++) {\n        a.globalAlpha = GLYPH.alpha[0] + ((GLYPH.alpha[1] - GLYPH.alpha[0]) * (g - 1)) / Math.max(1, n - 2);\n        a.save();\n        a.beginPath();\n        a.rect(g * cw, s * ch, cw, ch);\n        a.clip();\n        a.fillText(options.glyphs[g], g * cw + cw / 2, s * ch + ch / 2);\n        a.restore();\n      }\n    }\n  }\n\n  function layout() {\n    if (!canvas || !ctx) return;\n    const w = canvas.clientWidth;\n    const h = canvas.clientHeight;\n    dpr = Math.min(window.devicePixelRatio || 1, GLYPH.maxDpr);\n    width = Math.round(w * dpr);\n    height = Math.round(h * dpr);\n    canvas.width = width;\n    canvas.height = height;\n\n    ctx.font = font(options.cellSize * dpr);\n    cw = Math.max(1, Math.round(ctx.measureText(\"M\").width));\n    ch = Math.max(1, Math.round(options.cellSize * GLYPH.lineHeight * dpr));\n    cols = Math.max(0, Math.floor(width / cw));\n    rows = Math.max(0, Math.floor(height / ch));\n    ox = Math.floor((width - cols * cw) / 2);\n    oy = Math.floor((height - rows * ch) / 2);\n\n    if (cols * rows !== count) {\n      count = cols * rows;\n      weight = new Float32Array(count);\n      ink = new Float32Array(count);\n      prevInk = new Float32Array(count);\n      settle = new Float32Array(count);\n      drawn = new Int16Array(count);\n      slip = new Int8Array(count);\n      slips.length = 0;\n      grain = new Float32Array(count);\n      // Seeded, so the brush's grain and the print's scatter are the same on every render.\n      let seed = 48271;\n      for (let i = 0; i < count; i++) grain[i] = (seed = (seed * 16807) % 2147483647) / 2147483647;\n    }\n    read();\n    buildAtlas();\n    repaint();\n  }\n\n  /** Reads the source into one weight per cell. */\n  function read() {\n    ready = false;\n    if (!count) return;\n    const k = GLYPH.supersample;\n    const gw = (cols * cw) / dpr; // the grid, in CSS px\n    const gh = (rows * ch) / dpr;\n    const cx = gw / 2;\n    const cy = gh / 2;\n    weight.fill(0);\n\n    if (source.kind === \"orbit\") {\n      // Stood on end in a tall box, so it frames the content on a phone too.\n      const tilt = gh > gw * 1.15 ? Math.PI / 2 + ORBIT.tilt : ORBIT.tilt;\n      const cos = Math.cos(tilt);\n      const sin = Math.sin(tilt);\n      // Half the width and height of the tilted orbit at R = 1, out to the halo's edge.\n      const outer = ORBIT.halo + ORBIT.thin;\n      const ex = Math.hypot(cos, ORBIT.squash * sin) * outer;\n      const ey = Math.hypot(sin, ORBIT.squash * cos) * outer;\n      const R = (options.fit === \"cover\" ? Math.max : Math.min)((gw * ORBIT.margin) / 2 / ex, (gh * ORBIT.margin) / 2 / ey);\n      const a = R;\n      const b = R * ORBIT.squash;\n      const band = (e: number, theta: number, ring: number, thinness: number) => {\n        // Distance from the ellipse, roughly in px: how far off the ring the point sits, times the radius along its ray.\n        const d = Math.abs(e - ring) * Math.hypot(a * Math.cos(theta), b * Math.sin(theta));\n        const half = R * thinness;\n        return 1 - smoothstep(half * 0.25, half, d);\n      };\n      for (let r = 0; r < rows; r++) {\n        for (let c = 0; c < cols; c++) {\n          const x = ((c + 0.5) * cw) / dpr - cx;\n          const y = ((r + 0.5) * ch) / dpr - cy;\n          const u = x * cos + y * sin;\n          const v = -x * sin + y * cos;\n          const e = Math.hypot(u / a, v / b);\n          const theta = Math.atan2(v / b, u / a);\n          const front = 0.5 + 0.5 * Math.cos(theta - ORBIT.front);\n          const lit = 0.5 + 0.5 * Math.cos(theta - ORBIT.light);\n          const main = band(e, theta, 1, ORBIT.thin + (ORBIT.thick - ORBIT.thin) * front * front) * (0.3 + 0.7 * lit);\n          const halo = band(e, theta, ORBIT.halo, ORBIT.thin * 0.6) * ORBIT.haloWeight * (0.4 + 0.6 * (1 - lit));\n          weight[r * cols + c] = Math.max(main, halo);\n        }\n      }\n      finish(false);\n      return;\n    }\n\n    if (source.kind === \"image\" && !image) return;\n\n    const sample = document.createElement(\"canvas\");\n    sample.width = cols * k;\n    sample.height = rows * k;\n    const s = sample.getContext(\"2d\", { willReadFrequently: true });\n    if (!s) return;\n    // Draw in CSS px; the transform maps them onto k × k samples per cell.\n    const kx = (k * dpr) / cw;\n    const ky = (k * dpr) / ch;\n    const place = (w: number, h: number, pad: number) => {\n      const scale = options.fit === \"cover\" ? Math.max(gw / w, gh / h) : Math.min((gw * pad) / w, (gh * pad) / h);\n      return { scale, x: cx - (w * scale) / 2, y: cy - (h * scale) / 2 };\n    };\n\n    if (source.kind === \"text\") {\n      const lines = source.text.split(\"\\n\");\n      const base = 100;\n      s.font = `800 ${base}px ${source.font}`;\n      const metrics = lines.map((line) => s.measureText(line));\n      const ascent = Math.max(...metrics.map((m) => m.actualBoundingBoxAscent));\n      const descent = Math.max(...metrics.map((m) => m.actualBoundingBoxDescent));\n      const lineHeight = (ascent + descent) * 1.1;\n      const w = Math.max(...metrics.map((m) => m.width));\n      const h = ascent + descent + lineHeight * (lines.length - 1);\n      const p = place(w, h, 0.9);\n      s.setTransform(kx * p.scale, 0, 0, ky * p.scale, kx * p.x, ky * p.y);\n      s.fillStyle = \"#fff\";\n      s.textBaseline = \"alphabetic\";\n      lines.forEach((line, i) => s.fillText(line, (w - metrics[i].width) / 2, ascent + i * lineHeight));\n    } else if (source.kind === \"path\") {\n      const [minX, minY, w, h] = source.box;\n      const p = place(w, h, 0.9);\n      s.setTransform(kx * p.scale, 0, 0, ky * p.scale, kx * (p.x - minX * p.scale), ky * (p.y - minY * p.scale));\n      s.fillStyle = \"#fff\";\n      s.fill(new Path2D(source.d));\n    } else if (image) {\n      const w = image.naturalWidth;\n      const h = image.naturalHeight;\n      const p = place(w, h, 1);\n      s.setTransform(kx * p.scale, 0, 0, ky * p.scale, kx * p.x, ky * p.y);\n      s.drawImage(image, 0, 0, w, h);\n    }\n\n    let data: Uint8ClampedArray;\n    try {\n      data = s.getImageData(0, 0, sample.width, sample.height).data;\n    } catch {\n      // A cross-origin image without CORS headers taints the canvas: print nothing rather than throw.\n      if (!warned) console.warn(\"GlyphField: the image can't be read. Serve it with CORS headers (Access-Control-Allow-Origin).\");\n      warned = true;\n      finish(false);\n      return;\n    }\n\n    const lum = new Float32Array(count);\n    const cover = new Float32Array(count);\n    const stride = cols * k;\n    for (let r = 0; r < rows; r++) {\n      for (let c = 0; c < cols; c++) {\n        let l = 0;\n        let a = 0;\n        for (let sy = 0; sy < k; sy++) {\n          for (let sx = 0; sx < k; sx++) {\n            const p = ((r * k + sy) * stride + c * k + sx) * 4;\n            const alpha = data[p + 3] / 255;\n            a += alpha;\n            l += ((0.2126 * data[p] + 0.7152 * data[p + 1] + 0.0722 * data[p + 2]) / 255) * alpha;\n          }\n        }\n        const i = r * cols + c;\n        cover[i] = a / (k * k);\n        lum[i] = a > 0 ? l / a : 0;\n      }\n    }\n\n    if (source.kind !== \"image\") {\n      weight.set(cover);\n      finish(true);\n      return;\n    }\n\n    // A photo: which tones print heavy. `auto` reads the backdrop from the photo's edges (their median,\n    // so a shoulder touching the bottom doesn't skew it) and prints whatever differs from it: dark tones\n    // on a light backdrop, light tones on a dark one. The backdrop stays paper in either color scheme.\n    const rim: number[] = [];\n    let edges = 0;\n    for (let i = 0; i < count; i++) {\n      const c = i % cols;\n      const r = (i / cols) | 0;\n      if (r === 0 || c === 0 || r === rows - 1 || c === cols - 1) {\n        edges++;\n        if (cover[i] >= 0.5) rim.push(lum[i]);\n      }\n    }\n    const transparent = rim.length < edges / 2; // a cut-out: print its shape\n    rim.sort((x, y) => x - y);\n    const edge = rim.length ? rim[rim.length >> 1] : 1;\n    const tone = options.tone !== \"auto\" ? options.tone : edge > 0.6 ? \"dark\" : edge < 0.4 ? \"light\" : \"away\";\n    const raw = new Float32Array(count);\n    for (let i = 0; i < count; i++) {\n      const l = lum[i];\n      const toned = transparent ? 1 : tone === \"dark\" ? 1 - l : tone === \"light\" ? l : Math.abs(l - edge);\n      raw[i] = toned * cover[i];\n    }\n    // The backdrop's own tone maps to bare paper, so a near-white wall doesn't print as a field of dots.\n    const backdrop = transparent ? 0 : tone === \"dark\" ? 1 - edge : tone === \"light\" ? edge : 0;\n    const lo = Math.max(percentile(raw, 0.02), backdrop + 0.04);\n    const hi = percentile(raw, 0.985);\n    for (let i = 0; i < count; i++) weight[i] = hi > lo ? Math.pow(clamp01((raw[i] - lo) / (hi - lo)), 0.85) : 0;\n    // Sharpen: at a few glyphs per feature, eyes and edges need the extra contrast to read.\n    const soft = Float32Array.from(weight);\n    blur(soft, cols, rows, 2, 1);\n    for (let i = 0; i < count; i++) weight[i] = clamp01(weight[i] + (weight[i] - soft[i]) * 0.9);\n    finish(false);\n  }\n\n  /** Softens a hard-edged shape so it shades from dense to dots, then lists the marked cells. */\n  function finish(soften: boolean) {\n    if (soften && options.softness > 0) {\n      const rx = Math.round(options.softness * 4);\n      const ry = Math.round((options.softness * 4 * cw) / ch);\n      blur(weight, cols, rows, rx, ry);\n      blur(weight, cols, rows, rx, ry);\n      // Light from the upper left: the side of each stroke facing it runs heavier, the far side lighter.\n      const lit = Float32Array.from(weight);\n      for (let r = 0; r < rows; r++) {\n        for (let c = 0; c < cols; c++) {\n          const i = r * cols + c;\n          const w = lit[i];\n          if (w <= 0) continue;\n          const gx = (c > 0 ? lit[i - 1] : w) - (c < cols - 1 ? lit[i + 1] : w);\n          const gy = (r > 0 ? lit[i - cols] : w) - (r < rows - 1 ? lit[i + cols] : w);\n          weight[i] = clamp01(w * 1.15 + (gx * 0.6 + gy * 0.9) * 0.9 - (1 - w) * 0.08);\n        }\n      }\n    }\n    let n = 0;\n    for (let i = 0; i < count; i++) {\n      if (weight[i] < GLYPH.floor) weight[i] = 0;\n      else n++;\n    }\n    marked = new Int32Array(n);\n    for (let i = 0, j = 0; i < count; i++) if (weight[i] > 0) marked[j++] = i;\n    for (const s of slips) slip[s.i] = 0;\n    slips.length = 0;\n    ready = true;\n  }\n\n  /** Clears the canvas and lets the next frame draw every cell. */\n  function repaint() {\n    if (!ctx) return;\n    ctx.clearRect(0, 0, width, height);\n    drawn.fill(-1);\n    wake();\n  }\n\n  function startPrint() {\n    if (!ready || printed || !visible) return;\n    printed = true;\n    if (!options.decode || options.reduced) {\n      printing = false;\n      wake();\n      return;\n    }\n    const { delay, band } = TIMING.print;\n    const { scatter, slant } = GLYPH.print;\n    const { sweep } = options;\n    let end = 0;\n    for (let r = 0; r < rows; r++) {\n      for (let c = 0; c < cols; c++) {\n        const i = r * cols + c;\n        const order = (c / Math.max(1, cols - 1)) * (1 - slant) + (r / Math.max(1, rows - 1)) * slant;\n        settle[i] = delay + band + (order * (1 - scatter) + grain[i] * scatter) * sweep;\n        end = Math.max(end, settle[i]);\n      }\n    }\n    printing = true;\n    printStart = now();\n    printEnd = printStart + end;\n    wake();\n  }\n\n  function stamp(x: number, y: number) {\n    const R = options.radius;\n    const cwc = cw / dpr;\n    const chc = ch / dpr;\n    const oxc = ox / dpr;\n    const oyc = oy / dpr;\n    const c0 = Math.max(0, Math.floor((x - R - oxc) / cwc));\n    const c1 = Math.min(cols - 1, Math.floor((x + R - oxc) / cwc));\n    const r0 = Math.max(0, Math.floor((y - R - oyc) / chc));\n    const r1 = Math.min(rows - 1, Math.floor((y + R - oyc) / chc));\n    const R2 = R * R;\n    for (let r = r0; r <= r1; r++) {\n      const dy = oyc + (r + 0.5) * chc - y;\n      for (let c = c0; c <= c1; c++) {\n        const dx = oxc + (c + 0.5) * cwc - x;\n        const d2 = dx * dx + dy * dy;\n        if (d2 >= R2) continue;\n        const i = r * cols + c;\n        const q = 1 - d2 / R2;\n        const f = q * q * (1 - GLYPH.ink.grain + GLYPH.ink.grain * grain[i]);\n        if (f > ink[i]) ink[i] = f;\n      }\n    }\n  }\n\n  function frame() {\n    raf = 0;\n    if (!ctx || !atlas || !count) return;\n    const t = now();\n    const dt = Math.min(last ? t - last : 1 / 60, 1 / 20);\n    last = t;\n    let busy = false;\n    const { reduced, radius } = options;\n\n    // The brush: a spring toward the pointer, stamping along the way so a fast stroke stays unbroken.\n    if (brush.inside && radius > 0) {\n      if (reduced) {\n        brush.x = brush.tx;\n        brush.y = brush.ty;\n      } else {\n        const { stiffness, damping } = TIMING.brush;\n        brush.vx += (stiffness * (brush.tx - brush.x) - damping * brush.vx) * dt;\n        brush.vy += (stiffness * (brush.ty - brush.y) - damping * brush.vy) * dt;\n        brush.x += brush.vx * dt;\n        brush.y += brush.vy * dt;\n        if (Math.hypot(brush.tx - brush.x, brush.ty - brush.y) < 0.3 && Math.hypot(brush.vx, brush.vy) < 6) {\n          brush.x = brush.tx;\n          brush.y = brush.ty;\n          brush.vx = brush.vy = 0;\n        } else busy = true;\n      }\n    }\n\n    prevInk.set(ink);\n    const dry = Math.exp(-dt / (reduced ? TIMING.dryReduced : options.dry));\n    for (let i = 0; i < count; i++) {\n      if (ink[i] > 0) ink[i] = ink[i] * dry < 0.02 ? 0 : ink[i] * dry;\n    }\n    if (brush.inside && radius > 0) {\n      const steps = Math.max(1, Math.ceil(Math.hypot(brush.x - brush.lx, brush.y - brush.ly) / (radius * 0.3)));\n      for (let s = 1; s <= steps; s++) {\n        stamp(brush.lx + ((brush.x - brush.lx) * s) / steps, brush.ly + ((brush.y - brush.ly) * s) / steps);\n      }\n      brush.lx = brush.x;\n      brush.ly = brush.y;\n    }\n\n    const n = glyphCount();\n    const top = n - 1;\n    const shades = GLYPH.shades;\n    const elapsed = t - printStart;\n    const tick = Math.floor(elapsed * TIMING.print.fps);\n    const { band } = TIMING.print;\n    const { paper, shape } = GLYPH.ink;\n    if (printing && t >= printEnd) printing = false;\n    if (printing) busy = true;\n\n    for (let i = 0; i < count; i++) {\n      const w = ink[i];\n      if (w !== prevInk[i]) busy = true;\n      let base = ready && printed ? weight[i] : 0;\n      let flicker = false;\n      if (printing && base > 0) {\n        const s = settle[i];\n        if (elapsed < s - band) base = 0;\n        else if (elapsed < s) flicker = true;\n      }\n\n      let g: number;\n      if (flicker) {\n        g = 1 + Math.floor(hash(i, tick) * Math.min(top, Math.round(base * top) + 3));\n        if (g > top) g = top;\n      } else {\n        g = Math.round(Math.min(1, base + w * (paper + shape * base)) * top);\n        if (slip[i] && base > 0) g = Math.min(top, Math.max(1, g + slip[i]));\n      }\n      const key = g <= 0 ? -1 : g * shades + (w > 0 ? Math.min(shades - 1, Math.round(w * (shades - 1))) : 0);\n      if (key === drawn[i]) continue;\n      const x = ox + (i % cols) * cw;\n      const y = oy + ((i / cols) | 0) * ch;\n      ctx.clearRect(x, y, cw, ch);\n      if (key >= 0) {\n        const slot = key % shades;\n        ctx.drawImage(atlas, ((key - slot) / shades) * cw, slot * ch, cw, ch, x, y, cw, ch);\n      }\n      drawn[i] = key;\n    }\n\n    if (busy && visible && !document.hidden) raf = requestAnimationFrame(frame);\n    else last = 0;\n  }\n\n  function wake() {\n    if (raf || !visible || !ctx || document.hidden) return;\n    raf = requestAnimationFrame(frame);\n  }\n\n  /** Drift runs on a slow timer, not every frame: a handful of cells slip a step and back. */\n  function syncDrift() {\n    const want = visible && !document.hidden && options.drift && !options.reduced && marked.length > 0;\n    if (want && !driftTimer) {\n      driftTimer = window.setInterval(() => {\n        if (printing || !printed) return;\n        const t = now();\n        for (let j = slips.length - 1; j >= 0; j--) {\n          if (slips[j].until < t) {\n            slip[slips[j].i] = 0;\n            slips.splice(j, 1);\n          }\n        }\n        const [a, b] = TIMING.drift.hold;\n        const picks = Math.max(1, Math.round(marked.length * GLYPH.drift.share));\n        for (let p = 0; p < picks; p++) {\n          const i = marked[(Math.random() * marked.length) | 0];\n          if (slip[i]) continue;\n          slip[i] = Math.random() < 0.5 ? -1 : 1;\n          slips.push({ i, until: t + a + Math.random() * (b - a) });\n        }\n        wake();\n      }, TIMING.drift.every);\n    } else if (!want && driftTimer) {\n      clearInterval(driftTimer);\n      driftTimer = 0;\n      for (const s of slips) slip[s.i] = 0;\n      slips.length = 0;\n      wake();\n    }\n  }\n\n  function loadImage(src: string) {\n    image = null;\n    const img = new Image();\n    img.crossOrigin = \"anonymous\";\n    img.decoding = \"async\";\n    img.onload = () => {\n      if (source.kind !== \"image\" || source.src !== src) return;\n      image = img;\n      read();\n      repaint();\n      startPrint();\n      syncDrift();\n    };\n    img.src = src;\n  }\n\n  return {\n    connect(el: { root: HTMLElement; canvas: HTMLCanvasElement; glyph: HTMLElement; accent: HTMLElement }) {\n      root = el.root;\n      canvas = el.canvas;\n      ctx = canvas.getContext(\"2d\");\n      probes = { glyph: el.glyph, accent: el.accent };\n      readColors();\n      layout();\n\n      const resize = new ResizeObserver(() => {\n        if (!canvas) return;\n        const w = Math.round(canvas.clientWidth * Math.min(window.devicePixelRatio || 1, GLYPH.maxDpr));\n        const h = Math.round(canvas.clientHeight * Math.min(window.devicePixelRatio || 1, GLYPH.maxDpr));\n        if (w === width && h === height) return;\n        layout();\n        syncDrift();\n      });\n      resize.observe(canvas);\n      const io = new IntersectionObserver(([entry]) => {\n        visible = entry.isIntersecting;\n        if (visible) {\n          startPrint();\n          wake();\n        }\n        syncDrift();\n      });\n      io.observe(canvas);\n\n      // The glyph width comes from the font: measure again once web fonts have loaded.\n      document.fonts?.ready.then(() => {\n        if (canvas) layout();\n      });\n\n      const scheme = window.matchMedia(\"(prefers-color-scheme: dark)\");\n      const recolor = () => {\n        readColors();\n        buildAtlas();\n        repaint();\n      };\n      scheme.addEventListener(\"change\", recolor);\n      const themeAttrs = new MutationObserver(recolor);\n      themeAttrs.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"data-theme\"] });\n\n      const pageVisibility = () => {\n        if (!document.hidden) wake();\n        syncDrift();\n      };\n      document.addEventListener(\"visibilitychange\", pageVisibility);\n\n      const point = (e: PointerEvent) => {\n        if (!canvas) return;\n        const r = canvas.getBoundingClientRect();\n        brush.tx = e.clientX - r.left;\n        brush.ty = e.clientY - r.top;\n        if (!brush.inside) {\n          // Land where the pointer is, not glide in from the last place it left.\n          brush.x = brush.lx = brush.tx;\n          brush.y = brush.ly = brush.ty;\n          brush.vx = brush.vy = 0;\n          brush.inside = true;\n        }\n        wake();\n      };\n      const move = (e: PointerEvent) => {\n        if (e.pointerType === \"touch\" && !brush.down) return;\n        point(e);\n      };\n      const down = (e: PointerEvent) => {\n        if (e.pointerType === \"touch\") brush.down = true;\n        point(e);\n      };\n      const up = (e: PointerEvent) => {\n        if (e.pointerType !== \"touch\") return;\n        brush.down = false;\n        brush.inside = false;\n      };\n      const leave = () => {\n        brush.down = false;\n        brush.inside = false;\n      };\n      root.addEventListener(\"pointermove\", move);\n      root.addEventListener(\"pointerdown\", down);\n      root.addEventListener(\"pointerup\", up);\n      root.addEventListener(\"pointerleave\", leave);\n      root.addEventListener(\"pointercancel\", leave);\n\n      cleanups.push(\n        () => resize.disconnect(),\n        () => io.disconnect(),\n        () => scheme.removeEventListener(\"change\", recolor),\n        () => themeAttrs.disconnect(),\n        () => document.removeEventListener(\"visibilitychange\", pageVisibility),\n        () => {\n          root?.removeEventListener(\"pointermove\", move);\n          root?.removeEventListener(\"pointerdown\", down);\n          root?.removeEventListener(\"pointerup\", up);\n          root?.removeEventListener(\"pointerleave\", leave);\n          root?.removeEventListener(\"pointercancel\", leave);\n        },\n      );\n      return () => {\n        cancelAnimationFrame(raf);\n        raf = 0;\n        clearInterval(driftTimer);\n        driftTimer = 0;\n        visible = false;\n        cleanups.splice(0).forEach((fn) => fn());\n        root = canvas = null;\n        ctx = null;\n        probes = null;\n      };\n    },\n\n    setOptions(next: Options) {\n      const prev = options;\n      options = next;\n      if (!ctx) return;\n      if (next.reduced && printing) printing = false;\n      if (next.cellSize !== prev.cellSize || next.glyphs !== prev.glyphs) layout();\n      else if (next.fit !== prev.fit || next.tone !== prev.tone || next.softness !== prev.softness) {\n        read();\n        repaint();\n      }\n      syncDrift();\n      wake();\n    },\n\n    setSource(next: Source) {\n      if (sourceKey(next) === sourceKey(source)) return;\n      source = next;\n      // A new mark prints again; one that hasn't printed yet just waits for its turn.\n      printed = false;\n      printing = false;\n      if (next.kind === \"image\") loadImage(next.src);\n      else image = null;\n      if (!ctx) return;\n      read();\n      repaint();\n      startPrint();\n      syncDrift();\n    },\n  };\n}\n\ntype Field = ReturnType<typeof createField>;\n\nfunction parseViewBox(viewBox: string): [number, number, number, number] {\n  const n = viewBox.split(/[\\s,]+/).map(Number);\n  return n.length === 4 && n.every(Number.isFinite) && n[2] > 0 && n[3] > 0 ? [n[0], n[1], n[2], n[3]] : [0, 0, 24, 24];\n}\n\nexport interface GlyphFieldProps extends React.HTMLAttributes<HTMLDivElement> {\n  /** A word or short line to print. Use `\\n` for a second line. */\n  text?: string;\n  /** Font family `text` is set in, at weight 800, before it's turned into glyphs. */\n  textFont?: string;\n  /** An SVG path (`d`) to print, such as your logo mark. Read against `viewBox`. */\n  path?: string;\n  /** The coordinate box `path` is drawn in, like an SVG's `viewBox`. */\n  viewBox?: string;\n  /** An image to print, mapped by tone. It must be served with CORS headers (Unsplash is). */\n  src?: string;\n  /** For `src`: which tones print heavy. `auto` reads the backdrop from the photo's edges and prints what differs from it (dark tones on a light backdrop, light on a dark one), so the subject comes up as ink and the backdrop stays paper. */\n  tone?: Tone;\n  /** `contain` fits the whole mark inside the field; `cover` fills the field and crops. */\n  fit?: Fit;\n  /** Font size of the glyphs, in px. Each cell is one glyph wide and 1.2× this tall. */\n  cellSize?: number;\n  /** The glyphs from lightest to densest. Start with a space so the paper stays bare. */\n  glyphs?: string;\n  /** For `text` and `path`: how far the edges shade off into dots, from 0 (hard) to 1 (soft). */\n  softness?: number;\n  /** The pointer inks the glyphs it passes over, which then dry back. A number sets the brush radius in px. */\n  ink?: boolean | number;\n  /** Print the mark left to right, with a band of flickering glyphs, the first time it scrolls into view. */\n  decode?: boolean;\n  /** Let a few glyphs slip a step and back at idle, so the mark looks alive. */\n  drift?: boolean;\n  /** Seconds the print head takes to cross the mark when it prints. */\n  printDuration?: number;\n  /** How quickly the ink dries back, in seconds: a time constant, so it's gone after about three times this. */\n  dry?: number;\n  /** Describes the mark for screen readers. Without it, the field is decorative. */\n  label?: string;\n  /** A `text-*` color for the glyphs. The canvas reads it, so `dark:` variants work. */\n  glyphClassName?: string;\n  /** A `text-*` color the ink takes. */\n  accentClassName?: string;\n  /** Classes for the canvas. It fills the field by default; position it to print the mark in one part only. Its font (`font-mono` by default) is the glyphs' font. */\n  canvasClassName?: string;\n}\n\nexport function GlyphField({\n  text,\n  textFont = \"ui-sans-serif, system-ui, sans-serif\",\n  path,\n  viewBox = \"0 0 24 24\",\n  src,\n  tone = \"auto\",\n  fit = \"contain\",\n  cellSize = 12,\n  glyphs = DEFAULT_GLYPHS,\n  softness = 0.4,\n  ink = true,\n  decode = true,\n  drift = true,\n  printDuration = TIMING.print.duration,\n  dry = TIMING.dry,\n  label,\n  glyphClassName,\n  accentClassName,\n  canvasClassName,\n  className,\n  children,\n  ...props\n}: GlyphFieldProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const glyphRef = React.useRef<HTMLSpanElement>(null);\n  const accentRef = React.useRef<HTMLSpanElement>(null);\n  const [field] = React.useState<Field>(createField);\n  const reduced = useReducedMotion() ?? false;\n\n  React.useLayoutEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    const glyph = glyphRef.current;\n    const accent = accentRef.current;\n    if (!root || !canvas || !glyph || !accent) return;\n    return field.connect({ root, canvas, glyph, accent });\n  }, [field]);\n\n  const radius = ink === true ? GLYPH.ink.radius : ink === false ? 0 : Math.max(0, ink);\n  const ramp = glyphs.length >= 2 ? glyphs : DEFAULT_GLYPHS;\n  React.useEffect(() => {\n    field.setOptions({\n      cellSize: Math.max(4, cellSize),\n      glyphs: ramp,\n      tone,\n      fit,\n      softness: clamp01(softness),\n      radius,\n      decode,\n      drift,\n      sweep: Math.max(0, printDuration),\n      dry: Math.max(0.01, dry),\n      reduced,\n    });\n  }, [field, cellSize, ramp, tone, fit, softness, radius, decode, drift, printDuration, dry, reduced]);\n\n  React.useEffect(() => {\n    if (text) field.setSource({ kind: \"text\", text, font: textFont });\n    else if (path) field.setSource({ kind: \"path\", d: path, box: parseViewBox(viewBox) });\n    else if (src) field.setSource({ kind: \"image\", src });\n    else field.setSource({ kind: \"orbit\" });\n  }, [field, text, textFont, path, viewBox, src]);\n\n  return (\n    <div ref={rootRef} className={cn(\"relative isolate\", className)} {...props}>\n      <canvas\n        ref={canvasRef}\n        role={label ? \"img\" : undefined}\n        aria-label={label}\n        aria-hidden={label ? undefined : true}\n        className={cn(\"pointer-events-none absolute inset-0 -z-10 size-full font-mono\", canvasClassName)}\n      />\n      {/* Probes the canvas reads its colors from. Defaults apply only when no class is given, so a `dark:` default can't win over yours. */}\n      <span ref={glyphRef} aria-hidden className={cn(\"hidden\", glyphClassName ?? \"text-zinc-500 dark:text-zinc-400\")} />\n      <span ref={accentRef} aria-hidden className={cn(\"hidden\", accentClassName ?? \"text-violet-600 dark:text-violet-400\")} />\n      {children}\n    </div>\n  );\n}\n"
    }
  ]
}