{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bi-variance",
  "type": "registry:component",
  "title": "Variance chart (IBCS)",
  "description": "Actual and forecast against plan and prior year per period, with the absolute variance as green and red bars and the relative variance as pins, all on one aligned scale with a totals column.",
  "dependencies": [
    "clsx",
    "lucide-react",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "https://klar.run/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/klar/components/charts/bi/VarianceChart.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 { ExportLegend, Readout, type ReadoutRow } from '@/components/klar/charts/bi/Readout'\nimport { markHover, ringRect, useChartNav } from '@/components/klar/charts/bi/interaction'\nimport { biNumbers, clamp, signed, textW } from '@/components/klar/charts/bi/util'\n\nexport interface VariancePeriod {\n  /** Month, quarter, unit or account name. */\n  label: string\n  /** Actual (AC). Leave out for periods still to come. */\n  actual?: number | null\n  /** Forecast (FC): used where there is no actual, drawn hatched. */\n  forecast?: number | null\n  /** Plan / budget (PL): drawn as an outlined bar. */\n  plan?: number | null\n  /** Prior year (PY): drawn as a grey bar behind. */\n  prior?: number | null\n  /** Cost line: a fall is good (variance colours invert). Overrides the chart-wide flag. */\n  goodWhenLower?: boolean\n}\n\nexport interface VarianceRow {\n  label: string\n  /** 'AC' actual, 'FC' forecast, 'AC+FC' a total that mixes both, 'none' no value. */\n  scenario: 'AC' | 'FC' | 'AC+FC' | 'none'\n  total: boolean\n  value: number | null\n  plan: number | null\n  prior: number | null\n  /** value − plan */\n  deltaPlan: number | null\n  /** (value − plan) / |plan| */\n  deltaPlanPct: number | null\n  deltaPrior: number | null\n  deltaPriorPct: number | null\n  goodWhenLower: boolean\n}\n\nconst num = (v: number | null | undefined): v is number => v != null && Number.isFinite(v)\nconst pctOf = (d: number | null, b: number | null) => (d == null || b == null || b === 0 ? null : d / Math.abs(b))\n\n/**\n * Variance rows (IBCS): each period's value (actual, else forecast) against plan and\n * prior year, as absolute and relative variances, plus a total row when `totals` is on.\n * A total sums each scenario over the periods that have it; its variances compare like\n * with like (plan over the periods that have a value).\n */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport function varianceRows(\n  data: VariancePeriod[],\n  { goodWhenLower = false, totals = true, totalLabel = 'Total' }: { goodWhenLower?: boolean; totals?: boolean; totalLabel?: string } = {},\n): VarianceRow[] {\n  const out: VarianceRow[] = data.map((d) => {\n    const ac = num(d.actual)\n    const value = ac ? d.actual! : num(d.forecast) ? d.forecast! : null\n    const plan = num(d.plan) ? d.plan : null\n    const prior = num(d.prior) ? d.prior : null\n    const dP = value != null && plan != null ? value - plan : null\n    const dY = value != null && prior != null ? value - prior : null\n    return {\n      label: d.label,\n      scenario: ac ? 'AC' : value != null ? 'FC' : 'none',\n      total: false,\n      value,\n      plan,\n      prior,\n      deltaPlan: dP,\n      deltaPlanPct: pctOf(dP, plan),\n      deltaPrior: dY,\n      deltaPriorPct: pctOf(dY, prior),\n      goodWhenLower: d.goodWhenLower ?? goodWhenLower,\n    }\n  })\n  if (!totals || !out.length) return out\n  const sum = (f: (r: VarianceRow) => number | null) => {\n    let s = 0\n    let any = false\n    for (const r of out) {\n      const v = f(r)\n      if (v != null) {\n        s += v\n        any = true\n      }\n    }\n    return any ? s : null\n  }\n  const value = sum((r) => r.value)\n  const plan = sum((r) => r.plan)\n  const prior = sum((r) => r.prior)\n  const dP = sum((r) => r.deltaPlan)\n  const dY = sum((r) => r.deltaPrior)\n  const planLike = sum((r) => (r.value != null ? r.plan : null))\n  const priorLike = sum((r) => (r.value != null ? r.prior : null))\n  const hasAc = out.some((r) => r.scenario === 'AC')\n  const hasFc = out.some((r) => r.scenario === 'FC')\n  const lower = out.every((r) => r.goodWhenLower)\n  out.push({\n    label: totalLabel,\n    scenario: hasAc && hasFc ? 'AC+FC' : hasFc ? 'FC' : hasAc ? 'AC' : 'none',\n    total: true,\n    value,\n    plan,\n    prior,\n    deltaPlan: dP,\n    deltaPlanPct: pctOf(dP, planLike),\n    deltaPrior: dY,\n    deltaPriorPct: pctOf(dY, priorLike),\n    goodWhenLower: lower,\n  })\n  return out\n}\n\n/** Flat rows for CSV export: one per period (and the total), with both variances. */\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function varianceChartToRows(data: VariancePeriod[], opts?: { goodWhenLower?: boolean; totals?: boolean; totalLabel?: string }) {\n  return varianceRows(data, opts).map((r) => ({\n    label: r.label,\n    scenario: r.scenario,\n    value: r.value,\n    plan: r.plan,\n    prior: r.prior,\n    deltaPlan: r.deltaPlan,\n    deltaPlanPct: r.deltaPlanPct,\n    deltaPrior: r.deltaPrior,\n    deltaPriorPct: r.deltaPriorPct,\n    goodWhenLower: r.goodWhenLower,\n  }))\n}\n\nconst AC_FILL = 'color-mix(in oklab, var(--fg) 86%, var(--surface))'\nconst PY_FILL = 'color-mix(in oklab, var(--fg) 24%, var(--surface))'\nconst PL_STROKE = 'color-mix(in oklab, var(--fg) 88%, var(--surface))'\n\n/**\n * IBCS variance chart: actual (solid), forecast (hatched), plan (outlined) and prior\n * year (grey) per period, with the absolute variance as green / red bars pinned to\n * their own axis and the relative variance as a row of pins, all on one aligned scale\n * (a unit of variance is as long as a unit of value). A totals column sits on its own\n * scale, marked with an axis break. `goodWhenLower` (chart-wide or per row) inverts\n * the colours for cost lines.\n *\n * Data: `VariancePeriod[]` ({ label, actual?, forecast?, plan?, prior? }). Vertical\n * suits months (columns); horizontal suits units or accounts (rows).\n *\n * Interaction: hover, tap or drag across periods; Tab to the chart, then arrows\n * (Home/End) step through periods and the total, Esc clears. Comfortable with 4–24\n * periods vertically and up to ~16 rows horizontally.\n */\nexport function VarianceChart({\n  data,\n  compare = 'plan',\n  orientation = 'vertical',\n  goodWhenLower = false,\n  totals = true,\n  totalLabel = 'Total',\n  showPlan = true,\n  showPrior = true,\n  height: heightIn,\n  format: formatIn,\n  deltaFormat: deltaIn,\n  unit,\n  scenarioLabels: sl,\n  legend = true,\n  locale,\n  className,\n  ariaLabel,\n}: {\n  data: VariancePeriod[]\n  /** Which baseline the variance rows measure against. */\n  compare?: 'plan' | 'prior'\n  orientation?: 'vertical' | 'horizontal'\n  /** Cost lines: a value below the baseline is good (green). */\n  goodWhenLower?: boolean\n  totals?: boolean\n  totalLabel?: string\n  showPlan?: boolean\n  showPrior?: boolean\n  /** Default 440 vertical; horizontal grows with the rows (34 px each). */\n  height?: number\n  /** Value labels (default compact). */\n  format?: (v: number) => string\n  /** Absolute variance magnitude; the sign is added for you (default `format`). */\n  deltaFormat?: (v: number) => string\n  /** Short unit shown with the value panel, e.g. \"€M\". */\n  unit?: string\n  /** Scenario codes (IBCS defaults AC / FC / PL / PY). */\n  scenarioLabels?: Partial<Record<'actual' | 'forecast' | 'plan' | 'prior', string>>\n  legend?: boolean\n  /** BCP 47 locale for built-in number labels, e.g. 'de-DE' (default en-US). */\n  locale?: string\n  className?: string\n  ariaLabel?: string\n}) {\n  const [ref, { width }] = useMeasure()\n  const [hover, setHover] = useState<number | null>(null)\n  const uid = useId().replace(/:/g, '')\n  const nums = biNumbers(locale)\n  const format = formatIn ?? nums.short\n  const dfmt = deltaIn ?? format\n  const pctFmt = (p: number) => signed(p * 100, (v) => nums.fixed(v, 1)) + '%'\n  const S = { actual: 'AC', forecast: 'FC', plan: 'PL', prior: 'PY', ...sl }\n  const base = compare === 'plan' ? S.plan : S.prior\n  const vert = orientation === 'vertical'\n\n  const rows = varianceRows(data, { goodWhenLower, totals, totalLabel })\n  const n = data.length\n  const hasT = totals && n > 0\n  const slots = rows.length\n  const delta = (r: VarianceRow) => (compare === 'plan' ? r.deltaPlan : r.deltaPrior)\n  const deltaPct = (r: VarianceRow) => (compare === 'plan' ? r.deltaPlanPct : r.deltaPriorPct)\n  const isGood = (r: VarianceRow, d: number) => (d === 0 ? null : r.goodWhenLower ? d < 0 : d > 0)\n  const tone = (r: VarianceRow, d: number) => {\n    const g = isGood(r, d)\n    return g == null ? 'var(--fg-3)' : g ? 'var(--green)' : 'var(--red)'\n  }\n  const label = ariaLabel ?? `Variance chart: ${S.actual} against ${S.plan} and ${S.prior}, absolute and relative variance to ${base}`\n\n  /* ---------------- scales ---------------- */\n  const months = rows.filter((r) => !r.total)\n  const mainVals = (r: VarianceRow) => [r.value, showPlan ? r.plan : null, showPrior ? r.prior : null].filter(num)\n  const maxMain = Math.max(1e-9, ...months.flatMap(mainVals))\n  const ds = months.map(delta).filter(num)\n  const dPos = Math.max(0, ...ds)\n  const dNeg = Math.max(0, ...ds.map((d) => -d))\n  const ps = rows.map(deltaPct).filter(num)\n  const pPos = Math.max(0.001, ...ps)\n  const pNeg = Math.max(0, ...ps.map((p) => -p))\n  const tr = hasT ? rows[rows.length - 1] : null\n  const maxTotal = tr ? Math.max(1e-9, ...mainVals(tr)) : 1\n\n  const legendH = legend ? 30 : 0\n  const height = heightIn ?? (vert ? 440 : Math.max(300, 72 + legendH + slots * 34 + (hasT ? 14 : 0)))\n  const H = height - legendH\n  const brk = hasT ? 16 : 0 // gap before the totals slot\n\n  // Along the value axis: room for labels and the panels.\n  const lblMain = vert ? 18 : 44\n  const lblD = vert ? 16 : 44\n  const minD = vert ? 40 : 96\n  const gap = vert ? 14 : 18\n  const scenarioMix = vert && rows.some((r) => r.scenario === 'FC') && rows.some((r) => r.scenario === 'AC')\n\n  let catStart: number\n  let catLen: number\n  let valStart: number\n  let valLen: number\n  if (vert) {\n    catStart = 68\n    catLen = Math.max(10, width - catStart - 10)\n    valStart = 10\n    valLen = Math.max(60, H - valStart - 26 - (scenarioMix ? 16 : 0))\n  } else {\n    const lw = Math.min(150, Math.max(64, ...rows.map((r) => textW(r.label, 12, r.total ? 600 : 400))) + 16)\n    catStart = 30\n    catLen = Math.max(10, H - catStart - 6)\n    valStart = lw\n    valLen = Math.max(60, width - lw - 8)\n  }\n  const pctLen = vert ? clamp(valLen * 0.2, 60, 96) : clamp(valLen * 0.2, 110, 170)\n  const R = valLen - pctLen - gap * 2\n  let k = (R - lblMain - lblD * 2) / (maxMain + dPos + dNeg)\n  let dLen = (dPos + dNeg) * k + lblD * 2\n  if (dLen < minD) {\n    k = (R - lblMain - minD) / maxMain\n    dLen = minD\n  }\n  k = Math.max(0, k)\n  const mainLen = R - dLen\n  const kT = (maxMain * k) / maxTotal\n\n  // Panels along the value axis, in screen order.\n  const order = vert ? (['pct', 'delta', 'main'] as const) : (['main', 'delta', 'pct'] as const)\n  const lens = { pct: pctLen, delta: dLen, main: mainLen }\n  const start: Record<'pct' | 'delta' | 'main', number> = { pct: 0, delta: 0, main: 0 }\n  {\n    let p = valStart\n    for (const o of order) {\n      start[o] = p\n      p += lens[o] + gap\n    }\n  }\n  const sgn = vert ? -1 : 1\n  // zero positions\n  const mainZero = vert ? start.main + mainLen : start.main\n  const dSpan = (dPos + dNeg) * k\n  const dZero = vert ? start.delta + (dLen - dSpan) / 2 + dPos * k : start.delta + (dLen - dSpan) / 2 + dNeg * k\n  const pLbl = vert ? 15 : 46\n  const kp = (pctLen - pLbl * 2) / (pPos + pNeg)\n  const pZero = vert ? start.pct + pLbl + pPos * kp : start.pct + pLbl + pNeg * kp\n  const vMain = (v: number, total: boolean) => mainZero + sgn * v * (total ? kT : k)\n  const vDelta = (d: number, total: boolean) => {\n    const lim = (dLen - (dLen - dSpan) / 2) - 2\n    const raw = d * (total ? kT : k)\n    return dZero + sgn * clamp(raw, -lim, lim)\n  }\n  const vPct = (p: number) => pZero + sgn * clamp(p * kp, -(pctLen - pLbl), pctLen - pLbl)\n\n  const cw = (catLen - brk) / Math.max(1, slots)\n  const c0 = (i: number) => catStart + i * cw + (hasT && i === slots - 1 ? brk : 0)\n  const cc = (i: number) => c0(i) + cw / 2\n  const bw = vert ? Math.min(30, cw * 0.44) : Math.min(16, cw * 0.46)\n  const off = bw * 0.32\n\n  /** A rect from cat [a, a+s] and value-axis screen coords [p, q]. */\n  const box = (a: number, s: number, p: number, q: number) =>\n    vert ? { x: a, y: Math.min(p, q), width: s, height: Math.abs(q - p) } : { x: Math.min(p, q), y: a, width: Math.abs(q - p), height: s }\n  const pt = (c: number, v: number) => (vert ? { x: c, y: v } : { x: v, y: c })\n  /** Text beyond a bar end, on the side the bar points to. */\n  const endText = (c: number, v: number, dir: 1 | -1, pad = 5) =>\n    vert\n      ? { x: c, y: v + (dir * sgn > 0 ? pad + 9 : -pad), textAnchor: 'middle' as const }\n      : { x: v + dir * pad, y: c + 4, textAnchor: dir > 0 ? ('start' as const) : ('end' as const) }\n\n  const nav = useChartNav({\n    count: slots,\n    axis: vert ? 'x' : 'y',\n    onMove: (p) => setHover(p.i),\n    onClear: () => setHover(null),\n    start: hover != null ? { i: hover, j: 0 } : null,\n  })\n\n  const hr = hover != null ? rows[hover] : null\n  const scen = (r: VarianceRow) => (r.scenario === 'FC' ? S.forecast : r.scenario === 'AC+FC' ? `${S.actual}+${S.forecast}` : S.actual)\n  const deltaRows = (r: VarianceRow, which: 'plan' | 'prior'): ReadoutRow[] => {\n    const d = which === 'plan' ? r.deltaPlan : r.deltaPrior\n    const p = which === 'plan' ? r.deltaPlanPct : r.deltaPriorPct\n    const code = which === 'plan' ? S.plan : S.prior\n    if (d == null) return []\n    return [{ label: `Δ${code}`, value: `${signed(d, dfmt)}${p != null ? `  ·  ${pctFmt(p)}` : ''}`, color: tone(r, d), muted: which !== compare }]\n  }\n\n  const fcRows = rows.map((r) => r.scenario === 'FC')\n  const vLabelsFit = vert ? cw >= textW(format(maxMain), 10.5) + 4 : true\n\n  return (\n    <div\n      ref={ref}\n      role=\"figure\"\n      aria-label={label}\n      {...nav.root}\n      className={cn('relative w-full select-none', className)}\n      style={{ ...nav.root.style, height }}\n      onPointerLeave={(e) => e.pointerType === 'mouse' && setHover(null)}\n    >\n      {width > 0 && (\n        <svg width={width} height={H} className=\"overflow-visible\">\n          <defs>\n            <pattern id={`${uid}-fc`} width={4.5} height={4.5} patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\">\n              <rect width={4.5} height={4.5} fill=\"var(--surface)\" />\n              <line x1={0} x2={0} y1={0} y2={4.5} stroke={AC_FILL} strokeWidth={1.6} />\n            </pattern>\n            {(['green', 'red'] as const).map((c) => (\n              <pattern key={c} id={`${uid}-${c}`} width={4.5} height={4.5} patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\">\n                <rect width={4.5} height={4.5} fill={`color-mix(in oklab, var(--${c}) 18%, var(--surface))`} />\n                <line x1={0} x2={0} y1={0} y2={4.5} stroke={`var(--${c})`} strokeWidth={1.8} />\n              </pattern>\n            ))}\n          </defs>\n\n          {/* totals panel tint */}\n          {hasT && (\n            <rect\n              {...box(c0(slots - 1) - 2, cw + 4, valStart - (vert ? 4 : 0), valStart + valLen + (vert ? 22 : 0))}\n              rx={8}\n              fill=\"color-mix(in oklab, var(--fg) 3.5%, transparent)\"\n            />\n          )}\n          {/* hover band */}\n          {hover != null && (\n            <rect\n              {...box(c0(hover) + 1, cw - 2, valStart - (vert ? 4 : 0), valStart + valLen + (vert ? 22 : 0))}\n              rx={7}\n              fill=\"color-mix(in oklab, var(--accent) 7%, transparent)\"\n            />\n          )}\n\n          {/* panel titles */}\n          {vert ? (\n            <g className=\"text-[11px]\">\n              <text x={8} y={vPct(0) + 4} className=\"fill-fg-2 font-semibold\">{`Δ${base} %`}</text>\n              <text x={8} y={dZero + 4} className=\"fill-fg-2 font-semibold\">{`Δ${base}`}</text>\n              <text x={8} y={start.main + lblMain + 2} className=\"fill-fg-2 font-semibold\">\n                {S.actual}\n              </text>\n              {unit && (\n                <text x={8} y={start.main + lblMain + 16} className=\"fill-fg-3 text-[10.5px]\">\n                  {unit}\n                </text>\n              )}\n            </g>\n          ) : (\n            <g className=\"text-[11px]\">\n              <text x={start.main} y={14} className=\"fill-fg-2 font-semibold\">\n                {[S.actual, showPlan && S.plan, showPrior && S.prior].filter(Boolean).join(' · ')}\n                {unit && <tspan className=\"fill-fg-3 font-normal\">{`  ${unit}`}</tspan>}\n              </text>\n              <text x={dZero} y={14} textAnchor=\"middle\" className=\"fill-fg-2 font-semibold\">{`Δ${base}`}</text>\n              <text x={pZero} y={14} textAnchor=\"middle\" className=\"fill-fg-2 font-semibold\">{`Δ${base} %`}</text>\n            </g>\n          )}\n\n          {/* ---------- main panel ---------- */}\n          {rows.map((r, i) => {\n            const t = r.total\n            const ac = c0(i) + cw / 2\n            const dim = hover != null && hover !== i\n            const ends: number[] = []\n            const el: ReactNode[] = []\n            if (showPrior && r.prior != null) {\n              const q = vMain(r.prior, t)\n              ends.push(q)\n              el.push(<rect key=\"py\" {...box(ac - bw / 2 - off, bw, mainZero, q)} fill={PY_FILL} />)\n            }\n            if (showPlan && r.plan != null) {\n              const q = vMain(r.plan, t)\n              ends.push(q)\n              el.push(<rect key=\"pl\" {...box(ac - bw / 2 + off, bw, mainZero, q)} fill=\"var(--surface)\" stroke={PL_STROKE} strokeWidth={1.25} />)\n            }\n            if (r.value != null) {\n              const q = vMain(r.value, t)\n              ends.push(q)\n              const fc = r.scenario === 'FC'\n              el.push(\n                <rect\n                  key=\"ac\"\n                  {...box(ac - bw / 2, bw, mainZero, q)}\n                  fill={fc ? `url(#${uid}-fc)` : AC_FILL}\n                  stroke={fc ? AC_FILL : 'none'}\n                  strokeWidth={fc ? 1.25 : 0}\n                />,\n              )\n              if (r.scenario === 'AC+FC') {\n                // the forecast share of the total, hatched on top of the actual\n                const fcSum = rows.filter((x) => !x.total && x.scenario === 'FC').reduce((s, x) => s + (x.value ?? 0), 0)\n                const q0 = vMain(r.value - fcSum, t)\n                el.push(<rect key=\"acfc\" {...box(ac - bw / 2, bw, q0, q)} fill={`url(#${uid}-fc)`} stroke={AC_FILL} strokeWidth={1.25} />)\n              }\n            }\n            const far = ends.length ? (vert ? Math.min(...ends) : Math.max(...ends)) : mainZero\n            return (\n              <g key={`m${i}`} style={{ opacity: dim ? 0.55 : 1, transition: 'opacity .15s' }}>\n                <g className={vert ? 'anim-grow-y' : 'anim-grow-x'} style={{ transformBox: 'view-box', transformOrigin: vert ? `0 ${mainZero}px` : `${mainZero}px 0`, animationDelay: `${i * 30}ms` }}>\n                  {el}\n                </g>\n                {r.value != null && vLabelsFit && (\n                  <text\n                    {...(vert ? { x: ac, y: far - 6, textAnchor: 'middle' as const } : { x: far + 7, y: ac + 4, textAnchor: 'start' as const })}\n                    className={cn('num text-[10.5px]', t || hover === i ? 'fill-fg font-semibold' : 'fill-fg-2 font-medium')}\n                  >\n                    {format(r.value)}\n                  </text>\n                )}\n              </g>\n            )\n          })}\n          {/* main baseline + axis break before the total */}\n          {(() => {\n            const a = catStart\n            const b = hasT ? c0(slots - 1) - brk / 2 : catStart + catLen\n            const p = pt(0, mainZero)\n            return (\n              <g>\n                {vert ? (\n                  <line x1={a} x2={b - (hasT ? 3 : 0)} y1={p.y} y2={p.y} stroke=\"var(--fg)\" strokeWidth={1.25} />\n                ) : (\n                  <line y1={a - 4} y2={b - (hasT ? 3 : 0)} x1={p.x} x2={p.x} stroke=\"var(--fg)\" strokeWidth={1.25} />\n                )}\n                {hasT &&\n                  (vert ? (\n                    <>\n                      <line x1={b + 3} x2={catStart + catLen} y1={p.y} y2={p.y} stroke=\"var(--fg)\" strokeWidth={1.25} />\n                      <path d={`M${b - 6},${p.y + 5}L${b - 1},${p.y - 5}M${b + 1},${p.y + 5}L${b + 6},${p.y - 5}`} stroke=\"var(--fg-2)\" strokeWidth={1.25} />\n                    </>\n                  ) : (\n                    <>\n                      <line y1={b + 3} y2={catStart + catLen} x1={p.x} x2={p.x} stroke=\"var(--fg)\" strokeWidth={1.25} />\n                      <path d={`M${p.x - 5},${b - 1}L${p.x + 5},${b - 6}M${p.x - 5},${b + 6}L${p.x + 5},${b + 1}`} stroke=\"var(--fg-2)\" strokeWidth={1.25} />\n                    </>\n                  ))}\n              </g>\n            )\n          })()}\n\n          {/* ---------- absolute variance ---------- */}\n          {rows.map((r, i) => {\n            const d = delta(r)\n            const ac = cc(i)\n            const dim = hover != null && hover !== i\n            if (d == null) return null\n            const q = vDelta(d, r.total)\n            const c = tone(r, d)\n            const g = isGood(r, d)\n            const fill = fcRows[i] ? `url(#${uid}-${g === false ? 'red' : 'green'})` : c\n            const dir = (d >= 0 ? 1 : -1) as 1 | -1\n            return (\n              <g key={`d${i}`} style={{ opacity: dim ? 0.55 : 1, transition: 'opacity .15s' }}>\n                <rect {...box(ac - bw / 2, bw, dZero, q)} fill={fill} stroke={fcRows[i] ? c : 'none'} strokeWidth={fcRows[i] ? 1 : 0} className=\"anim-fade\" style={{ animationDelay: `${200 + i * 30}ms` }} />\n                <text {...endText(ac, q, vert ? dir : dir)} className={cn('num text-[10.5px] font-semibold', hover === i && 'text-[11px]')} fill={`color-mix(in oklab, ${c} 78%, var(--fg))`}>\n                  {signed(d, dfmt)}\n                </text>\n              </g>\n            )\n          })}\n          {/* variance axis: solid under actuals, dashed under forecasts */}\n          {rows.map((r, i) => {\n            const a = c0(i) + (i === 0 ? 0 : 0)\n            const s = cw\n            const p = pt(0, dZero)\n            const fc = r.scenario === 'FC'\n            const props = { stroke: 'var(--fg)', strokeWidth: 1.5, strokeDasharray: fc ? '3 2' : undefined }\n            return vert ? <line key={`da${i}`} x1={a + 2} x2={a + s - 2} y1={p.y} y2={p.y} {...props} /> : <line key={`da${i}`} y1={a + 2} y2={a + s - 2} x1={p.x} x2={p.x} {...props} />\n          })}\n\n          {/* ---------- relative variance pins ---------- */}\n          {rows.map((r, i) => {\n            const p = deltaPct(r)\n            const ac = cc(i)\n            const dim = hover != null && hover !== i\n            if (p == null) return null\n            const q = vPct(p)\n            const c = tone(r, p)\n            const dir = (p >= 0 ? 1 : -1) as 1 | -1\n            const head = pt(ac, q)\n            const fc = r.scenario === 'FC'\n            const clipped = Math.abs(p * kp) > pctLen - pLbl\n            return (\n              <g key={`p${i}`} style={{ opacity: dim ? 0.55 : 1, transition: 'opacity .15s' }} className=\"anim-fade\">\n                {vert ? (\n                  <line x1={ac} x2={ac} y1={pZero} y2={q} stroke={c} strokeWidth={2} />\n                ) : (\n                  <line y1={ac} y2={ac} x1={pZero} x2={q} stroke={c} strokeWidth={2} />\n                )}\n                <rect x={head.x - 3.75} y={head.y - 3.75} width={7.5} height={7.5} rx={1.25} fill={fc ? 'var(--surface)' : c} stroke={c} strokeWidth={1.5} />\n                {clipped && <path d={vert ? `M${ac - 4},${q + sgn * dir * -8}l4,${sgn * dir * -4}l4,${sgn * dir * 4}` : `M${q + dir * 8},${ac - 4}l${dir * 4},4l${-dir * 4},4`} fill=\"none\" stroke={c} strokeWidth={1.25} />}\n                <text {...endText(ac, q, dir, 8)} className=\"num text-[10.5px] font-semibold\" fill={`color-mix(in oklab, ${c} 78%, var(--fg))`}>\n                  {pctFmt(p)}\n                </text>\n              </g>\n            )\n          })}\n          {vert ? (\n            <line x1={catStart} x2={catStart + catLen} y1={pZero} y2={pZero} stroke=\"var(--fg-3)\" strokeWidth={1} />\n          ) : (\n            <line y1={catStart - 4} y2={catStart + catLen} x1={pZero} x2={pZero} stroke=\"var(--fg-3)\" strokeWidth={1} />\n          )}\n\n          {/* ---------- category labels ---------- */}\n          {rows.map((r, i) => {\n            const on = hover === i\n            const cls = cn('text-[11.5px]', r.total || on ? 'fill-fg font-semibold' : 'fill-fg-2')\n            if (vert) {\n              return (\n                <text key={`l${i}`} x={cc(i)} y={mainZero + 17} textAnchor=\"middle\" className={cls}>\n                  {r.label}\n                </text>\n              )\n            }\n            return (\n              <text key={`l${i}`} x={valStart - 12} y={cc(i) + 4} textAnchor=\"end\" className={cls}>\n                {r.label.length > 22 ? r.label.slice(0, 21) + '…' : r.label}\n              </text>\n            )\n          })}\n          {/* scenario bracket: AC | FC under the months */}\n          {scenarioMix &&\n            (() => {\n              const groups: { s: string; a: number; b: number }[] = []\n              rows.forEach((r, i) => {\n                if (r.total || r.scenario === 'none') return\n                const s = r.scenario === 'FC' ? S.forecast : S.actual\n                const last = groups[groups.length - 1]\n                if (last && last.s === s && last.b === i - 1) last.b = i\n                else groups.push({ s, a: i, b: i })\n              })\n              const y = mainZero + 28\n              return groups.map((g, gi) => (\n                <g key={gi}>\n                  <path d={`M${c0(g.a) + 6},${y - 3}V${y}H${c0(g.b) + cw - 6}V${y - 3}`} fill=\"none\" stroke=\"var(--fg-4)\" />\n                  <rect x={(c0(g.a) + c0(g.b) + cw) / 2 - 14} y={y - 5} width={28} height={11} fill=\"var(--surface)\" />\n                  <text x={(c0(g.a) + c0(g.b) + cw) / 2} y={y + 4} textAnchor=\"middle\" className=\"fill-fg-3 text-[10px] font-semibold tracking-[0.06em]\">\n                    {g.s}\n                  </text>\n                </g>\n              ))\n            })()}\n\n          {/* hit slots */}\n          {rows.map((_, i) => (\n            <rect key={`h${i}`} {...box(c0(i), cw, valStart - 6, valStart + valLen + (vert ? 26 : 0))} fill=\"transparent\" {...markHover(setHover, i, { leave: false })} />\n          ))}\n          {nav.pos &&\n            hover != null &&\n            (() => {\n              const b = box(c0(hover) + 1, cw - 2, valStart - (vert ? 4 : 0), valStart + valLen + (vert ? 22 : 0))\n              return <rect {...ringRect(b.x, b.y, b.width, b.height, { rx: 7, pad: 0 })} />\n            })()}\n        </svg>\n      )}\n\n      {hr && hover != null && (\n        <Readout\n          x={cc(hover)}\n          y={H / 2}\n          containerWidth={width}\n          containerHeight={H}\n          avoid={\n            vert\n              ? { x0: c0(hover) - 2, x1: c0(hover) + cw + 2, y0: valStart, y1: valStart + valLen, top: start.delta }\n              : { x0: valStart, x1: width, y0: c0(hover) - 2, y1: c0(hover) + cw + 2, vertical: true }\n          }\n          eyebrow={`${scen(hr)}${hr.goodWhenLower ? ' · lower is better' : ''}`}\n          title={hr.label}\n          headline={hr.value != null ? format(hr.value) : '–'}\n          rows={[\n            ...(hr.plan != null ? [{ label: S.plan, value: format(hr.plan), color: PL_STROKE }] : []),\n            ...(hr.prior != null ? [{ label: S.prior, value: format(hr.prior), color: PY_FILL }] : []),\n            ...deltaRows(hr, compare),\n            ...deltaRows(hr, compare === 'plan' ? 'prior' : 'plan'),\n          ]}\n          foot={hr.total ? (hr.scenario === 'AC+FC' ? `Year to date actuals plus forecast · own scale` : 'Own scale') : undefined}\n          width={212}\n        />\n      )}\n      {nav.pos && hr && (\n        <div className=\"sr-only\" aria-live=\"polite\">\n          {`${hr.label}: ${hr.value != null ? format(hr.value) : 'no value'}${delta(hr) != null ? `, ${signed(delta(hr)!, dfmt)} against ${base}` : ''}${deltaPct(hr) != null ? ` (${pctFmt(deltaPct(hr)!)})` : ''}`}\n        </div>\n      )}\n      <ChartDataTable\n        caption={label}\n        columns={[\n          { key: 'label', label: vert ? 'Period' : 'Item' },\n          { key: 'scenario', label: 'Scenario' },\n          { key: 'value', label: 'Value', format: (v) => (v == null ? '–' : format(v as number)) },\n          { key: 'plan', label: S.plan, format: (v) => (v == null ? '–' : format(v as number)) },\n          { key: 'prior', label: S.prior, format: (v) => (v == null ? '–' : format(v as number)) },\n          { key: 'deltaPlan', label: `Δ${S.plan}`, format: (v) => (v == null ? '–' : signed(v as number, dfmt)) },\n          { key: 'deltaPlanPct', label: `Δ${S.plan} %`, format: (v) => (v == null ? '–' : pctFmt(v as number)) },\n          { key: 'deltaPrior', label: `Δ${S.prior}`, format: (v) => (v == null ? '–' : signed(v as number, dfmt)) },\n          { key: 'deltaPriorPct', label: `Δ${S.prior} %`, format: (v) => (v == null ? '–' : pctFmt(v as number)) },\n        ]}\n        rows={varianceChartToRows(data, { goodWhenLower, totals, totalLabel })}\n      />\n      {legend && width > 0 && (\n        <ExportLegend\n          width={width}\n          height={22}\n          x={8}\n          items={[\n            { label: S.actual, color: AC_FILL, mark: 'bar' },\n            ...(rows.some((r) => r.scenario === 'FC') ? [{ label: `${S.forecast} (hatched)`, color: AC_FILL, mark: 'line' as const }] : []),\n            ...(showPlan ? [{ label: S.plan, color: PL_STROKE, mark: 'ring' as const }] : []),\n            ...(showPrior ? [{ label: S.prior, color: PY_FILL, mark: 'bar' as const }] : []),\n            { label: 'Favourable', color: 'var(--green)', mark: 'bar' },\n            { label: 'Unfavourable', color: 'var(--red)', mark: 'bar' },\n          ]}\n        />\n      )}\n      {legend && (\n        <div className=\"absolute inset-x-0 bottom-0 flex h-[22px] flex-wrap items-center gap-x-4 gap-y-1 px-2 text-[11.5px] text-fg-3\">\n          <span className=\"inline-flex items-center gap-1.5\">\n            <span className=\"h-3 w-2.5 rounded-[1px]\" style={{ background: AC_FILL }} />\n            {S.actual}\n          </span>\n          {rows.some((r) => r.scenario === 'FC' || r.scenario === 'AC+FC') && (\n            <span className=\"inline-flex items-center gap-1.5\">\n              <svg width={10} height={12}>\n                <rect x={0.6} y={0.6} width={8.8} height={10.8} fill={`url(#${uid}-fc)`} stroke={AC_FILL} strokeWidth={1.2} />\n              </svg>\n              {S.forecast}\n            </span>\n          )}\n          {showPlan && (\n            <span className=\"inline-flex items-center gap-1.5\">\n              <span className=\"h-3 w-2.5 rounded-[1px] border-[1.25px]\" style={{ borderColor: PL_STROKE }} />\n              {S.plan}\n            </span>\n          )}\n          {showPrior && (\n            <span className=\"inline-flex items-center gap-1.5\">\n              <span className=\"h-3 w-2.5 rounded-[1px]\" style={{ background: PY_FILL }} />\n              {S.prior}\n            </span>\n          )}\n          <span className=\"ml-auto inline-flex items-center gap-3\">\n            <span className=\"inline-flex items-center gap-1.5\">\n              <span className=\"size-2 rounded-[2px] bg-green\" />\n              Favourable\n            </span>\n            <span className=\"inline-flex items-center gap-1.5\">\n              <span className=\"size-2 rounded-[2px] bg-red\" />\n              Unfavourable\n            </span>\n            {(goodWhenLower || data.some((d) => d.goodWhenLower)) && <span className=\"text-fg-4\">· cost lines: lower is better</span>}\n          </span>\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/bi/VarianceChart.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/Readout.tsx",
      "content": "import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\nimport { placeClear, textW, type ReadoutAvoid } from '@/components/klar/charts/bi/util'\n\nexport interface ReadoutRow {\n  label: ReactNode\n  value: ReactNode\n  /** Swatch colour; `line` draws a short stroke instead of a dot. */\n  color?: string\n  line?: boolean\n  muted?: boolean\n}\n\n/**\n * Hover card shared by the BI charts: a small eyebrow, an optional headline\n * figure, rows of label/value pairs and an optional footnote. Positioned in\n * the chart's own pixel space and flipped to stay inside `containerWidth`.\n */\nexport function Readout({\n  x,\n  y,\n  containerWidth,\n  containerHeight,\n  eyebrow,\n  title,\n  headline,\n  rows = [],\n  foot,\n  place = 'side',\n  align = 'auto',\n  width = 196,\n  avoid,\n}: {\n  x: number\n  y: number\n  containerWidth: number\n  containerHeight?: number\n  eyebrow?: ReactNode\n  title?: ReactNode\n  headline?: ReactNode\n  rows?: ReadoutRow[]\n  foot?: ReactNode\n  /** `side` sits right of the point (flips left near the edge); `above` sits over it. */\n  place?: 'side' | 'above' | 'below'\n  /** Side placement: force the card to the right or left of the point. */\n  align?: 'auto' | 'right' | 'left'\n  width?: number\n  /**\n   * Box to keep clear (the hovered mark, usually widened to its neighbours). When\n   * given, the card goes right of it, else left, else above, else below, whichever\n   * fits first inside the container, so it never sits on the marks being read.\n   */\n  avoid?: ReadoutAvoid\n}) {\n  const box = useRef<HTMLDivElement>(null)\n  const [h, setH] = useState(120)\n  useLayoutEffect(() => {\n    const el = box.current\n    if (!el) return\n    const update = () => setH((p) => (Math.abs(el.offsetHeight - p) > 1 ? el.offsetHeight : p))\n    update()\n    const ro = new ResizeObserver(update)\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [])\n  let left = x\n  let top: number\n  let transform: string | undefined\n  if (avoid) {\n    const p = placeClear(avoid, width, h, containerWidth, containerHeight ?? Infinity, align)\n    left = p.left\n    top = p.top\n  } else if (place === 'above' || place === 'below') {\n    left = Math.max(width / 2 + 4, Math.min(containerWidth - width / 2 - 4, x))\n    transform = place === 'above' ? 'translate(-50%, calc(-100% - 12px))' : 'translate(-50%, 12px)'\n  } else {\n    const flip = align === 'left' || (align === 'auto' && x > containerWidth - width - 24)\n    transform = `translate(${flip ? 'calc(-100% - 14px)' : '14px'}, -50%)`\n  }\n  if (!avoid) top = containerHeight != null && place === 'side' ? Math.max(80, Math.min(containerHeight - 100, y)) : y\n  return (\n    <div\n      ref={box}\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, top: top!, transform, width, transition: 'left 90ms ease-out, top 90ms ease-out' }}\n    >\n      {eyebrow && <div className=\"text-[10.5px] font-medium tracking-[0.04em] text-fg-3 uppercase\">{eyebrow}</div>}\n      {title && <div className={cn('text-[12.5px] leading-snug font-semibold text-fg', eyebrow && 'mt-0.5')}>{title}</div>}\n      {headline && <div className=\"num mt-1 text-[20px] leading-none font-semibold tracking-tight text-fg\">{headline}</div>}\n      {rows.length > 0 && (\n        <div className={cn('flex flex-col gap-[5px]', (title || headline || eyebrow) && 'mt-2 border-t border-border pt-2')}>\n          {rows.map((r, i) => (\n            <div key={i} className=\"flex items-center justify-between gap-3 text-[12px]\">\n              <span className={cn('flex min-w-0 items-center gap-1.5', r.muted ? 'text-fg-3' : 'text-fg-2')}>\n                {r.color &&\n                  (r.line ? (\n                    <span className=\"h-[2px] w-2.5 shrink-0 rounded-full\" style={{ background: 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 font-semibold', r.muted ? 'text-fg-2' : 'text-fg')}>{r.value}</span>\n            </div>\n          ))}\n        </div>\n      )}\n      {foot && <div className=\"mt-2 border-t border-border pt-1.5 text-[11px] leading-snug text-fg-3\">{foot}</div>}\n    </div>\n  )\n}\n\n/** Small tinted chip for statuses inside readouts and labels. */\nexport function Chip({ color, children, className }: { color: string; children: ReactNode; className?: string }) {\n  return (\n    <span\n      className={cn('num inline-flex h-[18px] items-center rounded-[5px] px-1.5 text-[11px] font-semibold whitespace-nowrap', className)}\n      style={{ color: `color-mix(in oklab, ${color} 85%, var(--fg))`, background: `color-mix(in oklab, ${color} 14%, transparent)` }}\n    >\n      {children}\n    </span>\n  )\n}\n\nexport interface ExportLegendItem {\n  label: string\n  color: string\n  /** dot (default), ring (hollow dot), line, bar, tick or diamond */\n  mark?: 'dot' | 'ring' | 'line' | 'bar' | 'tick' | 'diamond'\n}\n\n/**\n * SVG twin of an HTML legend, for SVG/PNG export only. It sits under the HTML\n * legend with the `invisible` utility class, which the page hides but a standalone\n * exported SVG (no stylesheet) does not, so exports keep the series names.\n */\nexport function ExportLegend({ items, width, height = 20, x = 0, className }: { items: ExportLegendItem[]; width: number; height?: number; x?: number; className?: string }) {\n  const xs: number[] = []\n  for (let i = 0, acc = x; i < items.length; i++) {\n    xs.push(acc)\n    acc += 18 + textW(items[i].label, 11.5) + 16\n  }\n  const cy = height / 2\n  return (\n    <svg width={width} height={height} aria-hidden className={cn('pointer-events-none invisible absolute inset-x-0 bottom-0', className)}>\n      {items.map((it, i) => {\n        const x0 = xs[i]\n        const m = it.mark ?? 'dot'\n        return (\n          <g key={i}>\n            {m === 'dot' && <circle cx={x0 + 5} cy={cy} r={4.5} fill={it.color} />}\n            {m === 'ring' && <circle cx={x0 + 5} cy={cy} r={4} fill=\"none\" stroke={it.color} strokeWidth={2} />}\n            {m === 'line' && <rect x={x0} y={cy - 1} width={14} height={2} rx={1} fill={it.color} />}\n            {m === 'bar' && <rect x={x0} y={cy - 2} width={16} height={4} rx={1} fill={it.color} />}\n            {m === 'tick' && <rect x={x0 + 4} y={cy - 6} width={2.5} height={12} rx={1} fill={it.color} />}\n            {m === 'diamond' && <rect x={x0 + 1.5} y={cy - 3.5} width={7} height={7} transform={`rotate(45 ${x0 + 5} ${cy})`} fill={it.color} />}\n            <text x={x0 + 18} y={cy + 4} fill=\"var(--fg-3)\" style={{ fontSize: 11.5 }}>\n              {it.label}\n            </text>\n          </g>\n        )\n      })}\n    </svg>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/bi/Readout.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/bi/util.ts",
      "content": "/* Shared helpers for the BI collection: ticks, label dodging, text metrics, locale. */\nimport { fmt } from '@/components/klar/lib/format'\nimport { formatter } from '@/components/klar/charts/basic/core'\n\n\nexport const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v))\n\n/** \"Nice\" tick values covering [min, max] with roughly `count` steps. */\nexport function niceTicks(min: number, max: number, count = 5): number[] {\n  if (!(max > min)) return [min]\n  const raw = (max - min) / Math.max(1, count)\n  const exp = Math.pow(10, Math.floor(Math.log10(raw)))\n  const f = raw / exp\n  const step = (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * exp\n  const lo = Math.ceil(min / step - 1e-9) * step\n  const out: number[] = []\n  for (let v = lo; v <= max + step * 1e-6; v += step) out.push(+v.toFixed(10))\n  return out\n}\n\n/** A nice [lo, hi] domain around the data, padded by `pad` of the range. */\nexport function niceDomain(min: number, max: number, count = 5, pad = 0.06): [number, number] {\n  const r = max - min || Math.abs(max) || 1\n  const a = min - r * pad\n  const b = max + r * pad\n  const t = niceTicks(a, b, count)\n  const step = t.length > 1 ? t[1] - t[0] : r\n  return [Math.floor(a / step) * step, Math.ceil(b / step) * step]\n}\n\n/** Rough rendered width of a string at a given font size (Inter, tabular). */\nexport const textW = (s: string, px = 12, weight = 400) => s.length * px * (weight >= 600 ? 0.6 : 0.56)\n\n/**\n * 1-D label collision avoidance. Takes desired centre positions and returns\n * positions at least `gap` apart, kept inside [lo, hi], moving labels as little\n * as possible (clusters are centred on their mean).\n */\nexport function dodge(want: number[], gap: number, lo: number, hi: number): number[] {\n  const idx = want.map((_, i) => i).sort((a, b) => want[a] - want[b])\n  type Block = { start: number; ids: number[]; mean: number }\n  const blocks: Block[] = []\n  for (const i of idx) {\n    blocks.push({ start: want[i], ids: [i], mean: want[i] })\n    // merge while overlapping the previous block\n    while (blocks.length > 1) {\n      const b = blocks[blocks.length - 1]\n      const a = blocks[blocks.length - 2]\n      if (a.start + a.ids.length * gap <= b.start) break\n      const ids = [...a.ids, ...b.ids]\n      const mean = ids.reduce((s, k) => s + want[k], 0) / ids.length\n      blocks.splice(blocks.length - 2, 2, { ids, mean, start: mean - ((ids.length - 1) * gap) / 2 })\n    }\n  }\n  const out = new Array<number>(want.length)\n  for (const b of blocks) b.ids.forEach((k, j) => (out[k] = b.start + j * gap))\n  // clamp into bounds by sliding the whole stack\n  const order = idx\n  for (let j = 0; j < order.length; j++) {\n    const k = order[j]\n    const min = lo + j * gap\n    if (out[k] < min) out[k] = min\n    if (j > 0 && out[k] < out[order[j - 1]] + gap) out[k] = out[order[j - 1]] + gap\n  }\n  for (let j = order.length - 1; j >= 0; j--) {\n    const k = order[j]\n    const max = hi - (order.length - 1 - j) * gap\n    if (out[k] > max) out[k] = max\n    if (j < order.length - 1 && out[k] > out[order[j + 1]] - gap) out[k] = out[order[j + 1]] - gap\n  }\n  return out\n}\n\n/** Signed number with an explicit + sign. */\nexport const signed = (v: number, f: (v: number) => string) => (v > 0 ? '+' : v < 0 ? '−' : '±') + f(Math.abs(v))\n\n/** Split a label into at most two lines that fit `max` px; ellipsis if still too long. */\nexport function wrap2(s: string, max: number, px = 11): string[] {\n  if (textW(s, px) <= max) return [s]\n  const words = s.split(' ')\n  let a = ''\n  let i = 0\n  while (i < words.length && textW((a ? a + ' ' : '') + words[i], px) <= max) a = (a ? a + ' ' : '') + words[i++]\n  if (!a) a = words[i++] ?? ''\n  let b = words.slice(i).join(' ')\n  const fit = (t: string) => {\n    while (t.length > 1 && textW(t + '…', px) > max) t = t.slice(0, -1)\n    return t + '…'\n  }\n  if (textW(a, px) > max) a = fit(a)\n  if (b && textW(b, px) > max) b = fit(b)\n  return b ? [a, b] : [a]\n}\n\n/** Colour for a sequential step t∈[0,1] of a hue, mixed over the surface. */\nexport const ramp = (color: string, t: number, floor = 10) =>\n  `color-mix(in oklab, ${color} ${Math.round(floor + clamp(t, 0, 1) * (100 - floor))}%, var(--surface-3))`\n\n/** Tick labels drop a trailing \".0\" ($40.0M → $40M, 80.0% → 80%). */\nexport const trimTick = (s: string) => s.replace(/\\.0(?=\\D*$)/, '')\n\nexport interface ReadoutAvoid {\n  x0: number\n  x1: number\n  y0: number\n  y1: number\n  /** Preferred top edge when the card sits beside the box (default: centred on it). */\n  top?: number\n  /** Preferred vertical centre when the card sits beside the box. */\n  cy?: number\n  /** Try above/below before the sides (columns: the space over short bars is free). */\n  vertical?: boolean\n}\n\nconst GAP = 12\n\n/** Top-left of a `w`×`h` card placed beside `a` without overlapping it, inside the container. */\nexport function placeClear(a: ReadoutAvoid, w: number, h: number, cw: number, ch: number, align: 'auto' | 'right' | 'left' = 'auto') {\n  const midY = (a.y0 + a.y1) / 2\n  const midX = (a.x0 + a.x1) / 2\n  const vClamp = (t: number) => Math.max(4, Math.min((isFinite(ch) ? ch : t + h + 4) - h - 4, t))\n  const hClamp = (l: number) => Math.max(4, Math.min(cw - w - 4, l))\n  const sideTop = vClamp(a.top ?? (a.cy ?? midY) - h / 2)\n  const right = { left: a.x1 + GAP, top: sideTop, room: cw - a.x1 - GAP - w }\n  const leftS = { left: a.x0 - GAP - w, top: sideTop, room: a.x0 - GAP - w }\n  const above = { left: hClamp(midX - w / 2), top: a.y0 - GAP - h, room: a.y0 - GAP - h }\n  const below = { left: hClamp(midX - w / 2), top: a.y1 + GAP, room: (isFinite(ch) ? ch : Infinity) - a.y1 - GAP - h }\n  const sides = align === 'left' ? [leftS, right] : [right, leftS]\n  const order = a.vertical ? [above, below, ...sides] : [...sides, above, below]\n  const fit = order.find((c) => c.room >= 0)\n  if (fit) return { left: fit.left, top: fit.top }\n  // Nothing fits cleanly: take the side with the most room, kept inside the container.\n  const best = [right, leftS].sort((p, q) => q.room - p.room)[0]\n  return { left: hClamp(best.left), top: best.top }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Locale                                                            */\n/* ------------------------------------------------------------------ */\n\nconst LEGACY = {\n  int: fmt.int,\n  short: fmt.short,\n  /** Fixed decimals, no grouping (as `toFixed`). */\n  fixed: (v: number, digits = 1) => v.toFixed(digits),\n  /** Grouped, up to `max` decimals. */\n  group: (v: number, max = 1) => v.toLocaleString(DEFAULT_LOCALE, { maximumFractionDigits: max }),\n}\nexport type BiNumbers = typeof LEGACY\n\nconst DEFAULT_LOCALE = 'en-US'\nconst numCache = new Map<string, BiNumbers>()\n\n/**\n * Number helpers for the BI charts. With no `locale` they are exactly the en-US\n * helpers the charts always used, so existing call sites render identically; with\n * one (e.g. 'de-DE') every built-in label follows it (12.480 · 1,2 Mio. · 4,5).\n */\nexport function biNumbers(locale?: string): BiNumbers {\n  if (!locale) return LEGACY\n  const hit = numCache.get(locale)\n  if (hit) return hit\n  const f = formatter(locale)\n  const out: BiNumbers = {\n    int: (v) => f.number(Math.round(v)),\n    short: (v) => f.compact(v),\n    fixed: (v, digits = 1) => f.number(v, digits),\n    group: (v, max = 1) => new Intl.NumberFormat(locale, { maximumFractionDigits: max }).format(v),\n  }\n  numCache.set(locale, out)\n  return out\n}\n\nconst MONTHS_EN = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\nconst DAYS_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\n\n/** Short month (Jan…) and weekday (Sun…) names; English unless a locale is given. */\nexport function calendarNames(locale?: string): { months: string[]; days: string[] } {\n  if (!locale) return { months: MONTHS_EN, days: DAYS_EN }\n  const m = new Intl.DateTimeFormat(locale, { month: 'short', timeZone: 'UTC' })\n  const d = new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' })\n  return {\n    months: MONTHS_EN.map((_, i) => m.format(Date.UTC(2024, i, 1))),\n    // 2024-09-01 was a Sunday.\n    days: DAYS_EN.map((_, i) => d.format(Date.UTC(2024, 8, 1 + i))),\n  }\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/bi/util.ts"
    },
    {
      "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"
    },
    {
      "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"
    }
  ],
  "docs": "import { VarianceChart } from '@/components/klar/charts/bi/VarianceChart'\nData comes in through props.",
  "categories": [
    "charts",
    "bi",
    "comparison"
  ],
  "meta": {
    "collection": "bi",
    "kind": "comparison",
    "tags": [
      "variance",
      "ibcs",
      "plan-vs-actual",
      "budget",
      "forecast",
      "prior-year",
      "hichert",
      "financial-reporting"
    ],
    "standalone": true,
    "export": "VarianceChart",
    "import": "@/components/klar/charts/bi/VarianceChart"
  }
}
