{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bi-control-chart",
  "type": "registry:component",
  "title": "Control chart",
  "description": "A process measured day by day against its centre line and control limits, with Western Electric or Nelson rule violations flagged and limits recalculated after a process change.",
  "dependencies": [
    "clsx",
    "lucide-react",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "https://klar.run/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/klar/components/charts/bi/ControlChart.tsx",
      "content": "import { useMemo, useRef, useState } 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 { ExportMirror, usePlotPointer } from '@/components/klar/charts/science/parts'\nimport { Readout, type ReadoutRow } from '@/components/klar/charts/bi/Readout'\nimport { useChartNav } from '@/components/klar/charts/bi/interaction'\nimport { biNumbers, dodge, niceTicks, textW } from '@/components/klar/charts/bi/util'\nimport { dateLabel, sgn } from '@/components/klar/charts/bi/bi-b-util'\n\n/* ------------------------------------------------------------------ */\n/*  Maths: control limits and run rules                               */\n/* ------------------------------------------------------------------ */\n\n/**\n * Control-chart constants by subgroup size n (Montgomery, \"Introduction to Statistical\n * Quality Control\", Appendix VI): d2 = E[R]/σ, A2 = 3/(d2·√n), D3/D4 the R-chart factors.\n */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport const CONTROL_CONSTANTS: Record<number, { d2: number; A2: number; D3: number; D4: number }> = {\n  2: { d2: 1.128, A2: 1.88, D3: 0, D4: 3.267 },\n  3: { d2: 1.693, A2: 1.023, D3: 0, D4: 2.574 },\n  4: { d2: 2.059, A2: 0.729, D3: 0, D4: 2.282 },\n  5: { d2: 2.326, A2: 0.577, D3: 0, D4: 2.114 },\n  6: { d2: 2.534, A2: 0.483, D3: 0, D4: 2.004 },\n  7: { d2: 2.704, A2: 0.419, D3: 0.076, D4: 1.924 },\n  8: { d2: 2.847, A2: 0.373, D3: 0.136, D4: 1.864 },\n  9: { d2: 2.97, A2: 0.337, D3: 0.184, D4: 1.816 },\n  10: { d2: 3.078, A2: 0.308, D3: 0.223, D4: 1.777 },\n}\n\nexport type ControlMode = 'xmr' | 'xbar-r' | 'p'\n\nexport type ControlInput =\n  | { mode: 'xmr'; values: number[]; phases?: (string | undefined)[] }\n  | { mode: 'xbar-r'; subgroups: number[][]; phases?: (string | undefined)[] }\n  | { mode: 'p'; counts: number[]; sizes: number[]; phases?: (string | undefined)[] }\n\nexport interface ControlPhase {\n  phase: string\n  /** First index (inclusive) and end (exclusive) in the input. */\n  start: number\n  end: number\n  /** Centre line: x̄ (X–mR), x̿ (x̄–R) or p̄ (p chart). */\n  center: number\n  /** σ of the plotted statistic (for p charts, at the average subgroup size). */\n  sigma: number\n  /** Per-point σ, UCL, LCL and plotted value, local to the phase. */\n  sigmas: number[]\n  ucl: number[]\n  lcl: number[]\n  values: number[]\n  /** Moving range (X–mR) or subgroup range (x̄–R); null where undefined. Empty for p charts. */\n  ranges: (number | null)[]\n  rangeCenter: number\n  rangeUcl: number\n  rangeLcl: number\n}\n\nconst mean = (a: number[]) => (a.length ? a.reduce((s, v) => s + v, 0) / a.length : NaN)\nconst K = (n: number) => CONTROL_CONSTANTS[Math.max(2, Math.min(10, Math.round(n)))]\n\n/**\n * Control limits for an individuals (X–mR), x̄–R or p chart, recomputed for each phase\n * (a new phase starts wherever `phases[i]` changes).\n * - X–mR: σ̂ = MR̄ / d2 (d2 = 1.128), limits x̄ ± 3σ̂; MR chart UCL = D4·MR̄ = 3.267·MR̄.\n * - x̄–R: limits x̿ ± A2·R̄; R chart D3·R̄ … D4·R̄; σ of x̄ = R̄ / (d2·√n).\n * - p: p̄ = Σd / Σn, limits p̄ ± 3·√(p̄(1 − p̄)/nᵢ) per subgroup, clipped to [0, 1].\n */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport function controlLimits(input: ControlInput): ControlPhase[] {\n  const n = input.mode === 'xmr' ? input.values.length : input.mode === 'xbar-r' ? input.subgroups.length : input.counts.length\n  const ph = input.phases\n  const out: ControlPhase[] = []\n  let s = 0\n  for (let i = 1; i <= n; i++) {\n    if (i < n && (ph?.[i] ?? '') === (ph?.[s] ?? '')) continue\n    const e = i\n    const name = ph?.[s] ?? ''\n    if (input.mode === 'xmr') {\n      const v = input.values.slice(s, e)\n      const mr = v.map((x, k) => (k ? Math.abs(x - v[k - 1]) : null))\n      const mrs = mr.filter((m): m is number => m != null)\n      const mrBar = mrs.length ? mean(mrs) : 0\n      const c = mean(v)\n      const sig = mrBar / 1.128\n      out.push({ phase: name, start: s, end: e, center: c, sigma: sig, sigmas: v.map(() => sig), ucl: v.map(() => c + 3 * sig), lcl: v.map(() => c - 3 * sig), values: v, ranges: mr, rangeCenter: mrBar, rangeUcl: 3.267 * mrBar, rangeLcl: 0 })\n    } else if (input.mode === 'xbar-r') {\n      const g = input.subgroups.slice(s, e)\n      const means = g.map(mean)\n      const r = g.map((x) => Math.max(...x) - Math.min(...x))\n      const sizes = g.map((x) => x.length)\n      const size = mode(sizes)\n      const k = K(size)\n      const c = mean(means)\n      const rBar = mean(r)\n      const sig = rBar / k.d2 / Math.sqrt(size)\n      out.push({ phase: name, start: s, end: e, center: c, sigma: sig, sigmas: means.map(() => sig), ucl: means.map(() => c + k.A2 * rBar), lcl: means.map(() => c - k.A2 * rBar), values: means, ranges: r, rangeCenter: rBar, rangeUcl: k.D4 * rBar, rangeLcl: k.D3 * rBar })\n    } else {\n      const d = input.counts.slice(s, e)\n      const sz = input.sizes.slice(s, e)\n      const tot = sz.reduce((a, b) => a + b, 0)\n      const p = tot ? d.reduce((a, b) => a + b, 0) / tot : 0\n      const sig = (m: number) => Math.sqrt((p * (1 - p)) / Math.max(1, m))\n      const sigmas = sz.map(sig)\n      out.push({\n        phase: name,\n        start: s,\n        end: e,\n        center: p,\n        sigma: sig(tot / Math.max(1, sz.length)),\n        sigmas,\n        ucl: sigmas.map((q) => Math.min(1, p + 3 * q)),\n        lcl: sigmas.map((q) => Math.max(0, p - 3 * q)),\n        values: d.map((x, k) => (sz[k] ? x / sz[k] : 0)),\n        ranges: [],\n        rangeCenter: NaN,\n        rangeUcl: NaN,\n        rangeLcl: NaN,\n      })\n    }\n    s = i\n  }\n  return out\n}\n\nfunction mode(a: number[]) {\n  const c = new Map<number, number>()\n  let best = a[0] ?? 2\n  for (const v of a) {\n    c.set(v, (c.get(v) ?? 0) + 1)\n    if (c.get(v)! > (c.get(best) ?? 0)) best = v\n  }\n  return best\n}\n\nexport type Ruleset = 'western-electric' | 'nelson'\n\n/** Plain descriptions of each rule, by ruleset and number. */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport const RULE_TEXT: Record<Ruleset, Record<number, string>> = {\n  'western-electric': {\n    1: 'One point beyond 3σ',\n    2: '2 of 3 beyond 2σ, same side',\n    3: '4 of 5 beyond 1σ, same side',\n    4: '8 in a row on one side of CL',\n  },\n  nelson: {\n    1: 'One point beyond 3σ',\n    2: '9 in a row on one side of CL',\n    3: '6 in a row rising or falling',\n    4: '14 in a row alternating',\n    5: '2 of 3 beyond 2σ, same side',\n    6: '4 of 5 beyond 1σ, same side',\n    7: '15 in a row within 1σ',\n    8: '8 in a row beyond 1σ, either side',\n  },\n}\n\nexport interface RuleHits {\n  /** Per rule: indices where the rule fires (the pattern completes) and every point in a firing pattern. */\n  byRule: Record<number, { trigger: number[]; points: number[] }>\n  /** Per point: the rule numbers that fire at it. */\n  byPoint: number[][]\n  /** Per point: whether it belongs to any firing pattern. */\n  inPattern: boolean[]\n}\n\n/**\n * Western Electric (1956) or Nelson (1984) run rules on a control chart's values.\n * `center` and `sigma` are scalars or per-point arrays (p charts with varying limits).\n * Western Electric: 1 beyond 3σ · 2 two of three beyond 2σ · 3 four of five beyond 1σ ·\n * 4 eight in a row on one side. Nelson: 1 beyond 3σ · 2 nine on one side · 3 six rising or\n * falling · 4 fourteen alternating · 5 two of three beyond 2σ · 6 four of five beyond 1σ ·\n * 7 fifteen within 1σ · 8 eight beyond 1σ on either side. \"k of n\" rules count same-side\n * points in the n-point window ending at the firing point, which must itself be one of them.\n */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport function nelsonRules(\n  values: number[],\n  center: number | number[],\n  sigma: number | number[],\n  { ruleset = 'nelson', rules }: { ruleset?: Ruleset; rules?: number[] } = {},\n): RuleHits {\n  const n = values.length\n  const z = values.map((v, i) => {\n    const c = typeof center === 'number' ? center : center[i]\n    const s = typeof sigma === 'number' ? sigma : sigma[i]\n    return s > 0 ? (v - c) / s : 0\n  })\n  const all = ruleset === 'nelson' ? [1, 2, 3, 4, 5, 6, 7, 8] : [1, 2, 3, 4]\n  const on = new Set(rules ?? all)\n  const byRule: RuleHits['byRule'] = {}\n  const byPoint: number[][] = values.map(() => [])\n  const member = new Array<boolean>(n).fill(false)\n  const add = (rule: number, i: number, pts: number[]) => {\n    const r = (byRule[rule] ??= { trigger: [], points: [] })\n    r.trigger.push(i)\n    byPoint[i].push(rule)\n    for (const p of pts) {\n      member[p] = true\n      if (!r.points.includes(p)) r.points.push(p)\n    }\n  }\n  const kOfN = (rule: number, k: number, w: number, thr: number) => {\n    for (let i = 0; i < n; i++)\n      for (const side of [1, -1]) {\n        if (side * z[i] <= thr) continue\n        const pts: number[] = []\n        for (let j = Math.max(0, i - w + 1); j <= i; j++) if (side * z[j] > thr) pts.push(j)\n        if (pts.length >= k) add(rule, i, pts)\n      }\n  }\n  const run = (rule: number, len: number, test: (i: number) => number) => {\n    // test → a key; consecutive equal non-zero keys form a run\n    let startI = 0\n    for (let i = 0; i < n; i++) {\n      const key = test(i)\n      if (!key || (i > 0 && key !== test(i - 1))) startI = i\n      if (key && i - startI + 1 >= len) add(rule, i, range(startI, i))\n    }\n  }\n  const range = (a: number, b: number) => Array.from({ length: b - a + 1 }, (_, k) => a + k)\n  const side = (i: number) => (z[i] > 0 ? 1 : z[i] < 0 ? -1 : 0)\n  const trend = (rule: number, len: number) => {\n    // len points with len − 1 strictly monotone steps\n    let startI = 0\n    let dir = 0\n    for (let i = 1; i < n; i++) {\n      const d = Math.sign(values[i] - values[i - 1])\n      if (!d || d !== dir) startI = i - 1\n      dir = d\n      if (d && i - startI + 1 >= len) add(rule, i, range(startI, i))\n    }\n  }\n  const alternating = (rule: number, len: number) => {\n    let startI = 0\n    let prev = 0\n    for (let i = 1; i < n; i++) {\n      const d = Math.sign(values[i] - values[i - 1])\n      if (!d) startI = i\n      else if (prev && d === prev) startI = i - 1\n      else if (!prev) startI = i - 1\n      prev = d\n      if (d && i - startI + 1 >= len) add(rule, i, range(startI, i))\n    }\n  }\n  if (on.has(1))\n    for (let i = 0; i < n; i++) if (Math.abs(z[i]) > 3) add(1, i, [i])\n  if (ruleset === 'western-electric') {\n    if (on.has(2)) kOfN(2, 2, 3, 2)\n    if (on.has(3)) kOfN(3, 4, 5, 1)\n    if (on.has(4)) run(4, 8, side)\n  } else {\n    if (on.has(2)) run(2, 9, side)\n    if (on.has(3)) trend(3, 6)\n    if (on.has(4)) alternating(4, 14)\n    if (on.has(5)) kOfN(5, 2, 3, 2)\n    if (on.has(6)) kOfN(6, 4, 5, 1)\n    if (on.has(7)) run(7, 15, (i) => (Math.abs(z[i]) < 1 ? 1 : 0))\n    if (on.has(8)) run(8, 8, (i) => (Math.abs(z[i]) > 1 ? 1 : 0))\n  }\n  for (const r of all) {\n    if (!on.has(r)) continue\n    byRule[r] ??= { trigger: [], points: [] }\n    byRule[r].points.sort((a, b) => a - b)\n  }\n  for (const p of byPoint) p.sort((a, b) => a - b)\n  return { byRule, byPoint, inPattern: member }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Chart                                                             */\n/* ------------------------------------------------------------------ */\n\nexport interface ControlPoint {\n  /** ISO date or a subgroup label (\"Lot 14\"). */\n  label: string\n  /** X–mR: the individual measurement. */\n  value?: number\n  /** x̄–R: the subgroup's measurements. */\n  subgroup?: number[]\n  /** p chart: nonconforming count and subgroup size. */\n  count?: number\n  size?: number\n  /** Phase name; limits are recalculated wherever it changes (e.g. after a process change). */\n  phase?: string\n}\n\nexport interface ControlChartProps {\n  data: ControlPoint[]\n  mode?: ControlMode\n  ruleset?: Ruleset\n  /** Rule numbers to evaluate (default: all in the ruleset). */\n  rules?: number[]\n  /** Shade the A / B / C zones (±1σ, ±2σ, ±3σ). */\n  zones?: boolean\n  /** Second panel with the moving range / range (X–mR and x̄–R only). */\n  rangePanel?: boolean\n  format?: (v: number) => string\n  /** Unit suffix for values, e.g. \"h\". */\n  unit?: string\n  /** Name of the measure, e.g. \"Fulfilment time\". */\n  valueLabel?: string\n  /** Noun for one subgroup in the readout, e.g. \"Day\". */\n  subgroupNoun?: string\n  height?: number\n  locale?: string\n  className?: string\n  ariaLabel?: string\n}\n\nconst ISO = /^\\d{4}-\\d{2}-\\d{2}/\nconst ZONE_TINT = { A: 'var(--red)', B: 'var(--amber)', C: 'var(--green)' }\n\n/**\n * Statistical process control chart: individuals with a moving-range panel (`xmr`),\n * subgroup means with a range panel (`xbar-r`) or proportion nonconforming with\n * limits that step with each subgroup's size (`p`). Draws the centre line, UCL / LCL\n * and the A / B / C zones at ±1σ / ±2σ / ±3σ; evaluates Western Electric or Nelson run\n * rules per phase and flags firing points with their rule numbers, with a rule legend\n * (hover a rule to light its points). Phases (a `phase` change in the data) get their\n * own limits and a labelled divider.\n * Data: `{ label, value | subgroup | count + size, phase? }[]`.\n *\n * Interaction: hover, tap or drag across points for value, limits, σ distance and the\n * rules that fired; Tab to the chart, then ←/→ (Home/End) step points, Esc clears.\n * Comfortable from 20 to ~400 subgroups.\n */\nexport function ControlChart({\n  data,\n  mode = 'xmr',\n  ruleset = 'western-electric',\n  rules,\n  zones = true,\n  rangePanel = true,\n  format: formatIn,\n  unit = '',\n  valueLabel,\n  subgroupNoun = 'Point',\n  height = 460,\n  locale,\n  className,\n  ariaLabel,\n}: ControlChartProps) {\n  const [ref, { width }] = useMeasure()\n  const legendRef = useRef<HTMLDivElement>(null)\n  const nums = biNumbers(locale)\n  const isP = mode === 'p'\n  const format = formatIn ?? (isP ? (v: number) => `${nums.fixed(v * 100, 1)}%` : (v: number) => nums.fixed(v, 1) + (unit ? ` ${unit}` : ''))\n  const [hover, setHover] = useState<number | null>(null)\n  const [ruleHover, setRuleHover] = useState<number | null>(null)\n\n  const phases = useMemo(() => {\n    const ph = data.map((d) => d.phase)\n    if (mode === 'xmr') return controlLimits({ mode, values: data.map((d) => d.value ?? NaN), phases: ph })\n    if (mode === 'xbar-r') return controlLimits({ mode, subgroups: data.map((d) => d.subgroup ?? []), phases: ph })\n    return controlLimits({ mode, counts: data.map((d) => d.count ?? 0), sizes: data.map((d) => d.size ?? 0), phases: ph })\n  }, [data, mode])\n\n  const ruleKey = rules?.join(',') ?? ''\n  const hits = useMemo(() => {\n    const n = data.length\n    const byPoint: number[][] = Array.from({ length: n }, () => [])\n    const inPattern = new Array<boolean>(n).fill(false)\n    const byRule: Record<number, { trigger: number[]; points: number[] }> = {}\n    const list = ruleKey ? ruleKey.split(',').map(Number) : undefined\n    for (const p of phases) {\n      const r = nelsonRules(p.values, p.center, p.sigmas, { ruleset, rules: list })\n      r.byPoint.forEach((v, k) => (byPoint[p.start + k] = v))\n      r.inPattern.forEach((v, k) => (inPattern[p.start + k] = v))\n      for (const [k, v] of Object.entries(r.byRule)) {\n        const t = (byRule[+k] ??= { trigger: [], points: [] })\n        t.trigger.push(...v.trigger.map((i) => i + p.start))\n        t.points.push(...v.points.map((i) => i + p.start))\n      }\n    }\n    return { byPoint, inPattern, byRule }\n  }, [phases, ruleset, ruleKey, data.length])\n\n  type Pt = { i: number; v: number; cl: number; ucl: number; lcl: number; sig: number; r: number | null; ph: ControlPhase; pi: number }\n  const pts: Pt[] = useMemo(\n    () => phases.flatMap((p, pi) => p.values.map((v, k) => ({ i: p.start + k, v, cl: p.center, ucl: p.ucl[k], lcl: p.lcl[k], sig: p.sigmas[k], r: p.ranges[k] ?? null, ph: p, pi }))),\n    [phases],\n  )\n  const n = pts.length\n  const showRange = rangePanel && !isP\n\n  /* geometry */\n  const legendH = 34\n  const H = height - legendH\n  const pad = { l: 50, r: 96, t: 34, b: 26 }\n  const gap = showRange ? 30 : 0\n  const avail = H - pad.t - pad.b - gap\n  const mainH = showRange ? Math.round(avail * 0.7) : avail\n  const rangeH = showRange ? avail - mainH : 0\n  const iw = Math.max(10, width - pad.l - pad.r)\n  const slot = n ? iw / n : iw\n  const x = (i: number) => pad.l + slot * (i + 0.5)\n  let lo = Infinity\n  let hi = -Infinity\n  for (const p of pts) {\n    lo = Math.min(lo, p.v, p.lcl, p.cl - 3 * p.sig)\n    hi = Math.max(hi, p.v, p.ucl)\n  }\n  if (isP) lo = Math.max(0, lo)\n  if (!Number.isFinite(lo)) [lo, hi] = [0, 1]\n  const sp = hi - lo || 1\n  const yt = niceTicks(lo - sp * 0.04, hi + sp * 0.06, Math.max(3, Math.round(mainH / 54)))\n  const ys = yt.length > 1 ? yt[1] - yt[0] : sp\n  const d0 = Math.min(yt[0], lo - sp * 0.04)\n  const d1 = Math.max(yt[yt.length - 1], hi + sp * 0.04)\n  const y = (v: number) => pad.t + mainH - ((v - d0) / (d1 - d0 || 1)) * mainH\n  const tickFmt = (v: number) => (isP ? `${nums.fixed(v * 100, ys * 100 < 1 ? 1 : 0)}%` : nums.fixed(v, ys < 1 ? 1 : 0))\n\n  const rTop = pad.t + mainH + gap\n  const rMax = showRange ? Math.max(...pts.map((p) => p.r ?? 0), ...phases.map((p) => p.rangeUcl)) * 1.08 || 1 : 1\n  const ry = (v: number) => rTop + rangeH - (v / rMax) * rangeH\n  const rTicks = showRange ? niceTicks(0, rMax, 2).filter((t) => t <= rMax) : []\n\n  /* phase-wise step paths for limits and zones (steps change halfway between points) */\n  const stepPts = (p: ControlPhase, f: (k: number) => number) => {\n    const out: [number, number][] = []\n    const len = p.end - p.start\n    for (let k = 0; k < len; k++) {\n      const a = k === 0 ? pad.l + slot * p.start : x(p.start + k) - slot / 2\n      const b = k === len - 1 ? pad.l + slot * p.end : x(p.start + k) + slot / 2\n      const v = y(f(k))\n      out.push([a, v], [b, v])\n    }\n    return out\n  }\n  const P = (q: [number, number][]) => q.map(([a, b], k) => `${k ? 'L' : 'M'}${a.toFixed(1)},${b.toFixed(1)}`).join('')\n  const bandPath = (p: ControlPhase, f0: (k: number) => number, f1: (k: number) => number) => P(stepPts(p, f0)) + P(stepPts(p, f1).reverse()).replace(/^M/, 'L') + 'Z'\n  const clip = (v: number) => (isP ? Math.max(0, Math.min(1, v)) : v)\n\n  /* badges: one per run of identical trigger sets */\n  const badges: { i: number; rules: number[] }[] = []\n  for (let i = 0; i < n; i++) {\n    const r = hits.byPoint[i]\n    if (!r.length) continue\n    const prev = i > 0 ? hits.byPoint[i - 1] : []\n    if (prev.join() === r.join() && pts[i - 1]?.pi === pts[i].pi && !r.includes(1)) continue\n    badges.push({ i, rules: r })\n  }\n  const badgeX = dodge(\n    badges.map((b) => x(b.i)),\n    20,\n    pad.l,\n    pad.l + iw,\n  )\n\n  const ruleCounts = Object.entries(hits.byRule)\n    .map(([k, v]) => ({ rule: +k, count: v.trigger.length, points: new Set(v.points) }))\n    .sort((a, b) => a.rule - b.rule)\n  const fired = ruleCounts.filter((r) => r.count > 0)\n  const totalFlag = hits.byPoint.filter((r) => r.length).length\n\n  const pointer = usePlotPointer<SVGSVGElement>(\n    (px) => {\n      if (px < pad.l - 6 || px > pad.l + iw + 6 || !n) return setHover(null)\n      setHover(Math.max(0, Math.min(n - 1, Math.floor((px - pad.l) / slot))))\n    },\n    () => setHover(null),\n  )\n  const nav = useChartNav({ count: n, onMove: (p) => setHover(p.i), onClear: () => setHover(null), start: hover != null ? { i: hover, j: 0 } : null })\n\n  const fmtLabel = (s: string) => (ISO.test(s) ? dateLabel(s, 'short', locale) : s)\n  const xTickEvery = Math.max(1, Math.ceil(64 / slot))\n  const measure = valueLabel ?? (isP ? 'Proportion nonconforming' : mode === 'xbar-r' ? 'Subgroup mean' : 'Value')\n  const rangeName = mode === 'xmr' ? 'Moving range' : 'Range'\n\n  const hp = hover != null ? pts[hover] : null\n  const zOf = (p: Pt) => (p.sig > 0 ? (p.v - p.cl) / p.sig : 0)\n  const zoneOf = (z: number) => (Math.abs(z) > 3 ? 'beyond limits' : Math.abs(z) > 2 ? 'zone A' : Math.abs(z) > 1 ? 'zone B' : 'zone C')\n\n  const label =\n    ariaLabel ??\n    `${mode === 'p' ? 'p chart' : mode === 'xbar-r' ? 'X-bar and R chart' : 'Individuals and moving range chart'} of ${measure.toLowerCase()}, ${n} points in ${phases.length} phase${phases.length > 1 ? 's' : ''}; ${totalFlag} points flagged by ${ruleset === 'nelson' ? 'Nelson' : 'Western Electric'} rules`\n\n  const pillW = (t: string) => textW(t, 10, 600) + 10\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=\"block overflow-visible\" {...pointer}>\n          {/* zones + limits per phase */}\n          {phases.map((p, pi) => {\n            const len = p.end - p.start\n            const xa = pad.l + slot * p.start\n            const xb = pad.l + slot * p.end\n            const at = (k: number, m: number) => clip(p.center + m * p.sigmas[k])\n            return (\n              <g key={pi}>\n                {zones &&\n                  (['C', 'B', 'A'] as const).map((zn, zi) => (\n                    <g key={zn}>\n                      <path d={bandPath(p, (k) => at(k, zi), (k) => at(k, zi + 1))} fill={`color-mix(in oklab, ${ZONE_TINT[zn]} ${zn === 'C' ? 4 : 5.5}%, transparent)`} />\n                      <path d={bandPath(p, (k) => at(k, -zi), (k) => at(k, -zi - 1))} fill={`color-mix(in oklab, ${ZONE_TINT[zn]} ${zn === 'C' ? 4 : 5.5}%, transparent)`} />\n                    </g>\n                  ))}\n                {zones &&\n                  [-2, -1, 1, 2].map((m) => <path key={m} d={P(stepPts(p, (k) => at(k, m)))} fill=\"none\" stroke=\"var(--border-strong)\" strokeDasharray=\"1 3\" />)}\n                <path d={P(stepPts(p, (k) => p.ucl[k]))} fill=\"none\" stroke=\"var(--red)\" strokeOpacity={0.8} strokeWidth={1.25} strokeDasharray=\"5 3\" />\n                <path d={P(stepPts(p, (k) => p.lcl[k]))} fill=\"none\" stroke=\"var(--red)\" strokeOpacity={0.8} strokeWidth={1.25} strokeDasharray=\"5 3\" />\n                <line x1={xa} x2={xb} y1={y(p.center)} y2={y(p.center)} stroke=\"var(--fg-2)\" strokeWidth={1.25} />\n                {pi < phases.length - 1 && len * slot > 90 && (\n                  <g className=\"num text-[10px]\" pointerEvents=\"none\" stroke=\"var(--surface)\" strokeWidth={3} paintOrder=\"stroke\">\n                    <text x={xb - 6} y={y(p.ucl[len - 1]) - 5} textAnchor=\"end\" fill=\"color-mix(in oklab, var(--red) 80%, var(--fg))\">\n                      UCL {tickFmtFull(p.ucl[len - 1])}\n                    </text>\n                    <text x={xb - 6} y={y(p.lcl[len - 1]) + 13} textAnchor=\"end\" fill=\"color-mix(in oklab, var(--red) 80%, var(--fg))\">\n                      LCL {tickFmtFull(p.lcl[len - 1])}\n                    </text>\n                  </g>\n                )}\n                {/* phase divider + label */}\n                {pi > 0 && <line x1={xa} x2={xa} y1={pad.t - 26} y2={showRange ? rTop + rangeH : pad.t + mainH} stroke=\"var(--fg-2)\" strokeOpacity={0.55} strokeDasharray=\"3 3\" />}\n                {(() => {\n                  const title = p.phase || `Phase ${pi + 1}`\n                  const stat = `CL ${tickFmtFull(p.center)}`\n                  const room = xb - xa - 16\n                  const full = textW(title, 11, 600) + textW(stat, 11) + 10 <= room\n                  return (\n                    <text x={xa + 8} y={pad.t - 14} className=\"text-[11px] font-semibold\" fill=\"var(--fg-2)\">\n                      {textW(title, 11, 600) <= room ? title : `P${pi + 1}`}\n                      {full && (\n                        <tspan dx={8} className=\"num fill-fg-3\" fontWeight={400}>\n                          {stat}\n                        </tspan>\n                      )}\n                    </text>\n                  )\n                })()}\n                {/* zone letters inside the right edge of the last phase only; others at their right edge if wide */}\n                {zones && len * slot > 60 && (\n                  <g className=\"fill-fg-4 text-[9.5px] font-semibold\" pointerEvents=\"none\">\n                    {(['C', 'B', 'A'] as const).map((zn, zi) =>\n                      [1, -1].map((sgnz) => {\n                        const k = len - 1\n                        const yy = y(at(k, sgnz * (zi + 0.5)))\n                        const room = Math.abs(y(at(k, sgnz * (zi + 1))) - y(at(k, sgnz * zi)))\n                        return room >= 10 ? (\n                          <text key={`${zn}${sgnz}`} x={xb - 6} y={yy + 3.3} textAnchor=\"end\">\n                            {zn}\n                          </text>\n                        ) : null\n                      }),\n                    )}\n                  </g>\n                )}\n              </g>\n            )\n          })}\n\n          {/* y axis */}\n          {yt.map((t) => (\n            <g key={t}>\n              <line x1={pad.l - 4} x2={pad.l} y1={y(t)} y2={y(t)} stroke=\"var(--fg-4)\" />\n              <text x={pad.l - 8} y={y(t) + 3.5} textAnchor=\"end\" className=\"num fill-fg-3 text-[11px]\">\n                {tickFmt(t)}\n              </text>\n            </g>\n          ))}\n          <line x1={pad.l} x2={pad.l + iw} y1={pad.t + mainH + 0.5} y2={pad.t + mainH + 0.5} stroke=\"var(--border-strong)\" />\n          <text x={pad.l - 8} y={pad.t - 14} textAnchor=\"end\" className=\"fill-fg-3 text-[11px] font-medium\">\n            {isP ? '%' : unit}\n          </text>\n\n          {/* right-edge limit labels (last phase), dodged */}\n          {(() => {\n            const p = phases[phases.length - 1]\n            if (!p) return null\n            const k = p.end - p.start - 1\n            const items = [\n              { t: 'UCL', v: p.ucl[k], c: 'var(--red)' },\n              { t: 'CL', v: p.center, c: 'var(--fg-2)' },\n              { t: 'LCL', v: p.lcl[k], c: 'var(--red)' },\n            ]\n            const yy = dodge(\n              items.map((it) => y(it.v)),\n              15,\n              pad.t,\n              pad.t + mainH,\n            )\n            return items.map((it, j) => (\n              <text key={it.t} x={pad.l + iw + 10} y={yy[j] + 4} className=\"num text-[11px]\">\n                <tspan fill={it.c} fontWeight={600}>\n                  {it.t}\n                </tspan>\n                <tspan dx={5} className=\"fill-fg-2\">\n                  {tickFmtFull(it.v)}\n                </tspan>\n              </text>\n            ))\n          })()}\n\n          {/* x labels */}\n          {pts.map((p) =>\n            p.i % xTickEvery === 0 ? (\n              <text key={p.i} x={x(p.i)} y={(showRange ? rTop + rangeH : pad.t + mainH) + 17} textAnchor=\"middle\" className=\"num fill-fg-3 text-[10.5px]\">\n                {fmtLabel(data[p.i].label)}\n              </text>\n            ) : null,\n          )}\n\n          {/* series */}\n          {phases.map((p, pi) => (\n            <path key={pi} d={P(pts.slice(p.start, p.end).map((q) => [x(q.i), y(q.v)]))} fill=\"none\" stroke=\"var(--fg-3)\" strokeWidth={1.25} strokeLinejoin=\"round\" />\n          ))}\n\n          {hover != null && (\n            <line x1={x(hover)} x2={x(hover)} y1={pad.t - 4} y2={showRange ? rTop + rangeH : pad.t + mainH} stroke=\"var(--fg-3)\" strokeDasharray=\"2 3\" pointerEvents=\"none\" />\n          )}\n\n          {pts.map((p) => {\n            const trig = hits.byPoint[p.i].length > 0\n            const mem = hits.inPattern[p.i]\n            const lit = ruleHover != null && (ruleCounts.find((r) => r.rule === ruleHover)?.points.has(p.i) ?? false)\n            const dim = ruleHover != null && !lit\n            const r = hover === p.i ? 5 : trig ? 4 : 2.75\n            return (\n              <circle\n                key={p.i}\n                cx={x(p.i)}\n                cy={y(p.v)}\n                r={r}\n                fill={trig ? 'var(--red)' : mem ? 'color-mix(in oklab, var(--red) 22%, var(--surface))' : 'var(--surface)'}\n                stroke={trig || mem ? 'var(--red)' : 'var(--fg-2)'}\n                strokeWidth={lit ? 2.5 : 1.5}\n                opacity={dim ? 0.35 : 1}\n                style={{ transition: 'opacity .15s' }}\n              />\n            )\n          })}\n\n          {/* rule badges */}\n          {badges.map((b, k) => {\n            const t = b.rules.join('·')\n            const w = pillW(t)\n            const p = pts[b.i]\n            const above = p.v >= p.cl\n            const by = above ? y(p.v) - 18 : y(p.v) + 8\n            const cy = Math.max(pad.t - 4, Math.min(pad.t + mainH - 12, by))\n            return (\n              <g key={b.i} transform={`translate(${badgeX[k] - w / 2},${cy})`} pointerEvents=\"none\" opacity={ruleHover != null && !b.rules.includes(ruleHover) ? 0.3 : 1}>\n                <rect width={w} height={13} rx={6.5} fill=\"var(--red)\" />\n                <text x={w / 2} y={9.6} textAnchor=\"middle\" className=\"num text-[10px] font-semibold\" fill=\"var(--surface)\">\n                  {t}\n                </text>\n              </g>\n            )\n          })}\n\n          {/* range panel */}\n          {showRange && (\n            <g>\n              <text x={pad.l} y={rTop - 9} className=\"fill-fg-3 text-[11px] font-medium\">\n                {rangeName}\n              </text>\n              {rTicks.map((t) => (\n                <g key={t}>\n                  <line x1={pad.l - 4} x2={pad.l} y1={ry(t)} y2={ry(t)} stroke=\"var(--fg-4)\" />\n                  <text x={pad.l - 8} y={ry(t) + 3.5} textAnchor=\"end\" className=\"num fill-fg-3 text-[10.5px]\">\n                    {nums.fixed(t, rTicks[1] - rTicks[0] < 1 ? 1 : 0)}\n                  </text>\n                </g>\n              ))}\n              <line x1={pad.l} x2={pad.l + iw} y1={rTop + rangeH + 0.5} y2={rTop + rangeH + 0.5} stroke=\"var(--border-strong)\" />\n              {phases.map((p, pi) => {\n                const xa = pad.l + slot * p.start\n                const xb = pad.l + slot * p.end\n                return (\n                  <g key={pi}>\n                    <rect x={xa} y={ry(p.rangeUcl)} width={xb - xa} height={ry(p.rangeLcl) - ry(p.rangeUcl)} fill=\"color-mix(in oklab, var(--green) 4%, transparent)\" />\n                    <line x1={xa} x2={xb} y1={ry(p.rangeUcl)} y2={ry(p.rangeUcl)} stroke=\"var(--red)\" strokeOpacity={0.8} strokeWidth={1.25} strokeDasharray=\"5 3\" />\n                    {p.rangeLcl > 0 && <line x1={xa} x2={xb} y1={ry(p.rangeLcl)} y2={ry(p.rangeLcl)} stroke=\"var(--red)\" strokeOpacity={0.8} strokeWidth={1.25} strokeDasharray=\"5 3\" />}\n                    <line x1={xa} x2={xb} y1={ry(p.rangeCenter)} y2={ry(p.rangeCenter)} stroke=\"var(--fg-2)\" strokeWidth={1} />\n                    <path\n                      d={P(pts.slice(p.start, p.end).filter((q) => q.r != null).map((q) => [x(q.i), ry(q.r!)]))}\n                      fill=\"none\"\n                      stroke=\"var(--fg-3)\"\n                      strokeWidth={1}\n                      strokeLinejoin=\"round\"\n                    />\n                    {pts.slice(p.start, p.end).map((q) =>\n                      q.r == null ? null : (\n                        <circle key={q.i} cx={x(q.i)} cy={ry(q.r)} r={hover === q.i ? 4 : q.r > p.rangeUcl ? 3.5 : 2} fill={q.r > p.rangeUcl ? 'var(--red)' : 'var(--fg-3)'} />\n                      ),\n                    )}\n                  </g>\n                )\n              })}\n              {(() => {\n                const p = phases[phases.length - 1]\n                const items = [\n                  { t: 'UCL', v: p.rangeUcl, c: 'var(--red)' },\n                  { t: mode === 'xmr' ? 'MR̄' : 'R̄', v: p.rangeCenter, c: 'var(--fg-2)' },\n                ]\n                const yy = dodge(\n                  items.map((it) => ry(it.v)),\n                  14,\n                  rTop,\n                  rTop + rangeH,\n                )\n                return items.map((it, j) => (\n                  <text key={it.t} x={pad.l + iw + 10} y={yy[j] + 4} className=\"num text-[10.5px]\">\n                    <tspan fill={it.c} fontWeight={600}>\n                      {it.t}\n                    </tspan>\n                    <tspan dx={5} className=\"fill-fg-2\">\n                      {nums.fixed(it.v, 2)}\n                    </tspan>\n                  </text>\n                ))\n              })()}\n            </g>\n          )}\n\n          {/* keyboard focus ring */}\n          {nav.pos && hp && <circle cx={x(hp.i)} cy={y(hp.v)} r={8} fill=\"none\" stroke=\"var(--accent)\" strokeWidth={2} pointerEvents=\"none\" data-focus-ring=\"\" />}\n        </svg>\n      )}\n\n      {/* rule legend */}\n      <div ref={legendRef} className=\"absolute inset-x-0 bottom-0 flex h-[30px] flex-wrap items-center gap-x-1.5 gap-y-1 overflow-hidden pl-[50px] text-[11.5px] text-fg-3\">\n        <span className=\"mr-1.5 font-medium text-fg-2\">{ruleset === 'nelson' ? 'Nelson rules' : 'Western Electric rules'}</span>\n        {(() => {\n          const list = Object.entries(RULE_TEXT[ruleset]).filter(([k]) => !rules || rules.includes(+k))\n          const compact = list.length > 4\n          const quiet = list.filter(([k]) => !(ruleCounts.find((r) => r.rule === +k)?.count ?? 0))\n          return (\n            <>\n              {list.map(([k, text]) => {\n                const c = ruleCounts.find((r) => r.rule === +k)?.count ?? 0\n                if (!c && compact) return null\n                return (\n                  <span\n                    key={k}\n                    className={cn('inline-flex h-[22px] items-center gap-1.5 rounded-md pr-2 pl-1 transition-colors', c ? 'cursor-default text-fg-2' : 'text-fg-4')}\n                    style={{ background: ruleHover === +k ? 'color-mix(in oklab, var(--red) 12%, transparent)' : c ? 'var(--surface-2)' : undefined }}\n                    onPointerEnter={() => c && setRuleHover(+k)}\n                    onPointerLeave={() => setRuleHover(null)}\n                  >\n                    <span\n                      className=\"num inline-flex h-[15px] min-w-[15px] items-center justify-center rounded-full px-1 text-[10px] font-semibold\"\n                      style={c ? { background: 'var(--red)', color: 'var(--surface)' } : { boxShadow: 'inset 0 0 0 1px var(--border-strong)' }}\n                    >\n                      {k}\n                    </span>\n                    {text}\n                    {c > 0 && <span className=\"num font-semibold text-fg\">×{c}</span>}\n                  </span>\n                )\n              })}\n              {compact && quiet.length > 0 && (\n                <span className=\"ml-1 inline-flex items-center gap-1 text-fg-4\">\n                  {quiet.map(([k, text]) => (\n                    <span key={k} title={text} className=\"num inline-flex h-[15px] min-w-[15px] items-center justify-center rounded-full px-1 text-[10px] font-semibold\" style={{ boxShadow: 'inset 0 0 0 1px var(--border-strong)' }}>\n                      {k}\n                    </span>\n                  ))}\n                  <span className=\"ml-0.5\">not fired</span>\n                </span>\n              )}\n            </>\n          )\n        })()}\n        {fired.length === 0 && <span className=\"ml-1 text-fg-3\">· in control</span>}\n      </div>\n\n      {hp && (\n        <Readout\n          x={x(hp.i)}\n          y={pad.t + 40}\n          containerWidth={width}\n          containerHeight={height - legendH}\n          avoid={{ x0: x(hp.i) - 10, x1: x(hp.i) + 10, y0: 0, y1: H, top: pad.t }}\n          eyebrow={`${subgroupNoun} ${hp.i + 1} · ${hp.ph.phase || `Phase ${hp.pi + 1}`}`}\n          title={ISO.test(data[hp.i].label) ? dateLabel(data[hp.i].label, 'weekday', locale) : data[hp.i].label}\n          headline={format(hp.v)}\n          rows={(() => {\n            const z = zOf(hp)\n            const out: ReadoutRow[] = [\n              { label: 'Centre line', value: tickFmtFull(hp.cl), color: 'var(--fg-2)', line: true },\n              { label: 'UCL / LCL', value: `${tickFmtFull(hp.ucl)} / ${tickFmtFull(hp.lcl)}`, color: 'var(--red)', line: true },\n              { label: 'Distance', value: `${sgn(z, (v) => nums.fixed(v, 2))}σ · ${zoneOf(z)}`, muted: Math.abs(z) <= 2 },\n            ]\n            if (isP && data[hp.i].size != null) out.push({ label: 'Late / shipped', value: `${data[hp.i].count} / ${nums.int(data[hp.i].size!)}`, muted: true })\n            if (showRange && hp.r != null) out.push({ label: rangeName, value: nums.fixed(hp.r, 2), muted: hp.r <= hp.ph.rangeUcl })\n            return out\n          })()}\n          foot={\n            hits.byPoint[hp.i].length ? (\n              <span className=\"flex flex-col gap-0.5\">\n                {hits.byPoint[hp.i].map((r) => (\n                  <span key={r} className=\"text-fg-2\">\n                    <span className=\"mr-1 font-semibold\" style={{ color: 'var(--red)' }}>\n                      Rule {r}\n                    </span>\n                    {RULE_TEXT[ruleset][r]}\n                  </span>\n                ))}\n              </span>\n            ) : hits.inPattern[hp.i] ? (\n              'Part of a flagged pattern.'\n            ) : (\n              'No rule fired.'\n            )\n          }\n          width={232}\n        />\n      )}\n      {nav.pos && hp && (\n        <div className=\"sr-only\" aria-live=\"polite\">\n          {`${data[hp.i].label}: ${format(hp.v)}${hits.byPoint[hp.i].length ? `, rules ${hits.byPoint[hp.i].join(', ')} fired` : ''}`}\n        </div>\n      )}\n      {width > 0 && <ExportMirror target={legendRef} />}\n      <ChartDataTable\n        caption={label}\n        columns={[\n          { key: 'label', label: subgroupNoun },\n          { key: 'phase', label: 'Phase' },\n          { key: 'value', label: measure, format: (v) => format(v as number) },\n          { key: 'cl', label: 'CL', format: (v) => tickFmtFull(v as number) },\n          { key: 'ucl', label: 'UCL', format: (v) => tickFmtFull(v as number) },\n          { key: 'lcl', label: 'LCL', format: (v) => tickFmtFull(v as number) },\n          { key: 'rules', label: 'Rules fired' },\n        ]}\n        rows={controlChartToRows(data, { mode, ruleset, rules })}\n      />\n    </div>\n  )\n\n  function tickFmtFull(v: number) {\n    return isP ? `${nums.fixed(v * 100, 1)}%` : nums.fixed(v, Math.abs(v) >= 100 ? 0 : 1)\n  }\n}\n\n/** Flat rows for CSV: per point the phase, plotted value, limits, σ distance, range and the rules that fired. */\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function controlChartToRows(data: ControlPoint[], { mode = 'xmr', ruleset = 'western-electric', rules }: { mode?: ControlMode; ruleset?: Ruleset; rules?: number[] } = {}) {\n  const ph = data.map((d) => d.phase)\n  const phases =\n    mode === 'xmr'\n      ? controlLimits({ mode, values: data.map((d) => d.value ?? NaN), phases: ph })\n      : mode === 'xbar-r'\n        ? controlLimits({ mode, subgroups: data.map((d) => d.subgroup ?? []), phases: ph })\n        : controlLimits({ mode, counts: data.map((d) => d.count ?? 0), sizes: data.map((d) => d.size ?? 0), phases: ph })\n  const r4 = (v: number) => Math.round(v * 1e4) / 1e4\n  return phases.flatMap((p, pi) => {\n    const hits = nelsonRules(p.values, p.center, p.sigmas, { ruleset, rules })\n    return p.values.map((v, k) => ({\n      label: data[p.start + k].label,\n      phase: p.phase || `Phase ${pi + 1}`,\n      value: r4(v),\n      cl: r4(p.center),\n      ucl: r4(p.ucl[k]),\n      lcl: r4(p.lcl[k]),\n      sigma: r4(p.sigmas[k] > 0 ? (v - p.center) / p.sigmas[k] : 0),\n      range: p.ranges[k] == null ? null : r4(p.ranges[k]!),\n      rules: hits.byPoint[k].join(' '),\n    }))\n  })\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/bi/ControlChart.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/science/parts.tsx",
      "content": "/*\n * Science collection: shared drawing parts (axes, readout card, legend chips).\n * Axes follow journal style: hairline baseline, short outward ticks, receding\n * dashed gridlines, tabular figures.\n */\nimport { useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode, type RefObject } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\nimport { formatter } from '@/components/klar/charts/basic/core'\nimport { fmtP, minus, tickLabel } from '@/components/klar/charts/science/util'\n\n/** Default categorical palette for the collection (accent first). */\n// oxlint-disable-next-line react/only-export-components -- public constant exported with its chart\nexport const SCI_COLORS = ['var(--accent)', 'var(--teal)', 'var(--orange)', 'var(--sky)', 'var(--pink)', 'var(--lime)']\n\ntype Scale = (v: number) => number\n\nexport function AxisX({\n  ticks,\n  scale,\n  y,\n  x0,\n  x1,\n  format,\n  title,\n  grid,\n  tickSize = 4,\n  baseline = true,\n}: {\n  ticks: number[]\n  scale: Scale\n  y: number\n  x0: number\n  x1: number\n  format?: (v: number) => string\n  title?: ReactNode\n  /** Draw gridlines from grid[0] to grid[1] (y px). */\n  grid?: [number, number]\n  tickSize?: number\n  baseline?: boolean\n}) {\n  const step = ticks.length > 1 ? Math.abs(ticks[1] - ticks[0]) : undefined\n  const f = format ?? ((v: number) => minus(tickLabel(v, step)))\n  return (\n    <g>\n      {grid &&\n        ticks.map((t) => (\n          <line key={`g${t}`} x1={scale(t)} x2={scale(t)} y1={grid[0]} y2={grid[1]} stroke=\"var(--border)\" strokeDasharray=\"2 4\" />\n        ))}\n      {baseline && <line x1={x0} x2={x1} y1={y + 0.5} y2={y + 0.5} stroke=\"var(--border-strong)\" />}\n      {ticks.map((t) => (\n        <g key={t} transform={`translate(${scale(t)},${y})`}>\n          <line y1={0} y2={tickSize} stroke=\"var(--fg-4)\" />\n          <text y={tickSize + 12} textAnchor=\"middle\" className=\"num fill-fg-3 text-[11px]\">\n            {f(t)}\n          </text>\n        </g>\n      ))}\n      {title && (\n        <text x={x1} y={y + tickSize + 30} textAnchor=\"end\" className=\"fill-fg-3 text-[11px] font-medium\">\n          {title}\n        </text>\n      )}\n    </g>\n  )\n}\n\nexport function AxisY({\n  ticks,\n  scale,\n  x,\n  y0,\n  y1,\n  format,\n  title,\n  grid,\n  tickSize = 4,\n  baseline = true,\n}: {\n  ticks: number[]\n  scale: Scale\n  x: number\n  y0: number\n  y1: number\n  format?: (v: number) => string\n  /** Drawn horizontally above the axis, journal-figure style. */\n  title?: ReactNode\n  grid?: [number, number]\n  tickSize?: number\n  baseline?: boolean\n}) {\n  const step = ticks.length > 1 ? Math.abs(ticks[1] - ticks[0]) : undefined\n  const f = format ?? ((v: number) => minus(tickLabel(v, step)))\n  return (\n    <g>\n      {grid &&\n        ticks.map((t) => (\n          <line key={`g${t}`} x1={grid[0]} x2={grid[1]} y1={scale(t)} y2={scale(t)} stroke=\"var(--border)\" strokeDasharray=\"2 4\" />\n        ))}\n      {baseline && <line x1={x - 0.5} x2={x - 0.5} y1={y0} y2={y1} stroke=\"var(--border-strong)\" />}\n      {ticks.map((t) => (\n        <g key={t} transform={`translate(${x},${scale(t)})`}>\n          <line x1={-tickSize} x2={0} stroke=\"var(--fg-4)\" />\n          <text x={-tickSize - 5} y={3.8} textAnchor=\"end\" className=\"num fill-fg-3 text-[11px]\">\n            {f(t)}\n          </text>\n        </g>\n      ))}\n      {title && (\n        <text x={x - tickSize - 5} y={Math.min(y0, y1) - 12} textAnchor=\"start\" className=\"fill-fg-3 text-[11px] font-medium\">\n          {title}\n        </text>\n      )}\n    </g>\n  )\n}\n\nexport interface TipRow {\n  label: ReactNode\n  value: ReactNode\n  color?: string\n  /** Dimmer second value, e.g. a CI. */\n  sub?: ReactNode\n}\n\n/** Rich hover readout. Anchored at (x, y) inside a relative container of width W. */\nexport function SciTip({\n  x,\n  y,\n  W,\n  title,\n  subtitle,\n  rows,\n  foot,\n  width = 196,\n  anchor = 'middle',\n  side,\n}: {\n  x: number\n  y: number\n  W: number\n  title: ReactNode\n  subtitle?: ReactNode\n  rows: TipRow[]\n  foot?: ReactNode\n  width?: number\n  /** Vertical anchoring relative to y. */\n  anchor?: 'top' | 'middle' | 'bottom'\n  /** Force the card to the right or left of x (default: right unless it would overflow W). */\n  side?: 'left' | 'right'\n}) {\n  const flip = side ? side === 'left' : x + width + 18 > W\n  return (\n    <div\n      className=\"pointer-events-none absolute z-30 rounded-xl border border-border bg-surface/95 px-3 py-2.5 shadow-pop backdrop-blur-sm\"\n      style={{\n        left: x,\n        top: y,\n        width,\n        transform: `translate(${flip ? 'calc(-100% - 14px)' : '14px'}, ${anchor === 'middle' ? '-50%' : anchor === 'bottom' ? '-100%' : '0'})`,\n      }}\n    >\n      <div className=\"flex items-baseline justify-between gap-2\">\n        <div className=\"truncate text-[12px] font-semibold text-fg\">{title}</div>\n        {subtitle && <div className=\"num shrink-0 text-[11px] text-fg-3\">{subtitle}</div>}\n      </div>\n      <div className=\"mt-1.5 flex flex-col gap-[5px] border-t border-border pt-1.5\">\n        {rows.map((r, i) => (\n          <div key={i} className=\"flex items-baseline justify-between gap-3 text-[12px]\">\n            <span className=\"flex min-w-0 items-center gap-1.5 text-fg-3\">\n              {r.color && <span className=\"size-2 shrink-0 translate-y-[-0.5px] rounded-[2px]\" style={{ background: r.color }} />}\n              <span className=\"truncate\">{r.label}</span>\n            </span>\n            <span className=\"num shrink-0 text-right font-medium text-fg\">\n              {r.value}\n              {r.sub && <span className=\"ml-1 font-normal text-fg-3\">{r.sub}</span>}\n            </span>\n          </div>\n        ))}\n      </div>\n      {foot && <div className=\"mt-1.5 border-t border-border pt-1.5 text-[11px] leading-snug text-fg-3\">{foot}</div>}\n    </div>\n  )\n}\n\n/** Italic statistic symbol, typeset like a journal (r, p, n, R²). */\nexport const Sym = ({ children }: { children: ReactNode }) => <i className=\"font-serif text-[1.04em] italic\">{children}</i>\n\n/** Small key used in legends: swatch, line or dashed line. */\nexport function KeyMark({ color, kind = 'box', className }: { color: string; kind?: 'box' | 'line' | 'dash' | 'dot' | 'band'; className?: string }) {\n  if (kind === 'line') return <span className={cn('inline-block h-[2px] w-3.5 rounded-full', className)} style={{ background: color }} />\n  if (kind === 'dash') return <span className={cn('inline-block w-3.5 border-t-[1.5px] border-dashed', className)} style={{ borderColor: color }} />\n  if (kind === 'dot') return <span className={cn('inline-block size-2 rounded-full', className)} style={{ background: color }} />\n  if (kind === 'band')\n    return <span className={cn('inline-block h-2.5 w-3.5 rounded-[3px]', className)} style={{ background: `color-mix(in oklab, ${color} 22%, transparent)`, boxShadow: `inset 0 0 0 1px color-mix(in oklab, ${color} 45%, transparent)` }} />\n  return <span className={cn('inline-block size-2 rounded-[2px]', className)} style={{ background: color }} />\n}\n\n/** A text chip drawn in SVG (surface pill with hairline border). Width is estimated from length. */\nexport function SvgChip({\n  x,\n  y,\n  text,\n  color = 'var(--fg-2)',\n  anchor = 'middle',\n  strong,\n  solid,\n}: {\n  x: number\n  y: number\n  text: string\n  color?: string\n  anchor?: 'start' | 'middle' | 'end'\n  strong?: boolean\n  /** Filled with the colour, text on surface. */\n  solid?: boolean\n}) {\n  const w = text.length * 5.9 + 12\n  const x0 = anchor === 'middle' ? x - w / 2 : anchor === 'end' ? x - w : x\n  return (\n    <g pointerEvents=\"none\">\n      <rect\n        x={x0}\n        y={y - 9}\n        width={w}\n        height={18}\n        rx={5}\n        fill={solid ? color : 'var(--surface)'}\n        stroke={solid ? 'none' : `color-mix(in oklab, ${color} 40%, var(--border))`}\n      />\n      <text\n        x={x0 + w / 2}\n        y={y + 3.6}\n        textAnchor=\"middle\"\n        className={cn('num text-[10.5px]', strong ? 'font-semibold' : 'font-medium')}\n        fill={solid ? 'var(--surface)' : color}\n      >\n        {text}\n      </text>\n    </g>\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Locale                                                            */\n/* ------------------------------------------------------------------ */\n\n/** Locale used when a chart is given none. */\nexport const DEFAULT_LOCALE = 'en-US'\n\nexport interface SciFormat {\n  /** Fixed decimals, Unicode minus: −1.25 */\n  fixed: (v: number, digits: number) => string\n  /** Tick label with the tick step's precision (see `tickLabel`). */\n  tick: (v: number, step?: number) => string\n  /** Shortest exact form of a (nice) tick value, Unicode minus. */\n  str: (v: number) => string\n  /** Grouped integer: 3,200 */\n  int: (v: number) => string\n  /** 0.123 → 12.3% */\n  pct: (v: number, digits?: number) => string\n}\n\nconst sciCache = new Map<string, SciFormat>()\n\n/**\n * Number formatting for the science charts. Without a locale it reproduces the\n * collection's original output exactly (toFixed / String with a Unicode minus);\n * with one, decimals and grouping follow `Intl.NumberFormat`. Tick labels never group digits.\n */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport function sciFormat(locale?: string): SciFormat {\n  const key = locale ?? ''\n  const hit = sciCache.get(key)\n  if (hit) return hit\n  const f = formatter(locale ?? DEFAULT_LOCALE)\n  let out: SciFormat\n  if (!locale) {\n    out = {\n      fixed: (v, d) => minus(v.toFixed(d)),\n      tick: (v, step) => minus(tickLabel(v, step)),\n      str: (v) => minus(String(v)),\n      int: (v) => f.number(v),\n      pct: (v, d = 1) => `${(v * 100).toFixed(d)}%`,\n    }\n  } else {\n    const nfs = new Map<number, Intl.NumberFormat>()\n    const nf = (d: number) => {\n      let x = nfs.get(d)\n      if (!x) nfs.set(d, (x = new Intl.NumberFormat(locale, { minimumFractionDigits: d, maximumFractionDigits: d, useGrouping: false })))\n      return x\n    }\n    const free = new Intl.NumberFormat(locale, { maximumFractionDigits: 12, useGrouping: false })\n    const fixed = (v: number, d: number) => minus(nf(d).format(v))\n    out = {\n      fixed,\n      tick: (v, step) => {\n        const d = step ? Math.max(0, -Math.floor(Math.log10(step) + 1e-9)) : 2\n        return fixed(Object.is(v, -0) ? 0 : v, Math.min(d, 4)).replace(/^−0$/, '0')\n      },\n      str: (v) => minus(free.format(v)),\n      int: (v) => f.number(v),\n      pct: (v, d = 1) => f.percent(v, d),\n    }\n  }\n  sciCache.set(key, out)\n  return out\n}\n\n/** APA-style p-value (\"= 0.032\", \"< 0.001\") in the chart's locale. */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport function pValue(p: number, nf: SciFormat, locale?: string) {\n  if (!locale) return fmtP(p)\n  if (p < 0.001) return '< ' + nf.fixed(0.001, 3)\n  return '= ' + nf.fixed(p, p < 0.1 ? 3 : 2)\n}\n\n/* ------------------------------------------------------------------ */\n/*  Pointer (mouse, touch, pen) and keyboard                          */\n/* ------------------------------------------------------------------ */\n\n/** Focus ring for a keyboard-navigable chart (HTML element). */\nexport const FOCUS_RING = 'outline-none focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-accent/60'\n\n/**\n * Pointer handlers for a plot (mouse, touch and pen). `onPoint` gets the position\n * inside the element in unscaled pixels. Mouse clears on leave; a tap shows the\n * readout and keeps it until the next tap; a drag scrubs. `touch-action: pan-y`\n * keeps vertical page scrolling.\n */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport function usePlotPointer<T extends Element = SVGSVGElement>(onPoint: (x: number, y: number, e: PointerEvent<T>) => void, onClear: () => void) {\n  const locate = (e: PointerEvent<T>) => {\n    const el = e.currentTarget as unknown as Element\n    const r = el.getBoundingClientRect()\n    const w = (el as HTMLElement).offsetWidth || (el as SVGSVGElement).width?.baseVal?.value || r.width\n    const h = (el as HTMLElement).offsetHeight || (el as SVGSVGElement).height?.baseVal?.value || r.height\n    const sx = w ? r.width / w : 1\n    const sy = h ? r.height / h : 1\n    onPoint((e.clientX - r.left) / (sx || 1), (e.clientY - r.top) / (sy || 1), e)\n  }\n  return {\n    onPointerDown: (e: PointerEvent<T>) => locate(e),\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') onClear()\n    },\n    onPointerCancel: () => onClear(),\n    style: { touchAction: 'pan-y' } as const,\n  }\n}\n\n/**\n * Arrow-key stepping through `n` marks. Returns the next index, `null` for Escape,\n * or `undefined` when the key isn't handled (the caller then lets it through).\n */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport function stepKey(\n  e: KeyboardEvent,\n  n: number,\n  cur: number | null,\n  { next = ['ArrowRight', 'ArrowDown'], prev = ['ArrowLeft', 'ArrowUp'], wrap = false }: { next?: string[]; prev?: string[]; wrap?: boolean } = {},\n): number | null | undefined {\n  if (e.key === 'Escape') return cur == null ? undefined : null\n  if (n <= 0) return undefined\n  if (next.includes(e.key)) return cur == null ? 0 : wrap ? (cur + 1) % n : Math.min(n - 1, cur + 1)\n  if (prev.includes(e.key)) return cur == null ? n - 1 : wrap ? (cur - 1 + n) % n : Math.max(0, cur - 1)\n  if (e.key === 'Home') return 0\n  if (e.key === 'End') return n - 1\n  return undefined\n}\n\n/* ------------------------------------------------------------------ */\n/*  Export mirror                                                     */\n/* ------------------------------------------------------------------ */\n\ntype MirrorItem =\n  | { k: 'rect'; x: number; y: number; w: number; h: number; rx: number; fill: string; stroke?: string; sw?: number; op: number; grad?: { x2: number; y1: number; y2: number; x1: number; stops: [string, string][] } }\n  | { k: 'text'; x: number; y: number; text: string; fill: string; size: string; weight: string; family: string; style: string; ls: string; num: string; op: number }\n\nconst transparent = (c: string) => !c || c === 'transparent' || /rgba?\\([^)]*,\\s*0\\)$/.test(c) || /\\/\\s*0\\)$/.test(c)\n\n/** Split a CSS argument list on top-level commas. */\nfunction splitTop(s: string) {\n  const out: string[] = []\n  let depth = 0\n  let cur = ''\n  for (const ch of s) {\n    if (ch === '(') depth++\n    if (ch === ')') depth--\n    if (ch === ',' && depth === 0) {\n      out.push(cur.trim())\n      cur = ''\n    } else cur += ch\n  }\n  if (cur.trim()) out.push(cur.trim())\n  return out\n}\n\nfunction parseGradient(bg: string) {\n  const m = bg.match(/^linear-gradient\\((.*)\\)$/)\n  if (!m) return null\n  const parts = splitTop(m[1])\n  let dir = 'to bottom'\n  if (/^(to |-?[\\d.]+deg)/.test(parts[0])) dir = parts.shift()!\n  const ang = dir.endsWith('deg') ? parseFloat(dir) : ({ 'to top': 0, 'to right': 90, 'to bottom': 180, 'to left': 270 } as Record<string, number>)[dir] ?? 180\n  const rad = (ang * Math.PI) / 180\n  const dx = Math.sin(rad) / 2\n  const dy = -Math.cos(rad) / 2\n  const stops = parts.map((p, i): [string, string] => {\n    const pm = p.match(/^(.*\\))\\s+([\\d.]+%)$/) ?? p.match(/^(\\S+)\\s+([\\d.]+%)$/)\n    return pm ? [pm[1], pm[2]] : [p, `${(i / Math.max(1, parts.length - 1)) * 100}%`]\n  })\n  return { x1: 0.5 - dx, y1: 0.5 - dy, x2: 0.5 + dx, y2: 0.5 + dy, stops }\n}\n\nfunction collect(target: HTMLElement, origin: DOMRect, scale: number): MirrorItem[] {\n  const items: MirrorItem[] = []\n  const rel = (r: DOMRect) => ({ x: (r.left - origin.left) / scale, y: (r.top - origin.top) / scale, w: r.width / scale, h: r.height / scale })\n  const visit = (el: Element, op: number) => {\n    if (el instanceof SVGElement || el.tagName === 'BUTTON' || el.tagName === 'INPUT' || el.getAttribute('data-export') === 'skip') return\n    const cs = getComputedStyle(el)\n    if (cs.display === 'none' || cs.visibility === 'hidden' || el.classList.contains('sr-only')) return\n    const o = op * (parseFloat(cs.opacity) || 0)\n    if (o <= 0.01) return\n    const r = el.getBoundingClientRect()\n    if (r.width > 0 && r.height > 0) {\n      const g = cs.backgroundImage.startsWith('linear-gradient') ? parseGradient(cs.backgroundImage) : null\n      const bw = parseFloat(cs.borderTopWidth) || 0\n      const hasBorder = bw > 0 && cs.borderTopStyle !== 'none' && !transparent(cs.borderTopColor)\n      const hasBg = !transparent(cs.backgroundColor)\n      const dashed = cs.borderTopStyle === 'dashed' && bw > 0 && !hasBg\n      if (g || hasBg || (hasBorder && !dashed)) {\n        const b = rel(r)\n        items.push({\n          k: 'rect',\n          ...b,\n          rx: Math.min(parseFloat(cs.borderTopLeftRadius) || 0, b.w / 2, b.h / 2),\n          fill: g ? '' : hasBg ? cs.backgroundColor : 'none',\n          stroke: hasBorder ? cs.borderTopColor : undefined,\n          sw: hasBorder ? bw : undefined,\n          op: o,\n          grad: g ?? undefined,\n        })\n      } else if (dashed) {\n        const b = rel(r)\n        items.push({ k: 'rect', x: b.x, y: b.y, w: b.w, h: bw, rx: 0, fill: cs.borderTopColor, op: o })\n      }\n    }\n    for (const n of el.childNodes) {\n      if (n.nodeType === Node.TEXT_NODE) {\n        const raw = (n.textContent ?? '').replace(/\\s+/g, ' ')\n        if (!raw.trim()) continue\n        const range = document.createRange()\n        range.selectNodeContents(n)\n        const rr = range.getBoundingClientRect()\n        if (!rr.width) continue\n        const b = rel(rr)\n        const text = cs.textTransform === 'uppercase' ? raw.toUpperCase() : raw\n        items.push({\n          k: 'text',\n          x: b.x,\n          y: b.y + b.h / 2,\n          text: text.trim(),\n          fill: cs.color,\n          size: cs.fontSize,\n          weight: cs.fontWeight,\n          family: cs.fontFamily,\n          style: cs.fontStyle,\n          ls: cs.letterSpacing,\n          num: cs.fontVariantNumeric,\n          op: o,\n        })\n        // leading space shifts the visible start\n        if (text.startsWith(' ')) {\n          const t = items[items.length - 1] as Extract<MirrorItem, { k: 'text' }>\n          const sp = document.createRange()\n          sp.setStart(n, 0)\n          sp.setEnd(n, 1)\n          t.x += sp.getBoundingClientRect().width / scale\n        }\n      } else if (n.nodeType === Node.ELEMENT_NODE) visit(n as Element, o)\n    }\n  }\n  visit(target, 1)\n  return items\n}\n\n/**\n * An invisible SVG copy of an HTML panel (legend, stats box, colour bar). Chart export\n * composites only SVG and canvas layers, so this keeps HTML labels in exported images.\n * It is `visibility: hidden` on screen; exported files carry no stylesheet, so it shows there.\n * Render it inside the chart root; `target` is the HTML element to copy.\n */\nexport function ExportMirror({ target }: { target: RefObject<HTMLElement | null> }) {\n  const svg = useRef<SVGSVGElement>(null)\n  const uid = useId().replace(/:/g, '')\n  const [state, setState] = useState<{ box: { x: number; y: number; w: number; h: number }; items: MirrorItem[] } | null>(null)\n  useLayoutEffect(() => {\n    const el = target.current\n    const me = svg.current\n    if (!el || !me) return\n    let raf = 0\n    const run = () => {\n      raf = 0\n      const host = me.parentElement as HTMLElement | null\n      if (!host || !el.isConnected) return\n      const hr = host.getBoundingClientRect()\n      const scale = host.offsetWidth ? hr.width / host.offsetWidth : 1\n      const tr = el.getBoundingClientRect()\n      const box = { x: (tr.left - hr.left) / scale, y: (tr.top - hr.top) / scale, w: tr.width / scale, h: tr.height / scale }\n      const items = collect(el, tr, scale || 1)\n      setState((prev) => {\n        const next = { box, items }\n        return prev && JSON.stringify(prev) === JSON.stringify(next) ? prev : next\n      })\n    }\n    const schedule = () => {\n      if (!raf) raf = requestAnimationFrame(run)\n    }\n    run()\n    const mo = new MutationObserver(schedule)\n    mo.observe(el, { subtree: true, childList: true, characterData: true, attributes: true })\n    const ro = new ResizeObserver(schedule)\n    ro.observe(el)\n    if (me.parentElement) ro.observe(me.parentElement)\n    return () => {\n      mo.disconnect()\n      ro.disconnect()\n      cancelAnimationFrame(raf)\n    }\n  }, [target])\n  const box = state?.box\n  return (\n    <svg\n      ref={svg}\n      aria-hidden\n      data-export-mirror=\"\"\n      className=\"pointer-events-none invisible absolute overflow-visible\"\n      style={{ left: box?.x ?? 0, top: box?.y ?? 0 }}\n      width={box?.w ?? 0}\n      height={box?.h ?? 0}\n      viewBox={box ? `0 0 ${box.w} ${box.h}` : undefined}\n    >\n      {state?.items.map((it, i) =>\n        it.k === 'rect' ? (\n          <g key={i}>\n            {it.grad && (\n              <defs>\n                <linearGradient id={`${uid}-${i}`} x1={it.grad.x1} y1={it.grad.y1} x2={it.grad.x2} y2={it.grad.y2}>\n                  {it.grad.stops.map(([c, o], j) => (\n                    <stop key={j} offset={o} stopColor={c} />\n                  ))}\n                </linearGradient>\n              </defs>\n            )}\n            <rect x={it.x} y={it.y} width={it.w} height={it.h} rx={it.rx} fill={it.grad ? `url(#${uid}-${i})` : it.fill} stroke={it.stroke} strokeWidth={it.sw} opacity={it.op} />\n          </g>\n        ) : (\n          <text\n            key={i}\n            x={it.x}\n            y={it.y}\n            dominantBaseline=\"central\"\n            fill={it.fill}\n            opacity={it.op}\n            style={{ fontSize: it.size, fontWeight: it.weight, fontFamily: it.family, fontStyle: it.style, letterSpacing: it.ls === 'normal' ? undefined : it.ls, fontVariantNumeric: it.num === 'normal' ? undefined : it.num, whiteSpace: 'pre' }}\n          >\n            {it.text}\n          </text>\n        ),\n      )}\n    </svg>\n  )\n}\n\n/** Visible keyboard-focus outline for an SVG mark. */\nexport function FocusRect({ x, y, width, height, rx = 4 }: { x: number; y: number; width: number; height: number; rx?: number }) {\n  return <rect x={x} y={y} width={width} height={height} rx={rx} fill=\"none\" stroke=\"var(--accent)\" strokeOpacity={0.7} strokeWidth={2} pointerEvents=\"none\" />\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/science/parts.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/bi/bi-b-util.ts",
      "content": "/*\n * Private helpers for ForecastBand, ControlChart and HorizonChart: UTC calendar\n * maths (ISO dates never shift with the viewer's time zone), date ticks and labels.\n */\n\nconst DAY = 86_400_000\n\n/** 'YYYY-MM-DD' (or any ISO string) → UTC milliseconds at midnight. */\nexport function isoMs(iso: string): number {\n  const m = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(iso)\n  if (m) return Date.UTC(+m[1], +m[2] - 1, +m[3])\n  const t = Date.parse(iso)\n  return isNaN(t) ? 0 : t\n}\n\nexport const msIso = (ms: number) => new Date(ms).toISOString().slice(0, 10)\n\nexport type Frequency = 'day' | 'week' | 'month'\n\n/** The ISO date `k` steps after `iso`. */\nexport function addSteps(iso: string, k: number, freq: Frequency): string {\n  const t = isoMs(iso)\n  if (freq === 'day') return msIso(t + k * DAY)\n  if (freq === 'week') return msIso(t + k * 7 * DAY)\n  const d = new Date(t)\n  return msIso(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + k, Math.min(d.getUTCDate(), 28)))\n}\n\n/** Frequency of a regular date series, from the median gap. */\nexport function inferFrequency(dates: string[]): Frequency {\n  if (dates.length < 2) return 'day'\n  const gaps: number[] = []\n  for (let i = 1; i < Math.min(dates.length, 40); i++) gaps.push((isoMs(dates[i]) - isoMs(dates[i - 1])) / DAY)\n  gaps.sort((a, b) => a - b)\n  const g = gaps[gaps.length >> 1]\n  return g >= 25 ? 'month' : g >= 5 ? 'week' : 'day'\n}\n\nconst dtfCache = new Map<string, Intl.DateTimeFormat>()\nfunction dtf(locale: string | undefined, o: Intl.DateTimeFormatOptions) {\n  const key = `${locale ?? 'en-US'}|${JSON.stringify(o)}`\n  let f = dtfCache.get(key)\n  if (!f) dtfCache.set(key, (f = new Intl.DateTimeFormat(locale ?? 'en-US', { ...o, timeZone: 'UTC' })))\n  return f\n}\n\n/** Date label in UTC: 'day' → 23 Nov 2026, 'month' → Nov 2026, 'short' → 23 Nov, 'mon' → Nov. */\nexport function dateLabel(iso: string, kind: 'day' | 'month' | 'short' | 'mon' | 'weekday', locale?: string): string {\n  const t = isoMs(iso)\n  if (kind === 'day') return dtf(locale, { day: 'numeric', month: 'short', year: 'numeric' }).format(t)\n  if (kind === 'month') return dtf(locale, { month: 'short', year: 'numeric' }).format(t)\n  if (kind === 'short') return dtf(locale, { day: 'numeric', month: 'short' }).format(t)\n  if (kind === 'weekday') return dtf(locale, { weekday: 'short', day: 'numeric', month: 'short' }).format(t)\n  return dtf(locale, { month: 'short' }).format(t)\n}\n\nexport interface DateTick {\n  /** Index into the date array (fractional allowed for exact month starts). */\n  i: number\n  label: string\n  /** January (year boundary) ticks get the year and stronger ink. */\n  major: boolean\n}\n\n/**\n * Month-boundary ticks for a regular date array, thinned to every 1, 2, 3, 6 or\n * 12 months so labels sit at least `minGap` px apart for the given px-per-index.\n */\nexport function monthTicks(dates: string[], pxPerIndex: number, locale?: string, minGap = 64): DateTick[] {\n  if (!dates.length) return []\n  const t0 = isoMs(dates[0])\n  const t1 = isoMs(dates[dates.length - 1])\n  const span = Math.max(1, (t1 - t0) / (dates.length - 1 || 1))\n  const pxPerMonth = (30.44 * DAY * pxPerIndex) / span\n  const every = [1, 2, 3, 6, 12].find((k) => k * pxPerMonth >= minGap) ?? 12\n  const out: DateTick[] = []\n  const d0 = new Date(t0)\n  let y = d0.getUTCFullYear()\n  let m = d0.getUTCMonth() + (d0.getUTCDate() > 1 ? 1 : 0)\n  for (;;) {\n    if (m > 11) {\n      y += Math.floor(m / 12)\n      m %= 12\n    }\n    const t = Date.UTC(y, m, 1)\n    if (t > t1) break\n    if (m % every === 0) {\n      const i = (t - t0) / span\n      const major = m === 0\n      const mon = dtf(locale, { month: 'short' }).format(t)\n      out.push({ i, label: major ? `${mon} ${y}` : mon, major })\n    }\n    m++\n  }\n  return out\n}\n\n/** Unicode-minus signed number. */\nexport const sgn = (v: number, f: (a: number) => string) => (v > 0 ? '+' : v < 0 ? '−' : '±') + f(Math.abs(v))\n",
      "type": "registry:component",
      "target": "@components/klar/charts/bi/bi-b-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"
    },
    {
      "path": "registry/klar/components/charts/science/util.ts",
      "content": "/*\n * Science collection: numerical helpers shared by the charts.\n * Everything here is plain maths (no DOM) except the colour helpers at the end.\n * Not re-exported from the collection index, so names never clash with other kits.\n */\nimport { seeded } from '@/components/klar/lib/format'\nimport type { Theme } from '@/components/klar/lib/theme'\n\nexport type Pt = [number, number]\n\nexport const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))\n\n/* ------------------------------------------------------------------ */\n/*  Descriptive statistics                                            */\n/* ------------------------------------------------------------------ */\n\nexport const sum = (a: ArrayLike<number>) => {\n  let s = 0\n  for (let i = 0; i < a.length; i++) s += a[i]\n  return s\n}\nexport const mean = (a: ArrayLike<number>) => (a.length ? sum(a) / a.length : NaN)\n\n/** Sample variance (n − 1). */\nexport function variance(a: ArrayLike<number>) {\n  const n = a.length\n  if (n < 2) return 0\n  const m = mean(a)\n  let s = 0\n  for (let i = 0; i < n; i++) s += (a[i] - m) ** 2\n  return s / (n - 1)\n}\nexport const sd = (a: ArrayLike<number>) => Math.sqrt(variance(a))\n\n/** Quantile of an ascending array, linear interpolation (R type 7). */\nexport function quantile(sorted: ArrayLike<number>, p: number) {\n  const n = sorted.length\n  if (!n) return NaN\n  const h = (n - 1) * clamp(p, 0, 1)\n  const lo = Math.floor(h)\n  const hi = Math.min(n - 1, lo + 1)\n  return sorted[lo] + (h - lo) * (sorted[hi] - sorted[lo])\n}\n\nexport interface Summary {\n  n: number\n  mean: number\n  sd: number\n  se: number\n  min: number\n  max: number\n  q1: number\n  median: number\n  q3: number\n  iqr: number\n  /** Tukey whiskers: furthest data within 1.5 × IQR of the box. */\n  whiskerLo: number\n  whiskerHi: number\n  /** 95% CI of the mean (t distribution). */\n  ciLo: number\n  ciHi: number\n  skew: number\n  /** Excess kurtosis. */\n  kurtosis: number\n  sorted: number[]\n}\n\nexport function summarize(values: number[]): Summary {\n  const sorted = [...values].sort((a, b) => a - b)\n  const n = sorted.length\n  const m = mean(sorted)\n  const s = sd(sorted)\n  const q1 = quantile(sorted, 0.25)\n  const q3 = quantile(sorted, 0.75)\n  const iqr = q3 - q1\n  const lo = q1 - 1.5 * iqr\n  const hi = q3 + 1.5 * iqr\n  let whiskerLo = sorted[0]\n  let whiskerHi = sorted[n - 1]\n  for (const v of sorted) if (v >= lo) { whiskerLo = v; break }\n  for (let i = n - 1; i >= 0; i--) if (sorted[i] <= hi) { whiskerHi = sorted[i]; break }\n  let m3 = 0\n  let m4 = 0\n  for (const v of sorted) {\n    const d = v - m\n    m3 += d ** 3\n    m4 += d ** 4\n  }\n  const pv = (s * s * (n - 1)) / n\n  const se = s / Math.sqrt(n)\n  const t = n > 1 ? tInv(0.975, n - 1) : 0\n  return {\n    n,\n    mean: m,\n    sd: s,\n    se,\n    min: sorted[0],\n    max: sorted[n - 1],\n    q1,\n    median: quantile(sorted, 0.5),\n    q3,\n    iqr,\n    whiskerLo,\n    whiskerHi,\n    ciLo: m - t * se,\n    ciHi: m + t * se,\n    skew: pv > 0 ? m3 / n / pv ** 1.5 : 0,\n    kurtosis: pv > 0 ? m4 / n / pv ** 2 - 3 : 0,\n    sorted,\n  }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Kernel density                                                    */\n/* ------------------------------------------------------------------ */\n\n/** Silverman's rule of thumb bandwidth. */\nexport function silverman(values: number[]) {\n  const s = summarize(values)\n  const spread = Math.min(s.sd, s.iqr / 1.34) || s.sd || 1\n  return 0.9 * spread * Math.pow(s.n, -0.2)\n}\n\n/** Gaussian KDE evaluated at `xs`. Returns densities (integrate to 1). */\nexport function kde(values: number[], xs: number[], bw = silverman(values)) {\n  const n = values.length\n  const k = 1 / (n * bw * Math.sqrt(2 * Math.PI))\n  return xs.map((x) => {\n    let s = 0\n    for (let i = 0; i < n; i++) {\n      const u = (x - values[i]) / bw\n      if (u > -6 && u < 6) s += Math.exp(-0.5 * u * u)\n    }\n    return s * k\n  })\n}\n\nexport const linspace = (a: number, b: number, n: number) =>\n  Array.from({ length: n }, (_, i) => a + ((b - a) * i) / Math.max(1, n - 1))\n\n/* ------------------------------------------------------------------ */\n/*  Ticks and scales                                                  */\n/* ------------------------------------------------------------------ */\n\nexport function tickStep(lo: number, hi: number, count: number) {\n  const step0 = Math.abs(hi - lo) / Math.max(1, count)\n  let step = Math.pow(10, Math.floor(Math.log10(step0 || 1)))\n  const err = step0 / step\n  if (err >= Math.sqrt(50)) step *= 10\n  else if (err >= Math.sqrt(10)) step *= 5\n  else if (err >= Math.sqrt(2)) step *= 2\n  return step\n}\n\nconst tidy = (v: number) => +v.toFixed(10)\n\n/** Nice round tick values inside [lo, hi]. */\nexport function ticks(lo: number, hi: number, count = 5) {\n  const s = tickStep(lo, hi, count)\n  const out: number[] = []\n  for (let i = Math.ceil(lo / s - 1e-9); i <= Math.floor(hi / s + 1e-9); i++) out.push(tidy(i * s))\n  return out\n}\n\n/** Extends [lo, hi] outward to round tick values. */\nexport function niceDomain(lo: number, hi: number, count = 5): [number, number] {\n  let a = lo\n  let b = hi\n  for (let k = 0; k < 2; k++) {\n    const s = tickStep(a, b, count)\n    a = tidy(Math.floor(a / s) * s)\n    b = tidy(Math.ceil(b / s) * s)\n  }\n  return [a, b]\n}\n\n/** Ticks at 1-2-5 decades for a log axis. */\nexport function logTicks(lo: number, hi: number) {\n  const out: number[] = []\n  for (let e = Math.floor(Math.log10(lo)); e <= Math.ceil(Math.log10(hi)); e++)\n    for (const m of [1, 2, 5]) {\n      const v = tidy(m * 10 ** e)\n      if (v >= lo * 0.999 && v <= hi * 1.001) out.push(v)\n    }\n  return out\n}\n\n/** Linear map from domain to range; `.invert` goes back. */\nexport function scaleLinear([d0, d1]: readonly [number, number], [r0, r1]: readonly [number, number]) {\n  const k = (r1 - r0) / (d1 - d0 || 1)\n  const f = (v: number) => r0 + (v - d0) * k\n  f.invert = (p: number) => d0 + (p - r0) / k\n  return f\n}\n\nexport function scaleLog([d0, d1]: readonly [number, number], [r0, r1]: readonly [number, number]) {\n  const l0 = Math.log(d0)\n  const k = (r1 - r0) / (Math.log(d1) - l0 || 1)\n  const f = (v: number) => r0 + (Math.log(Math.max(v, 1e-12)) - l0) * k\n  f.invert = (p: number) => Math.exp(l0 + (p - r0) / k)\n  return f\n}\n\n/** Compact label for a tick value: drops float noise, keeps a sensible number of decimals. */\nexport function tickLabel(v: number, step?: number) {\n  const d = step ? Math.max(0, -Math.floor(Math.log10(step) + 1e-9)) : 2\n  return v.toFixed(Math.min(d, 4)).replace(/^-0$/, '0')\n}\n\n/* ------------------------------------------------------------------ */\n/*  Distributions                                                     */\n/* ------------------------------------------------------------------ */\n\nexport function erf(x: number) {\n  // Abramowitz & Stegun 7.1.26 refined with a Horner series; |error| < 1.5e-7\n  const s = Math.sign(x)\n  const a = Math.abs(x)\n  const t = 1 / (1 + 0.3275911 * a)\n  const y = 1 - ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-a * a)\n  return s * y\n}\nexport const normPdf = (x: number, mu = 0, s = 1) => Math.exp(-0.5 * ((x - mu) / s) ** 2) / (s * Math.sqrt(2 * Math.PI))\nexport const normCdf = (x: number) => 0.5 * (1 + erf(x / Math.SQRT2))\n\n/** Inverse standard normal CDF (Acklam). */\nexport function normInv(p: number): number {\n  const a = [-39.69683028665376, 220.9460984245205, -275.9285104469687, 138.357751867269, -30.66479806614716, 2.506628277459239]\n  const b = [-54.47609879822406, 161.5858368580409, -155.6989798598866, 66.80131188771972, -13.28068155288572]\n  const c = [-0.007784894002430293, -0.3223964580411365, -2.400758277161838, -2.549732539343734, 4.374664141464968, 2.938163982698783]\n  const d = [0.007784695709041462, 0.3224671290700398, 2.445134137142996, 3.754408661907416]\n  const pl = 0.02425\n  if (p < pl) {\n    const q = Math.sqrt(-2 * Math.log(p))\n    return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)\n  }\n  if (p > 1 - pl) return -normInv(1 - p)\n  const q = p - 0.5\n  const r = q * q\n  return ((((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q) / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1)\n}\n\nexport function lnGamma(x: number): number {\n  const g = [76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5]\n  let y = x\n  const tmp = x + 5.5 - (x + 0.5) * Math.log(x + 5.5)\n  let ser = 1.000000000190015\n  for (const c of g) ser += c / ++y\n  return -tmp + Math.log((2.5066282746310005 * ser) / x)\n}\n\nfunction betacf(a: number, b: number, x: number) {\n  const qab = a + b\n  const qap = a + 1\n  const qam = a - 1\n  let c = 1\n  let d = 1 - (qab * x) / qap\n  if (Math.abs(d) < 1e-30) d = 1e-30\n  d = 1 / d\n  let h = d\n  for (let m = 1; m <= 200; m++) {\n    const m2 = 2 * m\n    let aa = (m * (b - m) * x) / ((qam + m2) * (a + m2))\n    d = 1 + aa * d\n    if (Math.abs(d) < 1e-30) d = 1e-30\n    c = 1 + aa / c\n    if (Math.abs(c) < 1e-30) c = 1e-30\n    d = 1 / d\n    h *= d * c\n    aa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2))\n    d = 1 + aa * d\n    if (Math.abs(d) < 1e-30) d = 1e-30\n    c = 1 + aa / c\n    if (Math.abs(c) < 1e-30) c = 1e-30\n    d = 1 / d\n    const del = d * c\n    h *= del\n    if (Math.abs(del - 1) < 3e-12) break\n  }\n  return h\n}\n\n/** Regularised incomplete beta I_x(a, b). */\nexport function betaInc(x: number, a: number, b: number) {\n  if (x <= 0) return 0\n  if (x >= 1) return 1\n  const bt = Math.exp(lnGamma(a + b) - lnGamma(a) - lnGamma(b) + a * Math.log(x) + b * Math.log(1 - x))\n  return x < (a + 1) / (a + b + 2) ? (bt * betacf(a, b, x)) / a : 1 - (bt * betacf(b, a, 1 - x)) / b\n}\n\n/** Student t CDF. */\nexport function tCdf(t: number, df: number) {\n  const p = 0.5 * betaInc(df / (df + t * t), df / 2, 0.5)\n  return t >= 0 ? 1 - p : p\n}\n\n/** Two-sided p-value for a t statistic. */\nexport const tTwoSided = (t: number, df: number) => betaInc(df / (df + t * t), df / 2, 0.5)\n\n/** Inverse Student t CDF by bisection. */\nexport function tInv(p: number, df: number) {\n  let lo = -50\n  let hi = 50\n  for (let i = 0; i < 80; i++) {\n    const mid = (lo + hi) / 2\n    if (tCdf(mid, df) < p) lo = mid\n    else hi = mid\n  }\n  return (lo + hi) / 2\n}\n\n/** Regularised lower incomplete gamma P(a, x). */\nexport function gammaP(a: number, x: number) {\n  if (x <= 0) return 0\n  const gln = lnGamma(a)\n  if (x < a + 1) {\n    let ap = a\n    let del = 1 / a\n    let s = del\n    for (let n = 0; n < 300; n++) {\n      del *= x / ++ap\n      s += del\n      if (Math.abs(del) < Math.abs(s) * 1e-14) break\n    }\n    return s * Math.exp(-x + a * Math.log(x) - gln)\n  }\n  let b = x + 1 - a\n  let c = 1e30\n  let d = 1 / b\n  let h = d\n  for (let i = 1; i < 300; i++) {\n    const an = -i * (i - a)\n    b += 2\n    d = an * d + b\n    if (Math.abs(d) < 1e-30) d = 1e-30\n    c = b + an / c\n    if (Math.abs(c) < 1e-30) c = 1e-30\n    d = 1 / d\n    const del = d * c\n    h *= del\n    if (Math.abs(del - 1) < 1e-14) break\n  }\n  return 1 - Math.exp(-x + a * Math.log(x) - gln) * h\n}\n\n/** Upper tail of the χ² distribution. */\nexport const chi2Sf = (x: number, df: number) => 1 - gammaP(df / 2, x / 2)\n\n/* ------------------------------------------------------------------ */\n/*  Ordinary least squares                                            */\n/* ------------------------------------------------------------------ */\n\nexport interface OlsFit {\n  n: number\n  slope: number\n  intercept: number\n  r: number\n  r2: number\n  /** Residual standard error. */\n  s: number\n  seSlope: number\n  t: number\n  p: number\n  tcrit: number\n  xbar: number\n  sxx: number\n  predict: (x: number) => number\n  /** Half-width of the 95% confidence band for the mean at x. */\n  ci: (x: number) => number\n  /** Half-width of the 95% prediction band at x. */\n  pi: (x: number) => number\n}\n\nexport function ols(xs: number[], ys: number[]): OlsFit {\n  const n = xs.length\n  const xbar = mean(xs)\n  const ybar = mean(ys)\n  let sxx = 0\n  let sxy = 0\n  let syy = 0\n  for (let i = 0; i < n; i++) {\n    sxx += (xs[i] - xbar) ** 2\n    sxy += (xs[i] - xbar) * (ys[i] - ybar)\n    syy += (ys[i] - ybar) ** 2\n  }\n  const slope = sxy / (sxx || 1)\n  const intercept = ybar - slope * xbar\n  const sse = Math.max(0, syy - slope * sxy)\n  const df = Math.max(1, n - 2)\n  const s = Math.sqrt(sse / df)\n  const seSlope = s / Math.sqrt(sxx || 1)\n  const t = slope / (seSlope || 1e-12)\n  const tcrit = tInv(0.975, df)\n  const r = sxy / Math.sqrt(sxx * syy || 1)\n  return {\n    n,\n    slope,\n    intercept,\n    r,\n    r2: r * r,\n    s,\n    seSlope,\n    t,\n    p: tTwoSided(t, df),\n    tcrit,\n    xbar,\n    sxx,\n    predict: (x) => intercept + slope * x,\n    ci: (x) => tcrit * s * Math.sqrt(1 / n + (x - xbar) ** 2 / sxx),\n    pi: (x) => tcrit * s * Math.sqrt(1 + 1 / n + (x - xbar) ** 2 / sxx),\n  }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Formatting                                                        */\n/* ------------------------------------------------------------------ */\n\n/** \"< 0.001\", \"0.004\", \"0.032\", \"0.41\" (APA-style p-values). */\nexport function fmtP(p: number) {\n  if (p < 0.001) return '< 0.001'\n  if (p < 0.01) return '= ' + p.toFixed(3)\n  return '= ' + p.toFixed(p < 0.1 ? 3 : 2)\n}\n\n/** Unicode minus for negative numbers, the way journals typeset them. */\nexport const minus = (s: string) => s.replace(/^-/, '−')\n\nexport const fixed = (d: number) => (v: number) => minus(v.toFixed(d))\n\n/* ------------------------------------------------------------------ */\n/*  Deterministic random variates (for demo data)                     */\n/* ------------------------------------------------------------------ */\n\nexport function rng(seed: number) {\n  const u = seeded(seed)\n  let spare: number | null = null\n  const normal = (mu = 0, s = 1) => {\n    if (spare != null) {\n      const v = spare\n      spare = null\n      return mu + s * v\n    }\n    let a = 0\n    let b = 0\n    while (a <= 1e-12) a = u()\n    b = u()\n    const r = Math.sqrt(-2 * Math.log(a))\n    spare = r * Math.sin(2 * Math.PI * b)\n    return mu + s * r * Math.cos(2 * Math.PI * b)\n  }\n  return {\n    uniform: (a = 0, b = 1) => a + (b - a) * u(),\n    normal,\n    lognormal: (mu: number, s: number) => Math.exp(normal(mu, s)),\n    /** Weibull with shape k and scale lambda. */\n    weibull: (k: number, lambda: number) => lambda * Math.pow(-Math.log(1 - u() * 0.999999), 1 / k),\n    exponential: (rate: number) => -Math.log(1 - u() * 0.999999) / rate,\n    pick: <T,>(arr: T[]) => arr[Math.floor(u() * arr.length)],\n  }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Colour: the collection's sequential ramp (\"Klar magma\")          */\n/* ------------------------------------------------------------------ */\n\n/** A ramp stop: token `a` mixed `p`% into token `b` (p = 100 → pure `a`). */\ntype Stop = { a: string; p: number; b: string }\n\nconst RAMPS: Record<Theme, Stop[]> = {\n  /* light: pale amber → orange → pink → violet → ink violet (luminance falls) */\n  light: [\n    { a: '--amber', p: 8, b: '--surface' },\n    { a: '--amber', p: 52, b: '--surface' },\n    { a: '--orange', p: 100, b: '--orange' },\n    { a: '--pink', p: 100, b: '--pink' },\n    { a: '--violet', p: 100, b: '--violet' },\n    { a: '--violet', p: 52, b: '--fg' },\n  ],\n  /* dark: magma — night violet → violet → pink → orange → amber → pale gold */\n  dark: [\n    { a: '--violet', p: 16, b: '--surface' },\n    { a: '--violet', p: 72, b: '--surface' },\n    { a: '--pink', p: 100, b: '--pink' },\n    { a: '--orange', p: 100, b: '--orange' },\n    { a: '--amber', p: 100, b: '--amber' },\n    { a: '--amber', p: 42, b: '--fg' },\n  ],\n}\n\nconst stopCss = (s: Stop) => (s.p >= 100 ? `var(${s.a})` : `color-mix(in oklab, var(${s.a}) ${s.p}%, var(${s.b}))`)\n\n/** CSS colour at t ∈ [0, 1] on the collection ramp (for SVG fills). */\nexport function rampCss(theme: Theme, t: number) {\n  const stops = RAMPS[theme]\n  const x = clamp(t, 0, 1) * (stops.length - 1)\n  const i = Math.min(stops.length - 2, Math.floor(x))\n  const f = Math.round((x - i) * 100)\n  if (f <= 0) return stopCss(stops[i])\n  if (f >= 100) return stopCss(stops[i + 1])\n  return `color-mix(in oklab, ${stopCss(stops[i + 1])} ${f}%, ${stopCss(stops[i])})`\n}\n\n/** CSS linear-gradient of the ramp, for colour bars. */\nexport function rampGradient(theme: Theme, dir = 'to right') {\n  const n = 12\n  return `linear-gradient(${dir}, ${Array.from({ length: n + 1 }, (_, i) => `${rampCss(theme, i / n)} ${((i / n) * 100).toFixed(1)}%`).join(', ')})`\n}\n\ntype RGB = [number, number, number]\n\nexport function parseColor(s: string): RGB {\n  s = s.trim()\n  if (s.startsWith('#')) {\n    let h = s.slice(1)\n    if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('')\n    const n = parseInt(h.slice(0, 6), 16)\n    return [(n >> 16) & 255, (n >> 8) & 255, n & 255]\n  }\n  const m = s.match(/rgba?\\(([^)]+)\\)/)\n  if (m) {\n    const [r, g, b] = m[1].split(/[\\s,/]+/).map(parseFloat)\n    return [r, g, b]\n  }\n  return [128, 128, 128]\n}\n\nconst toLin = (c: number) => {\n  c /= 255\n  return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4\n}\nconst toSrgb = (c: number) => 255 * clamp(c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055, 0, 1)\n\nfunction rgbToOklab([r, g, b]: RGB): RGB {\n  const R = toLin(r)\n  const G = toLin(g)\n  const B = toLin(b)\n  const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B)\n  const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B)\n  const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B)\n  return [\n    0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,\n    1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,\n    0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,\n  ]\n}\nfunction oklabToRgb([L, a, b]: RGB): RGB {\n  const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3\n  const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3\n  const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3\n  return [\n    toSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),\n    toSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),\n    toSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),\n  ]\n}\nconst mixLab = (a: RGB, b: RGB, t: number): RGB => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]\n\n/** Reads a token's resolved value from an element inside the .klar scope. */\nexport function readToken(el: Element, name: string): RGB {\n  return parseColor(getComputedStyle(el).getPropertyValue(name) || '#888')\n}\n\n/** A 256-entry RGB lookup table of the ramp, resolved from live tokens (for canvas). */\nexport function rampLUT(el: Element, theme: Theme, size = 256) {\n  const stops = RAMPS[theme].map((s) => {\n    const a = rgbToOklab(readToken(el, s.a))\n    const b = rgbToOklab(readToken(el, s.b))\n    return mixLab(b, a, s.p / 100)\n  })\n  const lut = new Uint8ClampedArray(size * 3)\n  for (let i = 0; i < size; i++) {\n    const x = (i / (size - 1)) * (stops.length - 1)\n    const k = Math.min(stops.length - 2, Math.floor(x))\n    const rgb = oklabToRgb(mixLab(stops[k], stops[k + 1], x - k))\n    lut[i * 3] = rgb[0]\n    lut[i * 3 + 1] = rgb[1]\n    lut[i * 3 + 2] = rgb[2]\n  }\n  return lut\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/science/util.ts"
    }
  ],
  "docs": "import { ControlChart } from '@/components/klar/charts/bi/ControlChart'\nData comes in through props.",
  "categories": [
    "charts",
    "bi",
    "time"
  ],
  "meta": {
    "collection": "bi",
    "kind": "time",
    "tags": [
      "control chart",
      "spc",
      "shewhart",
      "xmr",
      "p chart",
      "nelson rules",
      "western electric",
      "quality"
    ],
    "standalone": true,
    "export": "ControlChart",
    "import": "@/components/klar/charts/bi/ControlChart"
  }
}
