{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "fin-treemap",
  "type": "registry:component",
  "title": "Market treemap",
  "description": "Every stock in an index as a tile sized by market cap and coloured by its daily move, grouped into sectors with their weighted change.",
  "dependencies": [
    "clsx",
    "lucide-react",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "https://klar.run/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/klar/components/charts/finance/MarketTreemap.tsx",
      "content": "import { useMemo, useState, type KeyboardEvent, type PointerEvent } 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 { releaseTouch, ringRect } from '@/components/klar/charts/bi/interaction'\nimport { clamp, compact, diverging, fixed, pointer, signed } from '@/components/klar/charts/finance/util'\n\nexport interface TreemapTicker {\n  ticker: string\n  name?: string\n  /** Market capitalisation (any currency unit). */\n  cap: number\n  /** Daily change in percent. */\n  change: number\n}\n\nexport interface TreemapSector {\n  sector: string\n  items: TreemapTicker[]\n}\n\nexport interface MarketTreemapProps {\n  data: TreemapSector[]\n  height?: number\n  /** Percent change at which tiles reach full colour (±). */\n  range?: number\n  /** Currency prefix for market caps. */\n  currency?: string\n  /** Legend and breadth strip above the map. */\n  legend?: boolean\n  /** BCP 47 locale for numbers (default en-US). */\n  locale?: string\n  /** Accessible name; defaults to a summary of sectors and the cap-weighted move. */\n  ariaLabel?: string\n  className?: string\n}\n\nexport interface Rect<T> {\n  x: number\n  y: number\n  w: number\n  h: number\n  data: T\n}\n\n/**\n * Squarified treemap layout (Bruls, Huizing & van Wijk, 2000): lays items out\n * in rows along the shorter side, adding to a row while it improves the worst\n * aspect ratio. Items must have positive `value`.\n */\n// oxlint-disable-next-line react/only-export-components -- layout helper lives next to its chart\nexport function squarify<T>(items: { value: number; data: T }[], x: number, y: number, w: number, h: number): Rect<T>[] {\n  const total = items.reduce((s, i) => s + i.value, 0)\n  if (!total || w <= 0 || h <= 0) return []\n  const k = (w * h) / total\n  const queue = [...items].sort((a, b) => b.value - a.value).map((i) => ({ area: i.value * k, data: i.data }))\n  const out: Rect<T>[] = []\n  let rx = x\n  let ry = y\n  let rw = w\n  let rh = h\n\n  const worst = (row: number[], side: number) => {\n    const s = row.reduce((a, b) => a + b, 0)\n    const mx = row.reduce((a, b) => (b > a ? b : a), -Infinity)\n    const mn = row.reduce((a, b) => (b < a ? b : a), Infinity)\n    return Math.max((side * side * mx) / (s * s), (s * s) / (side * side * mn))\n  }\n\n  let row: typeof queue = []\n  const layoutRow = () => {\n    const s = row.reduce((a, r) => a + r.area, 0)\n    if (rw >= rh) {\n      // vertical strip on the left\n      const cw = s / rh\n      let cy = ry\n      for (const r of row) {\n        const ch = r.area / cw\n        out.push({ x: rx, y: cy, w: cw, h: ch, data: r.data })\n        cy += ch\n      }\n      rx += cw\n      rw -= cw\n    } else {\n      const ch = s / rw\n      let cx = rx\n      for (const r of row) {\n        const cw = r.area / ch\n        out.push({ x: cx, y: ry, w: cw, h: ch, data: r.data })\n        cx += cw\n      }\n      ry += ch\n      rh -= ch\n    }\n    row = []\n  }\n\n  for (const item of queue) {\n    const side = Math.min(rw, rh)\n    if (!row.length || worst([...row.map((r) => r.area), item.area], side) <= worst(row.map((r) => r.area), side)) {\n      row.push(item)\n    } else {\n      layoutRow()\n      row.push(item)\n    }\n  }\n  if (row.length) layoutRow()\n  return out\n}\n\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function marketTreemapToRows(data: TreemapSector[]) {\n  return data.flatMap((s) => s.items.map((i) => ({ sector: s.sector, ticker: i.ticker, name: i.name ?? '', cap: i.cap, change: i.change })))\n}\n\n/** Truncates a label to fit `w` px at roughly `cw` px per character. */\nconst fitLabel = (s: string, w: number, cw: number) => {\n  const n = Math.floor(w / cw)\n  return s.length <= n ? s : n < 4 ? '' : `${s.slice(0, n - 1).trimEnd()}…`\n}\n\ninterface Tile extends TreemapTicker {\n  sector: string\n}\n\n/**\n * Market treemap: sectors, then tickers inside them, sized by market cap with a\n * squarified layout and coloured by daily change on a diverging red ↔ green\n * scale. Sector headers carry the cap-weighted move; tiles show ticker and\n * change when they fit; hover highlights the tile and reads out cap, index\n * weight, contribution and the sector's leaders and laggards.\n * Data: `TreemapSector[]` (`{ sector, items: { ticker, name?, cap, change }[] }`).\n *\n * Size: comfortable to ~2,000 tickers (one SVG group per tile; tiles too small\n * for text simply go unlabelled).\n *\n * Keyboard: focus the map, ←/→ step tiles, ↑/↓ jump sectors, Home/End, Esc clears.\n * Touch: tap a tile to read it; the readout stays until the next tap.\n */\nexport function MarketTreemap({ data, height = 480, range = 3, currency = '$', legend = true, locale, ariaLabel, className }: MarketTreemapProps) {\n  const [ref, { width }] = useMeasure()\n  const { theme } = useTheme()\n  const [hover, setHover] = useState<{ t: Tile; x: number; y: number } | null>(null)\n  const [kbd, setKbd] = useState(false)\n  const sg = (v: number, d: number, unit = '') => signed(v, d, unit, locale)\n\n  const LEGEND = legend ? 38 : 0\n  const mapH = height - LEGEND\n\n  const totals = useMemo(() => {\n    const total = data.reduce((s, d) => s + d.items.reduce((a, i) => a + i.cap, 0), 0)\n    const sectors = data.map((d) => {\n      const cap = d.items.reduce((a, i) => a + i.cap, 0)\n      return { sector: d.sector, cap, change: d.items.reduce((a, i) => a + i.cap * i.change, 0) / cap }\n    })\n    const all = data.flatMap((d) => d.items)\n    return {\n      total,\n      sectors: Object.fromEntries(sectors.map((s) => [s.sector, s])),\n      index: all.reduce((a, i) => a + i.cap * i.change, 0) / total,\n      up: all.filter((i) => i.change > 0.005).length,\n      down: all.filter((i) => i.change < -0.005).length,\n      flat: all.filter((i) => Math.abs(i.change) <= 0.005).length,\n    }\n  }, [data])\n\n  const layout = useMemo(() => {\n    if (!width) return []\n    const G = 3\n    const secs = squarify(\n      data.map((d) => ({ value: d.items.reduce((a, i) => a + i.cap, 0), data: d })),\n      0,\n      0,\n      width,\n      mapH,\n    )\n    return secs.map((s) => {\n      const header = s.h > 54 && s.w > 70 ? 18 : 0\n      const inner = { x: s.x + G / 2, y: s.y + G / 2 + header, w: s.w - G, h: s.h - G - header }\n      const tiles = squarify(\n        s.data.items.map((i) => ({ value: i.cap, data: { ...i, sector: s.data.sector } as Tile })),\n        inner.x,\n        inner.y,\n        inner.w,\n        inner.h,\n      )\n      return { ...s, header, tiles }\n    })\n  }, [data, width, mapH])\n\n  const textOn = (t: number) => {\n    if (theme === 'dark') return { main: 'var(--fg)', sub: 'color-mix(in oklab, var(--fg) 72%, transparent)' }\n    // knock-out text only on the fully saturated tiles, where it keeps its contrast\n    return Math.abs(t) > 0.86\n      ? { main: 'var(--surface)', sub: 'color-mix(in oklab, var(--surface) 86%, transparent)' }\n      : { main: 'var(--fg)', sub: 'color-mix(in oklab, var(--fg) 70%, transparent)' }\n  }\n  const fill = (change: number) => diverging(change / range, { mid: 'var(--surface-4)', gamma: theme === 'dark' ? 0.75 : 0.62 })\n\n  const onMove = (e: PointerEvent<Element>, t: Tile) => {\n    if (e.pointerType === 'touch' && e.type === 'pointermove' && e.buttons === 0) return\n    setKbd(false)\n    const [px, py] = pointer(e, e.currentTarget.closest('[data-tm]')!, width)\n    setHover({ t, x: px, y: py })\n  }\n\n  /* Keyboard: tiles in layout order, sector by sector. */\n  const flat = layout.flatMap((s, si) => s.tiles.map((r) => ({ r, si })))\n  const keyAt = (k: number) => {\n    const { r } = flat[k]\n    setKbd(true)\n    setHover({ t: r.data, x: r.x + r.w / 2, y: r.y + r.h / 2 })\n  }\n  const onKey = (e: KeyboardEvent) => {\n    if (!flat.length) return\n    const cur = hover ? flat.findIndex((f) => f.r.data.ticker === hover.t.ticker) : -1\n    let next: number | null | undefined\n    if (e.key === 'ArrowRight') next = cur < 0 ? 0 : Math.min(flat.length - 1, cur + 1)\n    else if (e.key === 'ArrowLeft') next = cur < 0 ? 0 : Math.max(0, cur - 1)\n    else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n      const si = cur < 0 ? -1 : flat[cur].si\n      const target = e.key === 'ArrowDown' ? Math.min(layout.length - 1, si + 1) : Math.max(0, si - 1)\n      next = flat.findIndex((f) => f.si === target)\n    } else if (e.key === 'Home') next = 0\n    else if (e.key === 'End') next = flat.length - 1\n    else if (e.key === 'Escape') next = null\n    if (next === undefined) return\n    e.preventDefault()\n    if (next == null || next < 0) {\n      setHover(null)\n      setKbd(false)\n    } else keyAt(next)\n  }\n  const kr = kbd && hover ? flat.find((f) => f.r.data.ticker === hover.t.ticker)?.r : undefined\n\n  const steps = [-range, (-range * 2) / 3, -range / 3, 0, range / 3, (range * 2) / 3, range]\n  const hs = hover ? data.find((d) => d.sector === hover.t.sector)! : null\n  // leaders and laggards of the hovered sector, always including the hovered name\n  const sorted = hs ? [...hs.items].sort((a, b) => b.change - a.change) : []\n  const peers =\n    sorted.length <= 7 ? sorted : sorted.filter((p, k) => k < 3 || k >= sorted.length - 3 || p.ticker === hover?.t.ticker)\n\n  return (\n    <div className={cn('flex flex-col', className)}>\n      {legend && (\n        <div className=\"flex h-[38px] items-start justify-between gap-4 text-[11.5px]\">\n          <div className=\"flex items-center gap-4 whitespace-nowrap text-fg-3\">\n            <span>\n              Cap-weighted{' '}\n              <span className=\"num font-semibold\" style={{ color: totals.index >= 0 ? 'var(--green)' : 'var(--red)' }}>\n                {sg(totals.index, 2, '%')}\n              </span>\n            </span>\n            <span className=\"num\">\n              <span className=\"font-medium text-green\">{totals.up}</span> up ·{' '}\n              <span className=\"font-medium text-red\">{totals.down}</span> down\n              {totals.flat > 0 && <> · {totals.flat} flat</>}\n            </span>\n            <span className=\"flex h-1.5 w-28 overflow-hidden rounded-full\">\n              <span style={{ flex: totals.up, background: 'var(--green)' }} />\n              <span style={{ flex: totals.flat, background: 'var(--fg-4)' }} />\n              <span style={{ flex: totals.down, background: 'var(--red)' }} />\n            </span>\n          </div>\n          <div className=\"flex items-center gap-[2px]\">\n            {steps.map((s, i) => (\n              <div key={i} className=\"flex flex-col items-center gap-1\">\n                <span className=\"h-3 w-9 first:rounded-l-[3px] last:rounded-r-[3px]\" style={{ background: fill(s), borderRadius: i === 0 ? '3px 0 0 3px' : i === steps.length - 1 ? '0 3px 3px 0' : 0 }} />\n                <span className=\"num text-[10px] text-fg-3\">{s === 0 ? '0%' : sg(s, Number.isInteger(s) ? 0 : 1, '%')}</span>\n              </div>\n            ))}\n          </div>\n        </div>\n      )}\n\n      <div\n        ref={ref}\n        data-tm\n        role=\"img\"\n        aria-label={ariaLabel ?? `Market treemap of ${data.length} sectors sized by market cap and coloured by daily change; cap-weighted ${sg(totals.index, 2, '%')}`}\n        tabIndex={0}\n        className=\"relative w-full outline-none\"\n        style={{ height: mapH, touchAction: 'pan-y' }}\n        onPointerLeave={(e) => {\n          if (e.pointerType !== 'touch') setHover(null)\n        }}\n        onPointerDown={(e) => {\n          // a tap on the gaps between tiles clears the readout\n          if (e.pointerType === 'touch' && !(e.target as Element).closest('[data-tile]')) setHover(null)\n        }}\n        onKeyDown={onKey}\n        onBlur={() => {\n          setHover(null)\n          setKbd(false)\n        }}\n      >\n        {width > 0 && (\n          <svg width={width} height={mapH} className=\"block\">\n            {layout.map((s) => {\n              const sec = totals.sectors[s.data.sector]\n              const dimSector = hover && hover.t.sector !== s.data.sector\n              return (\n                <g key={s.data.sector}>\n                  <rect x={s.x + 1} y={s.y + 1} width={s.w - 2} height={s.h - 2} rx={4} fill=\"var(--surface-2)\" />\n                  {s.header > 0 && (\n                    <g pointerEvents=\"none\">\n                      <text x={s.x + 7} y={s.y + 14} className=\"text-[10px] font-semibold tracking-[0.06em] uppercase\" fill={dimSector ? 'var(--fg-3)' : 'var(--fg-2)'}>\n                        {fitLabel(s.data.sector, s.w - 14 - (s.w > 110 ? 52 : 0), 7.1)}\n                      </text>\n                      {s.w > 110 && (\n                        <text\n                          x={s.x + s.w - 7}\n                          y={s.y + 14}\n                          textAnchor=\"end\"\n                          className=\"num text-[10.5px] font-semibold\"\n                          fill={sec.change >= 0 ? 'var(--green)' : 'var(--red)'}\n                        >\n                          {sg(sec.change, 2, '%')}\n                        </text>\n                      )}\n                    </g>\n                  )}\n                  {s.tiles.map((r) => {\n                    const t = r.data\n                    const tt = clamp(t.change / range, -1, 1)\n                    const tc = textOn(tt)\n                    const on = hover?.t.ticker === t.ticker\n                    const area = r.w * r.h\n                    const fs = clamp(Math.sqrt(area) / 4.6, 10, 22)\n                    const ps = clamp(fs * 0.62, 10, 13.5)\n                    const showT = r.w > t.ticker.length * fs * 0.66 + 6 && r.h > fs + 4\n                    const showP = showT && r.h > fs * 2 + 8 && r.w > 6 * ps * 0.62 + 6\n                    const showN = showP && r.w > 116 && r.h > fs * 2 + 34 && t.name\n                    const cy = r.y + r.h / 2\n                    const lines = showN ? 3 : showP ? 2 : 1\n                    const top = cy - ((lines - 1) * (fs * 0.62)) / 2\n                    return (\n                      <g\n                        key={t.ticker}\n                        data-tile=\"\"\n                        onPointerMove={(e) => onMove(e, t)}\n                        onPointerDown={(e) => {\n                          releaseTouch(e)\n                          onMove(e, t)\n                        }}\n                        style={{ cursor: 'pointer' }}\n                      >\n                        <rect\n                          x={r.x + 0.5}\n                          y={r.y + 0.5}\n                          width={Math.max(0, r.w - 1)}\n                          height={Math.max(0, r.h - 1)}\n                          rx={2.5}\n                          fill={fill(t.change)}\n                          opacity={dimSector ? 0.55 : 1}\n                          style={{ transition: 'opacity 160ms' }}\n                        />\n                        {showT && (\n                          <g pointerEvents=\"none\" opacity={dimSector ? 0.6 : 1}>\n                            <text x={r.x + r.w / 2} y={top + fs * 0.34} textAnchor=\"middle\" className=\"font-semibold\" style={{ fontSize: fs, letterSpacing: '-0.01em' }} fill={tc.main}>\n                              {t.ticker}\n                            </text>\n                            {showP && (\n                              <text\n                                x={r.x + r.w / 2}\n                                y={top + fs * 0.34 + fs * 0.62 + 4}\n                                textAnchor=\"middle\"\n                                className=\"num font-medium\"\n                                style={{ fontSize: ps }}\n                                fill={tc.sub}\n                              >\n                                {sg(t.change, 2, '%')}\n                              </text>\n                            )}\n                            {showN && (\n                              <text x={r.x + r.w / 2} y={top + fs * 0.34 + fs * 1.24 + 10} textAnchor=\"middle\" style={{ fontSize: 10.5 }} fill={tc.sub}>\n                                {t.name}\n                              </text>\n                            )}\n                          </g>\n                        )}\n                        {on && (\n                          <rect\n                            x={r.x + 0.5}\n                            y={r.y + 0.5}\n                            width={Math.max(0, r.w - 1)}\n                            height={Math.max(0, r.h - 1)}\n                            rx={2.5}\n                            fill=\"none\"\n                            stroke=\"var(--fg)\"\n                            strokeWidth={2}\n                            pointerEvents=\"none\"\n                          />\n                        )}\n                      </g>\n                    )\n                  })}\n                </g>\n              )\n            })}\n            {kr && <rect {...ringRect(kr.x + 0.5, kr.y + 0.5, Math.max(0, kr.w - 1), Math.max(0, kr.h - 1), { rx: 3.5, pad: 1.5 })} />}\n          </svg>\n        )}\n\n        {hover && hs && (\n          <div\n            className=\"pointer-events-none absolute z-30 w-[232px] rounded-xl border border-border-strong bg-surface/95 p-3 shadow-pop backdrop-blur-sm\"\n            style={{\n              left: hover.x,\n              top: clamp(hover.y, 0, mapH - 210),\n              transform: `translate(${hover.x > width - 260 ? 'calc(-100% - 14px)' : '14px'}, 0)`,\n            }}\n          >\n            <div className=\"flex items-baseline justify-between gap-2\">\n              <span className=\"text-[13px] font-semibold text-fg\">{hover.t.ticker}</span>\n              <span className=\"num text-[13px] font-semibold\" style={{ color: hover.t.change >= 0 ? 'var(--green)' : 'var(--red)' }}>\n                {sg(hover.t.change, 2, '%')}\n              </span>\n            </div>\n            <div className=\"truncate text-[11.5px] text-fg-3\">\n              {hover.t.name ? `${hover.t.name} · ` : ''}\n              {hover.t.sector}\n            </div>\n            <div className=\"mt-2 grid grid-cols-3 gap-2 border-y border-border py-2\">\n              {[\n                ['Mkt cap', `${currency}${compact(hover.t.cap, hover.t.cap >= 1e12 ? 2 : 1, locale)}`],\n                ['Weight', `${fixed((hover.t.cap / totals.total) * 100, 2, locale)}%`],\n                ['Contrib', `${sg((hover.t.cap / totals.total) * hover.t.change * 100, 1)}bp`],\n              ].map(([l, v]) => (\n                <div key={l}>\n                  <div className=\"text-[10px] font-medium tracking-[0.04em] text-fg-3 uppercase\">{l}</div>\n                  <div className=\"num text-[12px] font-medium text-fg\">{v}</div>\n                </div>\n              ))}\n            </div>\n            <div className=\"mt-2 flex flex-col gap-[3px]\">\n              {peers.map((p) => {\n                const w = Math.min(1, Math.abs(p.change) / range)\n                const on = p.ticker === hover.t.ticker\n                return (\n                  <div key={p.ticker} className={cn('grid grid-cols-[42px_1fr_48px] items-center gap-2 text-[11px]', on ? 'text-fg' : 'text-fg-2')}>\n                    <span className={cn('truncate', on && 'font-semibold')}>{p.ticker}</span>\n                    <span className=\"relative h-1.5\">\n                      <span className=\"absolute inset-y-0 left-1/2 w-px bg-border-strong\" />\n                      <span\n                        className=\"absolute inset-y-0 rounded-full\"\n                        style={{\n                          background: p.change >= 0 ? 'var(--green)' : 'var(--red)',\n                          left: p.change >= 0 ? '50%' : `${50 - w * 50}%`,\n                          width: `${w * 50}%`,\n                          opacity: on ? 1 : 0.6,\n                        }}\n                      />\n                    </span>\n                    <span className=\"num text-right\">{sg(p.change, 2, '%')}</span>\n                  </div>\n                )\n              })}\n              {sorted.length > peers.length && (\n                <div className=\"text-[10.5px] text-fg-4\">\n                  Top and bottom 3 of {sorted.length} in {hover.t.sector.toLowerCase()}\n                </div>\n              )}\n            </div>\n          </div>\n        )}\n      </div>\n      <ChartDataTable\n        caption=\"Tickers by sector: market cap and daily change\"\n        columns={[\n          { key: 'sector', label: 'Sector' },\n          { key: 'ticker', label: 'Ticker', align: 'left' },\n          { key: 'name', label: 'Name', align: 'left' },\n          { key: 'cap', label: 'Market cap', format: (v) => `${currency}${compact(Number(v), 1, locale)}` },\n          { key: 'change', label: 'Change', format: (v) => sg(Number(v), 2, '%') },\n        ]}\n        rows={marketTreemapToRows(data)}\n      />\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/finance/MarketTreemap.tsx"
    },
    {
      "path": "registry/klar/components/charts/a11y.tsx",
      "content": "import { useState, type ReactNode, type RefObject } from 'react'\nimport { Download, Table2 } from 'lucide-react'\nimport { cn } from '@/components/klar/lib/cn'\nimport { exportChartPng, exportChartSvg, exportCsv } from '@/components/klar/charts/export'\n\n/**\n * Accessible data behind a chart. Renders a real <table> that screen readers use\n * (visually hidden by default). With `toggle`, sighted users can reveal it too.\n *\n *   <ChartDataTable caption=\"Revenue by month\" columns={[{ key: 'month', label: 'Month' }, …]} rows={data} />\n */\nexport interface DataTableColumn {\n  key: string\n  label: string\n  /** Format a cell for display (the raw value is used for CSV). */\n  format?: (v: unknown, row: Record<string, unknown>) => string\n  align?: 'left' | 'right'\n}\n\nexport function ChartDataTable({\n  caption,\n  columns,\n  rows,\n  visible = false,\n  className,\n}: {\n  caption: string\n  columns: DataTableColumn[]\n  rows: Record<string, unknown>[]\n  /** Show the table visually instead of only to assistive tech. */\n  visible?: boolean\n  className?: string\n}) {\n  return (\n    <div className={cn(visible ? 'scroll-thin max-h-72 overflow-auto rounded-xl border border-border' : 'sr-only', className)}>\n      <table className=\"w-full border-collapse text-[12.5px]\">\n        <caption className={visible ? 'px-3 pt-2.5 pb-1 text-left text-[12px] text-fg-3' : undefined}>{caption}</caption>\n        <thead className={visible ? 'sticky top-0 bg-surface-2' : undefined}>\n          <tr>\n            {columns.map((c) => (\n              <th key={c.key} scope=\"col\" className={cn('px-3 py-2 font-medium text-fg-2', c.align === 'right' ? 'text-right' : 'text-left')}>\n                {c.label}\n              </th>\n            ))}\n          </tr>\n        </thead>\n        <tbody>\n          {rows.map((r, i) => (\n            <tr key={i} className={visible ? 'border-t border-border' : undefined}>\n              {columns.map((c, j) => {\n                const v = r[c.key]\n                const text = c.format ? c.format(v, r) : v == null ? '' : String(v)\n                return j === 0 ? (\n                  <th key={c.key} scope=\"row\" className=\"px-3 py-1.5 text-left font-normal text-fg\">\n                    {text}\n                  </th>\n                ) : (\n                  <td key={c.key} className={cn('num px-3 py-1.5 text-fg', c.align === 'left' ? 'text-left' : 'text-right')}>\n                    {text}\n                  </td>\n                )\n              })}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  )\n}\n\n/**\n * Small toolbar for a chart card: show data table, download PNG / SVG / CSV.\n * Pass a ref to the element that wraps the chart.\n */\nexport function ChartActions({\n  target,\n  name,\n  rows,\n  columns,\n  onToggleTable,\n  tableOpen,\n  className,\n  extra,\n}: {\n  target: RefObject<HTMLElement | null>\n  name: string\n  rows?: Record<string, unknown>[]\n  columns?: string[]\n  onToggleTable?: () => void\n  tableOpen?: boolean\n  className?: string\n  extra?: ReactNode\n}) {\n  const [open, setOpen] = useState(false)\n  const [busy, setBusy] = useState(false)\n  const run = async (kind: 'png' | 'svg' | 'csv') => {\n    setOpen(false)\n    if (kind === 'csv') return rows && exportCsv(rows, name, columns)\n    const el = target.current\n    if (!el) return\n    if (kind === 'svg') return exportChartSvg(el, name)\n    setBusy(true)\n    try {\n      await exportChartPng(el, name)\n    } finally {\n      setBusy(false)\n    }\n  }\n  const btn = 'inline-flex h-7 items-center gap-1.5 rounded-lg px-2 text-[12px] font-medium text-fg-3 transition-colors hover:bg-surface-3 hover:text-fg'\n  return (\n    <div className={cn('relative flex items-center gap-0.5', className)}>\n      {extra}\n      {onToggleTable && (\n        <button type=\"button\" aria-pressed={tableOpen} onClick={onToggleTable} className={cn(btn, tableOpen && 'bg-surface-3 text-fg')} title=\"Show data table\">\n          <Table2 size={14} />\n          <span className=\"sr-only\">Show data table</span>\n        </button>\n      )}\n      <button type=\"button\" aria-haspopup=\"menu\" aria-expanded={open} onClick={() => setOpen((o) => !o)} className={btn} title=\"Download\">\n        <Download size={14} className={busy ? 'animate-pulse' : undefined} />\n        <span className=\"sr-only\">Download chart</span>\n      </button>\n      {open && (\n        <div role=\"menu\" className=\"absolute top-8 right-0 z-40 min-w-[150px] rounded-xl border border-border bg-surface p-1 shadow-pop\" onMouseLeave={() => setOpen(false)}>\n          {(['png', 'svg', ...(rows ? (['csv'] as const) : [])] as const).map((k) => (\n            <button key={k} role=\"menuitem\" type=\"button\" onClick={() => run(k)} className=\"flex w-full items-center justify-between rounded-lg px-2.5 py-1.5 text-left text-[12.5px] text-fg-2 hover:bg-surface-3 hover:text-fg\">\n              {k === 'png' ? 'PNG image' : k === 'svg' ? 'SVG vector' : 'CSV data'}\n              <span className=\"font-mono text-[10.5px] text-fg-4\">.{k}</span>\n            </button>\n          ))}\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/a11y.tsx"
    },
    {
      "path": "registry/klar/components/charts/bi/interaction.ts",
      "content": "/**\n * Pointer (mouse, touch, pen) and keyboard plumbing shared by the BI, finance and\n * kit charts whose marks own their hover state.\n *\n *   const nav = useChartNav({ count: data.length, onMove: (p) => setHover(p ? p.i : null), onClear: () => setHover(null) })\n *   <div {...nav.root}>                         // focusable plot; arrows, Home/End, Esc\n *     <rect {...markHover(setHover, i)} />      // hover + tap on one mark\n *     {nav.pos && <rect {...ringRect(x, y, w, h)} />}  // explicit SVG focus ring on the keyed mark\n *\n * Touch: a tap shows the readout and it stays until the next tap elsewhere (a tap on\n * the chart background, or focus leaving the chart); a horizontal drag scrubs across\n * marks; vertical drags still scroll the page (`touch-action: pan-y`).\n */\nimport { useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent } from 'react'\n\nexport interface NavPos {\n  /** Primary index (period, row, bar). */\n  i: number\n  /** Secondary index (series, column); 0 when there is no cross axis. */\n  j: number\n}\n\ntype AnyPointer = PointerEvent<Element>\n\n/**\n * Handlers for one mark: pointer enter and tap set it, a mouse leaving clears it.\n * Touch and pen keep the readout after lifting (pointerleave is ignored for them).\n */\nexport function markHover<T>(set: (v: T | null) => void, value: T, { leave = true }: { leave?: boolean } = {}) {\n  return {\n    onPointerEnter: () => set(value),\n    onPointerDown: () => set(value),\n    onPointerLeave: leave\n      ? (e: AnyPointer) => {\n          if (e.pointerType === 'mouse') set(null)\n        }\n      : undefined,\n  }\n}\n\n/**\n * Keyboard navigation and touch persistence for a chart root.\n * - `axis: 'x'`: ←/→ step `i`, ↑/↓ step `j` (if `cross` > 0).\n * - `axis: 'y'`: ↑/↓ step `i`, ←/→ step `j` (rows × columns grids).\n * Home/End jump to the ends of `i`; Escape clears; blur clears.\n * `start` gives the position the first arrow press continues from (e.g. the hovered mark).\n */\nexport function useChartNav({\n  count,\n  cross = 0,\n  axis = 'x',\n  onMove,\n  onClear,\n  start,\n  crossDown = false,\n}: {\n  count: number\n  cross?: number\n  axis?: 'x' | 'y'\n  /** With `axis: 'x'`, ↓ (not ↑) steps `j` forward, for stacks drawn top to bottom. */\n  crossDown?: boolean\n  onMove: (p: NavPos) => void\n  onClear: () => void\n  start?: NavPos | null\n}) {\n  const [pos, setPos] = useState<NavPos | null>(null)\n  const touch = useRef(false)\n\n  const move = (p: NavPos) => {\n    setPos(p)\n    onMove(p)\n  }\n\n  const root = {\n    tabIndex: 0,\n    style: { touchAction: 'pan-y' } as CSSProperties,\n    onKeyDown: (e: KeyboardEvent<Element>) => {\n      if (count <= 0) return\n      const fwd = axis === 'x' ? 'ArrowRight' : 'ArrowDown'\n      const back = axis === 'x' ? 'ArrowLeft' : 'ArrowUp'\n      const cFwd = axis === 'x' ? (crossDown ? 'ArrowDown' : 'ArrowUp') : 'ArrowRight'\n      const cBack = axis === 'x' ? (crossDown ? 'ArrowUp' : 'ArrowDown') : 'ArrowLeft'\n      const cur = pos ?? (start && start.i < count ? start : null)\n      const j0 = Math.min(cur?.j ?? 0, Math.max(0, cross - 1))\n      let next: NavPos | null | undefined\n      if (e.key === fwd) next = cur ? { i: Math.min(count - 1, cur.i + (pos ? 1 : 0)), j: j0 } : { i: 0, j: 0 }\n      else if (e.key === back) next = cur ? { i: Math.max(0, cur.i - (pos ? 1 : 0)), j: j0 } : { i: count - 1, j: 0 }\n      else if (e.key === 'Home') next = { i: 0, j: j0 }\n      else if (e.key === 'End') next = { i: count - 1, j: j0 }\n      else if (cross > 1 && e.key === cFwd) next = cur ? { i: cur.i, j: Math.min(cross - 1, j0 + 1) } : { i: 0, j: 0 }\n      else if (cross > 1 && e.key === cBack) next = cur ? { i: cur.i, j: Math.max(0, j0 - 1) } : { i: 0, j: 0 }\n      else if (e.key === 'Escape') next = null\n      if (next === undefined) return\n      e.preventDefault()\n      if (next) move(next)\n      else {\n        setPos(null)\n        onClear()\n      }\n    },\n    onBlur: (e: { currentTarget: Element; relatedTarget: EventTarget | null }) => {\n      // Focus moving to a child of the chart (a focusable mark) is not leaving it.\n      if (e.relatedTarget instanceof Node && e.currentTarget.contains(e.relatedTarget)) return\n      setPos(null)\n      onClear()\n    },\n    onPointerDownCapture: (e: AnyPointer) => {\n      setPos(null)\n      touch.current = e.pointerType !== 'mouse'\n      if (!touch.current) return\n      // A tap on the background clears; a tap on a mark re-sets it in its own handler.\n      onClear()\n      // Touch captures the pointer to the first target; release it so a drag scrubs\n      // across marks (their pointerenter fires as the finger moves over them).\n      const t = e.target as Element\n      if (t.hasPointerCapture?.(e.pointerId)) t.releasePointerCapture(e.pointerId)\n    },\n    onPointerMove: (e: AnyPointer) => {\n      if (pos && e.pointerType === 'mouse') setPos(null)\n    },\n  }\n  const safe = pos && pos.i < count ? pos : null\n  return { pos: safe, root, isTouch: touch }\n}\n\n/** Release implicit touch capture so a drag scrubs over sibling marks. */\nexport function releaseTouch(e: AnyPointer) {\n  if (e.pointerType === 'mouse') return\n  const t = e.target as Element\n  if (t.hasPointerCapture?.(e.pointerId)) t.releasePointerCapture(e.pointerId)\n}\n\n/**\n * Explicit SVG focus ring (SVG marks do not draw CSS outlines reliably).\n *   {nav.pos && <rect {...ringRect(x, y, w, h)} />}\n */\nexport function ringRect(x: number, y: number, width: number, height: number, { rx = 4, pad = 2 }: { rx?: number; pad?: number } = {}) {\n  return {\n    x: x - pad,\n    y: y - pad,\n    width: Math.max(0, width + pad * 2),\n    height: Math.max(0, height + pad * 2),\n    rx,\n    fill: 'none',\n    stroke: 'var(--accent)',\n    strokeWidth: 2,\n    pointerEvents: 'none' as const,\n    'data-focus-ring': '',\n  }\n}\n\n/** Focus ring for a circular mark: `<circle {...ringCircle(cx, cy, r)} />`. */\nexport function ringCircle(cx: number, cy: number, r: number) {\n  return { cx, cy, r: r + 3, fill: 'none', stroke: 'var(--accent)', strokeWidth: 2, pointerEvents: 'none' as const, 'data-focus-ring': '' }\n}\n\n/** Root-level focus style for charts not inside `.klar` (which already draws one). */\nexport const FOCUS_ROOT = 'outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent'\n",
      "type": "registry:component",
      "target": "@components/klar/charts/bi/interaction.ts"
    },
    {
      "path": "registry/klar/components/charts/finance/util.ts",
      "content": "/*\n * Shared helpers for the finance chart collection: scales, nice ticks,\n * pointer mapping that survives scaled previews, date labels and colour\n * ramps (CSS color-mix for SVG, resolved RGB for canvas).\n */\nimport type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react'\nimport { formatter } from '@/components/klar/charts/basic/core'\n\nexport const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v))\n\n/** Linear map from a domain to a range. */\nexport function scale(d0: number, d1: number, r0: number, r1: number) {\n  const k = d1 === d0 ? 0 : (r1 - r0) / (d1 - d0)\n  return (v: number) => r0 + (v - d0) * k\n}\n\n/** A \"nice\" step (1, 2, 2.5, 5 × 10^n) close to span / count. */\nexport function niceStep(span: number, count: number) {\n  const raw = span / Math.max(1, count)\n  const exp = Math.pow(10, Math.floor(Math.log10(raw || 1)))\n  const f = raw / exp\n  const n = f < 1.5 ? 1 : f < 2.25 ? 2 : f < 3.5 ? 2.5 : f < 7.5 ? 5 : 10\n  return n * exp\n}\n\n/** Nice ticks covering [lo, hi] (inclusive of ticks inside the range only). */\nexport function ticks(lo: number, hi: number, count = 5) {\n  const step = niceStep(hi - lo, count)\n  const start = Math.ceil(lo / step - 1e-9) * step\n  const out: number[] = []\n  // `+ 0` turns -0 (from Math.ceil of a tiny negative) into 0, so formatters never print \"-0\".\n  for (let v = start; v <= hi + step * 1e-9; v += step) out.push(Math.round(v / step) * step + 0)\n  return out\n}\n\n/** Expand [lo, hi] outwards to the nearest nice step. */\nexport function niceDomain(lo: number, hi: number, count = 5): [number, number] {\n  const step = niceStep(hi - lo, count)\n  return [Math.floor(lo / step) * step, Math.ceil(hi / step) * step]\n}\n\n/** Decimals needed to print a tick step without noise. */\nexport const decimalsFor = (step: number) => Math.max(0, Math.min(6, -Math.floor(Math.log10(step) + 1e-9)))\n\n/**\n * Pointer position in the element's own (unscaled) pixel space, so hover works\n * inside the atlas' scaled previews too.\n */\nexport function pointer(e: { clientX: number; clientY: number }, el: Element, width: number): [number, number] {\n  const r = el.getBoundingClientRect()\n  const s = width ? r.width / width || 1 : 1\n  return [(e.clientX - r.left) / s, (e.clientY - r.top) / s]\n}\n\nexport const mix = (a: string, b: string, pct: number) =>\n  `color-mix(in oklab, ${a} ${Math.round(clamp(pct, 0, 100))}%, ${b})`\n\n/**\n * Diverging colour for t in [-1, 1]: neg ↔ mid ↔ pos. `gamma` < 1 lifts small\n * values so a ±0.3% move is still visibly tinted.\n */\nexport function diverging(\n  t: number,\n  { neg = 'var(--red)', pos = 'var(--green)', mid = 'var(--surface-3)', gamma = 0.8 } = {},\n) {\n  const a = Math.pow(clamp(Math.abs(t), 0, 1), gamma)\n  return mix(t < 0 ? neg : pos, mid, a * 100)\n}\n\n/* ------------------------------------------------------------------ */\n/*  Dates                                                             */\n/* ------------------------------------------------------------------ */\n\nexport const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\nconst DOW = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\n\n/** Parses 'YYYY-MM-DD' as a UTC date (no timezone drift). */\nexport function day(s: string) {\n  const [y, m, d] = s.split('-').map(Number)\n  return new Date(Date.UTC(y, (m || 1) - 1, d || 1))\n}\nexport const iso = (d: Date) => d.toISOString().slice(0, 10)\n\n/** True when output should follow the built-in English labels (today's output). */\nconst english = (locale?: string) => !locale || locale === 'en-US'\n\nconst dtfCache = new Map<string, Intl.DateTimeFormat>()\nconst dtf = (locale: string, o: Intl.DateTimeFormatOptions) => {\n  const key = locale + JSON.stringify(o)\n  let f = dtfCache.get(key)\n  if (!f) dtfCache.set(key, (f = new Intl.DateTimeFormat(locale, { ...o, timeZone: 'UTC' })))\n  return f\n}\n\n/** \"Mar 4, 2026\"; with a non-English `locale`, the locale's own short date (\"4. März 2026\"). */\nexport const fmtDate = (s: string, withYear = true, locale?: string) => {\n  const d = day(s)\n  if (!english(locale)) return dtf(locale!, { month: 'short', day: 'numeric', ...(withYear ? { year: 'numeric' } : {}) }).format(d)\n  return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}${withYear ? `, ${d.getUTCFullYear()}` : ''}`\n}\nexport const fmtDateDow = (s: string, locale?: string) => {\n  const d = day(s)\n  if (!english(locale)) return dtf(locale!, { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' }).format(d)\n  return `${DOW[d.getUTCDay()]} ${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`\n}\n/** Short month name for a 0-based month ('Mar'; 'März' in de-DE). */\nexport const monthLabel = (m: number, locale?: string) =>\n  english(locale) ? MONTHS[m] : dtf(locale!, { month: 'short' }).format(new Date(Date.UTC(2000, m, 1)))\n\n/** Business days (Mon–Fri) from start, `n` of them. */\nexport function businessDays(start: string, n: number) {\n  const out: string[] = []\n  const d = day(start)\n  while (out.length < n) {\n    const w = d.getUTCDay()\n    if (w !== 0 && w !== 6) out.push(iso(d))\n    d.setUTCDate(d.getUTCDate() + 1)\n  }\n  return out\n}\n\n/** Days between two ISO dates. */\nexport const daysBetween = (a: string, b: string) => Math.round((day(b).getTime() - day(a).getTime()) / 864e5)\n\n/* ------------------------------------------------------------------ */\n/*  Numbers                                                           */\n/* ------------------------------------------------------------------ */\n\n/** Fixed decimals with grouping, via `formatter(locale)` (default en-US: \"12,480.50\"). */\nexport const fixed = (v: number, d = 2, locale = 'en-US') => formatter(locale).number(v, d)\n\nexport const signed = (v: number, d = 2, unit = '', locale = 'en-US') =>\n  `${v > 0 ? '+' : v < 0 ? '−' : '±'}${fixed(Math.abs(v), d, locale)}${unit}`\n\nexport const compact = (v: number, d = 1, locale = 'en-US') => {\n  const a = Math.abs(v)\n  const s = a >= 1e12 ? [1e12, 'T'] : a >= 1e9 ? [1e9, 'B'] : a >= 1e6 ? [1e6, 'M'] : a >= 1e3 ? [1e3, 'K'] : [1, '']\n  return `${v < 0 ? '−' : ''}${fixed(a / (s[0] as number), s[1] ? d : 0, locale)}${s[1]}`\n}\n\n/** A tick value as plain text: `String(v)` by default (today's output), localised when `locale` is set. */\nexport const plain = (v: number, locale?: string) =>\n  english(locale) ? String(v) : new Intl.NumberFormat(locale, { maximumFractionDigits: 6 }).format(v)\n\n/* ------------------------------------------------------------------ */\n/*  Pointer and keyboard                                              */\n/* ------------------------------------------------------------------ */\n\n/**\n * Pointer handlers for a plot that reads the position itself (crosshair charts).\n * Mouse and hovering pens track on move and clear on leave; touch shows the readout\n * on tap and keeps it after lifting, a drag scrubs, and `touch-action: pan-y` keeps\n * vertical page scrolling.\n */\nexport function plotPointer(width: number, at: (x: number, y: number) => void, clear: () => void) {\n  const locate = (e: ReactPointerEvent<HTMLElement>) => {\n    const [x, y] = pointer(e, e.currentTarget, width)\n    at(x, y)\n  }\n  return {\n    onPointerDown: locate,\n    onPointerMove: (e: ReactPointerEvent<HTMLElement>) => {\n      if (e.pointerType !== 'touch' || e.buttons > 0) locate(e)\n    },\n    onPointerLeave: (e: ReactPointerEvent<HTMLElement>) => {\n      if (e.pointerType !== 'touch') clear()\n    },\n    onPointerCancel: clear,\n    style: { touchAction: 'pan-y' } as CSSProperties,\n  }\n}\n\n/**\n * Next index for a keyboard step along `n` marks: ←/→ (or ↑/↓ with `vertical`),\n * Shift for `big` steps, Home/End; `null` for Escape; `undefined` for other keys.\n */\nexport function stepKey(e: { key: string; shiftKey: boolean }, cur: number | null, n: number, { big = 5, from = 0, vertical = false } = {}) {\n  const fwd = vertical ? 'ArrowDown' : 'ArrowRight'\n  const back = vertical ? 'ArrowUp' : 'ArrowLeft'\n  const k = e.shiftKey ? big : 1\n  if (e.key === fwd) return cur == null ? clamp(from, 0, n - 1) : Math.min(n - 1, cur + k)\n  if (e.key === back) return cur == null ? clamp(from, 0, n - 1) : Math.max(0, cur - k)\n  if (e.key === 'Home') return 0\n  if (e.key === 'End') return n - 1\n  if (e.key === 'Escape') return null\n  return undefined\n}\n\n/** Standard normal draws from a seeded uniform source (Box–Muller). */\nexport function gauss(rnd: () => number) {\n  const u = Math.max(1e-9, rnd())\n  const v = rnd()\n  return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v)\n}\n\n/* ------------------------------------------------------------------ */\n/*  Canvas colour                                                     */\n/* ------------------------------------------------------------------ */\n\nexport type RGB = [number, number, number]\n\nexport function parseColor(s: string): RGB {\n  const v = s.trim()\n  if (v.startsWith('#')) {\n    const h = v.length === 4 ? v.slice(1).replace(/./g, (c) => c + c) : v.slice(1, 7)\n    return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)]\n  }\n  const m = v.match(/[\\d.]+/g)\n  return m ? [Number(m[0]), Number(m[1]), Number(m[2])] : [128, 128, 128]\n}\n\n/** Resolves a token like '--blue' on an element to RGB. */\nexport const readVar = (el: Element, name: string) => parseColor(getComputedStyle(el).getPropertyValue(name) || '#888')\n\nconst toLin = (c: number) => {\n  const x = c / 255\n  return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4)\n}\nconst toSrgb = (x: number) => 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055)\n\n/** Interpolates a multi-stop ramp in linear light (smooth, no muddy midpoints). */\nexport function rampAt(stops: RGB[], t: number): RGB {\n  const tt = clamp(t, 0, 1) * (stops.length - 1)\n  const i = Math.min(stops.length - 2, Math.floor(tt))\n  const f = tt - i\n  const a = stops[i]\n  const b = stops[i + 1]\n  return [0, 1, 2].map((k) => toSrgb(toLin(a[k]) * (1 - f) + toLin(b[k]) * f)) as RGB\n}\n\nexport const rgb = (c: RGB, a = 1) => `rgba(${Math.round(c[0])}, ${Math.round(c[1])}, ${Math.round(c[2])}, ${a})`\n",
      "type": "registry:component",
      "target": "@components/klar/charts/finance/util.ts"
    },
    {
      "path": "registry/klar/components/charts/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 { MarketTreemap } from '@/components/klar/charts/finance/MarketTreemap'\nData comes in through props.",
  "categories": [
    "charts",
    "finance",
    "hierarchy"
  ],
  "meta": {
    "collection": "finance",
    "kind": "hierarchy",
    "tags": [
      "treemap",
      "market-map",
      "sectors",
      "stocks",
      "market-cap",
      "heatmap"
    ],
    "standalone": true,
    "export": "MarketTreemap",
    "import": "@/components/klar/charts/finance/MarketTreemap"
  }
}
