{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "basic-data-table",
  "type": "registry:component",
  "title": "Data table with inline charts",
  "description": "Rows with a chart per column type: in-cell bars, deltas, sparklines, heat cells, badges and progress, with sortable sticky headers, a totals row and windowing for long lists.",
  "dependencies": [
    "clsx",
    "lucide-react",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "https://klar.run/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/klar/components/charts/basic/DataTable.tsx",
      "content": "import { useId, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'\nimport { ArrowDown, ArrowDownRight, ArrowUp, ArrowUpRight, ChevronsUpDown } from 'lucide-react'\nimport { Badge, type Tone } from '@/components/klar/ui/primitives'\nimport { cn } from '@/components/klar/lib/cn'\nimport { formatter, type Formatter } from '@/components/klar/charts/basic/core'\nimport { clamp, ink, minus, monotonePath, signedPct, tint } from '@/components/klar/charts/basic/util-b'\n\ninterface ColumnBase<R> {\n  /** Unique id; also the key in exported rows. */\n  key: string\n  header: string\n  align?: 'left' | 'right' | 'center'\n  /** Fixed width in px. Otherwise the column shares the free space. */\n  width?: number\n  /** Defaults to true for every type. */\n  sortable?: boolean\n  /**\n   * Totals row: `'sum'` or `'avg'` of the column, any other string as plain text\n   * (e.g. \"Total\"), or a function of all rows.\n   */\n  total?: 'sum' | 'avg' | (string & {}) | ((rows: R[]) => ReactNode)\n  /** Tooltip on the header (what the measure means). */\n  hint?: string\n}\n\n/** Column config: `type` picks the cell renderer and decides which other fields apply. */\nexport type DataTableColumnDef<R> =\n  | (ColumnBase<R> & { type: 'text'; value: (row: R) => string; /** Second line under the text. */ sub?: (row: R) => string | undefined; /** Avatar, icon or dot before the text. */ lead?: (row: R) => ReactNode })\n  | (ColumnBase<R> & { type: 'number'; value: (row: R) => number; format?: (v: number) => string })\n  | (ColumnBase<R> & { type: 'delta'; /** Ratio: 0.12 = +12%. */ value: (row: R) => number; format?: (v: number) => string; /** A fall is good. */ invert?: boolean })\n  | (ColumnBase<R> & { type: 'bar'; value: (row: R) => number; format?: (v: number) => string; /** Full-bar value; defaults to the column maximum. */ max?: number; color?: string })\n  | (ColumnBase<R> & { type: 'sparkline'; value: (row: R) => number[]; color?: string; /** What sorting uses: the last point (default), the change first → last, or the mean. */ sortBy?: 'last' | 'change' | 'mean' })\n  | (ColumnBase<R> & { type: 'heat'; value: (row: R) => number; format?: (v: number) => string; /** Colour scale ends; defaults to the column's range. A range that crosses zero diverges. */ domain?: [number, number]; color?: string; negativeColor?: string })\n  | (ColumnBase<R> & { type: 'badge'; value: (row: R) => string; tones?: Record<string, Tone> })\n  | (ColumnBase<R> & { type: 'progress'; /** Ratio of the goal: 1 = met. */ value: (row: R) => number; format?: (v: number) => string; color?: string })\n\nexport interface DataTableSort {\n  key: string\n  dir: 'asc' | 'desc'\n}\n\nexport interface DataTableProps<R> {\n  rows: R[]\n  columns: DataTableColumnDef<R>[]\n  rowKey: (row: R, index: number) => string\n  defaultSort?: DataTableSort\n  /** Controlled sort; pair with `onSortChange`. */\n  sort?: DataTableSort | null\n  onSortChange?: (sort: DataTableSort | null) => void\n  /** Totals row pinned under the body; each column opts in with `total`. */\n  totals?: boolean\n  stickyHeader?: boolean\n  /** Scroll the body inside this height (px). Needed for the sticky header and for windowing. */\n  maxHeight?: number\n  density?: 'comfortable' | 'compact'\n  onRowClick?: (row: R) => void\n  /** Accessible name; rendered as the table caption for screen readers. */\n  ariaLabel?: string\n  locale?: string\n  currency?: string\n  emptyLabel?: string\n  className?: string\n}\n\nconst sortValue = <R,>(c: DataTableColumnDef<R>, r: R): number | string => {\n  if (c.type === 'sparkline') {\n    const s = c.value(r)\n    if (!s.length) return 0\n    return c.sortBy === 'change' ? s[s.length - 1] - s[0] : c.sortBy === 'mean' ? s.reduce((a, b) => a + b, 0) / s.length : s[s.length - 1]\n  }\n  return c.value(r)\n}\n\n/** Plain rows for CSV export: one object per row keyed by column `key` (sparklines as a `;`-joined series). */\nexport function dataTableToRows<R>(rows: R[], columns: DataTableColumnDef<R>[]) {\n  return rows.map((r) => {\n    const out: Record<string, unknown> = {}\n    for (const c of columns) out[c.key] = c.type === 'sparkline' ? c.value(r).join(';') : c.value(r)\n    return out\n  })\n}\n\n/**\n * Data table with inline charts. Each column has a `type` that picks its cell:\n * `text` (with an optional second line), `number`, `delta` (good/bad aware),\n * `bar` (in-cell bar on a shared scale), `sparkline`, `heat` (cell tinted by\n * value), `badge` and `progress`. Headers sort on click or Enter / Space and\n * announce the order; the header can stick, rows highlight on hover and focus,\n * and a totals row sums or averages the columns that opt in.\n * Data: `rows: R[]` plus `columns: DataTableColumnDef<R>[]`.\n *\n * Scale: with `maxHeight` set, tables of more than 100 rows are windowed (only\n * the visible rows are in the DOM), which stays smooth to ~50,000 rows. Without\n * `maxHeight` every row is rendered, so keep it under ~1,000.\n */\nexport function DataTable<R>({\n  rows,\n  columns,\n  rowKey,\n  defaultSort,\n  sort: sortProp,\n  onSortChange,\n  totals = false,\n  stickyHeader = true,\n  maxHeight,\n  density = 'comfortable',\n  onRowClick,\n  ariaLabel = 'Data table',\n  locale,\n  currency,\n  emptyLabel = 'No rows',\n  className,\n}: DataTableProps<R>) {\n  const f = formatter(locale, currency)\n  const [inner, setInner] = useState<DataTableSort | null>(defaultSort ?? null)\n  const sort = sortProp !== undefined ? sortProp : inner\n  const [scrollTop, setScrollTop] = useState(0)\n  const scroller = useRef<HTMLDivElement>(null)\n  const liveId = useId()\n  const rowH = density === 'compact' ? 36 : 46\n\n  const setSort = (s: DataTableSort | null) => {\n    if (sortProp === undefined) setInner(s)\n    onSortChange?.(s)\n  }\n  const cycle = (c: DataTableColumnDef<R>) => {\n    const first = c.type === 'text' || c.type === 'badge' ? 'asc' : 'desc'\n    if (sort?.key !== c.key) return setSort({ key: c.key, dir: first })\n    if (sort.dir === first) return setSort({ key: c.key, dir: first === 'asc' ? 'desc' : 'asc' })\n    setSort(null)\n  }\n\n  const sorted = useMemo(() => {\n    const col = sort && columns.find((c) => c.key === sort.key)\n    if (!sort || !col) return rows\n    const cmp = new Intl.Collator(locale, { numeric: true, sensitivity: 'base' })\n    const k = sort.dir === 'asc' ? 1 : -1\n    return rows\n      .map((r, i) => ({ r, i, v: sortValue(col, r) }))\n      .sort((a, b) => (typeof a.v === 'string' || typeof b.v === 'string' ? cmp.compare(String(a.v), String(b.v)) : a.v - b.v) * k || a.i - b.i)\n      .map((x) => x.r)\n  }, [rows, columns, sort, locale])\n\n  /* Per-column statistics for bar scales, heat ramps and totals. */\n  const stats = useMemo(\n    () =>\n      columns.map((c) => {\n        if (c.type === 'text' || c.type === 'badge' || c.type === 'sparkline') return { min: 0, max: 0, sum: 0 }\n        let min = Infinity\n        let max = -Infinity\n        let sum = 0\n        for (const r of rows) {\n          const v = c.value(r)\n          if (!Number.isFinite(v)) continue\n          if (v < min) min = v\n          if (v > max) max = v\n          sum += v\n        }\n        return { min: min === Infinity ? 0 : min, max: max === -Infinity ? 0 : max, sum }\n      }),\n    [rows, columns],\n  )\n\n  /* Windowing */\n  const windowed = maxHeight != null && sorted.length > 100\n  const over = 8\n  const start = windowed ? Math.max(0, Math.floor(scrollTop / rowH) - over) : 0\n  const end = windowed ? Math.min(sorted.length, Math.ceil((scrollTop + maxHeight!) / rowH) + over) : sorted.length\n  const visible = windowed ? sorted.slice(start, end) : sorted\n\n  const alignOf = (c: DataTableColumnDef<R>) => c.align ?? (c.type === 'number' || c.type === 'delta' || c.type === 'heat' ? 'right' : 'left')\n  const alignCls = (c: DataTableColumnDef<R>) => (alignOf(c) === 'right' ? 'text-right' : alignOf(c) === 'center' ? 'text-center' : 'text-left')\n  const num = (c: { format?: (v: number) => string }, v: number) => (c.format ? c.format(v) : minus(Math.abs(v) >= 10000 ? f.compact(v) : f.number(v, Number.isInteger(v) ? 0 : 1)))\n\n  const cell = (c: DataTableColumnDef<R>, r: R, ci: number): ReactNode => {\n    switch (c.type) {\n      case 'text': {\n        const sub = c.sub?.(r)\n        return (\n          <span className=\"flex min-w-0 items-center gap-2.5\">\n            {c.lead?.(r)}\n            <span className=\"min-w-0\">\n              <span className=\"block truncate font-medium text-fg\">{c.value(r)}</span>\n              {sub && density !== 'compact' && <span className=\"block truncate text-[11.5px] leading-4 text-fg-3\">{sub}</span>}\n            </span>\n          </span>\n        )\n      }\n      case 'number':\n        return <span className=\"num text-fg\">{num(c, c.value(r))}</span>\n      case 'delta':\n        return <DeltaText v={c.value(r)} invert={c.invert} f={f} format={c.format} />\n      case 'bar': {\n        const v = c.value(r)\n        const max = c.max ?? Math.max(stats[ci].max, 1e-9)\n        return (\n          <span className=\"flex items-center gap-3\">\n            <span className=\"num w-[58px] shrink-0 text-right font-medium text-fg\">{num(c, v)}</span>\n            <span className=\"relative h-[6px] min-w-[48px] flex-1 overflow-hidden rounded-full bg-surface-3\" aria-hidden>\n              <span className=\"anim-grow-x absolute inset-y-0 left-0 rounded-full\" style={{ width: `${clamp(v / max, 0, 1) * 100}%`, background: c.color ?? 'var(--accent)' }} />\n            </span>\n          </span>\n        )\n      }\n      case 'sparkline':\n        return <CellSpark series={c.value(r)} color={c.color} f={f} />\n      case 'heat': {\n        const v = c.value(r)\n        return (\n          <span className=\"num inline-flex h-7 w-full min-w-[52px] items-center justify-end rounded-md px-2 font-medium text-fg\" style={{ background: heat(c, v, stats[ci]) }}>\n            {num(c, v)}\n          </span>\n        )\n      }\n      case 'badge': {\n        const v = c.value(r)\n        return (\n          <Badge tone={c.tones?.[v] ?? 'neutral'} dot size=\"xs\">\n            {v}\n          </Badge>\n        )\n      }\n      case 'progress': {\n        const v = c.value(r)\n        const col = v >= 1 ? 'var(--green)' : (c.color ?? 'var(--accent)')\n        return (\n          <span className=\"flex items-center gap-2.5\">\n            <span className=\"relative h-[6px] min-w-[56px] flex-1 overflow-hidden rounded-full bg-surface-3\" aria-hidden>\n              <span className=\"anim-grow-x absolute inset-y-0 left-0 rounded-full\" style={{ width: `${clamp(v, 0, 1) * 100}%`, background: col }} />\n            </span>\n            <span className={cn('num w-[38px] shrink-0 text-right text-[12.5px]', v >= 1 ? 'font-semibold' : 'font-medium text-fg-2')} style={v >= 1 ? { color: ink('var(--green)') } : undefined}>\n              {c.format ? c.format(v) : f.percent(v)}\n            </span>\n          </span>\n        )\n      }\n    }\n  }\n\n  const totalCell = (c: DataTableColumnDef<R>, ci: number): ReactNode => {\n    const t = c.total\n    if (t == null) return null\n    if (typeof t === 'function') return t(rows)\n    if (t !== 'sum' && t !== 'avg') return <span className=\"text-fg\">{t}</span>\n    if (c.type === 'sparkline') {\n      const len = Math.max(0, ...rows.map((r) => c.value(r).length))\n      const agg = Array.from({ length: len }, (_, i) => rows.reduce((s, r) => s + (c.value(r)[i] ?? 0), 0) / (t === 'avg' ? rows.length || 1 : 1))\n      return <CellSpark series={agg} color={c.color} f={f} />\n    }\n    if (c.type === 'text' || c.type === 'badge') return null\n    const v = t === 'sum' ? stats[ci].sum : stats[ci].sum / (rows.length || 1)\n    if (c.type === 'delta') return <DeltaText v={v} invert={c.invert} f={f} format={c.format} />\n    if (c.type === 'progress')\n      return (\n        <span className=\"flex items-center gap-2.5\">\n          <span className=\"min-w-[56px] flex-1\" />\n          <span className=\"num w-[38px] shrink-0 text-right text-[12.5px] text-fg\">{c.format ? c.format(v) : f.percent(v)}</span>\n        </span>\n      )\n    if (c.type === 'bar') return <span className=\"num inline-block w-[58px] text-right text-fg\">{num(c, v)}</span>\n    return <span className={cn('num text-fg', c.type === 'heat' && 'pr-2')}>{num(c, v)}</span>\n  }\n\n  const onRowKey = (e: KeyboardEvent<HTMLTableRowElement>, r: R) => {\n    if (e.target !== e.currentTarget) return\n    if (e.key === 'Enter' || e.key === ' ') {\n      e.preventDefault()\n      onRowClick?.(r)\n    } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n      const sib = (e.key === 'ArrowDown' ? e.currentTarget.nextElementSibling : e.currentTarget.previousElementSibling) as HTMLElement | null\n      if (sib?.tabIndex === 0) {\n        e.preventDefault()\n        sib.focus()\n      }\n    }\n  }\n\n  const sortedCol = sort && columns.find((c) => c.key === sort.key)\n  const pad = density === 'compact' ? 'px-3' : 'px-3.5'\n\n  return (\n    <div className={cn('relative w-full min-w-0', className)}>\n      <div\n        ref={scroller}\n        onScroll={windowed ? (e) => setScrollTop(e.currentTarget.scrollTop) : undefined}\n        className=\"scroll-thin w-full overflow-auto rounded-xl border border-border\"\n        style={{ maxHeight }}\n        tabIndex={maxHeight != null ? 0 : undefined}\n        role={maxHeight != null ? 'region' : undefined}\n        aria-label={maxHeight != null ? `${ariaLabel}, scrollable` : undefined}\n      >\n        <table className=\"w-full border-separate border-spacing-0 text-[13px] text-fg-2\" aria-rowcount={windowed ? sorted.length + 1 : undefined}>\n          <caption className=\"sr-only\">{ariaLabel}</caption>\n          <colgroup>\n            {columns.map((c) => (\n              <col key={c.key} style={c.width ? { width: c.width } : undefined} />\n            ))}\n          </colgroup>\n          <thead>\n            <tr>\n              {columns.map((c) => {\n                const on = sort?.key === c.key\n                const sortable = c.sortable ?? true\n                const Icon = on ? (sort!.dir === 'asc' ? ArrowUp : ArrowDown) : ChevronsUpDown\n                const right = alignOf(c) === 'right'\n                return (\n                  <th\n                    key={c.key}\n                    scope=\"col\"\n                    aria-sort={on ? (sort!.dir === 'asc' ? 'ascending' : 'descending') : sortable ? 'none' : undefined}\n                    title={c.hint}\n                    className={cn('h-9 border-b border-border bg-surface-2 text-[11.5px] font-medium whitespace-nowrap text-fg-3', pad, alignCls(c), stickyHeader && 'sticky top-0 z-10')}\n                  >\n                    {sortable ? (\n                      <button\n                        type=\"button\"\n                        onClick={() => cycle(c)}\n                        className={cn('group/h -mx-1.5 inline-flex h-6 items-center gap-1 rounded-md px-1.5 transition-colors hover:bg-surface-4 hover:text-fg', on && 'text-fg', right && 'flex-row-reverse')}\n                      >\n                        {c.header}\n                        <Icon size={12} strokeWidth={2.2} aria-hidden className={cn('shrink-0 transition-opacity', on ? 'opacity-100' : 'opacity-40 group-hover/h:opacity-100')} />\n                      </button>\n                    ) : (\n                      c.header\n                    )}\n                  </th>\n                )\n              })}\n            </tr>\n          </thead>\n          <tbody>\n            {windowed && start > 0 && (\n              <tr aria-hidden style={{ height: start * rowH }}>\n                <td colSpan={columns.length} />\n              </tr>\n            )}\n            {visible.map((r, vi) => {\n              const i = start + vi\n              return (\n                <tr\n                  key={rowKey(r, i)}\n                  aria-rowindex={windowed ? i + 2 : undefined}\n                  tabIndex={onRowClick ? 0 : undefined}\n                  onClick={onRowClick ? () => onRowClick(r) : undefined}\n                  onKeyDown={onRowClick ? (e) => onRowKey(e, r) : undefined}\n                  className={cn('group/r outline-none', onRowClick && 'cursor-pointer')}\n                  style={{ height: rowH }}\n                >\n                  {columns.map((c, ci) => {\n                    const content = cell(c, r, ci)\n                    const cls = cn(\n                      'border-b border-border whitespace-nowrap transition-colors group-hover/r:bg-surface-2 group-focus-visible/r:bg-surface-3',\n                      c.type === 'heat' ? 'px-1.5' : pad,\n                      alignCls(c),\n                      i === sorted.length - 1 && !totals && 'border-b-0',\n                      c.type === 'text' && 'max-w-[240px]',\n                      ci === 0 && 'group-focus-visible/r:shadow-[inset_2px_0_0_var(--accent)]',\n                    )\n                    return ci === 0 && c.type === 'text' ? (\n                      <th key={c.key} scope=\"row\" className={cn(cls, 'font-normal')}>\n                        {content}\n                      </th>\n                    ) : (\n                      <td key={c.key} className={cls}>\n                        {content}\n                      </td>\n                    )\n                  })}\n                </tr>\n              )\n            })}\n            {windowed && end < sorted.length && (\n              <tr aria-hidden style={{ height: (sorted.length - end) * rowH }}>\n                <td colSpan={columns.length} />\n              </tr>\n            )}\n            {!sorted.length && (\n              <tr>\n                <td colSpan={columns.length} className=\"h-24 text-center text-[12.5px] text-fg-3\">\n                  {emptyLabel}\n                </td>\n              </tr>\n            )}\n          </tbody>\n          {totals && sorted.length > 0 && (\n            <tfoot>\n              <tr style={{ height: rowH - 4 }}>\n                {columns.map((c, ci) => (\n                  <td key={c.key} className={cn('border-t border-border-strong bg-surface-2 font-semibold whitespace-nowrap', maxHeight != null && 'sticky bottom-0 z-10', c.type === 'heat' ? 'px-1.5' : pad, alignCls(c))} style={{ marginTop: -1 }}>\n                    {totalCell(c, ci)}\n                  </td>\n                ))}\n              </tr>\n            </tfoot>\n          )}\n        </table>\n      </div>\n      <span id={liveId} role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {sortedCol ? `Sorted by ${sortedCol.header}, ${sort!.dir === 'asc' ? 'ascending' : 'descending'}` : ''}\n      </span>\n    </div>\n  )\n}\n\nfunction heat(c: { domain?: [number, number]; color?: string; negativeColor?: string }, v: number, s: { min: number; max: number }) {\n  const [lo, hi] = c.domain ?? [s.min, s.max]\n  const pos = c.color ?? 'var(--accent)'\n  if (lo < 0 && hi > 0) {\n    const m = Math.max(-lo, hi)\n    const t = clamp(Math.abs(v) / m, 0, 1)\n    return tint(v < 0 ? (c.negativeColor ?? 'var(--red)') : pos, Math.round(4 + t * 34))\n  }\n  const t = hi === lo ? 0.5 : clamp((v - lo) / (hi - lo), 0, 1)\n  return tint(pos, Math.round(5 + t * 37))\n}\n\nfunction DeltaText({ v, invert, f, format }: { v: number; invert?: boolean; f: Formatter; format?: (v: number) => string }) {\n  const flat = Math.abs(v) < 0.0005\n  const good = invert ? v < 0 : v > 0\n  const c = flat ? 'var(--fg-3)' : good ? 'var(--green)' : 'var(--red)'\n  const Icon = v > 0 ? ArrowUpRight : ArrowDownRight\n  return (\n    <span className=\"num inline-flex items-center gap-0.5 font-medium\" style={{ color: flat ? c : ink(c, 82) }}>\n      {!flat && <Icon size={13} strokeWidth={2.3} aria-hidden />}\n      {format ? format(v) : signedPct(f, v)}\n    </span>\n  )\n}\n\nfunction CellSpark({ series, color, f }: { series: number[]; color?: string; f: Formatter }) {\n  const W = 92\n  const H = 26\n  if (series.length < 2) return <span className=\"text-fg-4\">–</span>\n  const lo = Math.min(...series)\n  const hi = Math.max(...series)\n  const x = (i: number) => 3 + (i / (series.length - 1)) * (W - 8)\n  const y = (v: number) => 4 + (1 - (hi === lo ? 0.5 : (v - lo) / (hi - lo))) * (H - 8)\n  const up = series[series.length - 1] >= series[0]\n  const c = color ?? (up ? 'var(--green)' : 'var(--red)')\n  const d = monotonePath(series.map((v, i) => [x(i), y(v)]))\n  const last = series.length - 1\n  return (\n    <svg\n      width={W}\n      height={H}\n      role=\"img\"\n      aria-label={`Trend ${up ? 'up' : 'down'} from ${f.compact(series[0])} to ${f.compact(series[last])}, low ${f.compact(lo)}, high ${f.compact(hi)}`}\n      className=\"inline-block align-middle\"\n    >\n      <path d={`${d}L${x(last)},${H}L${x(0)},${H}Z`} fill={tint(c, 10)} />\n      <path d={d} fill=\"none\" stroke={c} strokeWidth={1.5} strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n      <circle cx={x(last)} cy={y(series[last])} r={2.6} fill={c} stroke=\"var(--surface)\" strokeWidth={1.25} />\n    </svg>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/basic/DataTable.tsx"
    },
    {
      "path": "registry/klar/components/ui/primitives.tsx",
      "content": "import type { ButtonHTMLAttributes, CSSProperties, ReactNode } from 'react'\nimport type { LucideIcon } from 'lucide-react'\nimport { ArrowDownRight, ArrowUpRight, ChevronDown, Search } from 'lucide-react'\nimport { cn } from '@/components/klar/lib/cn'\n\n/* ------------------------------------------------------------------ */\n/*  Button                                                            */\n/* ------------------------------------------------------------------ */\n\ntype ButtonVariant = 'outline' | 'primary' | 'accent' | 'ghost' | 'soft'\ntype ButtonSize = 'xs' | 'sm' | 'md'\n\nconst buttonVariants: Record<ButtonVariant, string> = {\n  outline:\n    'bg-surface text-fg border border-border-strong shadow-btn hover:bg-surface-2 active:bg-surface-3',\n  primary: 'bg-invert text-invert-fg shadow-btn hover:opacity-90 active:opacity-80',\n  accent:\n    'bg-accent text-accent-fg shadow-[0_1px_2px_rgba(0,0,0,.08),inset_0_1px_0_rgba(255,255,255,.18)] hover:brightness-105 active:brightness-95',\n  ghost: 'text-fg-2 hover:bg-surface-3 hover:text-fg',\n  soft: 'bg-surface-3 text-fg hover:bg-surface-4',\n}\nconst buttonSizes: Record<ButtonSize, string> = {\n  xs: 'h-7 px-2.5 text-xs gap-1.5 rounded-lg',\n  sm: 'h-8 px-3 text-[13px] gap-1.5 rounded-[10px]',\n  md: 'h-9 px-3.5 text-sm gap-2 rounded-[10px]',\n}\n\nexport interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n  variant?: ButtonVariant\n  size?: ButtonSize\n  icon?: LucideIcon\n  iconRight?: LucideIcon\n}\n\nexport function Button({\n  variant = 'outline',\n  size = 'sm',\n  icon: Icon,\n  iconRight: IconRight,\n  className,\n  children,\n  ...props\n}: ButtonProps) {\n  const iconSize = size === 'md' ? 16 : 14\n  return (\n    <button\n      type=\"button\"\n      className={cn(\n        'inline-flex shrink-0 items-center justify-center font-medium whitespace-nowrap transition-[background,opacity,filter,color] duration-150 select-none',\n        buttonVariants[variant],\n        buttonSizes[size],\n        className,\n      )}\n      {...props}\n    >\n      {Icon && <Icon size={iconSize} strokeWidth={2} className=\"shrink-0\" />}\n      {children}\n      {IconRight && <IconRight size={iconSize} strokeWidth={2} className=\"shrink-0 opacity-60\" />}\n    </button>\n  )\n}\n\nexport function IconButton({\n  icon: Icon,\n  label,\n  variant = 'ghost',\n  size = 'sm',\n  className,\n  dot,\n  ...props\n}: Omit<ButtonProps, 'icon' | 'children'> & { icon: LucideIcon; label: string; dot?: boolean }) {\n  const box = size === 'xs' ? 'size-7' : size === 'md' ? 'size-9' : 'size-8'\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      title={label}\n      className={cn(\n        'relative inline-flex shrink-0 items-center justify-center rounded-[10px] transition-colors duration-150',\n        buttonVariants[variant],\n        box,\n        className,\n      )}\n      {...props}\n    >\n      <Icon size={size === 'md' ? 18 : 16} strokeWidth={1.9} />\n      {dot && (\n        <span className=\"absolute top-1.5 right-1.5 size-1.5 rounded-full bg-red ring-2 ring-panel\" />\n      )}\n    </button>\n  )\n}\n\n/** Looks like a select; used for filters such as \"Tessera Core ▾\". */\nexport function SelectButton({\n  children,\n  icon,\n  className,\n  size = 'xs',\n}: {\n  children: ReactNode\n  icon?: LucideIcon\n  className?: string\n  size?: ButtonSize\n}) {\n  return (\n    <Button size={size} icon={icon} iconRight={ChevronDown} className={className}>\n      {children}\n    </Button>\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Badge / status                                                    */\n/* ------------------------------------------------------------------ */\n\nexport type Tone =\n  | 'neutral'\n  | 'blue'\n  | 'green'\n  | 'orange'\n  | 'amber'\n  | 'red'\n  | 'violet'\n  | 'pink'\n  | 'teal'\n  | 'accent'\n\nexport const toneVar: Record<Tone, string> = {\n  neutral: 'var(--fg-3)',\n  blue: 'var(--blue)',\n  green: 'var(--green)',\n  orange: 'var(--orange)',\n  amber: 'var(--amber)',\n  red: 'var(--red)',\n  violet: 'var(--violet)',\n  pink: 'var(--pink)',\n  teal: 'var(--teal)',\n  accent: 'var(--accent)',\n}\n\n/** Soft tinted pill. Colour is mixed from the tone so it works in light and dark. */\nexport function Badge({\n  tone = 'neutral',\n  dot,\n  children,\n  className,\n  size = 'sm',\n}: {\n  tone?: Tone\n  dot?: boolean\n  children: ReactNode\n  className?: string\n  size?: 'xs' | 'sm'\n}) {\n  const c = toneVar[tone]\n  return (\n    <span\n      className={cn(\n        'inline-flex shrink-0 items-center gap-1.5 rounded-md font-medium whitespace-nowrap',\n        size === 'xs' ? 'h-5 px-1.5 text-[11px]' : 'h-6 px-2 text-xs',\n        className,\n      )}\n      style={{\n        color: tone === 'neutral' ? 'var(--fg-2)' : `color-mix(in oklab, ${c} 88%, var(--fg))`,\n        background: `color-mix(in oklab, ${c} ${tone === 'neutral' ? 12 : 11}%, transparent)`,\n      }}\n    >\n      {dot && <span className=\"size-1.5 rounded-full\" style={{ background: c }} />}\n      {children}\n    </span>\n  )\n}\n\nexport function StatusDot({ tone = 'green', pulse }: { tone?: Tone; pulse?: boolean }) {\n  return (\n    <span\n      className=\"inline-block size-2 shrink-0 rounded-full\"\n      style={{\n        background: toneVar[tone],\n        color: toneVar[tone],\n        animation: pulse ? 'pulse-dot 2s ease-in-out infinite' : undefined,\n      }}\n    />\n  )\n}\n\n/** Small \"↗ +3\" style trend marker used under KPI values. */\nexport function Delta({\n  value,\n  children,\n  invert,\n  className,\n}: {\n  value: string | number\n  children?: ReactNode\n  invert?: boolean\n  className?: string\n}) {\n  const negative = typeof value === 'number' ? value < 0 : String(value).trim().startsWith('-')\n  const good = invert ? negative : !negative\n  const Icon = negative ? ArrowDownRight : ArrowUpRight\n  const color = good ? 'var(--green)' : 'var(--red)'\n  return (\n    <span className={cn('inline-flex items-center gap-1.5 text-[13px] text-fg-2', className)}>\n      <span\n        className=\"inline-flex size-4 items-center justify-center rounded-full\"\n        style={{ background: `color-mix(in oklab, ${color} 14%, transparent)`, color }}\n      >\n        <Icon size={11} strokeWidth={2.4} />\n      </span>\n      <span className=\"font-medium\" style={{ color }}>\n        {typeof value === 'number' && value > 0 ? `+${value}` : value}\n      </span>\n      {children}\n    </span>\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Avatar                                                            */\n/* ------------------------------------------------------------------ */\n\nconst avatarPalette = [\n  ['#d9f5dd', '#1f7a3a'],\n  ['#e3e1fb', '#4b3cc4'],\n  ['#ffe4cc', '#b45309'],\n  ['#dbeafe', '#1d4ed8'],\n  ['#fde2ec', '#be185d'],\n  ['#d5f3ef', '#0f766e'],\n  ['#f1e6d6', '#7c5a2a'],\n]\n\nfunction hash(s: string) {\n  let h = 0\n  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0\n  return Math.abs(h)\n}\n\nexport function initials(name: string) {\n  const parts = name.trim().split(/\\s+/)\n  return (parts[0][0] + (parts.length > 1 ? parts[parts.length - 1][0] : '')).toUpperCase()\n}\n\n/**\n * Initial avatar. `variant=\"photo\"` renders a soft gradient portrait-like disc\n * that reads as a photo at small sizes without shipping images.\n */\nexport function Avatar({\n  name,\n  size = 24,\n  className,\n  variant = 'initials',\n  single,\n  ring,\n}: {\n  name: string\n  size?: number\n  className?: string\n  variant?: 'initials' | 'photo'\n  single?: boolean\n  ring?: boolean\n}) {\n  const h = hash(name)\n  const [bg, fg] = avatarPalette[h % avatarPalette.length]\n  const text = single ? initials(name)[0] : initials(name)\n  if (variant === 'photo') {\n    const hue = h % 360\n    return (\n      <span\n        className={cn(\n          'relative inline-flex shrink-0 items-end justify-center overflow-hidden rounded-full',\n          ring && 'ring-2 ring-panel',\n          className,\n        )}\n        style={{\n          width: size,\n          height: size,\n          background: `radial-gradient(120% 90% at 30% 15%, hsl(${hue} 70% 82%), hsl(${(hue + 40) % 360} 45% 52%))`,\n        }}\n        aria-label={name}\n      >\n        <span\n          className=\"absolute rounded-full\"\n          style={{\n            width: size * 0.42,\n            height: size * 0.42,\n            top: size * 0.2,\n            background: `hsl(${(hue + 20) % 360} 35% 32% / .55)`,\n          }}\n        />\n        <span\n          className=\"absolute rounded-t-full\"\n          style={{\n            width: size * 0.78,\n            height: size * 0.42,\n            bottom: -size * 0.06,\n            background: `hsl(${(hue + 20) % 360} 35% 28% / .5)`,\n          }}\n        />\n      </span>\n    )\n  }\n  return (\n    <span\n      className={cn(\n        'inline-flex shrink-0 items-center justify-center rounded-full font-semibold select-none',\n        ring && 'ring-2 ring-panel',\n        className,\n      )}\n      style={{\n        width: size,\n        height: size,\n        fontSize: Math.max(9, size * 0.4),\n        background: bg,\n        color: fg,\n      }}\n      aria-label={name}\n    >\n      {text}\n    </span>\n  )\n}\n\nexport function AvatarStack({\n  names,\n  size = 22,\n  max = 4,\n  variant,\n  single = true,\n}: {\n  names: string[]\n  size?: number\n  max?: number\n  variant?: 'initials' | 'photo'\n  single?: boolean\n}) {\n  const shown = names.slice(0, max)\n  const rest = names.length - shown.length\n  return (\n    <span className=\"inline-flex items-center\">\n      {shown.map((n, i) => (\n        <Avatar\n          key={n + i}\n          name={n}\n          size={size}\n          ring\n          variant={variant}\n          single={single}\n          className={i ? '-ml-1.5' : ''}\n        />\n      ))}\n      {rest > 0 && (\n        <span\n          className=\"-ml-1.5 inline-flex items-center justify-center rounded-full bg-surface-3 text-[10px] font-semibold text-fg-2 ring-2 ring-panel\"\n          style={{ width: size, height: size }}\n        >\n          +{rest}\n        </span>\n      )}\n    </span>\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Icon tile: coloured glyph in a soft or solid container            */\n/* ------------------------------------------------------------------ */\n\nexport function IconTile({\n  icon: Icon,\n  tone = 'blue',\n  variant = 'solid',\n  size = 28,\n  className,\n  rounded = 'lg',\n}: {\n  icon: LucideIcon\n  tone?: Tone\n  variant?: 'solid' | 'soft' | 'outline' | 'glyph'\n  size?: number\n  className?: string\n  rounded?: 'full' | 'lg'\n}) {\n  const c = toneVar[tone]\n  const style: CSSProperties =\n    variant === 'solid'\n      ? { background: c, color: '#fff' }\n      : variant === 'soft'\n        ? { background: `color-mix(in oklab, ${c} 13%, transparent)`, color: c }\n        : variant === 'outline'\n          ? { color: c }\n          : { color: c }\n  return (\n    <span\n      className={cn(\n        'inline-flex shrink-0 items-center justify-center',\n        rounded === 'full' ? 'rounded-full' : 'rounded-[9px]',\n        variant === 'outline' && 'border border-border bg-surface shadow-btn',\n        className,\n      )}\n      style={{ width: size, height: size, ...style }}\n    >\n      <Icon\n        size={Math.round(size * (variant === 'glyph' ? 0.85 : 0.55))}\n        strokeWidth={variant === 'solid' ? 2.2 : 2}\n      />\n    </span>\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Misc                                                              */\n/* ------------------------------------------------------------------ */\n\nexport function Kbd({ children, className }: { children: ReactNode; className?: string }) {\n  return (\n    <kbd\n      className={cn(\n        'inline-flex h-5 min-w-5 items-center justify-center rounded-md border border-border bg-surface px-1.5 font-sans text-[10.5px] font-medium text-fg-3 shadow-btn',\n        className,\n      )}\n    >\n      {children}\n    </kbd>\n  )\n}\n\nexport function SearchField({\n  placeholder = 'Search…',\n  className,\n  shortcut = '⌘K',\n}: {\n  placeholder?: string\n  className?: string\n  shortcut?: string | null\n}) {\n  return (\n    <label\n      className={cn(\n        'group flex h-9 items-center gap-2.5 rounded-[10px] border border-border bg-surface-2 px-3 text-sm text-fg-3 transition-colors focus-within:border-border-strong focus-within:bg-surface hover:border-border-strong',\n        className,\n      )}\n    >\n      <Search size={15} strokeWidth={2} className=\"shrink-0\" />\n      <input\n        placeholder={placeholder}\n        className=\"min-w-0 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-3\"\n      />\n      {shortcut && <Kbd>{shortcut}</Kbd>}\n    </label>\n  )\n}\n\nexport function Progress({\n  value,\n  color = 'var(--accent)',\n  className,\n  height = 6,\n  track = 'var(--surface-3)',\n}: {\n  value: number\n  color?: string\n  className?: string\n  height?: number\n  track?: string\n}) {\n  return (\n    <div\n      className={cn('w-full overflow-hidden rounded-full', className)}\n      style={{ height, background: track }}\n      role=\"progressbar\"\n      aria-valuenow={value}\n      aria-valuemin={0}\n      aria-valuemax={100}\n    >\n      <div\n        className=\"anim-grow-x h-full rounded-full\"\n        style={{ width: `${Math.min(100, Math.max(0, value))}%`, background: color }}\n      />\n    </div>\n  )\n}\n\nexport function Divider({ className, vertical }: { className?: string; vertical?: boolean }) {\n  return (\n    <span\n      className={cn(vertical ? 'h-4 w-px self-center' : 'h-px w-full', 'bg-border', className)}\n    />\n  )\n}\n\nexport function Legend({\n  items,\n  className,\n}: {\n  items: { label: ReactNode; color: string; value?: ReactNode }[]\n  className?: string\n}) {\n  return (\n    <div className={cn('flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-fg-2', className)}>\n      {items.map((it, i) => (\n        <span key={i} className=\"inline-flex items-center gap-1.5\">\n          <span className=\"size-2 rounded-full\" style={{ background: it.color }} />\n          {it.label}\n          {it.value != null && <span className=\"num text-fg-3\">{it.value}</span>}\n        </span>\n      ))}\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/ui/primitives.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-b.ts",
      "content": "/**\n * Helpers shared by the basic charts in set B: text metrics, label fitting and\n * dodging, default formats, colour mixing, a combined pointer + keyboard \"active\n * mark\" hook, vertical gridlines and time ticks.\n */\nimport { createElement, useEffect, useState, type KeyboardEvent, type FocusEvent, type ReactElement, type ReactNode, type RefObject } from 'react'\nimport { usePointerHover, type Formatter, type HoverPoint, 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/** Centre of the device pixel nearest to `v`, so a 1px stroke renders crisp. */\nexport const crisp = (v: number) => Math.round(v) + 0.5\n\n/* ------------------------------------------------------------------ */\n/*  Colour                                                            */\n/* ------------------------------------------------------------------ */\n\n/** Translucent tint of a colour. */\nexport const tint = (color: string, pct: number) => `color-mix(in oklab, ${color} ${pct}%, transparent)`\n/** Opaque tint: the colour mixed over the surface, so it adapts to the theme. */\nexport const over = (color: string, pct: number) => `color-mix(in oklab, ${color} ${pct}%, var(--surface))`\n/** Text colour derived from a hue: readable on the surface in both themes. */\nexport const ink = (color: string, pct = 78) => `color-mix(in oklab, ${color} ${pct}%, var(--fg))`\n\n/* ------------------------------------------------------------------ */\n/*  Text metrics                                                      */\n/* ------------------------------------------------------------------ */\n\nconst FONT = '\"Inter Variable\", Inter, ui-sans-serif, system-ui, sans-serif'\nlet ctx: CanvasRenderingContext2D | null | undefined\nconst widths = new Map<string, number>()\n\n/**\n * Rendered width of a string in the kit font. `num` measures with tabular\n * figures and the tighter tracking of the `num` utility.\n */\nexport function textW(s: string, px = 12, weight = 400, num = false): number {\n  if (!s) return 0\n  const approx = s.length * px * (weight >= 600 ? 0.58 : 0.55)\n  if (typeof document === 'undefined') return approx\n  const key = `${weight}|${px}|${num ? 1 : 0}|${s}`\n  const hit = widths.get(key)\n  if (hit != null) return hit\n  if (ctx === undefined) ctx = document.createElement('canvas').getContext('2d')\n  if (!ctx) return approx\n  ctx.font = `${weight} ${px}px ${FONT}`\n  let w = ctx.measureText(num ? s.replace(/\\d/g, '0') : s).width\n  if (num) w -= 0.02 * px * s.length\n  if (widths.size > 4000) widths.clear()\n  widths.set(key, w)\n  return w\n}\n\n/** Re-renders once web fonts have loaded, so measured labels are laid out again. */\nexport function useFontsReady() {\n  const [, bump] = useState(0)\n  useEffect(() => {\n    const fonts = typeof document !== 'undefined' ? document.fonts : undefined\n    if (!fonts) return\n    let live = true\n    const done = () => {\n      widths.clear()\n      if (live) bump((n) => n + 1)\n    }\n    if (fonts.status !== 'loaded') fonts.ready.then(done)\n    fonts.addEventListener?.('loadingdone', done)\n    return () => {\n      live = false\n      fonts.removeEventListener?.('loadingdone', done)\n    }\n  }, [])\n}\n\n/** Truncate with an ellipsis so the string fits `max` px. */\nexport function fitLabel(s: string, max: number, px = 12, 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/** Break a label into at most `lines` lines of `max` px; the last is ellipsised. */\nexport function wrapLabel(s: string, max: number, px = 11, lines = 2, weight = 400): string[] {\n  if (textW(s, px, weight) <= max) return [s]\n  const words = s.split(/\\s+/)\n  const out: string[] = []\n  let cur = ''\n  for (let i = 0; i < words.length; i++) {\n    const next = cur ? cur + ' ' + words[i] : words[i]\n    if (cur && textW(next, px, weight) > max) {\n      out.push(cur)\n      cur = words[i]\n      if (out.length === lines - 1) {\n        cur = words.slice(i).join(' ')\n        break\n      }\n    } else cur = next\n  }\n  out.push(cur)\n  return out.map((l) => fitLabel(l, max, px, weight))\n}\n\n/**\n * 1-D label dodging: returns positions at least `gap` apart inside [lo, hi],\n * moving each label 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 out = new Array<number>(want.length)\n  type Block = { start: number; ids: number[] }\n  const blocks: Block[] = []\n  for (const i of order) {\n    blocks.push({ start: want[i], ids: [i] })\n    while (blocks.length > 1) {\n      const b = blocks[blocks.length - 1]\n      const a = blocks[blocks.length - 2]\n      if (a.start + a.ids.length * gap <= b.start) break\n      const ids = [...a.ids, ...b.ids]\n      const mean = ids.reduce((s, k) => s + want[k], 0) / ids.length\n      blocks.splice(blocks.length - 2, 2, { ids, start: mean - ((ids.length - 1) * gap) / 2 })\n    }\n  }\n  for (const b of blocks) b.ids.forEach((k, j) => (out[k] = b.start + j * gap))\n  for (let j = 0; j < order.length; j++) {\n    const k = order[j]\n    out[k] = Math.max(out[k], lo + j * gap, j > 0 ? out[order[j - 1]] + gap : -Infinity)\n  }\n  for (let j = order.length - 1; j >= 0; j--) {\n    const k = order[j]\n    out[k] = Math.min(out[k], hi - (order.length - 1 - j) * gap, j < order.length - 1 ? out[order[j + 1]] - gap : Infinity)\n  }\n  return out\n}\n\n/* ------------------------------------------------------------------ */\n/*  Formatting                                                        */\n/* ------------------------------------------------------------------ */\n\n/** Typographic minus instead of a hyphen. */\nexport const minus = (s: string) => s.replace(/-(?=[\\d\\p{Sc}.,])/u, '−')\n\n/**\n * A sensible default value format for a set of values: compact above 10K,\n * integers when the data is integral, money when a currency was asked for.\n */\nexport function autoFormat(f: Formatter, values: number[], currency?: string, locale?: string): (v: number) => string {\n  const finite = values.filter((v) => Number.isFinite(v))\n  const max = finite.reduce((m, v) => Math.max(m, Math.abs(v)), 0)\n  const min = finite.reduce((m, v) => (v === 0 ? m : Math.min(m, Math.abs(v))), Infinity)\n  const ints = finite.every((v) => Number.isInteger(v))\n  if (max >= 10000) {\n    // Values that sit close together need a second decimal to stay distinct ($4.99M vs $5M).\n    const tight = finite.length > 1 && max - min < max * 0.35\n    if (!tight) return currency ? (v) => minus(f.currencyCompact(v)) : (v) => minus(f.compact(v))\n    const nf = compact2(locale, currency)\n    return (v) => minus(nf.format(v))\n  }\n  if (currency) return (v) => minus(f.currency(v, ints ? 0 : 2))\n  const digits = ints ? 0 : max < 10 ? 2 : 1\n  return (v) => minus(f.number(v, digits))\n}\n\nconst compactCache = new Map<string, Intl.NumberFormat>()\nfunction compact2(locale = 'en-US', currency?: string) {\n  const key = `${locale}|${currency ?? ''}`\n  let nf = compactCache.get(key)\n  if (!nf) compactCache.set(key, (nf = new Intl.NumberFormat(locale, { notation: 'compact', maximumFractionDigits: 2, ...(currency ? { style: 'currency', currency } : {}) })))\n  return nf\n}\n\n/**\n * Tick-label version of a value format: drops a decimal part that is all zeros\n * (5.0 h → 5 h) without touching thousands separators.\n */\nexport function tickFormat(f: Formatter, fmt: (v: number) => string): (v: number) => string {\n  const dec = f.number(1.5, 1).replace(/\\d/g, '') || '.'\n  const re = new RegExp(`\\\\${dec}0+(?=\\\\D*$)`)\n  return (v) => fmt(v).replace(re, '')\n}\n\n/** Signed value: +1.2K / −340 / 0. */\nexport const signed = (v: number, fmt: (v: number) => string) => (v > 0 ? '+' : v < 0 ? '−' : '') + fmt(Math.abs(v))\n\n/** Signed percentage from a ratio, in the chart's locale: +12.4% / −3.0%. */\nexport const signedPct = (f: Formatter, ratio: number, digits = 1) => (ratio > 0 ? '+' : ratio < 0 ? '−' : '') + f.percent(Math.abs(ratio), digits)\n\n/* ------------------------------------------------------------------ */\n/*  Statistics                                                        */\n/* ------------------------------------------------------------------ */\n\n/** Quantile of an ascending array by linear interpolation (R type 7). */\nexport function quantileSorted(sorted: number[], q: number): number {\n  if (!sorted.length) return NaN\n  const pos = (sorted.length - 1) * q\n  const lo = Math.floor(pos)\n  const hi = Math.ceil(pos)\n  return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo)\n}\n\n/* ------------------------------------------------------------------ */\n/*  Paths                                                             */\n/* ------------------------------------------------------------------ */\n\n/** Monotone cubic path through points (no overshoot between samples). */\nexport function monotonePath(pts: [number, number][]): string {\n  const n = pts.length\n  if (!n) return ''\n  if (n === 1) return `M${pts[0][0]},${pts[0][1]}`\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] || 1))\n  }\n  const t: number[] = [m[0]]\n  for (let i = 1; i < n - 1; i++) t.push(m[i - 1] * m[i] <= 0 ? 0 : (m[i - 1] + m[i]) / 2)\n  t.push(m[n - 2])\n  for (let i = 0; i < n - 1; i++) {\n    if (m[i] === 0) {\n      t[i] = 0\n      t[i + 1] = 0\n      continue\n    }\n    const a = t[i] / m[i]\n    const b = t[i + 1] / m[i]\n    const s = a * a + b * b\n    if (s > 9) {\n      const k = 3 / Math.sqrt(s)\n      t[i] = k * a * m[i]\n      t[i + 1] = k * b * m[i]\n    }\n  }\n  let d = `M${pts[0][0].toFixed(2)},${pts[0][1].toFixed(2)}`\n  for (let i = 0; i < n - 1; i++) {\n    const h = dx[i] / 3\n    d += `C${(pts[i][0] + h).toFixed(2)},${(pts[i][1] + t[i] * h).toFixed(2)} ${(pts[i + 1][0] - h).toFixed(2)},${(pts[i + 1][1] - t[i + 1] * h).toFixed(2)} ${pts[i + 1][0].toFixed(2)},${pts[i + 1][1].toFixed(2)}`\n  }\n  return d\n}\n\n/* ------------------------------------------------------------------ */\n/*  Active mark: pointer (mouse, touch, pen) + keyboard               */\n/* ------------------------------------------------------------------ */\n\n/**\n * One \"active mark\" for a chart, driven by the pointer (through `usePointerHover`,\n * so taps work) or by the arrow keys when the plot has focus. Spread `pointer`\n * on the element whose pixel space `locate` understands and `keys` on the\n * focusable element (usually the same one). A tap outside dismisses a touch readout.\n */\nexport function useActive(root: RefObject<HTMLElement | null>, count: number, locate: (p: HoverPoint) => number | null) {\n  const { point, bind, clear } = usePointerHover<HTMLDivElement>()\n  const [key, setKey] = useState<number | null>(null)\n  const located = point ? locate(point) : null\n  const raw = located ?? key\n  const active = raw != null && raw >= 0 && raw < count ? raw : null\n  const has = point != null\n\n  useEffect(() => {\n    if (!has) return\n    const away = (e: PointerEvent) => {\n      if (root.current && !root.current.contains(e.target as Node)) clear()\n    }\n    document.addEventListener('pointerdown', away)\n    return () => document.removeEventListener('pointerdown', away)\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [has])\n\n  const keys = {\n    tabIndex: 0,\n    onKeyDown: (e: KeyboardEvent<HTMLElement>) => {\n      if (!count) return\n      const cur = active\n      let next: number | null\n      if (e.key === 'ArrowRight' || e.key === 'ArrowDown') next = cur == null ? 0 : Math.min(count - 1, cur + 1)\n      else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') next = cur == null ? count - 1 : Math.max(0, cur - 1)\n      else if (e.key === 'Home') next = 0\n      else if (e.key === 'End') next = count - 1\n      else if (e.key === 'Escape') next = null\n      else return\n      e.preventDefault()\n      clear()\n      setKey(next)\n    },\n    onFocus: (e: FocusEvent<HTMLElement>) => {\n      if (count && e.target === e.currentTarget && e.currentTarget.matches(':focus-visible')) setKey((k) => k ?? 0)\n    },\n    onBlur: () => setKey(null),\n  }\n\n  return { active, point, viaKeys: located == null && key != null, pointer: bind, keys, clear }\n}\n\n/** Class for a focusable plot: keeps the kit focus ring tight to the chart. */\nexport const PLOT_FOCUS = 'rounded-lg outline-none focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-[var(--accent)]'\n\n/* ------------------------------------------------------------------ */\n/*  Small SVG / HTML pieces (createElement: this file is plain .ts)   */\n/* ------------------------------------------------------------------ */\n\n/** Vertical gridlines at a horizontal scale's ticks; the zero line is solid. */\nexport function gridX(scale: LinearScale, y0: number, y1: number, opts: { solidFirst?: boolean } = {}): ReactElement {\n  return createElement(\n    'g',\n    { 'aria-hidden': true },\n    scale.ticks.map((t, i) =>\n      createElement('line', {\n        key: t,\n        x1: crisp(scale(t)),\n        x2: crisp(scale(t)),\n        y1: y0,\n        y2: y1,\n        stroke: t === 0 ? 'var(--border-strong)' : 'var(--border)',\n        strokeDasharray: t === 0 || (opts.solidFirst && i === 0) ? undefined : '3 4',\n      }),\n    ),\n  )\n}\n\n/** Keeps readout labels and values on one line each (the tooltip shrinks near the plot edge otherwise). */\nexport interface TipRow {\n  label: ReactNode\n  value: ReactNode\n  color?: string\n  strong?: boolean\n}\nexport function tipRows(rows: TipRow[]): TipRow[] {\n  const one = (n: ReactNode) => (n == null || n === '' ? n : createElement('span', { className: 'whitespace-nowrap' }, n))\n  return rows.map((r) => ({ ...r, label: one(r.label), value: one(r.value) }))\n}\n\n/** Dashed placeholder shown when a chart has no data. */\nexport function emptyState(label: string, height: number): ReactElement {\n  return createElement(\n    'div',\n    {\n      role: 'status',\n      className: 'flex w-full items-center justify-center rounded-xl border border-dashed border-border-strong text-[12.5px] text-fg-3',\n      style: { height: Math.max(72, height) },\n    },\n    label,\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Time                                                              */\n/* ------------------------------------------------------------------ */\n\nexport const DAY = 86_400_000\nexport const toTime = (d: Date | string | number) => (d instanceof Date ? d.getTime() : new Date(d).getTime())\n\nexport interface TimeTick {\n  t: number\n  /** `major` ticks start a new year (or month, for day-level axes). */\n  major: boolean\n  unit: 'day' | 'month' | 'year'\n}\n\n/** Calendar-aligned ticks (UTC) for a time range, aiming for about `target` ticks. */\nexport function timeTicks(t0: number, t1: number, target = 8): TimeTick[] {\n  const days = (t1 - t0) / DAY\n  const out: TimeTick[] = []\n  const perTick = days / Math.max(1, target)\n  if (perTick < 9) {\n    const step = [1, 2, 7, 14].find((s) => s >= perTick) ?? 14\n    const start = new Date(t0)\n    let t = Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate())\n    if (step >= 7) t -= ((new Date(t).getUTCDay() + 6) % 7) * DAY\n    for (; t <= t1; t += step * DAY) if (t >= t0) out.push({ t, major: new Date(t).getUTCDate() <= step, unit: 'day' })\n    return out\n  }\n  const monthsPer = perTick / 30.44\n  if (monthsPer < 9) {\n    const step = [1, 2, 3, 6].find((s) => s >= monthsPer * 0.8) ?? 6\n    const s = new Date(t0)\n    let y = s.getUTCFullYear()\n    let m = Math.floor(s.getUTCMonth() / step) * step\n    for (;;) {\n      const t = Date.UTC(y, m, 1)\n      if (t > t1) break\n      if (t >= t0) out.push({ t, major: m === 0, unit: 'month' })\n      m += step\n      if (m >= 12) {\n        m -= 12\n        y++\n      }\n    }\n    return out\n  }\n  const step = Math.max(1, Math.round(perTick / 365.25))\n  for (let y = Math.floor(new Date(t0).getUTCFullYear() / step) * step; ; y += step) {\n    const t = Date.UTC(y, 0, 1)\n    if (t > t1) break\n    if (t >= t0) out.push({ t, major: true, unit: 'year' })\n  }\n  return out\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/basic/util-b.ts"
    }
  ],
  "docs": "import { DataTable } from '@/components/klar/charts/basic/DataTable'\nData comes in through props.",
  "categories": [
    "charts",
    "basic",
    "comparison"
  ],
  "meta": {
    "collection": "basic",
    "kind": "comparison",
    "tags": [
      "table",
      "grid",
      "sparkline",
      "heatmap cell",
      "sortable",
      "in-cell bar",
      "leaderboard",
      "report"
    ],
    "standalone": true,
    "export": "DataTable",
    "import": "@/components/klar/charts/basic/DataTable"
  }
}
