{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "live-chart",
  "type": "registry:component",
  "title": "Live chart",
  "description": "Stream a rolling window of samples into an area, line, or bar chart that glides smoothly as each value arrives.",
  "categories": [
    "charts"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/live-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/live-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconAlertTriangle as AlertTriangle } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type LiveChartVariant = \"area\" | \"line\" | \"bars\";\n\nexport interface LiveChartProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"children\" | \"color\"\n> {\n  /** Rolling window of samples, oldest first. Append to the end (and drop from the start) to stream. */\n  data: number[];\n  /** Metric name shown in the header and used in accessible summaries. */\n  label?: string;\n  description?: React.ReactNode;\n  /** Controls or a status indicator placed at the top right. */\n  actions?: React.ReactNode;\n  /** Unit shown beside the current value, e.g. \"req/s\" or \"ms\". */\n  unit?: string;\n  variant?: LiveChartVariant;\n  /** Samples visible across the plot. Defaults to `data.length`; shorter series fill in from the right. */\n  windowSize?: number;\n  /** Milliseconds between samples. Sets the glide speed (measured from updates otherwise) and labels the time axis. */\n  interval?: number;\n  threshold?: number;\n  thresholdLabel?: string;\n  /** Which side of `threshold` counts as a breach. */\n  alertWhen?: \"above\" | \"below\";\n  /** Show min, average, max and p95 for the visible window. */\n  stats?: boolean;\n  valueFormatter?: (value: number) => string;\n  /** Formats axis ticks. Defaults to a compact number. */\n  axisFormatter?: (value: number) => string;\n  /** Plot height in pixels. */\n  height?: number;\n  /** Fix the bottom of the value axis. Area and bar charts start at zero by default. */\n  min?: number;\n  /** Fix the top of the value axis. Otherwise it expands immediately and shrinks after a calm period. */\n  max?: number;\n  /** Any CSS color. Defaults to chart-1. */\n  color?: string;\n}\n\n// Plot insets keep the head marker and the top tick label inside the frame.\nconst PAD_TOP = 14;\nconst PAD_BOTTOM = 6;\n// Share of the incoming slope kept as each point's tangent. Past-only tangents keep\n// every curve segment final the moment it appears, so nothing wobbles as it scrolls.\nconst TENSION = 0.5;\nconst LEAD = 3;\nconst SHRINK_AFTER = 6;\nconst HEAD_SAMPLES = 24;\n\nconst formats = [0, 1, 2].map(\n  (digits) => new Intl.NumberFormat(\"en-US\", { maximumFractionDigits: digits }),\n);\nconst valueFormat = formats[1];\nconst compactFormat = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\n// Fewer decimals as magnitude grows, so readouts keep a steady width.\nconst defaultValueFormatter = (value: number) =>\n  formats[Math.abs(value) >= 100 ? 0 : Math.abs(value) >= 10 ? 1 : 2].format(value);\nconst defaultAxisFormatter = (value: number) =>\n  Math.abs(value) >= 1000\n    ? compactFormat.format(value).replace(\"K\", \"k\")\n    : valueFormat.format(value);\n\n/* ------------------------------------------------------------------------ */\n/* Scales                                                                    */\n/* ------------------------------------------------------------------------ */\n\ninterface Domain {\n  lo: number;\n  hi: number;\n  step: number;\n}\n\nconst tidy = (value: number) => +value.toPrecision(12);\n\n// \"Limit\" reads as \"above limit\"; acronyms such as \"SLO\" keep their case.\nconst inline = (text: string) => (text === text.toUpperCase() ? text : text.charAt(0).toLowerCase() + text.slice(1));\n\nfunction niceStep(span: number) {\n  const raw = span / 4;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const r = raw / magnitude;\n  return (r <= 1 ? 1 : r <= 2 ? 2 : r <= 2.5 ? 2.5 : r <= 5 ? 5 : 10) * magnitude;\n}\n\nfunction niceDomain(lo: number, hi: number, min?: number, max?: number): Domain {\n  if (!(hi > lo)) {\n    const pad = Math.abs(hi) * 0.1 || 1;\n    lo -= pad;\n    hi += pad;\n  }\n  const step = niceStep(hi - lo);\n  return {\n    lo: min ?? tidy(Math.floor(lo / step + 1e-9) * step),\n    hi: max ?? tidy(Math.ceil(hi / step - 1e-9) * step),\n    step,\n  };\n}\n\nfunction targetDomain(\n  values: number[],\n  zeroBased: boolean,\n  threshold: number | undefined,\n  min?: number,\n  max?: number,\n): Domain {\n  let lo = Infinity;\n  let hi = -Infinity;\n  for (const value of values) {\n    if (value < lo) lo = value;\n    if (value > hi) hi = value;\n  }\n  if (lo === Infinity) {\n    lo = 0;\n    hi = 1;\n  }\n  if (threshold !== undefined && Number.isFinite(threshold)) {\n    lo = Math.min(lo, threshold);\n    hi = Math.max(hi, threshold);\n  }\n  if (zeroBased) {\n    lo = Math.min(lo, 0);\n    hi = Math.max(hi, 0);\n  }\n  const span = hi - lo || Math.abs(hi) || 1;\n  return niceDomain(\n    zeroBased && lo >= 0 ? lo : lo - span * 0.1,\n    hi + span * 0.1,\n    min,\n    max,\n  );\n}\n\n/** Expand at once so nothing is clipped; shrink only after the window has stayed calm. */\nfunction stepDomain(\n  previous: Domain | undefined,\n  target: Domain,\n  calm: number,\n  min?: number,\n  max?: number,\n): [Domain, number] {\n  if (!previous) return [target, 0];\n  if (target.lo < previous.lo || target.hi > previous.hi)\n    return [\n      niceDomain(\n        Math.min(previous.lo, target.lo),\n        Math.max(previous.hi, target.hi),\n        min,\n        max,\n      ),\n      0,\n    ];\n  if (target.hi - target.lo < (previous.hi - previous.lo) * 0.8)\n    return calm + 1 >= SHRINK_AFTER ? [target, 0] : [previous, calm + 1];\n  return [previous, 0];\n}\n\nfunction ticksOf({ lo, hi, step }: Domain) {\n  const ticks: number[] = [];\n  for (let v = Math.ceil(lo / step - 1e-9) * step; v <= hi + step * 1e-6; v += step)\n    ticks.push(tidy(v));\n  return ticks;\n}\n\nfunction mapping({ lo, hi }: Domain, height: number) {\n  const a = -(height - PAD_TOP - PAD_BOTTOM) / (hi - lo || 1);\n  return { a, b: PAD_TOP - a * hi };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Frames: one per data update, carrying what the glide needs               */\n/* ------------------------------------------------------------------------ */\n\ninterface Frame {\n  key: string;\n  values: number[];\n  /** Samples that just left the window, kept so the left edge stays covered mid-glide. */\n  lead: number[];\n  /** Samples appended since the previous frame; 0 = unchanged, -1 = replaced. */\n  shift: number;\n  /** Running index of the newest sample. */\n  seq: number;\n  domain: Domain;\n  calm: number;\n}\n\nfunction sanitize(data: number[], cap: number) {\n  const start = Math.max(0, data.length - cap);\n  const out: number[] = [];\n  let last = 0;\n  for (let i = start; i < data.length; i++) {\n    const value = data[i];\n    if (Number.isFinite(value)) last = value;\n    out.push(last);\n  }\n  return out;\n}\n\nfunction detectShift(a: number[], b: number[]) {\n  if (a.length === b.length && a.every((value, i) => value === b[i])) return 0;\n  for (let k = 1; k <= LEAD; k++) {\n    const drop = a.length + k - b.length;\n    const keep = b.length - k;\n    if (drop < 0 || keep < 1) continue;\n    let match = true;\n    for (let i = 0; i < keep && match; i++) match = a[drop + i] === b[i];\n    if (match) return k;\n  }\n  return -1;\n}\n\nfunction buildFrame(\n  previous: Frame | undefined,\n  data: number[],\n  cap: number,\n  zeroBased: boolean,\n  threshold: number | undefined,\n  min?: number,\n  max?: number,\n): Frame {\n  const key = [cap, zeroBased, threshold, min, max].join();\n  const values = sanitize(data, cap);\n  const comparable = previous?.key === key ? previous : undefined;\n  const shift = comparable ? detectShift(comparable.values, values) : -1;\n  // Same samples in a new array: keep the frame so nothing restarts.\n  if (comparable && shift === 0) return comparable;\n  const dropped = previous && shift > 0 ? previous.values.length + shift - values.length : 0;\n  const [domain, calm] = stepDomain(\n    shift >= 0 ? previous?.domain : undefined,\n    targetDomain(values, zeroBased, threshold, min, max),\n    previous?.calm ?? 0,\n    min,\n    max,\n  );\n  return {\n    key,\n    values,\n    lead:\n      previous && shift > 0\n        ? [...previous.lead, ...previous.values.slice(0, dropped)].slice(-LEAD)\n        : [],\n    shift,\n    seq: (previous?.seq ?? values.length - 1) + Math.max(shift, 0),\n    domain,\n    calm,\n  };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Geometry                                                                  */\n/* ------------------------------------------------------------------------ */\n\ninterface Segment {\n  x0: number;\n  y0: number;\n  c1: number;\n  c2: number;\n  y1: number;\n}\n\nconst r2 = (value: number) => Math.round(value * 100) / 100;\n\nfunction bezier({ y0, c1, c2, y1 }: Segment, t: number) {\n  const u = 1 - t;\n  return u * u * u * y0 + 3 * u * u * t * c1 + 3 * u * t * t * c2 + t * t * t * y1;\n}\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction readTransform(element: Element | null) {\n  const value = element ? getComputedStyle(element).transform : \"none\";\n  if (!value || value === \"none\") return { x: 0, y: 0, k: 1 };\n  const matrix = new DOMMatrixReadOnly(value);\n  return { x: matrix.m41, y: matrix.m42, k: matrix.m22 };\n}\n\nfunction percentile(sorted: number[], p: number) {\n  if (!sorted.length) return 0;\n  return sorted[Math.min(sorted.length - 1, Math.ceil(p * sorted.length) - 1)];\n}\n\nfunction formatAgo(ms: number) {\n  const seconds = Math.round(ms / 1000);\n  if (seconds <= 0) return \"now\";\n  if (seconds < 120) return `${seconds}s ago`;\n  return `${Math.round(seconds / 60)}m ago`;\n}\n\nfunction formatSpan(ms: number) {\n  const seconds = Math.round(ms / 1000);\n  if (seconds < 120) return `−${seconds}s`;\n  if (seconds < 7200) return `−${Math.round(seconds / 60)}m`;\n  return `−${Math.round(seconds / 3600)}h`;\n}\n\n/* ------------------------------------------------------------------------ */\n/* LiveChart                                                                 */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A streaming chart for a fixed window of samples. Each update renders once; the\n * line then glides left on the compositor, so it stays smooth without per-frame renders.\n */\nexport function LiveChart({\n  data,\n  label = \"Live value\",\n  description,\n  actions,\n  unit,\n  variant = \"area\",\n  windowSize,\n  interval,\n  threshold,\n  thresholdLabel = \"Threshold\",\n  alertWhen = \"above\",\n  stats = true,\n  valueFormatter = defaultValueFormatter,\n  axisFormatter = defaultAxisFormatter,\n  height = 180,\n  min,\n  max,\n  color = \"var(--color-chart-1)\",\n  className,\n  style,\n  ...props\n}: LiveChartProps) {\n  const id = React.useId().replace(/:/g, \"\");\n  const reduced = useReducedMotion();\n  const bars = variant === \"bars\";\n  const zeroBased = variant !== \"line\";\n  const cap = Math.max(2, Math.round(windowSize ?? data.length));\n  const hasThreshold = threshold !== undefined && Number.isFinite(threshold);\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const rowRef = React.useRef<HTMLDivElement>(null);\n  const seriesRef = React.useRef<HTMLDivElement>(null);\n  const scaleRef = React.useRef<HTMLDivElement>(null);\n  const hoverRef = React.useRef<HTMLDivElement>(null);\n  const headRef = React.useRef<HTMLDivElement>(null);\n  const hotHeadRef = React.useRef<HTMLDivElement>(null);\n  const okHeadRef = React.useRef<HTMLDivElement>(null);\n  const frameRef = React.useRef<Frame | undefined>(undefined);\n  const committedRef = React.useRef<{ frame: Frame; width: number; height: number } | null>(null);\n  const animations = React.useRef<Animation[]>([]);\n  const cadence = React.useRef({ at: 0, every: interval ?? 1000 });\n  const pointerX = React.useRef<number | null>(null);\n\n  const [rowWidth, setRowWidth] = React.useState(0);\n  const [hoverSeq, setHoverSeq] = React.useState<number | null>(null);\n  const [gutterFloor, setGutterFloor] = React.useState(0);\n\n  // Reading the last committed frame keeps the render pure: it is only written after commit.\n  const frame = React.useMemo(\n    () =>\n      buildFrame(frameRef.current, data, cap, zeroBased, hasThreshold ? threshold : undefined, min, max),\n    [data, cap, zeroBased, threshold, min, max],\n  );\n\n  const { values, lead, domain, seq } = frame;\n  const n = values.length;\n  const latest = n ? values[n - 1] : undefined;\n  const breached = (value: number | undefined) =>\n    value !== undefined && hasThreshold\n      ? alertWhen === \"above\"\n        ? value > threshold!\n        : value < threshold!\n      : false;\n  const breach = breached(latest);\n\n  const summary = React.useMemo(() => {\n    if (!n) return null;\n    const sorted = [...values].sort((a, b) => a - b);\n    const sum = values.reduce((total, value) => total + value, 0);\n    return { min: sorted[0], max: sorted[n - 1], avg: sum / n, p95: percentile(sorted, 0.95) };\n  }, [values, n]);\n\n  const ticks = React.useMemo(() => ticksOf(domain), [domain]);\n  const tickLabels = ticks.map((tick) => axisFormatter(tick));\n  const gutterNeeded = Math.ceil(Math.max(3, ...tickLabels.map((t) => t.length)) * 6.1 + 12);\n  const gutter = Math.max(gutterNeeded, gutterFloor);\n  const W = Math.max(0, rowWidth - gutter);\n  const H = Math.max(48, height);\n  const step = bars ? W / cap : W / (cap - 1);\n  const { a, b } = mapping(domain, H);\n  const yOf = (value: number) => a * value + b;\n  const xOf = (index: number) => W - (n - 1 - index) * step - (bars ? step / 2 : 0);\n  const baseValue = Math.min(Math.max(zeroBased ? 0 : domain.lo, domain.lo), domain.hi);\n  const baseY = yOf(baseValue);\n  const thresholdY = hasThreshold ? yOf(threshold!) : 0;\n\n  const geometry = React.useMemo(() => {\n    if (!W || !n) return null;\n    const all = [...lead, ...values];\n    const offset = lead.length;\n    const xs = all.map((_, j) => xOf(j - offset));\n    const ys = all.map(yOf);\n    if (bars) {\n      const width = Math.max(1, step * 0.62);\n      const radius = Math.min(2, width / 2);\n      const shapes = all.map((value, j) => {\n        const top = Math.min(ys[j], baseY);\n        const bottom = Math.max(ys[j], baseY);\n        const left = xs[j] - width / 2;\n        const r = value >= baseValue ? Math.min(radius, bottom - top) : 0;\n        return {\n          key: seq - (n - 1 - (j - offset)),\n          latest: j === all.length - 1,\n          d:\n            `M${r2(left)} ${r2(bottom)}V${r2(top + r)}` +\n            (r ? `Q${r2(left)} ${r2(top)} ${r2(left + r)} ${r2(top)}` : \"\") +\n            `H${r2(left + width - r)}` +\n            (r ? `Q${r2(left + width)} ${r2(top)} ${r2(left + width)} ${r2(top + r)}` : \"\") +\n            `V${r2(bottom)}Z`,\n        };\n      });\n      return { bars: shapes, line: \"\", area: \"\", segments: [] as Segment[] };\n    }\n    const segments: Segment[] = [];\n    let tangent = 0;\n    let line = `M${r2(xs[0])} ${r2(ys[0])}`;\n    for (let j = 0; j < all.length - 1; j++) {\n      const slope = (ys[j + 1] - ys[j]) / step;\n      let out = tangent;\n      if (slope === 0 || out * slope <= 0) out = 0;\n      else if (Math.abs(out) > 3 * Math.abs(slope)) out = 3 * slope;\n      const into = TENSION * slope;\n      const segment = {\n        x0: xs[j],\n        y0: ys[j],\n        c1: ys[j] + (out * step) / 3,\n        c2: ys[j + 1] - (into * step) / 3,\n        y1: ys[j + 1],\n      };\n      segments.push(segment);\n      line += `C${r2(xs[j] + step / 3)} ${r2(segment.c1)} ${r2(xs[j + 1] - step / 3)} ${r2(segment.c2)} ${r2(xs[j + 1])} ${r2(ys[j + 1])}`;\n      tangent = into;\n    }\n    if (all.length === 1) line += `H${r2(xs[0] - step)}`;\n    const area = `${line}L${r2(xs[xs.length - 1])} ${r2(baseY)}L${r2(xs[0])} ${r2(baseY)}Z`;\n    return { bars: [], line, area, segments };\n  }, [frame, W, H, bars, step]);\n\n  const curveYAt = (x: number) => {\n    if (!geometry?.segments.length) return latest !== undefined ? yOf(latest) : 0;\n    const { segments } = geometry;\n    const j = Math.min(segments.length - 1, Math.max(0, Math.floor((x - segments[0].x0) / step)));\n    const t = Math.min(1, Math.max(0, (x - segments[j].x0) / step));\n    return bezier(segments[j], t);\n  };\n\n  const nearestSeq = (px: number, offset: number) => {\n    if (!n || !W) return null;\n    const i = Math.max(0, Math.min(n - 1, Math.round((px - offset - xOf(0)) / step)));\n    return seq - (n - 1 - i);\n  };\n\n  // Measure the plot once per resize; nothing measures per frame.\n  React.useLayoutEffect(() => {\n    const row = rowRef.current;\n    if (!row) return;\n    const measure = () => setRowWidth(Math.round(row.clientWidth));\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(row);\n    return () => observer.disconnect();\n  }, []);\n\n  React.useLayoutEffect(() => {\n    if (gutterNeeded > gutterFloor) setGutterFloor(gutterNeeded);\n  }, [gutterNeeded, gutterFloor]);\n\n  // Start the glide for a new frame: one compositor animation per layer, then rest.\n  React.useLayoutEffect(() => {\n    const previous = committedRef.current;\n    frameRef.current = frame;\n    committedRef.current = { frame, width: W, height: H };\n    const root = rootRef.current;\n    const changed = previous?.frame !== frame;\n    const glide =\n      !reduced &&\n      changed &&\n      !!previous &&\n      previous.width === W &&\n      previous.height === H &&\n      W > 0 &&\n      frame.shift > 0;\n\n    const now = performance.now();\n    if (changed && frame.shift > 0) {\n      const elapsed = (now - cadence.current.at) / frame.shift;\n      if (interval) cadence.current.every = interval;\n      else if (cadence.current.at && elapsed > 60 && elapsed < 10000)\n        cadence.current.every = cadence.current.every * 0.6 + elapsed * 0.4;\n      cadence.current.at = now;\n    }\n    // Slightly longer than the cadence: updates land mid-glide and motion never stalls.\n    const duration = Math.min(10000, Math.max(120, cadence.current.every * frame.shift * 1.08));\n    root?.style.setProperty(\"--live-chart-glide\", glide ? `${duration}ms` : \"0ms\");\n    if (!glide || !previous) {\n      for (const animation of animations.current) animation.cancel();\n      animations.current = [];\n      return;\n    }\n\n    const x = readTransform(seriesRef.current);\n    const y = readTransform(scaleRef.current);\n    for (const animation of animations.current) animation.cancel();\n    animations.current = [];\n\n    const start = x.x + frame.shift * step;\n    const before = mapping(previous.frame.domain, H);\n    const k = (y.k * before.a) / a;\n    const ty = y.y + y.k * before.b - k * b;\n    const timing: KeyframeAnimationOptions = { duration, easing: \"linear\" };\n    const slide = [{ transform: `translateX(${start}px)` }, { transform: \"translateX(0px)\" }];\n    // Start on the current frame (not the next one) so the hand-off from the previous glide is seamless.\n    const startAt = document.timeline.currentTime;\n    const run = (element: Element | null, keyframes: Keyframe[]) => {\n      if (!element) return;\n      const animation = element.animate(keyframes, timing);\n      if (startAt !== null) animation.startTime = startAt;\n      animations.current.push(animation);\n    };\n    run(seriesRef.current, slide);\n    run(hoverRef.current, slide);\n    if (Math.abs(k - 1) > 1e-4 || Math.abs(ty) > 0.05)\n      run(scaleRef.current, [\n        { transform: `translateY(${ty}px) scaleY(${k})` },\n        { transform: \"translateY(0px) scaleY(1)\" },\n      ]);\n\n    if (!bars && geometry) {\n      // The head rides the right edge: sample the curve where it meets the edge over time.\n      const path: Keyframe[] = [];\n      let crossing = -1;\n      const hotAtStart = breached(previous.frame.values[previous.frame.values.length - 1]);\n      for (let i = 0; i <= HEAD_SAMPLES; i++) {\n        const t = i / HEAD_SAMPLES;\n        const rest = curveYAt(W - start * (1 - t));\n        path.push({\n          transform: `translateY(${r2(ty * (1 - t) + (k + (1 - k) * t) * rest)}px)`,\n          offset: t,\n        });\n        const hot = hasThreshold && (alertWhen === \"above\" ? rest < thresholdY : rest > thresholdY);\n        if (crossing < 0 && hot === breach && hot !== hotAtStart) crossing = t;\n      }\n      run(headRef.current, path);\n      if (hasThreshold && hotAtStart !== breach) {\n        const at = Math.max(0, crossing);\n        const from = hotAtStart ? 1 : 0;\n        // Swap the head's tint at the moment it crosses the limit, not when the sample lands.\n        const swap = (value: number): Keyframe[] => [\n          { opacity: value, offset: 0 },\n          { opacity: value, offset: at },\n          { opacity: 1 - value, offset: Math.min(1, at + 0.04) },\n          { opacity: 1 - value, offset: 1 },\n        ];\n        run(hotHeadRef.current, swap(from));\n        run(okHeadRef.current, swap(1 - from));\n      }\n    }\n\n    if (pointerX.current !== null) setHoverSeq(nearestSeq(pointerX.current, start));\n  }, [frame, W, H, reduced]);\n\n  React.useEffect(\n    () => () => {\n      for (const animation of animations.current) animation.cancel();\n    },\n    [],\n  );\n\n  // Screen readers hear a calm summary at most every ten seconds, never every tick.\n  const spoken =\n    summary && latest !== undefined\n      ? `${label}: ${valueFormatter(latest)}${unit ? ` ${unit}` : \"\"}. Window min ${valueFormatter(summary.min)}, max ${valueFormatter(summary.max)}.${breach ? ` ${alertWhen === \"above\" ? \"Above\" : \"Below\"} ${inline(thresholdLabel)} of ${valueFormatter(threshold!)}.` : \"\"}`\n      : `${label}: waiting for data.`;\n  const [announcement, setAnnouncement] = React.useState(\"\");\n  const announcedAt = React.useRef(0);\n  React.useEffect(() => {\n    const now = Date.now();\n    if (!announcedAt.current) announcedAt.current = now;\n    else if (now - announcedAt.current >= 10000) {\n      announcedAt.current = now;\n      setAnnouncement(spoken);\n    }\n  }, [spoken]);\n\n  const hoverIndex = hoverSeq === null ? -1 : hoverSeq - (seq - (n - 1));\n  const hovered = hoverIndex >= 0 && hoverIndex < n ? values[hoverIndex] : undefined;\n  const hoverX = hovered !== undefined ? xOf(hoverIndex) : 0;\n\n  const handlePointer = (event: React.PointerEvent<HTMLDivElement>) => {\n    const rect = event.currentTarget.getBoundingClientRect();\n    const px = event.clientX - rect.left;\n    if (px < 0 || px > W + 4) {\n      pointerX.current = null;\n      setHoverSeq(null);\n      return;\n    }\n    pointerX.current = px;\n    setHoverSeq(nearestSeq(px, readTransform(seriesRef.current).x));\n  };\n  const clearPointer = () => {\n    pointerX.current = null;\n    setHoverSeq(null);\n  };\n\n  const glideTransition = \"transition-transform duration-(--live-chart-glide) ease-linear motion-reduce:transition-none\";\n  const strokeWidth = variant === \"line\" ? 2 : 1.75;\n  const hot = \"var(--color-destructive)\";\n\n  const renderSeries = (paint: string, tone: \"ok\" | \"hot\") => {\n    if (!geometry) return null;\n    if (bars)\n      return geometry.bars.map((bar) => (\n        <path\n          key={bar.key}\n          d={bar.d}\n          fill={paint}\n          className=\"transition-[fill-opacity] duration-500 motion-reduce:transition-none\"\n          fillOpacity={bar.latest ? 1 : 0.5}\n        />\n      ));\n    return (\n      <>\n        {variant === \"area\" && <path d={geometry.area} fill={`url(#${id}-fill-${tone})`} />}\n        <path\n          d={geometry.line}\n          fill=\"none\"\n          stroke={paint}\n          strokeWidth={6}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          className=\"opacity-[0.12] dark:opacity-25\"\n          filter={`url(#${id}-blur)`}\n        />\n        <path\n          d={geometry.line}\n          fill=\"none\"\n          stroke={paint}\n          strokeWidth={strokeWidth}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n        />\n      </>\n    );\n  };\n\n  const latestBar = bars && geometry?.bars.length ? geometry.bars[geometry.bars.length - 1] : null;\n  const span = interval ? cap * interval : 0;\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"live-chart\"\n      data-variant={variant}\n      data-breach={breach || undefined}\n      className={cn(\n        \"@container/live-chart flex min-w-0 flex-col rounded-xl border bg-card pb-4 text-card-foreground shadow-xs\",\n        className,\n      )}\n      style={style}\n      {...props}\n    >\n      <div className=\"flex flex-col gap-1 px-5 pt-4\">\n        <div className=\"flex min-h-6 flex-wrap items-center justify-between gap-x-3 gap-y-1.5\">\n          <p className=\"max-w-full truncate text-sm font-medium text-muted-foreground\">{label}</p>\n          {actions && <div className=\"ml-auto flex shrink-0 items-center gap-2\">{actions}</div>}\n        </div>\n        <div className=\"flex flex-wrap items-end justify-between gap-x-6 gap-y-2\">\n          <div className=\"flex min-w-0 flex-wrap items-baseline gap-x-1.5 gap-y-1\">\n            <span\n              className={cn(\n                \"text-3xl leading-9 font-semibold tracking-tight tabular-nums transition-colors duration-300 motion-reduce:transition-none\",\n                breach && \"text-destructive\",\n              )}\n            >\n              {latest !== undefined ? valueFormatter(latest) : \"—\"}\n            </span>\n            {unit && <span className=\"text-sm text-muted-foreground\">{unit}</span>}\n            {breach && (\n              <span className=\"ml-1 inline-flex items-center gap-1 self-center rounded-full bg-destructive/10 px-2 py-0.5 text-[11px] font-medium text-destructive\">\n                <AlertTriangle className=\"size-3\" aria-hidden=\"true\" />\n                {alertWhen === \"above\" ? \"Above\" : \"Below\"} {inline(thresholdLabel)}\n              </span>\n            )}\n          </div>\n          {stats && summary && (\n            <dl className=\"grid grid-cols-4 gap-x-4 pb-1 @md/live-chart:gap-x-5\">\n              {(\n                [\n                  [\"Min\", summary.min],\n                  [\"Avg\", summary.avg],\n                  [\"Max\", summary.max],\n                  [\"p95\", summary.p95],\n                ] as const\n              ).map(([name, value]) => (\n                <div key={name} className=\"min-w-0\">\n                  <dt className=\"text-[11px] leading-4 font-medium text-muted-foreground\">\n                    {name}\n                  </dt>\n                  <dd\n                    className={cn(\n                      \"font-mono text-xs leading-4 text-foreground tabular-nums\",\n                      breached(value) && \"text-destructive\",\n                    )}\n                  >\n                    {valueFormatter(value)}\n                  </dd>\n                </div>\n              ))}\n            </dl>\n          )}\n        </div>\n        {description && <p className=\"text-xs text-muted-foreground\">{description}</p>}\n      </div>\n\n      <div className=\"mt-4 px-5\">\n        <div\n          ref={rowRef}\n          role=\"img\"\n          aria-label={spoken}\n          className=\"relative touch-pan-y select-none\"\n          style={{ height: H }}\n          onPointerMove={handlePointer}\n          onPointerDown={handlePointer}\n          onPointerLeave={clearPointer}\n        >\n          {W > 0 && (\n            <>\n              <div aria-hidden=\"true\" className=\"absolute inset-y-0 left-0\" style={{ width: W }}>\n                {ticks.map((tick) => (\n                  <div\n                    key={tick}\n                    className={cn(\n                      \"absolute inset-x-0 top-0 h-px\",\n                      glideTransition,\n                      tick === baseValue ? \"bg-border\" : \"bg-border/60\",\n                    )}\n                    style={{ transform: `translateY(${r2(yOf(tick))}px)` }}\n                  />\n                ))}\n              </div>\n\n              <div\n                aria-hidden=\"true\"\n                className=\"absolute inset-y-0 left-0 overflow-hidden [mask-image:linear-gradient(to_right,transparent,black_36px)]\"\n                style={{ width: W }}\n              >\n                <div ref={seriesRef} className=\"absolute inset-0 will-change-transform\">\n                  <div ref={scaleRef} className=\"absolute inset-0 origin-top-left\">\n                    <svg width={W} height={H} className=\"absolute inset-0 overflow-visible\">\n                      <defs>\n                        <linearGradient id={`${id}-fill-ok`} gradientUnits=\"userSpaceOnUse\" x1=\"0\" y1={PAD_TOP} x2=\"0\" y2={H}>\n                          <stop offset=\"0\" stopColor={color} stopOpacity=\"0.26\" />\n                          <stop offset=\"1\" stopColor={color} stopOpacity=\"0.01\" />\n                        </linearGradient>\n                        <linearGradient id={`${id}-fill-hot`} gradientUnits=\"userSpaceOnUse\" x1=\"0\" y1={PAD_TOP} x2=\"0\" y2={H}>\n                          <stop offset=\"0\" stopColor={hot} stopOpacity=\"0.28\" />\n                          <stop offset=\"1\" stopColor={hot} stopOpacity=\"0.02\" />\n                        </linearGradient>\n                        <filter id={`${id}-blur`} x=\"-10%\" y=\"-50%\" width=\"120%\" height=\"200%\">\n                          <feGaussianBlur stdDeviation=\"3\" />\n                        </filter>\n                        {hasThreshold && (\n                          <>\n                            <clipPath id={`${id}-hot`}>\n                              {alertWhen === \"above\" ? (\n                                <rect x={-1e4} y={-1e4} width={2e4} height={1e4 + thresholdY} />\n                              ) : (\n                                <rect x={-1e4} y={thresholdY} width={2e4} height={2e4} />\n                              )}\n                            </clipPath>\n                            <clipPath id={`${id}-ok`}>\n                              {alertWhen === \"above\" ? (\n                                <rect x={-1e4} y={thresholdY} width={2e4} height={2e4} />\n                              ) : (\n                                <rect x={-1e4} y={-1e4} width={2e4} height={1e4 + thresholdY} />\n                              )}\n                            </clipPath>\n                          </>\n                        )}\n                      </defs>\n                      {latestBar && (\n                        <path\n                          d={latestBar.d}\n                          fill={breach ? hot : color}\n                          filter={`url(#${id}-blur)`}\n                          className=\"opacity-40 dark:opacity-60\"\n                        />\n                      )}\n                      {hasThreshold ? (\n                        <>\n                          <g clipPath={`url(#${id}-ok)`}>{renderSeries(color, \"ok\")}</g>\n                          <g clipPath={`url(#${id}-hot)`}>{renderSeries(hot, \"hot\")}</g>\n                        </>\n                      ) : (\n                        renderSeries(color, \"ok\")\n                      )}\n                    </svg>\n                  </div>\n                </div>\n              </div>\n\n              {hasThreshold && (\n                <div\n                  aria-hidden=\"true\"\n                  className={cn(\"pointer-events-none absolute top-0 left-0\", glideTransition)}\n                  style={{ width: W, transform: `translateY(${r2(thresholdY)}px)` }}\n                >\n                  <div className=\"border-t border-dashed border-destructive/55\" />\n                  <span className=\"absolute bottom-1 left-0 rounded-sm bg-card/85 px-1 font-mono text-[10px] leading-4 text-destructive\">\n                    {thresholdLabel} {valueFormatter(threshold!)}\n                  </span>\n                </div>\n              )}\n\n              <div ref={hoverRef} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 will-change-transform\">\n                {hovered !== undefined && (\n                  <>\n                    {bars ? (\n                      <div\n                        className=\"absolute inset-y-0 -translate-x-1/2 rounded-sm bg-foreground/[0.06]\"\n                        style={{ left: r2(hoverX), width: r2(Math.max(4, step * 0.92)) }}\n                      />\n                    ) : (\n                      <div className=\"absolute inset-y-0 w-px bg-foreground/25\" style={{ left: r2(hoverX) }} />\n                    )}\n                    <div\n                      className=\"absolute size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-card shadow-sm\"\n                      style={{\n                        left: r2(hoverX),\n                        top: r2(yOf(hovered)),\n                        background: breached(hovered) ? hot : color,\n                      }}\n                    />\n                    <div\n                      className={cn(\n                        \"absolute top-0 rounded-md border bg-popover px-2 py-1 whitespace-nowrap text-popover-foreground shadow-md\",\n                        hoverX > W * 0.6 ? \"-translate-x-full\" : \"\",\n                      )}\n                      style={{ left: r2(hoverX + (hoverX > W * 0.6 ? -8 : 8)) }}\n                    >\n                      <span className=\"block font-mono text-xs font-medium tabular-nums\">\n                        {valueFormatter(hovered)}\n                        {unit && <span className=\"ml-1 font-sans font-normal text-muted-foreground\">{unit}</span>}\n                      </span>\n                      <span className=\"block text-[10px] leading-3 text-muted-foreground\">\n                        {interval\n                          ? formatAgo((seq - hoverSeq!) * interval)\n                          : seq === hoverSeq\n                            ? \"Latest sample\"\n                            : `${seq - hoverSeq!} samples ago`}\n                      </span>\n                    </div>\n                  </>\n                )}\n              </div>\n\n              {!bars && latest !== undefined && (\n                <div\n                  ref={headRef}\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none absolute top-0 z-10\"\n                  style={{ left: W, transform: `translateY(${r2(yOf(latest))}px)` }}\n                >\n                  <div ref={okHeadRef} className=\"absolute top-0 left-0\" style={{ opacity: breach ? 0 : 1 }}>\n                    <HeadDot color={color} />\n                  </div>\n                  {hasThreshold && (\n                    <div ref={hotHeadRef} className=\"absolute top-0 left-0\" style={{ opacity: breach ? 1 : 0 }}>\n                      <HeadDot color={hot} />\n                    </div>\n                  )}\n                </div>\n              )}\n\n              <div aria-hidden=\"true\" className=\"absolute inset-y-0 right-0\" style={{ width: gutter }}>\n                {ticks.map((tick, i) => (\n                  <span\n                    key={tick}\n                    className={cn(\n                      \"absolute top-0 right-0 font-mono text-[10px] leading-none text-muted-foreground tabular-nums\",\n                      glideTransition,\n                    )}\n                    style={{ transform: `translateY(calc(${r2(yOf(tick))}px - 50%))` }}\n                  >\n                    {tickLabels[i]}\n                  </span>\n                ))}\n              </div>\n            </>\n          )}\n          {W > 0 && !n && (\n            <p className=\"absolute inset-0 grid place-items-center text-xs text-muted-foreground\" style={{ right: gutter }}>\n              Waiting for data…\n            </p>\n          )}\n        </div>\n        {span > 0 && W > 0 && (\n          <div aria-hidden=\"true\" className=\"relative mt-2 h-3 font-mono text-[10px] leading-3 text-muted-foreground\" style={{ width: W }}>\n            <span className=\"absolute left-0\">{formatSpan(span)}</span>\n            <span className=\"absolute left-1/2 -translate-x-1/2\">{formatSpan(span / 2)}</span>\n            <span className=\"absolute right-0\">now</span>\n          </div>\n        )}\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\" aria-atomic=\"true\">\n        {announcement}\n      </p>\n    </div>\n  );\n}\n\nfunction HeadDot({ color }: { color: string }) {\n  return (\n    <div className=\"absolute top-0 left-0\" style={{ color }}>\n      <span className=\"absolute -top-2 -left-2 size-4 animate-ping rounded-full bg-current opacity-35 [animation-duration:2.4s] motion-reduce:hidden\" />\n      <span className=\"absolute -top-[5px] -left-[5px] size-2.5 rounded-full border-2 border-card bg-current shadow-[0_0_0_3px_color-mix(in_oklab,currentColor_22%,transparent),0_0_14px_1px_currentColor]\" />\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* useLiveSeries                                                             */\n/* ------------------------------------------------------------------------ */\n\nexport interface UseLiveSeriesOptions {\n  /** Starting window, oldest first. */\n  initial: number[];\n  /** Produce the next sample from the latest one. */\n  next: (last: number) => number;\n  /** Milliseconds between samples. */\n  interval?: number;\n  /** Window length. Defaults to `initial.length`. */\n  length?: number;\n  paused?: boolean;\n}\n\n/** A rolling window that appends one sample per interval and pauses while the tab is hidden. */\nexport function useLiveSeries({\n  initial,\n  next,\n  interval = 1000,\n  length,\n  paused = false,\n}: UseLiveSeriesOptions) {\n  const size = Math.max(2, length ?? initial.length);\n  const [series, setSeries] = React.useState(() => initial.slice(-size));\n  const seriesRef = React.useRef(series);\n  const nextRef = React.useRef(next);\n  React.useEffect(() => {\n    nextRef.current = next;\n  });\n\n  React.useEffect(() => {\n    if (paused) return;\n    const timer = window.setInterval(() => {\n      if (document.hidden) return;\n      const current = seriesRef.current;\n      const value = nextRef.current(current.length ? current[current.length - 1] : 0);\n      const updated = current.slice(Math.max(0, current.length - size + 1));\n      updated.push(value);\n      seriesRef.current = updated;\n      setSeries(updated);\n    }, interval);\n    return () => window.clearInterval(timer);\n  }, [interval, size, paused]);\n\n  return series;\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/live-chart. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
