{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "particle-line",
  "type": "registry:component",
  "title": "Particle Line",
  "description": "WebGL particle reveal for LineChart series that hands off to a plain SVG line",
  "dependencies": [
    "d3-shape",
    "motion"
  ],
  "registryDependencies": [
    "@bklit/line-chart",
    "@bklit/chart-context",
    "@bklit/chart-series",
    "@bklit/x-axis",
    "@bklit/chart-tooltip"
  ],
  "files": [
    {
      "path": "src/charts/particle-line.tsx",
      "content": "\"use client\";\n\nimport { type CurveFactory, curveMonotoneX } from \"d3-shape\";\nimport { animate, m, useMotionValue } from \"motion/react\";\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n  selectIsChartHovering,\n  useChartHoverSelector,\n  useChartPortalContainer,\n  useChartStable,\n  useYScale,\n} from \"./chart-context\";\nimport { HighlightSegment } from \"./highlight-segment\";\nimport { linePathD } from \"./line-path\";\nimport { SeriesHoverDim } from \"./series-hover-dim\";\nimport { useHighlightSegment } from \"./use-highlight-segment\";\n\n/** Molten gold — the classic After Effects logo-reveal look. */\nexport const PARTICLE_LINE_GOLD = [\n  \"#c8891a\",\n  \"#ffd45e\",\n  \"#f2a91f\",\n  \"#ffe9a3\",\n] as const;\n\n/**\n * - `assemble` — a swarm swirls in and condenses onto the line.\n * - `comet` — the head streams a long, slow tail of embers behind it.\n * - `stardust` — the head leaves twinkling dust that drifts upward and lingers.\n */\nexport type ParticleLineEffect = \"assemble\" | \"comet\" | \"stardust\";\n\nexport interface ParticleLineProps {\n  /** Key in data to use for y values. */\n  dataKey: string;\n  /** Y-scale group id. Default: `\"left\"`. */\n  yAxisId?: string | number;\n  /** Curve function. Default: curveMonotoneX */\n  curve?: CurveFactory;\n  /** Series colour for the tooltip / legend. */\n  stroke?: string;\n  /** Line width in px. Default: 2.5 */\n  strokeWidth?: number;\n  /** Four hex colours cycled along the line and its particles. Default: gold. */\n  colors?: readonly string[];\n  /** Reveal style. Default: `\"assemble\"` */\n  effect?: ParticleLineEffect;\n  /** Time for the reveal front to cross the line, in ms. Default: the chart's `animationDuration` (1100). */\n  duration?: number;\n  /** Wait before the reveal starts, in ms. Default: 0 */\n  delay?: number;\n  /**\n   * Cubic-bezier for the reveal front. Default: the chart's enter easing —\n   * `cubic-bezier(0.85, 0, 0.15, 1)` unless the chart overrides it.\n   */\n  easing?: readonly [number, number, number, number];\n  /** Particles per px of line length. Default: 7 */\n  density?: number;\n  /** `assemble`: how far particles start from where they land. Other effects: spark speed multiplier × 150. Default: 150 */\n  spread?: number;\n  /** Length of the bright freshly-drawn section behind the front, in px. Default: 90 */\n  trail?: number;\n  /**\n   * Hover segment, like `<Line highlight>`: the stretch around the cursor stays\n   * full strength with soft ends, the rest dims and the glow fades out.\n   * `false` disables it. Default: `{ span: 3, fadeLength: 40, dimOpacity: 0.25 }`\n   */\n  highlight?: false | ParticleLineHighlight;\n}\n\nexport interface ParticleLineHighlight {\n  /** Data points either side of the hovered point the segment covers. Default: 3 */\n  span?: number;\n  /** Fade the segment's ends over this % (0–50) of its width per side. Default: 40 */\n  fadeLength?: number;\n  /** Opacity the rest of the line dims to while hovering. Default: 0.25 */\n  dimOpacity?: number;\n}\n\ninterface EffectPreset {\n  /** 0 = converge onto the line, 1 = emit from the head. */\n  mode: 0 | 1;\n  /** Particle life in s (assemble: linger after landing). */\n  life: [number, number];\n  /** Emit speed in px/s at `spread = 150`. */\n  speed: [number, number];\n  /** 0 = sprays in every direction, 1 = streams straight back along the line. */\n  backward: number;\n  /** px/s², positive falls. */\n  gravity: number;\n  drag: number;\n  size: [number, number];\n  twinkle: number;\n  /** How fast a particle cools from white-hot (1/s). */\n  cooling: number;\n  /** Head flare diameter in px; 0 hides it. */\n  flare: number;\n  /** Brightness of the freshly-drawn trail on the line. */\n  heatGain: number;\n}\n\nconst EFFECTS: Record<ParticleLineEffect, EffectPreset> = {\n  assemble: {\n    mode: 0,\n    life: [0.1, 0.7],\n    speed: [0, 0],\n    backward: 0,\n    gravity: 0,\n    drag: 0,\n    size: [1.2, 3.6],\n    twinkle: 0.45,\n    cooling: 0,\n    flare: 0,\n    heatGain: 1,\n  },\n  comet: {\n    mode: 1,\n    life: [0.8, 1.9],\n    speed: [50, 190],\n    backward: 0.93,\n    gravity: -12,\n    drag: 0.9,\n    size: [1.6, 5.2],\n    twinkle: 0.3,\n    cooling: 2.4,\n    flare: 38,\n    heatGain: 2.1,\n  },\n  stardust: {\n    mode: 1,\n    life: [1, 2.4],\n    speed: [8, 45],\n    backward: 0.25,\n    gravity: -30,\n    drag: 0.9,\n    size: [1, 3.4],\n    twinkle: 1,\n    cooling: 1.3,\n    flare: 22,\n    heatGain: 1.3,\n  },\n};\n\n/** Resting glow: a stroke this many times the line width, blurred, at this opacity. */\nconst GLOW_WIDTH_SCALE = 1.5;\nconst GLOW_BLUR = 3.5;\nconst GLOW_OPACITY = 0.6;\n/** Ribbon half-width must hold the blurred glow (stroke/2 + ~3σ). */\nconst RIBBON_PAD = 12;\n\nconst MAX_PARTICLES = 14_000;\nconst MAX_DPR = 2;\n/** Bright drawn trail and head flare fade out over this long after the front finishes (s). */\nconst HEAT_FADE_S = 0.9;\n/** Particle buffer layout: target xy, s, tangent xy, rand × 4, when (0–1 of the reveal). */\nconst PARTICLE_STRIDE = 10;\nconst RIBBON_STRIDE = 5;\n\n/* -------------------------------------------------------------------------- */\n/* Shaders                                                                    */\n/* -------------------------------------------------------------------------- */\n\nconst PALETTE_GLSL = `\nuniform vec3 u_hot;\nuniform vec3 u_c0;\nuniform vec3 u_c1;\nuniform vec3 u_c2;\nuniform vec3 u_c3;\nvec3 palette(float t) {\n  t = clamp(t, 0.0, 1.0) * 3.0;\n  vec3 c = mix(u_c0, u_c1, clamp(t, 0.0, 1.0));\n  c = mix(c, u_c2, clamp(t - 1.0, 0.0, 1.0));\n  return mix(c, u_c3, clamp(t - 2.0, 0.0, 1.0));\n}`;\n\nconst HOT = \"u_hot\";\n/** White-hot reads on dark surfaces; on light ones it vanishes, so burn deep instead. */\nconst HOT_ON_DARK: [number, number, number] = [1, 0.97, 0.88];\n\n/** The line itself: a ribbon that is only lit behind the reveal front. */\nconst RIBBON_VS = `\nattribute vec2 a_pos;\nattribute float a_s;\nattribute float a_side;\nattribute float a_cx;\nuniform vec2 u_res;\nvarying float v_s;\nvarying float v_side;\nvarying float v_cx;\nvoid main() {\n  v_s = a_s;\n  v_side = a_side;\n  // The fragment's own x — SVG gradients and the hover mask key off pixel x.\n  v_cx = a_pos.x;\n  vec2 clip = (a_pos / u_res) * 2.0 - 1.0;\n  gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);\n}`;\n\n/**\n * One stroke pass into an offscreen texture, drawn on a narrow ribbon with\n * MAX blending so overlapping triangles on tight bends can't double-paint.\n * Used twice: the line itself (radius = strokeWidth / 2, with reveal heat)\n * and the glow source (radius = glow width / 2, no heat).\n */\nconst STROKE_FS = `\nprecision highp float;\nvarying float v_s;\nvarying float v_side;\nvarying float v_cx;\nuniform float u_front;\nuniform float u_total;\nuniform float u_trail;\nuniform float u_heat;\nuniform float u_heatMix;\nuniform float u_radius;\nuniform float u_halfW;\nuniform float u_dpr;\nuniform float u_xStart;\nuniform float u_xSpan;\n${PALETTE_GLSL}\nvoid main() {\n  // Distance to the drawn centreline segment [0, end] — round caps at both\n  // ends and at the moving tip fall out of the same measure.\n  float end = min(u_front, u_total);\n  float across = abs(v_side) * u_halfW;\n  float along = v_s < 0.0 ? -v_s : max(v_s - end, 0.0);\n  float dist = length(vec2(along, across));\n  // Same coverage ramp as a rasterised SVG stroke: 1 device px wide.\n  float cov = clamp((u_radius - dist) * u_dpr + 0.5, 0.0, 1.0);\n\n  // Reveal-only: white-hot trail and metallic sheen, zero once cooled.\n  float heat = exp(-max(end - v_s, 0.0) / u_trail) * u_heat * u_heatMix;\n  float h = clamp(heat, 0.0, 1.0);\n  float sheen = mix(1.0, 0.85 + 0.25 * (-v_side), h);\n  float t = clamp((v_cx - u_xStart) / u_xSpan, 0.0, 1.0);\n  vec3 col = mix(palette(t), ${HOT}, h * 0.75) * sheen;\n  gl_FragColor = vec4(col * cov, cov);\n}`;\n\n/** Reveal-only additive bloom around the freshly drawn stretch (wide ribbon). */\nconst BLOOM_FS = `\nprecision highp float;\nvarying float v_s;\nvarying float v_side;\nuniform float u_front;\nuniform float u_total;\nuniform float u_trail;\nuniform float u_heat;\nuniform float u_halfW;\n${PALETTE_GLSL}\nvoid main() {\n  float end = min(u_front, u_total);\n  float across = abs(v_side) * u_halfW;\n  float along = v_s < 0.0 ? -v_s : max(v_s - end, 0.0);\n  float dist = length(vec2(along, across));\n  float heat = exp(-max(end - v_s, 0.0) / u_trail) * u_heat;\n  float b = exp(-(dist * dist) / (u_halfW * u_halfW * 0.06)) * heat;\n  gl_FragColor = vec4(${HOT} * b, b);\n}`;\n\n/** Full-canvas quad for the blur and composite passes. */\nconst QUAD_VS = `\nattribute vec2 a_pos;\nvarying vec2 v_uv;\nvoid main() {\n  v_uv = a_pos * 0.5 + 0.5;\n  gl_Position = vec4(a_pos, 0.0, 1.0);\n}`;\n\n/** One direction of a separable Gaussian — what feGaussianBlur computes. */\nconst BLUR_FS = `\nprecision highp float;\nvarying vec2 v_uv;\nuniform sampler2D u_tex;\nuniform vec2 u_step;\nuniform float u_sigma;\nvoid main() {\n  float reach = ceil(u_sigma * 3.0);\n  vec4 sum = vec4(0.0);\n  float total = 0.0;\n  for (int i = -48; i <= 48; i++) {\n    float fi = float(i);\n    if (abs(fi) > reach) {\n      continue;\n    }\n    float w = exp(-0.5 * fi * fi / (u_sigma * u_sigma));\n    sum += texture2D(u_tex, v_uv + u_step * fi) * w;\n    total += w;\n  }\n  gl_FragColor = sum / total;\n}`;\n\n/**\n * Stroke over glow, then hover — the same stack the SVG hand-off draws:\n * SeriesHoverDim(opacity) > [glow path, stroke path] + HighlightSegment.\n */\nconst COMPOSITE_FS = `\nprecision highp float;\nvarying vec2 v_uv;\nuniform sampler2D u_core;\nuniform sampler2D u_glow;\nuniform vec2 u_res;\nuniform float u_glowOpacity;\nuniform float u_hover;\nuniform vec2 u_seg;\nuniform float u_segFade;\nuniform float u_dim;\nvoid main() {\n  vec4 core = texture2D(u_core, v_uv);\n  vec4 glow = texture2D(u_glow, v_uv) * u_glowOpacity * (1.0 - u_hover);\n  vec4 line = core + glow * (1.0 - core.a);\n  float x = v_uv.x * u_res.x;\n  float inSegment =\n    clamp((x - u_seg.x) / u_segFade, 0.0, 1.0) *\n    clamp((u_seg.y - x) / u_segFade, 0.0, 1.0);\n  gl_FragColor = line * mix(1.0, mix(u_dim, 1.0, inSegment), u_hover);\n}`;\n\n/**\n * Stateless particles: each knows its spot on the line (`a_target`) and when\n * the front passes it (`a_s`), so position is a pure function of time.\n * Mode 0 flies in and lands there; mode 1 is born there and flies off.\n */\nconst PARTICLE_VS = `\nattribute vec2 a_target;\nattribute float a_s;\nattribute vec2 a_tan;\nattribute vec4 a_rand;\nattribute float a_when;\nuniform vec2 u_res;\nuniform float u_time;\nuniform float u_delay;\nuniform float u_duration;\nuniform float u_spread;\nuniform float u_dpr;\nuniform float u_mode;\nuniform vec2 u_life;\nuniform vec2 u_speed;\nuniform vec2 u_size;\nuniform float u_backward;\nuniform float u_gravity;\nuniform float u_drag;\nuniform float u_twinkle;\nuniform float u_cooling;\nvarying float v_alpha;\nvarying float v_heat;\nvarying float v_s;\n\nvec2 rotate(vec2 v, float a) {\n  float c = cos(a);\n  float s = sin(a);\n  return vec2(c * v.x - s * v.y, s * v.x + c * v.y);\n}\n\nvoid hide() {\n  gl_Position = vec4(2.0, 2.0, 2.0, 1.0);\n  gl_PointSize = 0.0;\n}\n\nvoid main() {\n  float pass = u_delay + a_when * u_duration;\n  float t = u_time - pass;\n  float life = mix(u_life.x, u_life.y, a_rand.y);\n  float twinkle = 1.0 - u_twinkle * (0.5 + 0.5 * sin(u_time * 18.0 + a_rand.w * 60.0));\n  vec2 pos;\n\n  if (u_mode < 0.5) {\n    // Assemble: fly in from up-right, swirl, land, glow briefly.\n    float flight = mix(0.55, 1.5, a_rand.x);\n    if (t < -flight || t > life) { hide(); return; }\n    float k = clamp((t + flight) / flight, 0.0, 1.0);\n    float e = 1.0 - pow(1.0 - k, 3.0);\n    vec2 offset = vec2(\n      mix(0.15, 1.0, a_rand.z) * u_spread,\n      -mix(-0.35, 1.0, a_rand.w) * u_spread * 0.85\n    );\n    offset = rotate(offset, (1.0 - e) * mix(-2.2, 2.2, a_rand.x));\n    pos = a_target + offset * (1.0 - e);\n    pos += vec2(\n      sin(u_time * 3.1 + a_rand.y * 40.0),\n      cos(u_time * 2.6 + a_rand.z * 40.0)\n    ) * 7.0 * (1.0 - e);\n    float landed = step(0.0, t);\n    float afterglow = 1.0 - clamp(t / life, 0.0, 1.0);\n    v_alpha = smoothstep(0.0, 0.3, k) * mix(1.0, afterglow, landed) * twinkle;\n    v_heat = mix(e * e, afterglow, landed);\n  } else {\n    // Emit: born at the head, thrown off, cooling as it trails away.\n    if (t < 0.0 || t > life) { hide(); return; }\n    float angle = a_rand.z * 6.2831853;\n    vec2 dir = normalize(mix(vec2(cos(angle), sin(angle)), -a_tan, u_backward) + 1e-4);\n    float speed = mix(u_speed.x, u_speed.y, a_rand.x * a_rand.x) * (u_spread / 150.0);\n    float travel = u_drag > 0.0 ? (1.0 - exp(-u_drag * t)) / u_drag : t;\n    pos = a_target + dir * speed * travel + vec2(0.0, 0.5 * u_gravity * t * t);\n    float fade = 1.0 - t / life;\n    v_alpha = fade * fade * twinkle;\n    v_heat = exp(-t * u_cooling);\n  }\n\n  v_s = a_s;\n  gl_PointSize = mix(u_size.x, u_size.y, a_rand.w * a_rand.z) * (0.7 + 0.6 * v_heat) * u_dpr;\n  vec2 clip = (pos / u_res) * 2.0 - 1.0;\n  gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);\n}`;\n\nconst PARTICLE_FS = `\nprecision highp float;\nvarying float v_alpha;\nvarying float v_heat;\nvarying float v_s;\n${PALETTE_GLSL}\nvoid main() {\n  vec2 uv = gl_PointCoord - 0.5;\n  float d = length(uv) * 2.0;\n  float a = exp(-d * d * 3.5) * v_alpha;\n  vec3 col = mix(palette(v_s), ${HOT}, v_heat * 0.6);\n  gl_FragColor = vec4(col * a, a);\n}`;\n\n/** The wand tip: a hot core, soft halo and a four-point glint. */\nconst FLARE_VS = `\nattribute vec2 a_pos;\nuniform vec2 u_res;\nuniform float u_size;\nuniform float u_dpr;\nvoid main() {\n  vec2 clip = (a_pos / u_res) * 2.0 - 1.0;\n  gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);\n  gl_PointSize = u_size * u_dpr;\n}`;\n\nconst FLARE_FS = `\nprecision highp float;\nuniform float u_alpha;\nuniform float u_time;\nuniform float u_tint;\n${PALETTE_GLSL}\nvoid main() {\n  vec2 uv = (gl_PointCoord - 0.5) * 2.0;\n  float d = length(uv);\n  float core = exp(-d * d * 40.0);\n  float halo = exp(-d * d * 5.0) * 0.55;\n  float flicker = 0.85 + 0.15 * sin(u_time * 40.0);\n  float rays = (exp(-abs(uv.y) * 28.0) + exp(-abs(uv.x) * 28.0)) * max(0.0, 1.0 - d) * 0.7;\n  float a = clamp((core + halo + rays) * u_alpha * flicker, 0.0, 1.0);\n  vec3 col = mix(palette(u_tint), ${HOT}, clamp(core * 2.0 + 0.4, 0.0, 1.0));\n  gl_FragColor = vec4(col * a, a);\n}`;\n\n/* -------------------------------------------------------------------------- */\n/* WebGL helpers                                                              */\n/* -------------------------------------------------------------------------- */\n\ninterface Program {\n  program: WebGLProgram;\n  uniform: (name: string) => WebGLUniformLocation | null;\n  attrib: (name: string) => number;\n}\n\nfunction compile(\n  gl: WebGLRenderingContext,\n  type: number,\n  source: string\n): WebGLShader | null {\n  const shader = gl.createShader(type);\n  if (!shader) {\n    return null;\n  }\n  gl.shaderSource(shader, source);\n  gl.compileShader(shader);\n  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n    console.warn(\"[ParticleLine]\", gl.getShaderInfoLog(shader));\n    gl.deleteShader(shader);\n    return null;\n  }\n  return shader;\n}\n\nfunction link(\n  gl: WebGLRenderingContext,\n  vsSource: string,\n  fsSource: string\n): Program | null {\n  const vs = compile(gl, gl.VERTEX_SHADER, vsSource);\n  const fs = compile(gl, gl.FRAGMENT_SHADER, fsSource);\n  const program = gl.createProgram();\n  if (!(vs && fs && program)) {\n    return null;\n  }\n  gl.attachShader(program, vs);\n  gl.attachShader(program, fs);\n  gl.linkProgram(program);\n  gl.deleteShader(vs);\n  gl.deleteShader(fs);\n  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n    console.warn(\"[ParticleLine]\", gl.getProgramInfoLog(program));\n    return null;\n  }\n  const uniforms = new Map<string, WebGLUniformLocation | null>();\n  return {\n    program,\n    uniform: (name) => {\n      if (!uniforms.has(name)) {\n        uniforms.set(name, gl.getUniformLocation(program, name));\n      }\n      return uniforms.get(name) ?? null;\n    },\n    attrib: (name) => gl.getAttribLocation(program, name),\n  };\n}\n\n/** Bind an interleaved float layout; returns the enabled locations to disable after drawing. */\nfunction bindAttribs(\n  gl: WebGLRenderingContext,\n  program: Program,\n  layout: [name: string, size: number][]\n): number[] {\n  const stride = layout.reduce((sum, [, size]) => sum + size, 0) * 4;\n  const enabled: number[] = [];\n  let offset = 0;\n  for (const [name, size] of layout) {\n    const loc = program.attrib(name);\n    if (loc >= 0) {\n      gl.enableVertexAttribArray(loc);\n      gl.vertexAttribPointer(loc, size, gl.FLOAT, false, stride, offset);\n      enabled.push(loc);\n    }\n    offset += size * 4;\n  }\n  return enabled;\n}\n\nfunction hexToRgb(hex: string): [number, number, number] {\n  let h = hex.trim().replace(\"#\", \"\");\n  if (h.length === 3) {\n    h = [...h].map((c) => c + c).join(\"\");\n  }\n  const rgb = [0, 2, 4].map((i) => Number.parseInt(h.slice(i, i + 2), 16));\n  if (rgb.some(Number.isNaN)) {\n    return [1, 1, 1];\n  }\n  return [(rgb[0] ?? 255) / 255, (rgb[1] ?? 255) / 255, (rgb[2] ?? 255) / 255];\n}\n\n/** Deterministic LCG so the swarm is identical on every replay. */\nfunction seededRandom(seed: number) {\n  let state = seed;\n  return () => {\n    state = (state * 1_664_525 + 1_013_904_223) % 4_294_967_296;\n    return state / 4_294_967_296;\n  };\n}\n\ntype Bezier = readonly [number, number, number, number];\n\nconst CUBIC_BEZIER_RE = /cubic-bezier\\(([^)]+)\\)/;\n\n/** The universal chart reveal — `DEFAULT_CHART_ENTER_TRANSITION`. */\nconst DEFAULT_EASE: Bezier = [0.85, 0, 0.15, 1];\n\nfunction bezierAxis(p1: number, p2: number, t: number): number {\n  const u = 1 - t;\n  return 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t;\n}\n\n/** Solve `axis(t) = value` by bisection (both axes are monotonic for valid easings). */\nfunction solveBezier(p1: number, p2: number, value: number): number {\n  let lo = 0;\n  let hi = 1;\n  for (let i = 0; i < 32; i++) {\n    const mid = (lo + hi) / 2;\n    if (bezierAxis(p1, p2, mid) < value) {\n      lo = mid;\n    } else {\n      hi = mid;\n    }\n  }\n  return (lo + hi) / 2;\n}\n\n/** Eased progress (fraction of line drawn) at a time fraction. */\nfunction easeAt([x1, y1, x2, y2]: Bezier, time: number): number {\n  return bezierAxis(y1, y2, solveBezier(x1, x2, time));\n}\n\n/** Time fraction at which the eased front reaches `progress`. */\nfunction timeAtProgress([x1, y1, x2, y2]: Bezier, progress: number): number {\n  return bezierAxis(x1, x2, solveBezier(y1, y2, progress));\n}\n\nfunction isBezier(value: unknown): value is Bezier {\n  return (\n    Array.isArray(value) &&\n    value.length === 4 &&\n    value.every((n) => typeof n === \"number\")\n  );\n}\n\n/** Same easing the chart's own clip reveal uses (springs fall back to the default, as there). */\nfunction resolveChartEase(\n  enterEase: unknown,\n  animationEasing: string | undefined\n): Bezier {\n  if (isBezier(enterEase)) {\n    return enterEase;\n  }\n  const match = animationEasing?.match(CUBIC_BEZIER_RE);\n  const parsed = match?.[1]?.split(\",\").map(Number);\n  if (isBezier(parsed) && parsed.every(Number.isFinite)) {\n    return parsed;\n  }\n  return DEFAULT_EASE;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Geometry                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface LineSamples {\n  /** Interleaved x, y pairs in canvas px (1px steps along the path). */\n  points: Float32Array;\n  /** Arc length at each sample. */\n  lengths: Float32Array;\n  total: number;\n  /** Plot left / right edges in canvas px — the reveal sweeps between them. */\n  xStart: number;\n  xEnd: number;\n}\n\nfunction sampleLine(\n  path: SVGPathElement,\n  offsetX: number,\n  offsetY: number,\n  plotWidth: number\n): LineSamples | null {\n  const total = path.getTotalLength();\n  if (!(total > 1)) {\n    return null;\n  }\n  const count = Math.ceil(total) + 1;\n  const points = new Float32Array(count * 2);\n  const lengths = new Float32Array(count);\n  for (let i = 0; i < count; i++) {\n    const at = Math.min(i, total);\n    const p = path.getPointAtLength(at);\n    points[i * 2] = p.x + offsetX;\n    points[i * 2 + 1] = p.y + offsetY;\n    lengths[i] = at;\n  }\n  return {\n    points,\n    lengths,\n    total,\n    xStart: offsetX,\n    xEnd: offsetX + Math.max(plotWidth, 1),\n  };\n}\n\nfunction pointAt(samples: LineSamples, length: number): [number, number] {\n  const last = samples.lengths.length - 1;\n  const i = Math.min(last, Math.max(0, Math.round(length)));\n  return [samples.points[i * 2] ?? 0, samples.points[i * 2 + 1] ?? 0];\n}\n\n/** 0–1 position of sample `i` across the plot width. */\nfunction xFraction(samples: LineSamples, i: number): number {\n  const x = samples.points[i * 2] ?? samples.xStart;\n  const span = samples.xEnd - samples.xStart;\n  return Math.min(Math.max((x - samples.xStart) / span, 0), 1);\n}\n\n/**\n * Arc length where the line crosses `fraction` of the plot width, so every\n * series reaches each date at the same moment — like the chart's clip reveal.\n */\nfunction lengthAtXFraction(samples: LineSamples, fraction: number): number {\n  const target = samples.xStart + fraction * (samples.xEnd - samples.xStart);\n  let lo = 0;\n  let hi = samples.lengths.length - 1;\n  while (lo < hi) {\n    const mid = Math.floor((lo + hi) / 2);\n    if ((samples.points[mid * 2] ?? 0) < target) {\n      lo = mid + 1;\n    } else {\n      hi = mid;\n    }\n  }\n  return samples.lengths[lo] ?? samples.total;\n}\n\nfunction tangentAt(samples: LineSamples, i: number): [number, number] {\n  const n = samples.lengths.length;\n  const a = Math.max(0, i - 2);\n  const b = Math.min(n - 1, i + 2);\n  const dx = (samples.points[b * 2] ?? 0) - (samples.points[a * 2] ?? 0);\n  const dy =\n    (samples.points[b * 2 + 1] ?? 0) - (samples.points[a * 2 + 1] ?? 0);\n  const len = Math.hypot(dx, dy) || 1;\n  return [dx / len, dy / len];\n}\n\n/**\n * Triangle strip: two vertices per sample — [x, y, s, side, centreline x] — plus one\n * extension at each end (s < 0, s > total) for the fragment shader's round caps.\n */\nfunction buildRibbon(samples: LineSamples, halfWidth: number): Float32Array {\n  const n = samples.lengths.length;\n  const out = new Float32Array((n + 2) * 2 * RIBBON_STRIDE);\n  const write = (\n    slot: number,\n    x: number,\n    y: number,\n    [tx, ty]: [number, number],\n    s: number\n  ) => {\n    for (const [j, side] of [\n      [0, -1],\n      [1, 1],\n    ] as const) {\n      const o = (slot * 2 + j) * RIBBON_STRIDE;\n      out[o] = x - ty * side * halfWidth;\n      out[o + 1] = y + tx * side * halfWidth;\n      out[o + 2] = s;\n      out[o + 3] = side;\n      out[o + 4] = x;\n    }\n  };\n  const first = tangentAt(samples, 0);\n  const last = tangentAt(samples, n - 1);\n  const x0 = samples.points[0] ?? 0;\n  const y0 = samples.points[1] ?? 0;\n  write(\n    0,\n    x0 - first[0] * halfWidth,\n    y0 - first[1] * halfWidth,\n    first,\n    -halfWidth\n  );\n  for (let i = 0; i < n; i++) {\n    write(\n      i + 1,\n      samples.points[i * 2] ?? 0,\n      samples.points[i * 2 + 1] ?? 0,\n      tangentAt(samples, i),\n      samples.lengths[i] ?? 0\n    );\n  }\n  const xn = samples.points[(n - 1) * 2] ?? 0;\n  const yn = samples.points[(n - 1) * 2 + 1] ?? 0;\n  write(\n    n + 1,\n    xn + last[0] * halfWidth,\n    yn + last[1] * halfWidth,\n    last,\n    samples.total + halfWidth\n  );\n  return out;\n}\n\nfunction buildParticles(\n  samples: LineSamples,\n  density: number,\n  strokeWidth: number,\n  timeAt: (progress: number) => number\n): Float32Array {\n  const count = Math.min(\n    MAX_PARTICLES,\n    Math.max(1, Math.round(samples.total * density))\n  );\n  const random = seededRandom(73_313);\n  const out = new Float32Array(count * PARTICLE_STRIDE);\n  const last = samples.lengths.length - 1;\n  for (let p = 0; p < count; p++) {\n    const s = random();\n    const i = Math.min(last, Math.round(s * last));\n    const [tx, ty] = tangentAt(samples, i);\n    const across = (random() - 0.5) * strokeWidth * 1.6;\n    const o = p * PARTICLE_STRIDE;\n    out[o] = (samples.points[i * 2] ?? 0) - ty * across;\n    out[o + 1] = (samples.points[i * 2 + 1] ?? 0) + tx * across;\n    // Colour position — x across the plot, matching the line's gradient.\n    out[o + 2] = xFraction(samples, i);\n    out[o + 3] = tx;\n    out[o + 4] = ty;\n    out[o + 5] = random();\n    out[o + 6] = random();\n    out[o + 7] = random();\n    out[o + 8] = random();\n    // When the eased front reaches this particle's x, as a fraction of the reveal.\n    out[o + 9] = timeAt(xFraction(samples, i));\n  }\n  return out;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Renderer                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface RenderSettings {\n  delay: number;\n  duration: number;\n  spread: number;\n  trail: number;\n  strokeWidth: number;\n  halfWidth: number;\n  /** Half-width of the narrow stroke / glow-source ribbon. */\n  narrowHalfWidth: number;\n  effect: EffectPreset;\n  ease: Bezier;\n}\n\ninterface HoverFrame {\n  /** 0 = not hovering, 1 = fully hovered (springs in and out). */\n  amount: number;\n  /** Segment left / right in canvas px. */\n  start: number;\n  end: number;\n  /** Soft-end width in px. */\n  fade: number;\n  dim: number;\n}\n\ninterface Frame {\n  hover: HoverFrame;\n  /** Plot left edge and width in canvas px (gradient + hover space). */\n  xStart: number;\n  xSpan: number;\n  time: number;\n  front: number;\n  total: number;\n  heat: number;\n  head: [number, number];\n  flareAlpha: number;\n}\n\ninterface Renderer {\n  setSize: (width: number, height: number, dpr: number) => void;\n  setGeometry: (\n    narrowRibbon: Float32Array,\n    wideRibbon: Float32Array,\n    particles: Float32Array\n  ) => void;\n  setColors: (colors: readonly string[], darkSurface: boolean) => void;\n  draw: (frame: Frame) => void;\n  dispose: () => void;\n}\n\ninterface Target {\n  texture: WebGLTexture;\n  framebuffer: WebGLFramebuffer;\n}\n\nfunction createTarget(gl: WebGLRenderingContext): Target | null {\n  const texture = gl.createTexture();\n  const framebuffer = gl.createFramebuffer();\n  if (!(texture && framebuffer)) {\n    return null;\n  }\n  gl.bindTexture(gl.TEXTURE_2D, texture);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n  gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n  gl.framebufferTexture2D(\n    gl.FRAMEBUFFER,\n    gl.COLOR_ATTACHMENT0,\n    gl.TEXTURE_2D,\n    texture,\n    0\n  );\n  gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n  return { texture, framebuffer };\n}\n\nconst RIBBON_LAYOUT: [string, number][] = [\n  [\"a_pos\", 2],\n  [\"a_s\", 1],\n  [\"a_side\", 1],\n  [\"a_cx\", 1],\n];\n\nfunction createRenderer(\n  canvas: HTMLCanvasElement,\n  settings: { current: RenderSettings }\n): Renderer | null {\n  const gl = canvas.getContext(\"webgl\", {\n    alpha: true,\n    antialias: false,\n    premultipliedAlpha: true,\n  });\n  if (!gl) {\n    return null;\n  }\n  // MAX blending makes overlapping ribbon triangles (inside of tight bends)\n  // idempotent. Universally supported; fall back to \"over\" just in case.\n  const minmax = gl.getExtension(\"EXT_blend_minmax\");\n  const stroke = link(gl, RIBBON_VS, STROKE_FS);\n  const bloom = link(gl, RIBBON_VS, BLOOM_FS);\n  const blur = link(gl, QUAD_VS, BLUR_FS);\n  const composite = link(gl, QUAD_VS, COMPOSITE_FS);\n  const particles = link(gl, PARTICLE_VS, PARTICLE_FS);\n  const flare = link(gl, FLARE_VS, FLARE_FS);\n  const narrowBuffer = gl.createBuffer();\n  const wideBuffer = gl.createBuffer();\n  const quadBuffer = gl.createBuffer();\n  const particleBuffer = gl.createBuffer();\n  const flareBuffer = gl.createBuffer();\n  const coreTarget = createTarget(gl);\n  const glowTarget = createTarget(gl);\n  const scratchTarget = createTarget(gl);\n  if (\n    !(\n      stroke &&\n      bloom &&\n      blur &&\n      composite &&\n      particles &&\n      flare &&\n      narrowBuffer &&\n      wideBuffer &&\n      quadBuffer &&\n      particleBuffer &&\n      flareBuffer &&\n      coreTarget &&\n      glowTarget &&\n      scratchTarget\n    )\n  ) {\n    return null;\n  }\n  const targets = [coreTarget, glowTarget, scratchTarget];\n\n  gl.bindBuffer(gl.ARRAY_BUFFER, quadBuffer);\n  gl.bufferData(\n    gl.ARRAY_BUFFER,\n    new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),\n    gl.STATIC_DRAW\n  );\n\n  const headData = new Float32Array(2);\n  let narrowCount = 0;\n  let wideCount = 0;\n  let particleCount = 0;\n  let cssWidth = 1;\n  let cssHeight = 1;\n  let dpr = 1;\n  let palette: [number, number, number][] = [];\n  let hot = HOT_ON_DARK;\n\n  const usePalette = (program: Program) => {\n    gl.uniform3f(program.uniform(\"u_hot\"), hot[0], hot[1], hot[2]);\n    palette.forEach(([r, g, b], i) => {\n      gl.uniform3f(program.uniform(`u_c${i}`), r, g, b);\n    });\n  };\n  const disable = (locations: number[]) => {\n    for (const loc of locations) {\n      gl.disableVertexAttribArray(loc);\n    }\n  };\n  const bindTarget = (target: Target | null) => {\n    gl.bindFramebuffer(gl.FRAMEBUFFER, target?.framebuffer ?? null);\n    gl.viewport(0, 0, canvas.width, canvas.height);\n    gl.clearColor(0, 0, 0, 0);\n    gl.clear(gl.COLOR_BUFFER_BIT);\n  };\n  const drawQuad = (program: Program) => {\n    gl.bindBuffer(gl.ARRAY_BUFFER, quadBuffer);\n    const enabled = bindAttribs(gl, program, [[\"a_pos\", 2]]);\n    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n    disable(enabled);\n  };\n  const bindTexture = (\n    program: Program,\n    name: string,\n    unit: number,\n    target: Target\n  ) => {\n    gl.activeTexture(gl.TEXTURE0 + unit);\n    gl.bindTexture(gl.TEXTURE_2D, target.texture);\n    gl.uniform1i(program.uniform(name), unit);\n  };\n\n  /** Stroke pass into `target` (MAX blend). */\n  const drawStroke = (\n    target: Target,\n    frame: Frame,\n    s: RenderSettings,\n    radius: number,\n    heatMix: number\n  ) => {\n    bindTarget(target);\n    gl.enable(gl.BLEND);\n    if (minmax) {\n      gl.blendEquation(minmax.MAX_EXT);\n      gl.blendFunc(gl.ONE, gl.ONE);\n    } else {\n      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n    }\n    gl.useProgram(stroke.program);\n    gl.bindBuffer(gl.ARRAY_BUFFER, narrowBuffer);\n    const enabled = bindAttribs(gl, stroke, RIBBON_LAYOUT);\n    const u = stroke.uniform;\n    gl.uniform2f(u(\"u_res\"), cssWidth, cssHeight);\n    gl.uniform1f(u(\"u_front\"), frame.front);\n    gl.uniform1f(u(\"u_total\"), frame.total);\n    gl.uniform1f(u(\"u_trail\"), s.trail);\n    gl.uniform1f(u(\"u_heat\"), frame.heat * s.effect.heatGain);\n    gl.uniform1f(u(\"u_heatMix\"), heatMix);\n    gl.uniform1f(u(\"u_radius\"), radius);\n    gl.uniform1f(u(\"u_halfW\"), s.narrowHalfWidth);\n    gl.uniform1f(u(\"u_dpr\"), dpr);\n    gl.uniform1f(u(\"u_xStart\"), frame.xStart);\n    gl.uniform1f(u(\"u_xSpan\"), Math.max(frame.xSpan, 1));\n    usePalette(stroke);\n    gl.drawArrays(gl.TRIANGLE_STRIP, 0, narrowCount);\n    disable(enabled);\n    gl.blendEquation(gl.FUNC_ADD);\n  };\n\n  const drawBlur = (from: Target, to: Target, dx: number, dy: number) => {\n    bindTarget(to);\n    gl.disable(gl.BLEND);\n    gl.useProgram(blur.program);\n    bindTexture(blur, \"u_tex\", 0, from);\n    gl.uniform2f(blur.uniform(\"u_step\"), dx / canvas.width, dy / canvas.height);\n    gl.uniform1f(blur.uniform(\"u_sigma\"), Math.min(GLOW_BLUR * dpr, 16));\n    drawQuad(blur);\n  };\n\n  const drawComposite = (frame: Frame) => {\n    bindTarget(null);\n    gl.disable(gl.BLEND);\n    gl.useProgram(composite.program);\n    bindTexture(composite, \"u_core\", 0, coreTarget);\n    bindTexture(composite, \"u_glow\", 1, glowTarget);\n    const u = composite.uniform;\n    gl.uniform2f(u(\"u_res\"), cssWidth, cssHeight);\n    gl.uniform1f(u(\"u_glowOpacity\"), GLOW_OPACITY);\n    gl.uniform1f(u(\"u_hover\"), frame.hover.amount);\n    gl.uniform2f(u(\"u_seg\"), frame.hover.start, frame.hover.end);\n    gl.uniform1f(u(\"u_segFade\"), frame.hover.fade);\n    gl.uniform1f(u(\"u_dim\"), frame.hover.dim);\n    drawQuad(composite);\n  };\n\n  const drawBloom = (frame: Frame, s: RenderSettings) => {\n    gl.enable(gl.BLEND);\n    gl.blendFunc(gl.ONE, gl.ONE);\n    gl.useProgram(bloom.program);\n    gl.bindBuffer(gl.ARRAY_BUFFER, wideBuffer);\n    const enabled = bindAttribs(gl, bloom, RIBBON_LAYOUT);\n    const u = bloom.uniform;\n    gl.uniform2f(u(\"u_res\"), cssWidth, cssHeight);\n    gl.uniform1f(u(\"u_front\"), frame.front);\n    gl.uniform1f(u(\"u_total\"), frame.total);\n    gl.uniform1f(u(\"u_trail\"), s.trail);\n    gl.uniform1f(u(\"u_heat\"), frame.heat * s.effect.heatGain);\n    gl.uniform1f(u(\"u_halfW\"), s.halfWidth);\n    usePalette(bloom);\n    gl.drawArrays(gl.TRIANGLE_STRIP, 0, wideCount);\n    disable(enabled);\n  };\n\n  const drawParticles = (frame: Frame, s: RenderSettings) => {\n    const fx = s.effect;\n    gl.enable(gl.BLEND);\n    gl.blendFunc(gl.ONE, gl.ONE);\n    gl.useProgram(particles.program);\n    gl.bindBuffer(gl.ARRAY_BUFFER, particleBuffer);\n    const enabled = bindAttribs(gl, particles, [\n      [\"a_target\", 2],\n      [\"a_s\", 1],\n      [\"a_tan\", 2],\n      [\"a_rand\", 4],\n      [\"a_when\", 1],\n    ]);\n    const u = particles.uniform;\n    gl.uniform2f(u(\"u_res\"), cssWidth, cssHeight);\n    gl.uniform1f(u(\"u_time\"), frame.time);\n    gl.uniform1f(u(\"u_delay\"), s.delay);\n    gl.uniform1f(u(\"u_duration\"), s.duration);\n    gl.uniform1f(u(\"u_spread\"), s.spread);\n    gl.uniform1f(u(\"u_dpr\"), dpr);\n    gl.uniform1f(u(\"u_mode\"), fx.mode);\n    gl.uniform2f(u(\"u_life\"), fx.life[0], fx.life[1]);\n    gl.uniform2f(u(\"u_speed\"), fx.speed[0], fx.speed[1]);\n    gl.uniform2f(u(\"u_size\"), fx.size[0], fx.size[1]);\n    gl.uniform1f(u(\"u_backward\"), fx.backward);\n    gl.uniform1f(u(\"u_gravity\"), fx.gravity);\n    gl.uniform1f(u(\"u_drag\"), fx.drag);\n    gl.uniform1f(u(\"u_twinkle\"), fx.twinkle);\n    gl.uniform1f(u(\"u_cooling\"), fx.cooling);\n    usePalette(particles);\n    gl.drawArrays(gl.POINTS, 0, particleCount);\n    disable(enabled);\n  };\n\n  const drawFlare = (frame: Frame, s: RenderSettings) => {\n    headData[0] = frame.head[0];\n    headData[1] = frame.head[1];\n    gl.enable(gl.BLEND);\n    gl.blendFunc(gl.ONE, gl.ONE);\n    gl.useProgram(flare.program);\n    gl.bindBuffer(gl.ARRAY_BUFFER, flareBuffer);\n    gl.bufferData(gl.ARRAY_BUFFER, headData, gl.DYNAMIC_DRAW);\n    const enabled = bindAttribs(gl, flare, [[\"a_pos\", 2]]);\n    gl.uniform2f(flare.uniform(\"u_res\"), cssWidth, cssHeight);\n    gl.uniform1f(flare.uniform(\"u_size\"), s.effect.flare);\n    gl.uniform1f(flare.uniform(\"u_dpr\"), dpr);\n    gl.uniform1f(flare.uniform(\"u_alpha\"), frame.flareAlpha);\n    gl.uniform1f(flare.uniform(\"u_time\"), frame.time);\n    gl.uniform1f(\n      flare.uniform(\"u_tint\"),\n      frame.total > 0 ? frame.front / frame.total : 0\n    );\n    usePalette(flare);\n    gl.drawArrays(gl.POINTS, 0, 1);\n    disable(enabled);\n  };\n\n  return {\n    setSize: (width, height, ratio) => {\n      cssWidth = width;\n      cssHeight = height;\n      dpr = ratio;\n      canvas.width = Math.max(1, Math.round(width * ratio));\n      canvas.height = Math.max(1, Math.round(height * ratio));\n      for (const target of targets) {\n        gl.bindTexture(gl.TEXTURE_2D, target.texture);\n        gl.texImage2D(\n          gl.TEXTURE_2D,\n          0,\n          gl.RGBA,\n          canvas.width,\n          canvas.height,\n          0,\n          gl.RGBA,\n          gl.UNSIGNED_BYTE,\n          null\n        );\n      }\n    },\n    setGeometry: (narrowData, wideData, particleData) => {\n      gl.bindBuffer(gl.ARRAY_BUFFER, narrowBuffer);\n      gl.bufferData(gl.ARRAY_BUFFER, narrowData, gl.STATIC_DRAW);\n      narrowCount = narrowData.length / RIBBON_STRIDE;\n      gl.bindBuffer(gl.ARRAY_BUFFER, wideBuffer);\n      gl.bufferData(gl.ARRAY_BUFFER, wideData, gl.STATIC_DRAW);\n      wideCount = wideData.length / RIBBON_STRIDE;\n      gl.bindBuffer(gl.ARRAY_BUFFER, particleBuffer);\n      gl.bufferData(gl.ARRAY_BUFFER, particleData, gl.STATIC_DRAW);\n      particleCount = particleData.length / PARTICLE_STRIDE;\n    },\n    setColors: (colors, darkSurface) => {\n      palette = [0, 1, 2, 3].map((i) =>\n        hexToRgb(colors[i % Math.max(colors.length, 1)] ?? \"#ffffff\")\n      );\n      hot = darkSurface ? HOT_ON_DARK : (palette[0] ?? HOT_ON_DARK);\n    },\n    draw: (frame) => {\n      const s = settings.current;\n      // Line: stroke + glow source offscreen, blur the glow, composite.\n      drawStroke(coreTarget, frame, s, s.strokeWidth / 2, 1);\n      drawStroke(\n        glowTarget,\n        frame,\n        s,\n        (s.strokeWidth * GLOW_WIDTH_SCALE) / 2,\n        0\n      );\n      drawBlur(glowTarget, scratchTarget, 1, 0);\n      drawBlur(scratchTarget, glowTarget, 0, 1);\n      drawComposite(frame);\n      // Reveal extras on top, additive.\n      if (frame.heat > 0) {\n        drawBloom(frame, s);\n      }\n      if (frame.time < s.delay + s.duration + s.effect.life[1]) {\n        drawParticles(frame, s);\n      }\n      if (s.effect.flare > 0 && frame.flareAlpha > 0) {\n        drawFlare(frame, s);\n      }\n    },\n    dispose: () => {\n      for (const buffer of [\n        narrowBuffer,\n        wideBuffer,\n        quadBuffer,\n        particleBuffer,\n        flareBuffer,\n      ]) {\n        gl.deleteBuffer(buffer);\n      }\n      for (const target of targets) {\n        gl.deleteFramebuffer(target.framebuffer);\n        gl.deleteTexture(target.texture);\n      }\n      for (const program of [\n        stroke,\n        bloom,\n        blur,\n        composite,\n        particles,\n        flare,\n      ]) {\n        gl.deleteProgram(program.program);\n      }\n    },\n  };\n}\n\n/** Light text colour on the chart ⇒ dark theme. */\nfunction isDarkSurface(element: HTMLElement): boolean {\n  const match = getComputedStyle(element).color.match(/[\\d.]+/g);\n  if (!match || match.length < 3) {\n    return true;\n  }\n  const [r = 0, g = 0, b = 0] = match.map(Number);\n  return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255 > 0.5;\n}\n\nfunction prefersReducedMotion(): boolean {\n  return (\n    typeof window !== \"undefined\" &&\n    window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches === true\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* SVG hand-off                                                               */\n/* -------------------------------------------------------------------------- */\n\n/** Filter region bleed around the plot so the blurred glow is never cropped. */\nconst GLOW_FILTER_BLEED = 40;\n\n/**\n * Resting glow. Its own hover subscriber so the parent stays on the stable\n * context; fades out while hovering, like the WebGL frame.\n */\nfunction ParticleLineGlow({\n  d,\n  filter,\n  stroke,\n  strokeWidth,\n}: {\n  d: string;\n  filter: string;\n  stroke: string;\n  strokeWidth: number;\n}) {\n  const hovering = useChartHoverSelector(selectIsChartHovering);\n  return (\n    <m.path\n      animate={{ opacity: hovering ? 0 : 1 }}\n      d={d}\n      fill=\"none\"\n      filter={filter}\n      initial={false}\n      stroke={stroke}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      strokeOpacity={GLOW_OPACITY}\n      strokeWidth={strokeWidth}\n      transition={{ duration: 0.4, ease: \"easeInOut\" }}\n    />\n  );\n}\n\n/**\n * Release a canvas's WebGL context once it is really gone. Deferred a tick so\n * Strict Mode's immediate effect re-run on the same canvas can cancel it — a\n * lost context can't compile shaders again.\n */\nconst pendingContextRelease = new WeakMap<HTMLCanvasElement, number>();\n\nfunction scheduleContextRelease(canvas: HTMLCanvasElement) {\n  const timer = window.setTimeout(() => {\n    pendingContextRelease.delete(canvas);\n    canvas\n      .getContext(\"webgl\")\n      ?.getExtension(\"WEBGL_lose_context\")\n      ?.loseContext();\n  }, 0);\n  pendingContextRelease.set(canvas, timer);\n}\n\nfunction cancelContextRelease(canvas: HTMLCanvasElement) {\n  const timer = pendingContextRelease.get(canvas);\n  if (timer !== undefined) {\n    window.clearTimeout(timer);\n    pendingContextRelease.delete(canvas);\n  }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Component                                                                  */\n/* -------------------------------------------------------------------------- */\n\n/**\n * A `LineChart` series drawn in WebGL and revealed with particles — either a\n * swarm condensing onto the line (`assemble`) or the line growing from a\n * glowing wand tip that sheds sparks (`comet`, `stardust`).\n * Registers as a normal series, so `ChartTooltip` and the y-domain treat it\n * like a `<Line>`.\n */\nexport function ParticleLine({\n  dataKey,\n  yAxisId,\n  curve = curveMonotoneX,\n  strokeWidth = 2.5,\n  colors = PARTICLE_LINE_GOLD,\n  effect = \"assemble\",\n  duration: durationProp,\n  delay = 0,\n  easing,\n  density = 7,\n  spread = 150,\n  trail = 90,\n  highlight,\n}: ParticleLineProps) {\n  const {\n    renderData,\n    xScale,\n    xAccessor,\n    width,\n    height,\n    innerWidth,\n    innerHeight,\n    lines,\n    margin,\n    containerRef,\n    revealEpoch,\n    animationDuration,\n    animationEasing,\n    enterTransition,\n  } = useChartStable();\n  const yScale = useYScale(yAxisId);\n  const container = useChartPortalContainer(containerRef);\n  const pathRef = useRef<SVGPathElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const rendererRef = useRef<Renderer | null>(null);\n  const samplesRef = useRef<LineSamples | null>(null);\n  const startRef = useRef<number | null>(null);\n  const [canvasReady, setCanvasReady] = useState(false);\n  /** WebGL while revealing; a plain SVG line once it has cooled. */\n  const [phase, setPhase] = useState<\"webgl\" | \"svg\">(\"webgl\");\n  const uniqueId = useId().replace(/:/g, \"\");\n  const gradientId = `particle-line-${uniqueId}`;\n  const glowFilterId = `${gradientId}-glow`;\n  const svgPathRef = useRef<SVGPathElement>(null);\n\n  const preset = EFFECTS[effect];\n  const duration = durationProp ?? animationDuration;\n  const chartEase = resolveChartEase(enterTransition?.ease, animationEasing);\n  const ease = easing ?? chartEase;\n  const easeKey = ease.join(\",\");\n  const halfWidth = (strokeWidth * GLOW_WIDTH_SCALE) / 2 + RIBBON_PAD;\n  // Just past the glow stroke's edge (+ AA ramp) — narrow enough that tight\n  // bends rarely fold it; MAX blending covers the folds that remain.\n  const narrowHalfWidth = (strokeWidth * GLOW_WIDTH_SCALE) / 2 + 1.5;\n  const settings: RenderSettings = {\n    delay: delay / 1000,\n    duration: duration / 1000,\n    spread,\n    trail,\n    strokeWidth,\n    halfWidth,\n    narrowHalfWidth,\n    effect: preset,\n    ease,\n  };\n  const settingsRef = useRef(settings);\n  settingsRef.current = settings;\n  const stopAt =\n    settings.delay + settings.duration + preset.life[1] + HEAT_FADE_S;\n\n  const highlightEnabled = highlight !== false;\n  const span = (highlight || undefined)?.span ?? 3;\n  const fadeLength = Math.min(\n    50,\n    Math.max(0, (highlight || undefined)?.fadeLength ?? 40)\n  );\n  const dimOpacity = (highlight || undefined)?.dimOpacity ?? 0.25;\n  const {\n    xSpring: segmentX,\n    widthSpring: segmentWidth,\n    isActive: hoverActive,\n  } = useHighlightSegment({ enabled: highlightEnabled, span });\n  // Same tween as SeriesHoverDim / HighlightSegment, so hover looks identical\n  // before and after the SVG hand-off.\n  const hoverAmount = useMotionValue(0);\n  useEffect(() => {\n    const controls = animate(hoverAmount, hoverActive ? 1 : 0, {\n      duration: 0.4,\n      ease: \"easeInOut\",\n    });\n    return () => controls.stop();\n  }, [hoverActive, hoverAmount]);\n  const hoverRef = useRef({ fadeLength, dimOpacity, marginLeft: margin.left });\n  hoverRef.current = { fadeLength, dimOpacity, marginLeft: margin.left };\n  const animatingRef = useRef(false);\n\n  const getX = useCallback(\n    (d: Record<string, unknown>) => xScale(xAccessor(d)) ?? 0,\n    [xAccessor, xScale]\n  );\n  const getY = useCallback(\n    (d: Record<string, unknown>) => yScale(Number(d[dataKey])) ?? 0,\n    [dataKey, yScale]\n  );\n  const defined = useCallback(\n    (d: Record<string, unknown>) => typeof d[dataKey] === \"number\",\n    [dataKey]\n  );\n  const lineD = useMemo(\n    () => linePathD(renderData, { curve, defined, x: getX, y: getY }),\n    [curve, defined, getX, getY, renderData]\n  );\n\n  const readHover = useCallback((): HoverFrame => {\n    const {\n      fadeLength: fadePct,\n      dimOpacity: dim,\n      marginLeft,\n    } = hoverRef.current;\n    const start = segmentX.get() + marginLeft;\n    const width = segmentWidth.get();\n    return {\n      amount: hoverAmount.get(),\n      start,\n      end: start + width,\n      fade: Math.max((width * fadePct) / 100, 0.5),\n      dim,\n    };\n  }, [hoverAmount, segmentWidth, segmentX]);\n\n  /** Draw one frame at `time` seconds since the reveal started. */\n  const drawAt = useCallback(\n    (time: number) => {\n      const renderer = rendererRef.current;\n      const samples = samplesRef.current;\n      if (!(renderer && samples)) {\n        return;\n      }\n      const s = settingsRef.current;\n      const linear = Math.min(Math.max((time - s.delay) / s.duration, 0), 1);\n      const progress = easeAt(s.ease, linear);\n      const front =\n        progress >= 1 ? samples.total : lengthAtXFraction(samples, progress);\n      const pastEnd = time - (s.delay + s.duration);\n      const cooldown = pastEnd > 0 ? Math.max(0, 1 - pastEnd / HEAT_FADE_S) : 1;\n      let flareAlpha = 0;\n      if (time >= s.delay) {\n        // Ignite quickly, then burn out after the end.\n        flareAlpha = Math.min(1, (time - s.delay) / 0.15) * cooldown ** 2;\n      }\n      renderer.draw({\n        time,\n        total: samples.total,\n        // Nothing (not even the start cap) before the reveal begins.\n        front: progress > 0 ? front : -1e4,\n        heat: cooldown,\n        head: pointAt(samples, front),\n        flareAlpha,\n        hover: readHover(),\n        xStart: samples.xStart,\n        xSpan: samples.xEnd - samples.xStart,\n      });\n    },\n    [readHover]\n  );\n\n  const currentTime = useCallback(() => {\n    // Not started yet: hold the first frame (empty stage), never the end.\n    if (startRef.current === null) {\n      return 0;\n    }\n    return (performance.now() - startRef.current) / 1000;\n  }, []);\n\n  // GL context lives as long as the canvas.\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    if (!(canvas && container)) {\n      return;\n    }\n    cancelContextRelease(canvas);\n    const renderer = createRenderer(canvas, settingsRef);\n    rendererRef.current = renderer;\n    setCanvasReady(renderer !== null);\n    return () => {\n      renderer?.dispose();\n      rendererRef.current = null;\n      setCanvasReady(false);\n      scheduleContextRelease(canvas);\n    };\n  }, [container, phase]);\n\n  const colorKey = colors.join(\",\");\n\n  // Size, colours + geometry: re-sample whenever the line or chart changes.\n  useLayoutEffect(() => {\n    const renderer = rendererRef.current;\n    const path = pathRef.current;\n    if (!(canvasReady && renderer && path && lineD)) {\n      return;\n    }\n    renderer.setSize(\n      width,\n      height,\n      Math.min(window.devicePixelRatio || 1, MAX_DPR)\n    );\n    renderer.setColors(\n      colorKey.split(\",\"),\n      isDarkSurface(container ?? path.ownerDocument.body)\n    );\n    const samples = sampleLine(path, margin.left, margin.top, innerWidth);\n    samplesRef.current = samples;\n    if (!samples) {\n      return;\n    }\n    renderer.setGeometry(\n      buildRibbon(samples, narrowHalfWidth),\n      buildRibbon(samples, halfWidth),\n      buildParticles(samples, density, strokeWidth, (progress) =>\n        timeAtProgress(settingsRef.current.ease, progress)\n      )\n    );\n    drawAt(Math.min(currentTime(), stopAt));\n  }, [\n    canvasReady,\n    colorKey,\n    container,\n    currentTime,\n    density,\n    easeKey,\n    drawAt,\n    halfWidth,\n    narrowHalfWidth,\n    height,\n    innerWidth,\n    lineD,\n    margin.left,\n    margin.top,\n    stopAt,\n    strokeWidth,\n    width,\n  ]);\n\n  // Play the reveal on mount, on every replay (`revealEpoch`) and when the effect changes.\n  useEffect(() => {\n    if (!canvasReady) {\n      return;\n    }\n    if (prefersReducedMotion()) {\n      startRef.current = Number.NEGATIVE_INFINITY;\n      setPhase(\"svg\");\n      return;\n    }\n    startRef.current = performance.now();\n    animatingRef.current = true;\n    let frame = 0;\n    const tick = () => {\n      const time = currentTime();\n      drawAt(Math.min(time, stopAt));\n      if (time < stopAt) {\n        frame = requestAnimationFrame(tick);\n      } else {\n        animatingRef.current = false;\n        // Cooled: the last frame is the resting look — swap to SVG and let\n        // the canvas (and its WebGL context) go.\n        setPhase(\"svg\");\n      }\n    };\n    frame = requestAnimationFrame(tick);\n    return () => {\n      cancelAnimationFrame(frame);\n      animatingRef.current = false;\n    };\n  }, [canvasReady, currentTime, drawAt, effect, revealEpoch, stopAt]);\n\n  // Replay: bring the canvas back for the reveal.\n  const lastEpochRef = useRef(revealEpoch);\n  useEffect(() => {\n    if (lastEpochRef.current === revealEpoch) {\n      return;\n    }\n    lastEpochRef.current = revealEpoch;\n    setPhase(\"webgl\");\n  }, [revealEpoch]);\n\n  // Hover redraws: one frame per spring change, batched to the next paint.\n  // During the intro the reveal loop already draws every frame.\n  useEffect(() => {\n    if (!canvasReady) {\n      return;\n    }\n    let frame = 0;\n    const request = () => {\n      if (animatingRef.current || frame) {\n        return;\n      }\n      frame = requestAnimationFrame(() => {\n        frame = 0;\n        drawAt(Math.min(currentTime(), stopAt));\n      });\n    };\n    const unsubscribe = [segmentX, segmentWidth, hoverAmount].map((value) =>\n      value.on(\"change\", request)\n    );\n    return () => {\n      cancelAnimationFrame(frame);\n      for (const off of unsubscribe) {\n        off();\n      }\n    };\n  }, [\n    canvasReady,\n    currentTime,\n    drawAt,\n    hoverAmount,\n    segmentWidth,\n    segmentX,\n    stopAt,\n  ]);\n\n  const palette = [0, 1, 2, 3].map(\n    (i) => colors[i % Math.max(colors.length, 1)] ?? \"#ffffff\"\n  );\n  const seriesIndex = Math.max(\n    0,\n    lines.findIndex((line) => line.dataKey === dataKey)\n  );\n  const glowWidth = strokeWidth * GLOW_WIDTH_SCALE;\n\n  return (\n    <>\n      {/* Invisible — only used to sample the curve. */}\n      <path d={lineD} fill=\"none\" ref={pathRef} stroke=\"none\" />\n      {phase === \"svg\" ? (\n        <>\n          <defs>\n            <linearGradient\n              gradientUnits=\"userSpaceOnUse\"\n              id={gradientId}\n              x1={0}\n              x2={Math.max(innerWidth, 1)}\n              y1={0}\n              y2={0}\n            >\n              {palette.map((color, i) => (\n                <stop key={`${i}-${color}`} offset={i / 3} stopColor={color} />\n              ))}\n            </linearGradient>\n            <filter\n              colorInterpolationFilters=\"sRGB\"\n              filterUnits=\"userSpaceOnUse\"\n              height={innerHeight + GLOW_FILTER_BLEED * 2}\n              id={glowFilterId}\n              width={innerWidth + GLOW_FILTER_BLEED * 2}\n              x={-GLOW_FILTER_BLEED}\n              y={-GLOW_FILTER_BLEED}\n            >\n              <feGaussianBlur stdDeviation={GLOW_BLUR} />\n            </filter>\n          </defs>\n          <SeriesHoverDim\n            dimOpacity={dimOpacity}\n            enabled={highlightEnabled}\n            seriesIndex={seriesIndex}\n          >\n            <ParticleLineGlow\n              d={lineD}\n              filter={`url(#${glowFilterId})`}\n              stroke={`url(#${gradientId})`}\n              strokeWidth={glowWidth}\n            />\n            <path\n              d={lineD}\n              fill=\"none\"\n              ref={svgPathRef}\n              stroke={`url(#${gradientId})`}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              strokeWidth={strokeWidth}\n            />\n          </SeriesHoverDim>\n          <HighlightSegment\n            fadeLength={fadeLength}\n            height={innerHeight}\n            pathRef={svgPathRef}\n            stroke={`url(#${gradientId})`}\n            strokeWidth={strokeWidth}\n            visible={highlightEnabled && hoverActive}\n            width={segmentWidth}\n            x={segmentX}\n          />\n        </>\n      ) : null}\n      {container && phase === \"webgl\"\n        ? createPortal(\n            <canvas\n              aria-hidden\n              className=\"pointer-events-none absolute top-0 left-0\"\n              ref={canvasRef}\n              style={{ width, height }}\n            />,\n            container\n          )\n        : null}\n    </>\n  );\n}\n\nParticleLine.displayName = \"ParticleLine\";\n\nexport default ParticleLine;\n",
      "type": "registry:component",
      "target": "components/charts/particle-line.tsx"
    }
  ]
}