{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sci-clustered-heatmap",
  "type": "registry:component",
  "title": "Clustered heatmap",
  "description": "A matrix reordered by hierarchical clustering of rows and columns, with dendrograms, z-scored colour and sample annotation strips.",
  "dependencies": [
    "clsx",
    "lucide-react",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "https://klar.run/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/klar/components/charts/science/ClusteredHeatmap.tsx",
      "content": "import { useEffect, useMemo, useRef, useState } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\nimport { useTheme } from '@/components/klar/lib/theme'\nimport { useMeasure } from '@/components/klar/lib/use-measure'\nimport { ChartDataTable } from '@/components/klar/charts/a11y'\nimport { ExportMirror, FOCUS_RING, SCI_COLORS, SciTip, sciFormat } from '@/components/klar/charts/science/parts'\nimport { divergingCss, divergingGradient, divergingRgb, labelW, prepCanvas } from '@/components/klar/charts/science/science-c-util'\nimport { clamp, quantile, scaleLinear } from '@/components/klar/charts/science/util'\n\nexport type Linkage = 'average' | 'complete' | 'single' | 'ward'\nexport type DistanceMetric = 'euclidean' | 'correlation'\n\nexport interface HclustOptions {\n  linkage?: Linkage\n  metric?: DistanceMetric\n  /**\n   * 'tree': R's order (left branch first, as `hclust()$order`). 'tight' (default): at every merge\n   * the two branches are flipped so the leaves meeting at the seam are as similar as possible\n   * (a Gruvaeus–Wainer style ordering; same tree, smoother heatmap).\n   */\n  leafOrder?: 'tight' | 'tree'\n}\n\nexport interface HclustResult {\n  /** R-style merge matrix: negative = singleton −(index + 1), positive = the merge made at that (1-based) step. */\n  merge: [number, number][]\n  /** Merge heights, non-decreasing for these linkages. */\n  height: number[]\n  /** Leaf order, 0-based indices. */\n  order: number[]\n  /** Leaves under each merge (0-based indices), in drawing order. */\n  members: number[][]\n}\n\nexport interface HeatmapAnnotation {\n  /** Track name, e.g. \"Condition\". */\n  label: string\n  /** One category per column. */\n  values: string[]\n  /** Category → colour; missing ones take the collection palette. */\n  colors?: Record<string, string>\n}\n\nexport interface ClusteredHeatmapProps {\n  /** rows × columns, e.g. genes × samples. */\n  matrix: number[][]\n  rowLabels: string[]\n  colLabels: string[]\n  /** Categorical strips above the columns (tissue, condition, batch…). */\n  colAnnotations?: HeatmapAnnotation[]\n  height?: number\n  /** 'row' z-scores each row (centre and scale, as R `scale()` on rows) before clustering and colouring. */\n  scale?: 'row' | 'none'\n  linkage?: Linkage\n  metric?: DistanceMetric\n  leafOrder?: 'tight' | 'tree'\n  clusterRows?: boolean\n  clusterCols?: boolean\n  /** Colour limits (symmetric about `center`); defaults to the 99th percentile of |value − center|. */\n  limit?: number\n  /** Value at the neutral colour; 0 for z-scores, the matrix mean otherwise. */\n  center?: number\n  /** Legend title for the colour bar. */\n  valueLabel?: string\n  /** Italicise row labels (gene symbols). */\n  italicRows?: boolean\n  rowName?: string\n  colName?: string\n  formatValue?: (v: number) => string\n  /** BCP 47 locale for numbers (default en-US formatting). */\n  locale?: string\n  /** Accessible name; defaults to a description of the matrix. */\n  ariaLabel?: string\n  className?: string\n}\n\n/* ------------------------------------------------------------------ */\n/*  Maths                                                             */\n/* ------------------------------------------------------------------ */\n\n/** Row z-scores: (x − mean) / sd with the n − 1 sd, as R `t(scale(t(x)))`. Constant rows become 0. */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport function zScoreRows(matrix: number[][]) {\n  return matrix.map((row) => {\n    const n = row.length\n    const m = row.reduce((a, b) => a + b, 0) / n\n    const s = Math.sqrt(row.reduce((a, b) => a + (b - m) ** 2, 0) / Math.max(1, n - 1))\n    return row.map((v) => (s > 0 ? (v - m) / s : 0))\n  })\n}\n\n/** Condensed pairwise distances between rows (upper triangle, row-major, as R `dist`). */\nfunction distances(rows: number[][], metric: DistanceMetric) {\n  const n = rows.length\n  const D = new Float64Array(n * n)\n  const prep =\n    metric === 'correlation'\n      ? rows.map((r) => {\n          const m = r.reduce((a, b) => a + b, 0) / r.length\n          const c = r.map((v) => v - m)\n          const s = Math.sqrt(c.reduce((a, b) => a + b * b, 0)) || 1\n          return c.map((v) => v / s)\n        })\n      : rows\n  for (let i = 0; i < n; i++)\n    for (let j = i + 1; j < n; j++) {\n      const a = prep[i]\n      const b = prep[j]\n      let s = 0\n      if (metric === 'correlation') {\n        for (let k = 0; k < a.length; k++) s += a[k] * b[k]\n        s = 1 - s\n      } else {\n        for (let k = 0; k < a.length; k++) s += (a[k] - b[k]) ** 2\n        s = Math.sqrt(s)\n      }\n      D[i * n + j] = D[j * n + i] = s\n    }\n  return D\n}\n\n/**\n * Agglomerative hierarchical clustering of the rows of `matrix` with Lance–Williams updates and a\n * nearest-neighbour cache (≈ O(n²) typical). Linkages: single, complete, average (UPGMA) and\n * Ward (Ward's minimum variance on Euclidean distances = R `hclust(method = \"ward.D2\")`).\n * Metrics: Euclidean, or correlation distance 1 − r (Pearson). Heights and merges match R `hclust`.\n */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport function hclust(matrix: number[][], { linkage = 'average', metric = 'euclidean', leafOrder = 'tight' }: HclustOptions = {}): HclustResult {\n  const n = matrix.length\n  if (n === 0) return { merge: [], height: [], order: [], members: [] }\n  if (n === 1) return { merge: [], height: [], order: [0], members: [] }\n  const D = distances(matrix, metric)\n  const ward = linkage === 'ward'\n  if (ward) for (let i = 0; i < D.length; i++) D[i] *= D[i]\n  const size = new Array<number>(n).fill(1)\n  const label = Array.from({ length: n }, (_, i) => -(i + 1)) // R label of the cluster held in slot i\n  const active = new Uint8Array(n).fill(1)\n  const nn = new Int32Array(n)\n  const nnd = new Float64Array(n)\n  const findNN = (i: number) => {\n    let best = -1\n    let bd = Infinity\n    for (let j = 0; j < n; j++) {\n      if (j === i || !active[j]) continue\n      const d = D[i * n + j]\n      if (d < bd) {\n        bd = d\n        best = j\n      }\n    }\n    nn[i] = best\n    nnd[i] = bd\n  }\n  for (let i = 0; i < n; i++) findNN(i)\n\n  const merge: [number, number][] = []\n  const height: number[] = []\n  const seq: number[][] = Array.from({ length: n }, (_, i) => [i]) // leaf sequence per slot\n  const members: number[][] = []\n  const tight = leafOrder === 'tight'\n  // original leaf-to-leaf distances (unsquared) for the seam test\n  const D0 = tight ? D.slice() : D\n  const leafD = (a: number, b: number) => (ward ? Math.sqrt(D0[a * n + b]) : D0[a * n + b])\n\n  for (let step = 0; step < n - 1; step++) {\n    let a = -1\n    let bd = Infinity\n    for (let i = 0; i < n; i++) if (active[i] && nnd[i] < bd) {\n      bd = nnd[i]\n      a = i\n    }\n    let b = nn[a]\n    if (b < a) [a, b] = [b, a]\n    const dab = D[a * n + b]\n    const na = size[a]\n    const nb = size[b]\n    // Lance–Williams update into slot a\n    for (let k = 0; k < n; k++) {\n      if (!active[k] || k === a || k === b) continue\n      const dak = D[a * n + k]\n      const dbk = D[b * n + k]\n      let d: number\n      if (linkage === 'single') d = Math.min(dak, dbk)\n      else if (linkage === 'complete') d = Math.max(dak, dbk)\n      else if (linkage === 'average') d = (na * dak + nb * dbk) / (na + nb)\n      else {\n        const nk = size[k]\n        d = ((na + nk) * dak + (nb + nk) * dbk - nk * dab) / (na + nb + nk)\n      }\n      D[a * n + k] = D[k * n + a] = d\n    }\n    // R merge row: singletons first (by index), then clusters by step\n    const la = label[a]\n    const lb = label[b]\n    const pair: [number, number] = la < 0 && lb < 0 ? (Math.abs(la) < Math.abs(lb) ? [la, lb] : [lb, la]) : la < 0 ? [la, lb] : lb < 0 ? [lb, la] : la < lb ? [la, lb] : [lb, la]\n    merge.push(pair)\n    height.push(ward ? Math.sqrt(Math.max(0, dab)) : dab)\n    // leaf sequences: R order puts merge[,1] first\n    const first = pair[0] === la ? seq[a] : seq[b]\n    const second = pair[0] === la ? seq[b] : seq[a]\n    let joined: number[]\n    if (tight && first.length + second.length > 2) {\n      const opts = [\n        [first, second],\n        [[...first].reverse(), second],\n        [first, [...second].reverse()],\n        [[...first].reverse(), [...second].reverse()],\n      ]\n      let bi = 0\n      let bv = Infinity\n      opts.forEach(([p, q], i) => {\n        const v = leafD(p[p.length - 1], q[0])\n        if (v < bv - 1e-12) {\n          bv = v\n          bi = i\n        }\n      })\n      joined = [...opts[bi][0], ...opts[bi][1]]\n    } else joined = [...first, ...second]\n    seq[a] = joined\n    members.push(joined)\n    size[a] = na + nb\n    label[a] = step + 1\n    active[b] = 0\n    // refresh nearest neighbours\n    findNN(a)\n    for (let k = 0; k < n; k++) {\n      if (!active[k] || k === a) continue\n      if (nn[k] === a || nn[k] === b) findNN(k)\n      else if (D[k * n + a] < nnd[k]) {\n        nn[k] = a\n        nnd[k] = D[k * n + a]\n      }\n    }\n  }\n  const root = members[members.length - 1]\n  return { merge, height, order: root, members }\n}\n\n/** Long-format rows (one per cell) with the raw value and the row z-score, for CSV export. */\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function clusteredHeatmapToRows(matrix: number[][], rowLabels: string[], colLabels: string[]) {\n  const z = zScoreRows(matrix)\n  return matrix.flatMap((row, i) => row.map((v, j) => ({ row: rowLabels[i], col: colLabels[j], value: v, z: z[i][j] })))\n}\n\n/* ------------------------------------------------------------------ */\n/*  Chart                                                             */\n/* ------------------------------------------------------------------ */\n\ntype Sel = { axis: 'row' | 'col'; node: number } | null\n\n/** Dendrogram geometry: one elbow per merge, in leaf-position units and heights. */\nfunction dendro(h: HclustResult, leafPos: number[]) {\n  const n = leafPos.length\n  const nodePos: number[] = []\n  const nodeH: number[] = []\n  const at = (lab: number) => (lab < 0 ? leafPos[-lab - 1] : nodePos[lab - 1])\n  const hAt = (lab: number) => (lab < 0 ? 0 : nodeH[lab - 1])\n  const elbows = h.merge.map(([l, r], s) => {\n    const pl = at(l)\n    const pr = at(r)\n    nodePos[s] = (pl + pr) / 2\n    nodeH[s] = h.height[s]\n    return { s, pl, pr, hl: hAt(l), hr: hAt(r), h: h.height[s], kids: [l, r] as const }\n  })\n  return { elbows, n }\n}\n\nconst LEG_W = 132\nconst DEND = 58\nconst STRIP = 10\n\n/**\n * Clustered heatmap: a matrix (e.g. genes × samples) with hierarchical clustering of rows and\n * columns (`hclust`: average, complete, single or Ward linkage on Euclidean or correlation\n * distance), dendrograms on the top and left, optional row z-scoring, a diverging colour bar\n * (blue ↔ surface ↔ red), categorical column annotation strips with legends, and a crosshair\n * readout. Data: `matrix[row][col]`, `rowLabels`, `colLabels`, optional `colAnnotations`.\n *\n * Above 3,000 cells the cells draw to a DPR canvas. Pointer, touch and keyboard: hover or tap a cell\n * for row, column, value and z; click a dendrogram branch to highlight that cluster (click again or\n * Esc to clear); focus the chart and use the arrow keys to move cell by cell. Comfortable to\n * ~1,000 rows × 200 columns (clustering cost grows with rows²).\n */\nexport function ClusteredHeatmap({\n  matrix,\n  rowLabels,\n  colLabels,\n  colAnnotations = [],\n  height = 560,\n  scale = 'row',\n  linkage = 'average',\n  metric = 'euclidean',\n  leafOrder = 'tight',\n  clusterRows = true,\n  clusterCols = true,\n  limit,\n  center,\n  valueLabel,\n  italicRows = true,\n  rowName = 'Gene',\n  colName = 'Sample',\n  formatValue,\n  locale,\n  ariaLabel,\n  className,\n}: ClusteredHeatmapProps) {\n  const [ref, { width: W }] = useMeasure<HTMLElement>()\n  const legendRef = useRef<HTMLDivElement>(null)\n  const canvas = useRef<HTMLCanvasElement>(null)\n  const nf = sciFormat(locale)\n  const fv = formatValue ?? ((v: number) => nf.fixed(v, 2))\n  const { theme } = useTheme()\n  const [hover, setHover] = useState<{ r: number; c: number } | null>(null)\n  const [sel, setSel] = useState<Sel>(null)\n  const [hoverNode, setHoverNode] = useState<Sel>(null)\n\n  const nR = matrix.length\n  const nC = matrix[0]?.length ?? 0\n  const z = useMemo(() => zScoreRows(matrix), [matrix])\n  const shown = scale === 'row' ? z : matrix\n  const ctr = center ?? (scale === 'row' ? 0 : matrix.flat().reduce((a, b) => a + b, 0) / Math.max(1, nR * nC))\n  const lim = useMemo(() => {\n    if (limit) return limit\n    const dev = shown.flat().map((v) => Math.abs(v - ctr)).sort((a, b) => a - b)\n    const q = quantile(dev, 0.99) || 1\n    const step = q > 4 ? 1 : 0.5\n    return Math.max(step, Math.round(q / step) * step)\n  }, [shown, ctr, limit])\n\n  const rowTree = useMemo(() => (clusterRows && nR > 1 ? hclust(shown, { linkage, metric, leafOrder }) : null), [shown, clusterRows, linkage, metric, leafOrder, nR])\n  const colTree = useMemo(() => {\n    if (!clusterCols || nC < 2) return null\n    const t = shown[0].map((_, j) => shown.map((r) => r[j]))\n    return hclust(t, { linkage, metric, leafOrder })\n  }, [shown, clusterCols, linkage, metric, leafOrder, nC])\n  const rowOrder = useMemo(() => rowTree?.order ?? matrix.map((_, i) => i), [rowTree, matrix])\n  const colOrder = useMemo(() => colTree?.order ?? (matrix[0] ?? []).map((_, j) => j), [colTree, matrix])\n  const rowPos = useMemo(() => {\n    const p = new Array<number>(nR)\n    rowOrder.forEach((r, k) => (p[r] = k))\n    return p\n  }, [rowOrder, nR])\n  const colPos = useMemo(() => {\n    const p = new Array<number>(nC)\n    colOrder.forEach((c, k) => (p[c] = k))\n    return p\n  }, [colOrder, nC])\n\n  /* annotation palettes */\n  const tracks = useMemo(\n    () =>\n      colAnnotations.map((a) => {\n        const cats = [...new Set(a.values)]\n        const color = new Map(cats.map((c, i) => [c, a.colors?.[c] ?? SCI_COLORS[i % SCI_COLORS.length]]))\n        return { ...a, cats, color }\n      }),\n    [colAnnotations],\n  )\n\n  /* layout */\n  const rowLabW = Math.ceil(Math.max(...rowLabels.map((l) => labelW(l, 10.5))) + 10)\n  const colLabH = Math.ceil(Math.max(...colLabels.map((l) => labelW(l, 10.5))) + 10)\n  const showLegend = W >= 420\n  const dl = rowTree ? DEND : 0\n  const dt = colTree ? DEND : 0\n  const gx0 = dl + 6\n  const gx1 = Math.max(gx0 + nC * 3, W - rowLabW - (showLegend ? LEG_W : 0))\n  const stripsH = tracks.length ? tracks.length * (STRIP + 2) + 4 : 0\n  const gy0 = dt + 6 + stripsH\n  const gy1 = Math.max(gy0 + nR * 3, height - colLabH)\n  const cw = (gx1 - gx0) / Math.max(1, nC)\n  const ch = (gy1 - gy0) / Math.max(1, nR)\n  const inset = cw >= 6 && ch >= 6 ? 0.5 : 0\n  const useCanvas = nR * nC > 3000\n\n  const color = (v: number) => divergingCss((v - ctr) / lim)\n\n  /* canvas cells */\n  useEffect(() => {\n    const cv = canvas.current\n    if (!cv || !useCanvas || !W) return\n    const ctx = prepCanvas(cv, gx1 - gx0, gy1 - gy0)\n    if (!ctx) return\n    const ramp = divergingRgb(cv)\n    for (let i = 0; i < nR; i++)\n      for (let j = 0; j < nC; j++) {\n        const [r, g, b] = ramp((shown[i][j] - ctr) / lim)\n        ctx.fillStyle = `rgb(${r | 0},${g | 0},${b | 0})`\n        ctx.fillRect(colPos[j] * cw, rowPos[i] * ch, cw + 0.3, ch + 0.3)\n      }\n  }, [useCanvas, W, theme, shown, ctr, lim, rowPos, colPos, cw, ch, gx0, gx1, gy0, gy1, nR, nC])\n\n  /* dendrograms */\n  const rowD = useMemo(() => (rowTree ? dendro(rowTree, rowPos) : null), [rowTree, rowPos])\n  const colD = useMemo(() => (colTree ? dendro(colTree, colPos) : null), [colTree, colPos])\n  const subtree = (t: HclustResult, s: number) => {\n    const out = new Set<number>([s])\n    const walk = (k: number) => {\n      for (const c of t.merge[k]) if (c > 0) {\n        out.add(c - 1)\n        walk(c - 1)\n      }\n    }\n    walk(s)\n    return out\n  }\n  const selSet = useMemo(() => {\n    const t = sel?.axis === 'row' ? rowTree : sel?.axis === 'col' ? colTree : null\n    return sel && t ? { nodes: subtree(t, sel.node), leaves: new Set(t.members[sel.node]) } : null\n  }, [sel, rowTree, colTree])\n\n  const rowIn = (r: number) => !selSet || sel?.axis !== 'row' || selSet.leaves.has(r)\n  const colIn = (c: number) => !selSet || sel?.axis !== 'col' || selSet.leaves.has(c)\n\n  const locate = (mx: number, my: number) => {\n    if (mx < gx0 || mx > gx1 || my < gy0 || my > gy1) return null\n    const ci = clamp(Math.floor((mx - gx0) / cw), 0, nC - 1)\n    const ri = clamp(Math.floor((my - gy0) / ch), 0, nR - 1)\n    return { r: rowOrder[ri], c: colOrder[ci] }\n  }\n\n  const label = ariaLabel ?? `Clustered heatmap of ${nR} ${rowName.toLowerCase()}s by ${nC} ${colName.toLowerCase()}s, ${linkage} linkage${scale === 'row' ? ', row z-scores' : ''}`\n  const legendTitle = valueLabel ?? (scale === 'row' ? 'Row z-score' : 'Value')\n\n  /* cluster readout */\n  const clusterInfo = useMemo(() => {\n    const s = sel ?? hoverNode\n    if (!s) return null\n    const t = s.axis === 'row' ? rowTree : colTree\n    if (!t) return null\n    const leaves = t.members[s.node]\n    const names = leaves.map((k) => (s.axis === 'row' ? rowLabels[k] : colLabels[k]))\n    let means: { cat: string; color: string; v: number }[] = []\n    if (s.axis === 'row' && tracks[0]) {\n      const tr = tracks[0]\n      means = tr.cats.map((cat) => {\n        let sum = 0\n        let cnt = 0\n        leaves.forEach((r) => tr.values.forEach((v, j) => v === cat && ((sum += shown[r][j]), cnt++)))\n        return { cat, color: tr.color.get(cat)!, v: cnt ? sum / cnt : NaN }\n      })\n    }\n    const d = s.axis === 'row' ? rowD : colD\n    const e = d!.elbows[s.node]\n    return { s, leaves, names, means, h: t.height[s.node], e }\n  }, [sel, hoverNode, rowTree, colTree, rowLabels, colLabels, tracks, shown, rowD, colD])\n\n  const hOfRow = (hgt: number) => (rowTree ? scaleLinear([0, rowTree.height[rowTree.height.length - 1] || 1], [gx0 - 3, 2]) : () => 0)(hgt)\n  const hOfCol = (hgt: number) => (colTree ? scaleLinear([0, colTree.height[colTree.height.length - 1] || 1], [dt + 2, 2]) : () => 0)(hgt)\n\n  const tipRows = hover\n    ? [\n        { label: scale === 'row' ? 'Value' : legendTitle, value: fv(matrix[hover.r][hover.c]) },\n        { label: 'Row z-score', value: (z[hover.r][hover.c] > 0 ? '+' : '') + nf.fixed(z[hover.r][hover.c], 2) },\n        ...tracks.map((t) => ({ label: t.label, value: t.values[hover.c], color: t.color.get(t.values[hover.c]) })),\n      ]\n    : []\n\n  return (\n    <figure\n      ref={ref}\n      className={cn(FOCUS_RING, 'rounded-lg', className)}\n      style={{ position: 'relative', height, margin: 0 }}\n      aria-label={label}\n      tabIndex={0}\n      onKeyDown={(e) => {\n        if (e.key === 'Escape') {\n          if (!hover && !sel) return\n          e.preventDefault()\n          setHover(null)\n          return setSel(null)\n        }\n        const d = { ArrowLeft: [0, -1], ArrowRight: [0, 1], ArrowUp: [-1, 0], ArrowDown: [1, 0] }[e.key]\n        if (!d) return\n        e.preventDefault()\n        const cur = hover ? { ri: rowPos[hover.r], ci: colPos[hover.c] } : { ri: 0, ci: 0 }\n        const ri = hover ? clamp(cur.ri + d[0], 0, nR - 1) : 0\n        const ci = hover ? clamp(cur.ci + d[1], 0, nC - 1) : 0\n        setHover({ r: rowOrder[ri], c: colOrder[ci] })\n      }}\n      onBlur={() => setHover(null)}\n    >\n      {W > 0 && (\n        <>\n          {useCanvas && <canvas ref={canvas} aria-hidden className=\"anim-fade pointer-events-none absolute\" style={{ left: gx0, top: gy0, width: gx1 - gx0, height: gy1 - gy0 }} />}\n          <svg\n            width={W}\n            height={height}\n            className=\"absolute inset-0 block overflow-visible\"\n            style={{ touchAction: 'pan-y' }}\n            onPointerDown={(e) => {\n              const r = e.currentTarget.getBoundingClientRect()\n              const hit = locate(e.clientX - r.left, e.clientY - r.top)\n              if (hit) setHover(hit)\n            }}\n            onPointerMove={(e) => {\n              if (e.pointerType !== 'mouse' && !(e.buttons > 0)) return\n              const r = e.currentTarget.getBoundingClientRect()\n              setHover(locate(e.clientX - r.left, e.clientY - r.top))\n            }}\n            onPointerLeave={(e) => e.pointerType === 'mouse' && setHover(null)}\n          >\n            {/* cells */}\n            {!useCanvas && (\n              <g className=\"anim-fade\">\n                {matrix.map((row, i) =>\n                  row.map((_, j) => (\n                    <rect\n                      key={`${i}-${j}`}\n                      x={gx0 + colPos[j] * cw + inset}\n                      y={gy0 + rowPos[i] * ch + inset}\n                      width={Math.max(0.5, cw - inset * 2)}\n                      height={Math.max(0.5, ch - inset * 2)}\n                      rx={cw > 10 && ch > 10 ? 1.5 : 0}\n                      fill={color(shown[i][j])}\n                    />\n                  )),\n                )}\n              </g>\n            )}\n\n            {/* dim outside the selected cluster */}\n            {selSet && sel && (\n              <g pointerEvents=\"none\">\n                {sel.axis === 'row'\n                  ? rowOrder.map((r, k) => (rowIn(r) ? null : <rect key={r} x={gx0} y={gy0 + k * ch} width={gx1 - gx0} height={ch} fill=\"var(--surface)\" fillOpacity={0.72} />))\n                  : colOrder.map((c, k) => (colIn(c) ? null : <rect key={c} x={gx0 + k * cw} y={gy0} width={cw} height={gy1 - gy0} fill=\"var(--surface)\" fillOpacity={0.72} />))}\n                {(() => {\n                  const ps = [...selSet.leaves].map((l) => (sel.axis === 'row' ? rowPos[l] : colPos[l]))\n                  const a = Math.min(...ps)\n                  const b = Math.max(...ps) + 1\n                  return sel.axis === 'row' ? (\n                    <rect x={gx0 - 1} y={gy0 + a * ch - 1} width={gx1 - gx0 + 2} height={(b - a) * ch + 2} fill=\"none\" stroke=\"var(--fg)\" strokeWidth={1.5} rx={2} />\n                  ) : (\n                    <rect x={gx0 + a * cw - 1} y={gy0 - 1} width={(b - a) * cw + 2} height={gy1 - gy0 + 2} fill=\"none\" stroke=\"var(--fg)\" strokeWidth={1.5} rx={2} />\n                  )\n                })()}\n              </g>\n            )}\n\n            {/* annotation strips */}\n            {tracks.map((t, ti) => {\n              const y = dt + 6 + ti * (STRIP + 2)\n              return (\n                <g key={t.label}>\n                  {t.values.map((v, j) => (\n                    <rect key={j} x={gx0 + colPos[j] * cw + inset} y={y} width={Math.max(0.5, cw - inset * 2)} height={STRIP} fill={t.color.get(v)} fillOpacity={colIn(j) ? 0.9 : 0.25} />\n                  ))}\n                  <text x={gx1 + 6} y={y + 8} className=\"fill-fg-3 text-[10px] font-medium\">\n                    {t.label}\n                  </text>\n                </g>\n              )\n            })}\n\n            {/* row dendrogram (left) */}\n            {rowD && (\n              <g>\n                {rowD.elbows.map((e) => {\n                  const yl = gy0 + (e.pl + 0.5) * ch\n                  const yr = gy0 + (e.pr + 0.5) * ch\n                  const xh = hOfRow(e.h)\n                  const d = `M${hOfRow(e.hl)},${yl}H${xh}V${yr}H${hOfRow(e.hr)}`\n                  const on = sel?.axis === 'row' && selSet?.nodes.has(e.s)\n                  const hv = hoverNode?.axis === 'row' && hoverNode.node === e.s\n                  return (\n                    <g key={e.s}>\n                      <path d={d} fill=\"none\" stroke={on ? 'var(--accent)' : hv ? 'var(--fg)' : 'var(--fg-3)'} strokeWidth={on || hv ? 1.6 : 1} />\n                      <path\n                        d={`M${xh},${yl}V${yr}`}\n                        fill=\"none\"\n                        stroke=\"transparent\"\n                        strokeWidth={9}\n                        className=\"cursor-pointer\"\n                        onPointerEnter={() => setHoverNode({ axis: 'row', node: e.s })}\n                        onPointerLeave={() => setHoverNode(null)}\n                        onClick={() => setSel(sel?.axis === 'row' && sel.node === e.s ? null : { axis: 'row', node: e.s })}\n                      />\n                    </g>\n                  )\n                })}\n              </g>\n            )}\n\n            {/* column dendrogram (top) */}\n            {colD && (\n              <g>\n                {colD.elbows.map((e) => {\n                  const xl = gx0 + (e.pl + 0.5) * cw\n                  const xr = gx0 + (e.pr + 0.5) * cw\n                  const yh = hOfCol(e.h)\n                  const d = `M${xl},${hOfCol(e.hl)}V${yh}H${xr}V${hOfCol(e.hr)}`\n                  const on = sel?.axis === 'col' && selSet?.nodes.has(e.s)\n                  const hv = hoverNode?.axis === 'col' && hoverNode.node === e.s\n                  return (\n                    <g key={e.s}>\n                      <path d={d} fill=\"none\" stroke={on ? 'var(--accent)' : hv ? 'var(--fg)' : 'var(--fg-3)'} strokeWidth={on || hv ? 1.6 : 1} />\n                      <path\n                        d={`M${xl},${yh}H${xr}`}\n                        fill=\"none\"\n                        stroke=\"transparent\"\n                        strokeWidth={9}\n                        className=\"cursor-pointer\"\n                        onPointerEnter={() => setHoverNode({ axis: 'col', node: e.s })}\n                        onPointerLeave={() => setHoverNode(null)}\n                        onClick={() => setSel(sel?.axis === 'col' && sel.node === e.s ? null : { axis: 'col', node: e.s })}\n                      />\n                    </g>\n                  )\n                })}\n              </g>\n            )}\n\n            {/* labels */}\n            <g pointerEvents=\"none\">\n              {rowOrder.map((r, k) => (\n                <text\n                  key={r}\n                  x={gx1 + 6}\n                  y={gy0 + (k + 0.5) * ch + 3.6}\n                  className={cn('text-[10.5px]', italicRows && 'italic', hover?.r === r ? 'fill-fg font-semibold' : rowIn(r) ? 'fill-fg-2' : 'fill-fg-4')}\n                >\n                  {ch >= 7 || hover?.r === r ? rowLabels[r] : ''}\n                </text>\n              ))}\n              {colOrder.map((c, k) => (\n                <text\n                  key={c}\n                  transform={`translate(${gx0 + (k + 0.5) * cw + 3.5},${gy1 + 6}) rotate(90)`}\n                  className={cn('num text-[10.5px]', hover?.c === c ? 'fill-fg font-semibold' : colIn(c) ? 'fill-fg-2' : 'fill-fg-4')}\n                >\n                  {cw >= 7 || hover?.c === c ? colLabels[c] : ''}\n                </text>\n              ))}\n            </g>\n\n            {/* crosshair */}\n            {hover && (\n              <g pointerEvents=\"none\">\n                <rect x={gx0} y={gy0 + rowPos[hover.r] * ch} width={gx1 - gx0} height={ch} fill=\"none\" stroke=\"var(--fg)\" strokeOpacity={0.35} />\n                <rect x={gx0 + colPos[hover.c] * cw} y={gy0} width={cw} height={gy1 - gy0} fill=\"none\" stroke=\"var(--fg)\" strokeOpacity={0.35} />\n                <rect x={gx0 + colPos[hover.c] * cw - 0.5} y={gy0 + rowPos[hover.r] * ch - 0.5} width={cw + 1} height={ch + 1} fill=\"none\" stroke=\"var(--fg)\" strokeWidth={2} rx={1.5} />\n              </g>\n            )}\n          </svg>\n\n          {showLegend && (\n            <div ref={legendRef} className=\"pointer-events-none absolute flex flex-col gap-3 text-[10.5px] text-fg-3\" style={{ left: W - LEG_W + 14, top: gy0, width: LEG_W - 14 }}>\n              <div>\n                <div className=\"mb-1.5 text-[11px] font-medium text-fg-2\">{legendTitle}</div>\n                <div className=\"flex gap-2\">\n                  <div className=\"w-2.5 rounded-[3px] ring-1 ring-border\" style={{ height: 96, background: divergingGradient('to top') }} />\n                  <div className=\"num relative\" style={{ height: 96 }}>\n                    {[lim, lim / 2, 0, -lim / 2, -lim].map((t, i) => (\n                      <span key={i} className=\"absolute left-0 -translate-y-1/2 whitespace-nowrap\" style={{ top: (i / 4) * 96 }}>\n                        {scale === 'row' ? (t > 0 ? '+' : t < 0 ? '−' : '') + nf.str(Math.abs(t)) : nf.str(+(ctr + t).toFixed(2))}\n                      </span>\n                    ))}\n                  </div>\n                </div>\n                {hover && <div className=\"num mt-1 text-fg-2\">{(shown[hover.r][hover.c] > 0 ? '+' : '') + nf.fixed(shown[hover.r][hover.c], 2)}</div>}\n              </div>\n              {tracks.map((t) => (\n                <div key={t.label}>\n                  <div className=\"mb-1 text-[11px] font-medium text-fg-2\">{t.label}</div>\n                  <div className=\"flex flex-col gap-[3px]\">\n                    {t.cats.map((c) => (\n                      <span key={c} className=\"flex items-center gap-1.5 text-fg-2\">\n                        <span className=\"size-2.5 rounded-[2px]\" style={{ background: t.color.get(c) }} />\n                        <span className=\"truncate\">{c}</span>\n                        <span className=\"num ml-auto text-fg-4\">{t.values.filter((v) => v === c).length}</span>\n                      </span>\n                    ))}\n                  </div>\n                </div>\n              ))}\n              <div className=\"border-t border-border pt-1.5 leading-snug text-fg-4\">\n                {linkage === 'ward' ? 'Ward' : linkage[0].toUpperCase() + linkage.slice(1)} linkage · {metric === 'correlation' ? '1 − r' : 'Euclidean'}\n              </div>\n            </div>\n          )}\n          {showLegend && <ExportMirror target={legendRef} />}\n        </>\n      )}\n\n      {W > 0 && hover && (\n        <SciTip\n          x={gx0 + (colPos[hover.c] + 1) * cw}\n          y={gy0 + (rowPos[hover.r] + 0.5) * ch}\n          W={W - (showLegend ? LEG_W : 0)}\n          width={196}\n          title={<span className={italicRows ? 'italic' : undefined}>{rowLabels[hover.r]}</span>}\n          subtitle={colLabels[hover.c]}\n          rows={tipRows}\n        />\n      )}\n\n      {W > 0 && !hover && clusterInfo && (\n        <SciTip\n          {...(() => {\n            const ps = clusterInfo.leaves.map((l) => (clusterInfo.s.axis === 'row' ? rowPos[l] : colPos[l]))\n            const a = Math.min(...ps)\n            const b = Math.max(...ps) + 1\n            if (clusterInfo.s.axis === 'col') return { x: gx0 + b * cw - 10, y: gy0 + 8, anchor: 'top' as const, side: 'right' as const }\n            const above = gy0 + a * ch > 150\n            return { x: gx0 - 14, y: above ? gy0 + a * ch - 6 : gy0 + b * ch + 6, anchor: above ? ('bottom' as const) : ('top' as const), side: 'right' as const }\n          })()}\n          W={W - (showLegend ? LEG_W : 0)}\n          width={204}\n          title={`Cluster of ${clusterInfo.leaves.length} ${(clusterInfo.s.axis === 'row' ? rowName : colName).toLowerCase()}s`}\n          subtitle={`h ${nf.fixed(clusterInfo.h, 2)}`}\n          rows={\n            clusterInfo.means.length\n              ? clusterInfo.means.map((m) => ({ label: `Mean in ${m.cat}`, value: (m.v > 0 ? '+' : '') + nf.fixed(m.v, 2), color: m.color }))\n              : [{ label: 'Merge height', value: nf.fixed(clusterInfo.h, 3) }]\n          }\n          foot={\n            <span className={clusterInfo.s.axis === 'row' && italicRows ? 'italic' : undefined}>\n              {clusterInfo.names.slice(0, 8).join(', ')}\n              {clusterInfo.names.length > 8 ? ` +${clusterInfo.names.length - 8}` : ''}\n              {!sel && <span className=\"not-italic text-fg-4\"> · click to highlight</span>}\n            </span>\n          }\n        />\n      )}\n\n      <ChartDataTable\n        caption={`${label}. Rows and columns in clustered order.`}\n        columns={[{ key: 'row', label: rowName }, ...colOrder.map((c) => ({ key: `c${c}`, label: colLabels[c], format: (v: unknown) => fv(v as number) }))]}\n        rows={rowOrder.map((r) => ({ row: rowLabels[r], ...Object.fromEntries(colOrder.map((c) => [`c${c}`, matrix[r][c]])) }))}\n      />\n    </figure>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/science/ClusteredHeatmap.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/science/science-c-util.ts",
      "content": "/*\n * Private helpers for the genomics charts (VolcanoPlot, ManhattanPlot, ClusteredHeatmap):\n * a screen-space grid index for nearest-point hover, a greedy label placer with leader\n * lines, scientific p-value formatting and the red ↔ surface ↔ blue diverging ramp.\n * Not re-exported from the collection index.\n */\nimport type { SciFormat } from '@/components/klar/charts/science/parts'\nimport { clamp, parseColor, readToken } from '@/components/klar/charts/science/util'\n\n/* ------------------------------------------------------------------ */\n/*  Grid index (CSR buckets) for nearest-point queries in pixels       */\n/* ------------------------------------------------------------------ */\n\nexport interface GridIndex {\n  /** Index of the nearest point within `maxR` px, or -1. `accept` filters candidates. */\n  nearest: (x: number, y: number, maxR: number, accept?: (i: number) => boolean) => number\n  /** Number of points inside a rectangle (for label placement). */\n  count: (x0: number, y0: number, x1: number, y1: number) => number\n}\n\nexport function gridIndex(xs: ArrayLike<number>, ys: ArrayLike<number>, width: number, height: number, cell = 12): GridIndex {\n  const cols = Math.max(1, Math.ceil(width / cell) + 1)\n  const rows = Math.max(1, Math.ceil(height / cell) + 1)\n  const n = xs.length\n  const cellOf = new Int32Array(n)\n  const start = new Int32Array(cols * rows + 1)\n  for (let i = 0; i < n; i++) {\n    const c = clamp(Math.floor(xs[i] / cell), 0, cols - 1)\n    const r = clamp(Math.floor(ys[i] / cell), 0, rows - 1)\n    const k = Number.isFinite(c + r) ? r * cols + c : 0\n    cellOf[i] = k\n    start[k + 1]++\n  }\n  for (let k = 0; k < cols * rows; k++) start[k + 1] += start[k]\n  const fill = start.slice(0, cols * rows)\n  const items = new Int32Array(n)\n  for (let i = 0; i < n; i++) items[fill[cellOf[i]]++] = i\n  return {\n    nearest(x, y, maxR, accept) {\n      const c0 = Math.floor((x - maxR) / cell)\n      const c1 = Math.floor((x + maxR) / cell)\n      const r0 = Math.floor((y - maxR) / cell)\n      const r1 = Math.floor((y + maxR) / cell)\n      let best = -1\n      let bd = maxR * maxR\n      for (let r = Math.max(0, r0); r <= Math.min(rows - 1, r1); r++)\n        for (let c = Math.max(0, c0); c <= Math.min(cols - 1, c1); c++) {\n          const k = r * cols + c\n          for (let j = start[k]; j < start[k + 1]; j++) {\n            const i = items[j]\n            const d = (xs[i] - x) ** 2 + (ys[i] - y) ** 2\n            if (d <= bd && (!accept || accept(i))) {\n              bd = d\n              best = i\n            }\n          }\n        }\n      return best\n    },\n    count(x0, y0, x1, y1) {\n      let s = 0\n      for (let r = Math.max(0, Math.floor(y0 / cell)); r <= Math.min(rows - 1, Math.floor(y1 / cell)); r++)\n        for (let c = Math.max(0, Math.floor(x0 / cell)); c <= Math.min(cols - 1, Math.floor(x1 / cell)); c++) {\n          const k = r * cols + c\n          for (let j = start[k]; j < start[k + 1]; j++) {\n            const i = items[j]\n            if (xs[i] >= x0 && xs[i] <= x1 && ys[i] >= y0 && ys[i] <= y1) s++\n          }\n        }\n      return s\n    },\n  }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Label placement with leader lines                                  */\n/* ------------------------------------------------------------------ */\n\nexport interface LabelRequest {\n  /** Anchor point (px). */\n  x: number\n  y: number\n  w: number\n  h: number\n  /** Preferred horizontal side: labels drift away from the centre of the plot. */\n  side?: 1 | -1\n}\n\nexport interface PlacedLabel {\n  /** Index into the request list. */\n  i: number\n  /** Box top-left. */\n  x: number\n  y: number\n  w: number\n  h: number\n  /** Leader line from the anchor to the box, when the box sits away from it. */\n  leader: [number, number, number, number] | null\n}\n\ntype Box = { x0: number; y0: number; x1: number; y1: number }\nconst hit = (a: Box, b: Box) => a.x0 < b.x1 && a.x1 > b.x0 && a.y0 < b.y1 && a.y1 > b.y0\n\n/**\n * Greedy placer: in priority order, tries a ring of candidate boxes around each anchor\n * (8 directions × growing radius) and keeps the cheapest that stays in bounds and clears\n * every placed label, every other anchor and the `avoid` boxes. Cost = distance plus a\n * crowding penalty from `density(box)` (points under the box). Labels that fit nowhere\n * are dropped rather than overlapped.\n */\nexport function placeLabels(\n  reqs: LabelRequest[],\n  bounds: Box,\n  {\n    density,\n    avoid = [],\n    radii = [6, 14, 24, 36, 52, 72],\n    pad = 2,\n    upFirst = false,\n  }: { density?: (b: Box) => number; avoid?: Box[]; radii?: number[]; pad?: number; /** Try straight above the anchor first. */ upFirst?: boolean } = {},\n): PlacedLabel[] {\n  const placed: Box[] = [...avoid]\n  const anchors: Box[] = reqs.map((r) => ({ x0: r.x - 4, y0: r.y - 4, x1: r.x + 4, y1: r.y + 4 }))\n  const out: PlacedLabel[] = []\n  reqs.forEach((r, i) => {\n    const side = r.side ?? 1\n    // directions, preferred first: up-out, out, up, down-out, up-in, in, down, down-in\n    const dirs: [number, number, number][] = [\n      [side, -1, upFirst ? 3 : 0],\n      [side, 0, upFirst ? 6 : 2],\n      [0, -1, upFirst ? 0 : 3],\n      [side, 1, 6],\n      [-side, -1, 8],\n      [-side, 0, 10],\n      [0, 1, 10],\n      [-side, 1, 14],\n    ]\n    let best: { b: Box; cost: number; rad: number } | null = null\n    for (const rad of radii)\n      for (const [dx, dy, pen] of dirs) {\n        const ox = dx * (rad * (dy ? 0.75 : 1))\n        const oy = dy * (rad * (dx ? 0.75 : 1))\n        const cx = r.x + ox + (dx * r.w) / 2\n        const cy = r.y + oy + (dy * r.h) / 2\n        const b = { x0: cx - r.w / 2, y0: cy - r.h / 2, x1: cx + r.w / 2, y1: cy + r.h / 2 }\n        if (b.x0 < bounds.x0 || b.x1 > bounds.x1 || b.y0 < bounds.y0 || b.y1 > bounds.y1) continue\n        const bp = { x0: b.x0 - pad, y0: b.y0 - pad, x1: b.x1 + pad, y1: b.y1 + pad }\n        if (placed.some((p) => hit(p, bp))) continue\n        if (anchors.some((a, j) => j !== i && hit(a, b))) continue\n        const cost = rad + pen + (density ? density(b) * 3 : 0)\n        if (!best || cost < best.cost) best = { b, cost, rad }\n      }\n    if (!best) return\n    placed.push(best.b)\n    const { b } = best\n    // nearest point on the box to the anchor\n    const nx = clamp(r.x, b.x0, b.x1)\n    const ny = clamp(r.y, b.y0, b.y1)\n    const dist = Math.hypot(nx - r.x, ny - r.y)\n    let leader: PlacedLabel['leader'] = null\n    if (dist > 7) {\n      const k = 3.5 / dist\n      leader = [r.x + (nx - r.x) * k, r.y + (ny - r.y) * k, nx, ny]\n    }\n    out.push({ i, x: b.x0, y: b.y0, w: r.w, h: r.h, leader })\n  })\n  return out\n}\n\n/** Rough text width for 11px labels (italic gene symbols run a touch narrower). */\nexport const labelW = (s: string, px = 11, weight = 500) => s.length * px * (weight >= 600 ? 0.6 : 0.565) + 2\n\n/* ------------------------------------------------------------------ */\n/*  p-values                                                           */\n/* ------------------------------------------------------------------ */\n\nconst SUP: Record<string, string> = { '-': '⁻', '0': '⁰', '1': '¹', '2': '²', '3': '³', '4': '⁴', '5': '⁵', '6': '⁶', '7': '⁷', '8': '⁸', '9': '⁹' }\nconst sup = (n: number) => String(n).replace(/./g, (c) => SUP[c] ?? c)\n\n/** \"0.032\", \"4.1 × 10⁻⁶\", \"< 10⁻³⁰⁰\" — p-values the way genomics papers print them. */\nexport function sciP(p: number, nf: SciFormat) {\n  if (!(p > 0)) return p === 0 ? '< 10⁻³⁰⁰' : '–'\n  if (p >= 0.001) return nf.fixed(p, p >= 0.1 ? 2 : 3)\n  const e = Math.floor(Math.log10(p))\n  let m = p / 10 ** e\n  let ee = e\n  if (+m.toFixed(1) >= 10) {\n    m /= 10\n    ee += 1\n  }\n  return `${nf.fixed(m, 1)} × 10${sup(ee)}`\n}\n\n/** Minus log10 with a floor so p = 0 stays finite. */\nexport const mlog10 = (p: number) => -Math.log10(Math.max(p, 1e-300))\n\n/* ------------------------------------------------------------------ */\n/*  Diverging ramp: blue ↔ surface ↔ red                               */\n/* ------------------------------------------------------------------ */\n\n/** CSS colour for t ∈ [−1, 1] (negative blue, positive red, 0 the surface). */\nexport function divergingCss(t: number) {\n  const a = Math.round(Math.pow(clamp(Math.abs(t), 0, 1), 0.85) * 100)\n  if (a <= 0) return 'var(--surface-3)'\n  return `color-mix(in oklab, var(${t < 0 ? '--blue' : '--red'}) ${a}%, var(--surface-3))`\n}\n\n/** CSS gradient of the diverging ramp, for colour bars. */\nexport function divergingGradient(dir = 'to top') {\n  const n = 10\n  return `linear-gradient(${dir}, ${Array.from({ length: n + 1 }, (_, i) => `${divergingCss(-1 + (2 * i) / n)} ${((i / n) * 100).toFixed(1)}%`).join(', ')})`\n}\n\ntype RGB = [number, number, number]\n\n/** Resolves the ramp to RGB from live tokens (for canvas). Mixed in linear sRGB: close to oklab for a tint ramp. */\nexport function divergingRgb(el: Element) {\n  const lo = readToken(el, '--blue')\n  const hi = readToken(el, '--red')\n  const mid = readToken(el, '--surface-3')\n  return (t: number): RGB => {\n    const a = Math.pow(clamp(Math.abs(t), 0, 1), 0.85)\n    const c = t < 0 ? lo : hi\n    return [mid[0] + (c[0] - mid[0]) * a, mid[1] + (c[1] - mid[1]) * a, mid[2] + (c[2] - mid[2]) * a]\n  }\n}\n\n/** A resolved token as an `rgba()` string with alpha, for canvas fills. */\nexport function tokenRgba(el: Element, name: string, alpha = 1) {\n  const v = getComputedStyle(el).getPropertyValue(name).trim()\n  const [r, g, b] = v ? parseColor(v) : readToken(el, name)\n  return `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${alpha})`\n}\n\n/**\n * Any CSS colour (tokens, color-mix) resolved by the browser to a string canvas accepts.\n * Uses a throwaway probe inside `el` so custom properties resolve in the chart's theme scope.\n */\nexport function cssColor(el: Element, css: string) {\n  const probe = document.createElement('span')\n  probe.style.color = css\n  probe.style.display = 'none'\n  el.appendChild(probe)\n  const c = getComputedStyle(probe).color\n  probe.remove()\n  return c || 'gray'\n}\n\n/** A device-pixel-ratio canvas context sized to w × h CSS pixels, cleared. */\nexport function prepCanvas(cv: HTMLCanvasElement, w: number, h: number) {\n  const dpr = Math.min(2, window.devicePixelRatio || 1)\n  cv.width = Math.max(1, Math.round(w * dpr))\n  cv.height = Math.max(1, Math.round(h * dpr))\n  const ctx = cv.getContext('2d')\n  if (!ctx) return null\n  ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n  ctx.clearRect(0, 0, w, h)\n  return ctx\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/science/science-c-util.ts"
    },
    {
      "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"
    },
    {
      "path": "registry/klar/components/charts/export.ts",
      "content": "/**\n * Chart export: SVG, PNG and CSV, with no dependencies.\n *\n *   const ref = useRef<HTMLDivElement>(null)\n *   <div ref={ref}>…chart…</div>\n *   exportChartSvg(ref.current!, 'revenue')\n *   exportChartPng(ref.current!, 'revenue', { scale: 2 })\n *   exportCsv([{ month: 'Jan', revenue: 120 }], 'revenue')\n *\n * SVG/PNG inline the resolved CSS custom properties (tokens) and text styles so the\n * file looks the same outside the page. Canvas layers (spectrogram, vol surface)\n * are composited into the PNG.\n */\n\nexport interface ExportOptions {\n  /** PNG pixel ratio (default 2). */\n  scale?: number\n  /** Background colour; defaults to the chart's resolved surface colour. */\n  background?: string\n  /** Padding around the chart in px (default 16). */\n  padding?: number\n}\n\nconst STYLE_PROPS = [\n  'fill',\n  'fill-opacity',\n  'stroke',\n  'stroke-width',\n  'stroke-opacity',\n  'stroke-dasharray',\n  'stroke-linecap',\n  'stroke-linejoin',\n  'opacity',\n  'font-family',\n  'font-size',\n  'font-weight',\n  'letter-spacing',\n  'text-anchor',\n  'dominant-baseline',\n  'font-variant-numeric',\n] as const\n\nfunction download(blob: Blob, filename: string) {\n  const url = URL.createObjectURL(blob)\n  const a = document.createElement('a')\n  a.href = url\n  a.download = filename\n  document.body.appendChild(a)\n  a.click()\n  a.remove()\n  setTimeout(() => URL.revokeObjectURL(url), 1000)\n}\n\nconst slug = (s: string) => s.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'chart'\n\nfunction resolvedBackground(el: Element) {\n  let node: Element | null = el\n  while (node) {\n    const bg = getComputedStyle(node).backgroundColor\n    if (bg && bg !== 'transparent' && !/rgba\\(0, 0, 0, 0\\)/.test(bg)) return bg\n    node = node.parentElement\n  }\n  return '#ffffff'\n}\n\n/** Clone an SVG with computed presentation styles inlined (so var(--x) resolves). */\nfunction inlineSvg(svg: SVGSVGElement): SVGSVGElement {\n  const clone = svg.cloneNode(true) as SVGSVGElement\n  const src = svg.querySelectorAll('*')\n  const dst = clone.querySelectorAll('*')\n  const apply = (from: Element, to: Element) => {\n    const cs = getComputedStyle(from)\n    const parts: string[] = []\n    for (const p of STYLE_PROPS) {\n      const v = cs.getPropertyValue(p)\n      if (v) parts.push(`${p}:${v}`)\n    }\n    const prev = to.getAttribute('style')\n    to.setAttribute('style', parts.join(';') + (prev ? ';' + prev : ''))\n    // Attributes written as var(--token) must be resolved too.\n    for (const attr of ['fill', 'stroke', 'stop-color', 'color']) {\n      const raw = to.getAttribute(attr)\n      if (raw && raw.includes('var(')) {\n        const value = attr === 'stop-color' ? cs.getPropertyValue('stop-color') : cs.getPropertyValue(attr)\n        if (value) to.setAttribute(attr, value)\n      }\n    }\n  }\n  apply(svg, clone)\n  src.forEach((n, i) => {\n    apply(n, dst[i])\n    // CSS text-transform isn't an SVG attribute; bake it into the text itself.\n    if ((n.tagName === 'text' || n.tagName === 'tspan') && n.childElementCount === 0) {\n      const tt = getComputedStyle(n).textTransform\n      const t = dst[i].textContent ?? ''\n      if (tt === 'uppercase') dst[i].textContent = t.toUpperCase()\n      else if (tt === 'lowercase') dst[i].textContent = t.toLowerCase()\n    }\n  })\n  clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg')\n  clone.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink')\n  return clone\n}\n\n/**\n * Combine every <svg> and <canvas> inside `root` into one SVG document positioned\n * as on screen. HTML labels (legends, readouts) are not included; charts keep their\n * essential labels in SVG.\n */\nfunction composeSvg(root: HTMLElement, opts: ExportOptions = {}) {\n  const pad = opts.padding ?? 16\n  const box = root.getBoundingClientRect()\n  const sx = root.offsetWidth ? box.width / root.offsetWidth : 1\n  const w = root.offsetWidth\n  const h = root.offsetHeight\n  const doc = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\n  doc.setAttribute('xmlns', 'http://www.w3.org/2000/svg')\n  doc.setAttribute('width', String(w + pad * 2))\n  doc.setAttribute('height', String(h + pad * 2))\n  doc.setAttribute('viewBox', `0 0 ${w + pad * 2} ${h + pad * 2}`)\n  const bg = document.createElementNS('http://www.w3.org/2000/svg', 'rect')\n  bg.setAttribute('width', '100%')\n  bg.setAttribute('height', '100%')\n  bg.setAttribute('fill', opts.background ?? resolvedBackground(root))\n  doc.appendChild(bg)\n\n  const layers = root.querySelectorAll<SVGSVGElement | HTMLCanvasElement>('svg, canvas')\n  layers.forEach((layer) => {\n    // Skip nested svgs (handled by their parent) and icons inside buttons.\n    if (layer instanceof SVGSVGElement && (layer.ownerSVGElement || layer.closest('button'))) return\n    const r = layer.getBoundingClientRect()\n    if (!r.width || !r.height) return\n    const x = (r.left - box.left) / sx + pad\n    const y = (r.top - box.top) / sx + pad\n    const lw = r.width / sx\n    const lh = r.height / sx\n    if (layer instanceof HTMLCanvasElement) {\n      const img = document.createElementNS('http://www.w3.org/2000/svg', 'image')\n      img.setAttribute('x', String(x))\n      img.setAttribute('y', String(y))\n      img.setAttribute('width', String(lw))\n      img.setAttribute('height', String(lh))\n      try {\n        img.setAttribute('href', layer.toDataURL('image/png'))\n        doc.appendChild(img)\n      } catch {\n        /* tainted canvas: skip */\n      }\n      return\n    }\n    const g = document.createElementNS('http://www.w3.org/2000/svg', 'g')\n    g.setAttribute('transform', `translate(${x} ${y})`)\n    const inner = inlineSvg(layer)\n    inner.setAttribute('width', String(lw))\n    inner.setAttribute('height', String(lh))\n    if (!inner.getAttribute('viewBox')) inner.setAttribute('viewBox', `0 0 ${layer.width.baseVal.value || lw} ${layer.height.baseVal.value || lh}`)\n    g.appendChild(inner)\n    doc.appendChild(g)\n  })\n  return { doc, width: w + pad * 2, height: h + pad * 2 }\n}\n\n/** The chart as an SVG string. */\nexport function chartToSvgString(root: HTMLElement, opts?: ExportOptions) {\n  const { doc } = composeSvg(root, opts)\n  return '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' + new XMLSerializer().serializeToString(doc)\n}\n\n/** Download the chart as SVG. */\nexport function exportChartSvg(root: HTMLElement, name = 'chart', opts?: ExportOptions) {\n  download(new Blob([chartToSvgString(root, opts)], { type: 'image/svg+xml' }), `${slug(name)}.svg`)\n}\n\n/** Render the chart to a PNG blob. */\nexport async function chartToPngBlob(root: HTMLElement, opts: ExportOptions = {}): Promise<Blob> {\n  const scale = opts.scale ?? 2\n  const { doc, width, height } = composeSvg(root, opts)\n  const svgText = new XMLSerializer().serializeToString(doc)\n  const img = new Image()\n  img.decoding = 'async'\n  const url = URL.createObjectURL(new Blob([svgText], { type: 'image/svg+xml' }))\n  try {\n    await new Promise<void>((res, rej) => {\n      img.onload = () => res()\n      img.onerror = () => rej(new Error('Could not rasterise chart'))\n      img.src = url\n    })\n    const canvas = document.createElement('canvas')\n    canvas.width = Math.round(width * scale)\n    canvas.height = Math.round(height * scale)\n    const ctx = canvas.getContext('2d')!\n    ctx.scale(scale, scale)\n    ctx.drawImage(img, 0, 0, width, height)\n    return await new Promise<Blob>((res, rej) => canvas.toBlob((b) => (b ? res(b) : rej(new Error('PNG encoding failed'))), 'image/png'))\n  } finally {\n    URL.revokeObjectURL(url)\n  }\n}\n\n/** Download the chart as PNG (2× by default). */\nexport async function exportChartPng(root: HTMLElement, name = 'chart', opts?: ExportOptions) {\n  download(await chartToPngBlob(root, opts), `${slug(name)}.png`)\n}\n\n/** Rows (array of flat objects) as RFC 4180 CSV. Column order follows the first row unless given. */\nexport function toCsv(rows: Record<string, unknown>[], columns?: string[]) {\n  const cols = columns ?? Object.keys(rows[0] ?? {})\n  const cell = (v: unknown) => {\n    if (v == null) return ''\n    const s = v instanceof Date ? v.toISOString() : String(v)\n    return /[\",\\n\\r]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s\n  }\n  return [cols.map(cell).join(','), ...rows.map((r) => cols.map((c) => cell(r[c])).join(','))].join('\\r\\n')\n}\n\n/** Download rows as a CSV file (UTF-8 with BOM so Excel opens it correctly). */\nexport function exportCsv(rows: Record<string, unknown>[], name = 'chart-data', columns?: string[]) {\n  download(new Blob(['﻿' + toCsv(rows, columns)], { type: 'text/csv;charset=utf-8' }), `${slug(name)}.csv`)\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/export.ts"
    },
    {
      "path": "registry/klar/components/charts/basic/core.tsx",
      "content": "/**\n * Shared foundation for the basic charts: scales, ticks, locale-aware formatting,\n * pointer (mouse + touch + pen) hover tracking, axes, legend and tooltip.\n * Advanced charts can use it too.\n */\nimport { useCallback, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\n\n/* ------------------------------------------------------------------ */\n/*  Scales and ticks                                                  */\n/* ------------------------------------------------------------------ */\n\nexport interface LinearScale {\n  (v: number): number\n  invert: (px: number) => number\n  domain: [number, number]\n  range: [number, number]\n  ticks: number[]\n}\n\n/** \"Nice\" tick values covering [min, max] with about `count` steps. */\nexport function niceTicks(min: number, max: number, count = 5): number[] {\n  if (!isFinite(min) || !isFinite(max)) return [0]\n  if (min === max) {\n    max = min + (Math.abs(min) || 1)\n  }\n  const span = max - min\n  const raw = span / Math.max(1, count)\n  const mag = Math.pow(10, Math.floor(Math.log10(raw)))\n  const norm = raw / mag\n  const step = (norm >= 7.5 ? 10 : norm >= 3.5 ? 5 : norm >= 1.5 ? 2 : 1) * mag\n  const start = Math.floor(min / step) * step\n  const end = Math.ceil(max / step) * step\n  const out: number[] = []\n  for (let v = start; v <= end + step * 1e-6; v += step) out.push(+v.toPrecision(12))\n  return out\n}\n\n/**\n * Linear scale. With `nice` (default) the domain is widened to round tick values.\n * `zero` forces the domain to include 0 (right for bars, optional for lines).\n */\nexport function linearScale(\n  domain: [number, number],\n  range: [number, number],\n  { nice = true, zero = false, ticks = 5 }: { nice?: boolean; zero?: boolean; ticks?: number } = {},\n): LinearScale {\n  let [d0, d1] = domain\n  if (zero) {\n    d0 = Math.min(0, d0)\n    d1 = Math.max(0, d1)\n  }\n  let t = niceTicks(d0, d1, ticks)\n  if (nice) {\n    d0 = t[0]\n    d1 = t[t.length - 1]\n  } else {\n    t = t.filter((v) => v >= d0 - 1e-9 && v <= d1 + 1e-9)\n  }\n  const [r0, r1] = range\n  const k = d1 === d0 ? 0 : (r1 - r0) / (d1 - d0)\n  const scale = ((v: number) => r0 + (v - d0) * k) as LinearScale\n  scale.invert = (px) => (k === 0 ? d0 : d0 + (px - r0) / k)\n  scale.domain = [d0, d1]\n  scale.range = [r0, r1]\n  scale.ticks = t\n  return scale\n}\n\nexport interface BandScale {\n  (i: number): number\n  bandwidth: number\n  step: number\n  /** Index of the band containing a pixel position (clamped). */\n  indexAt: (px: number) => number\n}\n\n/** Evenly spaced bands for `count` categories; `padding` is the gap fraction per step. */\nexport function bandScale(count: number, range: [number, number], padding = 0.3): BandScale {\n  const [r0, r1] = range\n  const step = count > 0 ? (r1 - r0) / count : 0\n  const bandwidth = step * (1 - padding)\n  const scale = ((i: number) => r0 + step * i + (step - bandwidth) / 2) as BandScale\n  scale.bandwidth = bandwidth\n  scale.step = step\n  scale.indexAt = (px) => Math.max(0, Math.min(count - 1, Math.floor((px - r0) / (step || 1))))\n  return scale\n}\n\nexport const extent = (values: number[]): [number, number] => {\n  let lo = Infinity\n  let hi = -Infinity\n  for (const v of values) {\n    if (v == null || !isFinite(v)) continue\n    if (v < lo) lo = v\n    if (v > hi) hi = v\n  }\n  return lo === Infinity ? [0, 1] : [lo, hi]\n}\n\n/* ------------------------------------------------------------------ */\n/*  Locale-aware formatting                                           */\n/* ------------------------------------------------------------------ */\n\nexport interface Formatter {\n  /** 12,480 */\n  number: (v: number, digits?: number) => string\n  /** 12.5K, 3.2M */\n  compact: (v: number) => string\n  /** 34.5% from 0.345 */\n  percent: (v: number, digits?: number) => string\n  currency: (v: number, digits?: number) => string\n  /** $1.2M */\n  currencyCompact: (v: number) => string\n  /** Signed: +4.2 / −4.2 */\n  delta: (v: number, digits?: number) => string\n  date: (d: Date | string | number, opts?: Intl.DateTimeFormatOptions) => string\n}\n\nconst cache = new Map<string, Formatter>()\n\n/**\n * Formatter bound to a locale and currency. Pass `locale` to any basic chart to\n * localise every label, e.g. `formatter('de-DE', 'EUR').currency(1234.5)` → \"1.234,50 €\".\n */\nexport function formatter(locale = 'en-US', currency = 'USD'): Formatter {\n  const key = `${locale}|${currency}`\n  const hit = cache.get(key)\n  if (hit) return hit\n  const nf = (o: Intl.NumberFormatOptions) => new Intl.NumberFormat(locale, o)\n  const compact = nf({ notation: 'compact', maximumFractionDigits: 1 })\n  const curCompact = nf({ style: 'currency', currency, notation: 'compact', maximumFractionDigits: 1 })\n  const f: Formatter = {\n    number: (v, digits = 0) => nf({ minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    compact: (v) => compact.format(v),\n    percent: (v, digits = 0) => nf({ style: 'percent', minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    currency: (v, digits = 0) => nf({ style: 'currency', currency, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    currencyCompact: (v) => curCompact.format(v),\n    delta: (v, digits = 1) => (v > 0 ? '+' : v < 0 ? '−' : '') + nf({ minimumFractionDigits: digits, maximumFractionDigits: digits }).format(Math.abs(v)),\n    date: (d, opts = { month: 'short', day: 'numeric' }) => new Intl.DateTimeFormat(locale, opts).format(new Date(d)),\n  }\n  cache.set(key, f)\n  return f\n}\n\n/* ------------------------------------------------------------------ */\n/*  Pointer hover (mouse, touch and pen)                              */\n/* ------------------------------------------------------------------ */\n\nexport interface HoverPoint {\n  /** Position inside the element, in its own (unscaled) pixels. */\n  x: number\n  y: number\n}\n\n/**\n * Tracks the pointer over a chart for mouse, touch and pen alike.\n * Spread `bind` on the plot container. On touch, a tap or drag shows the readout\n * and it stays until the next tap elsewhere; on mouse it clears on leave.\n */\nexport function usePointerHover<T extends HTMLElement | SVGElement = HTMLDivElement>() {\n  const [point, setPoint] = useState<HoverPoint | null>(null)\n  const touch = useRef(false)\n\n  const locate = useCallback((e: PointerEvent<T>) => {\n    const el = e.currentTarget as unknown as HTMLElement\n    const r = el.getBoundingClientRect()\n    // Compensate for ancestor CSS transforms (scaled previews).\n    const sx = el.offsetWidth ? r.width / el.offsetWidth : 1\n    const sy = el.offsetHeight ? r.height / el.offsetHeight : 1\n    setPoint({ x: (e.clientX - r.left) / (sx || 1), y: (e.clientY - r.top) / (sy || 1) })\n  }, [])\n\n  const bind = {\n    onPointerDown: (e: PointerEvent<T>) => {\n      touch.current = e.pointerType !== 'mouse'\n      locate(e)\n    },\n    onPointerMove: (e: PointerEvent<T>) => {\n      if (e.pointerType === 'mouse' || e.buttons > 0 || e.pressure > 0) locate(e)\n    },\n    onPointerLeave: (e: PointerEvent<T>) => {\n      if (e.pointerType === 'mouse') setPoint(null)\n    },\n    onPointerCancel: () => setPoint(null),\n    style: { touchAction: 'pan-y' } as CSSProperties,\n  }\n  return { point, bind, clear: () => setPoint(null), isTouch: touch }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Axes (SVG)                                                        */\n/* ------------------------------------------------------------------ */\n\n/** Horizontal gridlines with value labels on the left. */\nexport function AxisY({\n  scale,\n  x0,\n  x1,\n  format = String,\n  grid = true,\n  side = 'left',\n  label,\n}: {\n  scale: LinearScale\n  /** Left and right pixel edges of the plot. */\n  x0: number\n  x1: number\n  format?: (v: number) => string\n  grid?: boolean\n  side?: 'left' | 'right'\n  label?: string\n}) {\n  return (\n    <g aria-hidden>\n      {scale.ticks.map((t) => {\n        const y = scale(t)\n        const zero = t === 0\n        return (\n          <g key={t}>\n            {grid && (\n              <line\n                x1={x0}\n                x2={x1}\n                y1={y}\n                y2={y}\n                stroke={zero ? 'var(--border-strong)' : 'var(--border)'}\n                strokeDasharray={zero || t === scale.ticks[0] ? undefined : '3 4'}\n              />\n            )}\n            <text\n              x={side === 'left' ? x0 - 10 : x1 + 10}\n              y={y + 4}\n              textAnchor={side === 'left' ? 'end' : 'start'}\n              className=\"num fill-fg-3 text-[11px]\"\n            >\n              {format(t)}\n            </text>\n          </g>\n        )\n      })}\n      {label && (\n        <text x={side === 'left' ? x0 - 10 : x1 + 10} y={scale.range[1] - 12} textAnchor={side === 'left' ? 'end' : 'start'} className=\"fill-fg-4 text-[10.5px]\">\n          {label}\n        </text>\n      )}\n    </g>\n  )\n}\n\n/** Category or tick labels under the plot. Skips labels that would collide. */\nexport function AxisX({\n  labels,\n  y,\n  minGap = 8,\n  charWidth = 6.2,\n}: {\n  labels: { x: number; text: string; anchor?: 'start' | 'middle' | 'end' }[]\n  y: number\n  minGap?: number\n  charWidth?: number\n}) {\n  let lastEnd = -Infinity\n  return (\n    <g aria-hidden>\n      {labels.map((l, i) => {\n        const w = l.text.length * charWidth\n        const start = l.anchor === 'start' ? l.x : l.anchor === 'end' ? l.x - w : l.x - w / 2\n        if (start < lastEnd + minGap) return null\n        lastEnd = start + w\n        return (\n          <text key={i} x={l.x} y={y} textAnchor={l.anchor ?? 'middle'} className=\"fill-fg-3 text-[11px]\">\n            {l.text}\n          </text>\n        )\n      })}\n    </g>\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Legend and tooltip (HTML)                                         */\n/* ------------------------------------------------------------------ */\n\nexport interface LegendItem {\n  id: string\n  label: ReactNode\n  color: string\n  value?: ReactNode\n  /** line | bar | dot | dash */\n  mark?: 'line' | 'bar' | 'dot' | 'dash'\n}\n\n/** Legend whose items can be hovered (to highlight) and clicked (to toggle). */\nexport function ChartLegend({\n  items,\n  active,\n  hidden,\n  onHover,\n  onToggle,\n  className,\n}: {\n  items: LegendItem[]\n  active?: string | null\n  hidden?: Set<string>\n  onHover?: (id: string | null) => void\n  onToggle?: (id: string) => void\n  className?: string\n}) {\n  return (\n    <div className={cn('flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[12px] text-fg-2', className)}>\n      {items.map((it) => {\n        const off = hidden?.has(it.id)\n        const dim = active != null && active !== it.id\n        return (\n          <button\n            key={it.id}\n            type=\"button\"\n            aria-pressed={onToggle ? !off : undefined}\n            onPointerEnter={() => onHover?.(it.id)}\n            onPointerLeave={() => onHover?.(null)}\n            onFocus={() => onHover?.(it.id)}\n            onBlur={() => onHover?.(null)}\n            onClick={() => onToggle?.(it.id)}\n            className={cn('inline-flex items-center gap-1.5 rounded-md transition-opacity', (dim || off) && 'opacity-40', !onToggle && 'cursor-default')}\n          >\n            <span\n              className={cn(\n                'shrink-0',\n                it.mark === 'line' ? 'h-[2.5px] w-3.5 rounded-full' : it.mark === 'dash' ? 'h-0 w-3.5 border-t-2 border-dashed' : it.mark === 'bar' ? 'size-2.5 rounded-[3px]' : 'size-2 rounded-full',\n              )}\n              style={it.mark === 'dash' ? { borderColor: it.color } : { background: it.color }}\n            />\n            <span className={off ? 'line-through' : undefined}>{it.label}</span>\n            {it.value != null && <span className=\"num text-fg-3\">{it.value}</span>}\n          </button>\n        )\n      })}\n    </div>\n  )\n}\n\n/**\n * Tooltip card positioned inside a `relative` chart container. It flips to stay\n * inside `containerWidth` and never captures the pointer.\n */\nexport function ChartTooltip({\n  x,\n  y,\n  containerWidth,\n  title,\n  rows,\n  footer,\n  width = 170,\n}: {\n  x: number\n  y: number\n  containerWidth: number\n  title?: ReactNode\n  rows: { label: ReactNode; value: ReactNode; color?: string; strong?: boolean }[]\n  footer?: ReactNode\n  width?: number\n}) {\n  const flip = x > containerWidth - width - 24\n  return (\n    <div\n      role=\"status\"\n      className=\"pointer-events-none absolute z-30 rounded-xl border border-border bg-surface px-3 py-2.5 shadow-pop\"\n      style={{ left: x, top: Math.max(0, y), minWidth: width - 20, transform: `translate(${flip ? 'calc(-100% - 12px)' : '12px'}, -50%)` }}\n    >\n      {title != null && <div className=\"mb-1.5 text-[11.5px] font-medium text-fg-3\">{title}</div>}\n      <div className=\"flex flex-col gap-1\">\n        {rows.map((r, i) => (\n          <div key={i} className=\"flex items-center justify-between gap-5 text-[12.5px]\">\n            <span className=\"flex items-center gap-1.5 text-fg-2\">\n              {r.color && <span className=\"size-2 rounded-full\" style={{ background: r.color }} />}\n              {r.label}\n            </span>\n            <span className={cn('num text-fg', r.strong === false ? 'font-medium' : 'font-semibold')}>{r.value}</span>\n          </div>\n        ))}\n      </div>\n      {footer != null && <div className=\"mt-2 border-t border-border pt-1.5 text-[11.5px] text-fg-3\">{footer}</div>}\n    </div>\n  )\n}\n\n/** Default categorical palette, in order. */\nexport const PALETTE = ['var(--blue)', 'var(--orange)', 'var(--teal)', 'var(--violet)', 'var(--pink)', 'var(--amber)', 'var(--green)', 'var(--sky)']\n",
      "type": "registry:component",
      "target": "@components/klar/charts/basic/core.tsx"
    }
  ],
  "docs": "import { ClusteredHeatmap } from '@/components/klar/charts/science/ClusteredHeatmap'\nData comes in through props.",
  "categories": [
    "charts",
    "science",
    "relationship"
  ],
  "meta": {
    "collection": "science",
    "kind": "relationship",
    "tags": [
      "heatmap",
      "clustering",
      "dendrogram",
      "gene-expression",
      "z-score",
      "hclust",
      "matrix"
    ],
    "standalone": true,
    "export": "ClusteredHeatmap",
    "import": "@/components/klar/charts/science/ClusteredHeatmap"
  }
}
