{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "basic-stacked-area",
  "type": "registry:component",
  "title": "Stacked area",
  "description": "How a total is made up over time, switchable between real amounts and each layer’s share of 100%.",
  "dependencies": [
    "clsx",
    "lucide-react",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "https://klar.run/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/klar/components/charts/basic/StackedArea.tsx",
      "content": "import { useId, useMemo } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\nimport { useMeasure } from '@/components/klar/lib/use-measure'\nimport { ChartDataTable } from '@/components/klar/charts/a11y'\nimport { AxisX, AxisY, ChartLegend, ChartTooltip, PALETTE, formatter } from '@/components/klar/charts/basic/core'\nimport {\n  FOCUS_RING,\n  clamp,\n  crisp,\n  curvePath,\n  dodge,\n  exportLegend,\n  fitTicks,\n  fixedScale,\n  ink,\n  nearestIndex,\n  tableColumns,\n  textW,\n  truncate,\n  useChartHover,\n  useLegend,\n  valueFormat,\n  xModel,\n  xText,\n  yScale,\n  type ChartUnit,\n  type Pt,\n  type XValue,\n} from '@/components/klar/charts/basic/util-a'\n\nexport interface StackedAreaSeries {\n  id: string\n  label: string\n  /** One value per x position. Missing or negative values count as zero. */\n  values: (number | null | undefined)[]\n  color?: string\n}\n\nexport interface StackedAreaProps {\n  /** X positions: dates are spaced in proportion to time, strings and numbers evenly. */\n  x: XValue[]\n  /** Drawn bottom to top in this order. */\n  series: StackedAreaSeries[]\n  /** `absolute` stacks the values; `percent` stretches every moment to 100%. */\n  mode?: 'absolute' | 'percent'\n  curve?: 'smooth' | 'linear'\n  height?: number\n  /** Name and latest value (or share) at the right edge of each layer. */\n  endLabels?: boolean\n  legend?: boolean\n  yLabel?: string\n  totalLabel?: string\n  unit?: ChartUnit\n  locale?: string\n  currency?: string\n  format?: (v: number) => string\n  dateFormat?: Intl.DateTimeFormatOptions\n  emptyLabel?: string\n  className?: string\n  ariaLabel?: string\n}\n\n/** Flat rows for CSV export or a data table: one row per x position, one column per series. */\nexport function stackedAreaToRows(x: XValue[], series: Pick<StackedAreaSeries, 'label' | 'values'>[]): Record<string, unknown>[] {\n  return x.map((v, i) => ({ x: xText(v), ...Object.fromEntries(series.map((s) => [s.label, s.values[i] ?? null])) }))\n}\n\n/**\n * Stacked area chart: how a total is made up over time. `absolute` mode shows\n * the real amounts piling up; `percent` mode shows only the mix. A crosshair\n * reads every layer's value and share, layers are labelled at their right\n * edge, and the legend highlights or hides a layer (the rest restack).\n * Data: `x: (Date | string | number)[]` and `series: { id, label, values: number[] }[]`.\n * Scale: beyond about two points per pixel the layers are drawn from an even\n * sample of the points; readouts still use every point.\n */\nexport function StackedArea({\n  x,\n  series,\n  mode = 'absolute',\n  curve = 'smooth',\n  height = 340,\n  endLabels = true,\n  legend = true,\n  yLabel,\n  totalLabel = 'Total',\n  unit = 'number',\n  locale,\n  currency,\n  format,\n  dateFormat,\n  emptyLabel = 'No data',\n  className,\n  ariaLabel = 'Stacked area chart',\n}: StackedAreaProps) {\n  const uid = useId().replace(/:/g, '')\n  const [ref, { width, height: h }] = useMeasure()\n  const f = formatter(locale, currency)\n  const lg = useLegend(series.map((s) => s.id))\n  const n = x.length\n  const hover = useChartHover(n)\n  const all = useMemo(() => series.map((s, i) => ({ ...s, color: s.color ?? PALETTE[i % PALETTE.length] })), [series])\n  const shown = all.filter((s) => !lg.hidden.has(s.id))\n  const m = shown.length\n  const pctMode = mode === 'percent'\n\n  /* raw[k][i], totals[i], and cumulative tops in data units */\n  const raw = shown.map((s) => Array.from({ length: n }, (_, i) => Math.max(0, s.values[i] ?? 0) || 0))\n  const totals = Array.from({ length: n }, (_, i) => raw.reduce((a, r) => a + r[i], 0))\n  const tops: number[][] = []\n  raw.forEach((r, k) => tops.push(r.map((v, i) => (k ? tops[k - 1][i] : 0) + (pctMode ? (totals[i] ? v / totals[i] : 0) : v))))\n  const vf = valueFormat(f, unit, [...raw.flat(), ...totals], format)\n  const empty = n === 0 || m === 0 || totals.every((t) => t === 0)\n  const share = (k: number, i: number) => (totals[i] ? raw[k][i] / totals[i] : 0)\n  const pct = (p: number) => f.percent(p, p > 0 && p < 0.00995 ? 1 : 0)\n\n  /* ---- geometry ---- */\n  const padT = yLabel ? 24 : 10\n  const padB = 28\n  const bottomPx = Math.max(padT + 20, h - padB)\n  const probe = yScale([0, Math.max(1e-9, ...totals)], padT, bottomPx, { zero: true })\n  const y = pctMode ? fixedScale(0, 1, [probe.range[0], probe.range[0] - Math.floor((probe.range[0] - padT) / 4) * 4], [0, 0.25, 0.5, 0.75, 1]) : probe\n  const tick = pctMode ? (v: number) => f.percent(v) : vf.axis(y.ticks)\n  const bottom = y.range[0]\n  const top = y.range[1]\n  const padL = Math.max(26, ...y.ticks.map((t) => textW(tick(t), 11))) + 12\n  const last = n - 1\n  const withNames = width >= 520\n  const endText = shown.map((s, k) => ({ name: withNames ? truncate(s.label, 104, 11.5, 500) : '', value: empty ? '' : pctMode ? pct(share(k, last)) : vf.short(raw[k][last]) }))\n  const endW = endLabels && !empty ? Math.max(0, ...endText.map((t) => (t.name ? textW(t.name, 11.5, 500) + 7 : 0) + textW(t.value, 11.5, 600))) : 0\n  const padR = endW ? Math.ceil(endW) + 16 : 10\n  const x0 = crisp(padL)\n  const x1 = Math.max(x0 + 10, width - padR)\n  const xm = xModel(x, x0, x1, f, { dateFormat })\n\n  const stride = Math.max(1, Math.floor(n / Math.max(1, (x1 - x0) / 2)))\n  const keep = Array.from({ length: n }, (_, i) => i).filter((i) => i % stride === 0 || i === last)\n  const line = (k: number): Pt[] => keep.map((i) => [xm.pos[i], k < 0 ? bottom : y(tops[k][i])])\n\n  const mids = shown.map((_, k) => (y(tops[k][last] ?? 0) + (k ? y(tops[k - 1][last] ?? 0) : bottom)) / 2)\n  const endY = dodge(mids, 15, top + 4, bottom - 4)\n\n  /* ---- hover ---- */\n  const idx = empty ? null : hover.point ? nearestIndex(xm.pos, hover.point.x) : (hover.key?.i ?? null)\n  const hx = idx != null ? xm.pos[idx] : 0\n  const tipHalf = 34 + m * 11\n  const tableRows = useMemo(() => stackedAreaToRows(x, series).slice(0, 500), [x, series])\n  const summary = empty ? emptyLabel : `${m} layers over ${n} points, ${xm.label(0)} to ${xm.label(last)}. Latest total ${vf.value(totals[last])}.`\n  const legendOn = legend && all.length > 1\n\n  return (\n    <figure aria-label={ariaLabel} className={cn('flex w-full flex-col select-none', className)} style={{ height }}>\n      {legendOn && (\n        <ChartLegend className=\"mb-3\" items={all.map((s) => ({ id: s.id, label: s.label, color: s.color, mark: 'bar' }))} active={lg.active} hidden={lg.hidden} onHover={lg.setActive} onToggle={lg.toggle} />\n      )}\n      <div ref={ref} role=\"img\" aria-label={`${ariaLabel}. ${summary} Use arrow keys to read values.`} className={cn('relative min-h-0 flex-1', FOCUS_RING)} {...hover.bind}>\n        {width > 0 && h > 0 && (\n          <svg width={width} height={h} overflow=\"visible\" className=\"block\">\n            <defs>\n              <clipPath id={`${uid}-wipe`}>\n                <rect x={x0 - 2} y={top - 10} width={x1 - x0 + 8} height={bottom - top + 20} className=\"anim-grow-x\" style={{ transformBox: 'fill-box' }} />\n              </clipPath>\n            </defs>\n            {legendOn && exportLegend(all.map((s) => ({ label: s.label, color: s.color })))}\n            {yLabel && (\n              <text x={0} y={11} className=\"fill-fg-3 text-[11px]\">\n                {yLabel}\n              </text>\n            )}\n            <AxisY scale={y} x0={x0} x1={x1} format={tick} />\n\n            {!empty && n === 1 && (\n              <g className=\"anim-grow-y\" style={{ transformBox: 'fill-box' }}>\n                {shown.map((s, k) => {\n                  const yt = y(tops[k][0])\n                  const yb = k ? y(tops[k - 1][0]) : bottom\n                  return <rect key={s.id} x={xm.pos[0] - 18} y={yt} width={36} height={Math.max(0, yb - yt - (k < m - 1 ? 0 : 0))} fill={`color-mix(in oklab, ${s.color} 62%, var(--surface))`} stroke=\"var(--surface)\" strokeWidth={1.5} opacity={lg.active != null && lg.active !== s.id ? 0.3 : 1} />\n                })}\n              </g>\n            )}\n            {!empty && n > 1 && (\n              <g clipPath={`url(#${uid}-wipe)`}>\n                {shown.map((s, k) => {\n                  const up = line(k)\n                  const down = line(k - 1).reverse()\n                  const dim = lg.active != null && lg.active !== s.id\n                  return (\n                    <g key={s.id} style={{ opacity: dim ? 0.3 : 1, transition: 'opacity 160ms' }}>\n                      <path d={`${curvePath(up, curve)}${curvePath(down, curve, false)}Z`} fill={`color-mix(in oklab, ${s.color} 62%, var(--surface))`} style={{ transition: 'd 380ms cubic-bezier(0.2, 0.8, 0.2, 1)' }} />\n                      <path d={curvePath(up, curve)} fill=\"none\" stroke=\"var(--surface)\" strokeWidth={3} strokeLinejoin=\"round\" style={{ transition: 'd 380ms cubic-bezier(0.2, 0.8, 0.2, 1)' }} />\n                      <path d={curvePath(up, curve)} fill=\"none\" stroke={s.color} strokeWidth={1.75} strokeLinejoin=\"round\" strokeLinecap=\"round\" style={{ transition: 'd 380ms cubic-bezier(0.2, 0.8, 0.2, 1)' }} />\n                    </g>\n                  )\n                })}\n              </g>\n            )}\n\n            {/* gridlines read through the layers, faintly */}\n            {!empty && y.ticks.slice(1).map((t) => <line key={t} x1={x0} x2={x1} y1={y(t)} y2={y(t)} stroke=\"var(--surface)\" strokeOpacity={0.35} strokeDasharray=\"3 4\" />)}\n\n            {endLabels &&\n              !empty &&\n              shown.map((s, k) => {\n                const dim = lg.active != null && lg.active !== s.id\n                const moved = Math.abs(endY[k] - mids[k]) > 2.5\n                return (\n                  <g key={s.id} className=\"anim-fade\" style={{ animationDelay: '520ms', opacity: dim ? 0.25 : 1, transition: 'opacity 160ms' }}>\n                    <path d={`M${x1 + 3},${mids[k]}L${x1 + 9},${endY[k]}`} fill=\"none\" stroke={s.color} strokeOpacity={moved ? 0.7 : 0} />\n                    <text x={x1 + 12} y={endY[k] + 4} className=\"text-[11.5px]\">\n                      {endText[k].name && (\n                        <tspan className=\"font-medium\" fill={ink(s.color)}>\n                          {endText[k].name}{' '}\n                        </tspan>\n                      )}\n                      <tspan className=\"num font-semibold\" fill={endText[k].name ? 'var(--fg)' : ink(s.color, 80)}>\n                        {endText[k].value}\n                      </tspan>\n                    </text>\n                  </g>\n                )\n              })}\n\n            {idx != null && (\n              <g>\n                <line x1={crisp(hx)} x2={crisp(hx)} y1={top} y2={bottom} stroke=\"var(--fg)\" strokeOpacity={0.55} />\n                {shown.map((s, k) => (\n                  <circle key={s.id} cx={hx} cy={y(tops[k][idx])} r={4} fill={s.color} stroke=\"var(--surface)\" strokeWidth={2} opacity={lg.active != null && lg.active !== s.id ? 0.3 : 1} />\n                ))}\n              </g>\n            )}\n\n            <AxisX labels={fitTicks(xm.ticks, 0, width)} y={bottom + 19} />\n            {xm.time && xm.ticks.map((t, k) => <line key={k} x1={crisp(t.x)} x2={crisp(t.x)} y1={bottom} y2={bottom + 4} stroke=\"var(--border-strong)\" />)}\n          </svg>\n        )}\n        {empty && width > 0 && <div className=\"absolute inset-0 grid place-items-center text-[12.5px] text-fg-3\">{emptyLabel}</div>}\n        {idx != null && (\n          <ChartTooltip\n            x={hx}\n            y={clamp(hover.point?.y ?? (top + bottom) / 2, tipHalf, Math.max(tipHalf, h - tipHalf))}\n            containerWidth={width}\n            width={220}\n            title={xm.label(idx)}\n            rows={shown\n              .map((s, k) => ({\n                label: <span className=\"whitespace-nowrap\">{s.label}</span>,\n                color: s.color,\n                strong: lg.active ? lg.active === s.id : true,\n                value: (\n                  <span className=\"whitespace-nowrap\">\n                    {pctMode ? <span className=\"mr-2 font-normal text-fg-3\">{vf.short(raw[k][idx])}</span> : null}\n                    {pctMode ? <span className=\"inline-block min-w-[3.2em] text-right\">{f.percent(share(k, idx), 1)}</span> : vf.value(raw[k][idx])}\n                    {!pctMode ? <span className=\"ml-2 inline-block min-w-[3.2em] text-right font-normal text-fg-3\">{f.percent(share(k, idx), 1)}</span> : null}\n                  </span>\n                ),\n              }))\n              .reverse()}\n            footer={\n              <span className=\"flex justify-between gap-4\">\n                {totalLabel}\n                <span className=\"num font-semibold text-fg\">{vf.value(totals[idx])}</span>\n              </span>\n            }\n          />\n        )}\n      </div>\n      <ChartDataTable caption={ariaLabel} columns={tableColumns(tableRows, vf.value)} rows={tableRows} />\n    </figure>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/basic/StackedArea.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/basic/core.tsx",
      "content": "/**\n * Shared foundation for the basic charts: scales, ticks, locale-aware formatting,\n * pointer (mouse + touch + pen) hover tracking, axes, legend and tooltip.\n * Advanced charts can use it too.\n */\nimport { useCallback, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\n\n/* ------------------------------------------------------------------ */\n/*  Scales and ticks                                                  */\n/* ------------------------------------------------------------------ */\n\nexport interface LinearScale {\n  (v: number): number\n  invert: (px: number) => number\n  domain: [number, number]\n  range: [number, number]\n  ticks: number[]\n}\n\n/** \"Nice\" tick values covering [min, max] with about `count` steps. */\nexport function niceTicks(min: number, max: number, count = 5): number[] {\n  if (!isFinite(min) || !isFinite(max)) return [0]\n  if (min === max) {\n    max = min + (Math.abs(min) || 1)\n  }\n  const span = max - min\n  const raw = span / Math.max(1, count)\n  const mag = Math.pow(10, Math.floor(Math.log10(raw)))\n  const norm = raw / mag\n  const step = (norm >= 7.5 ? 10 : norm >= 3.5 ? 5 : norm >= 1.5 ? 2 : 1) * mag\n  const start = Math.floor(min / step) * step\n  const end = Math.ceil(max / step) * step\n  const out: number[] = []\n  for (let v = start; v <= end + step * 1e-6; v += step) out.push(+v.toPrecision(12))\n  return out\n}\n\n/**\n * Linear scale. With `nice` (default) the domain is widened to round tick values.\n * `zero` forces the domain to include 0 (right for bars, optional for lines).\n */\nexport function linearScale(\n  domain: [number, number],\n  range: [number, number],\n  { nice = true, zero = false, ticks = 5 }: { nice?: boolean; zero?: boolean; ticks?: number } = {},\n): LinearScale {\n  let [d0, d1] = domain\n  if (zero) {\n    d0 = Math.min(0, d0)\n    d1 = Math.max(0, d1)\n  }\n  let t = niceTicks(d0, d1, ticks)\n  if (nice) {\n    d0 = t[0]\n    d1 = t[t.length - 1]\n  } else {\n    t = t.filter((v) => v >= d0 - 1e-9 && v <= d1 + 1e-9)\n  }\n  const [r0, r1] = range\n  const k = d1 === d0 ? 0 : (r1 - r0) / (d1 - d0)\n  const scale = ((v: number) => r0 + (v - d0) * k) as LinearScale\n  scale.invert = (px) => (k === 0 ? d0 : d0 + (px - r0) / k)\n  scale.domain = [d0, d1]\n  scale.range = [r0, r1]\n  scale.ticks = t\n  return scale\n}\n\nexport interface BandScale {\n  (i: number): number\n  bandwidth: number\n  step: number\n  /** Index of the band containing a pixel position (clamped). */\n  indexAt: (px: number) => number\n}\n\n/** Evenly spaced bands for `count` categories; `padding` is the gap fraction per step. */\nexport function bandScale(count: number, range: [number, number], padding = 0.3): BandScale {\n  const [r0, r1] = range\n  const step = count > 0 ? (r1 - r0) / count : 0\n  const bandwidth = step * (1 - padding)\n  const scale = ((i: number) => r0 + step * i + (step - bandwidth) / 2) as BandScale\n  scale.bandwidth = bandwidth\n  scale.step = step\n  scale.indexAt = (px) => Math.max(0, Math.min(count - 1, Math.floor((px - r0) / (step || 1))))\n  return scale\n}\n\nexport const extent = (values: number[]): [number, number] => {\n  let lo = Infinity\n  let hi = -Infinity\n  for (const v of values) {\n    if (v == null || !isFinite(v)) continue\n    if (v < lo) lo = v\n    if (v > hi) hi = v\n  }\n  return lo === Infinity ? [0, 1] : [lo, hi]\n}\n\n/* ------------------------------------------------------------------ */\n/*  Locale-aware formatting                                           */\n/* ------------------------------------------------------------------ */\n\nexport interface Formatter {\n  /** 12,480 */\n  number: (v: number, digits?: number) => string\n  /** 12.5K, 3.2M */\n  compact: (v: number) => string\n  /** 34.5% from 0.345 */\n  percent: (v: number, digits?: number) => string\n  currency: (v: number, digits?: number) => string\n  /** $1.2M */\n  currencyCompact: (v: number) => string\n  /** Signed: +4.2 / −4.2 */\n  delta: (v: number, digits?: number) => string\n  date: (d: Date | string | number, opts?: Intl.DateTimeFormatOptions) => string\n}\n\nconst cache = new Map<string, Formatter>()\n\n/**\n * Formatter bound to a locale and currency. Pass `locale` to any basic chart to\n * localise every label, e.g. `formatter('de-DE', 'EUR').currency(1234.5)` → \"1.234,50 €\".\n */\nexport function formatter(locale = 'en-US', currency = 'USD'): Formatter {\n  const key = `${locale}|${currency}`\n  const hit = cache.get(key)\n  if (hit) return hit\n  const nf = (o: Intl.NumberFormatOptions) => new Intl.NumberFormat(locale, o)\n  const compact = nf({ notation: 'compact', maximumFractionDigits: 1 })\n  const curCompact = nf({ style: 'currency', currency, notation: 'compact', maximumFractionDigits: 1 })\n  const f: Formatter = {\n    number: (v, digits = 0) => nf({ minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    compact: (v) => compact.format(v),\n    percent: (v, digits = 0) => nf({ style: 'percent', minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    currency: (v, digits = 0) => nf({ style: 'currency', currency, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    currencyCompact: (v) => curCompact.format(v),\n    delta: (v, digits = 1) => (v > 0 ? '+' : v < 0 ? '−' : '') + nf({ minimumFractionDigits: digits, maximumFractionDigits: digits }).format(Math.abs(v)),\n    date: (d, opts = { month: 'short', day: 'numeric' }) => new Intl.DateTimeFormat(locale, opts).format(new Date(d)),\n  }\n  cache.set(key, f)\n  return f\n}\n\n/* ------------------------------------------------------------------ */\n/*  Pointer hover (mouse, touch and pen)                              */\n/* ------------------------------------------------------------------ */\n\nexport interface HoverPoint {\n  /** Position inside the element, in its own (unscaled) pixels. */\n  x: number\n  y: number\n}\n\n/**\n * Tracks the pointer over a chart for mouse, touch and pen alike.\n * Spread `bind` on the plot container. On touch, a tap or drag shows the readout\n * and it stays until the next tap elsewhere; on mouse it clears on leave.\n */\nexport function usePointerHover<T extends HTMLElement | SVGElement = HTMLDivElement>() {\n  const [point, setPoint] = useState<HoverPoint | null>(null)\n  const touch = useRef(false)\n\n  const locate = useCallback((e: PointerEvent<T>) => {\n    const el = e.currentTarget as unknown as HTMLElement\n    const r = el.getBoundingClientRect()\n    // Compensate for ancestor CSS transforms (scaled previews).\n    const sx = el.offsetWidth ? r.width / el.offsetWidth : 1\n    const sy = el.offsetHeight ? r.height / el.offsetHeight : 1\n    setPoint({ x: (e.clientX - r.left) / (sx || 1), y: (e.clientY - r.top) / (sy || 1) })\n  }, [])\n\n  const bind = {\n    onPointerDown: (e: PointerEvent<T>) => {\n      touch.current = e.pointerType !== 'mouse'\n      locate(e)\n    },\n    onPointerMove: (e: PointerEvent<T>) => {\n      if (e.pointerType === 'mouse' || e.buttons > 0 || e.pressure > 0) locate(e)\n    },\n    onPointerLeave: (e: PointerEvent<T>) => {\n      if (e.pointerType === 'mouse') setPoint(null)\n    },\n    onPointerCancel: () => setPoint(null),\n    style: { touchAction: 'pan-y' } as CSSProperties,\n  }\n  return { point, bind, clear: () => setPoint(null), isTouch: touch }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Axes (SVG)                                                        */\n/* ------------------------------------------------------------------ */\n\n/** Horizontal gridlines with value labels on the left. */\nexport function AxisY({\n  scale,\n  x0,\n  x1,\n  format = String,\n  grid = true,\n  side = 'left',\n  label,\n}: {\n  scale: LinearScale\n  /** Left and right pixel edges of the plot. */\n  x0: number\n  x1: number\n  format?: (v: number) => string\n  grid?: boolean\n  side?: 'left' | 'right'\n  label?: string\n}) {\n  return (\n    <g aria-hidden>\n      {scale.ticks.map((t) => {\n        const y = scale(t)\n        const zero = t === 0\n        return (\n          <g key={t}>\n            {grid && (\n              <line\n                x1={x0}\n                x2={x1}\n                y1={y}\n                y2={y}\n                stroke={zero ? 'var(--border-strong)' : 'var(--border)'}\n                strokeDasharray={zero || t === scale.ticks[0] ? undefined : '3 4'}\n              />\n            )}\n            <text\n              x={side === 'left' ? x0 - 10 : x1 + 10}\n              y={y + 4}\n              textAnchor={side === 'left' ? 'end' : 'start'}\n              className=\"num fill-fg-3 text-[11px]\"\n            >\n              {format(t)}\n            </text>\n          </g>\n        )\n      })}\n      {label && (\n        <text x={side === 'left' ? x0 - 10 : x1 + 10} y={scale.range[1] - 12} textAnchor={side === 'left' ? 'end' : 'start'} className=\"fill-fg-4 text-[10.5px]\">\n          {label}\n        </text>\n      )}\n    </g>\n  )\n}\n\n/** Category or tick labels under the plot. Skips labels that would collide. */\nexport function AxisX({\n  labels,\n  y,\n  minGap = 8,\n  charWidth = 6.2,\n}: {\n  labels: { x: number; text: string; anchor?: 'start' | 'middle' | 'end' }[]\n  y: number\n  minGap?: number\n  charWidth?: number\n}) {\n  let lastEnd = -Infinity\n  return (\n    <g aria-hidden>\n      {labels.map((l, i) => {\n        const w = l.text.length * charWidth\n        const start = l.anchor === 'start' ? l.x : l.anchor === 'end' ? l.x - w : l.x - w / 2\n        if (start < lastEnd + minGap) return null\n        lastEnd = start + w\n        return (\n          <text key={i} x={l.x} y={y} textAnchor={l.anchor ?? 'middle'} className=\"fill-fg-3 text-[11px]\">\n            {l.text}\n          </text>\n        )\n      })}\n    </g>\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Legend and tooltip (HTML)                                         */\n/* ------------------------------------------------------------------ */\n\nexport interface LegendItem {\n  id: string\n  label: ReactNode\n  color: string\n  value?: ReactNode\n  /** line | bar | dot | dash */\n  mark?: 'line' | 'bar' | 'dot' | 'dash'\n}\n\n/** Legend whose items can be hovered (to highlight) and clicked (to toggle). */\nexport function ChartLegend({\n  items,\n  active,\n  hidden,\n  onHover,\n  onToggle,\n  className,\n}: {\n  items: LegendItem[]\n  active?: string | null\n  hidden?: Set<string>\n  onHover?: (id: string | null) => void\n  onToggle?: (id: string) => void\n  className?: string\n}) {\n  return (\n    <div className={cn('flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[12px] text-fg-2', className)}>\n      {items.map((it) => {\n        const off = hidden?.has(it.id)\n        const dim = active != null && active !== it.id\n        return (\n          <button\n            key={it.id}\n            type=\"button\"\n            aria-pressed={onToggle ? !off : undefined}\n            onPointerEnter={() => onHover?.(it.id)}\n            onPointerLeave={() => onHover?.(null)}\n            onFocus={() => onHover?.(it.id)}\n            onBlur={() => onHover?.(null)}\n            onClick={() => onToggle?.(it.id)}\n            className={cn('inline-flex items-center gap-1.5 rounded-md transition-opacity', (dim || off) && 'opacity-40', !onToggle && 'cursor-default')}\n          >\n            <span\n              className={cn(\n                'shrink-0',\n                it.mark === 'line' ? 'h-[2.5px] w-3.5 rounded-full' : it.mark === 'dash' ? 'h-0 w-3.5 border-t-2 border-dashed' : it.mark === 'bar' ? 'size-2.5 rounded-[3px]' : 'size-2 rounded-full',\n              )}\n              style={it.mark === 'dash' ? { borderColor: it.color } : { background: it.color }}\n            />\n            <span className={off ? 'line-through' : undefined}>{it.label}</span>\n            {it.value != null && <span className=\"num text-fg-3\">{it.value}</span>}\n          </button>\n        )\n      })}\n    </div>\n  )\n}\n\n/**\n * Tooltip card positioned inside a `relative` chart container. It flips to stay\n * inside `containerWidth` and never captures the pointer.\n */\nexport function ChartTooltip({\n  x,\n  y,\n  containerWidth,\n  title,\n  rows,\n  footer,\n  width = 170,\n}: {\n  x: number\n  y: number\n  containerWidth: number\n  title?: ReactNode\n  rows: { label: ReactNode; value: ReactNode; color?: string; strong?: boolean }[]\n  footer?: ReactNode\n  width?: number\n}) {\n  const flip = x > containerWidth - width - 24\n  return (\n    <div\n      role=\"status\"\n      className=\"pointer-events-none absolute z-30 rounded-xl border border-border bg-surface px-3 py-2.5 shadow-pop\"\n      style={{ left: x, top: Math.max(0, y), minWidth: width - 20, transform: `translate(${flip ? 'calc(-100% - 12px)' : '12px'}, -50%)` }}\n    >\n      {title != null && <div className=\"mb-1.5 text-[11.5px] font-medium text-fg-3\">{title}</div>}\n      <div className=\"flex flex-col gap-1\">\n        {rows.map((r, i) => (\n          <div key={i} className=\"flex items-center justify-between gap-5 text-[12.5px]\">\n            <span className=\"flex items-center gap-1.5 text-fg-2\">\n              {r.color && <span className=\"size-2 rounded-full\" style={{ background: r.color }} />}\n              {r.label}\n            </span>\n            <span className={cn('num text-fg', r.strong === false ? 'font-medium' : 'font-semibold')}>{r.value}</span>\n          </div>\n        ))}\n      </div>\n      {footer != null && <div className=\"mt-2 border-t border-border pt-1.5 text-[11.5px] text-fg-3\">{footer}</div>}\n    </div>\n  )\n}\n\n/** Default categorical palette, in order. */\nexport const PALETTE = ['var(--blue)', 'var(--orange)', 'var(--teal)', 'var(--violet)', 'var(--pink)', 'var(--amber)', 'var(--green)', 'var(--sky)']\n",
      "type": "registry:component",
      "target": "@components/klar/charts/basic/core.tsx"
    },
    {
      "path": "registry/klar/components/charts/basic/util-a.ts",
      "content": "/**\n * Helpers shared by the basic charts in set A: text metrics, label dodging,\n * path builders, pixel-snapped scales, value formats, time ticks and a hover\n * hook that joins pointer (mouse, touch, pen) and keyboard navigation.\n */\nimport { createElement, useMemo, useState, type KeyboardEvent, type PointerEvent, type ReactElement } from 'react'\nimport { linearScale, niceTicks, usePointerHover, type Formatter, type LinearScale } 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/* ------------------------------------------------------------------ */\n/*  Text metrics (Inter, tabular figures)                             */\n/* ------------------------------------------------------------------ */\n\nconst NARROW = new Set(\"iljI.,:;'|!\".split(''))\nconst SEMI = new Set('tfr()[]/\\\\-·° '.split(''))\nconst WIDE = new Set('mwMW%…→@'.split(''))\n\n/** Estimated rendered width of a string. Deterministic, so layouts never jitter on font load. */\nexport function textW(s: string, px = 11, weight = 400): number {\n  let em = 0\n  for (const ch of s) {\n    if (ch >= '0' && ch <= '9') em += 0.63\n    else if (NARROW.has(ch)) em += 0.27\n    else if (SEMI.has(ch)) em += 0.37\n    else if (WIDE.has(ch)) em += 0.88\n    else if (ch >= 'A' && ch <= 'Z') em += 0.68\n    else if (ch >= 'a' && ch <= 'z') em += 0.57\n    else em += 0.64\n  }\n  return em * px * (weight >= 600 ? 1.045 : weight >= 500 ? 1.02 : 1)\n}\n\n/** Cuts a string with an ellipsis so it fits `max` pixels. */\nexport function truncate(s: string, max: number, px = 11, weight = 400): string {\n  if (textW(s, px, weight) <= max) return s\n  let t = s\n  while (t.length > 1 && textW(t.trimEnd() + '…', px, weight) > max) t = t.slice(0, -1)\n  return t.trimEnd() + '…'\n}\n\n/** Wraps a label on spaces into at most `lines` lines of `max` pixels; the last line is cut with an ellipsis. */\nexport function wrapLabel(s: string, max: number, px = 11, lines = 2, weight = 400): string[] {\n  if (textW(s, px, weight) <= max || lines <= 1) return [truncate(s, max, px, weight)]\n  const words = s.split(/\\s+/)\n  const out: string[] = []\n  let cur = ''\n  let i = 0\n  for (; i < words.length; i++) {\n    const next = cur ? `${cur} ${words[i]}` : words[i]\n    if (textW(next, px, weight) <= max || !cur) cur = next\n    else {\n      out.push(cur)\n      cur = words[i]\n      if (out.length === lines - 1) break\n    }\n  }\n  const rest = out.length === lines - 1 ? [cur, ...words.slice(i + 1)].join(' ') : cur\n  out.push(truncate(rest, max, px, weight))\n  return out.map((l) => truncate(l, max, px, weight))\n}\n\n/* ------------------------------------------------------------------ */\n/*  Collision avoidance                                               */\n/* ------------------------------------------------------------------ */\n\n/**\n * 1-D label dodging. Takes the positions labels want and returns positions at\n * least `gap` apart inside [lo, hi], moving each cluster as little as possible.\n */\nexport function dodge(want: number[], gap: number, lo: number, hi: number): number[] {\n  const order = want.map((_, i) => i).sort((a, b) => want[a] - want[b])\n  const blocks: { n: number; adj: number; pos: number }[] = []\n  const place = (b: { n: number; adj: number; pos: number }) => {\n    b.pos = clamp(b.adj / b.n, lo, Math.max(lo, hi - (b.n - 1) * gap))\n  }\n  for (const i of order) {\n    const b = { n: 1, adj: want[i], pos: 0 }\n    place(b)\n    blocks.push(b)\n    while (blocks.length > 1) {\n      const cur = blocks[blocks.length - 1]\n      const prev = blocks[blocks.length - 2]\n      if (prev.pos + prev.n * gap <= cur.pos + 1e-9) break\n      prev.adj += cur.adj - cur.n * prev.n * gap\n      prev.n += cur.n\n      place(prev)\n      blocks.pop()\n    }\n  }\n  const out = new Array<number>(want.length)\n  let k = 0\n  for (const b of blocks) for (let j = 0; j < b.n; j++) out[order[k++]] = b.pos + j * gap\n  return out\n}\n\nexport interface Box {\n  x: number\n  y: number\n  w: number\n  h: number\n}\n\nexport const boxesHit = (a: Box, b: Box, pad = 0) =>\n  a.x < b.x + b.w + pad && a.x + a.w + pad > b.x && a.y < b.y + b.h + pad && a.y + a.h + pad > b.y\n\n/** True when a box overlaps a circle. */\nexport const boxHitsCircle = (b: Box, cx: number, cy: number, r: number) => {\n  const nx = clamp(cx, b.x, b.x + b.w)\n  const ny = clamp(cy, b.y, b.y + b.h)\n  return (nx - cx) ** 2 + (ny - cy) ** 2 < r * r\n}\n\n/* ------------------------------------------------------------------ */\n/*  Paths                                                             */\n/* ------------------------------------------------------------------ */\n\nexport type Pt = [number, number]\n\nconst n1 = (v: number) => +v.toFixed(2)\n\nexport const linePathD = (pts: Pt[]) => pts.map((p, i) => `${i ? 'L' : 'M'}${n1(p[0])},${n1(p[1])}`).join('')\n\n/** Monotone cubic (Fritsch–Carlson): smooth, never overshoots the data. */\nexport function monotonePath(pts: Pt[], move = true): string {\n  const n = pts.length\n  if (n === 0) return ''\n  if (n < 3) return (move ? 'M' : 'L') + pts.map((p) => `${n1(p[0])},${n1(p[1])}`).join('L')\n  const dx: number[] = []\n  const m: number[] = []\n  for (let i = 0; i < n - 1; i++) {\n    dx.push(pts[i + 1][0] - pts[i][0])\n    m.push((pts[i + 1][1] - pts[i][1]) / (dx[i] || 1e-9))\n  }\n  const t: number[] = [m[0]]\n  for (let i = 1; i < n - 1; i++) {\n    if (m[i - 1] * m[i] <= 0) t.push(0)\n    else {\n      const w1 = 2 * dx[i] + dx[i - 1]\n      const w2 = dx[i] + 2 * dx[i - 1]\n      t.push((w1 + w2) / (w1 / m[i - 1] + w2 / m[i]))\n    }\n  }\n  t.push(m[n - 2])\n  let d = `${move ? 'M' : 'L'}${n1(pts[0][0])},${n1(pts[0][1])}`\n  for (let i = 0; i < n - 1; i++) {\n    const c = dx[i] / 3\n    d += `C${n1(pts[i][0] + c)},${n1(pts[i][1] + t[i] * c)} ${n1(pts[i + 1][0] - c)},${n1(pts[i + 1][1] - t[i + 1] * c)} ${n1(pts[i + 1][0])},${n1(pts[i + 1][1])}`\n  }\n  return d\n}\n\n/** Step path: `after` holds each value until the next x, `before` jumps first. */\nexport function stepPathD(pts: Pt[], mode: 'after' | 'before' = 'after', move = true): string {\n  if (!pts.length) return ''\n  let d = `${move ? 'M' : 'L'}${n1(pts[0][0])},${n1(pts[0][1])}`\n  for (let i = 1; i < pts.length; i++) {\n    d += mode === 'after' ? `H${n1(pts[i][0])}V${n1(pts[i][1])}` : `V${n1(pts[i][1])}H${n1(pts[i][0])}`\n  }\n  return d\n}\n\nexport const curvePath = (pts: Pt[], curve: 'linear' | 'smooth' | 'step', move = true) =>\n  curve === 'smooth' ? monotonePath(pts, move) : curve === 'step' ? stepPathD(pts, 'after', move) : (move ? '' : 'L') + linePathD(pts).slice(move ? 0 : 1)\n\n/** Splits a series with holes into runs of consecutive defined points. */\nexport function runsOf<T>(values: (T | null | undefined)[], ok: (v: T) => boolean = () => true): { i: number; v: T }[][] {\n  const out: { i: number; v: T }[][] = []\n  let cur: { i: number; v: T }[] = []\n  values.forEach((v, i) => {\n    if (v == null || (typeof v === 'number' && !isFinite(v)) || !ok(v)) {\n      if (cur.length) out.push(cur)\n      cur = []\n    } else cur.push({ i, v })\n  })\n  if (cur.length) out.push(cur)\n  return out\n}\n\n/**\n * Rectangle with rounding on one end only, for bars that sit on a baseline.\n * `end` is the side that points away from the baseline.\n */\nexport function barPath(x: number, y: number, w: number, h: number, r: number, end: 'top' | 'bottom' | 'left' | 'right' | 'all' | 'none'): string {\n  w = Math.max(0, w)\n  h = Math.max(0, h)\n  const k = Math.max(0, Math.min(r, w / 2, h / 2, end === 'top' || end === 'bottom' ? h : w))\n  const [tl, tr, br, bl] =\n    end === 'all' ? [k, k, k, k] : end === 'top' ? [k, k, 0, 0] : end === 'bottom' ? [0, 0, k, k] : end === 'left' ? [k, 0, 0, k] : end === 'right' ? [0, k, k, 0] : [0, 0, 0, 0]\n  const X = n1(x)\n  const Y = n1(y)\n  const R = n1(x + w)\n  const B = n1(y + h)\n  return `M${n1(x + tl)},${Y}H${n1(x + w - tr)}Q${R},${Y} ${R},${n1(y + tr)}V${n1(y + h - br)}Q${R},${B} ${n1(x + w - br)},${B}H${n1(x + bl)}Q${X},${B} ${X},${n1(y + h - bl)}V${n1(y + tl)}Q${X},${Y} ${n1(x + tl)},${Y}Z`\n}\n\nexport const polarPt = (cx: number, cy: number, r: number, a: number): Pt => [cx + r * Math.sin(a), cy - r * Math.cos(a)]\n\n/** Pie or ring sector between two angles (radians, clockwise from 12 o'clock). */\nexport function sectorD(cx: number, cy: number, r0: number, r1: number, a0: number, a1: number): string {\n  const sweep = Math.min(a1 - a0, Math.PI * 2 - 1e-4)\n  const end = a0 + sweep\n  const large = sweep > Math.PI ? 1 : 0\n  const [x0, y0] = polarPt(cx, cy, r1, a0)\n  const [x1, y1] = polarPt(cx, cy, r1, end)\n  if (r0 <= 0.01) return `M${n1(cx)},${n1(cy)}L${n1(x0)},${n1(y0)}A${r1},${r1} 0 ${large} 1 ${n1(x1)},${n1(y1)}Z`\n  const [x2, y2] = polarPt(cx, cy, r0, end)\n  const [x3, y3] = polarPt(cx, cy, r0, a0)\n  return `M${n1(x0)},${n1(y0)}A${r1},${r1} 0 ${large} 1 ${n1(x1)},${n1(y1)}L${n1(x2)},${n1(y2)}A${r0},${r0} 0 ${large} 0 ${n1(x3)},${n1(y3)}Z`\n}\n\n/* ------------------------------------------------------------------ */\n/*  Scales that land on the pixel grid                                */\n/* ------------------------------------------------------------------ */\n\ntype ScaleOpts = { nice?: boolean; zero?: boolean; ticks?: number }\n\n/** Half-pixel position, so 1px strokes render crisp. */\nexport const crisp = (v: number) => Math.round(v - 0.5) + 0.5\n\n/**\n * Vertical value scale whose gridlines all fall on half pixels: the baseline is\n * snapped and the plot height trimmed to a multiple of the tick interval count.\n */\nexport function yScale(domain: [number, number], top: number, bottom: number, opts: ScaleOpts = {}): LinearScale {\n  const b = crisp(bottom)\n  const probe = linearScale(domain, [b, top], opts)\n  const n = Math.max(1, probe.ticks.length - 1)\n  const h = Math.max(n, Math.floor((b - top) / n) * n)\n  return linearScale(domain, [b, b - h], opts)\n}\n\n/** Horizontal value scale with gridlines on half pixels. */\nexport function xScale(domain: [number, number], left: number, right: number, opts: ScaleOpts = {}): LinearScale {\n  const l = crisp(left)\n  const probe = linearScale(domain, [l, right], opts)\n  const n = Math.max(1, probe.ticks.length - 1)\n  const w = Math.max(n, Math.floor((right - l) / n) * n)\n  return linearScale(domain, [l, l + w], opts)\n}\n\n/** A linear scale over an explicit domain and tick list. */\nexport function fixedScale(d0: number, d1: number, range: [number, number], ticks: number[]): LinearScale {\n  const [r0, r1] = range\n  const k = d1 === d0 ? 0 : (r1 - r0) / (d1 - d0)\n  const s = ((v: number) => r0 + (v - d0) * k) as LinearScale\n  s.invert = (px) => (k === 0 ? d0 : d0 + (px - r0) / k)\n  s.domain = [d0, d1]\n  s.range = range\n  s.ticks = ticks\n  return s\n}\n\n/**\n * Round tick values covering [min, max] in exactly `intervals` steps, so a\n * second axis can share the first axis's gridlines.\n */\nexport function alignedTicks(min: number, max: number, intervals: number): number[] {\n  if (min === max) max = min + (Math.abs(min) || 1)\n  const raw = (max - min) / intervals\n  let mag = Math.pow(10, Math.floor(Math.log10(raw)) - 1)\n  for (let guard = 0; guard < 4; guard++, mag *= 10) {\n    for (const m of [1, 2, 2.5, 5, 10]) {\n      const step = m * mag\n      const start = Math.floor(min / step + 1e-9) * step\n      if (start + step * intervals >= max - step * 1e-9) {\n        return Array.from({ length: intervals + 1 }, (_, i) => +(start + i * step).toPrecision(12))\n      }\n    }\n  }\n  return niceTicks(min, max, intervals)\n}\n\n/* ------------------------------------------------------------------ */\n/*  Value formats                                                     */\n/* ------------------------------------------------------------------ */\n\n/** How a chart's values read: plain numbers, money, or fractions shown as percentages (0.34 → 34%). */\nexport type ChartUnit = 'number' | 'currency' | 'percent'\n\nexport interface ValueFormat {\n  /** Full precision, for readouts. */\n  value: (v: number) => string\n  /** Compact, for labels drawn on the chart. */\n  short: (v: number) => string\n  /** For axis ticks: digits follow the tick step. */\n  axis: (ticks: number[]) => (v: number) => string\n}\n\nconst stepDigits = (ticks: number[], mult = 1) => {\n  const step = ticks.length > 1 ? Math.abs(ticks[1] - ticks[0]) * mult : 1\n  return step >= 1 || step <= 0 ? 0 : Math.min(3, Math.ceil(-Math.log10(step) - 1e-9))\n}\n\n/** Formats for a chart's values. A `format` override wins everywhere. */\nexport function valueFormat(f: Formatter, unit: ChartUnit, sample: number[], override?: (v: number) => string): ValueFormat {\n  if (override) return { value: override, short: override, axis: () => override }\n  const vals = sample.filter((v) => v != null && isFinite(v))\n  const maxAbs = vals.reduce((a, v) => Math.max(a, Math.abs(v)), 0)\n  const whole = vals.every((v) => Math.abs(v - Math.round(v)) < 1e-9)\n  if (unit === 'percent') {\n    const wholePct = vals.every((v) => Math.abs(v * 100 - Math.round(v * 100)) < 1e-6)\n    return {\n      value: (v) => f.percent(v, wholePct ? 0 : 1),\n      short: (v) => f.percent(v, wholePct || maxAbs >= 1 ? 0 : 1),\n      axis: (t) => (v) => f.percent(v, stepDigits(t, 100)),\n    }\n  }\n  if (unit === 'currency') {\n    const d = whole || maxAbs >= 1000 ? 0 : 2\n    return {\n      value: (v) => f.currency(v, d),\n      short: (v) => (Math.abs(v) >= 1e4 ? f.currencyCompact(v) : f.currency(v, d)),\n      axis: (t) => {\n        const big = Math.max(...t.map(Math.abs)) >= 1e4\n        const dd = stepDigits(t)\n        return (v) => (big ? f.currencyCompact(v) : f.currency(v, dd))\n      },\n    }\n  }\n  /* as many decimals as the data uses, up to two (one for values in the hundreds, none beyond) */\n  const tenths = vals.every((v) => Math.abs(v * 10 - Math.round(v * 10)) < 1e-6)\n  const d = whole || maxAbs >= 1000 ? 0 : tenths || maxAbs >= 100 ? 1 : 2\n  return {\n    value: (v) => f.number(v, d),\n    short: (v) => (Math.abs(v) >= 1e4 ? f.compact(v) : f.number(v, d)),\n    axis: (t) => {\n      const big = Math.max(...t.map(Math.abs)) >= 1e4\n      const dd = stepDigits(t)\n      return (v) => (big ? f.compact(v) : f.number(v, dd))\n    },\n  }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Colour                                                            */\n/* ------------------------------------------------------------------ */\n\n/** A series colour darkened (light theme) or lightened (dark theme) towards the text colour, for coloured labels. */\nexport const ink = (color: string, pct = 74) => `color-mix(in oklab, ${color} ${pct}%, var(--fg))`\n\nexport const tint = (color: string, pct: number) => `color-mix(in oklab, ${color} ${pct}%, transparent)`\n\n/** A muted, theme-aware version of a colour that still reads as that colour. */\nexport const soften = (color: string, pct = 55) => `color-mix(in oklab, ${color} ${pct}%, var(--surface))`\n\n/** Text colour for a label sitting on a solid series fill. */\nexport const onFill = (color: string) =>\n  /amber|lime/.test(color) ? `color-mix(in oklab, ${color} 30%, #1b1405)` : 'var(--accent-fg)'\n\n/** Neutral bar fill for de-emphasised marks. */\nexport const NEUTRAL = 'color-mix(in oklab, var(--fg) 15%, var(--surface))'\n\n/** Focus ring for the keyboard-navigable plot area. */\nexport const FOCUS_RING = 'rounded-md focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-accent/60'\n\n/* ------------------------------------------------------------------ */\n/*  Time and category positions on the x axis                         */\n/* ------------------------------------------------------------------ */\n\nexport type XValue = string | number | Date\n\nconst HOUR = 3600e3\nconst DAY = 24 * HOUR\nconst STEPS: ['h' | 'd' | 'w' | 'm' | 'y', number, number][] = [\n  ['h', 1, HOUR],\n  ['h', 3, 3 * HOUR],\n  ['h', 6, 6 * HOUR],\n  ['h', 12, 12 * HOUR],\n  ['d', 1, DAY],\n  ['d', 2, 2 * DAY],\n  ['w', 1, 7 * DAY],\n  ['w', 2, 14 * DAY],\n  ['m', 1, 30.4 * DAY],\n  ['m', 2, 61 * DAY],\n  ['m', 3, 91 * DAY],\n  ['m', 6, 183 * DAY],\n  ['y', 1, 365 * DAY],\n  ['y', 2, 730 * DAY],\n  ['y', 5, 1826 * DAY],\n  ['y', 10, 3652 * DAY],\n  ['y', 25, 9131 * DAY],\n]\n\n/** Calendar-aligned ticks (local time) between two timestamps, at most about `max` of them. */\nexport function timeTicks(t0: number, t1: number, max: number, f: Formatter): { t: number; text: string }[] {\n  const span = Math.max(1, t1 - t0)\n  const [unit, n] = STEPS.find((s) => span / s[2] <= Math.max(2, max)) ?? STEPS[STEPS.length - 1]\n  const d = new Date(t0)\n  if (unit === 'h') {\n    d.setMinutes(0, 0, 0)\n    d.setHours(Math.floor(d.getHours() / n) * n)\n  } else {\n    d.setHours(0, 0, 0, 0)\n    if (unit === 'w') d.setDate(d.getDate() - ((d.getDay() + 6) % 7))\n    if (unit === 'm') d.setMonth(Math.floor(d.getMonth() / n) * n, 1)\n    if (unit === 'y') d.setFullYear(Math.floor(d.getFullYear() / n) * n, 0, 1)\n  }\n  const out: { t: number; text: string }[] = []\n  for (let guard = 0; guard < 400 && d.getTime() <= t1; guard++) {\n    const t = d.getTime()\n    if (t >= t0) {\n      const text =\n        unit === 'h'\n          ? d.getHours() === 0\n            ? f.date(d, { month: 'short', day: 'numeric' })\n            : f.date(d, { hour: 'numeric' })\n          : unit === 'y' || (unit === 'm' && d.getMonth() === 0)\n            ? f.date(d, { year: 'numeric' })\n            : unit === 'm'\n              ? f.date(d, { month: 'short' })\n              : f.date(d, { month: 'short', day: 'numeric' })\n      out.push({ t, text })\n    }\n    if (unit === 'h') d.setHours(d.getHours() + n)\n    else if (unit === 'd') d.setDate(d.getDate() + n)\n    else if (unit === 'w') d.setDate(d.getDate() + 7 * n)\n    else if (unit === 'm') d.setMonth(d.getMonth() + n)\n    else d.setFullYear(d.getFullYear() + n)\n  }\n  return out\n}\n\nexport interface XModel {\n  /** Pixel position of each data point. */\n  pos: number[]\n  ticks: { x: number; text: string }[]\n  /** Readout label for a point. */\n  label: (i: number) => string\n  /** True when x values are dates placed in proportion to time. */\n  time: boolean\n  /** Pixel position of a timestamp (time axes only). */\n  at: (t: number) => number\n}\n\n/**\n * Lays out x values between two pixel edges. Dates are placed in proportion to\n * time with calendar ticks; strings and numbers are spaced evenly, with a\n * uniform label stride that always keeps the most recent label.\n */\nexport function xModel(\n  x: XValue[],\n  x0: number,\n  x1: number,\n  f: Formatter,\n  { dateFormat, until, inset = 0 }: { dateFormat?: Intl.DateTimeFormatOptions; until?: XValue; inset?: number } = {},\n): XModel {\n  const n = x.length\n  const a = x0 + inset\n  const b = x1 - inset\n  const time = n > 0 && x.every((v) => v instanceof Date)\n  if (time) {\n    const ts = x.map((v) => (v as Date).getTime())\n    const t0 = Math.min(...ts)\n    const t1 = Math.max(...ts, until instanceof Date ? until.getTime() : -Infinity)\n    const span = t1 - t0\n    const at = (t: number) => (span === 0 ? (a + b) / 2 : a + ((t - t0) / span) * (b - a))\n    const readout: Intl.DateTimeFormatOptions =\n      dateFormat ?? (span === 0 ? { month: 'short', day: 'numeric', year: 'numeric' } : span < 3 * DAY ? { month: 'short', day: 'numeric', hour: 'numeric' } : span > 300 * DAY ? { month: 'short', day: 'numeric', year: 'numeric' } : { month: 'short', day: 'numeric' })\n    const ticks = span === 0 ? [{ x: at(t0), text: f.date(t0, readout) }] : timeTicks(t0, t1, Math.max(2, Math.floor((b - a) / 64)), f).map((k) => ({ x: at(k.t), text: k.text }))\n    return { pos: ts.map(at), ticks, label: (i) => f.date(x[i] as Date, readout), time: true, at }\n  }\n  const text = (v: XValue) => (v instanceof Date ? f.date(v, dateFormat) : String(v))\n  const pos = x.map((_, i) => (n === 1 ? (a + b) / 2 : a + ((b - a) * i) / (n - 1)))\n  const step = n > 1 ? (b - a) / (n - 1) : b - a\n  const widest = Math.max(0, ...x.map((v) => textW(text(v), 11)))\n  const stride = Math.max(1, Math.ceil((widest + 14) / Math.max(1, step)))\n  const ticks = x.map((v, i) => ({ x: pos[i], text: text(v), i })).filter((t) => (n - 1 - t.i) % stride === 0)\n  return { pos, ticks, label: (i) => text(x[i]), time: false, at: () => a }\n}\n\n/** Keeps centred tick labels inside [lo, hi] by nudging the ones at the edges. */\nexport function fitTicks<T extends { x: number; text: string }>(ticks: T[], lo: number, hi: number, px = 11): T[] {\n  return ticks.map((t) => {\n    const half = textW(t.text, px) / 2\n    return { ...t, x: clamp(t.x, lo + half, Math.max(lo + half, hi - half)) }\n  })\n}\n\n/** Index of the position nearest to a pixel. */\nexport function nearestIndex(pos: number[], px: number): number {\n  let best = 0\n  let bd = Infinity\n  for (let i = 0; i < pos.length; i++) {\n    const d = Math.abs(pos[i] - px)\n    if (d < bd) {\n      bd = d\n      best = i\n    }\n  }\n  return best\n}\n\n/* ------------------------------------------------------------------ */\n/*  Hooks                                                             */\n/* ------------------------------------------------------------------ */\n\n/**\n * Pointer hover (mouse, touch, pen) joined with keyboard navigation.\n * Spread `bind` on the plot element: arrow keys step through `count` marks\n * (and `cross` marks on the other axis, if given), Home/End jump, Esc clears.\n * A readout from touch stays until focus leaves the chart.\n */\nexport function useChartHover(count: number, { axis = 'x', cross = 0 }: { axis?: 'x' | 'y'; cross?: number } = {}) {\n  const { point, bind: pb, clear } = usePointerHover<HTMLDivElement>()\n  const [key, setKey] = useState<{ i: number; j: number } | null>(null)\n\n  const bind = {\n    ...pb,\n    tabIndex: 0,\n    onPointerDown: (e: PointerEvent<HTMLDivElement>) => {\n      setKey(null)\n      pb.onPointerDown(e)\n    },\n    onPointerMove: (e: PointerEvent<HTMLDivElement>) => {\n      if (key && e.pointerType === 'mouse') setKey(null)\n      pb.onPointerMove(e)\n    },\n    onBlur: () => {\n      setKey(null)\n      clear()\n    },\n    onKeyDown: (e: KeyboardEvent<HTMLDivElement>) => {\n      if (count <= 0) return\n      const fwd = axis === 'x' ? 'ArrowRight' : 'ArrowDown'\n      const back = axis === 'x' ? 'ArrowLeft' : 'ArrowUp'\n      const cFwd = axis === 'x' ? 'ArrowUp' : 'ArrowRight'\n      const cBack = axis === 'x' ? 'ArrowDown' : 'ArrowLeft'\n      let next: { i: number; j: number } | null | undefined\n      const cur = key ?? null\n      if (e.key === fwd) next = cur ? { ...cur, i: Math.min(count - 1, cur.i + 1) } : { i: 0, j: 0 }\n      else if (e.key === back) next = cur ? { ...cur, i: Math.max(0, cur.i - 1) } : { i: count - 1, j: 0 }\n      else if (e.key === 'Home') next = { i: 0, j: cur?.j ?? 0 }\n      else if (e.key === 'End') next = { i: count - 1, j: cur?.j ?? 0 }\n      else if (cross > 0 && e.key === cFwd) next = cur ? { ...cur, j: Math.min(cross - 1, cur.j + 1) } : { i: 0, j: 0 }\n      else if (cross > 0 && e.key === cBack) next = cur ? { ...cur, j: Math.max(0, cur.j - 1) } : { i: 0, j: 0 }\n      else if (e.key === 'Escape') next = null\n      if (next === undefined) return\n      e.preventDefault()\n      clear()\n      setKey(next)\n    },\n  }\n  const safeKey = key && key.i < count ? key : null\n  return { point, key: safeKey, bind, clear }\n}\n\n/**\n * Legend state: which series are hidden and which one is being pointed at.\n * The last visible series cannot be hidden; toggling it brings everything back.\n */\nexport function useLegend(ids: string[]) {\n  const [hidden, setHidden] = useState<Set<string>>(() => new Set())\n  const [active, setActive] = useState<string | null>(null)\n  const sig = ids.join('\\u0001')\n  const live = useMemo(() => new Set([...hidden].filter((id) => ids.includes(id))), [hidden, sig]) // eslint-disable-line react-hooks/exhaustive-deps\n  const toggle = (id: string) =>\n    setHidden((prev) => {\n      const next = new Set([...prev].filter((k) => ids.includes(k)))\n      if (next.has(id)) next.delete(id)\n      else if (next.size >= ids.length - 1) return new Set()\n      else next.add(id)\n      return next\n    })\n  return { hidden: live, active: active && !live.has(active) ? active : null, setActive, toggle }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Export, data tables and large inputs                              */\n/* ------------------------------------------------------------------ */\n\n/**\n * Series key drawn inside the SVG for exported images only. On screen the\n * interactive HTML legend sits in the same place and this group is hidden by a\n * class; an exported SVG or PNG carries no stylesheet, so the key shows there.\n * Place it in the band the HTML legend occupies (negative y, above the plot).\n */\nexport function exportLegend(items: { label: string; color: string }[], x = 0, y = -19): ReactElement {\n  let cx = x\n  return createElement(\n    'g',\n    { className: 'hidden', 'aria-hidden': true },\n    items.map((it, i) => {\n      const at = cx\n      cx += textW(it.label, 12) + 30\n      return createElement(\n        'g',\n        { key: i },\n        createElement('rect', { x: at, y: y - 8, width: 9, height: 9, rx: 2.5, fill: it.color }),\n        createElement('text', { x: at + 14, y, fontSize: 12, fill: 'var(--fg-2)' }, it.label),\n      )\n    }),\n  )\n}\n\n/** Columns for `ChartDataTable`, taken from the keys of flat rows. */\nexport function tableColumns(rows: Record<string, unknown>[], fmt?: (v: number) => string) {\n  return Object.keys(rows[0] ?? {}).map((key, i) => ({\n    key,\n    label: key,\n    align: (i === 0 ? 'left' : 'right') as 'left' | 'right',\n    format: (v: unknown) => (v == null ? '' : typeof v === 'number' && fmt ? fmt(v) : String(v)),\n  }))\n}\n\n/** A date as a CSV-friendly local `YYYY-MM-DD` (with `HH:mm` when it has a time). */\nexport function isoDay(d: Date): string {\n  const p = (v: number) => String(v).padStart(2, '0')\n  const day = `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`\n  return d.getHours() || d.getMinutes() ? `${day} ${p(d.getHours())}:${p(d.getMinutes())}` : day\n}\n\nexport const xText = (v: XValue) => (v instanceof Date ? isoDay(v) : v)\n\n/**\n * Indices to draw for a long series: keeps the first, last, lowest and highest\n * point of each pixel bucket, so peaks survive while the path stays light.\n * Returns every index when the series is already short enough.\n */\nexport function decimate(values: (number | null | undefined)[], buckets: number): number[] | null {\n  const n = values.length\n  if (n <= buckets * 4 || buckets < 1) return null\n  const keep: number[] = []\n  const size = n / buckets\n  for (let b = 0; b < buckets; b++) {\n    const a = Math.floor(b * size)\n    const z = Math.min(n, Math.floor((b + 1) * size))\n    let lo = -1\n    let hi = -1\n    for (let i = a; i < z; i++) {\n      const v = values[i]\n      if (v == null || !isFinite(v)) continue\n      if (lo < 0 || v < (values[lo] as number)) lo = i\n      if (hi < 0 || v > (values[hi] as number)) hi = i\n    }\n    const set = new Set([a, lo, hi, z - 1].filter((i) => i >= 0))\n    keep.push(...[...set].sort((p, q) => p - q))\n  }\n  return keep\n}\n\n/* ------------------------------------------------------------------ */\n/*  Point labels for scatter and bubble charts                        */\n/* ------------------------------------------------------------------ */\n\nexport interface PlacedLabel {\n  x: number\n  y: number\n  anchor: 'start' | 'middle' | 'end'\n}\n\n/**\n * Finds a spot beside each mark (right, left, above, below) where its label\n * touches no other mark and no label placed before it. Marks are tried in\n * `order`; a label with no free spot is left out rather than overlapped.\n */\nexport function placePointLabels(\n  marks: { x: number; y: number; r: number }[],\n  texts: (string | undefined)[],\n  order: number[],\n  bounds: Box,\n  px = 11,\n  weight = 500,\n  taken: Box[] = [],\n): Map<number, PlacedLabel> {\n  const out = new Map<number, PlacedLabel>()\n  const placed: Box[] = [...taken]\n  for (const i of order) {\n    const text = texts[i]\n    if (!text) continue\n    const m = marks[i]\n    const w = textW(text, px, weight)\n    const hgt = px + 3\n    const spots: [Box, PlacedLabel][] = [\n      [{ x: m.x + m.r + 5, y: m.y - hgt / 2, w, h: hgt }, { x: m.x + m.r + 5, y: m.y + px * 0.36, anchor: 'start' }],\n      [{ x: m.x - m.r - 5 - w, y: m.y - hgt / 2, w, h: hgt }, { x: m.x - m.r - 5, y: m.y + px * 0.36, anchor: 'end' }],\n      [{ x: m.x - w / 2, y: m.y - m.r - 4 - hgt, w, h: hgt }, { x: m.x, y: m.y - m.r - 7, anchor: 'middle' }],\n      [{ x: m.x - w / 2, y: m.y + m.r + 4, w, h: hgt }, { x: m.x, y: m.y + m.r + 4 + px * 0.86, anchor: 'middle' }],\n    ]\n    const hit = spots.find(\n      ([b]) =>\n        b.x >= bounds.x &&\n        b.x + b.w <= bounds.x + bounds.w &&\n        b.y >= bounds.y &&\n        b.y + b.h <= bounds.y + bounds.h &&\n        !placed.some((o) => boxesHit(b, o, 3)) &&\n        !marks.some((o, k) => k !== i && boxHitsCircle(b, o.x, o.y, o.r + 1.5)),\n    )\n    if (hit) {\n      placed.push(hit[0])\n      out.set(i, hit[1])\n    }\n  }\n  return out\n}\n\n/** An even, deterministic sample of at most `max` items (every k-th one). */\nexport function sampleEvenly<T>(items: T[], max: number): T[] {\n  if (items.length <= max) return items\n  const step = items.length / max\n  return Array.from({ length: max }, (_, i) => items[Math.floor(i * step)])\n}\n\n/**\n * Value-axis ticks thinned evenly (every 2nd, 3rd…) until their labels clear\n * each other, so a crowded axis never drops labels at random.\n */\nexport function spacedTicks(ticks: number[], pos: (t: number) => number, text: (t: number) => string, px = 11, gap = 10): number[] {\n  for (let stride = 1; stride < ticks.length; stride++) {\n    /* keep zero on the axis when there is one */\n    const zero = ticks.indexOf(0)\n    const kept = ticks.filter((_, i) => (i - (zero >= 0 ? zero : 0)) % stride === 0)\n    const clear = kept.every((t, i) => i === 0 || Math.abs(pos(t) - pos(kept[i - 1])) >= (textW(text(t), px) + textW(text(kept[i - 1]), px)) / 2 + gap)\n    if (clear) return kept\n  }\n  return ticks.slice(0, 1)\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/basic/util-a.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"
    }
  ],
  "docs": "import { StackedArea } from '@/components/klar/charts/basic/StackedArea'\nData comes in through props.",
  "categories": [
    "charts",
    "basic",
    "time"
  ],
  "meta": {
    "collection": "basic",
    "kind": "time",
    "tags": [
      "area",
      "stacked",
      "composition",
      "time series",
      "100%",
      "share",
      "cumulative"
    ],
    "standalone": true,
    "export": "StackedArea",
    "import": "@/components/klar/charts/basic/StackedArea"
  }
}
