{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tech-gantt",
  "type": "registry:component",
  "title": "Dependency Gantt",
  "description": "A project plan with finish-to-start arrows and the computed critical path, so you can see which late task moves the launch date.",
  "dependencies": [
    "clsx",
    "lucide-react",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "https://klar.run/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/klar/components/charts/tech/DependencyGantt.tsx",
      "content": "import { useId, useMemo, useState } 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 { Tip, TipRow, TipRule, TipTitle } from '@/components/klar/charts/tech/ui'\nimport { CATEGORICAL, fitText, FOCUS_RING, mix, stepIndex, techFormat, usePointer } from '@/components/klar/charts/tech/util'\n\nexport interface GanttTask {\n  id: string\n  name: string\n  /** Workstream id; tasks are grouped and coloured by it. */\n  stream: string\n  /** First day, `YYYY-MM-DD`. */\n  start: string\n  /** Last day (inclusive), `YYYY-MM-DD`. Ignored for milestones. */\n  end?: string\n  /** 0..1 */\n  progress?: number\n  /** Ids of tasks that must finish before this one starts (finish → start). */\n  deps?: string[]\n  milestone?: boolean\n  owner?: string\n}\n\nexport interface GanttStream {\n  id: string\n  label: string\n  color?: string\n}\n\n/** A stretch of non-working days, e.g. a change freeze or holidays. */\nexport interface GanttBlackout {\n  start: string\n  end: string\n  label?: string\n}\n\nconst DAY = 86400000\nconst MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\nconst toDay = (s: string) => {\n  const [y, m, d] = s.split('-').map(Number)\n  return Math.round(Date.UTC(y, m - 1, d) / DAY)\n}\nconst dateOf = (n: number) => new Date(n * DAY)\nconst dow = (n: number) => dateOf(n).getUTCDay()\nconst short = (n: number) => `${MON[dateOf(n).getUTCMonth()]} ${dateOf(n).getUTCDate()}`\n\n/** Rounded orthogonal polyline. */\nfunction elbow(pts: [number, number][], r = 4) {\n  let d = `M${pts[0][0]},${pts[0][1]}`\n  for (let i = 1; i < pts.length - 1; i++) {\n    const [x0, y0] = pts[i - 1]\n    const [x1, y1] = pts[i]\n    const [x2, y2] = pts[i + 1]\n    const l1 = Math.hypot(x1 - x0, y1 - y0)\n    const l2 = Math.hypot(x2 - x1, y2 - y1)\n    const rr = Math.min(r, l1 / 2, l2 / 2)\n    const ax = x1 - ((x1 - x0) / (l1 || 1)) * rr\n    const ay = y1 - ((y1 - y0) / (l1 || 1)) * rr\n    const bx = x1 + ((x2 - x1) / (l2 || 1)) * rr\n    const by = y1 + ((y2 - y1) / (l2 || 1)) * rr\n    d += `L${ax},${ay}Q${x1},${y1} ${bx},${by}`\n  }\n  const last = pts[pts.length - 1]\n  return d + `L${last[0]},${last[1]}`\n}\n\n/** One row per task (dates, stream, progress, dependencies) for CSV export. */\n// oxlint-disable-next-line react/only-export-components -- CSV rows helper lives next to its chart\nexport function dependencyGanttToRows(tasks: GanttTask[], streams?: GanttStream[]) {\n  return tasks.map((t) => ({\n    task: t.name,\n    stream: streams?.find((s) => s.id === t.stream)?.label ?? t.stream,\n    start: t.start,\n    end: t.milestone ? t.start : (t.end ?? t.start),\n    milestone: !!t.milestone,\n    progress: t.progress ?? 0,\n    dependsOn: (t.deps ?? []).map((d) => tasks.find((q) => q.id === d)?.name ?? d).join('; '),\n    owner: t.owner ?? '',\n  }))\n}\n\n/**\n * Project plan as a Gantt chart: tasks grouped by workstream, finish→start\n * dependency arrows routed with elbows, the critical path computed (backward\n * pass over working days) and highlighted, milestone diamonds, a today line,\n * per-task progress and weekend / blackout shading. Hover a task for its dates,\n * slack and dependencies.\n *\n * Data: `tasks` ({ id, name, stream, start, end, progress, deps, milestone }),\n * optional `streams` for labels and colours.\n *\n * Pointer, touch and keyboard: hover or tap a task; focus the chart and use ↑/↓ (or ←/→) to\n * step through tasks, Esc to clear. Scale: comfortable to ~200 tasks over ~1 year (one row per task;\n * working-day maths walks each day).\n */\nexport function DependencyGantt({\n  tasks,\n  streams,\n  today,\n  blackouts = [],\n  rowHeight = 28,\n  labelWidth,\n  critical: showCritical = true,\n  weekends = true,\n  locale,\n  ariaLabel,\n  className,\n}: {\n  tasks: GanttTask[]\n  streams?: GanttStream[]\n  /** `YYYY-MM-DD` */\n  today?: string\n  blackouts?: GanttBlackout[]\n  rowHeight?: number\n  labelWidth?: number\n  /** Highlight the critical path. */\n  critical?: boolean\n  /** Shade Saturdays and Sundays. */\n  weekends?: boolean\n  /** BCP 47 locale for dates and numbers (default: English short months). */\n  locale?: string\n  /** Accessible name; defaults to a description of the plan. */\n  ariaLabel?: string\n  className?: string\n}) {\n  const uid = useId().replace(/:/g, '')\n  const [ref, { width: W }] = useMeasure()\n  const [pos, onMove, setPos] = usePointer()\n  const tf = techFormat(locale)\n  const day = (n: number) => tf.day(n * DAY)\n  const monthYear = useMemo(() => (locale ? new Intl.DateTimeFormat(locale, { month: 'short', year: 'numeric', timeZone: 'UTC' }) : null), [locale])\n  const [hover, setHover] = useState<string | null>(null)\n\n  const model = useMemo(() => {\n    const black = blackouts.map((b) => [toDay(b.start), toDay(b.end)] as const)\n    const working = (d: number) => dow(d) !== 0 && dow(d) !== 6 && !black.some(([a, b]) => d >= a && d <= b)\n    const workBetween = (a: number, b: number) => {\n      let n = 0\n      for (let d = a; d < b; d++) if (working(d)) n++\n      return n\n    }\n    const T = tasks.map((t) => {\n      const s = toDay(t.start)\n      const e = t.milestone ? s : toDay(t.end ?? t.start) + 1 // exclusive\n      return { ...t, s, e, dur: e - s }\n    })\n    const byId = new Map(T.map((t) => [t.id, t]))\n    const succ = new Map<string, string[]>(T.map((t) => [t.id, []]))\n    for (const t of T) for (const d of t.deps ?? []) succ.get(d)?.push(t.id)\n    const projEnd = Math.max(...T.map((t) => t.e))\n    // Backward pass in reverse topological order.\n    const order: string[] = []\n    const seen = new Set<string>()\n    const visit = (id: string) => {\n      if (seen.has(id)) return\n      seen.add(id)\n      for (const n of succ.get(id) ?? []) visit(n)\n      order.push(id)\n    }\n    for (const t of T) visit(t.id)\n    // Step back over `n` working days from an exclusive finish.\n    const backWork = (lf: number, n: number) => {\n      let d = lf\n      for (let c = 0; c < n; ) if (working(--d)) c++\n      return d\n    }\n    const LF = new Map<string, number>()\n    const LS = new Map<string, number>()\n    for (const id of order) {\n      const t = byId.get(id)!\n      const ss = succ.get(id)!\n      const lf = ss.length ? Math.min(...ss.map((n) => LS.get(n)!)) : projEnd\n      LF.set(id, lf)\n      LS.set(id, t.dur ? backWork(lf, workBetween(t.s, t.e)) : lf)\n    }\n    const slack = new Map(T.map((t) => [t.id, workBetween(t.e, LF.get(t.id)!)]))\n    const crit = new Set(T.filter((t) => slack.get(t.id)! <= 0).map((t) => t.id))\n    const start = Math.min(...T.map((t) => t.s))\n    // Pad to whole weeks (Monday to Sunday).\n    const d0 = start - ((dow(start) + 6) % 7)\n    const d1 = projEnd + ((7 - ((dow(projEnd) + 6) % 7)) % 7) + 3\n    const streamIds = streams?.map((s) => s.id) ?? [...new Set(T.map((t) => t.stream))]\n    const rows: ({ kind: 'stream'; id: string } | { kind: 'task'; id: string })[] = []\n    for (const sid of streamIds) {\n      const ts = T.filter((t) => t.stream === sid)\n      if (!ts.length) continue\n      rows.push({ kind: 'stream', id: sid })\n      for (const t of ts) rows.push({ kind: 'task', id: t.id })\n    }\n    const critDays = workBetween(start, projEnd)\n    return { T, byId, succ, slack, crit, d0, d1, rows, streamIds, working, workBetween, black, projEnd, start, critDays }\n  }, [tasks, streams, blackouts])\n\n  const streamMeta = (id: string) => {\n    const i = model.streamIds.indexOf(id)\n    const s = streams?.find((q) => q.id === id)\n    return { label: s?.label ?? id, color: s?.color ?? CATEGORICAL[i % CATEGORICAL.length] }\n  }\n\n  const LW = labelWidth ?? (W < 900 ? 190 : 248)\n  const HEAD = 46\n  const STREAM_H = 30\n  const plotW = Math.max(200, W - LW)\n  const days = model.d1 - model.d0\n  const ppd = plotW / days\n  const X = (d: number) => LW + (d - model.d0) * ppd\n\n  const rowY = new Map<string, number>()\n  const rowList: ((typeof model.rows)[number] & { y: number; h: number })[] = []\n  let yEnd = HEAD\n  for (const r of model.rows) {\n    const h = r.kind === 'stream' ? STREAM_H : rowHeight\n    rowList.push({ ...r, y: yEnd, h })\n    if (r.kind === 'task') rowY.set(r.id, yEnd + h / 2)\n    yEnd += h\n  }\n  const H = yEnd + 8\n\n  const hoverSet = useMemo(() => {\n    if (!hover) return null\n    const set = new Set<string>([hover])\n    // Upstream and downstream chains.\n    const up = (id: string) => {\n      for (const d of model.byId.get(id)?.deps ?? [])\n        if (!set.has(d)) {\n          set.add(d)\n          up(d)\n        }\n    }\n    const down = (id: string) => {\n      for (const d of model.succ.get(id) ?? [])\n        if (!set.has(d)) {\n          set.add(d)\n          down(d)\n        }\n    }\n    up(hover)\n    down(hover)\n    return set\n  }, [hover, model])\n\n  const edges = model.T.flatMap((t) =>\n    (t.deps ?? [])\n      .filter((d) => model.byId.has(d))\n      .map((d) => {\n        const p = model.byId.get(d)!\n        const ys = rowY.get(p.id)!\n        const yt = rowY.get(t.id)!\n        const xs = p.milestone ? X(p.s) + 6 : X(p.e)\n        const xt = t.milestone ? X(t.s) - 7 : X(t.s)\n        const dir = yt > ys ? 1 : -1\n        let pts: [number, number][]\n        if (xt - xs >= 14) {\n          const mx = xs + 6\n          pts = [[xs, ys], [mx, ys], [mx, yt], [xt - 1, yt]]\n        } else {\n          const yb = ys + (dir * rowHeight) / 2\n          pts = [[xs, ys], [xs + 7, ys], [xs + 7, yb], [xt - 9, yb], [xt - 9, yt], [xt - 1, yt]]\n        }\n        const critical = showCritical && model.crit.has(p.id) && model.crit.has(t.id) && model.workBetween(p.e, t.s) === 0\n        return { key: d + '>' + t.id, from: d, to: t.id, d: elbow(pts, 4), critical }\n      }),\n  )\n\n  const weeks: number[] = []\n  for (let d = model.d0; d <= model.d1; d++) if (dow(d) === 1) weeks.push(d)\n  const months: { d: number; label: string }[] = []\n  for (let d = model.d0; d < model.d1; d++) {\n    const dt = dateOf(d)\n    if (d === model.d0 || dt.getUTCDate() === 1) months.push({ d, label: monthYear ? monthYear.format(dt) : `${MON[dt.getUTCMonth()]} ${dt.getUTCFullYear()}` })\n  }\n  const todayN = today ? toDay(today) : null\n  const ht = hover ? model.byId.get(hover) : null\n  const critCount = model.crit.size\n  const lit = (id: string) => !hoverSet || hoverSet.has(id)\n  /* The \"today\" pill hides the week-number labels it would cover. */\n  const todayX = todayN != null && todayN >= model.d0 && todayN <= model.d1 ? X(todayN) : null\n  const underPill = (d: number) => todayX != null && X(d) + 4 < todayX + 32 && X(d) + 4 + 14 > todayX - 32\n  const taskOrder = rowList.filter((r) => r.kind === 'task').map((r) => r.id)\n  const label = ariaLabel ?? `Project plan with ${tasks.length} tasks; ${critCount} on the critical path`\n\n  return (\n    <div className={cn('flex min-w-0 flex-col', className)}>\n      <div\n        ref={ref}\n        role=\"figure\"\n        aria-label={label}\n        tabIndex={0}\n        className={cn('relative w-full rounded-lg select-none', FOCUS_RING)}\n        style={{ height: H, touchAction: 'pan-y' }}\n        onPointerMove={onMove}\n        onPointerDown={onMove}\n        onPointerLeave={(e) => e.pointerType === 'mouse' && setHover(null)}\n        onKeyDown={(e) => {\n          const cur = hover ? taskOrder.indexOf(hover) : null\n          const k = stepIndex(e.key, taskOrder.length, cur === -1 ? null : cur, { wrap: false })\n          if (k === undefined) return\n          e.preventDefault()\n          if (k == null) return setHover(null)\n          const t = model.byId.get(taskOrder[k])!\n          setPos([Math.min(W - 40, X(t.milestone ? t.s : t.e)), (rowY.get(t.id) ?? 0) + 4])\n          setHover(t.id)\n        }}\n        onBlur={() => setHover(null)}\n      >\n        {W > 0 && (\n          <svg width={W} height={H} className=\"absolute inset-0 overflow-visible\">\n            <defs>\n              {['n', 'c', 'h'].map((k) => (\n                <marker key={k} id={`${uid}-${k}`} viewBox=\"0 0 8 8\" refX={7} refY={4} markerWidth={6} markerHeight={6} orient=\"auto\">\n                  <path d=\"M1,1 L7,4 L1,7 Z\" fill={k === 'c' ? 'var(--red)' : k === 'h' ? 'var(--fg)' : 'var(--fg-3)'} />\n                </marker>\n              ))}\n              <pattern id={`${uid}-hatch`} width={6} height={6} patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\">\n                <line x1={0} y1={0} x2={0} y2={6} stroke=\"var(--border-strong)\" strokeWidth={2.2} />\n              </pattern>\n              <clipPath id={`${uid}-plot`}>\n                <rect x={LW} y={0} width={plotW} height={H} />\n              </clipPath>\n            </defs>\n\n            {/* stream bands */}\n            {rowList.map((r) =>\n              r.kind === 'stream' ? <rect key={'b' + r.id} x={0} y={r.y} width={W} height={r.h} fill=\"var(--surface-2)\" /> : null,\n            )}\n\n            <g clipPath={`url(#${uid}-plot)`}>\n              {/* weekends */}\n              {weekends &&\n                Array.from({ length: days }, (_, i) => model.d0 + i)\n                  .filter((d) => dow(d) === 6)\n                  .map((d) => <rect key={'w' + d} x={X(d)} y={HEAD} width={ppd * 2} height={H - HEAD} fill={mix('var(--fg)', 3.5)} />)}\n              {/* blackouts */}\n              {model.black.map(([a, b], i) => (\n                <g key={'k' + i}>\n                  <rect x={X(a)} y={HEAD} width={(b - a + 1) * ppd} height={H - HEAD} fill={`url(#${uid}-hatch)`} opacity={0.8} />\n                  <rect x={X(a)} y={HEAD} width={(b - a + 1) * ppd} height={H - HEAD} fill={mix('var(--fg)', 2.5)} />\n                </g>\n              ))}\n              {/* week lines */}\n              {weeks.map((d) => (\n                <line key={'g' + d} x1={X(d)} x2={X(d)} y1={HEAD - 18} y2={H} stroke=\"var(--border)\" />\n              ))}\n            </g>\n\n            {/* header */}\n            <line x1={0} x2={W} y1={HEAD - 0.5} y2={HEAD - 0.5} stroke=\"var(--border-strong)\" />\n            <text x={0} y={HEAD - 13} className=\"fill-fg-3 text-[11px] font-medium tracking-[0.04em] uppercase\">\n              Workstream · task\n            </text>\n            {months.map((m, i) => {\n              const next = months[i + 1]?.d ?? model.d1\n              if ((next - m.d) * ppd < 60) return null\n              return (\n                <g key={'m' + m.d}>\n                  {i > 0 && <line x1={X(m.d)} x2={X(m.d)} y1={2} y2={HEAD} stroke=\"var(--border-strong)\" />}\n                  <text x={X(m.d) + 6} y={13} className=\"fill-fg-2 text-[11.5px] font-semibold\">\n                    {m.label}\n                  </text>\n                </g>\n              )\n            })}\n            {weeks.map((d) => (\n              <text key={'wl' + d} x={X(d) + 4} y={HEAD - 9} className=\"num fill-fg-3 text-[10.5px]\">\n                {ppd * 7 > 34 && !underPill(d) ? dateOf(d).getUTCDate() : ''}\n              </text>\n            ))}\n            {model.black.map(([a, b], i) =>\n              blackouts[i]?.label && (b - a + 1) * ppd > 50 ? (\n                <text key={'kl' + i} x={X(a) + ((b - a + 1) * ppd) / 2} y={H - 10} textAnchor=\"middle\" className=\"fill-fg-3 text-[10.5px] font-medium\">\n                  {blackouts[i].label}\n                </text>\n              ) : null,\n            )}\n\n            {/* rows */}\n            {rowList.map((r) => {\n              if (r.kind === 'stream') {\n                const m = streamMeta(r.id)\n                const ts = model.T.filter((t) => t.stream === r.id && !t.milestone)\n                const done = ts.reduce((a, t) => a + (t.progress ?? 0) * t.dur, 0) / (ts.reduce((a, t) => a + t.dur, 0) || 1)\n                return (\n                  <g key={'s' + r.id}>\n                    <rect x={0} y={r.y + 9} width={3} height={12} rx={1.5} fill={m.color} />\n                    <text x={11} y={r.y + 19.5} className=\"fill-fg text-[12px] font-semibold\">\n                      {m.label}\n                    </text>\n                    <text x={LW - 14} y={r.y + 19.5} textAnchor=\"end\" className=\"num fill-fg-3 text-[11px]\">\n                      {Math.round(done * 100)}% · {ts.length}\n                    </text>\n                    <line x1={0} x2={W} y1={r.y + r.h - 0.5} y2={r.y + r.h - 0.5} stroke=\"var(--border)\" />\n                  </g>\n                )\n              }\n              const t = model.byId.get(r.id)!\n              const m = streamMeta(t.stream)\n              const crit = showCritical && model.crit.has(t.id)\n              const cy = r.y + r.h / 2\n              const on = lit(t.id)\n              const x0 = X(t.s)\n              const x1 = X(t.e)\n              const bh = 14\n              const prog = t.progress ?? 0\n              return (\n                <g\n                  key={t.id}\n                  onPointerEnter={() => setHover(t.id)}\n                  // also answers synthetic / compatibility mouse events (test tools, older embeds)\n                  onMouseEnter={() => setHover(t.id)}\n                  style={{ opacity: on ? 1 : 0.28, transition: 'opacity .2s' }}\n                >\n                  <rect x={0} y={r.y} width={W} height={r.h} fill={hover === t.id ? mix('var(--accent)', 7) : 'transparent'} />\n                  {crit && <circle cx={14} cy={cy} r={2.6} fill=\"var(--red)\" />}\n                  <text x={24} y={cy + 4} className={cn('text-[12.5px]', t.milestone ? 'fill-fg font-medium' : 'fill-fg-2')}>\n                    {fitText(t.name, LW - 24 - 78, 6.6)}\n                  </text>\n                  {!t.milestone && (\n                    <text x={LW - 14} y={cy + 4} textAnchor=\"end\" className=\"num text-[11px]\">\n                      <tspan className=\"fill-fg-4\">{model.workBetween(t.s, t.e)}d</tspan>\n                      <tspan dx={8} className={prog >= 1 ? 'fill-fg-3' : 'fill-fg-2'}>\n                        {prog >= 1 ? 'Done' : `${Math.round(prog * 100)}%`}\n                      </tspan>\n                    </text>\n                  )}\n                  {t.milestone ? (\n                    <g transform={`translate(${x0},${cy}) rotate(45)`}>\n                      <rect x={-5.5} y={-5.5} width={11} height={11} rx={2} fill={crit ? 'var(--red)' : 'var(--fg)'} stroke=\"var(--surface)\" strokeWidth={1.5} />\n                    </g>\n                  ) : (\n                    <g>\n                      <rect x={x0 + 1} y={cy - bh / 2} width={Math.max(2, x1 - x0 - 2)} height={bh} rx={4} fill={mix(m.color, 24, 'var(--surface)')} stroke={crit ? 'var(--red)' : mix(m.color, 55, 'var(--surface)')} strokeWidth={crit ? 1.4 : 1} />\n                      {prog > 0 && (\n                        <rect\n                          className=\"anim-grow-x\"\n                          x={x0 + 1}\n                          y={cy - bh / 2}\n                          width={Math.max(2, (x1 - x0 - 2) * Math.min(1, prog))}\n                          height={bh}\n                          rx={4}\n                          fill={m.color}\n                          style={{ transformOrigin: `${x0}px ${cy}px` }}\n                        />\n                      )}\n                      {x1 - x0 > 40 && prog > 0 && prog < 1 && (x1 - x0) * prog > 30 && (\n                        <text x={x0 + 6} y={cy + 3.6} className=\"num fill-[var(--surface)] text-[10px] font-semibold\">\n                          {Math.round(prog * 100)}%\n                        </text>\n                      )}\n                    </g>\n                  )}\n                  {t.milestone && (\n                    <text x={x0 + 15} y={cy + 3.8} className=\"num fill-fg-2 text-[10.5px] font-medium\">\n                      {day(t.s)}\n                    </text>\n                  )}\n                </g>\n              )\n            })}\n\n            {/* dependency arrows */}\n            <g fill=\"none\" className=\"pointer-events-none\">\n              {edges\n                .slice()\n                .sort((a, b) => Number(a.critical) - Number(b.critical))\n                .map((e) => {\n                  const hot = hoverSet && hoverSet.has(e.from) && hoverSet.has(e.to)\n                  const dim = hoverSet && !hot\n                  return (\n                    <path\n                      key={e.key}\n                      d={e.d}\n                      stroke={e.critical ? 'var(--red)' : hot ? 'var(--fg)' : 'var(--fg-3)'}\n                      strokeWidth={e.critical || hot ? 1.4 : 1}\n                      strokeOpacity={dim ? 0.15 : e.critical ? 0.95 : 0.7}\n                      markerEnd={`url(#${uid}-${e.critical ? 'c' : hot ? 'h' : 'n'})`}\n                      style={{ transition: 'stroke-opacity .2s' }}\n                    />\n                  )\n                })}\n            </g>\n\n            {/* today */}\n            {todayN != null && todayN >= model.d0 && todayN <= model.d1 && (\n              <g className=\"pointer-events-none\">\n                <line x1={X(todayN)} x2={X(todayN)} y1={HEAD - 4} y2={H} stroke=\"var(--accent)\" strokeWidth={1.25} />\n                <rect x={X(todayN) - 28} y={HEAD - 24} width={56} height={18} rx={9} fill=\"var(--accent)\" />\n                <text x={X(todayN)} y={HEAD - 11.5} textAnchor=\"middle\" className=\"num fill-[var(--accent-fg)] text-[10.5px] font-semibold\">\n                  {day(todayN)}\n                </text>\n              </g>\n            )}\n          </svg>\n        )}\n\n        {ht && W > 0 && (\n          <Tip x={pos[0]} y={pos[1]} width={W} height={H} w={250} h={230}>\n            <TipTitle color={streamMeta(ht.stream).color} sub={streamMeta(ht.stream).label + (ht.owner ? ` · ${ht.owner}` : '')}>\n              {ht.name}\n            </TipTitle>\n            {ht.milestone ? (\n              <TipRow label=\"Date\" value={day(ht.s)} strong />\n            ) : (\n              <>\n                <TipRow label=\"Dates\" value={`${day(ht.s)} → ${day(ht.e - 1)}`} strong />\n                <TipRow label=\"Duration\" value={`${model.workBetween(ht.s, ht.e)} working days`} />\n                <TipRow label=\"Progress\" value={`${Math.round((ht.progress ?? 0) * 100)}%`} />\n              </>\n            )}\n            <TipRow\n              label=\"Slack\"\n              value={\n                model.crit.has(ht.id) ? (\n                  <span style={{ color: 'var(--red)' }}>0d · critical</span>\n                ) : (\n                  `${model.slack.get(ht.id)}d`\n                )\n              }\n            />\n            {!!(ht.deps?.length || model.succ.get(ht.id)?.length) && <TipRule />}\n            {!!ht.deps?.length && (\n              <div className=\"text-[11.5px] leading-[1.5]\">\n                <span className=\"text-fg-3\">After </span>\n                <span className=\"text-fg-2\">{ht.deps.map((d) => model.byId.get(d)?.name).join(', ')}</span>\n              </div>\n            )}\n            {!!model.succ.get(ht.id)?.length && (\n              <div className=\"text-[11.5px] leading-[1.5]\">\n                <span className=\"text-fg-3\">Blocks </span>\n                <span className=\"text-fg-2\">{model.succ.get(ht.id)!.map((d) => model.byId.get(d)?.name).join(', ')}</span>\n              </div>\n            )}\n          </Tip>\n        )}\n\n        <ChartDataTable\n          caption={label}\n          columns={[\n            { key: 'task', label: 'Task' },\n            { key: 'stream', label: 'Workstream' },\n            { key: 'start', label: 'Start', format: (v) => day(toDay(v as string)) },\n            { key: 'end', label: 'End', format: (v) => day(toDay(v as string)) },\n            { key: 'progress', label: 'Progress', format: (v) => `${Math.round((v as number) * 100)}%` },\n            { key: 'slack', label: 'Slack (working days)' },\n            { key: 'dependsOn', label: 'After' },\n          ]}\n          rows={dependencyGanttToRows(tasks, streams).map((r, i) => ({ ...r, slack: model.slack.get(tasks[i].id) ?? '' }))}\n        />\n      </div>\n    </div>\n  )\n}\n\n/** Critical-path summary for a plan, for headers and legends. */\n// oxlint-disable-next-line react/only-export-components -- maths / layout helper exported with its chart (public API)\nexport function ganttSummary(tasks: GanttTask[]) {\n  const s = Math.min(...tasks.map((t) => toDay(t.start)))\n  const e = Math.max(...tasks.map((t) => toDay(t.end ?? t.start)))\n  return { start: short(s), end: short(e), weeks: Math.ceil((e - s + 1) / 7) }\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/tech/DependencyGantt.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/tech/ui.tsx",
      "content": "import type { ReactNode } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\n\n/* Shared tooltip pieces for the tech collection. */\n\nexport { ExportMirror } from '../science/parts'\n\n/** Floating readout card, placed at (x, y) inside a relative container; flips near the edges. */\nexport function Tip({\n  x,\n  y,\n  width,\n  height,\n  children,\n  w = 220,\n  h = 140,\n  className,\n}: {\n  x: number\n  y: number\n  /** Container size, used to flip the card away from the edges. */\n  width: number\n  height?: number\n  children: ReactNode\n  /** Rough card size for the flip test. */\n  w?: number\n  h?: number\n  className?: string\n}) {\n  const fx = x > width - w - 24\n  const fy = height != null && y > height - h - 12\n  return (\n    <div\n      className={cn(\n        'pointer-events-none absolute z-30 rounded-xl border border-border bg-surface px-3 py-2.5 text-[12.5px] shadow-pop',\n        className,\n      )}\n      style={{\n        left: x,\n        top: y,\n        minWidth: Math.min(w, 180),\n        maxWidth: w + 60,\n        transform: `translate(${fx ? 'calc(-100% - 14px)' : '14px'}, ${fy ? 'calc(-100% - 10px)' : '12px'})`,\n      }}\n    >\n      {children}\n    </div>\n  )\n}\n\nexport function TipTitle({ children, color, sub }: { children: ReactNode; color?: string; sub?: ReactNode }) {\n  return (\n    <div className=\"mb-2\">\n      <div className=\"flex items-center gap-1.5 text-[12.5px] font-semibold text-fg\">\n        {color && <span className=\"size-2 shrink-0 rounded-[3px]\" style={{ background: color }} />}\n        <span className=\"min-w-0 truncate\">{children}</span>\n      </div>\n      {sub && <div className=\"mt-0.5 text-[11.5px] text-fg-3\">{sub}</div>}\n    </div>\n  )\n}\n\nexport function TipRow({ label, value, color, strong }: { label: ReactNode; value: ReactNode; color?: string; strong?: boolean }) {\n  return (\n    <div className=\"flex items-center justify-between gap-5 leading-[1.6]\">\n      <span className=\"flex min-w-0 items-center gap-1.5 text-fg-3\">\n        {color && <span className=\"size-1.5 shrink-0 rounded-full\" style={{ background: color }} />}\n        <span className=\"truncate\">{label}</span>\n      </span>\n      <span className={cn('num shrink-0 text-fg', strong ? 'font-semibold' : 'font-medium')}>{value}</span>\n    </div>\n  )\n}\n\nexport function TipRule() {\n  return <div className=\"my-1.5 h-px bg-border\" />\n}\n\n/** Legend swatch with label and optional value. */\nexport function Swatch({ color, label, value, dim, onEnter, onLeave, shape = 'square' }: {\n  color: string\n  label: ReactNode\n  value?: ReactNode\n  dim?: boolean\n  onEnter?: () => void\n  onLeave?: () => void\n  shape?: 'square' | 'dot' | 'line'\n}) {\n  return (\n    <span\n      className={cn('inline-flex items-center gap-1.5 text-[11.5px] whitespace-nowrap text-fg-2 transition-opacity', dim && 'opacity-35')}\n      onPointerEnter={onEnter}\n      onPointerLeave={onLeave}\n    >\n      <span\n        className={cn('shrink-0', shape === 'dot' ? 'size-2 rounded-full' : shape === 'line' ? 'h-[2px] w-3 rounded-full' : 'size-2 rounded-[2px]')}\n        style={{ background: color }}\n      />\n      {label}\n      {value != null && <span className=\"num text-fg-3\">{value}</span>}\n    </span>\n  )\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/tech/ui.tsx"
    },
    {
      "path": "registry/klar/components/charts/tech/util.ts",
      "content": "import { useCallback, useState, type MouseEvent } from 'react'\nimport { fmt } from '@/components/klar/lib/format'\nimport { formatter } from '@/components/klar/charts/basic/core'\n\n/* Shared helpers for the tech collection. Not re-exported from the kit index. */\n\nexport const TAU = Math.PI * 2\n\n/** `color-mix(in oklab, c p%, base)`; base defaults to transparent. */\nexport const mix = (c: string, p: number, base = 'transparent') => `color-mix(in oklab, ${c} ${p}%, ${base})`\n\n/** Categorical token palette, ordered so neighbours stay distinct in both themes. */\nexport const CATEGORICAL = [\n  'var(--accent)',\n  'var(--violet)',\n  'var(--amber)',\n  'var(--pink)',\n  'var(--green)',\n  'var(--blue)',\n  'var(--orange)',\n  'var(--teal)',\n  'var(--lime)',\n  'var(--red)',\n  'var(--sky)',\n]\n\n/** Small deterministic string hash (FNV-1a), for stable colour picks. */\nexport function hash(s: string) {\n  let h = 2166136261\n  for (let i = 0; i < s.length; i++) {\n    h ^= s.charCodeAt(i)\n    h = Math.imul(h, 16777619)\n  }\n  return h >>> 0\n}\n\n/**\n * Pointer position relative to the element, corrected for ancestor scale transforms.\n * Works with mouse and pointer events (bind it to `onPointerMove` and `onPointerDown`);\n * the setter lets keyboard navigation anchor the readout on a mark.\n */\nexport function usePointer() {\n  const [pos, setPos] = useState<[number, number]>([0, 0])\n  const onMove = useCallback((e: MouseEvent<Element>) => {\n    const el = e.currentTarget as HTMLElement\n    const r = el.getBoundingClientRect()\n    const s = r.width / (el.offsetWidth || r.width) || 1\n    setPos([(e.clientX - r.left) / s, (e.clientY - r.top) / s])\n  }, [])\n  return [pos, onMove, setPos] as const\n}\n\n/** Focus ring for a keyboard-navigable chart (HTML element). */\nexport const FOCUS_RING = 'outline-none focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-accent/60'\n\nexport interface TechFormat {\n  /** Default value format: 96K / 1.2M (or a compact currency with `currency`). */\n  value: (v: number) => string\n  /** Grouped integer. */\n  int: (v: number) => string\n  /** Share from a fraction: 0.123 → 12.3% */\n  pct: (v: number, digits?: number) => string\n  /** Fixed decimals. */\n  fixed: (v: number, digits: number) => string\n  /** Short date (UTC day number → \"Nov 26\"). */\n  day: (utcMs: number) => string\n}\n\n/**\n * Number and date formatting for the tech charts. With no locale and no currency it reproduces\n * the original output exactly; otherwise it follows `formatter(locale, currency)`.\n */\nexport function techFormat(locale?: string, currency?: string): TechFormat {\n  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n  if (!locale && !currency)\n    return {\n      value: (v) => fmt.short(v),\n      int: (v) => fmt.int(v),\n      pct: (v, d = 1) => `${(v * 100).toFixed(d)}%`,\n      fixed: (v, d) => v.toFixed(d),\n      day: (t) => `${MON[new Date(t).getUTCMonth()]} ${new Date(t).getUTCDate()}`,\n    }\n  const f = formatter(locale, currency)\n  const dtf = new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', timeZone: 'UTC' })\n  return {\n    value: (v) => (currency ? f.currencyCompact(v) : f.compact(v)),\n    int: (v) => f.number(v),\n    pct: (v, d = 1) => f.percent(v, d),\n    fixed: (v, d) => f.number(v, d),\n    day: (t) => dtf.format(new Date(t)),\n  }\n}\n\n/** Arrow-key stepping through `n` marks; returns the next index, null for Escape, undefined if unhandled. */\nexport function stepIndex(key: string, n: number, cur: number | null, { next = ['ArrowRight', 'ArrowDown'], prev = ['ArrowLeft', 'ArrowUp'], wrap = true } = {}): number | null | undefined {\n  if (key === 'Escape') return cur == null ? undefined : null\n  if (n <= 0) return undefined\n  if (next.includes(key)) return cur == null ? 0 : wrap ? (cur + 1) % n : Math.min(n - 1, cur + 1)\n  if (prev.includes(key)) return cur == null ? n - 1 : wrap ? (cur - 1 + n) % n : Math.max(0, cur - 1)\n  if (key === 'Home') return 0\n  if (key === 'End') return n - 1\n  return undefined\n}\n\n/** Truncate a label to fit `px` at roughly `charW` pixels per character. */\nexport function fitText(s: string, px: number, charW = 6.6) {\n  const n = Math.floor(px / charW)\n  if (n >= s.length) return s\n  if (n < 3) return ''\n  return s.slice(0, n - 1) + '…'\n}\n\n/** Nice tick step for a span split into about `count` parts. */\nexport function niceStep(span: number, count = 5) {\n  const raw = span / Math.max(1, count)\n  const exp = Math.pow(10, Math.floor(Math.log10(raw)))\n  const f = raw / exp\n  return (f < 1.5 ? 1 : f < 3 ? 2 : f < 7 ? 5 : 10) * exp\n}\n\nexport const clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v))\n\nexport const pct = (v: number, digits = 1) => `${(v * 100).toFixed(digits)}%`\n",
      "type": "registry:component",
      "target": "@components/klar/charts/tech/util.ts"
    },
    {
      "path": "registry/klar/components/charts/export.ts",
      "content": "/**\n * Chart export: SVG, PNG and CSV, with no dependencies.\n *\n *   const ref = useRef<HTMLDivElement>(null)\n *   <div ref={ref}>…chart…</div>\n *   exportChartSvg(ref.current!, 'revenue')\n *   exportChartPng(ref.current!, 'revenue', { scale: 2 })\n *   exportCsv([{ month: 'Jan', revenue: 120 }], 'revenue')\n *\n * SVG/PNG inline the resolved CSS custom properties (tokens) and text styles so the\n * file looks the same outside the page. Canvas layers (spectrogram, vol surface)\n * are composited into the PNG.\n */\n\nexport interface ExportOptions {\n  /** PNG pixel ratio (default 2). */\n  scale?: number\n  /** Background colour; defaults to the chart's resolved surface colour. */\n  background?: string\n  /** Padding around the chart in px (default 16). */\n  padding?: number\n}\n\nconst STYLE_PROPS = [\n  'fill',\n  'fill-opacity',\n  'stroke',\n  'stroke-width',\n  'stroke-opacity',\n  'stroke-dasharray',\n  'stroke-linecap',\n  'stroke-linejoin',\n  'opacity',\n  'font-family',\n  'font-size',\n  'font-weight',\n  'letter-spacing',\n  'text-anchor',\n  'dominant-baseline',\n  'font-variant-numeric',\n] as const\n\nfunction download(blob: Blob, filename: string) {\n  const url = URL.createObjectURL(blob)\n  const a = document.createElement('a')\n  a.href = url\n  a.download = filename\n  document.body.appendChild(a)\n  a.click()\n  a.remove()\n  setTimeout(() => URL.revokeObjectURL(url), 1000)\n}\n\nconst slug = (s: string) => s.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'chart'\n\nfunction resolvedBackground(el: Element) {\n  let node: Element | null = el\n  while (node) {\n    const bg = getComputedStyle(node).backgroundColor\n    if (bg && bg !== 'transparent' && !/rgba\\(0, 0, 0, 0\\)/.test(bg)) return bg\n    node = node.parentElement\n  }\n  return '#ffffff'\n}\n\n/** Clone an SVG with computed presentation styles inlined (so var(--x) resolves). */\nfunction inlineSvg(svg: SVGSVGElement): SVGSVGElement {\n  const clone = svg.cloneNode(true) as SVGSVGElement\n  const src = svg.querySelectorAll('*')\n  const dst = clone.querySelectorAll('*')\n  const apply = (from: Element, to: Element) => {\n    const cs = getComputedStyle(from)\n    const parts: string[] = []\n    for (const p of STYLE_PROPS) {\n      const v = cs.getPropertyValue(p)\n      if (v) parts.push(`${p}:${v}`)\n    }\n    const prev = to.getAttribute('style')\n    to.setAttribute('style', parts.join(';') + (prev ? ';' + prev : ''))\n    // Attributes written as var(--token) must be resolved too.\n    for (const attr of ['fill', 'stroke', 'stop-color', 'color']) {\n      const raw = to.getAttribute(attr)\n      if (raw && raw.includes('var(')) {\n        const value = attr === 'stop-color' ? cs.getPropertyValue('stop-color') : cs.getPropertyValue(attr)\n        if (value) to.setAttribute(attr, value)\n      }\n    }\n  }\n  apply(svg, clone)\n  src.forEach((n, i) => {\n    apply(n, dst[i])\n    // CSS text-transform isn't an SVG attribute; bake it into the text itself.\n    if ((n.tagName === 'text' || n.tagName === 'tspan') && n.childElementCount === 0) {\n      const tt = getComputedStyle(n).textTransform\n      const t = dst[i].textContent ?? ''\n      if (tt === 'uppercase') dst[i].textContent = t.toUpperCase()\n      else if (tt === 'lowercase') dst[i].textContent = t.toLowerCase()\n    }\n  })\n  clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg')\n  clone.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink')\n  return clone\n}\n\n/**\n * Combine every <svg> and <canvas> inside `root` into one SVG document positioned\n * as on screen. HTML labels (legends, readouts) are not included; charts keep their\n * essential labels in SVG.\n */\nfunction composeSvg(root: HTMLElement, opts: ExportOptions = {}) {\n  const pad = opts.padding ?? 16\n  const box = root.getBoundingClientRect()\n  const sx = root.offsetWidth ? box.width / root.offsetWidth : 1\n  const w = root.offsetWidth\n  const h = root.offsetHeight\n  const doc = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\n  doc.setAttribute('xmlns', 'http://www.w3.org/2000/svg')\n  doc.setAttribute('width', String(w + pad * 2))\n  doc.setAttribute('height', String(h + pad * 2))\n  doc.setAttribute('viewBox', `0 0 ${w + pad * 2} ${h + pad * 2}`)\n  const bg = document.createElementNS('http://www.w3.org/2000/svg', 'rect')\n  bg.setAttribute('width', '100%')\n  bg.setAttribute('height', '100%')\n  bg.setAttribute('fill', opts.background ?? resolvedBackground(root))\n  doc.appendChild(bg)\n\n  const layers = root.querySelectorAll<SVGSVGElement | HTMLCanvasElement>('svg, canvas')\n  layers.forEach((layer) => {\n    // Skip nested svgs (handled by their parent) and icons inside buttons.\n    if (layer instanceof SVGSVGElement && (layer.ownerSVGElement || layer.closest('button'))) return\n    const r = layer.getBoundingClientRect()\n    if (!r.width || !r.height) return\n    const x = (r.left - box.left) / sx + pad\n    const y = (r.top - box.top) / sx + pad\n    const lw = r.width / sx\n    const lh = r.height / sx\n    if (layer instanceof HTMLCanvasElement) {\n      const img = document.createElementNS('http://www.w3.org/2000/svg', 'image')\n      img.setAttribute('x', String(x))\n      img.setAttribute('y', String(y))\n      img.setAttribute('width', String(lw))\n      img.setAttribute('height', String(lh))\n      try {\n        img.setAttribute('href', layer.toDataURL('image/png'))\n        doc.appendChild(img)\n      } catch {\n        /* tainted canvas: skip */\n      }\n      return\n    }\n    const g = document.createElementNS('http://www.w3.org/2000/svg', 'g')\n    g.setAttribute('transform', `translate(${x} ${y})`)\n    const inner = inlineSvg(layer)\n    inner.setAttribute('width', String(lw))\n    inner.setAttribute('height', String(lh))\n    if (!inner.getAttribute('viewBox')) inner.setAttribute('viewBox', `0 0 ${layer.width.baseVal.value || lw} ${layer.height.baseVal.value || lh}`)\n    g.appendChild(inner)\n    doc.appendChild(g)\n  })\n  return { doc, width: w + pad * 2, height: h + pad * 2 }\n}\n\n/** The chart as an SVG string. */\nexport function chartToSvgString(root: HTMLElement, opts?: ExportOptions) {\n  const { doc } = composeSvg(root, opts)\n  return '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' + new XMLSerializer().serializeToString(doc)\n}\n\n/** Download the chart as SVG. */\nexport function exportChartSvg(root: HTMLElement, name = 'chart', opts?: ExportOptions) {\n  download(new Blob([chartToSvgString(root, opts)], { type: 'image/svg+xml' }), `${slug(name)}.svg`)\n}\n\n/** Render the chart to a PNG blob. */\nexport async function chartToPngBlob(root: HTMLElement, opts: ExportOptions = {}): Promise<Blob> {\n  const scale = opts.scale ?? 2\n  const { doc, width, height } = composeSvg(root, opts)\n  const svgText = new XMLSerializer().serializeToString(doc)\n  const img = new Image()\n  img.decoding = 'async'\n  const url = URL.createObjectURL(new Blob([svgText], { type: 'image/svg+xml' }))\n  try {\n    await new Promise<void>((res, rej) => {\n      img.onload = () => res()\n      img.onerror = () => rej(new Error('Could not rasterise chart'))\n      img.src = url\n    })\n    const canvas = document.createElement('canvas')\n    canvas.width = Math.round(width * scale)\n    canvas.height = Math.round(height * scale)\n    const ctx = canvas.getContext('2d')!\n    ctx.scale(scale, scale)\n    ctx.drawImage(img, 0, 0, width, height)\n    return await new Promise<Blob>((res, rej) => canvas.toBlob((b) => (b ? res(b) : rej(new Error('PNG encoding failed'))), 'image/png'))\n  } finally {\n    URL.revokeObjectURL(url)\n  }\n}\n\n/** Download the chart as PNG (2× by default). */\nexport async function exportChartPng(root: HTMLElement, name = 'chart', opts?: ExportOptions) {\n  download(await chartToPngBlob(root, opts), `${slug(name)}.png`)\n}\n\n/** Rows (array of flat objects) as RFC 4180 CSV. Column order follows the first row unless given. */\nexport function toCsv(rows: Record<string, unknown>[], columns?: string[]) {\n  const cols = columns ?? Object.keys(rows[0] ?? {})\n  const cell = (v: unknown) => {\n    if (v == null) return ''\n    const s = v instanceof Date ? v.toISOString() : String(v)\n    return /[\",\\n\\r]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s\n  }\n  return [cols.map(cell).join(','), ...rows.map((r) => cols.map((c) => cell(r[c])).join(','))].join('\\r\\n')\n}\n\n/** Download rows as a CSV file (UTF-8 with BOM so Excel opens it correctly). */\nexport function exportCsv(rows: Record<string, unknown>[], name = 'chart-data', columns?: string[]) {\n  download(new Blob(['﻿' + toCsv(rows, columns)], { type: 'text/csv;charset=utf-8' }), `${slug(name)}.csv`)\n}\n",
      "type": "registry:component",
      "target": "@components/klar/charts/export.ts"
    },
    {
      "path": "registry/klar/components/charts/basic/core.tsx",
      "content": "/**\n * Shared foundation for the basic charts: scales, ticks, locale-aware formatting,\n * pointer (mouse + touch + pen) hover tracking, axes, legend and tooltip.\n * Advanced charts can use it too.\n */\nimport { useCallback, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from 'react'\nimport { cn } from '@/components/klar/lib/cn'\n\n/* ------------------------------------------------------------------ */\n/*  Scales and ticks                                                  */\n/* ------------------------------------------------------------------ */\n\nexport interface LinearScale {\n  (v: number): number\n  invert: (px: number) => number\n  domain: [number, number]\n  range: [number, number]\n  ticks: number[]\n}\n\n/** \"Nice\" tick values covering [min, max] with about `count` steps. */\nexport function niceTicks(min: number, max: number, count = 5): number[] {\n  if (!isFinite(min) || !isFinite(max)) return [0]\n  if (min === max) {\n    max = min + (Math.abs(min) || 1)\n  }\n  const span = max - min\n  const raw = span / Math.max(1, count)\n  const mag = Math.pow(10, Math.floor(Math.log10(raw)))\n  const norm = raw / mag\n  const step = (norm >= 7.5 ? 10 : norm >= 3.5 ? 5 : norm >= 1.5 ? 2 : 1) * mag\n  const start = Math.floor(min / step) * step\n  const end = Math.ceil(max / step) * step\n  const out: number[] = []\n  for (let v = start; v <= end + step * 1e-6; v += step) out.push(+v.toPrecision(12))\n  return out\n}\n\n/**\n * Linear scale. With `nice` (default) the domain is widened to round tick values.\n * `zero` forces the domain to include 0 (right for bars, optional for lines).\n */\nexport function linearScale(\n  domain: [number, number],\n  range: [number, number],\n  { nice = true, zero = false, ticks = 5 }: { nice?: boolean; zero?: boolean; ticks?: number } = {},\n): LinearScale {\n  let [d0, d1] = domain\n  if (zero) {\n    d0 = Math.min(0, d0)\n    d1 = Math.max(0, d1)\n  }\n  let t = niceTicks(d0, d1, ticks)\n  if (nice) {\n    d0 = t[0]\n    d1 = t[t.length - 1]\n  } else {\n    t = t.filter((v) => v >= d0 - 1e-9 && v <= d1 + 1e-9)\n  }\n  const [r0, r1] = range\n  const k = d1 === d0 ? 0 : (r1 - r0) / (d1 - d0)\n  const scale = ((v: number) => r0 + (v - d0) * k) as LinearScale\n  scale.invert = (px) => (k === 0 ? d0 : d0 + (px - r0) / k)\n  scale.domain = [d0, d1]\n  scale.range = [r0, r1]\n  scale.ticks = t\n  return scale\n}\n\nexport interface BandScale {\n  (i: number): number\n  bandwidth: number\n  step: number\n  /** Index of the band containing a pixel position (clamped). */\n  indexAt: (px: number) => number\n}\n\n/** Evenly spaced bands for `count` categories; `padding` is the gap fraction per step. */\nexport function bandScale(count: number, range: [number, number], padding = 0.3): BandScale {\n  const [r0, r1] = range\n  const step = count > 0 ? (r1 - r0) / count : 0\n  const bandwidth = step * (1 - padding)\n  const scale = ((i: number) => r0 + step * i + (step - bandwidth) / 2) as BandScale\n  scale.bandwidth = bandwidth\n  scale.step = step\n  scale.indexAt = (px) => Math.max(0, Math.min(count - 1, Math.floor((px - r0) / (step || 1))))\n  return scale\n}\n\nexport const extent = (values: number[]): [number, number] => {\n  let lo = Infinity\n  let hi = -Infinity\n  for (const v of values) {\n    if (v == null || !isFinite(v)) continue\n    if (v < lo) lo = v\n    if (v > hi) hi = v\n  }\n  return lo === Infinity ? [0, 1] : [lo, hi]\n}\n\n/* ------------------------------------------------------------------ */\n/*  Locale-aware formatting                                           */\n/* ------------------------------------------------------------------ */\n\nexport interface Formatter {\n  /** 12,480 */\n  number: (v: number, digits?: number) => string\n  /** 12.5K, 3.2M */\n  compact: (v: number) => string\n  /** 34.5% from 0.345 */\n  percent: (v: number, digits?: number) => string\n  currency: (v: number, digits?: number) => string\n  /** $1.2M */\n  currencyCompact: (v: number) => string\n  /** Signed: +4.2 / −4.2 */\n  delta: (v: number, digits?: number) => string\n  date: (d: Date | string | number, opts?: Intl.DateTimeFormatOptions) => string\n}\n\nconst cache = new Map<string, Formatter>()\n\n/**\n * Formatter bound to a locale and currency. Pass `locale` to any basic chart to\n * localise every label, e.g. `formatter('de-DE', 'EUR').currency(1234.5)` → \"1.234,50 €\".\n */\nexport function formatter(locale = 'en-US', currency = 'USD'): Formatter {\n  const key = `${locale}|${currency}`\n  const hit = cache.get(key)\n  if (hit) return hit\n  const nf = (o: Intl.NumberFormatOptions) => new Intl.NumberFormat(locale, o)\n  const compact = nf({ notation: 'compact', maximumFractionDigits: 1 })\n  const curCompact = nf({ style: 'currency', currency, notation: 'compact', maximumFractionDigits: 1 })\n  const f: Formatter = {\n    number: (v, digits = 0) => nf({ minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    compact: (v) => compact.format(v),\n    percent: (v, digits = 0) => nf({ style: 'percent', minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    currency: (v, digits = 0) => nf({ style: 'currency', currency, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v),\n    currencyCompact: (v) => curCompact.format(v),\n    delta: (v, digits = 1) => (v > 0 ? '+' : v < 0 ? '−' : '') + nf({ minimumFractionDigits: digits, maximumFractionDigits: digits }).format(Math.abs(v)),\n    date: (d, opts = { month: 'short', day: 'numeric' }) => new Intl.DateTimeFormat(locale, opts).format(new Date(d)),\n  }\n  cache.set(key, f)\n  return f\n}\n\n/* ------------------------------------------------------------------ */\n/*  Pointer hover (mouse, touch and pen)                              */\n/* ------------------------------------------------------------------ */\n\nexport interface HoverPoint {\n  /** Position inside the element, in its own (unscaled) pixels. */\n  x: number\n  y: number\n}\n\n/**\n * Tracks the pointer over a chart for mouse, touch and pen alike.\n * Spread `bind` on the plot container. On touch, a tap or drag shows the readout\n * and it stays until the next tap elsewhere; on mouse it clears on leave.\n */\nexport function usePointerHover<T extends HTMLElement | SVGElement = HTMLDivElement>() {\n  const [point, setPoint] = useState<HoverPoint | null>(null)\n  const touch = useRef(false)\n\n  const locate = useCallback((e: PointerEvent<T>) => {\n    const el = e.currentTarget as unknown as HTMLElement\n    const r = el.getBoundingClientRect()\n    // Compensate for ancestor CSS transforms (scaled previews).\n    const sx = el.offsetWidth ? r.width / el.offsetWidth : 1\n    const sy = el.offsetHeight ? r.height / el.offsetHeight : 1\n    setPoint({ x: (e.clientX - r.left) / (sx || 1), y: (e.clientY - r.top) / (sy || 1) })\n  }, [])\n\n  const bind = {\n    onPointerDown: (e: PointerEvent<T>) => {\n      touch.current = e.pointerType !== 'mouse'\n      locate(e)\n    },\n    onPointerMove: (e: PointerEvent<T>) => {\n      if (e.pointerType === 'mouse' || e.buttons > 0 || e.pressure > 0) locate(e)\n    },\n    onPointerLeave: (e: PointerEvent<T>) => {\n      if (e.pointerType === 'mouse') setPoint(null)\n    },\n    onPointerCancel: () => setPoint(null),\n    style: { touchAction: 'pan-y' } as CSSProperties,\n  }\n  return { point, bind, clear: () => setPoint(null), isTouch: touch }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Axes (SVG)                                                        */\n/* ------------------------------------------------------------------ */\n\n/** Horizontal gridlines with value labels on the left. */\nexport function AxisY({\n  scale,\n  x0,\n  x1,\n  format = String,\n  grid = true,\n  side = 'left',\n  label,\n}: {\n  scale: LinearScale\n  /** Left and right pixel edges of the plot. */\n  x0: number\n  x1: number\n  format?: (v: number) => string\n  grid?: boolean\n  side?: 'left' | 'right'\n  label?: string\n}) {\n  return (\n    <g aria-hidden>\n      {scale.ticks.map((t) => {\n        const y = scale(t)\n        const zero = t === 0\n        return (\n          <g key={t}>\n            {grid && (\n              <line\n                x1={x0}\n                x2={x1}\n                y1={y}\n                y2={y}\n                stroke={zero ? 'var(--border-strong)' : 'var(--border)'}\n                strokeDasharray={zero || t === scale.ticks[0] ? undefined : '3 4'}\n              />\n            )}\n            <text\n              x={side === 'left' ? x0 - 10 : x1 + 10}\n              y={y + 4}\n              textAnchor={side === 'left' ? 'end' : 'start'}\n              className=\"num fill-fg-3 text-[11px]\"\n            >\n              {format(t)}\n            </text>\n          </g>\n        )\n      })}\n      {label && (\n        <text x={side === 'left' ? x0 - 10 : x1 + 10} y={scale.range[1] - 12} textAnchor={side === 'left' ? 'end' : 'start'} className=\"fill-fg-4 text-[10.5px]\">\n          {label}\n        </text>\n      )}\n    </g>\n  )\n}\n\n/** Category or tick labels under the plot. Skips labels that would collide. */\nexport function AxisX({\n  labels,\n  y,\n  minGap = 8,\n  charWidth = 6.2,\n}: {\n  labels: { x: number; text: string; anchor?: 'start' | 'middle' | 'end' }[]\n  y: number\n  minGap?: number\n  charWidth?: number\n}) {\n  let lastEnd = -Infinity\n  return (\n    <g aria-hidden>\n      {labels.map((l, i) => {\n        const w = l.text.length * charWidth\n        const start = l.anchor === 'start' ? l.x : l.anchor === 'end' ? l.x - w : l.x - w / 2\n        if (start < lastEnd + minGap) return null\n        lastEnd = start + w\n        return (\n          <text key={i} x={l.x} y={y} textAnchor={l.anchor ?? 'middle'} className=\"fill-fg-3 text-[11px]\">\n            {l.text}\n          </text>\n        )\n      })}\n    </g>\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Legend and tooltip (HTML)                                         */\n/* ------------------------------------------------------------------ */\n\nexport interface LegendItem {\n  id: string\n  label: ReactNode\n  color: string\n  value?: ReactNode\n  /** line | bar | dot | dash */\n  mark?: 'line' | 'bar' | 'dot' | 'dash'\n}\n\n/** Legend whose items can be hovered (to highlight) and clicked (to toggle). */\nexport function ChartLegend({\n  items,\n  active,\n  hidden,\n  onHover,\n  onToggle,\n  className,\n}: {\n  items: LegendItem[]\n  active?: string | null\n  hidden?: Set<string>\n  onHover?: (id: string | null) => void\n  onToggle?: (id: string) => void\n  className?: string\n}) {\n  return (\n    <div className={cn('flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[12px] text-fg-2', className)}>\n      {items.map((it) => {\n        const off = hidden?.has(it.id)\n        const dim = active != null && active !== it.id\n        return (\n          <button\n            key={it.id}\n            type=\"button\"\n            aria-pressed={onToggle ? !off : undefined}\n            onPointerEnter={() => onHover?.(it.id)}\n            onPointerLeave={() => onHover?.(null)}\n            onFocus={() => onHover?.(it.id)}\n            onBlur={() => onHover?.(null)}\n            onClick={() => onToggle?.(it.id)}\n            className={cn('inline-flex items-center gap-1.5 rounded-md transition-opacity', (dim || off) && 'opacity-40', !onToggle && 'cursor-default')}\n          >\n            <span\n              className={cn(\n                'shrink-0',\n                it.mark === 'line' ? 'h-[2.5px] w-3.5 rounded-full' : it.mark === 'dash' ? 'h-0 w-3.5 border-t-2 border-dashed' : it.mark === 'bar' ? 'size-2.5 rounded-[3px]' : 'size-2 rounded-full',\n              )}\n              style={it.mark === 'dash' ? { borderColor: it.color } : { background: it.color }}\n            />\n            <span className={off ? 'line-through' : undefined}>{it.label}</span>\n            {it.value != null && <span className=\"num text-fg-3\">{it.value}</span>}\n          </button>\n        )\n      })}\n    </div>\n  )\n}\n\n/**\n * Tooltip card positioned inside a `relative` chart container. It flips to stay\n * inside `containerWidth` and never captures the pointer.\n */\nexport function ChartTooltip({\n  x,\n  y,\n  containerWidth,\n  title,\n  rows,\n  footer,\n  width = 170,\n}: {\n  x: number\n  y: number\n  containerWidth: number\n  title?: ReactNode\n  rows: { label: ReactNode; value: ReactNode; color?: string; strong?: boolean }[]\n  footer?: ReactNode\n  width?: number\n}) {\n  const flip = x > containerWidth - width - 24\n  return (\n    <div\n      role=\"status\"\n      className=\"pointer-events-none absolute z-30 rounded-xl border border-border bg-surface px-3 py-2.5 shadow-pop\"\n      style={{ left: x, top: Math.max(0, y), minWidth: width - 20, transform: `translate(${flip ? 'calc(-100% - 12px)' : '12px'}, -50%)` }}\n    >\n      {title != null && <div className=\"mb-1.5 text-[11.5px] font-medium text-fg-3\">{title}</div>}\n      <div className=\"flex flex-col gap-1\">\n        {rows.map((r, i) => (\n          <div key={i} className=\"flex items-center justify-between gap-5 text-[12.5px]\">\n            <span className=\"flex items-center gap-1.5 text-fg-2\">\n              {r.color && <span className=\"size-2 rounded-full\" style={{ background: r.color }} />}\n              {r.label}\n            </span>\n            <span className={cn('num text-fg', r.strong === false ? 'font-medium' : 'font-semibold')}>{r.value}</span>\n          </div>\n        ))}\n      </div>\n      {footer != null && <div className=\"mt-2 border-t border-border pt-1.5 text-[11.5px] text-fg-3\">{footer}</div>}\n    </div>\n  )\n}\n\n/** Default categorical palette, in order. */\nexport const PALETTE = ['var(--blue)', 'var(--orange)', 'var(--teal)', 'var(--violet)', 'var(--pink)', 'var(--amber)', 'var(--green)', 'var(--sky)']\n",
      "type": "registry:component",
      "target": "@components/klar/charts/basic/core.tsx"
    }
  ],
  "docs": "import { DependencyGantt } from '@/components/klar/charts/tech/DependencyGantt'\nData comes in through props.",
  "categories": [
    "charts",
    "tech",
    "schedule"
  ],
  "meta": {
    "collection": "tech",
    "kind": "schedule",
    "tags": [
      "gantt",
      "dependencies",
      "critical-path",
      "project-plan",
      "timeline",
      "schedule"
    ],
    "standalone": true,
    "export": "DependencyGantt",
    "import": "@/components/klar/charts/tech/DependencyGantt"
  }
}
