{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "fin-vol-surface",
  "type": "registry:component",
  "title": "Volatility surface",
  "description": "Implied volatility by strike and expiry as a banded contour grid, linked to the smile of any expiry and the at-the-money term structure.",
  "dependencies": [
    "clsx",
    "lucide-react",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "https://klar.run/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/klar/components/charts/finance/VolSurface.tsx",
      "content": "import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent } from 'react'\nimport { smoothPath } from '@/components/klar/charts/lines'\nimport { cn } from '@/components/klar/lib/cn'\nimport { useTheme } from '@/components/klar/lib/theme'\nimport { useMeasure } from '@/components/klar/lib/use-measure'\nimport { ChartDataTable } from '@/components/klar/charts/a11y'\nimport { ringCircle } from '@/components/klar/charts/bi/interaction'\nimport { Stat, Tip } from '@/components/klar/charts/finance/parts'\nimport { clamp, fixed, niceDomain, plain, plotPointer, rampAt, readVar, rgb, scale, signed, ticks, type RGB } from '@/components/klar/charts/finance/util'\n\nexport interface VolExpiry {\n  /** e.g. '1M'. */\n  label: string\n  /** Calendar days to expiry. */\n  days: number\n}\n\nexport interface VolSurfaceProps {\n  /** Strikes as moneyness K / S, ascending (1 = at the money). */\n  strikes: number[]\n  /** Expiries, nearest first. */\n  expiries: VolExpiry[]\n  /** Implied volatility in percent, `iv[expiry][strike]`. */\n  iv: number[][]\n  /** Spot, to print absolute strikes under the moneyness axis. */\n  spot?: number\n  height?: number\n  /**\n   * Selected (pinned) expiry index. Pass it with `onSelect` to control the selection\n   * from outside, e.g. to keep an expiry switcher in sync; omit it and the chart keeps\n   * its own selection (starting at `defaultSelected`).\n   */\n  selected?: number\n  /** Called whenever the user pins an expiry: clicking or tapping a row, the term structure, or Enter on the keyboard. */\n  onSelect?: (i: number) => void\n  /** Initial pinned expiry when uncontrolled (default: the 5th, or the last if fewer). */\n  defaultSelected?: number\n  /** Vol points per colour band (default 1). */\n  band?: number\n  /** Vol points between contour lines (default 2). */\n  contour?: number\n  /** Wing strikes for risk reversal / butterfly, as moneyness. */\n  wings?: [number, number]\n  /** Colour ramp tokens, low → high. */\n  ramp?: string[]\n  /** BCP 47 locale for numbers (default en-US). */\n  locale?: string\n  /** Accessible name; defaults to a summary of the surface and the pinned expiry. */\n  ariaLabel?: string\n  className?: string\n}\n\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function volSurfaceToRows(strikes: number[], expiries: VolExpiry[], iv: number[][]) {\n  return expiries.map((x, i) => ({\n    expiry: x.label,\n    days: x.days,\n    ...Object.fromEntries(strikes.map((k, j) => [`${+(k * 100).toFixed(4)}%`, iv[i][j]])),\n  }))\n}\n\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t\n\n/** Bilinear sample of the grid at fractional (row, col). */\nfunction sampler(g: number[][]) {\n  const R = g.length\n  const C = g[0].length\n  return (v: number, u: number) => {\n    const i0 = clamp(Math.floor(v), 0, R - 2)\n    const j0 = clamp(Math.floor(u), 0, C - 2)\n    const fv = clamp(v - i0, 0, 1)\n    const fu = clamp(u - j0, 0, 1)\n    return lerp(lerp(g[i0][j0], g[i0][j0 + 1], fu), lerp(g[i0 + 1][j0], g[i0 + 1][j0 + 1], fu), fv)\n  }\n}\n\n/** Marching squares: line segments of `level` over a regular grid F[r][c] (unit spacing). */\nfunction isoSegments(F: number[][], level: number) {\n  const segs: [number, number, number, number][] = []\n  const R = F.length\n  const C = F[0].length\n  for (let r = 0; r < R - 1; r++) {\n    for (let c = 0; c < C - 1; c++) {\n      const a = F[r][c]\n      const b = F[r][c + 1]\n      const cc = F[r + 1][c + 1]\n      const d = F[r + 1][c]\n      const k = (a > level ? 8 : 0) | (b > level ? 4 : 0) | (cc > level ? 2 : 0) | (d > level ? 1 : 0)\n      if (k === 0 || k === 15) continue\n      const t = (p: number, q: number) => (level - p) / (q - p || 1e-9)\n      const top: [number, number] = [c + t(a, b), r]\n      const right: [number, number] = [c + 1, r + t(b, cc)]\n      const bottom: [number, number] = [c + t(d, cc), r + 1]\n      const left: [number, number] = [c, r + t(a, d)]\n      const add = (p: [number, number], q: [number, number]) => segs.push([p[0], p[1], q[0], q[1]])\n      const centre = (a + b + cc + d) / 4 > level\n      switch (k) {\n        case 1: case 14: add(left, bottom); break\n        case 2: case 13: add(bottom, right); break\n        case 3: case 12: add(left, right); break\n        case 4: case 11: add(top, right); break\n        case 6: case 9: add(top, bottom); break\n        case 7: case 8: add(left, top); break\n        case 5:\n          if (centre) {\n            add(left, top)\n            add(bottom, right)\n          } else {\n            add(left, bottom)\n            add(top, right)\n          }\n          break\n        case 10:\n          if (centre) {\n            add(top, right)\n            add(left, bottom)\n          } else {\n            add(left, top)\n            add(bottom, right)\n          }\n          break\n      }\n    }\n  }\n  return segs\n}\n\nconst DEFAULT_RAMP = ['--blue', '--violet', '--pink', '--orange', '--amber']\n\n/**\n * Implied volatility surface: a banded heat grid of IV by moneyness × expiry with\n * contour lines, a smile chart for the selected expiry (click or hover a row) over\n * every other expiry, and the at-the-money term structure. Readouts show ATM vol,\n * risk reversal and butterfly for the chosen wings.\n * Data: `strikes` (moneyness), `expiries` ({ label, days }[]) and `iv[expiry][strike]` in %.\n *\n * Size: comfortable to ~40 expiries × 60 strikes. The heat field is a canvas\n * (cost depends on pixels, not grid size); contours and the smile panel scale\n * with the grid.\n *\n * Keyboard: focus the surface, ↑/↓ move between expiries, ←/→ between strikes,\n * Home/End jump to the wings, Enter or Space pins the expiry, Esc clears.\n * Touch: tap a cell to read it and pin its expiry; drag to scrub.\n */\nexport function VolSurface({\n  strikes,\n  expiries,\n  iv,\n  spot,\n  height = 460,\n  selected,\n  onSelect,\n  band = 1,\n  contour = 2,\n  wings = [0.9, 1.1],\n  ramp = DEFAULT_RAMP,\n  defaultSelected,\n  locale,\n  ariaLabel,\n  className,\n}: VolSurfaceProps) {\n  const uid = useId().replace(/:/g, '')\n  const [ref, { width }] = useMeasure()\n  const { theme } = useTheme()\n  const canvas = useRef<HTMLCanvasElement>(null)\n  const [inner, setInner] = useState(() => defaultSelected ?? Math.min(4, expiries.length - 1))\n  const sel = clamp(selected ?? inner, 0, expiries.length - 1)\n  // Uncontrolled: keep our own state even when onSelect is given; controlled: report and let the parent decide.\n  const select = (i: number) => {\n    if (selected == null) setInner(i)\n    onSelect?.(i)\n  }\n  const [hover, setHover] = useState<{ i: number; j: number; smile?: boolean } | null>(null)\n  const [kbd, setKbd] = useState(false)\n  const fx = (v: number, d: number) => fixed(v, d, locale)\n  const sg = (v: number, d: number) => signed(v, d, '', locale)\n  const [lutCss, setLutCss] = useState<string[]>([])\n  const [rowPeek, setRowPeek] = useState<number | null>(null)\n  const active = rowPeek ?? hover?.i ?? sel\n\n  const nE = expiries.length\n  const nS = strikes.length\n  const flat = iv.flat()\n  const vMin = flat.reduce((m, v) => (v < m ? v : m), Infinity)\n  const vMax = flat.reduce((m, v) => (v > m ? v : m), -Infinity)\n  const bLo = Math.floor(vMin / band) * band\n  const bHi = Math.ceil(vMax / band) * band\n\n  /* Geometry */\n  const STRIP = 34\n  const bodyH = height - STRIP - 12\n  const heatW = Math.round(width * 0.56)\n  const padL = 40\n  const padT = 4\n  const axisH = 36\n  const legendH = 30\n  const gridW = Math.max(0, heatW - padL)\n  const gridH = Math.max(0, bodyH - padT - axisH - legendH)\n  const cw = gridW / nS\n  const ch = gridH / nE\n  const nodeX = (j: number) => padL + (j + 0.5) * cw\n  const nodeY = (i: number) => padT + (i + 0.5) * ch\n\n  const at = useMemo(() => sampler(iv), [iv])\n  const atmIdx = strikes.reduce((b, k, j) => (Math.abs(k - 1) < Math.abs(strikes[b] - 1) ? j : b), 0)\n  const ivAtK = (i: number, k: number) => {\n    // linear in moneyness along a row\n    let j = 0\n    while (j < nS - 2 && strikes[j + 1] < k) j++\n    const t = (k - strikes[j]) / (strikes[j + 1] - strikes[j])\n    return lerp(iv[i][j], iv[i][j + 1], t)\n  }\n  const atm = expiries.map((_, i) => ivAtK(i, 1))\n  const rr = (i: number) => ivAtK(i, wings[1]) - ivAtK(i, wings[0])\n  const bf = (i: number) => (ivAtK(i, wings[1]) + ivAtK(i, wings[0])) / 2 - atm[i]\n\n  /* Canvas heat field, quantised into bands. */\n  useEffect(() => {\n    const cv = canvas.current\n    if (!cv || !gridW || !gridH) return\n    const dpr = Math.min(2, window.devicePixelRatio || 1)\n    const W = Math.round(gridW * dpr)\n    const H = Math.round(gridH * dpr)\n    cv.width = W\n    cv.height = H\n    const ctx = cv.getContext('2d')\n    if (!ctx) return\n    const stops: RGB[] = ramp.map((v) => readVar(cv, v))\n    const surf = readVar(cv, '--surface')\n    const nb = Math.round((bHi - bLo) / band)\n    const lut = Array.from({ length: nb + 1 }, (_, b) => {\n      // gamma < 1 spends more of the ramp on the crowded low-vol end\n      const c = rampAt(stops, nb ? Math.pow((b + 0.5) / nb, 0.72) : 0.5)\n      // a breath of the surface keeps the field from glaring in either theme\n      return [0, 1, 2].map((k) => lerp(c[k], surf[k], theme === 'dark' ? 0.16 : 0.08)) as RGB\n    })\n    const img = ctx.createImageData(W, H)\n    for (let py = 0; py < H; py++) {\n      const v = (py + 0.5) / dpr / ch - 0.5\n      for (let px = 0; px < W; px++) {\n        const u = (px + 0.5) / dpr / cw - 0.5\n        const val = at(v, u)\n        const b = clamp(Math.floor((val - bLo) / band), 0, nb)\n        const c = lut[b]\n        const o = (py * W + px) * 4\n        img.data[o] = c[0]\n        img.data[o + 1] = c[1]\n        img.data[o + 2] = c[2]\n        img.data[o + 3] = 255\n      }\n    }\n    ctx.putImageData(img, 0, 0)\n    setLutCss(lut.slice(0, nb).map((c) => rgb(c)))\n  }, [at, gridW, gridH, cw, ch, theme, band, bLo, bHi, ramp])\n\n  /* Contours on a 4× resampled grid spanning the full cell area. */\n  const contours = useMemo(() => {\n    if (!gridW || !gridH) return []\n    const U = 4\n    const R = nE * U + 1\n    const C = nS * U + 1\n    const F = Array.from({ length: R }, (_, r) => Array.from({ length: C }, (_, c) => at(r / U - 0.5, c / U - 0.5)))\n    const levels: number[] = []\n    for (let l = Math.ceil(vMin / contour) * contour; l < vMax; l += contour) levels.push(l)\n    return levels.map((l) => ({\n      l,\n      d: isoSegments(F, l)\n        .map(([x1, y1, x2, y2]) => `M${(padL + (x1 / U) * cw).toFixed(1)},${(padT + (y1 / U) * ch).toFixed(1)}L${(padL + (x2 / U) * cw).toFixed(1)},${(padT + (y2 / U) * ch).toFixed(1)}`)\n        .join(''),\n    }))\n  }, [at, gridW, gridH, nE, nS, cw, ch, vMin, vMax, contour])\n\n  /* Right column: smile (top) and ATM term structure (bottom). */\n  const rx0 = heatW + 32\n  const rW = Math.max(0, width - rx0 - 8)\n  const sPadL = 34\n  const smileH = Math.round((bodyH - 24) * 0.56)\n  const termTop = smileH + 34\n  const termH = bodyH - termTop - 2\n  const [yLo, yHi] = niceDomain(vMin - 0.5, vMax + 0.5, 4)\n  const sx = scale(strikes[0], strikes[nS - 1], rx0 + sPadL, rx0 + rW)\n  const sy = scale(yLo, yHi, padT + smileH - 22, padT + 26)\n  const logD = (d: number) => Math.log(d)\n  const tx = scale(logD(expiries[0].days), logD(expiries[nE - 1].days), rx0 + sPadL + 6, rx0 + rW - 6)\n  const [aLo, aHi] = niceDomain(Math.min(...atm) - 0.4, Math.max(...atm) + 0.4, 3)\n  const ty = scale(aLo, aHi, termTop + termH - 22, termTop + 18)\n\n  const onHeat = (px: number, py: number) => {\n    setKbd(false)\n    if (px >= padL && px <= padL + gridW && py >= padT && py <= padT + gridH) {\n      setRowPeek(null)\n      return setHover({ i: clamp(Math.floor((py - padT) / ch), 0, nE - 1), j: clamp(Math.floor((px - padL) / cw), 0, nS - 1) })\n    }\n    // smile panel: snap to strike on the active row\n    if (px >= rx0 + sPadL - 6 && px <= rx0 + rW + 6 && py <= padT + smileH) {\n      let j = 0\n      strikes.forEach((k, jj) => {\n        if (Math.abs(sx(k) - px) < Math.abs(sx(strikes[j]) - px)) j = jj\n      })\n      return setHover({ i: rowPeek ?? sel, j, smile: true })\n    }\n    // term panel: peek an expiry\n    if (px >= rx0 && py >= termTop) {\n      let i = 0\n      expiries.forEach((x, ii) => {\n        if (Math.abs(tx(logD(x.days)) - px) < Math.abs(tx(logD(expiries[i].days)) - px)) i = ii\n      })\n      setHover(null)\n      return setRowPeek(i)\n    }\n    setHover(null)\n    setRowPeek(null)\n  }\n\n  const onClick = () => {\n    if (hover) select(hover.i)\n    else if (rowPeek != null) select(rowPeek)\n  }\n  const clear = () => {\n    setHover(null)\n    setRowPeek(null)\n  }\n  const ptr = plotPointer(width, onHeat, clear)\n  const onKey = (e: KeyboardEvent) => {\n    const cur = hover && !hover.smile ? hover : null\n    const base = cur ?? { i: sel, j: atmIdx }\n    let next: { i: number; j: number } | null | undefined\n    if (e.key === 'ArrowUp') next = cur ? { ...base, i: Math.max(0, base.i - 1) } : base\n    else if (e.key === 'ArrowDown') next = cur ? { ...base, i: Math.min(nE - 1, base.i + 1) } : base\n    else if (e.key === 'ArrowLeft') next = cur ? { ...base, j: Math.max(0, base.j - 1) } : base\n    else if (e.key === 'ArrowRight') next = cur ? { ...base, j: Math.min(nS - 1, base.j + 1) } : base\n    else if (e.key === 'Home') next = { ...base, j: 0 }\n    else if (e.key === 'End') next = { ...base, j: nS - 1 }\n    else if (e.key === 'Enter' || e.key === ' ') {\n      if (cur) select(cur.i)\n      next = cur ?? base\n    } else if (e.key === 'Escape') next = null\n    if (next === undefined) return\n    e.preventDefault()\n    setRowPeek(null)\n    setKbd(next != null)\n    setHover(next)\n  }\n\n  const kLabel = (k: number) => `${Math.round(k * 100)}`\n  const mTicks = strikes.filter((k) => Math.abs(Math.round(k * 100) % 10) < 1e-6)\n  const smilePath = (i: number) => smoothPath(strikes.map((k, j) => [sx(k), sy(iv[i][j])]))\n\n  /* Legend */\n  const legW = Math.min(gridW, 300)\n  const legX = padL + gridW - legW\n  const legY = padT + gridH + axisH + 6\n\n  return (\n    <div className={cn('flex flex-col', className)}>\n      <div className=\"mb-3 flex h-[34px] items-center gap-x-5 overflow-hidden border-b border-border pb-2\">\n        <span className=\"inline-flex items-baseline gap-1.5 whitespace-nowrap\">\n          <span className=\"text-[12.5px] font-semibold text-fg\">{expiries[active].label}</span>\n          <span className=\"num text-[11.5px] text-fg-3\">{expiries[active].days}d</span>\n        </span>\n        <Stat label=\"ATM\">{fx(atm[active], 2)}%</Stat>\n        <Stat label={`${kLabel(wings[0])}/${kLabel(wings[1])} RR`} color={rr(active) < 0 ? 'var(--red)' : 'var(--green)'}>\n          {sg(rr(active), 2)}\n        </Stat>\n        <Stat label=\"Fly\">{sg(bf(active), 2)}</Stat>\n        {spot != null && <Stat label=\"Spot\">{fx(spot, 2)}</Stat>}\n        <span className=\"ml-auto hidden text-[11px] text-fg-3 @3xl/app:inline\">Click a row to pin an expiry</span>\n      </div>\n\n      <div\n        ref={ref}\n        role=\"img\"\n        aria-label={ariaLabel ?? `Implied volatility surface, ${nE} expiries by ${nS} strikes, ${fx(vMin, 1)}% to ${fx(vMax, 1)}%; ${expiries[sel].label} ATM ${fx(atm[sel], 2)}%`}\n        tabIndex={0}\n        className=\"relative w-full outline-none\"\n        {...ptr}\n        style={{ ...ptr.style, height: bodyH, cursor: 'crosshair' }}\n        onClick={onClick}\n        onKeyDown={onKey}\n        onBlur={() => {\n          clear()\n          setKbd(false)\n        }}\n      >\n        {width > 0 && (\n          <>\n            <canvas\n              ref={canvas}\n              className=\"anim-fade absolute rounded-[3px]\"\n              style={{ left: padL, top: padT, width: gridW, height: gridH }}\n            />\n            <svg width={width} height={bodyH} className=\"absolute inset-0 block\">\n              <defs>\n                <linearGradient id={`${uid}-smile`} x1=\"0\" x2=\"0\" y1=\"0\" y2=\"1\">\n                  <stop offset=\"0\" stopColor=\"var(--accent)\" stopOpacity={0.2} />\n                  <stop offset=\"1\" stopColor=\"var(--accent)\" stopOpacity={0} />\n                </linearGradient>\n              </defs>\n\n              {/* contours */}\n              <g pointerEvents=\"none\">\n                {contours.map((c) => (\n                  <path\n                    key={c.l}\n                    d={c.d}\n                    fill=\"none\"\n                    stroke=\"var(--surface)\"\n                    strokeOpacity={c.l % (contour * 2) === 0 ? 0.7 : 0.38}\n                    strokeWidth={c.l % (contour * 2) === 0 ? 1 : 0.75}\n                  />\n                ))}\n              </g>\n\n              {/* ATM column marker */}\n              <line x1={nodeX(atmIdx)} x2={nodeX(atmIdx)} y1={padT} y2={padT + gridH} stroke=\"var(--surface)\" strokeOpacity={0.6} strokeDasharray=\"2 3\" />\n\n              {/* expiry labels */}\n              {expiries.map((x, i) => (\n                <text\n                  key={x.label}\n                  x={padL - 8}\n                  y={nodeY(i) + 3.8}\n                  textAnchor=\"end\"\n                  className={cn('num text-[11px]', i === active ? 'fill-fg font-semibold' : 'fill-fg-3')}\n                >\n                  {x.label}\n                </text>\n              ))}\n\n              {/* moneyness axis */}\n              {strikes.map((k, j) => {\n                const major = mTicks.includes(k)\n                return (\n                  <g key={k}>\n                    <line x1={nodeX(j)} x2={nodeX(j)} y1={padT + gridH} y2={padT + gridH + (major ? 5 : 3)} stroke={major ? 'var(--fg-3)' : 'var(--fg-4)'} />\n                    {major && (\n                      <>\n                        <text x={nodeX(j)} y={padT + gridH + 17} textAnchor=\"middle\" className={cn('num text-[11px]', hover?.j === j ? 'fill-fg font-semibold' : 'fill-fg-2')}>\n                          {kLabel(k)}%\n                        </text>\n                        {spot != null && (\n                          <text x={nodeX(j)} y={padT + gridH + 30} textAnchor=\"middle\" className=\"num fill-fg-4 text-[10px]\">\n                            {fx(Math.round(spot * k), 0)}\n                          </text>\n                        )}\n                      </>\n                    )}\n                  </g>\n                )\n              })}\n\n              {/* selected / active rows */}\n              <rect x={padL - 0.5} y={padT + sel * ch} width={gridW + 1} height={ch} fill=\"none\" stroke=\"var(--fg)\" strokeWidth={1.5} rx={2} />\n              <path d={`M${padL - 36},${nodeY(sel) - 4}l5,4l-5,4z`} fill=\"var(--fg)\" />\n              {active !== sel && (\n                <rect x={padL - 0.5} y={padT + active * ch} width={gridW + 1} height={ch} fill=\"none\" stroke=\"var(--fg)\" strokeOpacity={0.55} strokeDasharray=\"3 2\" rx={2} />\n              )}\n\n              {/* hover node */}\n              {hover && (\n                <g pointerEvents=\"none\">\n                  <line x1={padL} x2={padL + gridW} y1={nodeY(hover.i)} y2={nodeY(hover.i)} stroke=\"var(--surface)\" strokeOpacity={0.5} />\n                  <line x1={nodeX(hover.j)} x2={nodeX(hover.j)} y1={padT} y2={padT + gridH} stroke=\"var(--surface)\" strokeOpacity={0.5} />\n                  <circle cx={nodeX(hover.j)} cy={nodeY(hover.i)} r={5} fill=\"none\" stroke=\"var(--surface)\" strokeWidth={2} />\n                  <circle cx={nodeX(hover.j)} cy={nodeY(hover.i)} r={6.5} fill=\"none\" stroke=\"var(--fg)\" strokeWidth={1} />\n                  {kbd && <circle {...ringCircle(nodeX(hover.j), nodeY(hover.i), 7)} />}\n                </g>\n              )}\n\n              {/* colour legend */}\n              <g>\n                <text x={padL} y={legY + 9} className=\"fill-fg-3 text-[10px] font-medium tracking-[0.04em] uppercase\">\n                  Implied vol\n                </text>\n                <clipPath id={`${uid}-leg`}>\n                  <rect x={legX} y={legY} width={legW} height={8} rx={4} />\n                </clipPath>\n                <g clipPath={`url(#${uid}-leg)`}>\n                  {lutCss.map((c, b) => (\n                    <rect key={b} x={legX + (b / lutCss.length) * legW} y={legY} width={legW / lutCss.length - (b < lutCss.length - 1 ? 1 : 0)} height={8} fill={c} />\n                  ))}\n                </g>\n                {ticks(bLo, bHi, 5).map((t) => (\n                  <text key={t} x={legX + ((t - bLo) / (bHi - bLo)) * legW} y={legY + 21} textAnchor=\"middle\" className=\"num fill-fg-3 text-[10px]\">\n                    {plain(t, locale)}\n                  </text>\n                ))}\n              </g>\n\n              {/* ---------- smile ---------- */}\n              <text x={rx0} y={padT + 8} className=\"fill-fg-2 text-[11px] font-semibold\">\n                Smile\n                <tspan className=\"fill-fg-3 font-normal\" dx={6}>\n                  {expiries[active].label} · IV by moneyness\n                </tspan>\n              </text>\n              {ticks(yLo, yHi, 4).map((t) => (\n                <g key={t}>\n                  <line x1={rx0 + sPadL} x2={rx0 + rW} y1={Math.round(sy(t)) + 0.5} y2={Math.round(sy(t)) + 0.5} stroke=\"var(--border)\" strokeDasharray=\"2 4\" />\n                  <text x={rx0 + sPadL - 6} y={sy(t) + 3.8} textAnchor=\"end\" className=\"num fill-fg-3 text-[10.5px]\">\n                    {plain(t, locale)}%\n                  </text>\n                </g>\n              ))}\n              <line x1={sx(1)} x2={sx(1)} y1={padT + 26} y2={padT + smileH - 22} stroke=\"var(--fg-4)\" strokeDasharray=\"2 3\" />\n              <text x={sx(1)} y={padT + smileH - 26} dx={4} className=\"fill-fg-4 text-[10px] font-medium\">\n                ATM\n              </text>\n              {expiries.map((_, i) =>\n                i === active ? null : <path key={i} d={smilePath(i)} fill=\"none\" stroke=\"var(--fg-4)\" strokeOpacity={0.45} strokeWidth={1} />,\n              )}\n              <path d={`${smilePath(active)}L${sx(strikes[nS - 1])},${padT + smileH - 22}L${sx(strikes[0])},${padT + smileH - 22}Z`} fill={`url(#${uid}-smile)`} />\n              <path d={smilePath(active)} fill=\"none\" stroke=\"var(--accent)\" strokeWidth={2} />\n              {strikes.map((k, j) => (\n                <circle\n                  key={k}\n                  cx={sx(k)}\n                  cy={sy(iv[active][j])}\n                  r={hover?.j === j && hover.i === active ? 4.5 : 2.25}\n                  fill={hover?.j === j && hover.i === active ? 'var(--surface)' : 'var(--accent)'}\n                  stroke=\"var(--accent)\"\n                  strokeWidth={2}\n                />\n              ))}\n              {[wings[0], wings[1]].map((k) => (\n                <g key={k}>\n                  <line x1={sx(k)} x2={sx(k)} y1={sy(ivAtK(active, k)) + 6} y2={padT + smileH - 22} stroke=\"var(--fg-4)\" strokeDasharray=\"1 2\" />\n                </g>\n              ))}\n              <line x1={rx0 + sPadL} x2={rx0 + rW} y1={padT + smileH - 21.5} y2={padT + smileH - 21.5} stroke=\"var(--border-strong)\" />\n              {mTicks.map((k, n) => (\n                <text key={k} x={sx(k)} y={padT + smileH - 8} textAnchor={n === mTicks.length - 1 ? 'end' : n === 0 ? 'start' : 'middle'} className=\"num fill-fg-3 text-[10.5px]\">\n                  {kLabel(k)}%\n                </text>\n              ))}\n\n              {/* ---------- ATM term structure ---------- */}\n              <text x={rx0} y={termTop + 4} className=\"fill-fg-2 text-[11px] font-semibold\">\n                ATM term structure\n              </text>\n              {ticks(aLo, aHi, 3).map((t) => (\n                <g key={t}>\n                  <line x1={rx0 + sPadL} x2={rx0 + rW} y1={Math.round(ty(t)) + 0.5} y2={Math.round(ty(t)) + 0.5} stroke=\"var(--border)\" strokeDasharray=\"2 4\" />\n                  <text x={rx0 + sPadL - 6} y={ty(t) + 3.8} textAnchor=\"end\" className=\"num fill-fg-3 text-[10.5px]\">\n                    {plain(t, locale)}%\n                  </text>\n                </g>\n              ))}\n              <path d={smoothPath(expiries.map((x, i) => [tx(logD(x.days)), ty(atm[i])]))} fill=\"none\" stroke=\"var(--accent)\" strokeWidth={1.75} />\n              {expiries.map((x, i) => {\n                const on = i === active\n                return (\n                  <g key={x.label}>\n                    <circle cx={tx(logD(x.days))} cy={ty(atm[i])} r={on ? 4.5 : 2.5} fill={on ? 'var(--surface)' : 'var(--accent)'} stroke=\"var(--accent)\" strokeWidth={2} />\n                    {on && (\n                      <text x={tx(logD(x.days))} y={ty(atm[i]) - 9} textAnchor=\"middle\" className=\"num fill-fg text-[10.5px] font-semibold\">\n                        {fx(atm[i], 2)}%\n                      </text>\n                    )}\n                    <text x={tx(logD(x.days))} y={termTop + termH - 6} textAnchor=\"middle\" className={cn('num text-[10.5px]', on ? 'fill-fg font-semibold' : 'fill-fg-3')}>\n                      {x.label}\n                    </text>\n                  </g>\n                )\n              })}\n              <line x1={rx0 + sPadL} x2={rx0 + rW} y1={termTop + termH - 21.5} y2={termTop + termH - 21.5} stroke=\"var(--border-strong)\" />\n            </svg>\n          </>\n        )}\n        {hover && width > 0 && (\n          <Tip\n            x={hover.smile ? sx(strikes[hover.j]) : nodeX(hover.j)}\n            y={hover.smile ? clamp(sy(iv[hover.i][hover.j]), padT + 60, padT + smileH - 60) : nodeY(hover.i)}\n            width={hover.smile ? width : heatW + 40}\n            w={190}\n            title={\n              <span className=\"flex justify-between\">\n                <span className=\"font-semibold text-fg\">{expiries[hover.i].label}</span>\n                <span>{expiries[hover.i].days} days</span>\n              </span>\n            }\n            rows={[\n              { label: 'Moneyness', value: `${fx(strikes[hover.j] * 100, 1)}%` },\n              ...(spot != null ? [{ label: 'Strike', value: fx(Math.round(spot * strikes[hover.j]), 0) }] : []),\n              { label: 'Implied vol', value: `${fx(iv[hover.i][hover.j], 2)}%`, strong: true, color: 'var(--accent)' },\n              { label: 'vs ATM', value: `${sg(iv[hover.i][hover.j] - atm[hover.i], 2)} pts` },\n            ]}\n            footer={hover.i !== sel ? (kbd ? 'Press Enter to pin this expiry' : 'Click to pin this expiry') : undefined}\n          />\n        )}\n      </div>\n      <ChartDataTable\n        caption=\"Implied volatility (%) by expiry and moneyness\"\n        columns={[\n          { key: 'expiry', label: 'Expiry' },\n          { key: 'days', label: 'Days' },\n          ...strikes.map((k) => ({ key: `${+(k * 100).toFixed(4)}%`, label: `${fx(k * 100, 0)}%`, format: (v: unknown) => fx(Number(v), 2) })),\n        ]}\n        rows={volSurfaceToRows(strikes, expiries, iv)}\n      />\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/finance/VolSurface.tsx"
    },
    {
      "path": "registry/klar/components/charts/lines.tsx",
      "content": "import { useId, useState, type ReactNode } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\nimport { useMeasure } from '@/components/klar/lib/use-measure'\nimport { ChartDataTable } from '@/components/klar/charts/a11y'\nimport { formatter, usePointerHover } from '@/components/klar/charts/basic/core'\nimport { niceMax, Tooltip } from '@/components/klar/charts/bars'\nimport { ringRect, useChartNav } from '@/components/klar/charts/bi/interaction'\n\n/** Min / max without spreading (spread throws on very large arrays). */\nfunction minMax(values: number[]): [number, number] {\n  let lo = Infinity\n  let hi = -Infinity\n  for (const v of values) {\n    if (v < lo) lo = v\n    if (v > hi) hi = v\n  }\n  return [lo, hi]\n}\n\n/* ------------------------------------------------------------------ */\n/*  Path helpers                                                      */\n/* ------------------------------------------------------------------ */\n\ntype Pt = [number, number]\n\n/** Monotone cubic interpolation — smooth without overshooting. */\n// oxlint-disable-next-line react/only-export-components -- shared path helper used across the kit\nexport function smoothPath(pts: Pt[]) {\n  if (pts.length < 2) return ''\n  const n = pts.length\n  const dx: number[] = []\n  const m: number[] = []\n  for (let i = 0; i < n - 1; i++) {\n    dx.push(pts[i + 1][0] - pts[i][0])\n    m.push((pts[i + 1][1] - pts[i][1]) / (dx[i] || 1))\n  }\n  const t: number[] = [m[0]]\n  for (let i = 1; i < n - 1; i++) {\n    t.push(m[i - 1] * m[i] <= 0 ? 0 : (m[i - 1] + m[i]) / 2)\n  }\n  t.push(m[n - 2])\n  let d = `M${pts[0][0]},${pts[0][1]}`\n  for (let i = 0; i < n - 1; i++) {\n    const c = dx[i] / 3\n    d += `C${pts[i][0] + c},${pts[i][1] + t[i] * c} ${pts[i + 1][0] - c},${pts[i + 1][1] - t[i + 1] * c} ${pts[i + 1][0]},${pts[i + 1][1]}`\n  }\n  return d\n}\n\n// oxlint-disable-next-line react/only-export-components -- shared path helper used across the kit\nexport function linePath(pts: Pt[]) {\n  return pts.map((p, i) => `${i ? 'L' : 'M'}${p[0]},${p[1]}`).join('')\n}\n\n/* ------------------------------------------------------------------ */\n/*  AreaChart: multi-series smooth lines with gradient area fills,    */\n/*  crosshair, hover tooltip and optional marker annotations.         */\n/* ------------------------------------------------------------------ */\n\nexport interface LineSeries {\n  key: string\n  label: string\n  color: string\n  /** Fill under the line. */\n  area?: boolean\n  dashed?: boolean\n  width?: number\n}\n\n/**\n * Comfortable to ~2,000 points per series (SVG paths); past that, downsample first.\n * Hover, tap or drag to scrub; focus the chart and use ←/→, Home/End, Esc.\n */\nexport function AreaChart({\n  data,\n  series,\n  xKey = 'x',\n  height = 240,\n  yTicks = 4,\n  formatY: formatYProp,\n  formatTooltip,\n  xLabelEvery = 1,\n  curve = 'smooth',\n  markers,\n  min = 0,\n  className,\n  grid = 'dashed',\n  showDots = false,\n  locale,\n  currency,\n  ariaLabel,\n}: {\n  data: Record<string, number | string>[]\n  series: LineSeries[]\n  xKey?: string\n  height?: number\n  yTicks?: number\n  formatY?: (v: number) => string\n  formatTooltip?: (v: number) => string\n  xLabelEvery?: number\n  curve?: 'smooth' | 'linear' | 'step'\n  /** Vertical annotation markers at data indices. */\n  markers?: { index: number; label: ReactNode; color?: string }[]\n  min?: number\n  className?: string\n  grid?: 'dashed' | 'solid' | 'none'\n  showDots?: boolean\n  /** Locale for the default number format (default: plain rounded integers, as today). */\n  locale?: string\n  currency?: string\n  ariaLabel?: string\n}) {\n  const gid = useId().replace(/:/g, '')\n  const [ref, { width }] = useMeasure()\n  const { point, bind, clear } = usePointerHover<HTMLDivElement>()\n  const [keyed, setKeyed] = useState<number | null>(null)\n  const formatY = formatYProp ?? (locale ? (v: number) => formatter(locale, currency).number(v) : (v: number) => String(Math.round(v)))\n  const padL = 44\n  const padR = 8\n  const padT = 12\n  const padB = 26\n  const innerW = Math.max(0, width - padL - padR)\n  const innerH = height - padT - padB\n  const allVals = data.flatMap((d) => series.map((s) => Number(d[s.key] ?? 0)))\n  const max = niceMax(Math.max(minMax(allVals)[1], 1))\n  const lo = min\n  const x = (i: number) => padL + (data.length === 1 ? innerW / 2 : (i / (data.length - 1)) * innerW)\n  const y = (v: number) => padT + innerH - ((v - lo) / (max - lo)) * innerH\n  const fmtTip = formatTooltip ?? formatY\n  const pointIndex = point\n    ? Math.max(0, Math.min(data.length - 1, Math.round(((point.x - padL) / innerW) * (data.length - 1))))\n    : null\n  const hover = keyed ?? pointIndex\n  const nav = useChartNav({\n    count: data.length,\n    onMove: (p) => {\n      clear()\n      setKeyed(p.i)\n    },\n    onClear: () => {\n      clear()\n      setKeyed(null)\n    },\n    start: hover != null ? { i: hover, j: 0 } : null,\n  })\n  const label = ariaLabel ?? `Line chart of ${series.map((s) => s.label).join(', ')} across ${data.length} points`\n\n  const build = (pts: Pt[]) => {\n    if (curve === 'linear') return linePath(pts)\n    if (curve === 'step') {\n      return pts\n        .map((p, i) => (i ? `H${p[0]}V${p[1]}` : `M${p[0]},${p[1]}`))\n        .join('')\n    }\n    return smoothPath(pts)\n  }\n\n  return (\n    <div\n      ref={ref}\n      role=\"figure\"\n      aria-label={label}\n      className={cn('relative w-full select-none', className)}\n      {...nav.root}\n      {...bind}\n      onPointerDown={(e) => {\n        setKeyed(null)\n        bind.onPointerDown(e)\n      }}\n      onPointerMove={(e) => {\n        nav.root.onPointerMove(e)\n        if (keyed != null && e.pointerType === 'mouse') setKeyed(null)\n        bind.onPointerMove(e)\n      }}\n      style={{ height, ...bind.style }}\n    >\n      <ChartDataTable\n        caption={label}\n        columns={[{ key: xKey, label: xKey }, ...series.map((s) => ({ key: s.label, label: s.label, format: (v: unknown) => fmtTip(Number(v)) }))]}\n        rows={areaChartToRows(data, series, xKey)}\n      />\n      {width > 0 && (\n        <svg width={width} height={height} className=\"overflow-visible\" aria-hidden>\n          <defs>\n            {series.map((s) => (\n              <linearGradient key={s.key} id={`${gid}-${s.key}`} x1=\"0\" x2=\"0\" y1=\"0\" y2=\"1\">\n                <stop offset=\"0%\" stopColor={s.color} stopOpacity={0.28} />\n                <stop offset=\"100%\" stopColor={s.color} stopOpacity={0} />\n              </linearGradient>\n            ))}\n            <clipPath id={`${gid}-reveal`}>\n              <rect x={0} y={0} width={width} height={height} className=\"anim-grow-x\" />\n            </clipPath>\n          </defs>\n          {grid !== 'none' &&\n            Array.from({ length: yTicks + 1 }, (_, i) => {\n              const v = lo + ((max - lo) / yTicks) * i\n              return (\n                <g key={i}>\n                  <line\n                    x1={padL}\n                    x2={width - padR}\n                    y1={y(v)}\n                    y2={y(v)}\n                    stroke=\"var(--border)\"\n                    strokeDasharray={i === 0 || grid === 'solid' ? undefined : '3 4'}\n                  />\n                  <text x={padL - 10} y={y(v) + 4} textAnchor=\"end\" className=\"num fill-fg-3 text-[11px]\">\n                    {formatY(v)}\n                  </text>\n                </g>\n              )\n            })}\n          {data.map((d, i) =>\n            i % xLabelEvery === 0 ? (\n              <text\n                key={i}\n                x={x(i)}\n                y={height - 6}\n                textAnchor={i === 0 ? 'start' : i === data.length - 1 ? 'end' : 'middle'}\n                className=\"fill-fg-3 text-[11px]\"\n              >\n                {String(d[xKey])}\n              </text>\n            ) : null,\n          )}\n          {markers?.map((m, i) => (\n            <g key={i}>\n              <line\n                x1={x(m.index)}\n                x2={x(m.index)}\n                y1={padT}\n                y2={padT + innerH}\n                stroke={m.color ?? 'var(--fg-4)'}\n                strokeDasharray=\"2 3\"\n              />\n            </g>\n          ))}\n          <g clipPath={`url(#${gid}-reveal)`}>\n            {series.map((s) => {\n              const pts: Pt[] = data.map((d, i) => [x(i), y(Number(d[s.key] ?? 0))])\n              const path = build(pts)\n              return (\n                <g key={s.key}>\n                  {s.area && (\n                    <path\n                      d={`${path}L${x(data.length - 1)},${y(lo)}L${x(0)},${y(lo)}Z`}\n                      fill={`url(#${gid}-${s.key})`}\n                    />\n                  )}\n                  <path\n                    d={path}\n                    fill=\"none\"\n                    stroke={s.color}\n                    strokeWidth={s.width ?? 2}\n                    strokeLinecap=\"round\"\n                    strokeLinejoin=\"round\"\n                    strokeDasharray={s.dashed ? '4 5' : undefined}\n                  />\n                  {showDots &&\n                    pts.map((p, i) => (\n                      <circle key={i} cx={p[0]} cy={p[1]} r={2.5} fill=\"var(--surface)\" stroke={s.color} strokeWidth={1.5} />\n                    ))}\n                </g>\n              )\n            })}\n          </g>\n          {hover != null && (\n            <g>\n              <line\n                x1={x(hover)}\n                x2={x(hover)}\n                y1={padT}\n                y2={padT + innerH}\n                stroke=\"var(--fg-4)\"\n                strokeDasharray=\"3 3\"\n              />\n              {series.map((s) => (\n                <circle\n                  key={s.key}\n                  cx={x(hover)}\n                  cy={y(Number(data[hover][s.key] ?? 0))}\n                  r={4.5}\n                  fill=\"var(--surface)\"\n                  stroke={s.color}\n                  strokeWidth={2.2}\n                />\n              ))}\n            </g>\n          )}\n          {nav.pos && <rect {...ringRect(x(nav.pos.i) - 7, padT, 14, innerH, { rx: 7 })} />}\n        </svg>\n      )}\n      {markers?.map((m, i) =>\n        width > 0 ? (\n          <span\n            key={i}\n            className=\"absolute -translate-x-1/2 rounded-md border border-border bg-surface px-1.5 py-0.5 text-[10.5px] font-medium whitespace-nowrap text-fg-2 shadow-btn\"\n            style={{ left: x(m.index), top: padT - 4 }}\n          >\n            {m.label}\n          </span>\n        ) : null,\n      )}\n      {hover != null && width > 0 && (\n        <Tooltip\n          x={x(hover)}\n          y={y(Math.max(...series.map((s) => Number(data[hover][s.key] ?? 0))))}\n          containerWidth={width}\n          title={String(data[hover][xKey])}\n          rows={series.map((s) => ({\n            label: s.label,\n            color: s.color,\n            value: fmtTip(Number(data[hover][s.key] ?? 0)),\n          }))}\n        />\n      )}\n    </div>\n  )\n}\n\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function areaChartToRows(data: Record<string, number | string>[], series: LineSeries[], xKey = 'x') {\n  return data.map((d) => {\n    const row: Record<string, string | number> = { [xKey]: String(d[xKey]) }\n    for (const s of series) row[s.label] = Number(d[s.key] ?? 0)\n    return row\n  })\n}\n\n/* ------------------------------------------------------------------ */\n/*  Sparkline                                                         */\n/* ------------------------------------------------------------------ */\n\n/** Micro-chart, comfortable to a few hundred values. Read out as first / last / range via `aria-label`. */\nexport function Sparkline({\n  values,\n  color = 'var(--accent)',\n  width = 80,\n  height = 24,\n  area = false,\n  strokeWidth = 1.75,\n  className,\n  ariaLabel,\n}: {\n  values: number[]\n  color?: string\n  width?: number\n  height?: number\n  area?: boolean\n  strokeWidth?: number\n  className?: string\n  ariaLabel?: string\n}) {\n  const gid = useId().replace(/:/g, '')\n  const [lo, hi] = minMax(values)\n  const pts: Pt[] = values.map((v, i) => [\n    (i / (values.length - 1)) * width,\n    height - 2 - ((v - lo) / (hi - lo || 1)) * (height - 4),\n  ])\n  const d = smoothPath(pts)\n  const label =\n    ariaLabel ??\n    (values.length\n      ? `Trend of ${values.length} values, from ${values[0]} to ${values[values.length - 1]} (low ${lo}, high ${hi})`\n      : 'Empty trend')\n  return (\n    <svg role=\"img\" aria-label={label} width={width} height={height} className={cn('overflow-visible', className)}>\n      {area && (\n        <>\n          <defs>\n            <linearGradient id={gid} x1=\"0\" x2=\"0\" y1=\"0\" y2=\"1\">\n              <stop offset=\"0%\" stopColor={color} stopOpacity={0.25} />\n              <stop offset=\"100%\" stopColor={color} stopOpacity={0} />\n            </linearGradient>\n          </defs>\n          <path d={`${d}L${width},${height}L0,${height}Z`} fill={`url(#${gid})`} />\n        </>\n      )}\n      <path d={d} fill=\"none\" stroke={color} strokeWidth={strokeWidth} strokeLinecap=\"round\" />\n    </svg>\n  )\n}\n\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function sparklineToRows(values: number[]) {\n  return values.map((value, index) => ({ index, value }))\n}\n\n/** ECG-like heartbeat glyph used beside headline percentages. Decorative (hidden from screen readers). */\nexport function Pulse({ color = 'var(--green)', width = 70, height = 22 }: { color?: string; width?: number; height?: number }) {\n  const m = height / 2\n  const d = `M0,${m} L${width * 0.3},${m} L${width * 0.38},${m - 2} L${width * 0.45},${height - 1} L${width * 0.53},1 L${width * 0.6},${m + 3} L${width * 0.66},${m} L${width},${m}`\n  return (\n    <svg width={width} height={height} className=\"overflow-visible\" aria-hidden>\n      <path d={d} fill=\"none\" stroke={color} strokeWidth={1.6} strokeLinejoin=\"round\" strokeLinecap=\"round\" />\n    </svg>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/lines.tsx"
    },
    {
      "path": "registry/klar/components/charts/a11y.tsx",
      "content": "import { useState, type ReactNode, type RefObject } from 'react'\nimport { Download, Table2 } from 'lucide-react'\nimport { cn } from '@/components/klar/lib/cn'\nimport { exportChartPng, exportChartSvg, exportCsv } from '@/components/klar/charts/export'\n\n/**\n * Accessible data behind a chart. Renders a real <table> that screen readers use\n * (visually hidden by default). With `toggle`, sighted users can reveal it too.\n *\n *   <ChartDataTable caption=\"Revenue by month\" columns={[{ key: 'month', label: 'Month' }, …]} rows={data} />\n */\nexport interface DataTableColumn {\n  key: string\n  label: string\n  /** Format a cell for display (the raw value is used for CSV). */\n  format?: (v: unknown, row: Record<string, unknown>) => string\n  align?: 'left' | 'right'\n}\n\nexport function ChartDataTable({\n  caption,\n  columns,\n  rows,\n  visible = false,\n  className,\n}: {\n  caption: string\n  columns: DataTableColumn[]\n  rows: Record<string, unknown>[]\n  /** Show the table visually instead of only to assistive tech. */\n  visible?: boolean\n  className?: string\n}) {\n  return (\n    <div className={cn(visible ? 'scroll-thin max-h-72 overflow-auto rounded-xl border border-border' : 'sr-only', className)}>\n      <table className=\"w-full border-collapse text-[12.5px]\">\n        <caption className={visible ? 'px-3 pt-2.5 pb-1 text-left text-[12px] text-fg-3' : undefined}>{caption}</caption>\n        <thead className={visible ? 'sticky top-0 bg-surface-2' : undefined}>\n          <tr>\n            {columns.map((c) => (\n              <th key={c.key} scope=\"col\" className={cn('px-3 py-2 font-medium text-fg-2', c.align === 'right' ? 'text-right' : 'text-left')}>\n                {c.label}\n              </th>\n            ))}\n          </tr>\n        </thead>\n        <tbody>\n          {rows.map((r, i) => (\n            <tr key={i} className={visible ? 'border-t border-border' : undefined}>\n              {columns.map((c, j) => {\n                const v = r[c.key]\n                const text = c.format ? c.format(v, r) : v == null ? '' : String(v)\n                return j === 0 ? (\n                  <th key={c.key} scope=\"row\" className=\"px-3 py-1.5 text-left font-normal text-fg\">\n                    {text}\n                  </th>\n                ) : (\n                  <td key={c.key} className={cn('num px-3 py-1.5 text-fg', c.align === 'left' ? 'text-left' : 'text-right')}>\n                    {text}\n                  </td>\n                )\n              })}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  )\n}\n\n/**\n * Small toolbar for a chart card: show data table, download PNG / SVG / CSV.\n * Pass a ref to the element that wraps the chart.\n */\nexport function ChartActions({\n  target,\n  name,\n  rows,\n  columns,\n  onToggleTable,\n  tableOpen,\n  className,\n  extra,\n}: {\n  target: RefObject<HTMLElement | null>\n  name: string\n  rows?: Record<string, unknown>[]\n  columns?: string[]\n  onToggleTable?: () => void\n  tableOpen?: boolean\n  className?: string\n  extra?: ReactNode\n}) {\n  const [open, setOpen] = useState(false)\n  const [busy, setBusy] = useState(false)\n  const run = async (kind: 'png' | 'svg' | 'csv') => {\n    setOpen(false)\n    if (kind === 'csv') return rows && exportCsv(rows, name, columns)\n    const el = target.current\n    if (!el) return\n    if (kind === 'svg') return exportChartSvg(el, name)\n    setBusy(true)\n    try {\n      await exportChartPng(el, name)\n    } finally {\n      setBusy(false)\n    }\n  }\n  const btn = 'inline-flex h-7 items-center gap-1.5 rounded-lg px-2 text-[12px] font-medium text-fg-3 transition-colors hover:bg-surface-3 hover:text-fg'\n  return (\n    <div className={cn('relative flex items-center gap-0.5', className)}>\n      {extra}\n      {onToggleTable && (\n        <button type=\"button\" aria-pressed={tableOpen} onClick={onToggleTable} className={cn(btn, tableOpen && 'bg-surface-3 text-fg')} title=\"Show data table\">\n          <Table2 size={14} />\n          <span className=\"sr-only\">Show data table</span>\n        </button>\n      )}\n      <button type=\"button\" aria-haspopup=\"menu\" aria-expanded={open} onClick={() => setOpen((o) => !o)} className={btn} title=\"Download\">\n        <Download size={14} className={busy ? 'animate-pulse' : undefined} />\n        <span className=\"sr-only\">Download chart</span>\n      </button>\n      {open && (\n        <div role=\"menu\" className=\"absolute top-8 right-0 z-40 min-w-[150px] rounded-xl border border-border bg-surface p-1 shadow-pop\" onMouseLeave={() => setOpen(false)}>\n          {(['png', 'svg', ...(rows ? (['csv'] as const) : [])] as const).map((k) => (\n            <button key={k} role=\"menuitem\" type=\"button\" onClick={() => run(k)} className=\"flex w-full items-center justify-between rounded-lg px-2.5 py-1.5 text-left text-[12.5px] text-fg-2 hover:bg-surface-3 hover:text-fg\">\n              {k === 'png' ? 'PNG image' : k === 'svg' ? 'SVG vector' : 'CSV data'}\n              <span className=\"font-mono text-[10.5px] text-fg-4\">.{k}</span>\n            </button>\n          ))}\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/a11y.tsx"
    },
    {
      "path": "registry/klar/components/charts/bi/interaction.ts",
      "content": "/**\n * Pointer (mouse, touch, pen) and keyboard plumbing shared by the BI, finance and\n * kit charts whose marks own their hover state.\n *\n *   const nav = useChartNav({ count: data.length, onMove: (p) => setHover(p ? p.i : null), onClear: () => setHover(null) })\n *   <div {...nav.root}>                         // focusable plot; arrows, Home/End, Esc\n *     <rect {...markHover(setHover, i)} />      // hover + tap on one mark\n *     {nav.pos && <rect {...ringRect(x, y, w, h)} />}  // explicit SVG focus ring on the keyed mark\n *\n * Touch: a tap shows the readout and it stays until the next tap elsewhere (a tap on\n * the chart background, or focus leaving the chart); a horizontal drag scrubs across\n * marks; vertical drags still scroll the page (`touch-action: pan-y`).\n */\nimport { useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent } from 'react'\n\nexport interface NavPos {\n  /** Primary index (period, row, bar). */\n  i: number\n  /** Secondary index (series, column); 0 when there is no cross axis. */\n  j: number\n}\n\ntype AnyPointer = PointerEvent<Element>\n\n/**\n * Handlers for one mark: pointer enter and tap set it, a mouse leaving clears it.\n * Touch and pen keep the readout after lifting (pointerleave is ignored for them).\n */\nexport function markHover<T>(set: (v: T | null) => void, value: T, { leave = true }: { leave?: boolean } = {}) {\n  return {\n    onPointerEnter: () => set(value),\n    onPointerDown: () => set(value),\n    onPointerLeave: leave\n      ? (e: AnyPointer) => {\n          if (e.pointerType === 'mouse') set(null)\n        }\n      : undefined,\n  }\n}\n\n/**\n * Keyboard navigation and touch persistence for a chart root.\n * - `axis: 'x'`: ←/→ step `i`, ↑/↓ step `j` (if `cross` > 0).\n * - `axis: 'y'`: ↑/↓ step `i`, ←/→ step `j` (rows × columns grids).\n * Home/End jump to the ends of `i`; Escape clears; blur clears.\n * `start` gives the position the first arrow press continues from (e.g. the hovered mark).\n */\nexport function useChartNav({\n  count,\n  cross = 0,\n  axis = 'x',\n  onMove,\n  onClear,\n  start,\n  crossDown = false,\n}: {\n  count: number\n  cross?: number\n  axis?: 'x' | 'y'\n  /** With `axis: 'x'`, ↓ (not ↑) steps `j` forward, for stacks drawn top to bottom. */\n  crossDown?: boolean\n  onMove: (p: NavPos) => void\n  onClear: () => void\n  start?: NavPos | null\n}) {\n  const [pos, setPos] = useState<NavPos | null>(null)\n  const touch = useRef(false)\n\n  const move = (p: NavPos) => {\n    setPos(p)\n    onMove(p)\n  }\n\n  const root = {\n    tabIndex: 0,\n    style: { touchAction: 'pan-y' } as CSSProperties,\n    onKeyDown: (e: KeyboardEvent<Element>) => {\n      if (count <= 0) return\n      const fwd = axis === 'x' ? 'ArrowRight' : 'ArrowDown'\n      const back = axis === 'x' ? 'ArrowLeft' : 'ArrowUp'\n      const cFwd = axis === 'x' ? (crossDown ? 'ArrowDown' : 'ArrowUp') : 'ArrowRight'\n      const cBack = axis === 'x' ? (crossDown ? 'ArrowUp' : 'ArrowDown') : 'ArrowLeft'\n      const cur = pos ?? (start && start.i < count ? start : null)\n      const j0 = Math.min(cur?.j ?? 0, Math.max(0, cross - 1))\n      let next: NavPos | null | undefined\n      if (e.key === fwd) next = cur ? { i: Math.min(count - 1, cur.i + (pos ? 1 : 0)), j: j0 } : { i: 0, j: 0 }\n      else if (e.key === back) next = cur ? { i: Math.max(0, cur.i - (pos ? 1 : 0)), j: j0 } : { i: count - 1, j: 0 }\n      else if (e.key === 'Home') next = { i: 0, j: j0 }\n      else if (e.key === 'End') next = { i: count - 1, j: j0 }\n      else if (cross > 1 && e.key === cFwd) next = cur ? { i: cur.i, j: Math.min(cross - 1, j0 + 1) } : { i: 0, j: 0 }\n      else if (cross > 1 && e.key === cBack) next = cur ? { i: cur.i, j: Math.max(0, j0 - 1) } : { i: 0, j: 0 }\n      else if (e.key === 'Escape') next = null\n      if (next === undefined) return\n      e.preventDefault()\n      if (next) move(next)\n      else {\n        setPos(null)\n        onClear()\n      }\n    },\n    onBlur: (e: { currentTarget: Element; relatedTarget: EventTarget | null }) => {\n      // Focus moving to a child of the chart (a focusable mark) is not leaving it.\n      if (e.relatedTarget instanceof Node && e.currentTarget.contains(e.relatedTarget)) return\n      setPos(null)\n      onClear()\n    },\n    onPointerDownCapture: (e: AnyPointer) => {\n      setPos(null)\n      touch.current = e.pointerType !== 'mouse'\n      if (!touch.current) return\n      // A tap on the background clears; a tap on a mark re-sets it in its own handler.\n      onClear()\n      // Touch captures the pointer to the first target; release it so a drag scrubs\n      // across marks (their pointerenter fires as the finger moves over them).\n      const t = e.target as Element\n      if (t.hasPointerCapture?.(e.pointerId)) t.releasePointerCapture(e.pointerId)\n    },\n    onPointerMove: (e: AnyPointer) => {\n      if (pos && e.pointerType === 'mouse') setPos(null)\n    },\n  }\n  const safe = pos && pos.i < count ? pos : null\n  return { pos: safe, root, isTouch: touch }\n}\n\n/** Release implicit touch capture so a drag scrubs over sibling marks. */\nexport function releaseTouch(e: AnyPointer) {\n  if (e.pointerType === 'mouse') return\n  const t = e.target as Element\n  if (t.hasPointerCapture?.(e.pointerId)) t.releasePointerCapture(e.pointerId)\n}\n\n/**\n * Explicit SVG focus ring (SVG marks do not draw CSS outlines reliably).\n *   {nav.pos && <rect {...ringRect(x, y, w, h)} />}\n */\nexport function ringRect(x: number, y: number, width: number, height: number, { rx = 4, pad = 2 }: { rx?: number; pad?: number } = {}) {\n  return {\n    x: x - pad,\n    y: y - pad,\n    width: Math.max(0, width + pad * 2),\n    height: Math.max(0, height + pad * 2),\n    rx,\n    fill: 'none',\n    stroke: 'var(--accent)',\n    strokeWidth: 2,\n    pointerEvents: 'none' as const,\n    'data-focus-ring': '',\n  }\n}\n\n/** Focus ring for a circular mark: `<circle {...ringCircle(cx, cy, r)} />`. */\nexport function ringCircle(cx: number, cy: number, r: number) {\n  return { cx, cy, r: r + 3, fill: 'none', stroke: 'var(--accent)', strokeWidth: 2, pointerEvents: 'none' as const, 'data-focus-ring': '' }\n}\n\n/** Root-level focus style for charts not inside `.klar` (which already draws one). */\nexport const FOCUS_ROOT = 'outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent'\n",
      "type": "registry:component",
      "target": "@components/klar/charts/bi/interaction.ts"
    },
    {
      "path": "registry/klar/components/charts/finance/parts.tsx",
      "content": "import type { ReactNode } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\n\n/** Floating readout card used by every finance chart. Flips at the right edge. */\nexport function Tip({\n  x,\n  y,\n  width,\n  title,\n  rows,\n  footer,\n  w = 196,\n  anchor = 'middle',\n}: {\n  x: number\n  y: number\n  /** Container width, for flipping. */\n  width: number\n  title: ReactNode\n  rows: { label: ReactNode; value: ReactNode; color?: string; dashed?: boolean; strong?: boolean }[]\n  footer?: ReactNode\n  w?: number\n  anchor?: 'middle' | 'top'\n}) {\n  const flip = x + w + 18 > width\n  return (\n    <div\n      className=\"pointer-events-none absolute z-30 rounded-xl border border-border-strong bg-surface/95 px-3 py-2.5 shadow-pop backdrop-blur-sm\"\n      style={{\n        left: x,\n        top: y,\n        width: w,\n        transform: `translate(${flip ? 'calc(-100% - 14px)' : '14px'}, ${anchor === 'middle' ? '-50%' : '0'})`,\n      }}\n    >\n      <div className=\"mb-1.5 text-[11px] font-medium text-fg-3\">{title}</div>\n      <div className=\"flex flex-col gap-[5px]\">\n        {rows.map((r, i) => (\n          <div key={i} className=\"flex items-center justify-between gap-3 text-[12px] leading-4\">\n            <span className=\"flex min-w-0 items-center gap-1.5 text-fg-2\">\n              {r.color &&\n                (r.dashed ? (\n                  <span className=\"w-2.5 border-t-[1.5px] border-dashed\" style={{ borderColor: r.color }} />\n                ) : (\n                  <span className=\"size-2 shrink-0 rounded-[2px]\" style={{ background: r.color }} />\n                ))}\n              <span className=\"truncate\">{r.label}</span>\n            </span>\n            <span className={cn('num shrink-0 text-fg', r.strong ? 'font-semibold' : 'font-medium')}>{r.value}</span>\n          </div>\n        ))}\n      </div>\n      {footer && <div className=\"mt-2 border-t border-border pt-1.5 text-[11px] text-fg-3\">{footer}</div>}\n    </div>\n  )\n}\n\n/** Label/value pair for a chart's readout strip. */\nexport function Stat({\n  label,\n  children,\n  color,\n  className,\n}: {\n  label: ReactNode\n  children: ReactNode\n  color?: string\n  className?: string\n}) {\n  return (\n    <span className={cn('inline-flex items-baseline gap-1.5 whitespace-nowrap', className)}>\n      <span className=\"text-[10.5px] font-medium tracking-[0.04em] text-fg-3 uppercase\">{label}</span>\n      <span className=\"num text-[12px] font-medium text-fg\" style={color ? { color } : undefined}>\n        {children}\n      </span>\n    </span>\n  )\n}\n\n/** A filled value tag on an axis gutter (last price, crosshair price, date). */\nexport function AxisTag({\n  x,\n  y,\n  text,\n  fill,\n  color = 'var(--surface)',\n  align = 'left',\n  w,\n  h = 17,\n}: {\n  x: number\n  y: number\n  text: string\n  fill: string\n  color?: string\n  align?: 'left' | 'center' | 'right'\n  w?: number\n  h?: number\n}) {\n  const width = w ?? text.length * 6.4 + 12\n  const x0 = align === 'left' ? x : align === 'center' ? x - width / 2 : x - width\n  return (\n    <g pointerEvents=\"none\">\n      <rect x={x0} y={y - h / 2} width={width} height={h} rx={3.5} fill={fill} />\n      <text x={x0 + width / 2} y={y + 3.8} textAnchor=\"middle\" className=\"num text-[11px] font-semibold\" fill={color}>\n        {text}\n      </text>\n    </g>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/finance/parts.tsx"
    },
    {
      "path": "registry/klar/components/charts/finance/util.ts",
      "content": "/*\n * Shared helpers for the finance chart collection: scales, nice ticks,\n * pointer mapping that survives scaled previews, date labels and colour\n * ramps (CSS color-mix for SVG, resolved RGB for canvas).\n */\nimport type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react'\nimport { formatter } from '@/components/klar/charts/basic/core'\n\nexport const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v))\n\n/** Linear map from a domain to a range. */\nexport function scale(d0: number, d1: number, r0: number, r1: number) {\n  const k = d1 === d0 ? 0 : (r1 - r0) / (d1 - d0)\n  return (v: number) => r0 + (v - d0) * k\n}\n\n/** A \"nice\" step (1, 2, 2.5, 5 × 10^n) close to span / count. */\nexport function niceStep(span: number, count: number) {\n  const raw = span / Math.max(1, count)\n  const exp = Math.pow(10, Math.floor(Math.log10(raw || 1)))\n  const f = raw / exp\n  const n = f < 1.5 ? 1 : f < 2.25 ? 2 : f < 3.5 ? 2.5 : f < 7.5 ? 5 : 10\n  return n * exp\n}\n\n/** Nice ticks covering [lo, hi] (inclusive of ticks inside the range only). */\nexport function ticks(lo: number, hi: number, count = 5) {\n  const step = niceStep(hi - lo, count)\n  const start = Math.ceil(lo / step - 1e-9) * step\n  const out: number[] = []\n  // `+ 0` turns -0 (from Math.ceil of a tiny negative) into 0, so formatters never print \"-0\".\n  for (let v = start; v <= hi + step * 1e-9; v += step) out.push(Math.round(v / step) * step + 0)\n  return out\n}\n\n/** Expand [lo, hi] outwards to the nearest nice step. */\nexport function niceDomain(lo: number, hi: number, count = 5): [number, number] {\n  const step = niceStep(hi - lo, count)\n  return [Math.floor(lo / step) * step, Math.ceil(hi / step) * step]\n}\n\n/** Decimals needed to print a tick step without noise. */\nexport const decimalsFor = (step: number) => Math.max(0, Math.min(6, -Math.floor(Math.log10(step) + 1e-9)))\n\n/**\n * Pointer position in the element's own (unscaled) pixel space, so hover works\n * inside the atlas' scaled previews too.\n */\nexport function pointer(e: { clientX: number; clientY: number }, el: Element, width: number): [number, number] {\n  const r = el.getBoundingClientRect()\n  const s = width ? r.width / width || 1 : 1\n  return [(e.clientX - r.left) / s, (e.clientY - r.top) / s]\n}\n\nexport const mix = (a: string, b: string, pct: number) =>\n  `color-mix(in oklab, ${a} ${Math.round(clamp(pct, 0, 100))}%, ${b})`\n\n/**\n * Diverging colour for t in [-1, 1]: neg ↔ mid ↔ pos. `gamma` < 1 lifts small\n * values so a ±0.3% move is still visibly tinted.\n */\nexport function diverging(\n  t: number,\n  { neg = 'var(--red)', pos = 'var(--green)', mid = 'var(--surface-3)', gamma = 0.8 } = {},\n) {\n  const a = Math.pow(clamp(Math.abs(t), 0, 1), gamma)\n  return mix(t < 0 ? neg : pos, mid, a * 100)\n}\n\n/* ------------------------------------------------------------------ */\n/*  Dates                                                             */\n/* ------------------------------------------------------------------ */\n\nexport const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\nconst DOW = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\n\n/** Parses 'YYYY-MM-DD' as a UTC date (no timezone drift). */\nexport function day(s: string) {\n  const [y, m, d] = s.split('-').map(Number)\n  return new Date(Date.UTC(y, (m || 1) - 1, d || 1))\n}\nexport const iso = (d: Date) => d.toISOString().slice(0, 10)\n\n/** True when output should follow the built-in English labels (today's output). */\nconst english = (locale?: string) => !locale || locale === 'en-US'\n\nconst dtfCache = new Map<string, Intl.DateTimeFormat>()\nconst dtf = (locale: string, o: Intl.DateTimeFormatOptions) => {\n  const key = locale + JSON.stringify(o)\n  let f = dtfCache.get(key)\n  if (!f) dtfCache.set(key, (f = new Intl.DateTimeFormat(locale, { ...o, timeZone: 'UTC' })))\n  return f\n}\n\n/** \"Mar 4, 2026\"; with a non-English `locale`, the locale's own short date (\"4. März 2026\"). */\nexport const fmtDate = (s: string, withYear = true, locale?: string) => {\n  const d = day(s)\n  if (!english(locale)) return dtf(locale!, { month: 'short', day: 'numeric', ...(withYear ? { year: 'numeric' } : {}) }).format(d)\n  return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}${withYear ? `, ${d.getUTCFullYear()}` : ''}`\n}\nexport const fmtDateDow = (s: string, locale?: string) => {\n  const d = day(s)\n  if (!english(locale)) return dtf(locale!, { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' }).format(d)\n  return `${DOW[d.getUTCDay()]} ${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`\n}\n/** Short month name for a 0-based month ('Mar'; 'März' in de-DE). */\nexport const monthLabel = (m: number, locale?: string) =>\n  english(locale) ? MONTHS[m] : dtf(locale!, { month: 'short' }).format(new Date(Date.UTC(2000, m, 1)))\n\n/** Business days (Mon–Fri) from start, `n` of them. */\nexport function businessDays(start: string, n: number) {\n  const out: string[] = []\n  const d = day(start)\n  while (out.length < n) {\n    const w = d.getUTCDay()\n    if (w !== 0 && w !== 6) out.push(iso(d))\n    d.setUTCDate(d.getUTCDate() + 1)\n  }\n  return out\n}\n\n/** Days between two ISO dates. */\nexport const daysBetween = (a: string, b: string) => Math.round((day(b).getTime() - day(a).getTime()) / 864e5)\n\n/* ------------------------------------------------------------------ */\n/*  Numbers                                                           */\n/* ------------------------------------------------------------------ */\n\n/** Fixed decimals with grouping, via `formatter(locale)` (default en-US: \"12,480.50\"). */\nexport const fixed = (v: number, d = 2, locale = 'en-US') => formatter(locale).number(v, d)\n\nexport const signed = (v: number, d = 2, unit = '', locale = 'en-US') =>\n  `${v > 0 ? '+' : v < 0 ? '−' : '±'}${fixed(Math.abs(v), d, locale)}${unit}`\n\nexport const compact = (v: number, d = 1, locale = 'en-US') => {\n  const a = Math.abs(v)\n  const s = a >= 1e12 ? [1e12, 'T'] : a >= 1e9 ? [1e9, 'B'] : a >= 1e6 ? [1e6, 'M'] : a >= 1e3 ? [1e3, 'K'] : [1, '']\n  return `${v < 0 ? '−' : ''}${fixed(a / (s[0] as number), s[1] ? d : 0, locale)}${s[1]}`\n}\n\n/** A tick value as plain text: `String(v)` by default (today's output), localised when `locale` is set. */\nexport const plain = (v: number, locale?: string) =>\n  english(locale) ? String(v) : new Intl.NumberFormat(locale, { maximumFractionDigits: 6 }).format(v)\n\n/* ------------------------------------------------------------------ */\n/*  Pointer and keyboard                                              */\n/* ------------------------------------------------------------------ */\n\n/**\n * Pointer handlers for a plot that reads the position itself (crosshair charts).\n * Mouse and hovering pens track on move and clear on leave; touch shows the readout\n * on tap and keeps it after lifting, a drag scrubs, and `touch-action: pan-y` keeps\n * vertical page scrolling.\n */\nexport function plotPointer(width: number, at: (x: number, y: number) => void, clear: () => void) {\n  const locate = (e: ReactPointerEvent<HTMLElement>) => {\n    const [x, y] = pointer(e, e.currentTarget, width)\n    at(x, y)\n  }\n  return {\n    onPointerDown: locate,\n    onPointerMove: (e: ReactPointerEvent<HTMLElement>) => {\n      if (e.pointerType !== 'touch' || e.buttons > 0) locate(e)\n    },\n    onPointerLeave: (e: ReactPointerEvent<HTMLElement>) => {\n      if (e.pointerType !== 'touch') clear()\n    },\n    onPointerCancel: clear,\n    style: { touchAction: 'pan-y' } as CSSProperties,\n  }\n}\n\n/**\n * Next index for a keyboard step along `n` marks: ←/→ (or ↑/↓ with `vertical`),\n * Shift for `big` steps, Home/End; `null` for Escape; `undefined` for other keys.\n */\nexport function stepKey(e: { key: string; shiftKey: boolean }, cur: number | null, n: number, { big = 5, from = 0, vertical = false } = {}) {\n  const fwd = vertical ? 'ArrowDown' : 'ArrowRight'\n  const back = vertical ? 'ArrowUp' : 'ArrowLeft'\n  const k = e.shiftKey ? big : 1\n  if (e.key === fwd) return cur == null ? clamp(from, 0, n - 1) : Math.min(n - 1, cur + k)\n  if (e.key === back) return cur == null ? clamp(from, 0, n - 1) : Math.max(0, cur - k)\n  if (e.key === 'Home') return 0\n  if (e.key === 'End') return n - 1\n  if (e.key === 'Escape') return null\n  return undefined\n}\n\n/** Standard normal draws from a seeded uniform source (Box–Muller). */\nexport function gauss(rnd: () => number) {\n  const u = Math.max(1e-9, rnd())\n  const v = rnd()\n  return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v)\n}\n\n/* ------------------------------------------------------------------ */\n/*  Canvas colour                                                     */\n/* ------------------------------------------------------------------ */\n\nexport type RGB = [number, number, number]\n\nexport function parseColor(s: string): RGB {\n  const v = s.trim()\n  if (v.startsWith('#')) {\n    const h = v.length === 4 ? v.slice(1).replace(/./g, (c) => c + c) : v.slice(1, 7)\n    return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)]\n  }\n  const m = v.match(/[\\d.]+/g)\n  return m ? [Number(m[0]), Number(m[1]), Number(m[2])] : [128, 128, 128]\n}\n\n/** Resolves a token like '--blue' on an element to RGB. */\nexport const readVar = (el: Element, name: string) => parseColor(getComputedStyle(el).getPropertyValue(name) || '#888')\n\nconst toLin = (c: number) => {\n  const x = c / 255\n  return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4)\n}\nconst toSrgb = (x: number) => 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055)\n\n/** Interpolates a multi-stop ramp in linear light (smooth, no muddy midpoints). */\nexport function rampAt(stops: RGB[], t: number): RGB {\n  const tt = clamp(t, 0, 1) * (stops.length - 1)\n  const i = Math.min(stops.length - 2, Math.floor(tt))\n  const f = tt - i\n  const a = stops[i]\n  const b = stops[i + 1]\n  return [0, 1, 2].map((k) => toSrgb(toLin(a[k]) * (1 - f) + toLin(b[k]) * f)) as RGB\n}\n\nexport const rgb = (c: RGB, a = 1) => `rgba(${Math.round(c[0])}, ${Math.round(c[1])}, ${Math.round(c[2])}, ${a})`\n",
      "type": "registry:component",
      "target": "@components/klar/charts/finance/util.ts"
    },
    {
      "path": "registry/klar/components/charts/basic/core.tsx",
      "content": "/**\n * Shared foundation for the basic charts: scales, ticks, locale-aware formatting,\n * pointer (mouse + touch + pen) hover tracking, axes, legend and tooltip.\n * Advanced charts can use it too.\n */\nimport { useCallback, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\n\n/* ------------------------------------------------------------------ */\n/*  Scales and ticks                                                  */\n/* ------------------------------------------------------------------ */\n\nexport interface LinearScale {\n  (v: number): number\n  invert: (px: number) => number\n  domain: [number, number]\n  range: [number, number]\n  ticks: number[]\n}\n\n/** \"Nice\" tick values covering [min, max] with about `count` steps. */\nexport function niceTicks(min: number, max: number, count = 5): number[] {\n  if (!isFinite(min) || !isFinite(max)) return [0]\n  if (min === max) {\n    max = min + (Math.abs(min) || 1)\n  }\n  const span = max - min\n  const raw = span / Math.max(1, count)\n  const mag = Math.pow(10, Math.floor(Math.log10(raw)))\n  const norm = raw / mag\n  const step = (norm >= 7.5 ? 10 : norm >= 3.5 ? 5 : norm >= 1.5 ? 2 : 1) * mag\n  const start = Math.floor(min / step) * step\n  const end = Math.ceil(max / step) * step\n  const out: number[] = []\n  for (let v = start; v <= end + step * 1e-6; v += step) out.push(+v.toPrecision(12))\n  return out\n}\n\n/**\n * Linear scale. With `nice` (default) the domain is widened to round tick values.\n * `zero` forces the domain to include 0 (right for bars, optional for lines).\n */\nexport function linearScale(\n  domain: [number, number],\n  range: [number, number],\n  { nice = true, zero = false, ticks = 5 }: { nice?: boolean; zero?: boolean; ticks?: number } = {},\n): LinearScale {\n  let [d0, d1] = domain\n  if (zero) {\n    d0 = Math.min(0, d0)\n    d1 = Math.max(0, d1)\n  }\n  let t = niceTicks(d0, d1, ticks)\n  if (nice) {\n    d0 = t[0]\n    d1 = t[t.length - 1]\n  } else {\n    t = t.filter((v) => v >= d0 - 1e-9 && v <= d1 + 1e-9)\n  }\n  const [r0, r1] = range\n  const k = d1 === d0 ? 0 : (r1 - r0) / (d1 - d0)\n  const scale = ((v: number) => r0 + (v - d0) * k) as LinearScale\n  scale.invert = (px) => (k === 0 ? d0 : d0 + (px - r0) / k)\n  scale.domain = [d0, d1]\n  scale.range = [r0, r1]\n  scale.ticks = t\n  return scale\n}\n\nexport interface BandScale {\n  (i: number): number\n  bandwidth: number\n  step: number\n  /** Index of the band containing a pixel position (clamped). */\n  indexAt: (px: number) => number\n}\n\n/** Evenly spaced bands for `count` categories; `padding` is the gap fraction per step. */\nexport function bandScale(count: number, range: [number, number], padding = 0.3): BandScale {\n  const [r0, r1] = range\n  const step = count > 0 ? (r1 - r0) / count : 0\n  const bandwidth = step * (1 - padding)\n  const scale = ((i: number) => r0 + step * i + (step - bandwidth) / 2) as BandScale\n  scale.bandwidth = bandwidth\n  scale.step = step\n  scale.indexAt = (px) => Math.max(0, Math.min(count - 1, Math.floor((px - r0) / (step || 1))))\n  return scale\n}\n\nexport const extent = (values: number[]): [number, number] => {\n  let lo = Infinity\n  let hi = -Infinity\n  for (const v of values) {\n    if (v == null || !isFinite(v)) continue\n    if (v < lo) lo = v\n    if (v > hi) hi = v\n  }\n  return lo === Infinity ? [0, 1] : [lo, hi]\n}\n\n/* ------------------------------------------------------------------ */\n/*  Locale-aware formatting                                           */\n/* ------------------------------------------------------------------ */\n\nexport interface Formatter {\n  /** 12,480 */\n  number: (v: number, digits?: number) => string\n  /** 12.5K, 3.2M */\n  compact: (v: number) => string\n  /** 34.5% from 0.345 */\n  percent: (v: number, digits?: number) => string\n  currency: (v: number, digits?: number) => string\n  /** $1.2M */\n  currencyCompact: (v: number) => string\n  /** Signed: +4.2 / −4.2 */\n  delta: (v: number, digits?: number) => string\n  date: (d: Date | string | number, opts?: Intl.DateTimeFormatOptions) => string\n}\n\nconst cache = new Map<string, Formatter>()\n\n/**\n * Formatter bound to a locale and currency. Pass `locale` to any basic chart to\n * localise every label, e.g. `formatter('de-DE', 'EUR').currency(1234.5)` → \"1.234,50 €\".\n */\nexport function formatter(locale = 'en-US', currency = 'USD'): Formatter {\n  const key = `${locale}|${currency}`\n  const hit = cache.get(key)\n  if (hit) return hit\n  const nf = (o: Intl.NumberFormatOptions) => new Intl.NumberFormat(locale, o)\n  const compact = nf({ notation: 'compact', maximumFractionDigits: 1 })\n  const curCompact = nf({ style: 'currency', currency, notation: 'compact', maximumFractionDigits: 1 })\n  const f: Formatter = {\n    number: (v, digits = 0) => nf({ minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    compact: (v) => compact.format(v),\n    percent: (v, digits = 0) => nf({ style: 'percent', minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    currency: (v, digits = 0) => nf({ style: 'currency', currency, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    currencyCompact: (v) => curCompact.format(v),\n    delta: (v, digits = 1) => (v > 0 ? '+' : v < 0 ? '−' : '') + nf({ minimumFractionDigits: digits, maximumFractionDigits: digits }).format(Math.abs(v)),\n    date: (d, opts = { month: 'short', day: 'numeric' }) => new Intl.DateTimeFormat(locale, opts).format(new Date(d)),\n  }\n  cache.set(key, f)\n  return f\n}\n\n/* ------------------------------------------------------------------ */\n/*  Pointer hover (mouse, touch and pen)                              */\n/* ------------------------------------------------------------------ */\n\nexport interface HoverPoint {\n  /** Position inside the element, in its own (unscaled) pixels. */\n  x: number\n  y: number\n}\n\n/**\n * Tracks the pointer over a chart for mouse, touch and pen alike.\n * Spread `bind` on the plot container. On touch, a tap or drag shows the readout\n * and it stays until the next tap elsewhere; on mouse it clears on leave.\n */\nexport function usePointerHover<T extends HTMLElement | SVGElement = HTMLDivElement>() {\n  const [point, setPoint] = useState<HoverPoint | null>(null)\n  const touch = useRef(false)\n\n  const locate = useCallback((e: PointerEvent<T>) => {\n    const el = e.currentTarget as unknown as HTMLElement\n    const r = el.getBoundingClientRect()\n    // Compensate for ancestor CSS transforms (scaled previews).\n    const sx = el.offsetWidth ? r.width / el.offsetWidth : 1\n    const sy = el.offsetHeight ? r.height / el.offsetHeight : 1\n    setPoint({ x: (e.clientX - r.left) / (sx || 1), y: (e.clientY - r.top) / (sy || 1) })\n  }, [])\n\n  const bind = {\n    onPointerDown: (e: PointerEvent<T>) => {\n      touch.current = e.pointerType !== 'mouse'\n      locate(e)\n    },\n    onPointerMove: (e: PointerEvent<T>) => {\n      if (e.pointerType === 'mouse' || e.buttons > 0 || e.pressure > 0) locate(e)\n    },\n    onPointerLeave: (e: PointerEvent<T>) => {\n      if (e.pointerType === 'mouse') setPoint(null)\n    },\n    onPointerCancel: () => setPoint(null),\n    style: { touchAction: 'pan-y' } as CSSProperties,\n  }\n  return { point, bind, clear: () => setPoint(null), isTouch: touch }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Axes (SVG)                                                        */\n/* ------------------------------------------------------------------ */\n\n/** Horizontal gridlines with value labels on the left. */\nexport function AxisY({\n  scale,\n  x0,\n  x1,\n  format = String,\n  grid = true,\n  side = 'left',\n  label,\n}: {\n  scale: LinearScale\n  /** Left and right pixel edges of the plot. */\n  x0: number\n  x1: number\n  format?: (v: number) => string\n  grid?: boolean\n  side?: 'left' | 'right'\n  label?: string\n}) {\n  return (\n    <g aria-hidden>\n      {scale.ticks.map((t) => {\n        const y = scale(t)\n        const zero = t === 0\n        return (\n          <g key={t}>\n            {grid && (\n              <line\n                x1={x0}\n                x2={x1}\n                y1={y}\n                y2={y}\n                stroke={zero ? 'var(--border-strong)' : 'var(--border)'}\n                strokeDasharray={zero || t === scale.ticks[0] ? undefined : '3 4'}\n              />\n            )}\n            <text\n              x={side === 'left' ? x0 - 10 : x1 + 10}\n              y={y + 4}\n              textAnchor={side === 'left' ? 'end' : 'start'}\n              className=\"num fill-fg-3 text-[11px]\"\n            >\n              {format(t)}\n            </text>\n          </g>\n        )\n      })}\n      {label && (\n        <text x={side === 'left' ? x0 - 10 : x1 + 10} y={scale.range[1] - 12} textAnchor={side === 'left' ? 'end' : 'start'} className=\"fill-fg-4 text-[10.5px]\">\n          {label}\n        </text>\n      )}\n    </g>\n  )\n}\n\n/** Category or tick labels under the plot. Skips labels that would collide. */\nexport function AxisX({\n  labels,\n  y,\n  minGap = 8,\n  charWidth = 6.2,\n}: {\n  labels: { x: number; text: string; anchor?: 'start' | 'middle' | 'end' }[]\n  y: number\n  minGap?: number\n  charWidth?: number\n}) {\n  let lastEnd = -Infinity\n  return (\n    <g aria-hidden>\n      {labels.map((l, i) => {\n        const w = l.text.length * charWidth\n        const start = l.anchor === 'start' ? l.x : l.anchor === 'end' ? l.x - w : l.x - w / 2\n        if (start < lastEnd + minGap) return null\n        lastEnd = start + w\n        return (\n          <text key={i} x={l.x} y={y} textAnchor={l.anchor ?? 'middle'} className=\"fill-fg-3 text-[11px]\">\n            {l.text}\n          </text>\n        )\n      })}\n    </g>\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Legend and tooltip (HTML)                                         */\n/* ------------------------------------------------------------------ */\n\nexport interface LegendItem {\n  id: string\n  label: ReactNode\n  color: string\n  value?: ReactNode\n  /** line | bar | dot | dash */\n  mark?: 'line' | 'bar' | 'dot' | 'dash'\n}\n\n/** Legend whose items can be hovered (to highlight) and clicked (to toggle). */\nexport function ChartLegend({\n  items,\n  active,\n  hidden,\n  onHover,\n  onToggle,\n  className,\n}: {\n  items: LegendItem[]\n  active?: string | null\n  hidden?: Set<string>\n  onHover?: (id: string | null) => void\n  onToggle?: (id: string) => void\n  className?: string\n}) {\n  return (\n    <div className={cn('flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[12px] text-fg-2', className)}>\n      {items.map((it) => {\n        const off = hidden?.has(it.id)\n        const dim = active != null && active !== it.id\n        return (\n          <button\n            key={it.id}\n            type=\"button\"\n            aria-pressed={onToggle ? !off : undefined}\n            onPointerEnter={() => onHover?.(it.id)}\n            onPointerLeave={() => onHover?.(null)}\n            onFocus={() => onHover?.(it.id)}\n            onBlur={() => onHover?.(null)}\n            onClick={() => onToggle?.(it.id)}\n            className={cn('inline-flex items-center gap-1.5 rounded-md transition-opacity', (dim || off) && 'opacity-40', !onToggle && 'cursor-default')}\n          >\n            <span\n              className={cn(\n                'shrink-0',\n                it.mark === 'line' ? 'h-[2.5px] w-3.5 rounded-full' : it.mark === 'dash' ? 'h-0 w-3.5 border-t-2 border-dashed' : it.mark === 'bar' ? 'size-2.5 rounded-[3px]' : 'size-2 rounded-full',\n              )}\n              style={it.mark === 'dash' ? { borderColor: it.color } : { background: it.color }}\n            />\n            <span className={off ? 'line-through' : undefined}>{it.label}</span>\n            {it.value != null && <span className=\"num text-fg-3\">{it.value}</span>}\n          </button>\n        )\n      })}\n    </div>\n  )\n}\n\n/**\n * Tooltip card positioned inside a `relative` chart container. It flips to stay\n * inside `containerWidth` and never captures the pointer.\n */\nexport function ChartTooltip({\n  x,\n  y,\n  containerWidth,\n  title,\n  rows,\n  footer,\n  width = 170,\n}: {\n  x: number\n  y: number\n  containerWidth: number\n  title?: ReactNode\n  rows: { label: ReactNode; value: ReactNode; color?: string; strong?: boolean }[]\n  footer?: ReactNode\n  width?: number\n}) {\n  const flip = x > containerWidth - width - 24\n  return (\n    <div\n      role=\"status\"\n      className=\"pointer-events-none absolute z-30 rounded-xl border border-border bg-surface px-3 py-2.5 shadow-pop\"\n      style={{ left: x, top: Math.max(0, y), minWidth: width - 20, transform: `translate(${flip ? 'calc(-100% - 12px)' : '12px'}, -50%)` }}\n    >\n      {title != null && <div className=\"mb-1.5 text-[11.5px] font-medium text-fg-3\">{title}</div>}\n      <div className=\"flex flex-col gap-1\">\n        {rows.map((r, i) => (\n          <div key={i} className=\"flex items-center justify-between gap-5 text-[12.5px]\">\n            <span className=\"flex items-center gap-1.5 text-fg-2\">\n              {r.color && <span className=\"size-2 rounded-full\" style={{ background: r.color }} />}\n              {r.label}\n            </span>\n            <span className={cn('num text-fg', r.strong === false ? 'font-medium' : 'font-semibold')}>{r.value}</span>\n          </div>\n        ))}\n      </div>\n      {footer != null && <div className=\"mt-2 border-t border-border pt-1.5 text-[11.5px] text-fg-3\">{footer}</div>}\n    </div>\n  )\n}\n\n/** Default categorical palette, in order. */\nexport const PALETTE = ['var(--blue)', 'var(--orange)', 'var(--teal)', 'var(--violet)', 'var(--pink)', 'var(--amber)', 'var(--green)', 'var(--sky)']\n",
      "type": "registry:component",
      "target": "@components/klar/charts/basic/core.tsx"
    },
    {
      "path": "registry/klar/components/charts/bars.tsx",
      "content": "import { isValidElement, useState, type ReactNode } from 'react'\nimport { ArrowUp } from 'lucide-react'\nimport { cn } from '@/components/klar/lib/cn'\nimport { useMeasure } from '@/components/klar/lib/use-measure'\nimport { ChartDataTable } from '@/components/klar/charts/a11y'\nimport { formatter } from '@/components/klar/charts/basic/core'\nimport { markHover, ringRect, useChartNav } from '@/components/klar/charts/bi/interaction'\n\n/** Plain text of a ReactNode label (for aria-labels, tables and CSV). */\nfunction textOf(n: ReactNode): string {\n  if (n == null || typeof n === 'boolean') return ''\n  if (typeof n === 'string' || typeof n === 'number') return String(n)\n  if (Array.isArray(n)) return n.map(textOf).join('')\n  if (isValidElement<{ children?: ReactNode }>(n)) return textOf(n.props.children)\n  return ''\n}\n\n/** Max without spreading (spread throws on very large arrays). */\nfunction maxOf(values: number[], floor = -Infinity) {\n  let m = floor\n  for (const v of values) if (v > m) m = v\n  return m\n}\n\n/* ------------------------------------------------------------------ */\n/*  HatchColumns: tall columns on a hatched track with the value as a */\n/*  solid fill, optional dashed target line and a callout pin.        */\n/*  (Tessera \"Team performance\", Insights \"Conversion\")               */\n/* ------------------------------------------------------------------ */\n\nexport interface HatchColumn {\n  label: ReactNode\n  value: number // 0..100\n  color: string\n  /** Text drawn inside the bottom of the fill. Defaults to `${value}%`. */\n  display?: ReactNode\n  /** Small pill pinned above the fill, e.g. \"↑ 12%\". */\n  callout?: ReactNode\n  /** Label shown in a floating chip at the fill top, Insights-style. */\n  chip?: ReactNode\n  textColor?: string\n  highlight?: boolean\n}\n\n/**\n * Comfortable with 2–12 columns (each is a flex child; past ~20 they get too thin to read).\n * HTML, not SVG: PNG/SVG export does not capture it; use `hatchColumnsToRows` for CSV.\n */\nexport function HatchColumns({\n  data,\n  height = 250,\n  target,\n  targetLabel,\n  gap = 14,\n  radius = 10,\n  axis,\n  fillStyle = 'solid',\n  className,\n  locale,\n  ariaLabel,\n}: {\n  data: HatchColumn[]\n  height?: number\n  target?: number\n  targetLabel?: ReactNode\n  gap?: number\n  radius?: number\n  /** Show a 0–100% y axis on the left. */\n  axis?: boolean\n  /** \"gradient\" fades the fill downward (Insights highlight bar). */\n  fillStyle?: 'solid' | 'gradient'\n  className?: string\n  /** Formats the default value text and axis ticks (default: \"12%\" as today). */\n  locale?: string\n  ariaLabel?: string\n}) {\n  const pct = (v: number) => (locale ? formatter(locale).percent(v / 100, Number.isInteger(v) ? 0 : 1) : `${v}%`)\n  const rows = hatchColumnsToRows(data)\n  const label = ariaLabel ?? `Columns: ${rows.map((r) => `${r.label} ${pct(r.value)}`).join(', ')}${target != null ? `; target ${pct(target)}` : ''}`\n  return (\n    <div role=\"figure\" aria-label={label} className={cn('flex flex-col', className)}>\n      <ChartDataTable\n        caption={label}\n        columns={[\n          { key: 'label', label: 'Column' },\n          { key: 'value', label: 'Value', format: (v) => pct(Number(v)) },\n        ]}\n        rows={rows}\n      />\n      <div className=\"flex\">\n        {axis && (\n          <div\n            className=\"relative mr-3 w-9 shrink-0 text-right text-[11.5px] text-fg-3\"\n            style={{ height }}\n          >\n            {[100, 50, 25, 0].map((t) => (\n              <span\n                key={t}\n                className=\"num absolute right-0 -translate-y-1/2\"\n                style={{ top: `${100 - t}%` }}\n              >\n                {pct(t)}\n              </span>\n            ))}\n            {target != null && (\n              <span\n                className=\"num absolute right-0 -translate-y-1/2 rounded-full bg-orange px-1.5 py-0.5 text-[10.5px] font-semibold text-white\"\n                style={{ top: `${100 - target}%` }}\n              >\n                {pct(target)}\n              </span>\n            )}\n          </div>\n        )}\n        <div className=\"relative flex flex-1 items-end\" style={{ height, gap }}>\n          {target != null && (\n            <div\n              className=\"pointer-events-none absolute inset-x-0 z-10 flex items-center\"\n              style={{ bottom: `${target}%` }}\n            >\n              <div\n                className=\"h-0 flex-1 border-t-[1.5px] border-dashed\"\n                style={{ borderColor: axis ? 'var(--orange)' : 'var(--fg-4)' }}\n              />\n              {targetLabel && (\n                <span className=\"ml-1 rounded-md border border-border bg-surface px-1.5 py-0.5 text-[10.5px] whitespace-nowrap text-fg-2 shadow-btn\">\n                  {targetLabel}\n                </span>\n              )}\n            </div>\n          )}\n          {data.map((d, i) => {\n            const textColor = d.textColor ?? (d.value > 20 ? '#fff' : 'var(--fg)')\n            return (\n              <div key={i} className=\"relative h-full flex-1\">\n                <div\n                  className=\"hatch absolute inset-0 border border-border/60 bg-surface-2/60\"\n                  style={{ borderRadius: radius }}\n                />\n                <div\n                  className=\"anim-grow-y absolute inset-x-0 bottom-0 flex items-end overflow-hidden\"\n                  style={{\n                    height: `${Math.max(d.value, 0)}%`,\n                    borderRadius: radius,\n                    background:\n                      fillStyle === 'gradient'\n                        ? `linear-gradient(180deg, ${d.color}, color-mix(in oklab, ${d.color} 25%, transparent))`\n                        : d.color,\n                    animationDelay: `${i * 70}ms`,\n                  }}\n                >\n                  {!d.chip && (\n                    <span\n                      className=\"num px-3 pb-2.5 text-[13px] font-semibold\"\n                      style={{ color: textColor }}\n                    >\n                      {d.display ?? pct(d.value)}\n                    </span>\n                  )}\n                </div>\n                {d.chip && (\n                  <div\n                    className=\"absolute inset-x-1.5 z-20 flex justify-center\"\n                    style={{ bottom: `calc(${d.value}% - 18px)` }}\n                  >\n                    <span\n                      className={cn(\n                        'num inline-flex h-9 items-center gap-1.5 rounded-[10px] px-3 text-[14px] font-semibold whitespace-nowrap shadow-btn',\n                        d.highlight\n                          ? 'text-white'\n                          : 'border border-border bg-surface text-fg',\n                      )}\n                      style={d.highlight ? { background: d.color } : undefined}\n                    >\n                      {d.chip}\n                    </span>\n                  </div>\n                )}\n                {d.callout && (\n                  <div\n                    className=\"absolute inset-x-0 z-20 flex justify-center\"\n                    style={{ bottom: `calc(${d.value}% + 8px)` }}\n                  >\n                    <span className=\"relative inline-flex items-center gap-0.5 rounded-full border border-border bg-surface px-2 py-0.5 text-[11px] font-semibold text-fg shadow-pop\">\n                      {d.callout}\n                    </span>\n                  </div>\n                )}\n              </div>\n            )\n          })}\n        </div>\n      </div>\n      <div className=\"mt-3 flex\" style={{ gap, marginLeft: axis ? 48 : 0 }}>\n        {data.map((d, i) => (\n          <div\n            key={i}\n            className={cn(\n              'flex flex-1 items-center justify-center gap-1.5 text-[13px]',\n              d.highlight ? 'font-semibold text-fg' : 'text-fg-2',\n            )}\n          >\n            {d.label}\n          </div>\n        ))}\n      </div>\n    </div>\n  )\n}\n\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function hatchColumnsToRows(data: HatchColumn[]) {\n  return data.map((d) => ({ label: textOf(d.label), value: d.value }))\n}\n\nexport const Up = ({ children }: { children: ReactNode }) => (\n  <>\n    <ArrowUp size={10} strokeWidth={3} />\n    {children}\n  </>\n)\n\n/* ------------------------------------------------------------------ */\n/*  SegmentMeter: big % labels over guide lines that drop to a thick  */\n/*  segmented bar. (Tessera \"Cycle capacity\", Insights \"Mix\")         */\n/* ------------------------------------------------------------------ */\n\nexport interface Segment {\n  label: string\n  value: number\n  color: string\n  /** Secondary label next to the %, e.g. \"120h\". */\n  detail?: ReactNode\n  /** Draw the label column above this segment. Default true. */\n  showLabel?: boolean\n}\n\n/** Comfortable with 2–6 segments (labels need room above each one). */\nexport function SegmentMeter({\n  segments,\n  height = 150,\n  barHeight = 12,\n  hatchRemainder = true,\n  className,\n  locale,\n  ariaLabel,\n}: {\n  segments: Segment[]\n  height?: number\n  barHeight?: number\n  hatchRemainder?: boolean\n  className?: string\n  /** Formats the % labels (default \"42%\" as today). */\n  locale?: string\n  ariaLabel?: string\n}) {\n  const total = segments.reduce((a, s) => a + s.value, 0)\n  const pctText = (p: number) => (locale ? formatter(locale).percent(Math.round(p) / 100) : `${Math.round(p)}%`)\n  const rows = segmentMeterToRows(segments)\n  const label = ariaLabel ?? `Split: ${rows.map((r) => `${r.label} ${pctText(r.share * 100)}`).join(', ')}`\n  return (\n    <div role=\"figure\" aria-label={label} className={cn('relative', className)} style={{ height }}>\n      <ChartDataTable\n        caption={label}\n        columns={[\n          { key: 'label', label: 'Segment' },\n          { key: 'value', label: 'Value' },\n          { key: 'share', label: 'Share', format: (v) => pctText(Number(v) * 100) },\n        ]}\n        rows={rows}\n      />\n      <div className=\"absolute inset-x-0 top-0 bottom-0 flex gap-1\">\n        {segments.map((s, i) => {\n          const pct = (s.value / total) * 100\n          return (\n            <div key={i} className=\"relative flex min-w-0 flex-col\" style={{ width: `${pct}%` }}>\n              {s.showLabel !== false && (\n                <>\n                  <div className=\"flex items-baseline gap-1.5 whitespace-nowrap\">\n                    <span className=\"num text-[17px] font-semibold text-fg\">{pctText(pct)}</span>\n                    {s.detail && <span className=\"num text-xs text-fg-3\">{s.detail}</span>}\n                  </div>\n                  <div className=\"ml-[1px] w-px flex-1 bg-border-strong\" />\n                </>\n              )}\n              {s.showLabel === false && <div className=\"flex-1\" />}\n              <div\n                className={cn('anim-grow-x relative rounded-full', hatchRemainder && i === segments.length - 1 && s.color === 'hatch' && 'hatch bg-surface-3')}\n                style={{\n                  height: barHeight,\n                  background: s.color === 'hatch' ? undefined : s.color,\n                  animationDelay: `${i * 90}ms`,\n                }}\n              />\n            </div>\n          )\n        })}\n      </div>\n      {hatchRemainder && (\n        <div\n          className=\"hatch pointer-events-none absolute inset-x-0 -z-0 rounded-full opacity-70\"\n          style={{ bottom: -6, height: barHeight + 12 }}\n        />\n      )}\n    </div>\n  )\n}\n\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function segmentMeterToRows(segments: Segment[]) {\n  const total = segments.reduce((a, s) => a + s.value, 0) || 1\n  return segments.map((s) => ({ label: s.label, value: s.value, share: s.value / total }))\n}\n\n/* ------------------------------------------------------------------ */\n/*  StackBar: thin 100% horizontal bar with gaps between segments.    */\n/* ------------------------------------------------------------------ */\n\n/** Micro-chart: comfortable with up to ~10 segments. Labelled for screen readers via `aria-label`. */\nexport function StackBar({\n  segments,\n  height = 10,\n  gap = 3,\n  className,\n  ariaLabel,\n}: {\n  segments: { value: number; color: string; label?: string }[]\n  height?: number\n  gap?: number\n  className?: string\n  ariaLabel?: string\n}) {\n  const total = segments.reduce((a, s) => a + s.value, 0) || 1\n  const label =\n    ariaLabel ?? stackBarToRows(segments).map((r) => `${r.label}: ${r.value} (${Math.round(r.share * 100)}%)`).join(', ')\n  return (\n    <div role=\"img\" aria-label={label} className={cn('flex w-full', className)} style={{ gap, height }}>\n      {segments.map((s, i) => (\n        <div\n          key={i}\n          title={s.label}\n          className=\"anim-grow-x h-full min-w-[3px] rounded-full\"\n          style={{ flexGrow: s.value / total, flexBasis: 0, background: s.color, animationDelay: `${i * 60}ms` }}\n        />\n      ))}\n    </div>\n  )\n}\n\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function stackBarToRows(segments: { value: number; label?: string }[]) {\n  const total = segments.reduce((a, s) => a + s.value, 0) || 1\n  return segments.map((s, i) => ({ label: s.label ?? `Segment ${i + 1}`, value: s.value, share: s.value / total }))\n}\n\n/* ------------------------------------------------------------------ */\n/*  PillMeter: four small vertical pills, n filled (Insights table)   */\n/* ------------------------------------------------------------------ */\n\n/** Micro-chart for one 0..1 value. */\nexport function PillMeter({\n  value,\n  count = 4,\n  colors = ['var(--lime)', 'var(--lime)', 'var(--lime)', 'var(--lime)'],\n  className,\n  ariaLabel,\n}: {\n  /** 0..1 */\n  value: number\n  count?: number\n  colors?: string[]\n  className?: string\n  ariaLabel?: string\n}) {\n  const filled = Math.max(1, Math.round(value * count))\n  return (\n    <span role=\"img\" aria-label={ariaLabel ?? `${filled} of ${count}`} className={cn('inline-flex items-center gap-[3px]', className)}>\n      {Array.from({ length: count }, (_, i) => (\n        <span\n          key={i}\n          className=\"h-[18px] w-[6px] rounded-full\"\n          style={{ background: i < filled ? colors[i % colors.length] : 'var(--surface-4)' }}\n        />\n      ))}\n    </span>\n  )\n}\n\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function pillMeterToRows(value: number, count = 4) {\n  return [{ value, filled: Math.max(1, Math.round(value * count)), count }]\n}\n\n/* ------------------------------------------------------------------ */\n/*  BarChart: vertical bars (single or stacked) with axis + tooltip.  */\n/* ------------------------------------------------------------------ */\n\nexport interface BarSeries {\n  key: string\n  label: string\n  color: string\n}\n\n/**\n * Comfortable up to ~60 periods × 6 series; beyond that bars get thinner than a pixel\n * and labels collide (aggregate first). Tap or hover a period for the readout;\n * focus the chart and use ←/→, Home/End, Esc.\n */\nexport function BarChart({\n  data,\n  series,\n  height = 220,\n  stacked = true,\n  barRadius = 6,\n  yTicks = 4,\n  formatY: formatYProp,\n  formatTooltip,\n  xKey = 'x',\n  highlightIndex,\n  barWidth = 0.62,\n  className,\n  locale,\n  currency,\n  ariaLabel,\n}: {\n  data: Record<string, number | string>[]\n  series: BarSeries[]\n  height?: number\n  stacked?: boolean\n  barRadius?: number\n  yTicks?: number\n  formatY?: (v: number) => string\n  formatTooltip?: (v: number) => string\n  xKey?: string\n  highlightIndex?: number\n  /** Fraction of the slot the bar group occupies. */\n  barWidth?: number\n  className?: string\n  /** Locale for the default number format (default: plain rounded integers, as today). */\n  locale?: string\n  currency?: string\n  ariaLabel?: string\n}) {\n  const [ref, { width }] = useMeasure()\n  const [hover, setHover] = useState<number | null>(null)\n  const formatY = formatYProp ?? (locale ? (v: number) => formatter(locale, currency).number(v) : (v: number) => String(Math.round(v)))\n  const nav = useChartNav({ count: data.length, onMove: (p) => setHover(p.i), onClear: () => setHover(null), start: hover != null ? { i: hover, j: 0 } : null })\n  const padL = 40\n  const padB = 24\n  const padT = 8\n  const innerW = Math.max(0, width - padL)\n  const innerH = height - padB - padT\n  const totals = data.map((d) =>\n    stacked\n      ? series.reduce((a, s) => a + Number(d[s.key] ?? 0), 0)\n      : Math.max(...series.map((s) => Number(d[s.key] ?? 0))),\n  )\n  const max = niceMax(maxOf(totals, 1))\n  const slot = innerW / data.length\n  const bw = slot * barWidth\n  const fmtTip = formatTooltip ?? formatY\n  const rows = barChartToRows(data, series, xKey)\n  const label = ariaLabel ?? `Bar chart of ${series.map((s) => s.label).join(', ')} across ${data.length} periods`\n\n  return (\n    <div\n      ref={ref}\n      role=\"figure\"\n      aria-label={label}\n      className={cn('relative w-full', className)}\n      {...nav.root}\n      style={{ height, ...nav.root.style }}\n    >\n      <ChartDataTable\n        caption={label}\n        columns={[{ key: xKey, label: xKey }, ...series.map((s) => ({ key: s.label, label: s.label, format: (v: unknown) => fmtTip(Number(v)) }))]}\n        rows={rows}\n      />\n      {width > 0 && (\n        <svg width={width} height={height} className=\"overflow-visible\" aria-hidden>\n          {Array.from({ length: yTicks + 1 }, (_, i) => {\n            const v = (max / yTicks) * i\n            const y = padT + innerH - (v / max) * innerH\n            return (\n              <g key={i}>\n                <line\n                  x1={padL}\n                  x2={width}\n                  y1={y}\n                  y2={y}\n                  stroke=\"var(--border)\"\n                  strokeDasharray={i === 0 ? undefined : '3 4'}\n                />\n                <text x={padL - 10} y={y + 4} textAnchor=\"end\" className=\"num fill-fg-3 text-[11px]\">\n                  {formatY(v)}\n                </text>\n              </g>\n            )\n          })}\n          {data.map((d, i) => {\n            const x0 = padL + slot * i + (slot - bw) / 2\n            const dim = (hover != null && hover !== i) || (highlightIndex != null && highlightIndex !== i && hover == null)\n            let acc = 0\n            return (\n              <g\n                key={i}\n                {...markHover(setHover, i)}\n                style={{ opacity: dim ? 0.45 : 1, transition: 'opacity .15s' }}\n              >\n                <rect x={padL + slot * i} y={padT} width={slot} height={innerH} fill=\"transparent\" />\n                {series.map((s, si) => {\n                  const v = Number(d[s.key] ?? 0)\n                  const h = (v / max) * innerH\n                  if (stacked) {\n                    const y = padT + innerH - acc - h\n                    acc += h\n                    const top = si === series.length - 1\n                    return (\n                      <rect\n                        key={s.key}\n                        x={x0}\n                        y={y}\n                        width={bw}\n                        height={Math.max(0, h - (top ? 0 : 2))}\n                        rx={top ? Math.min(barRadius, bw / 2) : 2}\n                        fill={s.color}\n                        className=\"anim-grow-y\"\n                        style={{ transformBox: 'fill-box', animationDelay: `${i * 25}ms` }}\n                      />\n                    )\n                  }\n                  const gw = bw / series.length\n                  return (\n                    <rect\n                      key={s.key}\n                      x={x0 + gw * si + 1}\n                      y={padT + innerH - h}\n                      width={gw - 2}\n                      height={h}\n                      rx={Math.min(barRadius, gw / 2)}\n                      fill={s.color}\n                      className=\"anim-grow-y\"\n                      style={{ transformBox: 'fill-box', animationDelay: `${i * 25}ms` }}\n                    />\n                  )\n                })}\n                <text\n                  x={x0 + bw / 2}\n                  y={height - 6}\n                  textAnchor=\"middle\"\n                  className=\"fill-fg-3 text-[11px]\"\n                >\n                  {String(d[xKey])}\n                </text>\n              </g>\n            )\n          })}\n          {nav.pos && <rect {...ringRect(padL + slot * nav.pos.i + 1, padT, slot - 2, innerH, { rx: 6 })} />}\n        </svg>\n      )}\n      {hover != null && width > 0 && (\n        <Tooltip\n          x={padL + slot * hover + slot / 2}\n          y={padT + innerH - (totals[hover] / max) * innerH}\n          containerWidth={width}\n          title={String(data[hover][xKey])}\n          rows={series.map((s) => ({\n            label: s.label,\n            color: s.color,\n            value: fmtTip(Number(data[hover][s.key] ?? 0)),\n          }))}\n        />\n      )}\n    </div>\n  )\n}\n\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function barChartToRows(data: Record<string, number | string>[], series: BarSeries[], xKey = 'x') {\n  return data.map((d) => {\n    const row: Record<string, string | number> = { [xKey]: String(d[xKey]) }\n    for (const s of series) row[s.label] = Number(d[s.key] ?? 0)\n    return row\n  })\n}\n\n// oxlint-disable-next-line react/only-export-components -- shared scale helper used by lines/matrix\nexport function niceMax(v: number) {\n  const exp = Math.pow(10, Math.floor(Math.log10(v)))\n  const f = v / exp\n  const nice = f <= 1 ? 1 : f <= 1.5 ? 1.5 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 3 ? 3 : f <= 4 ? 4 : f <= 5 ? 5 : f <= 6 ? 6 : f <= 8 ? 8 : 10\n  return nice * exp\n}\n\nexport function Tooltip({\n  x,\n  y,\n  title,\n  rows,\n  containerWidth,\n}: {\n  x: number\n  y: number\n  title: ReactNode\n  rows: { label: ReactNode; value: ReactNode; color?: string }[]\n  containerWidth: number\n}) {\n  const flip = x > containerWidth - 170\n  return (\n    <div\n      role=\"status\"\n      className=\"pointer-events-none absolute z-30 min-w-[150px] rounded-xl border border-border bg-surface px-3 py-2.5 shadow-pop\"\n      style={{\n        left: x,\n        top: y,\n        transform: `translate(${flip ? 'calc(-100% - 12px)' : '12px'}, -50%)`,\n      }}\n    >\n      <div className=\"mb-1.5 text-[11.5px] font-medium text-fg-3\">{title}</div>\n      <div className=\"flex flex-col gap-1\">\n        {rows.map((r, i) => (\n          <div key={i} className=\"flex items-center justify-between gap-4 text-[12.5px]\">\n            <span className=\"flex items-center gap-1.5 text-fg-2\">\n              {r.color && <span className=\"size-2 rounded-full\" style={{ background: r.color }} />}\n              {r.label}\n            </span>\n            <span className=\"num font-semibold text-fg\">{r.value}</span>\n          </div>\n        ))}\n      </div>\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/bars.tsx"
    },
    {
      "path": "registry/klar/components/charts/export.ts",
      "content": "/**\n * Chart export: SVG, PNG and CSV, with no dependencies.\n *\n *   const ref = useRef<HTMLDivElement>(null)\n *   <div ref={ref}>…chart…</div>\n *   exportChartSvg(ref.current!, 'revenue')\n *   exportChartPng(ref.current!, 'revenue', { scale: 2 })\n *   exportCsv([{ month: 'Jan', revenue: 120 }], 'revenue')\n *\n * SVG/PNG inline the resolved CSS custom properties (tokens) and text styles so the\n * file looks the same outside the page. Canvas layers (spectrogram, vol surface)\n * are composited into the PNG.\n */\n\nexport interface ExportOptions {\n  /** PNG pixel ratio (default 2). */\n  scale?: number\n  /** Background colour; defaults to the chart's resolved surface colour. */\n  background?: string\n  /** Padding around the chart in px (default 16). */\n  padding?: number\n}\n\nconst STYLE_PROPS = [\n  'fill',\n  'fill-opacity',\n  'stroke',\n  'stroke-width',\n  'stroke-opacity',\n  'stroke-dasharray',\n  'stroke-linecap',\n  'stroke-linejoin',\n  'opacity',\n  'font-family',\n  'font-size',\n  'font-weight',\n  'letter-spacing',\n  'text-anchor',\n  'dominant-baseline',\n  'font-variant-numeric',\n] as const\n\nfunction download(blob: Blob, filename: string) {\n  const url = URL.createObjectURL(blob)\n  const a = document.createElement('a')\n  a.href = url\n  a.download = filename\n  document.body.appendChild(a)\n  a.click()\n  a.remove()\n  setTimeout(() => URL.revokeObjectURL(url), 1000)\n}\n\nconst slug = (s: string) => s.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'chart'\n\nfunction resolvedBackground(el: Element) {\n  let node: Element | null = el\n  while (node) {\n    const bg = getComputedStyle(node).backgroundColor\n    if (bg && bg !== 'transparent' && !/rgba\\(0, 0, 0, 0\\)/.test(bg)) return bg\n    node = node.parentElement\n  }\n  return '#ffffff'\n}\n\n/** Clone an SVG with computed presentation styles inlined (so var(--x) resolves). */\nfunction inlineSvg(svg: SVGSVGElement): SVGSVGElement {\n  const clone = svg.cloneNode(true) as SVGSVGElement\n  const src = svg.querySelectorAll('*')\n  const dst = clone.querySelectorAll('*')\n  const apply = (from: Element, to: Element) => {\n    const cs = getComputedStyle(from)\n    const parts: string[] = []\n    for (const p of STYLE_PROPS) {\n      const v = cs.getPropertyValue(p)\n      if (v) parts.push(`${p}:${v}`)\n    }\n    const prev = to.getAttribute('style')\n    to.setAttribute('style', parts.join(';') + (prev ? ';' + prev : ''))\n    // Attributes written as var(--token) must be resolved too.\n    for (const attr of ['fill', 'stroke', 'stop-color', 'color']) {\n      const raw = to.getAttribute(attr)\n      if (raw && raw.includes('var(')) {\n        const value = attr === 'stop-color' ? cs.getPropertyValue('stop-color') : cs.getPropertyValue(attr)\n        if (value) to.setAttribute(attr, value)\n      }\n    }\n  }\n  apply(svg, clone)\n  src.forEach((n, i) => {\n    apply(n, dst[i])\n    // CSS text-transform isn't an SVG attribute; bake it into the text itself.\n    if ((n.tagName === 'text' || n.tagName === 'tspan') && n.childElementCount === 0) {\n      const tt = getComputedStyle(n).textTransform\n      const t = dst[i].textContent ?? ''\n      if (tt === 'uppercase') dst[i].textContent = t.toUpperCase()\n      else if (tt === 'lowercase') dst[i].textContent = t.toLowerCase()\n    }\n  })\n  clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg')\n  clone.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink')\n  return clone\n}\n\n/**\n * Combine every <svg> and <canvas> inside `root` into one SVG document positioned\n * as on screen. HTML labels (legends, readouts) are not included; charts keep their\n * essential labels in SVG.\n */\nfunction composeSvg(root: HTMLElement, opts: ExportOptions = {}) {\n  const pad = opts.padding ?? 16\n  const box = root.getBoundingClientRect()\n  const sx = root.offsetWidth ? box.width / root.offsetWidth : 1\n  const w = root.offsetWidth\n  const h = root.offsetHeight\n  const doc = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\n  doc.setAttribute('xmlns', 'http://www.w3.org/2000/svg')\n  doc.setAttribute('width', String(w + pad * 2))\n  doc.setAttribute('height', String(h + pad * 2))\n  doc.setAttribute('viewBox', `0 0 ${w + pad * 2} ${h + pad * 2}`)\n  const bg = document.createElementNS('http://www.w3.org/2000/svg', 'rect')\n  bg.setAttribute('width', '100%')\n  bg.setAttribute('height', '100%')\n  bg.setAttribute('fill', opts.background ?? resolvedBackground(root))\n  doc.appendChild(bg)\n\n  const layers = root.querySelectorAll<SVGSVGElement | HTMLCanvasElement>('svg, canvas')\n  layers.forEach((layer) => {\n    // Skip nested svgs (handled by their parent) and icons inside buttons.\n    if (layer instanceof SVGSVGElement && (layer.ownerSVGElement || layer.closest('button'))) return\n    const r = layer.getBoundingClientRect()\n    if (!r.width || !r.height) return\n    const x = (r.left - box.left) / sx + pad\n    const y = (r.top - box.top) / sx + pad\n    const lw = r.width / sx\n    const lh = r.height / sx\n    if (layer instanceof HTMLCanvasElement) {\n      const img = document.createElementNS('http://www.w3.org/2000/svg', 'image')\n      img.setAttribute('x', String(x))\n      img.setAttribute('y', String(y))\n      img.setAttribute('width', String(lw))\n      img.setAttribute('height', String(lh))\n      try {\n        img.setAttribute('href', layer.toDataURL('image/png'))\n        doc.appendChild(img)\n      } catch {\n        /* tainted canvas: skip */\n      }\n      return\n    }\n    const g = document.createElementNS('http://www.w3.org/2000/svg', 'g')\n    g.setAttribute('transform', `translate(${x} ${y})`)\n    const inner = inlineSvg(layer)\n    inner.setAttribute('width', String(lw))\n    inner.setAttribute('height', String(lh))\n    if (!inner.getAttribute('viewBox')) inner.setAttribute('viewBox', `0 0 ${layer.width.baseVal.value || lw} ${layer.height.baseVal.value || lh}`)\n    g.appendChild(inner)\n    doc.appendChild(g)\n  })\n  return { doc, width: w + pad * 2, height: h + pad * 2 }\n}\n\n/** The chart as an SVG string. */\nexport function chartToSvgString(root: HTMLElement, opts?: ExportOptions) {\n  const { doc } = composeSvg(root, opts)\n  return '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' + new XMLSerializer().serializeToString(doc)\n}\n\n/** Download the chart as SVG. */\nexport function exportChartSvg(root: HTMLElement, name = 'chart', opts?: ExportOptions) {\n  download(new Blob([chartToSvgString(root, opts)], { type: 'image/svg+xml' }), `${slug(name)}.svg`)\n}\n\n/** Render the chart to a PNG blob. */\nexport async function chartToPngBlob(root: HTMLElement, opts: ExportOptions = {}): Promise<Blob> {\n  const scale = opts.scale ?? 2\n  const { doc, width, height } = composeSvg(root, opts)\n  const svgText = new XMLSerializer().serializeToString(doc)\n  const img = new Image()\n  img.decoding = 'async'\n  const url = URL.createObjectURL(new Blob([svgText], { type: 'image/svg+xml' }))\n  try {\n    await new Promise<void>((res, rej) => {\n      img.onload = () => res()\n      img.onerror = () => rej(new Error('Could not rasterise chart'))\n      img.src = url\n    })\n    const canvas = document.createElement('canvas')\n    canvas.width = Math.round(width * scale)\n    canvas.height = Math.round(height * scale)\n    const ctx = canvas.getContext('2d')!\n    ctx.scale(scale, scale)\n    ctx.drawImage(img, 0, 0, width, height)\n    return await new Promise<Blob>((res, rej) => canvas.toBlob((b) => (b ? res(b) : rej(new Error('PNG encoding failed'))), 'image/png'))\n  } finally {\n    URL.revokeObjectURL(url)\n  }\n}\n\n/** Download the chart as PNG (2× by default). */\nexport async function exportChartPng(root: HTMLElement, name = 'chart', opts?: ExportOptions) {\n  download(await chartToPngBlob(root, opts), `${slug(name)}.png`)\n}\n\n/** Rows (array of flat objects) as RFC 4180 CSV. Column order follows the first row unless given. */\nexport function toCsv(rows: Record<string, unknown>[], columns?: string[]) {\n  const cols = columns ?? Object.keys(rows[0] ?? {})\n  const cell = (v: unknown) => {\n    if (v == null) return ''\n    const s = v instanceof Date ? v.toISOString() : String(v)\n    return /[\",\\n\\r]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s\n  }\n  return [cols.map(cell).join(','), ...rows.map((r) => cols.map((c) => cell(r[c])).join(','))].join('\\r\\n')\n}\n\n/** Download rows as a CSV file (UTF-8 with BOM so Excel opens it correctly). */\nexport function exportCsv(rows: Record<string, unknown>[], name = 'chart-data', columns?: string[]) {\n  download(new Blob(['﻿' + toCsv(rows, columns)], { type: 'text/csv;charset=utf-8' }), `${slug(name)}.csv`)\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/export.ts"
    }
  ],
  "docs": "import { VolSurface } from '@/components/klar/charts/finance/VolSurface'\nData comes in through props.",
  "categories": [
    "charts",
    "finance",
    "markets"
  ],
  "meta": {
    "collection": "finance",
    "kind": "markets",
    "tags": [
      "volatility",
      "surface",
      "options",
      "contour",
      "smile",
      "heatmap",
      "derivatives"
    ],
    "standalone": true,
    "export": "VolSurface",
    "import": "@/components/klar/charts/finance/VolSurface"
  }
}
