{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "phosphor-score",
  "title": "Phosphor Score",
  "description": "Vertical sheet music on a CRT phosphor: notes fall, bloom at the playhead, then exit in a flare.",
  "files": [
    {
      "path": "registry/phosphor-score/phosphor-score.tsx",
      "content": "\"use client\"\n\nimport { useEffect, useRef } from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport type PhosphorScoreTheme = \"light\" | \"dark\" | \"auto\"\n\nexport type PhosphorScoreOptions = {\n  /**\n   * Ink / phosphor color, any CSS color. Omit to follow `theme`\n   * (`LIGHT_COLOR` / `DARK_COLOR`).\n   */\n  color?: string\n  /**\n   * Bloom amount, 0–100. Default `50`. Scales the playhead halo and the\n   * flare a note leaves as it plays.\n   */\n  glow?: number\n  /** Scroll speed in beats per second. Default `1.35`. */\n  speed?: number\n  /** How packed the notation is, `0.35`–`1.85`. Default `1`. */\n  density?: number\n  /** Slow camera drift. Default `true`. */\n  sway?: boolean\n  /** Deterministic score. Default `23`. */\n  seed?: number\n  /**\n   * Tilt the plane about its horizontal axis, in degrees, `-70`–`70`.\n   * Positive tips the incoming notes away. Default `0`.\n   */\n  rotateX?: number\n  /**\n   * Turn the plane about its vertical axis, in degrees, `-70`–`70`.\n   * Positive swings the right side away. Default `0`.\n   */\n  rotateY?: number\n  /** Spin the plane in place, in degrees. Positive is clockwise. Default `0`. */\n  rotateZ?: number\n  /**\n   * Palette mode. Default `auto` follows shadcn / next-themes\n   * (`html.dark` class).\n   */\n  theme?: PhosphorScoreTheme\n  /** Fires whenever resolved dark mode changes. */\n  onThemeChange?: (dark: boolean) => void\n}\n\nexport type PhosphorScoreInstance = {\n  setOptions: (options: Partial<PhosphorScoreOptions>) => void\n  destroy: () => void\n}\n\n/** Phosphor on black */\nexport const DARK_COLOR = \"#4DFF6A\"\n/** Forest ink on the page background */\nexport const LIGHT_COLOR = \"#147A3A\"\n/** @deprecated Use `DARK_COLOR` or omit `color` and set `theme`. */\nexport const DEFAULT_COLOR = DARK_COLOR\n/** Transparent in both themes; the parent's background shows through. */\nexport const DARK_BG = \"transparent\"\n/** Transparent in both themes; the parent's background shows through. */\nexport const LIGHT_BG = \"transparent\"\nexport const DEFAULT_GLOW = 50\nexport const DEFAULT_SPEED = 1.35\nexport const DEFAULT_DENSITY = 1\nexport const DEFAULT_SEED = 23\n\n/** Length of the generated score; it loops seamlessly. */\nconst LOOP_BEATS = 48\n/** Nothing is written in the last half beat, so the loop seam never collides. */\nconst LOOP_END = LOOP_BEATS - 0.5\n/** Stem length in half-spaces (3.5 staff spaces). */\nconst STEM = 7\n/** Playhead height as a share of the canvas; the rest below is afterglow. */\nconst PLAYHEAD = 0.7\n/** Share of the height faded out at the top and bottom edges. */\nconst EDGE_FADE = 0.16\n/** Seconds to crossfade when `seed` or `density` regenerates the score. */\nconst REBUILD_FADE = 0.35\n/** Seconds a flare lasts after its note plays. */\nconst FLARE_LIFE = 0.5\nconst MAX_FLARES = 48\n/** `rotateX` / `rotateY` stop short of edge-on. */\nconst MAX_TILT = 70\n/** Camera distance as a multiple of the canvas' longer side. */\nconst PERSPECTIVE = 1.2\n/** Depth scale where the plane has fully faded into the distance. */\nconst FAR_SCALE = 0.12\n/** Depth-scale range over which the plane fades in from `FAR_SCALE`. */\nconst FOG_RANGE = 0.3\nconst DYNAMICS = [\"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\"] as const\n\ntype Staff = 0 | 1\ntype Rgb = [number, number, number]\n\ntype Note = {\n  t: number\n  /** Staff position in half-spaces; the five lines sit on 0, 2, 4, 6, 8. */\n  pitch: number\n  staff: Staff\n  /** Half notes and longer draw hollow heads. */\n  hollow: boolean\n  acc: -1 | 0 | 1\n}\n\n/**\n * A stem carrier: a beamed group, a chord, or a lone note. Stems point\n * away from the middle of the system, so beams sit on the outer side and\n * dynamics have the space between the staves to themselves.\n */\ntype Stem = {\n  staff: Staff\n  notes: Note[]\n  t0: number\n  t1: number\n  /** Where the stems end (and the beam runs), in half-spaces. */\n  tip: number\n  /** 0 for chords and lone notes, 1 for eighths, 2 for sixteenths. */\n  beams: 0 | 1 | 2\n  chord: boolean\n}\n\ntype Mark = { t: number; text: string }\ntype Hairpin = { t: number; dur: number; opening: boolean }\ntype Slur = { staff: Staff; first: Note; last: Note }\n\ntype Score = {\n  notes: Note[]\n  stems: Stem[]\n  marks: Mark[]\n  hairpins: Hairpin[]\n  slurs: Slur[]\n}\n\ntype Dust = { x: number; y: number; z: number; s: number; a: number }\ntype Flare = { staff: Staff; pitch: number; age: number }\n\nfunction mulberry32(seed: number) {\n  let a = seed >>> 0\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\nfunction clamp(value: number, min: number, max: number) {\n  return Math.min(max, Math.max(min, value))\n}\n\n/** Signed beats from `now` to `t`, taking the shorter way round the loop. */\nfunction wrapDelta(t: number, now: number) {\n  const d = t - now\n  return (\n    ((((d + LOOP_BEATS / 2) % LOOP_BEATS) + LOOP_BEATS) % LOOP_BEATS) -\n    LOOP_BEATS / 2\n  )\n}\n\nfunction numberOr(value: unknown, fallback: number, min: number, max: number) {\n  if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback\n  return clamp(value, min, max)\n}\n\nconst glowOf = (value?: number) => numberOr(value, DEFAULT_GLOW, 0, 100)\nconst speedOf = (value?: number) => numberOr(value, DEFAULT_SPEED, 0.15, 4)\nconst densityOf = (value?: number) =>\n  numberOr(value, DEFAULT_DENSITY, 0.35, 1.85)\nconst seedOf = (value?: number) =>\n  Math.round(numberOr(value, DEFAULT_SEED, 0, 2 ** 32 - 1)) >>> 0\n\nconst tiltOf = (value?: number) => numberOr(value, 0, -MAX_TILT, MAX_TILT)\nconst spinOf = (value?: number) => {\n  const deg = numberOr(value, 0, -Infinity, Infinity)\n  return ((((deg + 180) % 360) + 360) % 360) - 180\n}\n\nfunction themeOf(value?: PhosphorScoreTheme): PhosphorScoreTheme {\n  return value === \"light\" || value === \"dark\" || value === \"auto\"\n    ? value\n    : \"auto\"\n}\n\nfunction optionalColor(value?: string) {\n  const next = value?.trim()\n  return next ? next : undefined\n}\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: PhosphorScoreTheme): boolean {\n  if (theme === \"dark\") return true\n  if (theme === \"light\") return false\n  return isDarkTheme()\n}\n\nexport function resolveColor(color: string | undefined, dark: boolean) {\n  const custom = optionalColor(color)\n  if (custom) return custom\n  return dark ? DARK_COLOR : LIGHT_COLOR\n}\n\nexport function resolveBg(dark: boolean) {\n  return dark ? DARK_BG : LIGHT_BG\n}\n\n/** Any CSS color → rgb, using the canvas' own parser. */\nfunction parseColor(\n  ctx: CanvasRenderingContext2D,\n  input: string,\n  fallback: string\n): Rgb {\n  ctx.fillStyle = fallback\n  ctx.fillStyle = input\n  const value = String(ctx.fillStyle)\n  if (value.startsWith(\"#\") && value.length === 7) {\n    return [\n      parseInt(value.slice(1, 3), 16),\n      parseInt(value.slice(3, 5), 16),\n      parseInt(value.slice(5, 7), 16),\n    ]\n  }\n  const parts = value.match(/[\\d.]+/g)?.map(Number) ?? []\n  return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0]\n}\n\nfunction rgba(rgb: Rgb, a: number) {\n  return `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${clamp(a, 0, 1)})`\n}\n\nfunction generateScore(seed: number, density: number): Score {\n  const rng = mulberry32(seed)\n  const notes: Note[] = []\n  const stems: Stem[] = []\n  const marks: Mark[] = []\n  const hairpins: Hairpin[] = []\n  const slurs: Slur[] = []\n\n  const note = (t: number, pitch: number, staff: Staff, hollow = false) => {\n    const n: Note = {\n      t,\n      pitch: clamp(Math.round(pitch), -3, 11),\n      staff,\n      hollow,\n      acc: rng() < 0.08 ? (rng() < 0.5 ? -1 : 1) : 0,\n    }\n    notes.push(n)\n    return n\n  }\n\n  const addStem = (\n    staff: Staff,\n    list: Note[],\n    beams: Stem[\"beams\"],\n    chord = false\n  ) => {\n    const pitches = list.map((n) => n.pitch)\n    const tip =\n      staff === 0 ? Math.min(...pitches) - STEM : Math.max(...pitches) + STEM\n    stems.push({\n      staff,\n      notes: list,\n      t0: list[0]!.t,\n      t1: list[list.length - 1]!.t,\n      tip,\n      beams: list.length > 1 && !chord ? beams : 0,\n      chord,\n    })\n  }\n\n  const run = (\n    staff: Staff,\n    start: number,\n    pitch: number,\n    count: number,\n    step: number\n  ) => {\n    let dir = rng() < 0.5 ? 1 : -1\n    let p = pitch\n    const list: Note[] = []\n    for (let i = 0; i < count; i++) {\n      if (i === 0 || rng() > 0.12 / density)\n        list.push(note(start + i * step, p, staff))\n      p += dir * (rng() < 0.18 ? 2 : 1)\n      if (p >= 10 || p <= -2) {\n        dir = -dir\n        p = clamp(p, -2, 10)\n      }\n    }\n    // A run thinned down to one note is drawn as a lone quarter.\n    addStem(staff, list, step <= 0.25 ? 2 : 1)\n    if (list.length >= 4 && rng() < 0.45) {\n      slurs.push({ staff, first: list[0]!, last: list[list.length - 1]! })\n    }\n  }\n\n  const arpeggio = (\n    staff: Staff,\n    start: number,\n    root: number,\n    step: number\n  ) => {\n    const shape = [0, 2, 4, 7, 4, 2, 0, -1]\n    const list = shape.map((offset, i) =>\n      note(start + i * step, root + offset, staff)\n    )\n    addStem(staff, list, step <= 0.25 ? 2 : 1)\n  }\n\n  const chord = (staff: Staff, t: number, root: number, hollow: boolean) => {\n    const list = [\n      note(t, root, staff, hollow),\n      note(t, root + 2, staff, hollow),\n    ]\n    if (rng() < 0.7) list.push(note(t, root + 4, staff, hollow))\n    addStem(staff, list, 0, true)\n  }\n\n  let t = 0\n  while (t < LOOP_END) {\n    const room = LOOP_END - t\n    const kind = rng()\n    const lead: Staff = rng() < 0.55 ? 0 : 1\n    const other: Staff = lead === 0 ? 1 : 0\n    const phraseStart = t\n\n    if (kind < 0.5) {\n      const count = rng() < 0.4 ? 8 : rng() < 0.55 ? 6 : 4\n      const step = rng() < 0.35 * density ? 0.25 : 0.5\n      const length = count * step\n      if (length > room) break\n      run(lead, t, Math.floor(rng() * 7) + 1, count, step)\n      if (rng() < 0.55 * density) {\n        chord(other, t, 1 + Math.floor(rng() * 4), length >= 2 && rng() < 0.5)\n      }\n      t += length\n    } else if (kind < 0.72) {\n      if (room < 2) break\n      arpeggio(lead, t, 1 + Math.floor(rng() * 4), 0.25)\n      if (rng() < 0.7 * density)\n        run(other, t, Math.floor(rng() * 4) + 1, 4, 0.5)\n      t += 2\n    } else if (kind < 0.88) {\n      const hollow = rng() < 0.45\n      const length = hollow ? 2 : 1\n      if (length > room) break\n      chord(0, t, 2 + Math.floor(rng() * 4), hollow)\n      chord(1, t, Math.floor(rng() * 4), hollow)\n      t += length\n    } else {\n      // A rest. Sparser scores rest longer.\n      t += density < 0.8 ? 1 : 0.5\n      continue\n    }\n\n    if (rng() < 0.2)\n      marks.push({\n        t: phraseStart,\n        text: DYNAMICS[Math.floor(rng() * DYNAMICS.length)]!,\n      })\n    if (rng() < 0.14) {\n      const dur = Math.min(2 + Math.floor(rng() * 3), LOOP_END - phraseStart)\n      if (dur >= 1) hairpins.push({ t: phraseStart, dur, opening: rng() < 0.5 })\n    }\n  }\n\n  return { notes, stems, marks, hairpins, slurs }\n}\n\nfunction makeDust(seed: number): Dust[] {\n  const rng = mulberry32(seed ^ 0x9e3779b9)\n  return Array.from({ length: 90 }, () => ({\n    x: rng(),\n    y: rng(),\n    z: rng(),\n    s: 0.4 + rng() * 1.4,\n    a: 0.08 + rng() * 0.22,\n  }))\n}\n\n/** A soft round glow in `rgb`, drawn once and stamped with `drawImage`. */\nfunction makeGlowSprite(rgb: Rgb) {\n  const size = 64\n  const sprite = document.createElement(\"canvas\")\n  sprite.width = size\n  sprite.height = size\n  const g = sprite.getContext(\"2d\")\n  if (!g) return sprite\n  const grad = g.createRadialGradient(\n    size / 2,\n    size / 2,\n    0,\n    size / 2,\n    size / 2,\n    size / 2\n  )\n  grad.addColorStop(0, rgba(rgb, 1))\n  grad.addColorStop(0.25, rgba(rgb, 0.45))\n  grad.addColorStop(0.6, rgba(rgb, 0.1))\n  grad.addColorStop(1, rgba(rgb, 0))\n  g.fillStyle = grad\n  g.fillRect(0, 0, size, size)\n  return sprite\n}\n\n/** Brightness at the playhead: ramps in just before, decays after (phosphor persistence). */\nfunction litAt(d: number) {\n  if (d > 0.3) return 0\n  if (d >= 0) {\n    const k = 1 - d / 0.3\n    return k * k\n  }\n  return Math.exp(d * 2.4)\n}\n\n/**\n * How the score plane sits in front of the camera. Plane coordinates are\n * the unrotated canvas pixels; it turns about the playhead, which is also\n * where perspective converges.\n */\ntype View = {\n  /** `rotateX · rotateY · rotateZ`, row-major, CSS axes (y down, z toward you). */\n  m: number[]\n  ox: number\n  oy: number\n  /** Camera distance. */\n  cam: number\n  /** No depth variation across the plane, so nothing foreshortens or fogs. */\n  depthless: boolean\n  /** Bounds of the plane that are on screen and not lost in the distance. */\n  x0: number\n  x1: number\n  y0: number\n  y1: number\n}\n\nfunction makeView(\n  w: number,\n  h: number,\n  rotateX: number,\n  rotateY: number,\n  rotateZ: number\n): View {\n  const rad = Math.PI / 180\n  const [cx, sx] = [Math.cos(rotateX * rad), Math.sin(rotateX * rad)]\n  const [cy, sy] = [Math.cos(rotateY * rad), Math.sin(rotateY * rad)]\n  const [cz, sz] = [Math.cos(rotateZ * rad), Math.sin(rotateZ * rad)]\n  // Rx · Ry · Rz, the order CSS applies `rotateX() rotateY() rotateZ()`.\n  const m = [\n    cy * cz,\n    -cy * sz,\n    sy,\n    sx * sy * cz + cx * sz,\n    -sx * sy * sz + cx * cz,\n    -sx * cy,\n    -cx * sy * cz + sx * sz,\n    cx * sy * sz + sx * cz,\n    cx * cy,\n  ]\n  const ox = w / 2\n  const oy = h * PLAYHEAD\n  const cam = Math.max(w, h) * PERSPECTIVE\n  const view: View = {\n    m,\n    ox,\n    oy,\n    cam,\n    depthless: Math.abs(m[6]!) + Math.abs(m[7]!) < 1e-6,\n    x0: 0,\n    x1: w,\n    y0: 0,\n    y1: h,\n  }\n  if (rotateX === 0 && rotateY === 0 && rotateZ === 0) return view\n\n  // The screen, less whatever lies beyond FAR_SCALE, traced back onto the\n  // plane. Along a ray through screen point (u, v) the plane is hit at\n  // t = m22·cam / (m22·cam − m02·u − m12·v), with depth scale 1 / t, so\n  // \"not too far\" is a straight line on screen and clips the rectangle.\n  const [m02, m12, m22] = [m[2]!, m[5]!, m[8]!]\n  const far = (u: number, v: number) =>\n    m22 * cam * (1 - FAR_SCALE) - m02 * u - m12 * v\n  const corners: [number, number][] = [\n    [-ox, -oy],\n    [w - ox, -oy],\n    [w - ox, h - oy],\n    [-ox, h - oy],\n  ]\n  const kept: [number, number][] = []\n  corners.forEach((a, i) => {\n    const b = corners[(i + 1) % corners.length]!\n    const fa = far(a[0], a[1])\n    const fb = far(b[0], b[1])\n    if (fa >= 0) kept.push(a)\n    if (fa >= 0 !== fb >= 0) {\n      const k = fa / (fa - fb)\n      kept.push([a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k])\n    }\n  })\n\n  view.x0 = view.y0 = Infinity\n  view.x1 = view.y1 = -Infinity\n  for (const [u, v] of kept) {\n    const t = (m22 * cam) / (m22 * cam - m02 * u - m12 * v)\n    const [wx, wy, wz] = [t * u, t * v, cam - t * cam]\n    const px = m[0]! * wx + m[3]! * wy + m[6]! * wz + ox\n    const py = m[1]! * wx + m[4]! * wy + m[7]! * wz + oy\n    view.x0 = Math.min(view.x0, px)\n    view.x1 = Math.max(view.x1, px)\n    view.y0 = Math.min(view.y0, py)\n    view.y1 = Math.max(view.y1, py)\n  }\n  return view\n}\n\n/** Fades the plane out as it recedes toward `FAR_SCALE`. */\nfunction fogOf(scale: number) {\n  const k = clamp((scale - FAR_SCALE) / FOG_RANGE, 0, 1)\n  return k * k * (3 - 2 * k)\n}\n\n/**\n * Vertical phosphor sheet music: a grand staff scrolls down toward a\n * playhead, each note blooms and flares as it plays, then fades with a\n * phosphor afterglow. Canvas 2D; pauses off-screen and in hidden tabs, and\n * holds a still frame under `prefers-reduced-motion`.\n */\nexport function createPhosphorScore(\n  canvas: HTMLCanvasElement,\n  initial: PhosphorScoreOptions = {}\n): PhosphorScoreInstance | null {\n  let options: PhosphorScoreOptions = {\n    glow: DEFAULT_GLOW,\n    speed: DEFAULT_SPEED,\n    density: DEFAULT_DENSITY,\n    seed: DEFAULT_SEED,\n    ...initial,\n    sway: initial.sway ?? true,\n    theme: themeOf(initial.theme),\n  }\n\n  const ctx = canvas.getContext(\"2d\", { alpha: true })\n  if (!ctx) return null\n\n  let score = generateScore(seedOf(options.seed), densityOf(options.density))\n  let previous: Score | null = null\n  let rebuildAge = REBUILD_FADE\n  let dust = makeDust(seedOf(options.seed))\n\n  let dark = resolveDark(themeOf(options.theme))\n  let rgb: Rgb = [0, 0, 0]\n  let glowSprite = document.createElement(\"canvas\")\n  const recolor = () => {\n    rgb = parseColor(\n      ctx,\n      resolveColor(options.color, dark),\n      dark ? DARK_COLOR : LIGHT_COLOR\n    )\n    glowSprite = makeGlowSprite(rgb)\n  }\n  recolor()\n  options.onThemeChange?.(dark)\n\n  const flares: Flare[] = []\n  const size = { w: 0, h: 0, dpr: 1 }\n  let reduce = false\n  let onScreen = true\n  let running = true\n  let raf = 0\n  let lastFrame = 0\n  // Start a few bars in, so the first frame already has notes at the playhead.\n  let beat = 8\n  let clock = 0\n  let view = makeView(1, 1, 0, 0, 0)\n\n  /** Sizes the canvas to its parent; true when the backing store changed. */\n  const resize = () => {\n    const parent = canvas.parentElement\n    if (!parent) return false\n    const dpr = Math.min(window.devicePixelRatio || 1, 2)\n    const w = parent.clientWidth\n    const h = parent.clientHeight\n    if (w === size.w && h === size.h && dpr === size.dpr) return false\n    size.w = w\n    size.h = h\n    size.dpr = dpr\n    canvas.width = Math.max(1, Math.floor(w * dpr))\n    canvas.height = Math.max(1, Math.floor(h * dpr))\n    canvas.style.width = `${w}px`\n    canvas.style.height = `${h}px`\n    wake()\n    return true\n  }\n\n  const shouldAnimate = () =>\n    running && onScreen && !reduce && document.visibilityState !== \"hidden\"\n\n  function wake() {\n    if (!running || raf) return\n    lastFrame = performance.now()\n    raf = requestAnimationFrame(tick)\n  }\n\n  const syncTheme = () => {\n    const next = resolveDark(themeOf(options.theme))\n    if (next === dark) return\n    dark = next\n    recolor()\n    options.onThemeChange?.(dark)\n    wake()\n  }\n\n  // Resizing cleared the canvas; draw now, or it shows blank for a frame.\n  const ro = new ResizeObserver(() => {\n    if (resize() && running) draw()\n  })\n  if (canvas.parentElement) ro.observe(canvas.parentElement)\n\n  const io = new IntersectionObserver(([entry]) => {\n    onScreen = entry?.isIntersecting ?? true\n    wake()\n  })\n  io.observe(canvas)\n\n  const onVisibility = () => wake()\n  document.addEventListener(\"visibilitychange\", onVisibility)\n\n  const mqReduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n  const onReduce = () => {\n    reduce = mqReduce.matches\n    wake()\n  }\n  reduce = mqReduce.matches\n  mqReduce.addEventListener(\"change\", onReduce)\n\n  const mo = new MutationObserver(syncTheme)\n  mo.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: [\"class\", \"data-theme\"],\n  })\n  const mqDark = window.matchMedia(\"(prefers-color-scheme: dark)\")\n  mqDark.addEventListener(\"change\", syncTheme)\n\n  function tick(now: number) {\n    raf = 0\n    if (!running) return\n    if (Math.min(window.devicePixelRatio || 1, 2) !== size.dpr) resize()\n\n    const dt = Math.min(0.05, Math.max(0, (now - lastFrame) / 1000))\n    lastFrame = now\n    const animate = shouldAnimate()\n    const before = beat\n    if (animate) {\n      clock += dt\n      beat = (beat + dt * speedOf(options.speed)) % LOOP_BEATS\n      rebuildAge += dt\n      spawnFlares(before, beat)\n    } else {\n      rebuildAge = REBUILD_FADE\n      flares.length = 0\n    }\n    for (let i = flares.length - 1; i >= 0; i--) {\n      flares[i]!.age += dt\n      if (flares[i]!.age >= FLARE_LIFE) flares.splice(i, 1)\n    }\n\n    draw()\n    // A pixel-ratio change above resized, and its wake may have queued the\n    // next frame already; a second request would run two loops.\n    if (animate && !raf) raf = requestAnimationFrame(tick)\n  }\n\n  /** Every note whose time was crossed since the last frame flares once; no frame can skip one. */\n  function spawnFlares(from: number, to: number) {\n    const span = wrapDelta(to, from)\n    if (span <= 0) return\n    for (const n of score.notes) {\n      const d = wrapDelta(n.t, from)\n      if (d > 0 && d <= span) {\n        if (flares.length >= MAX_FLARES) flares.shift()\n        flares.push({ staff: n.staff, pitch: n.pitch, age: 0 })\n      }\n    }\n  }\n\n  function draw() {\n    const { w, h, dpr } = size\n    ctx!.setTransform(dpr, 0, 0, dpr, 0, 0)\n    ctx!.globalCompositeOperation = \"source-over\"\n    ctx!.globalAlpha = 1\n    ctx!.clearRect(0, 0, w, h)\n    if (w < 2 || h < 2) return\n\n    view = makeView(\n      w,\n      h,\n      tiltOf(options.rotateX),\n      tiltOf(options.rotateY),\n      spinOf(options.rotateZ)\n    )\n    const swayOn = options.sway !== false && !reduce\n    const cam = {\n      x: swayOn ? Math.cos(clock * 0.23) * 10 : 0,\n      y: swayOn ? Math.sin(clock * 0.31) * 8 : 0,\n    }\n    const sp = clamp(Math.min(w, h) * 0.021, 5, 11)\n    const layout = {\n      sp,\n      gap: clamp(w * 0.16, sp * 6.5, sp * 12),\n      ppb: clamp(h * 0.15, sp * 5.2, sp * 11),\n      cx: w / 2 + cam.x,\n      playY: h * PLAYHEAD + cam.y,\n    }\n    const bloom = glowOf(options.glow) / 50\n\n    // Dust drifts in screen space, beneath everything.\n    for (const d of dust) {\n      const px = (d.x + clock * 0.01 * d.z) % 1\n      const py = (d.y + beat * 0.004 * (0.3 + d.z)) % 1\n      ctx!.fillStyle = rgba(rgb, dark ? d.a : d.a * 0.35)\n      ctx!.fillRect(px * w, py * h, d.s, d.s)\n    }\n\n    drawStaves(layout)\n\n    const fade = previous ? clamp(rebuildAge / REBUILD_FADE, 0, 1) : 1\n    if (previous && fade >= 1) previous = null\n    if (previous) drawScore(previous, layout, 1 - fade, 0)\n    drawScore(score, layout, fade, bloom)\n\n    drawPlayhead(layout, bloom)\n    drawFlares(layout, bloom)\n    drawEdgeFade(w, h)\n  }\n\n  type Layout = {\n    sp: number\n    gap: number\n    ppb: number\n    cx: number\n    playY: number\n  }\n\n  const xOf = (l: Layout, staff: Staff, pitch: number) =>\n    l.cx + (staff === 0 ? -l.gap : l.gap) + (pitch - 4) * (l.sp / 2)\n  const yOf = (l: Layout, d: number) => l.playY - d * l.ppb\n\n  /**\n   * Every beat offset at which something at time `t`, lasting `len` beats,\n   * is in view. Usually one; a steep tilt can see several loops ahead.\n   */\n  function spots(l: Layout, t: number, len = 0) {\n    const minD = (l.playY - view.y1 - l.ppb) / l.ppb\n    const maxD = (l.playY - view.y0 + l.ppb) / l.ppb\n    const first = wrapDelta(t, beat)\n    const out: number[] = []\n    const from = Math.ceil((minD - len - first) / LOOP_BEATS)\n    const to = Math.floor((maxD - first) / LOOP_BEATS)\n    for (let k = from; k <= to; k++) out.push(first + k * LOOP_BEATS)\n    return out\n  }\n\n  /**\n   * Plane point → screen `[x, y, scale]`, where scale is how much the\n   * perspective enlarges it there. Scale is `0` behind the camera.\n   */\n  function project(x: number, y: number): [number, number, number] {\n    const { m, ox, oy, cam } = view\n    const px = x - ox\n    const py = y - oy\n    const z = m[6]! * px + m[7]! * py\n    if (cam - z < cam * 0.02) return [0, 0, 0]\n    const s = cam / (cam - z)\n    return [\n      ox + (m[0]! * px + m[1]! * py) * s,\n      oy + (m[3]! * px + m[4]! * py) * s,\n      s,\n    ]\n  }\n\n  /**\n   * Moves the canvas into the plane at `(x, y)`, so a notehead, glyph or\n   * glow drawn around the origin tilts and foreshortens with the score.\n   * Returns the distance fog there; `leave()` restores screen space.\n   */\n  function enter(x: number, y: number) {\n    const { m, ox, oy, cam } = view\n    const { dpr } = size\n    const px = x - ox\n    const py = y - oy\n    const qx = m[0]! * px + m[1]! * py\n    const qy = m[3]! * px + m[4]! * py\n    const z = m[6]! * px + m[7]! * py\n    if (cam - z < cam * 0.02) return 0\n    const s = cam / (cam - z)\n    // Jacobian of the projection: how a unit step along the plane lands on screen.\n    const k = (s * s) / cam\n    ctx!.setTransform(\n      dpr * (s * m[0]! + qx * k * m[6]!),\n      dpr * (s * m[3]! + qy * k * m[6]!),\n      dpr * (s * m[1]! + qx * k * m[7]!),\n      dpr * (s * m[4]! + qy * k * m[7]!),\n      dpr * (ox + qx * s),\n      dpr * (oy + qy * s)\n    )\n    return fogOf(s)\n  }\n\n  function leave() {\n    const { dpr } = size\n    ctx!.setTransform(dpr, 0, 0, dpr, 0, 0)\n    ctx!.globalAlpha = 1\n  }\n\n  /** Plane stroke width; `line` and `polyline` scale it with depth. */\n  let lw = 1\n\n  /**\n   * A straight stroke on the plane. Long ones pass `segments` so the fog\n   * can thin them as they recede.\n   */\n  function line(x0: number, y0: number, x1: number, y1: number, segments = 1) {\n    const n = view.depthless ? 1 : segments\n    for (let i = 0; i < n; i++) {\n      const a = i / n\n      const b = (i + 1) / n\n      polyline([\n        [x0 + (x1 - x0) * a, y0 + (y1 - y0) * a],\n        [x0 + (x1 - x0) * b, y0 + (y1 - y0) * b],\n      ])\n    }\n  }\n\n  function polyline(points: [number, number][]) {\n    let scale = 0\n    ctx!.beginPath()\n    for (const [i, [x, y]] of points.entries()) {\n      const p = project(x, y)\n      if (p[2] <= 0) return\n      scale += p[2]\n      if (i === 0) ctx!.moveTo(p[0], p[1])\n      else ctx!.lineTo(p[0], p[1])\n    }\n    scale /= points.length\n    const fog = fogOf(scale)\n    if (fog <= 0) return\n    ctx!.globalAlpha = fog\n    ctx!.lineWidth = lw * scale\n    ctx!.stroke()\n    ctx!.globalAlpha = 1\n  }\n\n  /** A quadratic curve on the plane; its control point is projected too. */\n  function curve(\n    x0: number,\n    y0: number,\n    cx: number,\n    cy: number,\n    x1: number,\n    y1: number\n  ) {\n    const a = project(x0, y0)\n    const c = project(cx, cy)\n    const b = project(x1, y1)\n    if (a[2] <= 0 || b[2] <= 0 || c[2] <= 0) return\n    const scale = (a[2] + b[2]) / 2\n    const fog = fogOf(scale)\n    if (fog <= 0) return\n    ctx!.globalAlpha = fog\n    ctx!.lineWidth = lw * scale\n    ctx!.beginPath()\n    ctx!.moveTo(a[0], a[1])\n    ctx!.quadraticCurveTo(c[0], c[1], b[0], b[1])\n    ctx!.stroke()\n    ctx!.globalAlpha = 1\n  }\n\n  /** The glow sprite, stretched to `rx` × `ry` around `(x, y)` on the plane. */\n  function glow(x: number, y: number, rx: number, ry: number, alpha: number) {\n    const fog = enter(x, y)\n    if (fog > 0) {\n      ctx!.globalAlpha = alpha * fog\n      ctx!.drawImage(glowSprite, -rx, -ry, rx * 2, ry * 2)\n    }\n    leave()\n  }\n\n  function drawStaves(l: Layout) {\n    ctx!.lineCap = \"butt\"\n    lw = 1\n    ctx!.strokeStyle = rgba(rgb, dark ? 0.2 : 0.24)\n    for (const staff of [0, 1] as const) {\n      for (let p = 0; p <= 8; p += 2) {\n        const x = Math.round(xOf(l, staff, p)) + 0.5\n        line(x, view.y0, x, view.y1, 16)\n      }\n    }\n    // Bar lines every four beats, through both staves like a grand staff.\n    for (let bar = 0; bar < LOOP_BEATS; bar += 4) {\n      for (const d of spots(l, bar)) {\n        const y = yOf(l, d)\n        ctx!.strokeStyle = rgba(rgb, (dark ? 0.16 : 0.2) + litAt(d) * 0.3)\n        line(xOf(l, 0, 0), y, xOf(l, 1, 8), y)\n      }\n    }\n  }\n\n  function drawScore(s: Score, l: Layout, opacity: number, bloom: number) {\n    if (opacity <= 0) return\n    const base = (d: number) =>\n      d >= 0 ? (dark ? 0.46 : 0.58) : dark ? 0.22 : 0.3\n    const alphaAt = (d: number) => {\n      const b = base(d)\n      return (b + (1 - b) * litAt(d)) * opacity\n    }\n    const sp = l.sp\n    const rx = sp * 0.5\n    const ry = sp * 0.64\n\n    ctx!.lineCap = \"butt\"\n\n    // Dynamics and hairpins share the space between the staves.\n    ctx!.font = `italic ${Math.round(clamp(sp * 1.3, 10, 17))}px Georgia, \"Times New Roman\", serif`\n    ctx!.textAlign = \"center\"\n    ctx!.textBaseline = \"middle\"\n    for (const mark of s.marks) {\n      for (const d of spots(l, mark.t)) {\n        const fog = enter(l.cx, yOf(l, d) + sp * 0.9)\n        if (fog > 0) {\n          ctx!.globalAlpha = fog\n          ctx!.fillStyle = rgba(rgb, alphaAt(d) * 0.85)\n          ctx!.fillText(mark.text, 0, 0)\n        }\n        leave()\n      }\n    }\n    lw = 1\n    for (const pin of s.hairpins) {\n      for (const d0 of spots(l, pin.t, pin.dur)) {\n        const d1 = d0 + pin.dur\n        const narrow = pin.opening ? d0 : d1\n        const wide = pin.opening ? d1 : d0\n        const half = sp * 0.9\n        ctx!.strokeStyle = rgba(\n          rgb,\n          alphaAt(Math.min(Math.abs(d0), Math.abs(d1))) * 0.6\n        )\n        polyline([\n          [l.cx - half, yOf(l, wide)],\n          [l.cx, yOf(l, narrow)],\n          [l.cx + half, yOf(l, wide)],\n        ])\n      }\n    }\n\n    // Slurs curve on the inner side, opposite the stems.\n    lw = Math.max(1, sp * 0.1)\n    for (const slur of s.slurs) {\n      const len = slur.last.t - slur.first.t\n      for (const d0 of spots(l, slur.first.t, len)) {\n        const d1 = d0 + len\n        const inward = slur.staff === 0 ? 1 : -1\n        const y0 = yOf(l, d0)\n        const y1 = yOf(l, d1)\n        const x0 = xOf(l, slur.staff, slur.first.pitch + inward * 2)\n        const x1 = xOf(l, slur.staff, slur.last.pitch + inward * 2)\n        const edge =\n          inward > 0\n            ? Math.max(slur.first.pitch, slur.last.pitch) + 3.5\n            : Math.min(slur.first.pitch, slur.last.pitch) - 3.5\n        ctx!.strokeStyle = rgba(\n          rgb,\n          alphaAt(d1 < 0 ? d1 : Math.max(0, d0)) * 0.5\n        )\n        curve(x0, y0, xOf(l, slur.staff, edge), (y0 + y1) / 2, x1, y1)\n      }\n    }\n\n    // Stems and beams. A stem runs along the pitch axis from the side of its\n    // head (the time axis is \"across\" here), out to the beam.\n    const stemW = Math.max(1, sp * 0.11)\n    const side = -ry * 0.8\n    for (const stem of s.stems) {\n      const len = stem.t1 - stem.t0\n      for (const d0 of spots(l, stem.t0, len)) {\n        const d1 = d0 + len\n        const out = stem.staff === 0 ? -1 : 1\n        const tipX = xOf(l, stem.staff, stem.tip)\n        lw = stemW\n        if (stem.chord) {\n          // One stem through the chord, from the innermost head out to the tip.\n          const inner =\n            out < 0\n              ? Math.max(...stem.notes.map((n) => n.pitch))\n              : Math.min(...stem.notes.map((n) => n.pitch))\n          const y = yOf(l, d0) + side\n          ctx!.strokeStyle = rgba(rgb, alphaAt(d0))\n          line(xOf(l, stem.staff, inner), y, tipX, y)\n          continue\n        }\n        for (const n of stem.notes) {\n          const d = d0 + (n.t - stem.t0)\n          const y = yOf(l, d) + side\n          ctx!.strokeStyle = rgba(rgb, alphaAt(d))\n          line(xOf(l, stem.staff, n.pitch), y, tipX, y)\n        }\n        if (stem.beams === 0) continue\n        const nearest = d1 < 0 ? d1 : d0 > 0 ? d0 : 0\n        ctx!.strokeStyle = rgba(rgb, alphaAt(nearest))\n        lw = sp * 0.36\n        const yA = yOf(l, d0) + side + stemW / 2\n        const yB = yOf(l, d1) + side - stemW / 2\n        const offset = sp * 0.18 * out\n        line(tipX - offset, yA, tipX - offset, yB)\n        if (stem.beams === 2) {\n          const x2 = tipX - offset - out * sp * 0.75\n          line(x2, yA, x2, yB)\n        }\n      }\n    }\n\n    // Ledger lines, parallel to the staff lines.\n    lw = 1\n    for (const n of s.notes) {\n      if (n.pitch > -2 && n.pitch < 10) continue\n      for (const d of spots(l, n.t)) {\n        const y = yOf(l, d)\n        ctx!.strokeStyle = rgba(rgb, alphaAt(d) * 0.7)\n        const from = n.pitch < 0 ? -2 : 10\n        const step = n.pitch < 0 ? -2 : 2\n        for (let p = from; step < 0 ? p >= n.pitch : p <= n.pitch; p += step) {\n          const x = xOf(l, n.staff, p)\n          line(x, y - ry * 1.7, x, y + ry * 1.7)\n        }\n      }\n    }\n\n    // Glow under the heads that are playing.\n    if (bloom > 0) {\n      ctx!.globalCompositeOperation = dark ? \"lighter\" : \"source-over\"\n      for (const n of s.notes) {\n        for (const d of spots(l, n.t)) {\n          const lit = litAt(d)\n          if (lit < 0.03) continue\n          const r = sp * (1.1 + lit * 1.5) * bloom\n          glow(\n            xOf(l, n.staff, n.pitch),\n            yOf(l, d),\n            r,\n            r,\n            lit * (dark ? 0.7 : 0.32) * Math.min(1, bloom) * opacity\n          )\n        }\n      }\n      ctx!.globalCompositeOperation = \"source-over\"\n    }\n\n    // Noteheads, with accidentals just before them in reading order (below).\n    ctx!.font = `${Math.round(sp * 1.5)}px Georgia, \"Times New Roman\", serif`\n    for (const n of s.notes) {\n      for (const d of spots(l, n.t)) {\n        const fog = enter(xOf(l, n.staff, n.pitch), yOf(l, d))\n        if (fog <= 0) {\n          leave()\n          continue\n        }\n        ctx!.globalAlpha = fog\n        const color = rgba(rgb, alphaAt(d))\n        ctx!.beginPath()\n        ctx!.ellipse(0, 0, rx, ry, 0.35, 0, Math.PI * 2)\n        if (n.hollow) {\n          ctx!.strokeStyle = color\n          ctx!.lineWidth = Math.max(1.2, sp * 0.16)\n          ctx!.stroke()\n        } else {\n          ctx!.fillStyle = color\n          ctx!.fill()\n        }\n        if (n.acc !== 0) {\n          ctx!.fillStyle = color\n          ctx!.fillText(n.acc > 0 ? \"♯\" : \"♭\", 0, ry + sp * 0.95)\n        }\n        leave()\n      }\n    }\n  }\n\n  function drawPlayhead(l: Layout, bloom: number) {\n    const y = Math.round(l.playY) + 0.5\n    if (bloom > 0) {\n      ctx!.globalCompositeOperation = dark ? \"lighter\" : \"source-over\"\n      const alpha = (dark ? 0.35 : 0.12) * Math.min(1, bloom)\n      const band = l.sp * 1.4 * Math.max(0.6, bloom)\n      // In slices, so the band follows the perspective across the plane.\n      const slices = view.depthless ? 1 : 24\n      const span = (view.x1 - view.x0) / slices\n      const src = glowSprite.width / slices\n      for (let i = 0; i < slices; i++) {\n        const fog = enter(view.x0 + (i + 0.5) * span, y)\n        if (fog > 0) {\n          ctx!.globalAlpha = alpha * fog\n          ctx!.drawImage(\n            glowSprite,\n            i * src,\n            0,\n            src,\n            glowSprite.height,\n            -span / 2,\n            -band,\n            span,\n            band * 2\n          )\n        }\n        leave()\n      }\n      ctx!.globalCompositeOperation = \"source-over\"\n    }\n    ctx!.strokeStyle = rgba(rgb, dark ? 0.75 : 0.55)\n    lw = 1\n    line(view.x0, y, view.x1, y, 12)\n  }\n\n  function drawFlares(l: Layout, bloom: number) {\n    if (flares.length === 0 || bloom <= 0) return\n    ctx!.globalCompositeOperation = dark ? \"lighter\" : \"source-over\"\n    for (const f of flares) {\n      const k = f.age / FLARE_LIFE\n      const fade = (1 - k) * (1 - k)\n      const x = xOf(l, f.staff, f.pitch)\n      const r = l.sp * (1.6 + k * 1.4) * bloom\n      glow(x, l.playY, r, r, fade * (dark ? 0.8 : 0.4))\n      // A streak along the playhead.\n      const streak = l.sp * (2.5 + k * 3) * bloom\n      glow(x, l.playY, streak, 1.5, fade * (dark ? 0.9 : 0.5))\n    }\n    ctx!.globalCompositeOperation = \"source-over\"\n  }\n\n  /** Top and bottom fade into the background, in the canvas, so it costs nothing and blurs nothing. */\n  function drawEdgeFade(w: number, h: number) {\n    const f = h * EDGE_FADE\n    // Erase toward the edges rather than paint over them, so the fade\n    // lands on whatever background the parent has.\n    const solid = \"rgba(0,0,0,1)\"\n    const clear = \"rgba(0,0,0,0)\"\n    ctx!.globalCompositeOperation = \"destination-out\"\n    const top = ctx!.createLinearGradient(0, 0, 0, f)\n    top.addColorStop(0, solid)\n    top.addColorStop(1, clear)\n    ctx!.fillStyle = top\n    ctx!.fillRect(0, 0, w, f)\n    const bottom = ctx!.createLinearGradient(0, h - f, 0, h)\n    bottom.addColorStop(0, clear)\n    bottom.addColorStop(1, solid)\n    ctx!.fillStyle = bottom\n    ctx!.fillRect(0, h - f, w, f)\n    ctx!.globalCompositeOperation = \"source-over\"\n  }\n\n  resize()\n  wake()\n\n  return {\n    setOptions(next) {\n      const prevSeed = seedOf(options.seed)\n      const prevDensity = densityOf(options.density)\n      const prevColor = options.color\n      options = {\n        ...options,\n        ...next,\n        sway: next.sway ?? options.sway,\n        theme: themeOf(next.theme ?? options.theme),\n      }\n      syncTheme()\n      if (options.color !== prevColor) recolor()\n      if (\n        seedOf(options.seed) !== prevSeed ||\n        densityOf(options.density) !== prevDensity\n      ) {\n        // Crossfade from the old score instead of cutting.\n        previous = reduce ? null : score\n        rebuildAge = reduce ? REBUILD_FADE : 0\n        score = generateScore(seedOf(options.seed), densityOf(options.density))\n        dust = makeDust(seedOf(options.seed))\n        flares.length = 0\n      }\n      wake()\n    },\n    destroy() {\n      running = false\n      cancelAnimationFrame(raf)\n      raf = 0\n      ro.disconnect()\n      io.disconnect()\n      mo.disconnect()\n      document.removeEventListener(\"visibilitychange\", onVisibility)\n      mqReduce.removeEventListener(\"change\", onReduce)\n      mqDark.removeEventListener(\"change\", syncTheme)\n    },\n  }\n}\n\nexport type PhosphorScoreProps = Omit<PhosphorScoreOptions, \"onThemeChange\"> & {\n  className?: string\n}\n\n/**\n * Vertical phosphor sheet music: a grand staff scrolls down to a playhead,\n * each note blooms and flares as it plays, then fades with an afterglow.\n * Follows light and dark.\n */\nexport function PhosphorScore({\n  className,\n  color,\n  glow = DEFAULT_GLOW,\n  speed = DEFAULT_SPEED,\n  density = DEFAULT_DENSITY,\n  sway = true,\n  seed = DEFAULT_SEED,\n  rotateX = 0,\n  rotateY = 0,\n  rotateZ = 0,\n  theme = \"auto\",\n}: PhosphorScoreProps) {\n  const canvasRef = useRef<HTMLCanvasElement>(null)\n  const instanceRef = useRef<PhosphorScoreInstance | null>(null)\n\n  useEffect(() => {\n    const canvas = canvasRef.current\n    if (!canvas) return\n    instanceRef.current = createPhosphorScore(canvas, {\n      color,\n      glow,\n      speed,\n      density,\n      sway,\n      seed,\n      rotateX,\n      rotateY,\n      rotateZ,\n      theme,\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({\n      color,\n      glow,\n      speed,\n      density,\n      sway,\n      seed,\n      rotateX,\n      rotateY,\n      rotateZ,\n      theme,\n    })\n  }, [\n    color,\n    glow,\n    speed,\n    density,\n    sway,\n    seed,\n    rotateX,\n    rotateY,\n    rotateZ,\n    theme,\n  ])\n\n  return (\n    <div\n      data-slot=\"phosphor-score\"\n      role=\"img\"\n      aria-label=\"Falling phosphor sheet music\"\n      className={cn(\"absolute inset-0 overflow-hidden\", className)}\n    >\n      <canvas ref={canvasRef} className=\"absolute inset-0 size-full\" />\n    </div>\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/ui/phosphor-score.tsx"
    }
  ],
  "type": "registry:ui"
}