{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart",
  "title": "Charts",
  "description": "What the scrollfx charts share: series from a config, nice ticks and scales, monotone curves, markers, hatching for bars, areas and wedges, and the pens that ink a chart in order (axes, hatching, then the lines) as it reaches the middle of the screen.",
  "dependencies": [
    "svg-scroll-draw@^2.29.0"
  ],
  "registryDependencies": [
    "https://scrollfx-ui.vercel.app/r/plotter.json"
  ],
  "files": [
    {
      "path": "lib/chart.ts",
      "content": "/**\n * chart — what the scrollfx charts share: series from a config (as shadcn's\n * chart takes one), nice ticks and scales, curves, markers, hatching for bars,\n * areas and wedges, and the pens that ink a chart in order as it scrolls in:\n * the axes first, then the hatching, then the lines in the accent colour, the\n * last pen lifting exactly as the chart reaches the middle of the screen (or,\n * with `trigger=\"view\"`, played once in the same order as it comes into view).\n *\n * Strokes are made in the browser at the chart's measured size, so hatching\n * keeps the same spacing at any width. Labels, ticks and the data table are\n * plain HTML, rendered on the server.\n *\n * Part of scrollfx (MIT): https://github.com/DhruvilChauahan0210/scrollfx\n */\n\nimport { createElement as h, Fragment, useEffect, useRef, useState, type ReactNode, type RefObject } from 'react';\nimport { ScrollDraw } from 'svg-scroll-draw/react';\nimport { hatchPolygon, scrollWindow, staggerFor } from './plotter';\n\nexport type Pt = [number, number];\n/** One row of chart data: the index key (a label) and a number per series. */\nexport type Datum = Record<string, string | number>;\n\n/** How one series is named and inked. */\nexport interface SeriesConfig {\n  label: string;\n  /** Its pen colour. The first series takes the accent, the rest the ink (currentColor). */\n  color?: string;\n}\n/** Series by key, in drawing order, like shadcn's ChartConfig. */\nexport type ChartConfig = Record<string, SeriesConfig>;\n\n/** Parallel strokes: their angle in degrees (0 across, 90 upright), spacing, and a second pass across. */\nexport interface Hatch {\n  angle: number;\n  gap: number;\n  cross?: boolean;\n}\nexport type MarkerKind = 'circle' | 'square' | 'triangle' | 'diamond' | 'cross';\n\nexport interface Series {\n  key: string;\n  label: string;\n  color: string;\n  hatch: Hatch;\n  marker: MarkerKind;\n}\n\n/** The scrollfx accent, a vermilion. */\nexport const ACCENT = '#e0482a';\n\n/** Hatches told apart by angle and density, the way a plotter shades without colour. */\nexport const HATCHES: Hatch[] = [\n  { angle: 60, gap: 5 },\n  { angle: 120, gap: 5 },\n  { angle: 90, gap: 4 },\n  { angle: 45, gap: 7, cross: true },\n  { angle: 0, gap: 4 },\n  { angle: 30, gap: 6 },\n];\nexport const MARKERS: MarkerKind[] = ['circle', 'square', 'triangle', 'diamond', 'cross'];\n\n/** The series to draw: from the config, or every numeric key in the first datum. */\nexport function seriesOf(data: Datum[], index: string, config: ChartConfig | undefined, accent: string): Series[] {\n  const keys = config ? Object.keys(config) : Object.keys(data[0] ?? {}).filter((k) => k !== index && typeof data[0][k] === 'number');\n  return keys.map((key, i) => ({\n    key,\n    label: config?.[key]?.label ?? key,\n    color: config?.[key]?.color ?? (i === 0 ? accent : 'currentColor'),\n    hatch: HATCHES[i % HATCHES.length],\n    marker: MARKERS[i % MARKERS.length],\n  }));\n}\n\nexport const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);\n\n/** Round ticks covering lo to hi, about `count` of them: steps of 1, 2 or 5 times a power of ten. */\nexport function niceTicks(lo: number, hi: number, count = 5): number[] {\n  if (!(hi > lo)) hi = lo + 1;\n  const raw = (hi - lo) / Math.max(1, count);\n  const mag = 10 ** Math.floor(Math.log10(raw));\n  const e = raw / mag;\n  const step = (e >= 7.5 ? 10 : e >= 3.5 ? 5 : e >= 1.5 ? 2 : 1) * mag;\n  const out: number[] = [];\n  for (let v = Math.floor(lo / step) * step; v <= Math.ceil(hi / step) * step + step * 1e-6; v += step) out.push(+v.toPrecision(12));\n  return out;\n}\n\n/** A linear scale from [d0, d1] to [r0, r1]. */\nexport const linear = (d0: number, d1: number, r0: number, r1: number) => (v: number) => r0 + ((v - d0) / (d1 - d0 || 1)) * (r1 - r0);\n\n/** How axis numbers are written: compact by default (1.2K). Fixed to one locale so the server and browser agree. */\nexport function formatter(format?: Intl.NumberFormatOptions, locale = 'en-US') {\n  const nf = new Intl.NumberFormat(locale, format ?? { notation: 'compact', maximumFractionDigits: 1 });\n  return (v: number) => nf.format(v);\n}\n\nconst f = (v: number) => v.toFixed(1);\nexport const toPath = (pts: Pt[]) => 'M' + pts.map(([x, y]) => `${f(x)} ${f(y)}`).join('L');\n\nexport type Curve = 'smooth' | 'linear' | 'step';\n\n/**\n * A line through points, as dense points (for hatching under it). Smooth is a\n * monotone cubic: it never overshoots a point, so a curve never dips below zero\n * between two positive values.\n */\nexport function curvePoints(pts: Pt[], curve: Curve = 'smooth', per = 14): Pt[] {\n  if (pts.length < 2) return pts;\n  if (curve === 'linear') return pts;\n  if (curve === 'step') {\n    const out: Pt[] = [pts[0]];\n    for (let i = 1; i < pts.length; i++) {\n      const mx = (pts[i - 1][0] + pts[i][0]) / 2;\n      out.push([mx, pts[i - 1][1]], [mx, pts[i][1]]);\n    }\n    out.push(pts[pts.length - 1]);\n    return out;\n  }\n  const m = monotoneTangents(pts);\n  const out: Pt[] = [pts[0]];\n  for (let i = 0; i < pts.length - 1; i++) {\n    const [x0, y0] = pts[i], [x1, y1] = pts[i + 1];\n    const dx = x1 - x0;\n    for (let k = 1; k <= per; k++) {\n      const t = k / per, t2 = t * t, t3 = t2 * t;\n      const y = (2 * t3 - 3 * t2 + 1) * y0 + (t3 - 2 * t2 + t) * dx * m[i] + (-2 * t3 + 3 * t2) * y1 + (t3 - t2) * dx * m[i + 1];\n      out.push([x0 + dx * t, y]);\n    }\n  }\n  return out;\n}\n\n/** The same line as an SVG path: cubic Béziers for smooth, so the pen runs one clean stroke. */\nexport function curvePath(pts: Pt[], curve: Curve = 'smooth'): string {\n  if (curve !== 'smooth' || pts.length < 3) return toPath(curvePoints(pts, curve));\n  const m = monotoneTangents(pts);\n  let d = `M${f(pts[0][0])} ${f(pts[0][1])}`;\n  for (let i = 0; i < pts.length - 1; i++) {\n    const [x0, y0] = pts[i], [x1, y1] = pts[i + 1];\n    const k = (x1 - x0) / 3;\n    d += `C${f(x0 + k)} ${f(y0 + k * m[i])} ${f(x1 - k)} ${f(y1 - k * m[i + 1])} ${f(x1)} ${f(y1)}`;\n  }\n  return d;\n}\n\n// Fritsch–Carlson tangents (d3's curveMonotoneX).\nfunction monotoneTangents(pts: Pt[]): number[] {\n  const n = pts.length;\n  const s = Array.from({ length: n - 1 }, (_, i) => (pts[i + 1][1] - pts[i][1]) / (pts[i + 1][0] - pts[i][0] || 1));\n  const m = pts.map((_, i) => (i === 0 ? s[0] : i === n - 1 ? s[n - 2] : s[i - 1] * s[i] <= 0 ? 0 : (s[i - 1] + s[i]) / 2));\n  for (let i = 0; i < n - 1; i++) {\n    if (s[i] === 0) { m[i] = 0; m[i + 1] = 0; continue; }\n    const a = m[i] / s[i], b = m[i + 1] / s[i];\n    const r = a * a + b * b;\n    if (r > 9) { const t = 3 / Math.sqrt(r); m[i] = t * a * s[i]; m[i + 1] = t * b * s[i]; }\n  }\n  return m;\n}\n\n/** A circle as one path the pen can draw round, starting at its right. */\nexport const circle = (cx: number, cy: number, r: number) => `M${f(cx + r)} ${f(cy)}A${f(r)} ${f(r)} 0 1 1 ${f(cx - r)} ${f(cy)}A${f(r)} ${f(r)} 0 1 1 ${f(cx + r)} ${f(cy)}`;\n\n/** A small plotted marker centred on (x, y). */\nexport function marker(kind: MarkerKind, x: number, y: number, r = 3.2): string {\n  switch (kind) {\n    case 'circle': return circle(x, y, r);\n    case 'square': return toPath([[x - r, y - r], [x + r, y - r], [x + r, y + r], [x - r, y + r], [x - r, y - r]]);\n    case 'triangle': return toPath([[x, y - r * 1.2], [x + r * 1.1, y + r * 0.8], [x - r * 1.1, y + r * 0.8], [x, y - r * 1.2]]);\n    case 'diamond': return toPath([[x, y - r * 1.3], [x + r * 1.1, y], [x, y + r * 1.3], [x - r * 1.1, y], [x, y - r * 1.3]]);\n    case 'cross': return `${toPath([[x - r, y - r], [x + r, y + r]])}${toPath([[x + r, y - r], [x - r, y + r]])}`;\n  }\n}\n\n/** A rectangle's corners, clockwise from its top left. */\nexport const rect = (x: number, y: number, w: number, hh: number): Pt[] => [[x, y], [x + w, y], [x + w, y + hh], [x, y + hh]];\n\n/** Points along an arc, angles in radians clockwise from twelve o'clock. */\nexport function arc(cx: number, cy: number, r: number, a0: number, a1: number, step = 0.04): Pt[] {\n  const n = Math.max(2, Math.ceil(Math.abs(a1 - a0) / step));\n  return Array.from({ length: n + 1 }, (_, k): Pt => {\n    const a = a0 + ((a1 - a0) * k) / n;\n    return [cx + Math.sin(a) * r, cy - Math.cos(a) * r];\n  });\n}\n\n/** A wedge of a pie (inner 0) or a ring segment of a donut, as an outline. */\nexport function wedge(cx: number, cy: number, inner: number, outer: number, a0: number, a1: number): Pt[] {\n  const o = arc(cx, cy, outer, a0, a1);\n  return inner > 0 ? [...o, ...arc(cx, cy, inner, a1, a0)] : [[cx, cy], ...o];\n}\n\n/** One stroke for the pens: its path, and how it is inked. */\nexport interface Mark {\n  d: string;\n  color?: string;\n  width?: number;\n  opacity?: number;\n}\n\n/** Hatching inside an outline (or several), as marks in one colour. */\nexport function hatchMarks(outline: Pt[] | Pt[][], hatch: Hatch, { color, width = 0.9, opacity = 0.8, inset = 2.5, reverse = false }: { color?: string; width?: number; opacity?: number; inset?: number; reverse?: boolean } = {}): Mark[] {\n  const lines = hatchPolygon(outline, { angle: hatch.angle, gap: hatch.gap, inset, reverse });\n  const cross = hatch.cross ? hatchPolygon(outline, { angle: hatch.angle + 90, gap: hatch.gap, inset, reverse }) : [];\n  return [...lines, ...cross].map((s) => ({ d: s.d, color, width, opacity }));\n}\n\n/**\n * A pen: a set of strokes inked one after another between two points of the\n * scroll. `from` and `to` are where the drawing's centre sits on the screen\n * (1 is the bottom edge, 0.5 the middle) when this pen starts and lifts;\n * `spread` is how far the strokes are staggered (see scrollWindow).\n */\nexport interface Pen {\n  marks: Mark[];\n  from: number;\n  to: number;\n  spread?: number;\n}\n\n/** When each pen works, as the chart's centre rises up the screen. The last lifts at the middle. */\nexport const PHASE = {\n  axes: { from: 1.15, to: 0.92 },\n  fill: { from: 1.06, to: 0.7 },\n  ink: { from: 0.8, to: 0.5 },\n} as const;\n\n/**\n * When a chart is inked: `scroll` ties it to the scroll, the last pen lifting\n * as the chart reaches the middle of the screen; `view` plays it once, over\n * `duration` ms, as it comes into view, each pen in the same order and overlap\n * it keeps on the scroll. Reduced motion shows it drawn either way.\n */\nexport type ChartTrigger = 'scroll' | 'view';\n\n// The span of the scroll the pens share (where the chart's centre sits, 1.15 to 0.5), for timing them in `view`.\nconst SPAN = { from: 1.15, to: 0.5 };\n\n/** The pens, layered in order in one box: each its own svg-scroll-draw drawing. */\nexport function PenLayers({ size, pens, trigger = 'scroll', duration = 1800 }: { size: { w: number; h: number }; pens: Pen[]; trigger?: ChartTrigger; duration?: number }) {\n  const span = SPAN.from - SPAN.to;\n  return h(\n    Fragment,\n    null,\n    pens.filter((p) => p.marks.length).map((p, i) => {\n      const spread = p.spread ?? 0;\n      const stagger = staggerFor(p.marks.length, spread);\n      // On arrival, each pen starts and lifts at the same share of `duration` as it does of the scroll.\n      const timing =\n        trigger === 'view'\n          ? { autoplay: true, once: true, native: false, delay: Math.max(0, ((SPAN.from - p.from) / span) * duration), duration: (((p.from - p.to) / span) * duration) / (1 + spread) }\n          : { trigger: scrollWindow(spread, { from: p.from, to: p.to }) };\n      return h(\n        ScrollDraw,\n        {\n          key: `${size.w}x${size.h}:${i}`,\n          className: 'pointer-events-none absolute inset-0',\n          'aria-hidden': true,\n          easing: 'linear',\n          progressVar: false,\n          stagger,\n          ...timing,\n          children: h(\n            'svg',\n            { viewBox: `0 0 ${size.w} ${size.h}`, 'data-ink': trigger, className: 'block size-full overflow-visible', fill: 'none', stroke: 'currentColor', strokeLinecap: 'round', strokeLinejoin: 'round' },\n            p.marks.map((m, j) => h('path', { key: j, d: m.d, stroke: m.color, strokeWidth: m.width ?? 1, opacity: m.opacity })),\n          ),\n        },\n      );\n    }),\n  );\n}\n\n/**\n * The box's size in CSS pixels, once it is in the page (null on the server\n * and the first render, so the server HTML carries no strokes). Later\n * changes, such as a phone turning, settle for a moment before redrawing.\n */\nexport function useSize<T extends HTMLElement>(): [RefObject<T | null>, { w: number; h: number } | null] {\n  const ref = useRef<T>(null);\n  const [size, setSize] = useState<{ w: number; h: number } | null>(null);\n  useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    let timer = 0;\n    const read = () => {\n      const w = Math.round(el.clientWidth), hh = Math.round(el.clientHeight);\n      if (w > 0 && hh > 0) setSize((s) => (s && s.w === w && s.h === hh ? s : { w, h: hh }));\n    };\n    read();\n    const ro = new ResizeObserver(() => { clearTimeout(timer); timer = window.setTimeout(read, 120); });\n    ro.observe(el);\n    return () => { ro.disconnect(); clearTimeout(timer); };\n  }, []);\n  return [ref, size];\n}\n\n/** The width YLabels takes for these labels, to indent what sits under the plot by the same. */\nexport const gutter = (labels: string[]) => `${(Math.max(2, ...labels.map((l) => l.length)) * 1.15 + 1).toFixed(2)}ch`;\n\nconst LABEL = 'font-mono text-[11px] uppercase tracking-[0.12em] text-muted-foreground';\n\n/** Labels up the left of a plot, each centred on its fraction of the height (0 at the bottom). */\nexport function YLabels({ ticks }: { ticks: { label: string; at: number }[] }) {\n  const width = Math.max(2, ...ticks.map((t) => t.label.length)) * 1.15 + 1;\n  return h(\n    'div',\n    { 'data-slot': 'y-labels', className: `relative shrink-0 ${LABEL} tabular-nums`, style: { width: `${width}ch` } },\n    ticks.map((t, i) => h('span', { key: i, className: 'absolute right-[1ch] -translate-y-1/2 whitespace-nowrap leading-none', style: { top: `${((1 - t.at) * 100).toFixed(2)}%` } }, t.label)),\n  );\n}\n\n// Container widths (rem) at which a label may show, as whole class names so Tailwind finds them.\nconst TIERS: [number, string][] = [\n  [20, 'hidden @xs:block'], [24, 'hidden @sm:block'], [28, 'hidden @md:block'], [32, 'hidden @lg:block'],\n  [36, 'hidden @xl:block'], [42, 'hidden @2xl:block'], [48, 'hidden @3xl:block'], [56, 'hidden @4xl:block'], [64, 'hidden @5xl:block'],\n];\nconst tier = (rem: number) => (rem <= 16 ? '' : (TIERS.find(([w]) => w >= rem) ?? TIERS[TIERS.length - 1])[1]);\n\n/**\n * Labels along the bottom, each centred on its fraction of the width; the\n * ones at the very ends align inward so they stay inside. Where the chart is\n * too narrow for them all (a container query, so it holds in a card as on a\n * phone), every other one goes, then all but every fourth.\n */\nexport function XLabels({ ticks, offset }: { ticks: { label: string; at: number }[]; offset?: string }) {\n  // The room they all need: about half a rem a character, with a gap of two.\n  const need = ticks.length * (Math.max(...ticks.map((t) => t.label.length), 1) + 2) * 0.5;\n  return h(\n    'div',\n    { 'data-slot': 'x-labels', className: `@container relative mt-2.5 h-4 ${LABEL} tabular-nums`, style: offset ? { marginLeft: offset } : undefined },\n    ticks.map((t, i) =>\n      h(\n        'span',\n        {\n          key: i,\n          className: `absolute top-0 whitespace-nowrap leading-none ${t.at < 0.02 ? '' : t.at > 0.98 ? '-translate-x-full' : '-translate-x-1/2'} ${tier(i % 4 === 0 ? need / 4 : i % 2 === 0 ? need / 2 : need)}`,\n          style: { left: `${(t.at * 100).toFixed(2)}%` },\n        },\n        t.label,\n      ),\n    ),\n  );\n}\n\n/** A key: a small swatch for each series, drawn as its strokes are, beside its label. */\nexport function Legend({ series, kind, className = '' }: { series: Series[]; kind: 'line' | 'hatch' | 'marker'; className?: string }) {\n  return h(\n    'ul',\n    { 'data-slot': 'legend', className: `flex flex-wrap items-center gap-x-6 gap-y-2 ${LABEL} ${className}` },\n    series.map((s) =>\n      h(\n        'li',\n        { key: s.key, className: 'flex items-center gap-2' },\n        h('svg', { viewBox: '0 0 18 12', className: 'h-3 w-[18px] shrink-0 overflow-visible', fill: 'none', stroke: 'currentColor', strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }, swatch(s, kind)),\n        h('span', { className: 'text-foreground/80' }, s.label),\n      ),\n    ),\n  );\n}\n\nfunction swatch(s: Series, kind: 'line' | 'hatch' | 'marker'): ReactNode {\n  if (kind === 'hatch') {\n    const box = rect(1, 1, 16, 10);\n    return [\n      ...hatchMarks(box, { ...s.hatch, gap: Math.max(2.4, s.hatch.gap * 0.55) }, { inset: 0.5, width: 0.8 }).map((m, i) => h('path', { key: i, d: m.d, strokeWidth: 0.8, opacity: 0.85 })),\n      h('path', { key: 'o', d: toPath([...box, box[0]]), stroke: s.color, strokeWidth: 1.2 }),\n    ];\n  }\n  if (kind === 'marker') return h('path', { d: marker(s.marker, 9, 6, 3.4), stroke: s.color, strokeWidth: 1.3 });\n  return [h('path', { key: 'l', d: 'M1 6L17 6', stroke: s.color, strokeWidth: 1.6 }), h('path', { key: 'm', d: marker(s.marker, 9, 6, 2.6), stroke: s.color, strokeWidth: 1.2, fill: 'var(--background, white)' })];\n}\n\n/** The numbers behind a chart, as a table only screen readers see. */\nexport function DataTable({ caption, head, rows }: { caption: string; head: string[]; rows: (string | number)[][] }) {\n  return h(\n    'table',\n    { className: 'sr-only' },\n    h('caption', null, caption),\n    h('thead', null, h('tr', null, head.map((c, i) => h('th', { key: i, scope: 'col' }, c)))),\n    h('tbody', null, rows.map((r, i) => h('tr', { key: i }, r.map((c, j) => (j === 0 ? h('th', { key: j, scope: 'row' }, c) : h('td', { key: j }, c)))))),\n  );\n}\n",
      "type": "registry:lib"
    }
  ],
  "type": "registry:lib"
}