{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "realtime-line-chart",
  "title": "Realtime Line Chart",
  "description": "A live streaming line chart: a new reading every second glides in from the right, the scale eases to fit, readings over the alert threshold turn the line red, and a pulsing live badge, pause button and current / average / peak / alerts stats sit above it.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/realtime-line-chart/realtime-line-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type ChartTheme = \"dark\" | \"light\";\n\nexport interface RealtimeLineChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"div\">,\n  \"title\"\n> {\n  theme?: ChartTheme;\n  title?: string;\n  subtitle?: string;\n  /** Produces the next value from the previous one. Defaults to a simulated latency feed. */\n  next?: (previous: number) => number;\n  /** Values to start with (oldest first); the window is padded from these. */\n  initial?: number[];\n  /** Milliseconds between points. */\n  interval?: number;\n  /** How many points the window holds. */\n  windowSize?: number;\n  /** Values above this are alerts: the line turns red and the counter goes up. */\n  threshold?: number;\n  unit?: string;\n  color?: string;\n  alertColor?: string;\n  /** Height of the plot, in px. */\n  height?: number;\n  formatValue?: (value: number) => string;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#0E0E0E\",\n    border: \"rgba(255,255,255,0.08)\",\n    text: \"#F4F5F7\",\n    sub: \"rgba(255,255,255,0.55)\",\n    grid: \"rgba(255,255,255,0.06)\",\n    axis: \"rgba(255,255,255,0.45)\",\n    tip: \"rgba(20,20,20,0.96)\",\n    tipBorder: \"rgba(255,255,255,0.12)\",\n    chip: \"rgba(255,255,255,0.06)\",\n    line: \"#87FFE3\",\n    alert: \"#FF6B78\",\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(0,0,0,0.07)\",\n    text: \"#111317\",\n    sub: \"rgba(17,19,23,0.55)\",\n    grid: \"rgba(17,19,23,0.06)\",\n    axis: \"rgba(17,19,23,0.5)\",\n    tip: \"rgba(255,255,255,0.98)\",\n    tipBorder: \"rgba(0,0,0,0.08)\",\n    chip: \"rgba(17,19,23,0.05)\",\n    line: \"#0E9F80\",\n    alert: \"#E5484D\",\n  },\n};\n\n// A believable p95 latency feed: drifts around a baseline, with the odd spike.\nfunction makeSimulator(random: () => number, start = 0) {\n  let spike = 0;\n  let n = start;\n  return (prev: number) => {\n    if (spike <= 0 && random() < 0.05) spike = 3 + Math.floor(random() * 4);\n    n++;\n    // A slow swell from a step counter (not the clock), so a seeded run is the same everywhere.\n    const target = spike > 0 ? 210 + random() * 60 : 118 + Math.sin(n / 9) * 14;\n    if (spike > 0) spike--;\n    return Math.max(40, prev + (target - prev) * 0.45 + (random() - 0.5) * 22);\n  };\n}\n\nfunction seeded(seed: number) {\n  let s = seed;\n  return () => (s = (s * 16807) % 2147483647) / 2147483647;\n}\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(entry.contentRect.width),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\nfunction niceStep(span: number, count = 4) {\n  const raw = Math.max(1e-9, span / count);\n  const mag = Math.pow(10, Math.floor(Math.log10(raw)));\n  return (\n    [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? 10 * mag\n  );\n}\n\ntype Point = { i: number; v: number };\n\nconst M = { top: 12, right: 64, bottom: 26, left: 8 };\n\nexport function RealtimeLineChart({\n  theme = \"dark\",\n  title = \"API latency\",\n  subtitle = \"p95 across all regions, live\",\n  next,\n  initial,\n  interval = 1000,\n  windowSize = 60,\n  threshold = 180,\n  unit = \"ms\",\n  color,\n  alertColor,\n  height = 240,\n  formatValue = (v) => `${Math.round(v)}`,\n  className,\n  style,\n  ...props\n}: RealtimeLineChartProps) {\n  const pal = PALETTES[theme];\n  const lineColor = color ?? pal.line;\n  const alert = alertColor ?? pal.alert;\n  const reduce = useReducedMotion();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(plotRef);\n  const id = React.useId();\n\n  // The first window is generated from a fixed seed, so the server and the first client render match.\n  const [points, setPoints] = React.useState<Point[]>(() => {\n    const gen = next ?? makeSimulator(seeded(5));\n    const out: Point[] = [];\n    let v = initial?.[0] ?? 120;\n    for (let i = 0; i < windowSize + 1; i++) {\n      v = initial?.[i] ?? (i === 0 ? v : gen(v));\n      out.push({ i, v });\n    }\n    return out;\n  });\n  const [paused, setPaused] = React.useState(false);\n  const [visible, setVisible] = React.useState(true);\n  // Fraction of the way to the next point, so the line glides left between ticks.\n  const [phase, setPhase] = React.useState(0);\n  const [domain, setDomain] = React.useState<[number, number]>(() => [0, 300]);\n  const [hover, setHover] = React.useState<number | null>(null);\n  const genRef = React.useRef<((p: number) => number) | null>(null);\n  const domainRef = React.useRef<[number, number] | null>(null);\n\n  React.useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    const io = new IntersectionObserver(([entry]) =>\n      setVisible(entry.isIntersecting),\n    );\n    io.observe(el);\n    const onVis = () =>\n      setVisible(!document.hidden && el.getBoundingClientRect().bottom > 0);\n    document.addEventListener(\"visibilitychange\", onVis);\n    return () => {\n      io.disconnect();\n      document.removeEventListener(\"visibilitychange\", onVis);\n    };\n  }, []);\n\n  const running = !paused && visible;\n  React.useEffect(() => {\n    if (!running) return;\n    genRef.current ??= next ?? makeSimulator(Math.random, windowSize);\n    const timer = window.setInterval(() => {\n      setPoints((ps) => {\n        const last = ps[ps.length - 1];\n        const v = genRef.current!(last.v);\n        return [...ps.slice(-windowSize), { i: last.i + 1, v }];\n      });\n    }, interval);\n    return () => window.clearInterval(timer);\n  }, [running, interval, windowSize, next]);\n\n  // One animation loop: glide the line between ticks and ease the y range toward the data.\n  const lastTick = React.useRef(0);\n  const lastIndex = points[points.length - 1]?.i ?? 0;\n  React.useEffect(() => {\n    lastTick.current = performance.now();\n  }, [lastIndex]);\n  const lo = Math.min(...points.map((p) => p.v), threshold);\n  const hi = Math.max(...points.map((p) => p.v), threshold);\n  const targetLo = Math.max(0, lo - (hi - lo) * 0.15);\n  const targetHi = hi + (hi - lo) * 0.18;\n  React.useEffect(() => {\n    let raf = 0;\n    const tick = () => {\n      const k =\n        reduce || !running\n          ? running\n            ? 1\n            : 0\n          : Math.min(1, (performance.now() - lastTick.current) / interval);\n      setPhase(reduce ? 0 : k);\n      const d = domainRef.current ?? [targetLo, targetHi];\n      const ease = reduce ? 1 : 0.08;\n      const nd: [number, number] = [\n        d[0] + (targetLo - d[0]) * ease,\n        d[1] + (targetHi - d[1]) * ease,\n      ];\n      domainRef.current = nd;\n      setDomain(nd);\n      if (running && !reduce) raf = requestAnimationFrame(tick);\n    };\n    raf = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(raf);\n  }, [running, reduce, interval, targetLo, targetHi]);\n\n  const plotW = Math.max(0, width - M.left - M.right);\n  const step = plotW / Math.max(1, windowSize - 1);\n  // The newest point sits at the right edge once its tick has fully slid in.\n  const xAt = (i: number) =>\n    M.left +\n    plotW -\n    (lastIndex - i) * step +\n    (running && !reduce ? (1 - phase) * step : 0);\n  const [d0, d1] = domain;\n  const yAt = (v: number) =>\n    M.top + height - ((v - d0) / Math.max(1e-9, d1 - d0)) * height;\n  const pts = points.map((p) => [xAt(p.i), yAt(p.v)] as [number, number]);\n  const line = pts\n    .map(([x, y], k) => `${k ? \"L\" : \"M\"}${x.toFixed(1)},${y.toFixed(1)}`)\n    .join(\"\");\n  const area = pts.length\n    ? `${line}L${pts[pts.length - 1][0]},${M.top + height}L${pts[0][0]},${M.top + height}Z`\n    : \"\";\n  const tStep = niceStep(d1 - d0);\n  const ticks: number[] = [];\n  for (let v = Math.ceil(d0 / tStep) * tStep; v <= d1; v += tStep)\n    ticks.push(v);\n\n  const windowPts = points.slice(-windowSize);\n  const current = points[points.length - 1]?.v ?? 0;\n  const avg =\n    windowPts.reduce((s, p) => s + p.v, 0) / Math.max(1, windowPts.length);\n  const peak = Math.max(...windowPts.map((p) => p.v));\n  const alerts = windowPts.filter((p) => p.v > threshold).length;\n  const over = current > threshold;\n  const secs = (windowSize * interval) / 1000;\n  const timeMarks = [0, 0.25, 0.5, 0.75, 1].map((f) => ({\n    f,\n    label: f === 1 ? \"now\" : `−${Math.round(secs * (1 - f))}s`,\n  }));\n\n  const pick = (clientX: number) => {\n    const r = plotRef.current?.getBoundingClientRect();\n    if (!r) return;\n    const x = clientX - r.left;\n    let best = null as number | null;\n    let bestD = Infinity;\n    points.forEach((p) => {\n      const d = Math.abs(xAt(p.i) - x);\n      if (d < bestD && xAt(p.i) >= M.left - 1) {\n        bestD = d;\n        best = p.i;\n      }\n    });\n    setHover(best);\n  };\n  const hp = hover !== null ? points.find((p) => p.i === hover) : null;\n  const hx = hp ? xAt(hp.i) : 0;\n  const ago = hp ? Math.round(((lastIndex - hp.i) * interval) / 1000) : 0;\n\n  return (\n    <div\n      ref={rootRef}\n      className={cn(\n        \"w-full overflow-hidden rounded-[20px] p-5 sm:p-7\",\n        className,\n      )}\n      style={{\n        background: pal.card,\n        border: `1px solid ${pal.border}`,\n        color: pal.text,\n        fontFamily: \"Inter, -apple-system, BlinkMacSystemFont, sans-serif\",\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-4\">\n        <div className=\"min-w-0\">\n          <p className=\"flex items-center gap-2 text-[15px] font-semibold tracking-[-0.01em]\">\n            {title}\n            <span\n              className=\"flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[10.5px] font-semibold tracking-[0.06em] uppercase\"\n              style={{\n                background: pal.chip,\n                color: paused ? pal.sub : over ? alert : lineColor,\n              }}\n            >\n              <span className=\"relative flex size-1.5\">\n                {!paused && !reduce && (\n                  <span\n                    className=\"absolute inset-0 animate-ping rounded-full opacity-70\"\n                    style={{ background: over ? alert : lineColor }}\n                  />\n                )}\n                <span\n                  className=\"relative size-1.5 rounded-full\"\n                  style={{\n                    background: paused ? pal.sub : over ? alert : lineColor,\n                  }}\n                />\n              </span>\n              {paused ? \"Paused\" : \"Live\"}\n            </span>\n          </p>\n          {subtitle && (\n            <p className=\"mt-1 text-[12.5px]\" style={{ color: pal.sub }}>\n              {subtitle}\n            </p>\n          )}\n        </div>\n        <button\n          type=\"button\"\n          onClick={() => setPaused((p) => !p)}\n          aria-pressed={paused}\n          className=\"flex cursor-pointer items-center gap-1.5 rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors\"\n          style={{ background: pal.chip }}\n        >\n          {paused ? (\n            <svg width=\"10\" height=\"10\" viewBox=\"0 0 10 10\" aria-hidden=\"true\">\n              <path d=\"M2 1l7 4-7 4z\" fill=\"currentColor\" />\n            </svg>\n          ) : (\n            <svg width=\"10\" height=\"10\" viewBox=\"0 0 10 10\" aria-hidden=\"true\">\n              <path d=\"M2 1h2v8H2zM6 1h2v8H6z\" fill=\"currentColor\" />\n            </svg>\n          )}\n          {paused ? \"Resume\" : \"Pause\"}\n        </button>\n      </div>\n\n      <dl className=\"mt-4 grid grid-cols-2 gap-x-6 gap-y-3 sm:grid-cols-4\">\n        {(\n          [\n            [\n              \"Current\",\n              `${formatValue(current)} ${unit}`,\n              over ? alert : pal.text,\n            ],\n            [`Avg (${secs}s)`, `${formatValue(avg)} ${unit}`, pal.text],\n            [\n              \"Peak\",\n              `${formatValue(peak)} ${unit}`,\n              peak > threshold ? alert : pal.text,\n            ],\n            [\"Alerts\", `${alerts}`, alerts ? alert : pal.text],\n          ] as const\n        ).map(([k, v, c]) => (\n          <div key={k}>\n            <dt className=\"text-[11.5px]\" style={{ color: pal.sub }}>\n              {k}\n            </dt>\n            <dd\n              className=\"mt-0.5 text-[19px] leading-tight font-semibold tracking-[-0.02em] tabular-nums\"\n              style={{ color: c }}\n            >\n              {v}\n            </dd>\n          </div>\n        ))}\n      </dl>\n\n      <div\n        ref={plotRef}\n        role=\"img\"\n        aria-label={`${title}: ${formatValue(current)} ${unit} now, average ${formatValue(avg)} ${unit} and peak ${formatValue(peak)} ${unit} over the last ${secs} seconds, ${alerts} readings above ${formatValue(threshold)} ${unit}.`}\n        onPointerMove={(e) => pick(e.clientX)}\n        onPointerDown={(e) => pick(e.clientX)}\n        onPointerLeave={(e) => e.pointerType === \"mouse\" && setHover(null)}\n        className=\"relative mt-4 w-full\"\n        style={{ height: height + M.top + M.bottom }}\n      >\n        {width > 0 && (\n          <svg\n            width={width}\n            height={height + M.top + M.bottom}\n            className=\"block\"\n            aria-hidden=\"true\"\n          >\n            <defs>\n              <clipPath id={`${id}-plot`}>\n                <rect\n                  x={M.left}\n                  y={0}\n                  width={plotW}\n                  height={height + M.top + 2}\n                />\n              </clipPath>\n              <clipPath id={`${id}-over`}>\n                <rect\n                  x={M.left}\n                  y={0}\n                  width={plotW}\n                  height={Math.max(0, yAt(threshold))}\n                />\n              </clipPath>\n              <linearGradient id={`${id}-area`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                <stop offset=\"0%\" stopColor={lineColor} stopOpacity={0.28} />\n                <stop offset=\"100%\" stopColor={lineColor} stopOpacity={0} />\n              </linearGradient>\n            </defs>\n            {ticks.map((t) => (\n              <g key={t}>\n                <line\n                  x1={M.left}\n                  x2={M.left + plotW}\n                  y1={yAt(t)}\n                  y2={yAt(t)}\n                  stroke={pal.grid}\n                />\n                <text\n                  x={M.left + plotW + 10}\n                  y={yAt(t) + 4}\n                  fontSize={11}\n                  fill={pal.axis}\n                  className=\"tabular-nums\"\n                >\n                  {formatValue(t)}\n                </text>\n              </g>\n            ))}\n            {timeMarks.map(({ f, label }) => (\n              <text\n                key={label}\n                x={M.left + plotW * f}\n                y={M.top + height + 18}\n                textAnchor={f === 0 ? \"start\" : f === 1 ? \"end\" : \"middle\"}\n                fontSize={11}\n                fill={pal.axis}\n              >\n                {label}\n              </text>\n            ))}\n            <line\n              x1={M.left}\n              x2={M.left + plotW}\n              y1={yAt(threshold)}\n              y2={yAt(threshold)}\n              stroke={alert}\n              strokeOpacity={0.7}\n              strokeDasharray=\"4 4\"\n            />\n            <text\n              x={M.left + 6}\n              y={yAt(threshold) - 6}\n              fontSize={10.5}\n              fontWeight={600}\n              fill={alert}\n            >\n              Alert above {formatValue(threshold)} {unit}\n            </text>\n            <g clipPath={`url(#${id}-plot)`}>\n              <path d={area} fill={`url(#${id}-area)`} />\n              <path\n                d={line}\n                fill=\"none\"\n                stroke={lineColor}\n                strokeWidth={2}\n                strokeLinejoin=\"round\"\n              />\n              {/* The same line, clipped to the area above the threshold and drawn in the alert colour. */}\n              <path\n                d={line}\n                fill=\"none\"\n                stroke={alert}\n                strokeWidth={2.2}\n                strokeLinejoin=\"round\"\n                clipPath={`url(#${id}-over)`}\n              />\n            </g>\n            {pts.length > 0 && (\n              <g>\n                <circle\n                  cx={pts[pts.length - 1][0]}\n                  cy={pts[pts.length - 1][1]}\n                  r={4}\n                  fill={over ? alert : lineColor}\n                />\n                <circle\n                  cx={pts[pts.length - 1][0]}\n                  cy={pts[pts.length - 1][1]}\n                  r={8}\n                  fill={over ? alert : lineColor}\n                  opacity={0.25}\n                />\n                <rect\n                  x={M.left + plotW + 4}\n                  y={pts[pts.length - 1][1] - 10}\n                  width={56}\n                  height={20}\n                  rx={5}\n                  fill={over ? alert : lineColor}\n                />\n                <text\n                  x={M.left + plotW + 32}\n                  y={pts[pts.length - 1][1] + 4}\n                  textAnchor=\"middle\"\n                  fontSize={11}\n                  fontWeight={700}\n                  fill={theme === \"dark\" ? \"#0E0E0E\" : \"#FFFFFF\"}\n                  className=\"tabular-nums\"\n                >\n                  {formatValue(current)}\n                </text>\n              </g>\n            )}\n            {hp && (\n              <g>\n                <line\n                  x1={hx}\n                  x2={hx}\n                  y1={M.top}\n                  y2={M.top + height}\n                  stroke={pal.text}\n                  strokeOpacity={0.5}\n                  strokeDasharray=\"2 3\"\n                />\n                <circle\n                  cx={hx}\n                  cy={yAt(hp.v)}\n                  r={4.5}\n                  fill={pal.card}\n                  stroke={hp.v > threshold ? alert : lineColor}\n                  strokeWidth={2}\n                />\n              </g>\n            )}\n          </svg>\n        )}\n        {hp && (\n          <div\n            className=\"pointer-events-none absolute top-1 z-10 rounded-xl px-3 py-2 text-[12px] whitespace-nowrap shadow-xl\"\n            style={{\n              left: hx > width - 180 ? undefined : hx + 12,\n              right: hx > width - 180 ? width - hx + 12 : undefined,\n              background: pal.tip,\n              border: `1px solid ${pal.tipBorder}`,\n              backdropFilter: \"blur(8px)\",\n            }}\n          >\n            <span\n              className=\"font-semibold tabular-nums\"\n              style={{ color: hp.v > threshold ? alert : pal.text }}\n            >\n              {formatValue(hp.v)} {unit}\n            </span>\n            <span style={{ color: pal.sub }}>\n              {\" \"}\n              · {ago === 0 ? \"now\" : `${ago}s ago`}\n            </span>\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}