{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "kymograph-smoke-trace",
  "title": "Kymograph Smoke Trace",
  "description": "A full-bleed hero built on a subtractive recording mechanic: a soot-coated drum turns beneath a fixed stylus that scratches a bright, permanent trace through the dark coating, while a resmoking brush at the trailing edge repaints the outgoing soot fresh so the drum recirculates forever.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/loud/kymograph-smoke-trace/component.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\n// ---------------------------------------------------------------------------\n// KymographSmokeTrace — a full-bleed hero built on a subtractive recording\n// mechanic: a soot-coated drum turns beneath a fixed stylus that scratches a\n// bright, permanent trace through the dark coating. The drum's circumference\n// is wider than the visible window, so a hidden arc carries the trace off\n// past the LEFT edge before it can reappear at the WRITE point on the right\n// — a resmoking brush lives at the left edge and repaints that outgoing soot\n// back to full density just before it exits view, which is what lets the\n// drum recirculate forever without ever hard-resetting the canvas.\n//\n// Everything is drawn into one persistent offscreen buffer (the \"drum\"); the\n// visible canvas each frame is just a window blitted out of that buffer, so\n// the scratch trace is genuinely permanent ink, not a redrawn sample array.\n// ---------------------------------------------------------------------------\n\ntype Vec3 = [number, number, number];\n\nfunction parseColor(raw: string): Vec3 | null {\n  const s = raw.trim();\n  if (s.startsWith(\"#\")) {\n    const hex = s.slice(1);\n    if (hex.length === 3) {\n      const r = parseInt(hex[0]! + hex[0], 16);\n      const g = parseInt(hex[1]! + hex[1], 16);\n      const b = parseInt(hex[2]! + hex[2], 16);\n      return Number.isNaN(r + g + b) ? null : [r, g, b];\n    }\n    if (hex.length >= 6) {\n      const r = parseInt(hex.slice(0, 2), 16);\n      const g = parseInt(hex.slice(2, 4), 16);\n      const b = parseInt(hex.slice(4, 6), 16);\n      return Number.isNaN(r + g + b) ? null : [r, g, b];\n    }\n    return null;\n  }\n  const m = s.match(/rgba?\\(\\s*([\\d.]+)[,\\s]+([\\d.]+)[,\\s]+([\\d.]+)/);\n  return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;\n}\n\n// -- real numbers (documented in the spec, not exposed as props: this\n// specific mechanical character IS the component) --------------------------\nconst SPEED_PX_S = 40; // drum surface speed\nconst REVOLUTION_FACTOR = 1.8; // drum circumference = container width * this\nconst WRITE_INSET = 26; // px from the right edge — the fixed stylus point\nconst BRUSH_INSET = 26; // px from the left edge — the fixed resmoke point\nconst TWITCH_INTERVAL_S = 3.2; // mean seconds between twitch events\nconst TWITCH_JITTER_S = 0.5; // +/- randomization on that interval\nconst TWITCH_RISE_S = 0.12;\nconst TWITCH_DECAY_S = 0.6;\nconst TWITCH_MIN_AMP = 18;\nconst TWITCH_MAX_AMP = 30;\nconst BASELINE_JITTER_AMP = 1.5;\nconst SCRATCH_WIDTH = 2;\nconst STATIC_TIME_S = 9.8; // reduced-motion freeze frame, deliberately non-t0\nconst DPR_CAP = 1.5;\n\n// small deterministic PRNG so the reduced-motion freeze frame is built the\n// same way the live loop would build it, just run once and stopped.\nfunction mulberry32(seed: number) {\n  let a = seed;\n  return () => {\n    a |= 0;\n    a = (a + 0x6d2b79f5) | 0;\n    let t = Math.imul(a ^ (a >>> 15), 1 | a);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\nexport interface KymographSmokeTraceProps {\n  /** content rendered on top of the drum, e.g. a headline + CTA */\n  children?: React.ReactNode;\n  className?: string;\n}\n\nexport function KymographSmokeTrace({\n  children,\n  className = \"\",\n}: KymographSmokeTraceProps) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    if (!root || !canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n\n    // -- token-derived ink, read at mount and re-derived on theme flip ------\n    let bg: Vec3 = [10, 10, 10];\n    let fg: Vec3 = [237, 237, 237];\n    let mu: Vec3 = [110, 110, 110];\n    const derive = () => {\n      const cs = getComputedStyle(document.documentElement);\n      bg = parseColor(cs.getPropertyValue(\"--background\")) ?? bg;\n      fg = parseColor(cs.getPropertyValue(\"--foreground\")) ?? fg;\n      mu = parseColor(cs.getPropertyValue(\"--ns-muted\")) ?? mu;\n    };\n    derive();\n\n    // -- hot-path state: locals only, never React state ---------------------\n    let w = 0;\n    let h = 0;\n    let dpr = 1;\n    let bufW = 0; // drum circumference, device px\n    let buf: HTMLCanvasElement | null = null;\n    let bctx: CanvasRenderingContext2D | null = null;\n    let raf = 0;\n    let last = 0;\n    let paused = false;\n    let reduced = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n\n    let scrollOffset = 0; // world px, wraps at bufW (CSS px, not device)\n    let prevWriteWorldX = 0;\n    let prevStylusY = 0;\n    let stylusY = 0; // css px, relative to h\n    let nextTwitchAt = 0;\n    let twitchStart = -Infinity;\n    let twitchAmp = 0;\n    let simTime = 0;\n    let rand = Math.random;\n\n    // -- soot texture: a muted fill biased toward the background so the\n    // scratch trace (drawn at full foreground contrast) always reads as the\n    // far end of the ramp from it in both themes -----------------------------\n    const sootRGBA = (alpha: number) =>\n      `rgba(${Math.round((mu[0] + bg[0]) / 2)},${Math.round(\n        (mu[1] + bg[1]) / 2\n      )},${Math.round((mu[2] + bg[2]) / 2)},${alpha})`;\n\n    const paintSoot = (x0: number, width: number) => {\n      if (!bctx || !buf || width <= 0) return;\n      // a few overlapping rects at slightly varying alpha reads as a\n      // textured coating rather than a flat fill\n      bctx.fillStyle = sootRGBA(1);\n      bctx.fillRect(x0, 0, width, buf.height);\n      const grain = Math.max(2, Math.round(width / 6));\n      for (let i = 0; i < grain; i++) {\n        const gx = x0 + rand() * width;\n        const gy = rand() * buf.height;\n        const gw = 1 + rand() * 3;\n        const gh = 1 + rand() * 3;\n        bctx.fillStyle = sootRGBA(0.35 + rand() * 0.25);\n        bctx.fillRect(gx, gy, gw, gh);\n      }\n    };\n\n    const twitchOffset = (t: number) => {\n      const dt = t - twitchStart;\n      if (dt < 0) return 0;\n      const rise = Math.min(1, dt / TWITCH_RISE_S);\n      const decay = Math.exp(-dt / TWITCH_DECAY_S);\n      const ring = Math.sin((dt / TWITCH_DECAY_S) * Math.PI * 2.4);\n      return twitchAmp * rise * decay * ring;\n    };\n\n    const scheduleTwitch = (t: number) => {\n      nextTwitchAt =\n        t + TWITCH_INTERVAL_S + (rand() * 2 - 1) * TWITCH_JITTER_S;\n      twitchAmp = TWITCH_MIN_AMP + rand() * (TWITCH_MAX_AMP - TWITCH_MIN_AMP);\n    };\n\n    const stylusYAt = (t: number) => {\n      const jitter = Math.sin(t * 5.3) * BASELINE_JITTER_AMP * 0.6 +\n        Math.sin(t * 11.7 + 1.4) * BASELINE_JITTER_AMP * 0.4;\n      return h / 2 + jitter + twitchOffset(t);\n    };\n\n    // one simulation step: advances scrollOffset, scratches the buffer at\n    // the write point, and resmokes the buffer at the brush point.\n    const step = (dt: number) => {\n      simTime += dt;\n      if (simTime >= nextTwitchAt) {\n        twitchStart = simTime;\n        scheduleTwitch(simTime);\n      }\n      const prevOffset = scrollOffset;\n      scrollOffset = (scrollOffset + SPEED_PX_S * dt) % (bufW / dpr);\n      stylusY = stylusYAt(simTime);\n\n      if (!bctx || !buf) return;\n      const bufWCss = bufW / dpr;\n      const writeWorldX = (scrollOffset + WRITE_INSET) % bufWCss;\n      const wrapped = writeWorldX < prevWriteWorldX - 1; // crossed the seam\n      bctx.strokeStyle = `rgb(${fg[0]},${fg[1]},${fg[2]})`;\n      bctx.lineWidth = SCRATCH_WIDTH;\n      bctx.lineCap = \"round\";\n      if (!wrapped) {\n        bctx.beginPath();\n        bctx.moveTo(prevWriteWorldX * dpr, prevStylusY * dpr);\n        bctx.lineTo(writeWorldX * dpr, stylusY * dpr);\n        bctx.stroke();\n      }\n      prevWriteWorldX = writeWorldX;\n      prevStylusY = stylusY;\n\n      // resmoke: a fixed screen point (BRUSH_INSET from the left) that\n      // continuously repaints whatever world column is currently passing\n      // beneath it back to fresh soot, right before that column scrolls\n      // off the visible window for good.\n      const advance = Math.max(1, Math.ceil((scrollOffset - prevOffset + bufWCss) % bufWCss * dpr));\n      const brushWorldX = ((scrollOffset + BRUSH_INSET) % bufWCss) * dpr;\n      paintSoot(brushWorldX - advance, advance + 1);\n    };\n\n    const blit = () => {\n      if (!buf) return;\n      const bufWCss = bufW / dpr;\n      const srcX = (scrollOffset % bufWCss) * dpr;\n      const destWpx = Math.round(w * dpr);\n      const hpx = Math.round(h * dpr);\n      ctx.setTransform(1, 0, 0, 1, 0, 0);\n      ctx.clearRect(0, 0, destWpx, hpx);\n      const firstChunk = Math.min(destWpx, buf.width - srcX);\n      ctx.drawImage(buf, srcX, 0, firstChunk, hpx, 0, 0, firstChunk, hpx);\n      if (firstChunk < destWpx) {\n        const remaining = destWpx - firstChunk;\n        ctx.drawImage(buf, 0, 0, remaining, hpx, firstChunk, 0, remaining, hpx);\n      }\n    };\n\n    const initBuffer = () => {\n      const bufWCss = Math.max(w, 480) * REVOLUTION_FACTOR;\n      bufW = Math.max(1, Math.round(bufWCss * dpr));\n      const bh = Math.max(1, Math.round(h * dpr));\n      buf = document.createElement(\"canvas\");\n      buf.width = bufW;\n      buf.height = bh;\n      bctx = buf.getContext(\"2d\");\n      scrollOffset = 0;\n      prevWriteWorldX = WRITE_INSET;\n      prevStylusY = h / 2;\n      simTime = 0;\n      nextTwitchAt = TWITCH_INTERVAL_S * 0.4;\n      twitchStart = -Infinity;\n      if (bctx) paintSoot(0, bufW);\n    };\n\n    const renderStatic = () => {\n      // deterministic replay up to STATIC_TIME_S, then stop — the frame\n      // never changes again, satisfying the reduced-motion byte-stability\n      // check.\n      rand = mulberry32(20260827);\n      initBuffer();\n      const stepDt = 1 / 60;\n      let t = 0;\n      while (t < STATIC_TIME_S) {\n        const d = Math.min(stepDt, STATIC_TIME_S - t);\n        step(d);\n        t += d;\n      }\n      blit();\n    };\n\n    const draw = (now: number) => {\n      const dt = Math.min(0.05, last === 0 ? 1 / 60 : (now - last) / 1000);\n      last = now;\n      step(dt);\n      blit();\n    };\n\n    const rafLoop = (now: number) => {\n      draw(now);\n      if (!paused) raf = requestAnimationFrame(rafLoop);\n    };\n\n    const stopLoop = () => {\n      if (raf) cancelAnimationFrame(raf);\n      raf = 0;\n      last = 0;\n    };\n\n    const startLoop = () => {\n      stopLoop();\n      if (paused) return;\n      if (reduced) {\n        renderStatic();\n        return;\n      }\n      rand = Math.random;\n      raf = requestAnimationFrame(rafLoop);\n    };\n\n    const resize = () => {\n      const rect = root.getBoundingClientRect();\n      w = rect.width;\n      h = rect.height;\n      dpr = Math.min(DPR_CAP, window.devicePixelRatio || 1);\n      canvas.width = Math.max(1, Math.round(w * dpr));\n      canvas.height = Math.max(1, Math.round(h * dpr));\n      initBuffer();\n      startLoop();\n    };\n\n    resize();\n\n    const ro = new ResizeObserver(resize);\n    ro.observe(root);\n\n    const onThemeChange = () => {\n      derive();\n      // soot already painted with the old tokens keeps its shape; only the\n      // colour of future paints changes, matching how a MutationObserver\n      // re-derive is expected to behave without a hard reset.\n    };\n    const mo = new MutationObserver(onThemeChange);\n    mo.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: [\"class\", \"data-theme\"],\n    });\n    const colorScheme = window.matchMedia(\"(prefers-color-scheme: dark)\");\n    colorScheme.addEventListener(\"change\", onThemeChange);\n\n    const reducedMq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    const onReducedChange = () => {\n      reduced = reducedMq.matches;\n      startLoop();\n    };\n    reducedMq.addEventListener(\"change\", onReducedChange);\n\n    const onVisibility = () => {\n      paused = document.hidden;\n      if (paused) stopLoop();\n      else startLoop();\n    };\n    document.addEventListener(\"visibilitychange\", onVisibility);\n\n    let io: IntersectionObserver | undefined;\n    if (\"IntersectionObserver\" in window) {\n      io = new IntersectionObserver((entries) => {\n        const entry = entries[0];\n        if (!entry) return;\n        paused = !entry.isIntersecting || document.hidden;\n        if (paused) stopLoop();\n        else startLoop();\n      });\n      io.observe(root);\n    }\n\n    return () => {\n      stopLoop();\n      ro.disconnect();\n      mo.disconnect();\n      colorScheme.removeEventListener(\"change\", onThemeChange);\n      reducedMq.removeEventListener(\"change\", onReducedChange);\n      document.removeEventListener(\"visibilitychange\", onVisibility);\n      io?.disconnect();\n    };\n  }, []);\n\n  return (\n    <div\n      ref={rootRef}\n      className={`relative h-full w-full overflow-hidden bg-background ${className}`}\n    >\n      <canvas\n        ref={canvasRef}\n        aria-hidden\n        className=\"pointer-events-none absolute inset-0 h-full w-full\"\n      />\n      {children}\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "components/ui/kymograph-smoke-trace.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "color-ns-muted": "var(--ns-muted)"
    },
    "light": {
      "ns-muted": "#4d4d4d"
    },
    "dark": {
      "ns-muted": "#8f8f8f"
    }
  },
  "meta": {
    "collection": "loud",
    "tags": [
      "canvas",
      "hero",
      "kymograph",
      "recording-instrument",
      "physiology",
      "drum",
      "ink",
      "mono",
      "ambient",
      "generative"
    ],
    "instruction": "`<KymographSmokeTrace children? className? />` renders a full-bleed hero canvas simulating a 19th-century kymograph: a drum wrapped in soot-blackened paper turns at a constant surface speed (40px/s, hardcoded, not a prop — this specific mechanical character is the component's identity) beneath a fixed stylus that scratches a bright permanent trace through the soot as the drum rotates. Internally the whole drum surface is drawn into ONE PERSISTENT OFFSCREEN CANVAS (`buf`) whose width is the drum's circumference — `max(containerWidth, 480) * 1.8` CSS px (device-scaled by a DPR capped at 1.5) — deliberately wider than the visible window, so a hidden arc of the drum exists off both edges of what's shown. Every rAF frame accumulates real elapsed time into `scrollOffset` (mod the circumference) and the visible `<canvas>` is just a window blitted out of `buf` at that offset (two `drawImage` calls when the window straddles the buffer's wrap seam) — nothing about the trace is redrawn from a sample array; ink drawn into `buf` stays there permanently until the resmoke brush repaints over it. The STYLUS is a fixed point on screen, `WRITE_INSET = 26px` from the right edge; each frame its world-space x-coordinate is `(scrollOffset + WRITE_INSET) mod circumference`, and a line segment is stroked into `buf` (in `--foreground`, 2px, round caps) from the previous frame's write position to the current one at a y driven by a twitch generator: low-amplitude sinusoidal baseline jitter (`±1.5px`, two summed sine terms) plus a discrete twitch event that fires on average every 3.2s (jittered ±0.5s) — a fast rise (0.12s) into an exponentially-decaying (0.6s time constant) ~2.4-cycle ring, amplitude randomized 18-30px — modeled as a muscle-twitch/pulse trace, not literal biodata. The RESMOKE BRUSH is a second fixed point, `BRUSH_INSET = 26px` from the LEFT edge; every frame it repaints the `buf` column(s) currently passing beneath that screen position back to fresh soot (a semi-transparent fill derived from `--ns-muted` mixed toward `--background`, plus a scatter of small randomized-alpha grain rects for texture) — since content only becomes visible again at the write point after crossing the hidden arc, by the time any given patch of drum re-enters view on the right it has already been resmoked clean at the left, which is what lets the loop run forever with no hard reset. All colors come from `getComputedStyle(document.documentElement)` on `--background`, `--foreground`, `--ns-muted`, re-read on a `MutationObserver` watching `documentElement`'s class/data-theme attributes and a `prefers-color-scheme` `matchMedia` listener (already-painted soot keeps its color until the next repaint touches it, by design — no hard re-tint sweep). `--ns-accent` is never used anywhere; this is a fully ambient, non-interactive hero (`pointer-events-none` on the canvas, `aria-hidden`) with `autoplay: mode: none` because it animates entirely on its own internal clock and there is nothing for a synthetic pointer driver to do. REDUCED MOTION: instead of the rAF loop, a deterministic replay runs synchronously at mount — a seeded PRNG (`mulberry32`, fixed seed) drives the exact same `step()` function through fixed 1/60s ticks from t=0 to `STATIC_TIME_S = 9.8` (chosen because it lands mid-revolution with a substantial scratch trace and at least two completed twitch spikes already inked, not the empty t=0 frame), then a single `blit()` is called and the loop never starts — the canvas is genuinely byte-stable afterward, not just slowed down. The rAF loop pauses on `document.hidden` (`visibilitychange`) and via an `IntersectionObserver` (threshold default) while scrolled offscreen, both resuming through the same `startLoop()` path used by resize and theme/reduced-motion changes; `ResizeObserver` on the root re-derives `w/h/dpr`, rebuilds `buf` at the new circumference and restarts (a visual restart on resize is an accepted tradeoff, not a correctness bug). `children` render as an ordinary absolutely-positioned DOM overlay on top of the canvas (untouched by any of this — a headline/CTA can sit on it with a token scrim, same pattern as `flyback-tear`). Zero dependencies, DOM+Canvas 2D only, no WebGL."
  },
  "type": "registry:ui"
}