{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "basic-timeline",
  "type": "registry:component",
  "title": "Timeline",
  "description": "Events on a time axis with labels staggered above and below so none collide, periods as spans, categories by colour and icon, and a marker for today.",
  "dependencies": [
    "clsx",
    "lucide-react",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "https://klar.run/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/klar/components/charts/basic/Timeline.tsx",
      "content": "import { useEffect, useMemo, useRef, useState, type ReactNode } 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, ChartLegend, ChartTooltip, PALETTE, formatter } from '@/components/klar/charts/basic/core'\nimport { DAY, PLOT_FOCUS, clamp, crisp, emptyState, fitLabel, ink, over, textW, timeTicks, tint, toTime, useActive, useFontsReady, tipRows } from '@/components/klar/charts/basic/util-b'\n\nexport interface TimelineEvent {\n  id?: string\n  /** Start (or the moment, for a point event). ISO strings are read as UTC dates. */\n  date: Date | string | number\n  /** Set an end to draw the event as a span. */\n  end?: Date | string | number\n  label: string\n  /** Id of a category; decides colour and icon. */\n  category?: string\n  /** Extra line in the readout. */\n  description?: string\n}\n\nexport interface TimelineCategory {\n  id: string\n  label: string\n  color?: string\n  /** Small icon (about 12px) drawn inside the marker. */\n  icon?: ReactNode\n}\n\nexport interface TimelineProps {\n  events: TimelineEvent[]\n  categories?: TimelineCategory[]\n  /** Draws a \"today\" marker; events after it are drawn hollow, as planned. */\n  today?: Date | string | number\n  todayLabel?: string\n  /** Time range. Defaults to the events' extent with a little padding. */\n  domain?: [Date | string | number, Date | string | number]\n  /** `fit` squeezes the range into the width; `scroll` keeps `pxPerDay` and scrolls sideways. */\n  mode?: 'fit' | 'scroll'\n  pxPerDay?: number\n  height?: number\n  /** Category legend; click an item to hide that category. */\n  legend?: boolean\n  /** Above this many point events, neighbours closer than ~24px merge into a counted cluster. */\n  clusterAbove?: number\n  locale?: string\n  emptyLabel?: string\n  className?: string\n  ariaLabel?: string\n}\n\n/** Rows for CSV export: one per event, with ISO dates. */\nexport function timelineToRows(events: TimelineEvent[], categories?: TimelineCategory[]) {\n  const iso = (d: Date | string | number) => new Date(toTime(d)).toISOString().slice(0, 10)\n  return [...events]\n    .sort((a, b) => toTime(a.date) - toTime(b.date))\n    .map((e) => ({\n      event: e.label,\n      start: iso(e.date),\n      end: e.end != null ? iso(e.end) : null,\n      category: categories?.find((c) => c.id === e.category)?.label ?? e.category ?? null,\n      description: e.description ?? null,\n    }))\n}\n\ninterface Item {\n  key: string\n  kind: 'point' | 'span' | 'cluster'\n  t: number\n  t1: number\n  x: number\n  x1: number\n  label: string\n  dateText: string\n  color: string\n  cat?: TimelineCategory\n  future: boolean\n  ev: TimelineEvent[]\n  /* layout */\n  lane: number\n  side: 1 | -1\n  level: number\n  placed: boolean\n  flip: boolean\n  bx0: number\n  bx1: number\n  inside: boolean\n  spanLabel: string\n}\n\n/**\n * Timeline: events on a time axis. Point events are dots whose labels are\n * staggered above and below the axis on as many levels as needed to avoid\n * collisions; events with an `end` are spans in lanes under the axis.\n * Categories set colour and icon, a marker shows today (later events are drawn\n * hollow), and each event reads out on hover, tap or the arrow keys. `fit`\n * mode squeezes the range into the width; `scroll` mode keeps a fixed scale and\n * scrolls sideways.\n * Data: `{ date, end?, label, category?, description? }[]`.\n *\n * Scale: every event is one SVG group. Past `clusterAbove` point events (default\n * 120) close neighbours merge into counted clusters, and labels that cannot be\n * placed without overlap are left to the readout, so thousands of events stay\n * usable; beyond ~5,000, filter or aggregate before passing them in.\n */\nexport function Timeline({\n  events,\n  categories = [],\n  today,\n  todayLabel = 'Today',\n  domain,\n  mode = 'fit',\n  pxPerDay = 7,\n  height = 340,\n  legend = true,\n  clusterAbove = 120,\n  locale,\n  emptyLabel = 'No events',\n  className,\n  ariaLabel = 'Timeline',\n}: TimelineProps) {\n  useFontsReady()\n  const [ref, { width }] = useMeasure()\n  const scroller = useRef<HTMLDivElement>(null)\n  const [sl, setSl] = useState(0)\n  const [hidden, setHidden] = useState<Set<string>>(() => new Set())\n  const [legendCat, setLegendCat] = useState<string | null>(null)\n  const f = formatter(locale)\n  const scroll = mode === 'scroll'\n\n  const catOf = (id?: string) => categories.find((c) => c.id === id)\n  const colorOf = (id?: string) => {\n    const i = categories.findIndex((c) => c.id === id)\n    return i < 0 ? 'var(--accent)' : (categories[i].color ?? PALETTE[i % PALETTE.length])\n  }\n  const dfmt = (t: number, year = true) => f.date(t, { month: 'short', day: 'numeric', ...(year ? { year: 'numeric' } : {}), timeZone: 'UTC' })\n\n  const shown = useMemo(() => events.filter((e) => !e.category || !hidden.has(e.category)).sort((a, b) => toTime(a.date) - toTime(b.date)), [events, hidden])\n  const times = events.flatMap((e) => [toTime(e.date), e.end != null ? toTime(e.end) : toTime(e.date)])\n  const now = today != null ? toTime(today) : null\n  const rawLo = domain ? toTime(domain[0]) : Math.min(...times, ...(now != null ? [now] : []))\n  const rawHi = domain ? toTime(domain[1]) : Math.max(...times, ...(now != null ? [now] : []))\n  const padT = domain ? 0 : Math.max(DAY, (rawHi - rawLo) * 0.03)\n  const t0 = rawLo - padT\n  const t1 = rawHi + padT\n  const days = (t1 - t0) / DAY\n\n  const W = scroll ? Math.max(width, Math.round(days * pxPerDay)) : width\n  const padX = 14\n  const x = (t: number) => padX + ((t - t0) / (t1 - t0 || 1)) * (W - padX * 2)\n\n  /* ---------- layout ---------- */\n  const topPad = 22\n  const axisH = 24\n  const laneH = 24\n  const LEVEL = 34\n\n  const layout = useMemo(() => {\n    if (W <= 0) return { items: [] as Item[], lanes: 0, axisY: 0, belowY: 0 }\n    const base = (e: TimelineEvent, i: number): Item => {\n      const t = toTime(e.date)\n      const te = e.end != null ? toTime(e.end) : t\n      const span = e.end != null && te > t\n      return {\n        key: e.id ?? `${e.label}-${i}`,\n        kind: span ? 'span' : 'point',\n        t,\n        t1: te,\n        x: x(t),\n        x1: x(te),\n        label: e.label,\n        dateText: span ? `${dfmt(t, false)} – ${dfmt(te, false)}` : dfmt(t, false),\n        color: colorOf(e.category),\n        cat: catOf(e.category),\n        future: now != null && t > now,\n        ev: [e],\n        lane: 0,\n        side: 1,\n        level: 0,\n        placed: false,\n        flip: false,\n        bx0: 0,\n        bx1: 0,\n        inside: false,\n        spanLabel: '',\n      }\n    }\n    let items = shown.map(base)\n    const spans = items.filter((i) => i.kind === 'span')\n    let points = items.filter((i) => i.kind === 'point')\n\n    // Cluster dense point events.\n    if (points.length > clusterAbove) {\n      const merged: Item[] = []\n      for (const p of points) {\n        const last = merged[merged.length - 1]\n        if (last && p.x - last.x < 24) {\n          last.ev.push(...p.ev)\n          last.t1 = p.t\n          last.x1 = p.x\n          last.kind = 'cluster'\n        } else merged.push({ ...p, ev: [...p.ev] })\n      }\n      for (const m of merged)\n        if (m.kind === 'cluster') {\n          m.x = (m.x + m.x1) / 2\n          m.label = `${f.number(m.ev.length)} events`\n          m.dateText = `${dfmt(m.t, false)} – ${dfmt(m.t1, false)}`\n          const cats = new Set(m.ev.map((e) => e.category))\n          m.color = cats.size === 1 ? colorOf(m.ev[0].category) : 'var(--fg-2)'\n          m.cat = undefined\n        }\n      points = merged\n    }\n\n    // Spans: greedy lanes; the label goes inside when it fits, else just after.\n    const laneEnd: number[] = []\n    for (const s of spans) {\n      const w = s.x1 - s.x\n      const lw = textW(s.label, 11.5, 500)\n      s.inside = lw + 16 <= w\n      if (!s.inside) {\n        // Not enough room inside: put it after the span, or squeeze it inside if that shows more.\n        const after = fitLabel(s.label, Math.max(0, Math.min(170, W - s.x1 - 10)), 11.5, 500)\n        const within = fitLabel(s.label, Math.max(0, w - 16), 11.5, 500)\n        if (after.length < s.label.length && within.length > after.length) s.inside = true\n        s.spanLabel = s.inside ? within : after\n      } else s.spanLabel = s.label\n      if (s.spanLabel === '…') s.spanLabel = ''\n      const outW = s.inside || !s.spanLabel ? 0 : textW(s.spanLabel, 11.5, 500) + 8\n      let lane = laneEnd.findIndex((end) => end + 10 <= s.x)\n      if (lane < 0) lane = laneEnd.length\n      laneEnd[lane] = s.x1 + outW\n      s.lane = lane\n      s.placed = true\n    }\n    const lanes = laneEnd.length\n    const spanBand = lanes ? lanes * laneH + 8 : 0\n    const free = height - topPad - axisH - spanBand\n    const aboveH = Math.round(free * (lanes ? 0.54 : 0.5))\n    const axisY = topPad + aboveH\n    const belowH = free - aboveH\n    const levels: Record<number, number> = { 1: Math.max(1, Math.floor((aboveH - 14) / LEVEL)), [-1]: Math.max(1, Math.floor((belowH - 12) / LEVEL)) }\n\n    // Points: stagger labels above / below on the first level without a collision.\n    const boxes: Record<number, { x0: number; x1: number; level: number }[]> = { 1: [], [-1]: [] }\n    const leaders: Record<number, { x: number; level: number }[]> = { 1: [], [-1]: [] }\n    const free1 = (side: 1 | -1, level: number, b0: number, b1: number, px: number) =>\n      !boxes[side].some((b) => (b.level === level && b0 < b.x1 + 10 && b1 > b.x0 - 10) || (b.level < level && px > b.x0 - 3 && px < b.x1 + 3)) && !leaders[side].some((l) => l.level > level && l.x > b0 - 3 && l.x < b1 + 3)\n    points.forEach((p, i) => {\n      const text = fitLabel(p.label, Math.min(190, Math.max(60, W - p.x - 12, p.x - 12)), 12, 500)\n      const w = Math.max(textW(text, 12, 500), textW(p.dateText, 10.5, 400, true)) + 7\n      const flip = p.x + w > W - 2 && p.x - w >= 0\n      const b0 = flip ? p.x - w : p.x\n      const b1 = flip ? p.x : p.x + w\n      const pref: 1 | -1 = i % 2 === 0 ? 1 : -1\n      const maxL = Math.max(levels[1], levels[-1])\n      search: for (let level = 0; level < maxL; level++) {\n        for (const side of [pref, -pref as 1 | -1]) {\n          if (level >= levels[side]) continue\n          if (free1(side, level, b0, b1, p.x)) {\n            Object.assign(p, { side, level, placed: true, flip, bx0: b0, bx1: b1, spanLabel: text })\n            boxes[side].push({ x0: b0, x1: b1, level })\n            leaders[side].push({ x: p.x, level })\n            break search\n          }\n        }\n      }\n    })\n    items = [...spans, ...points].sort((a, b) => a.t - b.t)\n    // Centre what was actually used, so a sparse timeline does not float in empty space.\n    const used = (side: 1 | -1) => (boxes[side].length ? (Math.max(...boxes[side].map((b) => b.level)) + 1) * LEVEL + 14 : 14)\n    const slack = free - used(1) - used(-1)\n    const ay = slack > 0 ? Math.round(topPad + slack / 2 + used(1)) : axisY\n    return { items, lanes, axisY: ay, belowY: ay + spanBand }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [shown, W, height, t0, t1, now, clusterAbove, locale, categories])\n\n  const { items, axisY, belowY } = layout\n  const labelY = (it: Item) => (it.side === 1 ? axisY - 27 - it.level * LEVEL : belowY + 26 + it.level * LEVEL)\n  const spanY = (it: Item) => axisY + 9 + it.lane * laneH\n\n  const { active, pointer, keys, viaKeys } = useActive(ref, items.length, (p) => {\n    let best: number | null = null\n    let bestD = Infinity\n    items.forEach((it, i) => {\n      let d = Infinity\n      if (it.kind === 'span') {\n        const y = spanY(it)\n        if (p.x >= it.x - 3 && p.x <= Math.max(it.x1, it.x + 6) + (it.inside ? 3 : textW(it.spanLabel, 11.5, 500) + 10) && p.y >= y - 3 && p.y <= y + 21) d = 0\n      } else {\n        const dd = Math.hypot(p.x - it.x, p.y - axisY)\n        if (dd <= 13) d = dd\n        if (it.placed) {\n          const ly = labelY(it)\n          if (p.x >= it.bx0 - 4 && p.x <= it.bx1 + 4 && p.y >= ly - 16 && p.y <= ly + 18) d = Math.min(d, 1)\n          // the leader itself\n          const [ya, yb] = it.side === 1 ? [ly, axisY] : [axisY, ly]\n          if (Math.abs(p.x - it.x) <= 5 && p.y >= ya && p.y <= yb) d = Math.min(d, 2 + Math.abs(p.x - it.x))\n        }\n      }\n      if (d < bestD) {\n        bestD = d\n        best = i\n      }\n    })\n    return best\n  })\n\n  // Scroll mode: start with today (or the end) in view, and follow keyboard focus.\n  const didInit = useRef(false)\n  useEffect(() => {\n    const el = scroller.current\n    if (!el || !scroll || didInit.current || width <= 0 || W <= width) return\n    didInit.current = true\n    el.scrollLeft = clamp((now != null ? x(now) : W) - width * 0.68, 0, W - width)\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [scroll, width, W])\n  useEffect(() => {\n    const el = scroller.current\n    if (!el || !scroll || !viaKeys || active == null) return\n    const it = items[active]\n    if (it.x < el.scrollLeft + 40 || it.x > el.scrollLeft + width - 40) el.scrollTo({ left: clamp(it.x - width / 2, 0, W - width), behavior: 'smooth' })\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [active, viaKeys])\n\n  if (!events.length) return emptyState(emptyLabel, height)\n\n  const ticks = W > 0 ? timeTicks(t0, t1, Math.max(2, Math.floor(W / 96))) : []\n  const tickText = (t: (typeof ticks)[number], i: number) =>\n    t.unit === 'year'\n      ? f.date(t.t, { year: 'numeric', timeZone: 'UTC' })\n      : t.unit === 'month'\n        ? f.date(t.t, t.major || i === 0 ? { month: 'short', year: 'numeric', timeZone: 'UTC' } : { month: 'short', timeZone: 'UTC' })\n        : f.date(t.t, { month: 'short', day: 'numeric', timeZone: 'UTC' })\n  const a = active != null ? items[active] : null\n  const dimmed = (it: Item) => (a ? a !== it : legendCat != null && !it.ev.some((e) => e.category === legendCat))\n  const plotBottom = height - axisH\n\n  const counts = new Map<string, number>()\n  for (const e of events) if (e.category) counts.set(e.category, (counts.get(e.category) ?? 0) + 1)\n\n  const duration = (it: Item) => {\n    const d = Math.round((it.t1 - it.t) / DAY)\n    return d >= 14 && d % 7 === 0 ? `${f.number(d / 7)} weeks` : `${f.number(d)} day${d === 1 ? '' : 's'}`\n  }\n\n  const plot = (\n    <div {...pointer} className=\"relative select-none\" style={{ width: scroll ? W : '100%', height, ...pointer.style, ...(scroll ? { touchAction: 'pan-x pan-y' } : null) }}>\n      {W > 0 && (\n        <svg width={W} height={height} className=\"block overflow-visible\" aria-hidden>\n          {/* time grid */}\n          {ticks.map((t) => (\n            <line key={t.t} x1={crisp(x(t.t))} x2={crisp(x(t.t))} y1={topPad - 6} y2={plotBottom + 4} stroke=\"var(--border)\" strokeDasharray={t.major ? undefined : '3 4'} />\n          ))}\n          <AxisX y={height - 6} labels={ticks.map((t, i) => ({ x: x(t.t) + 5, text: tickText(t, i), anchor: 'start' as const })).filter((l) => l.x + textW(l.text, 11) <= W)} minGap={10} />\n\n          {/* today */}\n          {now != null && now >= t0 && now <= t1 && (\n            <g>\n              <rect x={x(now)} y={topPad - 6} width={Math.max(0, W - x(now))} height={plotBottom + 10 - topPad} fill=\"var(--surface-2)\" opacity={0.55} />\n              <line x1={crisp(x(now))} x2={crisp(x(now))} y1={topPad - 6} y2={plotBottom + 4} stroke=\"var(--accent)\" strokeWidth={1.25} />\n            </g>\n          )}\n\n          {/* leaders */}\n          {items.map((it) =>\n            it.kind !== 'span' && it.placed ? (\n              <line\n                key={it.key}\n                x1={crisp(it.x)}\n                x2={crisp(it.x)}\n                y1={axisY}\n                y2={it.side === 1 ? labelY(it) - 11 : labelY(it) + 15}\n                stroke={a === it ? it.color : 'var(--border-strong)'}\n                opacity={dimmed(it) ? 0.5 : 1}\n                style={{ transition: 'opacity .15s' }}\n              />\n            ) : null,\n          )}\n\n          {/* axis */}\n          <line x1={0} x2={W} y1={crisp(axisY)} y2={crisp(axisY)} stroke=\"var(--fg-4)\" />\n\n          {/* spans */}\n          {items.map((it, i) => {\n            if (it.kind !== 'span') return null\n            const y = spanY(it)\n            const w = Math.max(6, it.x1 - it.x)\n            const on = a === it\n            return (\n              <g key={it.key} opacity={dimmed(it) ? 0.4 : 1} style={{ transition: 'opacity .15s' }}>\n                <g className=\"anim-grow-x\" style={{ transformBox: 'fill-box', transformOrigin: 'left', animationDelay: `${i * 25}ms` }}>\n                  <rect x={it.x} y={y} width={w} height={18} rx={5} fill={over(it.color, on ? 30 : 18)} stroke={it.future ? it.color : 'none'} strokeDasharray={it.future ? '3 2' : undefined} strokeOpacity={0.7} />\n                  <rect x={it.x} y={y} width={3} height={18} rx={1.5} fill={it.color} />\n                </g>\n                {it.spanLabel && (\n                  <text x={it.inside ? it.x + 10 : it.x + w + 7} y={y + 13} className=\"anim-fade text-[11.5px] font-medium\" fill={it.inside ? ink(it.color, 62) : 'var(--fg-2)'}>\n                    {it.spanLabel}\n                  </text>\n                )}\n              </g>\n            )\n          })}\n\n          {/* points */}\n          {items.map((it, i) => {\n            if (it.kind === 'span') return null\n            const on = a === it\n            const big = it.kind === 'cluster' || !!it.cat?.icon\n            const ly = labelY(it)\n            return (\n              <g key={it.key} opacity={dimmed(it) ? 0.4 : 1} style={{ transition: 'opacity .15s' }}>\n                <g className=\"anim-fade\" style={{ animationDelay: `${Math.min(600, i * 25)}ms` }}>\n                  {on && <circle cx={it.x} cy={axisY} r={big ? 15 : 10.5} fill={tint(it.color, 18)} />}\n                  {big ? (\n                    <circle cx={it.x} cy={axisY} r={10} fill={over(it.color, it.future ? 0 : 16)} stroke={it.color} strokeWidth={1.5} strokeDasharray={it.future ? '3 2' : undefined} />\n                  ) : (\n                    <circle cx={it.x} cy={axisY} r={5} fill={it.future ? 'var(--surface)' : it.color} stroke={it.future ? it.color : 'var(--surface)'} strokeWidth={it.future ? 1.75 : 2} />\n                  )}\n                  {it.kind === 'cluster' && (\n                    <text x={it.x} y={axisY + 3.5} textAnchor=\"middle\" className=\"num text-[9.5px] font-semibold\" fill={ink(it.color, 70)}>\n                      {it.ev.length > 999 ? f.compact(it.ev.length) : it.ev.length}\n                    </text>\n                  )}\n                  {it.placed && (\n                    <g>\n                      <text x={it.flip ? it.x - 7 : it.x + 7} y={ly} textAnchor={it.flip ? 'end' : 'start'} className=\"fill-fg text-[12px] font-medium\" stroke=\"var(--surface)\" strokeWidth={3} paintOrder=\"stroke\">\n                        {it.spanLabel}\n                      </text>\n                      <text x={it.flip ? it.x - 7 : it.x + 7} y={ly + 13.5} textAnchor={it.flip ? 'end' : 'start'} className=\"num fill-fg-3 text-[10.5px]\" stroke=\"var(--surface)\" strokeWidth={3} paintOrder=\"stroke\">\n                        {it.dateText}\n                      </text>\n                    </g>\n                  )}\n                </g>\n              </g>\n            )\n          })}\n\n          {/* today tag */}\n          {now != null && now >= t0 && now <= t1 && (\n            <g>\n              {(() => {\n                const w = Math.round(textW(todayLabel, 10.5, 600) + 12)\n                const tx = clamp(Math.round(x(now) - w / 2), 0, W - w)\n                return (\n                  <>\n                    <rect x={tx} y={0} width={w} height={17} rx={5} fill=\"var(--accent)\" />\n                    <text x={tx + w / 2} y={12} textAnchor=\"middle\" className=\"text-[10.5px] font-semibold\" fill=\"var(--accent-fg)\">\n                      {todayLabel}\n                    </text>\n                  </>\n                )\n              })()}\n            </g>\n          )}\n        </svg>\n      )}\n      {/* category icons sit in the markers */}\n      {items.map((it) =>\n        it.kind === 'point' && it.cat?.icon ? (\n          <span key={it.key} aria-hidden className=\"pointer-events-none absolute flex size-5 items-center justify-center\" style={{ left: it.x - 10, top: axisY - 10, color: ink(it.color, 75), opacity: dimmed(it) ? 0.4 : 1 }}>\n            {it.cat.icon}\n          </span>\n        ) : null,\n      )}\n    </div>\n  )\n\n  return (\n    <div role=\"figure\" aria-label={ariaLabel} className={cn('w-full', className)}>\n      {legend && categories.length > 0 && (\n        <ChartLegend\n          className=\"mb-3\"\n          items={categories.map((c) => ({ id: c.id, label: c.label, color: colorOf(c.id), value: f.number(counts.get(c.id) ?? 0) }))}\n          hidden={hidden}\n          active={legendCat}\n          onHover={setLegendCat}\n          onToggle={(id) =>\n            setHidden((h) => {\n              const n = new Set(h)\n              if (n.has(id)) n.delete(id)\n              else n.add(id)\n              return n\n            })\n          }\n        />\n      )}\n      <div ref={ref} className=\"relative w-full\">\n        <div\n          ref={scroller}\n          {...keys}\n          role=\"group\"\n          aria-label={`${ariaLabel}. Use the arrow keys to step through ${f.number(items.length)} events in date order.`}\n          onScroll={scroll ? (e) => setSl(e.currentTarget.scrollLeft) : undefined}\n          className={cn('w-full', PLOT_FOCUS, scroll && 'scroll-thin overflow-x-auto overflow-y-hidden pb-1')}\n        >\n          {plot}\n        </div>\n        {a && width > 0 && (\n          <ChartTooltip\n            x={clamp((a.kind === 'span' ? Math.max(a.x1, a.x + 6) + (a.inside ? 0 : textW(a.spanLabel, 11.5, 500) + 8) : a.x + (a.cat?.icon || a.kind === 'cluster' ? 6 : 0)) - (scroll ? sl : 0), 0, width)}\n            y={a.kind === 'span' ? spanY(a) + 9 : axisY}\n            containerWidth={width}\n            width={214}\n            title={a.kind === 'cluster' ? a.label : (a.cat?.label ?? (a.kind === 'span' ? 'Period' : 'Event'))}\n            rows={tipRows(\n              a.kind === 'cluster'\n                ? [...a.ev.slice(0, 5).map((e) => ({ label: fitLabel(e.label, 120, 12.5), value: dfmt(toTime(e.date), false), color: colorOf(e.category), strong: false })), ...(a.ev.length > 5 ? [{ label: `+ ${f.number(a.ev.length - 5)} more`, value: '', strong: false }] : [])]\n                : a.kind === 'span'\n                  ? [\n                      { label: fitLabel(a.label, 190, 12.5), value: '', color: a.color },\n                      { label: 'Starts', value: dfmt(a.t), strong: false },\n                      { label: 'Ends', value: dfmt(a.t1), strong: false },\n                      { label: 'Duration', value: duration(a), strong: false },\n                    ]\n                  : [\n                      { label: fitLabel(a.label, 190, 12.5), value: '', color: a.color },\n                      { label: 'Date', value: dfmt(a.t), strong: false },\n                      ...(now != null ? [{ label: a.future ? 'In' : 'Ago', value: `${f.number(Math.abs(Math.round((a.t - now) / DAY)))} days`, strong: false }] : []),\n                    ]\n            )}\n            footer={a.ev.length === 1 ? a.ev[0].description : undefined}\n          />\n        )}\n      </div>\n      <ChartDataTable\n        caption={ariaLabel}\n        columns={[\n          { key: 'event', label: 'Event' },\n          { key: 'start', label: 'Start', align: 'left' },\n          { key: 'end', label: 'End', align: 'left', format: (v) => (v == null ? '–' : String(v)) },\n          { key: 'category', label: 'Category', align: 'left', format: (v) => (v == null ? '–' : String(v)) },\n          { key: 'description', label: 'Description', align: 'left', format: (v) => (v == null ? '' : String(v)) },\n        ]}\n        rows={timelineToRows(events, categories)}\n      />\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/basic/Timeline.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-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"
    },
    {
      "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 { Timeline } from '@/components/klar/charts/basic/Timeline'\nData comes in through props.",
  "categories": [
    "charts",
    "basic",
    "schedule"
  ],
  "meta": {
    "collection": "basic",
    "kind": "schedule",
    "tags": [
      "timeline",
      "events",
      "milestones",
      "roadmap",
      "releases",
      "incidents",
      "history",
      "schedule"
    ],
    "standalone": true,
    "export": "Timeline",
    "import": "@/components/klar/charts/basic/Timeline"
  }
}
