{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "realtime-monitor",
  "type": "registry:block",
  "title": "Realtime monitor",
  "description": "A live operations console that combines throughput, fleet health, objectives, and an event stream.",
  "categories": [
    "blocks"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/realtime-monitor.tsx",
      "type": "registry:component",
      "target": "components/overtrue/realtime-monitor.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconArrowDownRight,\n  IconArrowUpRight,\n  IconPlayerPauseFilled,\n  IconPlayerPlayFilled,\n  IconServer2,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { NumberTicker } from \"./number-ticker\";\nimport { LiveChart } from \"./live-chart\";\nimport { HostMap, type HostMapHost } from \"./host-map\";\nimport { LogStream, type LogEntry } from \"./log-stream\";\nimport { BulletChart, type BulletChartItem } from \"./bullet-chart\";\n\nexport interface Telemetry {\n  /** Requests per second, oldest first. */\n  requests: number[];\n  /** p95 latency in milliseconds, oldest first. */\n  latency: number[];\n  /** Failed requests as a 0–1 fraction. */\n  errorRate: number;\n  /** Error rate one minute ago, for the comparison. */\n  previousErrorRate?: number;\n  activeSessions: number;\n  previousSessions?: number;\n  hosts: HostMapHost[];\n  events: LogEntry[];\n  objectives: BulletChartItem[];\n}\n\nexport interface RealtimeMonitorProps\n  extends Omit<React.ComponentProps<\"section\">, \"title\"> {\n  data: Telemetry;\n  title?: string;\n  /** Hostname, cluster, or environment shown under the title. */\n  environment?: string;\n  paused?: boolean;\n  onPausedChange?: (paused: boolean) => void;\n  /** Samples arrive this often; keeps the chart glide in step. */\n  interval?: number;\n}\n\nconst integer = new Intl.NumberFormat(\"en-US\", { maximumFractionDigits: 0 });\n\nfunction change(current: number, previous: number | undefined) {\n  if (previous === undefined || previous === 0) return undefined;\n  return (current - previous) / previous;\n}\n\nfunction Delta({\n  value,\n  invert = false,\n  neutral = false,\n}: {\n  value: number | undefined;\n  invert?: boolean;\n  /** Movement without a better or worse direction, such as traffic. */\n  neutral?: boolean;\n}) {\n  if (value === undefined || !Number.isFinite(value)) return null;\n  const flat = Math.abs(value) < 0.0005;\n  const good = flat || neutral ? null : value > 0 !== invert;\n  const Icon = value >= 0 ? IconArrowUpRight : IconArrowDownRight;\n  return (\n    <span\n      className={cn(\n        \"inline-flex items-center gap-0.5 text-xs font-medium tabular-nums\",\n        good === null\n          ? \"text-muted-foreground\"\n          : good\n            ? \"text-emerald-700 dark:text-emerald-400\"\n            : \"text-rose-600 dark:text-rose-400\",\n      )}\n    >\n      {!flat && <Icon aria-hidden=\"true\" className=\"size-3\" stroke={2.25} />}\n      <span className=\"sr-only\">\n        {flat ? \"Unchanged\" : value > 0 ? \"Up\" : \"Down\"}{\" \"}\n      </span>\n      {Math.abs(value * 100).toFixed(1)}%\n    </span>\n  );\n}\n\nfunction Metric({\n  label,\n  children,\n  delta,\n}: {\n  label: string;\n  children: React.ReactNode;\n  delta?: React.ReactNode;\n}) {\n  return (\n    <div className=\"flex min-w-0 flex-col gap-2 px-5 py-4\">\n      <p className=\"truncate text-xs text-muted-foreground\">{label}</p>\n      <div className=\"text-2xl font-semibold tracking-tight text-card-foreground tabular-nums @3xl/monitor:text-[1.75rem]\">\n        {children}\n      </div>\n      <div className=\"flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-muted-foreground\">\n        {delta}\n        <span className=\"whitespace-nowrap\">vs. 1 min ago</span>\n      </div>\n    </div>\n  );\n}\n\n/** A live operations console: traffic, fleet health, objectives, and events. */\nexport function RealtimeMonitor({\n  data,\n  title = \"Production\",\n  environment = \"api.acme.studio\",\n  paused = false,\n  onPausedChange,\n  interval = 1000,\n  className,\n  ...props\n}: RealtimeMonitorProps) {\n  const requests = data.requests[data.requests.length - 1] ?? 0;\n  const latency = data.latency[data.latency.length - 1] ?? 0;\n  const lookback = Math.min(60, data.requests.length - 1);\n  const hostCounts = data.hosts.reduce(\n    (counts, host) => {\n      const status =\n        host.status ??\n        ((host.value ?? 0) >= 0.9\n          ? \"critical\"\n          : (host.value ?? 0) >= 0.7\n            ? \"warn\"\n            : \"ok\");\n      counts[status] = (counts[status] ?? 0) + 1;\n      return counts;\n    },\n    {} as Record<string, number>,\n  );\n  const regions = new Set(data.hosts.map((host) => host.group)).size;\n\n  return (\n    <section\n      data-slot=\"realtime-monitor\"\n      aria-label={`${title} monitor`}\n      className={cn(\n        \"@container/monitor flex min-w-0 flex-col gap-3 text-foreground sm:gap-4\",\n        className,\n      )}\n      {...props}\n    >\n      <header className=\"flex flex-wrap items-end justify-between gap-3\">\n        <div className=\"flex min-w-0 items-center gap-3\">\n          <span className=\"flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary\">\n            <IconServer2 aria-hidden=\"true\" className=\"size-[18px]\" stroke={1.75} />\n          </span>\n          <div className=\"min-w-0\">\n            <h2 className=\"truncate text-base font-semibold tracking-tight\">\n              {title}\n            </h2>\n            <p className=\"truncate text-xs text-muted-foreground\">\n              {environment} · {data.hosts.length} hosts in {regions}{\" \"}\n              {regions === 1 ? \"region\" : \"regions\"}\n            </p>\n          </div>\n        </div>\n        <div className=\"flex items-center gap-2\">\n          <span\n            className={cn(\n              \"inline-flex h-7 items-center gap-2 rounded-full border px-2.5 text-xs font-medium\",\n              paused\n                ? \"text-muted-foreground\"\n                : \"border-emerald-500/25 bg-emerald-500/10 text-emerald-800 dark:text-emerald-300\",\n            )}\n          >\n            <span className=\"relative flex size-1.5\">\n              {!paused && (\n                <span className=\"absolute inline-flex size-full animate-ping rounded-full bg-emerald-500 opacity-60 motion-reduce:animate-none\" />\n              )}\n              <span\n                className={cn(\n                  \"relative inline-flex size-1.5 rounded-full\",\n                  paused ? \"bg-muted-foreground\" : \"bg-emerald-500\",\n                )}\n              />\n            </span>\n            {paused ? \"Paused\" : \"Live\"}\n          </span>\n          {onPausedChange && (\n            <button\n              type=\"button\"\n              onClick={() => onPausedChange(!paused)}\n              aria-pressed={paused}\n              className=\"inline-flex h-7 items-center gap-1.5 rounded-md border bg-card px-2.5 text-xs font-medium text-foreground transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none\"\n            >\n              {paused ? (\n                <IconPlayerPlayFilled aria-hidden=\"true\" className=\"size-3\" />\n              ) : (\n                <IconPlayerPauseFilled aria-hidden=\"true\" className=\"size-3\" />\n              )}\n              {paused ? \"Resume\" : \"Pause\"}\n            </button>\n          )}\n        </div>\n      </header>\n\n      <div className=\"grid gap-3 sm:gap-4\">\n        <div className=\"grid grid-cols-2 gap-px overflow-hidden rounded-xl border bg-border shadow-xs @3xl/monitor:grid-cols-4 [&>*]:bg-card\">\n          <Metric\n            label=\"Requests / s\"\n            delta={\n              <Delta\n                neutral\n                value={change(requests, data.requests[data.requests.length - 1 - lookback])}\n              />\n            }\n          >\n            <NumberTicker value={Math.round(requests)} animateOnMount />\n          </Metric>\n          <Metric\n            label=\"p95 latency\"\n            delta={\n              <Delta\n                invert\n                value={change(latency, data.latency[data.latency.length - 1 - lookback])}\n              />\n            }\n          >\n            <NumberTicker\n              value={Math.round(latency)}\n              animateOnMount\n              suffix={<span className=\"ml-1 text-base font-medium text-muted-foreground\">ms</span>}\n            />\n          </Metric>\n          <Metric\n            label=\"Error rate\"\n            delta={\n              <Delta\n                invert\n                value={change(data.errorRate, data.previousErrorRate)}\n              />\n            }\n          >\n            <NumberTicker\n              value={data.errorRate}\n              animateOnMount\n              format=\"percent\"\n              formatOptions={{ style: \"percent\", minimumFractionDigits: 2, maximumFractionDigits: 2 }}\n            />\n          </Metric>\n          <Metric\n            label=\"Sessions\"\n            delta={\n              <Delta value={change(data.activeSessions, data.previousSessions)} />\n            }\n          >\n            <NumberTicker value={data.activeSessions} animateOnMount />\n          </Metric>\n        </div>\n\n        <div className=\"grid gap-3 sm:gap-4 @4xl/monitor:grid-cols-[minmax(0,1.65fr)_minmax(0,1fr)]\">\n          <LiveChart\n            data={data.requests}\n            interval={interval}\n            label=\"Throughput\"\n            description=\"Requests per second, last 2 minutes\"\n            unit=\"req/s\"\n            threshold={1600}\n            thresholdLabel=\"Autoscale\"\n            valueFormatter={(value) => integer.format(value)}\n            height={196}\n          />\n          <HostMap\n            hosts={data.hosts}\n            title=\"Fleet\"\n            description={`CPU by region · ${hostCounts.critical ?? 0} critical, ${hostCounts.warn ?? 0} warning`}\n            metricLabel=\"CPU\"\n            cellSize=\"sm\"\n            groupOrder={[\"us-east\", \"eu-west\", \"ap-south\"]}\n          />\n          <LogStream\n            entries={data.events}\n            title=\"Events\"\n            height={232}\n            maxEntries={120}\n            live={!paused}\n          />\n          <BulletChart\n            items={data.objectives}\n            title=\"Objectives\"\n            description=\"Rolling 30 days\"\n            tone=\"status\"\n          />\n        </div>\n      </div>\n    </section>\n  );\n}\n\n/* Simulation --------------------------------------------------------------- */\n\nconst regionsSeed = [\n  { group: \"us-east\", count: 24 },\n  { group: \"eu-west\", count: 16 },\n  { group: \"ap-south\", count: 12 },\n];\n\nconst eventTemplates: Omit<LogEntry, \"id\" | \"time\">[] = [\n  { level: \"info\", source: \"api\", message: \"GET /v1/projects 200 · 38 ms\" },\n  { level: \"info\", source: \"api\", message: \"POST /v1/invoices 201 · 112 ms\" },\n  { level: \"debug\", source: \"cache\", message: \"Warmed 1,204 keys for workspace acme-studio\" },\n  { level: \"info\", source: \"deploy\", message: \"web@4f2c1a9 promoted to 25% of traffic\" },\n  { level: \"info\", source: \"queue\", message: \"billing-worker drained 312 jobs\" },\n  { level: \"warn\", source: \"db\", message: \"Slow query on reports.monthly_rollup · 1.8 s\" },\n  { level: \"info\", source: \"auth\", message: \"Session refreshed for 42 users\" },\n  { level: \"error\", source: \"api\", message: \"Upstream timeout from payments-provider · retrying (1/3)\" },\n  { level: \"info\", source: \"api\", message: \"Retry succeeded for payments-provider · 640 ms\" },\n  { level: \"debug\", source: \"scheduler\", message: \"Next autoscale check in 30 s\" },\n];\n\nfunction jitter(value: number, amount: number, low: number, high: number) {\n  return Math.min(high, Math.max(low, value + (Math.random() - 0.5) * amount));\n}\n\nfunction seedSeries(length: number, base: number, swing: number) {\n  return Array.from({ length }, (_, index) =>\n    Math.round(base + Math.sin(index / 9) * swing + Math.cos(index / 4) * swing * 0.3),\n  );\n}\n\nfunction seedHosts(): HostMapHost[] {\n  let index = 0;\n  return regionsSeed.flatMap(({ group, count }) =>\n    Array.from({ length: count }, (_, n) => {\n      index += 1;\n      const value = 0.28 + ((index * 37) % 41) / 100;\n      return {\n        id: `${group}-${n + 1}`,\n        name: `${group}-node-${String(n + 1).padStart(2, \"0\")}`,\n        group,\n        value: index === 7 ? 0.93 : index === 31 ? 0.81 : value,\n      };\n    }),\n  );\n}\n\nfunction objectives(latency: number, errorRate: number): BulletChartItem[] {\n  return [\n    {\n      id: \"apdex\",\n      label: \"Apdex\",\n      sublabel: \"User satisfaction\",\n      value: Math.min(1, 0.97 - Math.max(0, latency - 180) * 0.0011),\n      target: 0.9,\n      max: 1,\n      ranges: [0.7, 0.85, 1],\n      valueFormatter: (value) => value.toFixed(2),\n    },\n    {\n      id: \"latency\",\n      label: \"p95 latency\",\n      sublabel: \"Lower is better\",\n      value: Math.round(latency),\n      target: 220,\n      max: 320,\n      ranges: [200, 260, 320],\n      invert: true,\n      valueFormatter: (value) => `${Math.round(value)} ms`,\n    },\n    {\n      id: \"budget\",\n      label: \"Error budget\",\n      sublabel: \"Remaining this month\",\n      value: Math.max(0, 74 - errorRate * 900),\n      target: 50,\n      max: 100,\n      ranges: [25, 50, 100],\n      valueFormatter: (value) => `${Math.round(value)}%`,\n    },\n    {\n      id: \"cache\",\n      label: \"Cache hit rate\",\n      sublabel: \"Edge and application\",\n      value: 0.9 + Math.sin(latency / 17) * 0.025,\n      target: 0.9,\n      max: 1,\n      ranges: [0.7, 0.85, 1],\n      valueFormatter: (value) => `${Math.round(value * 100)}%`,\n    },\n  ];\n}\n\n/**\n * Sample telemetry for demos and prototypes. Replace it with your own stream —\n * the monitor only reads the `Telemetry` you pass in.\n */\nexport function useSimulatedTelemetry({\n  interval = 1000,\n  paused = false,\n  windowSize = 120,\n}: { interval?: number; paused?: boolean; windowSize?: number } = {}) {\n  const [state, setState] = React.useState<Telemetry>(() => {\n    const start = Date.now() - 6000;\n    const latency = seedSeries(windowSize, 186, 14);\n    return {\n      requests: seedSeries(windowSize, 1240, 120),\n      latency,\n      errorRate: 0.0042,\n      previousErrorRate: 0.0047,\n      activeSessions: 18204,\n      previousSessions: 17960,\n      hosts: seedHosts(),\n      events: eventTemplates.slice(0, 6).map((event, index) => ({\n        ...event,\n        id: `seed-${index}`,\n        time: start + index * 900,\n      })),\n      objectives: objectives(latency[latency.length - 1], 0.0042),\n    };\n  });\n  const tick = React.useRef(0);\n\n  React.useEffect(() => {\n    if (paused) return;\n    const timer = window.setInterval(() => {\n      if (document.hidden) return;\n      tick.current += 1;\n      const step = tick.current;\n      setState((current) => {\n        const lastRequests = current.requests[current.requests.length - 1];\n        const surge = step % 45 > 36 ? 90 : 0;\n        const nextRequests = Math.round(\n          jitter(lastRequests + surge - (step % 45 === 0 ? 260 : 0), 140, 820, 1780),\n        );\n        const lastLatency = current.latency[current.latency.length - 1];\n        const nextLatency = Math.round(\n          jitter(lastLatency + (nextRequests - lastRequests) * 0.04, 16, 132, 296),\n        );\n        const errorRate = jitter(\n          0.0036 + Math.max(0, nextLatency - 210) * 0.00004,\n          0.0012,\n          0.0008,\n          0.018,\n        );\n        const hosts = current.hosts.map((host, index) =>\n          (index + step) % 3 === 0\n            ? {\n                ...host,\n                value: jitter(\n                  (host.value ?? 0.4) + (nextRequests - 1240) * 0.00003,\n                  0.08,\n                  0.12,\n                  index === 6 ? 0.98 : 0.86,\n                ),\n              }\n            : host,\n        );\n        const template = eventTemplates[step % eventTemplates.length];\n        const events =\n          step % 2 === 0\n            ? [\n                ...current.events.slice(-119),\n                { ...template, id: `event-${step}`, time: Date.now() },\n              ]\n            : current.events;\n        return {\n          requests: [...current.requests.slice(1), nextRequests],\n          latency: [...current.latency.slice(1), nextLatency],\n          previousErrorRate: step % 60 === 0 ? current.errorRate : current.previousErrorRate,\n          errorRate,\n          previousSessions:\n            step % 60 === 0 ? current.activeSessions : current.previousSessions,\n          activeSessions: Math.round(\n            jitter(current.activeSessions + 4, 40, 15000, 24000),\n          ),\n          hosts,\n          events,\n          objectives: objectives(nextLatency, errorRate),\n        };\n      });\n    }, interval);\n    return () => window.clearInterval(timer);\n  }, [interval, paused]);\n\n  return state;\n}\n"
    },
    {
      "path": "src/registry/overtrue/number-ticker.tsx",
      "type": "registry:component",
      "target": "components/overtrue/number-ticker.tsx",
      "content": "\"use client\";\nimport {\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useState,\n  useSyncExternalStore,\n  type ComponentProps,\n  type CSSProperties,\n  type ReactNode,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport type NumberTickerFormat = \"number\" | \"currency\" | \"percent\" | \"compact\";\n\nexport interface NumberTickerProps extends Omit<\n  ComponentProps<\"span\">,\n  \"children\" | \"prefix\"\n> {\n  value: number;\n  /** Preset Intl options. Percent expects a fraction: 0.124 renders 12.4%. */\n  format?: NumberTickerFormat;\n  /** Merged over the preset, e.g. `{ maximumFractionDigits: 0 }`. */\n  formatOptions?: Intl.NumberFormatOptions;\n  locale?: string;\n  /** ISO 4217 code used by the currency preset. */\n  currency?: string;\n  prefix?: ReactNode;\n  suffix?: ReactNode;\n  /** Roll duration in milliseconds. */\n  duration?: number;\n  /** Tint the number briefly: emerald when it rises, red when it falls. */\n  highlightChanges?: boolean;\n  /** Roll up from zero on first mount instead of rendering the value directly. */\n  animateOnMount?: boolean;\n}\n\n// Each column is a wheel of five 0–9 runs. It rests in the middle run, so two\n// rapid changes in either direction can always roll forward or backward.\nconst CELLS = 50;\nconst REST = 20;\nconst STAGGER = 32;\nconst MAX_STAGGER = 224;\nconst SLIDE_EASE = \"cubic-bezier(0.2, 1, 0.32, 1)\";\n// Overshoot scales with distance, so longer rolls get a gentler curve: every\n// wheel settles past its digit by about a tenth of a cell, whatever it travelled.\nconst SETTLE = [1.534, 1.368, 1.3, 1.262, 1.236, 1.217, 1.203, 1.191, 1.181];\nconst rollEase = (cells: number) =>\n  `cubic-bezier(0.2, ${SETTLE[Math.min(Math.max(Math.abs(cells), 1), 9) - 1]}, 0.32, 1)`;\nconst SIZE_EASE = \"cubic-bezier(0.32, 0.72, 0, 1)\";\nconst REDUCED_QUERY = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribeReducedMotion(callback: () => void) {\n  const query = window.matchMedia(REDUCED_QUERY);\n  query.addEventListener(\"change\", callback);\n  return () => query.removeEventListener(\"change\", callback);\n}\n\nfunction usePrefersReducedMotion() {\n  return useSyncExternalStore(\n    subscribeReducedMotion,\n    () => window.matchMedia(REDUCED_QUERY).matches,\n    () => false,\n  );\n}\n\nconst presets: Record<\n  NumberTickerFormat,\n  (currency: string) => Intl.NumberFormatOptions\n> = {\n  number: () => ({}),\n  currency: (currency) => ({ style: \"currency\", currency }),\n  percent: () => ({\n    style: \"percent\",\n    minimumFractionDigits: 1,\n    maximumFractionDigits: 1,\n  }),\n  compact: () => ({ notation: \"compact\", maximumSignificantDigits: 3 }),\n};\n\ninterface TickerFormatter {\n  format: Intl.NumberFormat;\n  /** The locale's digit glyphs, so Arabic-Indic or Devanagari numerals roll too. */\n  glyphs: string[];\n  /** One padded cell per wheel position, created once and shared by every column. */\n  cells: ReactNode[];\n}\n\nconst formatterCache = new Map<string, TickerFormatter>();\n\nfunction resolveOptions(\n  format: NumberTickerFormat,\n  currency: string,\n  overrides: Intl.NumberFormatOptions | undefined,\n): Intl.NumberFormatOptions {\n  const options = { ...presets[format](currency), ...overrides };\n  // Keep a preset's fixed precision from conflicting with a partial override.\n  const { minimumFractionDigits: min, maximumFractionDigits: max } = options;\n  if (min !== undefined && max !== undefined && min > max) {\n    if (overrides?.maximumFractionDigits !== undefined)\n      options.minimumFractionDigits = max;\n    else options.maximumFractionDigits = min;\n  }\n  return options;\n}\n\nfunction getFormatter(\n  locale: string,\n  options: Intl.NumberFormatOptions,\n): TickerFormatter {\n  const key = `${locale}|${JSON.stringify(options)}`;\n  let entry = formatterCache.get(key);\n  if (!entry) {\n    let format: Intl.NumberFormat;\n    try {\n      format = new Intl.NumberFormat(locale, options);\n    } catch {\n      format = new Intl.NumberFormat(\"en-US\");\n    }\n    const digits = new Intl.NumberFormat(format.resolvedOptions().locale, {\n      useGrouping: false,\n      numberingSystem: format.resolvedOptions().numberingSystem,\n    } as Intl.NumberFormatOptions);\n    const glyphs = Array.from({ length: 10 }, (_, digit) =>\n      digits.format(digit),\n    );\n    const cells = Array.from({ length: CELLS }, (_, cell) => (\n      <span key={cell} className=\"block py-(--ticker-gap)\">\n        {glyphs[cell % 10]}\n      </span>\n    ));\n    entry = { format, glyphs, cells };\n    formatterCache.set(key, entry);\n  }\n  return entry;\n}\n\ntype Slot =\n  | { key: string; kind: \"digit\"; digit: number; order: number }\n  | { key: string; kind: \"char\"; char: string };\n\ntype Item = Slot & { phase: \"idle\" | \"enter\" | \"exit\" };\n\n/**\n * Split a formatted number into keyed slots. Integer digits are keyed by place\n * value and fraction digits by position, so the ones column stays the ones\n * column when 999 becomes 1,000 and only the new leading columns enter.\n */\nfunction toSlots(value: number, formatter: TickerFormatter) {\n  if (!Number.isFinite(value)) {\n    return {\n      text: \"—\",\n      slots: [{ key: \"missing\", kind: \"char\", char: \"—\" }] as Slot[],\n    };\n  }\n  const parts = formatter.format.formatToParts(value);\n  const isDigit = (char: string) => formatter.glyphs.includes(char);\n  let integerDigits = 0;\n  for (const part of parts)\n    if (part.type === \"integer\")\n      for (const char of part.value) if (isDigit(char)) integerDigits++;\n\n  const slots: Slot[] = [];\n  const seen = new Map<string, number>();\n  let integerIndex = 0;\n  let fractionIndex = 0;\n  const pushChar = (type: string, char: string) => {\n    const count = seen.get(type) ?? 0;\n    seen.set(type, count + 1);\n    slots.push({ key: `${type}${count}:${char}`, kind: \"char\", char });\n  };\n  for (const part of parts) {\n    if (part.type === \"integer\" || part.type === \"fraction\") {\n      for (const char of part.value) {\n        const digit = formatter.glyphs.indexOf(char);\n        if (digit < 0) pushChar(part.type, char);\n        else if (part.type === \"integer\")\n          slots.push({\n            key: `i${integerDigits - 1 - integerIndex++}`,\n            kind: \"digit\",\n            digit,\n            order: 0,\n          });\n        else\n          slots.push({\n            key: `f${fractionIndex++}`,\n            kind: \"digit\",\n            digit,\n            order: 0,\n          });\n      }\n    } else if (part.type === \"group\") {\n      slots.push({\n        key: `g${integerDigits - integerIndex}:${part.value}`,\n        kind: \"char\",\n        char: part.value,\n      });\n    } else {\n      pushChar(part.type, part.value);\n    }\n  }\n  // Stagger from the rightmost digit outward, like a carry moving left.\n  let order = 0;\n  for (let i = slots.length - 1; i >= 0; i--) {\n    const slot = slots[i];\n    if (slot.kind === \"digit\") slots[i] = { ...slot, order: order++ };\n  }\n  return { text: parts.map((part) => part.value).join(\"\"), slots };\n}\n\n/** Keep removed slots in place for one transition so they can collapse out. */\nfunction mergeSlots(previous: Item[], next: Slot[], animate: boolean): Item[] {\n  const previousKeys = new Set(previous.map((item) => item.key));\n  const live: Item[] = next.map((slot) => ({\n    ...slot,\n    phase: animate && !previousKeys.has(slot.key) ? \"enter\" : \"idle\",\n  }));\n  if (!animate) return live;\n  const nextKeys = new Set(next.map((slot) => slot.key));\n  const leadingExits = new Map<string, Item[]>();\n  let pending: Item[] = [];\n  for (const item of previous) {\n    if (nextKeys.has(item.key)) {\n      if (pending.length) leadingExits.set(item.key, pending);\n      pending = [];\n    } else if (item.phase !== \"exit\") {\n      pending.push({ ...item, phase: \"exit\" });\n    }\n  }\n  const merged: Item[] = [];\n  for (const item of live) {\n    const exits = leadingExits.get(item.key);\n    if (exits) merged.push(...exits);\n    merged.push(item);\n  }\n  return merged.concat(pending);\n}\n\nfunction zeroed(slots: Slot[]): Slot[] {\n  return slots.map((slot) =>\n    slot.kind === \"digit\" ? { ...slot, digit: 0 } : slot,\n  );\n}\n\ninterface TickerState {\n  signature: string;\n  value: number;\n  items: Item[];\n  direction: number;\n  flash: \"up\" | \"down\" | null;\n  version: number;\n}\n\n/** An odometer-style number: each digit rolls on its own wheel when `value` changes. */\nexport function NumberTicker({\n  value,\n  format = \"number\",\n  formatOptions,\n  locale = \"en-US\",\n  currency = \"USD\",\n  prefix,\n  suffix,\n  duration = 800,\n  highlightChanges = false,\n  animateOnMount = false,\n  className,\n  ...props\n}: NumberTickerProps) {\n  const reduced = usePrefersReducedMotion();\n  const optionsKey = JSON.stringify(formatOptions ?? null);\n  const formatter = useMemo(\n    () => getFormatter(locale, resolveOptions(format, currency, formatOptions)),\n    // formatOptions is compared by content so inline objects stay cheap.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [locale, format, currency, optionsKey],\n  );\n  const { text, slots } = useMemo(\n    () => toSlots(value, formatter),\n    [value, formatter],\n  );\n\n  const [armed, setArmed] = useState(!animateOnMount);\n  const shown = armed ? slots : zeroed(slots);\n  const signature = (armed ? \"\" : \"0|\") + shown.map(slotKey).join(\"|\");\n  const shownValue = armed ? value : 0;\n\n  const [state, setState] = useState<TickerState>(() => ({\n    signature,\n    value: shownValue,\n    items: shown.map((slot) => ({ ...slot, phase: \"idle\" })),\n    direction: 0,\n    flash: null,\n    version: 0,\n  }));\n  if (state.signature !== signature) {\n    const direction = Math.sign(shownValue - state.value);\n    // The first roll up from zero is an entrance, not a change worth tinting.\n    const entrance = state.signature.startsWith(\"0|\");\n    setState({\n      signature,\n      value: shownValue,\n      items: mergeSlots(state.items, shown, !reduced),\n      direction,\n      flash:\n        highlightChanges && !entrance && direction !== 0\n          ? direction > 0\n            ? \"up\"\n            : \"down\"\n          : null,\n      version: state.version + 1,\n    });\n  }\n\n  // Roll up from zero after the first paint (or settle at once without motion).\n  useLayoutEffect(() => {\n    if (armed) return;\n    if (reduced) {\n      setArmed(true);\n      return;\n    }\n    let inner = 0;\n    const outer = requestAnimationFrame(() => {\n      inner = requestAnimationFrame(() => setArmed(true));\n    });\n    return () => {\n      cancelAnimationFrame(outer);\n      cancelAnimationFrame(inner);\n    };\n  }, [armed, reduced]);\n\n  // Drop collapsed slots and fade the tint once the roll has settled.\n  const { version } = state;\n  const hasExits = state.items.some((item) => item.phase === \"exit\");\n  useEffect(() => {\n    if (!hasExits) return;\n    const timer = window.setTimeout(\n      () =>\n        setState((current) =>\n          current.version === version\n            ? {\n                ...current,\n                items: current.items.filter((item) => item.phase !== \"exit\"),\n              }\n            : current,\n        ),\n      duration + MAX_STAGGER,\n    );\n    return () => window.clearTimeout(timer);\n  }, [version, hasExits, duration]);\n  const flashing = state.flash !== null;\n  useEffect(() => {\n    if (!flashing) return;\n    const timer = window.setTimeout(\n      () =>\n        setState((current) =>\n          current.version === version ? { ...current, flash: null } : current,\n        ),\n      Math.max(360, duration * 0.75),\n    );\n    return () => window.clearTimeout(timer);\n  }, [version, flashing, duration]);\n\n  const animate = !reduced;\n  return (\n    <span\n      data-slot=\"number-ticker\"\n      data-direction={\n        state.direction > 0 ? \"up\" : state.direction < 0 ? \"down\" : undefined\n      }\n      className={cn(\"inline-block whitespace-nowrap tabular-nums\", className)}\n      {...props}\n    >\n      {prefix}\n      <span className=\"sr-only\">{text}</span>\n      {/* Digits always run left to right, even inside right-to-left text. */}\n      <span\n        aria-hidden=\"true\"\n        dir=\"ltr\"\n        data-slot=\"number-ticker-value\"\n        className={cn(\n          \"transition-colors motion-reduce:transition-none\",\n          state.flash === \"up\" && \"text-emerald-700 dark:text-emerald-400\",\n          state.flash === \"down\" && \"text-red-600 dark:text-red-400\",\n        )}\n        style={{ transitionDuration: state.flash ? \"140ms\" : \"900ms\" }}\n      >\n        {state.items.map((item) => (\n          <TickerSlot\n            key={item.key}\n            item={item}\n            direction={state.direction}\n            formatter={formatter}\n            duration={duration}\n            animate={animate}\n          />\n        ))}\n      </span>\n      {suffix}\n    </span>\n  );\n}\n\nfunction slotKey(slot: Slot) {\n  return slot.kind === \"digit\" ? `${slot.key}=${slot.digit}` : slot.key;\n}\n\nfunction TickerSlot({\n  item,\n  direction,\n  formatter,\n  duration,\n  animate,\n}: {\n  item: Item;\n  direction: number;\n  formatter: TickerFormatter;\n  duration: number;\n  animate: boolean;\n}) {\n  // New slots mount collapsed, then open on the next frame so the change transitions.\n  const [open, setOpen] = useState(item.phase !== \"enter\" || !animate);\n  useEffect(() => {\n    if (open) return;\n    let inner = 0;\n    const outer = requestAnimationFrame(() => {\n      inner = requestAnimationFrame(() => setOpen(true));\n    });\n    return () => {\n      cancelAnimationFrame(outer);\n      cancelAnimationFrame(inner);\n    };\n  }, [open]);\n\n  const collapsed = !open || item.phase === \"exit\";\n  const travel = direction < 0 ? -1 : 1;\n  const offset = item.phase === \"exit\" ? -travel : travel;\n  const delay =\n    item.kind === \"digit\" ? Math.min(item.order * STAGGER, MAX_STAGGER) : 0;\n  const style: CSSProperties = {\n    gridTemplateColumns: collapsed ? \"0fr\" : \"1fr\",\n    opacity: collapsed ? 0 : 1,\n    transform: collapsed ? `translateY(${offset * 0.42}em)` : undefined,\n    transition: animate\n      ? `grid-template-columns ${duration * 0.7}ms ${SIZE_EASE}, opacity ${duration * 0.5}ms ease, transform ${duration}ms ${SLIDE_EASE}`\n      : \"none\",\n  };\n  return (\n    <span className=\"inline-grid\" style={style} data-phase={item.phase}>\n      <span className=\"min-w-0 [clip-path:inset(-50%_0)]\">\n        {item.kind === \"digit\" ? (\n          <DigitWheel\n            digit={item.digit}\n            direction={direction}\n            formatter={formatter}\n            duration={duration}\n            delay={delay}\n            animate={animate}\n          />\n        ) : (\n          <span className=\"whitespace-pre\">{item.char}</span>\n        )}\n      </span>\n    </span>\n  );\n}\n\nfunction DigitWheel({\n  digit,\n  direction,\n  formatter,\n  duration,\n  delay,\n  animate,\n}: {\n  digit: number;\n  direction: number;\n  formatter: TickerFormatter;\n  duration: number;\n  delay: number;\n  animate: boolean;\n}) {\n  const [wheel, setWheel] = useState({\n    digit,\n    cell: REST + digit,\n    travel: 0,\n    rolling: false,\n  });\n  if (wheel.digit !== digit) {\n    // Roll forward when the value rises and backward when it falls, wrapping\n    // through 9 → 0 the way a mechanical counter carries.\n    const forward = (digit - wheel.digit + 10) % 10;\n    const backward = (wheel.digit - digit + 10) % 10;\n    const step =\n      direction > 0\n        ? forward\n        : direction < 0\n          ? -backward\n          : forward <= backward\n            ? forward\n            : -backward;\n    let cell = wheel.cell + step;\n    if (cell < 0 || cell >= CELLS) cell = REST + digit;\n    setWheel(\n      animate\n        ? { digit, cell, travel: cell - wheel.cell, rolling: true }\n        : { digit, cell: REST + digit, travel: 0, rolling: false },\n    );\n  }\n\n  // Once settled, jump back to the matching cell in the middle run (same glyph).\n  useEffect(() => {\n    if (!wheel.rolling) return;\n    const timer = window.setTimeout(\n      () =>\n        setWheel((current) => ({\n          digit: current.digit,\n          cell: REST + current.digit,\n          travel: 0,\n          rolling: false,\n        })),\n      duration + delay + 40,\n    );\n    return () => window.clearTimeout(timer);\n  }, [wheel, duration, delay]);\n\n  // Cells carry --ticker-gap of padding above and below, and the clipping window\n  // reaches that far past the line box. At rest only padding shows in the\n  // overhang; while rolling, neighbors fade through it like a real wheel.\n  return (\n    <span className=\"relative inline-block [--ticker-gap:0.2em]\">\n      <span className=\"invisible\">{formatter.glyphs[digit]}</span>\n      <span className=\"absolute inset-x-0 -inset-y-(--ticker-gap) overflow-hidden [mask-image:linear-gradient(to_bottom,transparent,#000_var(--ticker-gap),#000_calc(100%_-_var(--ticker-gap)),transparent)]\">\n        <span\n          className=\"absolute inset-x-0 top-0 flex flex-col text-center\"\n          style={{\n            transform: `translateY(${(-wheel.cell * 100) / CELLS}%)`,\n            transition: wheel.rolling\n              ? `transform ${duration}ms ${rollEase(wheel.travel)} ${delay}ms`\n              : \"none\",\n            willChange: wheel.rolling ? \"transform\" : undefined,\n          }}\n        >\n          {formatter.cells}\n        </span>\n      </span>\n    </span>\n  );\n}\n"
    },
    {
      "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"
    },
    {
      "path": "src/registry/overtrue/host-map.tsx",
      "type": "registry:component",
      "target": "components/overtrue/host-map.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type HostStatus = \"ok\" | \"warn\" | \"critical\" | \"offline\";\n\nexport interface HostMapHost {\n  id: string;\n  name: string;\n  /** Region, cluster, or zone. Hosts sharing a group are drawn together. */\n  group?: string;\n  /** Metric as a 0–1 fraction, e.g. CPU utilisation. */\n  value?: number;\n  /** Explicit health. When omitted it is derived from `value` and `thresholds`. */\n  status?: HostStatus;\n}\n\nexport interface HostMapThresholds {\n  /** Values at or above this run warm. */\n  warn: number;\n  /** Values at or above this read as critical. */\n  critical: number;\n}\n\nexport interface HostMapProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"onSelect\"\n> {\n  hosts: HostMapHost[];\n  /** Color cells by metric value or by health status. */\n  colorBy?: \"value\" | \"status\";\n  /** Name of the metric, e.g. \"CPU\". */\n  metricLabel?: string;\n  /** Formats a 0–1 metric value. Defaults to a whole percent. */\n  valueFormatter?: (value: number) => string;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed under the heading, such as a metric picker. */\n  actions?: React.ReactNode;\n  cellSize?: \"sm\" | \"md\";\n  /** Where cells turn warm and critical, and how status is derived from value. */\n  thresholds?: HostMapThresholds;\n  /** Order groups explicitly. Unlisted groups follow in order of appearance. */\n  groupOrder?: string[];\n  /** Mark one host as selected. Pass null for none to expose pressed state. */\n  selectedId?: string | null;\n  /** Called when a host is clicked or activated with Enter or Space. */\n  onSelect?: (host: HostMapHost) => void;\n  showLegend?: boolean;\n  /** Noun for one cell, used in counts and labels. */\n  unit?: [singular: string, plural: string];\n}\n\nconst statusLabel: Record<HostStatus, string> = {\n  ok: \"Healthy\",\n  warn: \"Warning\",\n  critical: \"Critical\",\n  offline: \"Offline\",\n};\n\nconst statusOrder: HostStatus[] = [\"ok\", \"warn\", \"critical\", \"offline\"];\n\nconst statusFill: Record<HostStatus, string> = {\n  ok: \"bg-emerald-500/65 dark:bg-emerald-500/55\",\n  warn: \"bg-amber-400 dark:bg-amber-400/90\",\n  critical: \"bg-destructive\",\n  offline: \"border border-dashed border-muted-foreground/45 bg-transparent\",\n};\n\nconst statusDot: Record<HostStatus, string> = {\n  ok: \"bg-emerald-500\",\n  warn: \"bg-amber-400\",\n  critical: \"bg-destructive\",\n  offline: \"border border-dashed border-muted-foreground/60\",\n};\n\nconst statusText: Record<HostStatus, string> = {\n  ok: \"text-emerald-700 dark:text-emerald-400\",\n  warn: \"text-amber-700 dark:text-amber-400\",\n  critical: \"text-destructive\",\n  offline: \"text-muted-foreground\",\n};\n\nconst AMBER = \"var(--color-amber-400, oklch(82.8% 0.189 84.429))\";\n\nfunction defaultValueFormatter(value: number) {\n  return `${Math.round(value * 100)}%`;\n}\n\nfunction clamp01(value: number) {\n  return Math.min(1, Math.max(0, value));\n}\n\nfunction metricOf(host: HostMapHost) {\n  return host.value != null && Number.isFinite(host.value) ? host.value : null;\n}\n\n/**\n * Calm values ramp up the chart color; warm values move from amber towards the\n * destructive color so hot spots read before any label is checked.\n */\nfunction valueFill(value: number, warn: number, critical: number) {\n  const v = clamp01(value);\n  if (v >= critical) return \"var(--color-destructive)\";\n  if (v >= warn) {\n    const t = (v - warn) / (critical - warn || 1);\n    return `color-mix(in oklab, var(--color-destructive) ${Math.round(t * 45)}%, ${AMBER})`;\n  }\n  const t = v / (warn || 1);\n  return `color-mix(in oklab, var(--color-chart-1) ${Math.round(12 + t * 66)}%, var(--color-muted))`;\n}\n\nfunction statusOf(host: HostMapHost, warn: number, critical: number): HostStatus {\n  if (host.status) return host.status;\n  const value = metricOf(host);\n  if (value == null) return \"offline\";\n  if (value >= critical) return \"critical\";\n  if (value >= warn) return \"warn\";\n  return \"ok\";\n}\n\n/**\n * Find the cell to move to with the arrow keys, following the visual layout across\n * wrapped rows and groups. Offsets ignore the hover scale transform.\n */\nfunction neighbor(\n  cells: HTMLElement[],\n  from: HTMLElement,\n  direction: \"up\" | \"down\",\n) {\n  const top = from.offsetTop;\n  const cx = from.offsetLeft + from.offsetWidth / 2;\n  const below = direction === \"down\";\n  let rowTop: number | null = null;\n  for (const cell of cells) {\n    const ahead = below ? cell.offsetTop > top + 1 : cell.offsetTop < top - 1;\n    if (!ahead) continue;\n    if (\n      rowTop == null ||\n      (below ? cell.offsetTop < rowTop - 1 : cell.offsetTop > rowTop + 1)\n    )\n      rowTop = cell.offsetTop;\n  }\n  if (rowTop == null) return null;\n  let best: HTMLElement | null = null;\n  let bestDistance = Infinity;\n  for (const cell of cells) {\n    if (Math.abs(cell.offsetTop - rowTop) > 1) continue;\n    const distance = Math.abs(cell.offsetLeft + cell.offsetWidth / 2 - cx);\n    if (distance < bestDistance) {\n      best = cell;\n      bestDistance = distance;\n    }\n  }\n  return best;\n}\n\ninterface HostCellProps {\n  host: HostMapHost;\n  status: HostStatus;\n  fill: string | undefined;\n  label: string;\n  active: boolean;\n  selected: boolean | undefined;\n  dimmed: boolean;\n  tabStop: boolean;\n  selectable: boolean;\n  onHover: (id: string) => void;\n  onFocusCell: (id: string) => void;\n  onSelect?: (host: HostMapHost) => void;\n}\n\n/** Memoised so hovering one cell does not re-render a fleet of hundreds. */\nconst HostCell = React.memo(function HostCell({\n  host,\n  status,\n  fill,\n  label,\n  active,\n  selected,\n  dimmed,\n  tabStop,\n  selectable,\n  onHover,\n  onFocusCell,\n  onSelect,\n}: HostCellProps) {\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"host-map-cell\"\n      data-id={host.id}\n      data-status={status}\n      data-active={active || undefined}\n      data-selected={selected || undefined}\n      aria-label={label}\n      aria-pressed={selected}\n      tabIndex={tabStop ? 0 : -1}\n      onPointerEnter={() => onHover(host.id)}\n      onFocus={() => onFocusCell(host.id)}\n      onClick={onSelect ? () => onSelect(host) : undefined}\n      className={cn(\n        \"relative size-(--host-cell) rounded-[3px] outline-none\",\n        \"transition-[transform,opacity,background-color,box-shadow] duration-150 ease-out motion-reduce:transition-none\",\n        fill ? \"\" : statusFill[status],\n        dimmed && \"opacity-20\",\n        selectable ? \"cursor-pointer\" : \"cursor-default\",\n        \"data-[active]:z-10 data-[active]:scale-[1.35] data-[active]:ring-2 data-[active]:ring-foreground/85 data-[active]:ring-offset-1 data-[active]:ring-offset-card\",\n        \"focus-visible:z-10 focus-visible:scale-[1.35] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-card\",\n        \"data-[selected]:ring-2 data-[selected]:ring-primary data-[selected]:ring-offset-1 data-[selected]:ring-offset-card\",\n        status === \"critical\" &&\n          !dimmed &&\n          \"after:pointer-events-none after:absolute after:-inset-[3px] after:rounded-[5px] after:border after:border-destructive/70 after:opacity-0 motion-safe:after:animate-[host-map-pulse_2.4s_ease-out_infinite]\",\n      )}\n      style={fill ? { backgroundColor: fill } : undefined}\n    />\n  );\n});\n\n/**\n * A fleet host map: one small cell per host, pod, or node, colored by a metric or by\n * health and grouped by region. Hover or focus a cell to inspect it in a fixed readout;\n * arrow keys move through the map and Enter selects.\n */\nfunction HostMap({\n  hosts,\n  colorBy = \"value\",\n  metricLabel = \"Load\",\n  valueFormatter = defaultValueFormatter,\n  title,\n  description,\n  actions,\n  cellSize = \"md\",\n  thresholds,\n  groupOrder,\n  selectedId,\n  onSelect,\n  showLegend = true,\n  unit = [\"host\", \"hosts\"],\n  className,\n  ...props\n}: HostMapProps) {\n  const warn = thresholds?.warn ?? 0.7;\n  const critical = thresholds?.critical ?? 0.9;\n  const mapRef = React.useRef<HTMLDivElement>(null);\n  const [hoveredId, setHoveredId] = React.useState<string | null>(null);\n  const [focusedId, setFocusedId] = React.useState<string | null>(null);\n  const [tabStopId, setTabStopId] = React.useState<string | null>(null);\n  const [isolated, setIsolated] = React.useState<HostStatus | null>(null);\n\n  const onFocusCell = React.useCallback((id: string) => {\n    setFocusedId(id);\n    setTabStopId(id);\n  }, []);\n\n  const groups = React.useMemo(() => {\n    const map = new Map<string, HostMapHost[]>();\n    for (const name of groupOrder ?? []) map.set(name, []);\n    for (const host of hosts) {\n      const key = host.group ?? \"\";\n      if (!map.has(key)) map.set(key, []);\n      map.get(key)!.push(host);\n    }\n    return [...map.entries()]\n      .filter(([, members]) => members.length > 0)\n      .map(([name, members]) => {\n        const counts = { ok: 0, warn: 0, critical: 0, offline: 0 };\n        let sum = 0;\n        let measured = 0;\n        for (const host of members) {\n          const status = statusOf(host, warn, critical);\n          counts[status] += 1;\n          const value = metricOf(host);\n          if (status !== \"offline\" && value != null) {\n            sum += value;\n            measured += 1;\n          }\n        }\n        return {\n          name,\n          hosts: members,\n          counts,\n          sum,\n          measured,\n          average: measured ? sum / measured : null,\n        };\n      });\n  }, [hosts, groupOrder, warn, critical]);\n\n  const fleet = React.useMemo(() => {\n    const counts = { ok: 0, warn: 0, critical: 0, offline: 0 };\n    let sum = 0;\n    let measured = 0;\n    for (const group of groups) {\n      for (const status of statusOrder) counts[status] += group.counts[status];\n      sum += group.sum;\n      measured += group.measured;\n    }\n    return { counts, average: measured ? sum / measured : null };\n  }, [groups]);\n\n  const ordered = React.useMemo(\n    () => groups.flatMap((group) => group.hosts),\n    [groups],\n  );\n  const grouped = groups.length > 1 || (groups[0]?.name ?? \"\") !== \"\";\n\n  const activeId = hoveredId ?? focusedId;\n  const activeHost = activeId\n    ? (hosts.find((host) => host.id === activeId) ?? null)\n    : null;\n  const stopId =\n    tabStopId && ordered.some((host) => host.id === tabStopId)\n      ? tabStopId\n      : (ordered[0]?.id ?? null);\n\n  const plural = (n: number) => (n === 1 ? unit[0] : unit[1]);\n  const { counts } = fleet;\n  const attention =\n    counts.warn + counts.critical + (colorBy === \"status\" ? counts.offline : 0);\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const target = event.target as HTMLElement;\n    if (target.dataset.slot !== \"host-map-cell\") return;\n    const all = Array.from(\n      event.currentTarget.querySelectorAll<HTMLElement>(\n        '[data-slot=\"host-map-cell\"]',\n      ),\n    );\n    const index = all.indexOf(target);\n    const moves: Record<string, () => HTMLElement | null | undefined> = {\n      ArrowRight: () => all[index + 1],\n      ArrowLeft: () => all[index - 1],\n      ArrowDown: () => neighbor(all, target, \"down\"),\n      ArrowUp: () => neighbor(all, target, \"up\"),\n      Home: () => all[0],\n      End: () => all[all.length - 1],\n    };\n    const move = moves[event.key];\n    if (!move) return;\n    event.preventDefault();\n    const next = move();\n    if (!next) return;\n    setTabStopId(next.dataset.id ?? null);\n    next.focus();\n  };\n\n  const describe = (host: HostMapHost, status: HostStatus) => {\n    const parts = [host.name];\n    if (host.group) parts.push(host.group);\n    const value = metricOf(host);\n    if (value != null && status !== \"offline\")\n      parts.push(`${metricLabel} ${valueFormatter(value)}`);\n    parts.push(statusLabel[status]);\n    return parts.join(\", \");\n  };\n\n  const hasHeader = title != null || description != null || actions != null;\n  const mapLabel = typeof title === \"string\" ? title : \"Host map\";\n\n  let readout: React.ReactNode;\n  if (activeHost) {\n    const status = statusOf(activeHost, warn, critical);\n    const value = status === \"offline\" ? null : metricOf(activeHost);\n    readout = (\n      <>\n        <div className=\"flex min-w-0 items-center gap-2\">\n          <span\n            aria-hidden=\"true\"\n            className={cn(\"size-2 shrink-0 rounded-full\", statusDot[status])}\n          />\n          <span className=\"truncate font-mono text-xs font-medium text-foreground\">\n            {activeHost.name}\n          </span>\n          {activeHost.group ? (\n            <span className=\"ml-auto shrink-0 font-mono text-[10.5px] text-muted-foreground\">\n              {activeHost.group}\n            </span>\n          ) : null}\n        </div>\n        <div className=\"flex items-center gap-2.5\">\n          <span className=\"text-[11px] text-muted-foreground\">\n            {metricLabel}\n          </span>\n          <span className=\"text-sm font-semibold tabular-nums\">\n            {value != null ? valueFormatter(value) : \"—\"}\n          </span>\n          <span className=\"relative h-1 min-w-8 flex-1 overflow-hidden rounded-full bg-muted\">\n            {value != null ? (\n              <span\n                className=\"absolute inset-y-0 left-0 rounded-full\"\n                style={{\n                  width: `${clamp01(value) * 100}%`,\n                  background: valueFill(value, warn, critical),\n                }}\n              />\n            ) : null}\n          </span>\n          <span className={cn(\"text-xs font-medium\", statusText[status])}>\n            {statusLabel[status]}\n          </span>\n        </div>\n      </>\n    );\n  } else {\n    readout = (\n      <>\n        <div className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n          <span className=\"text-[11px] font-medium\">\n            Fleet\n          </span>\n          <span className=\"ml-auto tabular-nums\">\n            {hosts.length} {plural(hosts.length)}\n          </span>\n        </div>\n        <div className=\"flex items-center gap-3 text-xs\">\n          <span className=\"flex items-baseline gap-1.5\">\n            <span className=\"text-muted-foreground\">\n              {colorBy === \"value\" ? `avg ${metricLabel}` : \"healthy\"}\n            </span>\n            <span className=\"text-sm font-semibold tabular-nums\">\n              {colorBy === \"value\"\n                ? fleet.average != null\n                  ? valueFormatter(fleet.average)\n                  : \"—\"\n                : counts.ok}\n            </span>\n          </span>\n          <span className=\"flex items-baseline gap-1.5\">\n            <span className=\"text-muted-foreground\">\n              {colorBy === \"value\" ? \"hot\" : \"need attention\"}\n            </span>\n            <span\n              className={cn(\n                \"text-sm font-semibold tabular-nums\",\n                counts.critical > 0\n                  ? \"text-destructive\"\n                  : attention > 0\n                    ? \"text-amber-700 dark:text-amber-400\"\n                    : \"text-foreground\",\n              )}\n            >\n              {attention}\n            </span>\n          </span>\n        </div>\n      </>\n    );\n  }\n\n  return (\n    <div\n      data-slot=\"host-map\"\n      data-color-by={colorBy}\n      className={cn(\n        \"@container/host-map flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      {...props}\n    >\n      <div\n        className={cn(\n          \"flex flex-col gap-3 px-5 pt-5 @md/host-map:flex-row @md/host-map:items-start @md/host-map:justify-between @md/host-map:gap-6\",\n          !hasHeader && \"@md/host-map:justify-end\",\n        )}\n      >\n        {hasHeader ? (\n          <div className=\"min-w-0 space-y-1\">\n            {title != null ? (\n              <h3 className=\"text-sm leading-5 font-semibold tracking-tight\">\n                {title}\n              </h3>\n            ) : null}\n            {description != null ? (\n              <p className=\"text-xs text-muted-foreground\">{description}</p>\n            ) : null}\n            {actions != null ? (\n              <div className=\"flex items-center gap-2 pt-2\">{actions}</div>\n            ) : null}\n          </div>\n        ) : null}\n        <div\n          data-slot=\"host-map-readout\"\n          aria-hidden=\"true\"\n          data-active={activeHost ? true : undefined}\n          className=\"flex min-w-0 shrink-0 flex-col justify-center gap-1.5 rounded-lg bg-muted/50 px-3 py-2 transition-colors data-[active]:bg-muted motion-reduce:transition-none @md/host-map:w-56 dark:bg-muted/30 dark:data-[active]:bg-muted/60\"\n        >\n          {readout}\n        </div>\n      </div>\n\n      <div\n        ref={mapRef}\n        role=\"group\"\n        aria-label={`${mapLabel}: ${hosts.length} ${plural(hosts.length)}. Use the arrow keys to move between them.`}\n        onKeyDown={onKeyDown}\n        onPointerLeave={() => setHoveredId(null)}\n        onBlur={(event) => {\n          if (!event.currentTarget.contains(event.relatedTarget as Node))\n            setFocusedId(null);\n        }}\n        className=\"flex flex-col gap-4 p-5\"\n        style={\n          {\n            \"--host-cell\": cellSize === \"sm\" ? \"10px\" : \"14px\",\n            \"--host-gap\": cellSize === \"sm\" ? \"2px\" : \"3px\",\n          } as React.CSSProperties\n        }\n      >\n        {hosts.length === 0 ? (\n          <p className=\"py-6 text-center text-xs text-muted-foreground\">\n            No {unit[1]} to show.\n          </p>\n        ) : null}\n        {groups.map((group) => {\n          const groupActive =\n            activeHost != null && (activeHost.group ?? \"\") === group.name;\n          const groupHot = group.counts.warn + group.counts.critical;\n          return (\n            <div\n              key={group.name || \"_\"}\n              role={grouped ? \"group\" : undefined}\n              aria-label={\n                grouped\n                  ? `${group.name}, ${group.hosts.length} ${plural(group.hosts.length)}`\n                  : undefined\n              }\n              className=\"flex min-w-0 flex-col gap-2\"\n            >\n              {grouped ? (\n                <div\n                  aria-hidden=\"true\"\n                  data-slot=\"host-map-group-header\"\n                  className=\"flex items-baseline gap-2 text-[11px]\"\n                >\n                  <span\n                    className={cn(\n                      \"font-mono font-medium transition-colors motion-reduce:transition-none\",\n                      groupActive ? \"text-foreground\" : \"text-foreground/80\",\n                    )}\n                  >\n                    {group.name}\n                  </span>\n                  <span className=\"text-muted-foreground tabular-nums\">\n                    {group.hosts.length}\n                  </span>\n                  <span className=\"h-px min-w-4 flex-1 self-center bg-border\" />\n                  <span className=\"flex items-baseline gap-2.5 text-muted-foreground tabular-nums\">\n                    {colorBy === \"value\" ? (\n                      <>\n                        {group.average != null ? (\n                          <span>\n                            avg{\" \"}\n                            <span className=\"font-medium text-foreground\">\n                              {valueFormatter(group.average)}\n                            </span>\n                          </span>\n                        ) : null}\n                        {groupHot > 0 ? (\n                          <span\n                            className={\n                              group.counts.critical > 0\n                                ? \"text-destructive\"\n                                : \"text-amber-700 dark:text-amber-400\"\n                            }\n                          >\n                            {groupHot} hot\n                          </span>\n                        ) : null}\n                      </>\n                    ) : (\n                      statusOrder\n                        .filter(\n                          (status) =>\n                            status !== \"ok\" && group.counts[status] > 0,\n                        )\n                        .map((status) => (\n                          <span key={status} className={statusText[status]}>\n                            {group.counts[status]}{\" \"}\n                            {status === \"warn\" ? \"warn\" : status}\n                          </span>\n                        ))\n                    )}\n                  </span>\n                </div>\n              ) : null}\n              <div\n                className=\"grid\"\n                style={{\n                  gap: \"var(--host-gap)\",\n                  gridTemplateColumns: \"repeat(auto-fill, var(--host-cell))\",\n                }}\n              >\n                {group.hosts.map((host) => {\n                  const status = statusOf(host, warn, critical);\n                  const value = metricOf(host);\n                  return (\n                    <HostCell\n                      key={host.id}\n                      host={host}\n                      status={status}\n                      fill={\n                        colorBy === \"value\" && status !== \"offline\" && value != null\n                          ? valueFill(value, warn, critical)\n                          : undefined\n                      }\n                      label={describe(host, status)}\n                      active={host.id === activeId}\n                      selected={\n                        selectedId === undefined\n                          ? undefined\n                          : host.id === selectedId\n                      }\n                      dimmed={isolated != null && status !== isolated}\n                      tabStop={host.id === stopId}\n                      selectable={onSelect != null}\n                      onHover={setHoveredId}\n                      onFocusCell={onFocusCell}\n                      onSelect={onSelect}\n                    />\n                  );\n                })}\n              </div>\n            </div>\n          );\n        })}\n      </div>\n\n      {showLegend ? (\n        <div\n          data-slot=\"host-map-legend\"\n          className=\"flex flex-wrap items-center justify-between gap-x-6 gap-y-2 border-t px-5 py-3 text-[11px] text-muted-foreground\"\n        >\n          {colorBy === \"value\" ? (\n            <>\n              <span className=\"text-[11px] font-medium\">\n                {metricLabel}\n              </span>\n              <span className=\"flex items-center gap-4\">\n                <span className=\"flex flex-col gap-1\">\n                  <span\n                    aria-hidden=\"true\"\n                    className=\"flex h-2 w-40 overflow-hidden rounded-full\"\n                  >\n                    <span\n                      className=\"h-full\"\n                      style={{\n                        width: `${warn * 100}%`,\n                        background: `linear-gradient(to right, ${valueFill(0, warn, critical)}, ${valueFill(warn - 0.001, warn, critical)})`,\n                      }}\n                    />\n                    <span\n                      className=\"h-full\"\n                      style={{\n                        width: `${(critical - warn) * 100}%`,\n                        background: `linear-gradient(to right, ${valueFill(warn, warn, critical)}, ${valueFill(critical - 0.001, warn, critical)})`,\n                      }}\n                    />\n                    <span\n                      className=\"h-full flex-1\"\n                      style={{ background: valueFill(1, warn, critical) }}\n                    />\n                  </span>\n                  <span className=\"relative h-3 w-40 font-mono text-[10px] tabular-nums\">\n                    <span className=\"absolute left-0\">{valueFormatter(0)}</span>\n                    <span\n                      className=\"absolute -translate-x-1/2\"\n                      style={{ left: `${warn * 100}%` }}\n                    >\n                      {valueFormatter(warn)}\n                    </span>\n                    <span\n                      className=\"absolute -translate-x-1/2\"\n                      style={{ left: `${critical * 100}%` }}\n                    >\n                      {valueFormatter(critical)}\n                    </span>\n                  </span>\n                </span>\n                <span className=\"flex items-center gap-1.5\">\n                  <span\n                    aria-hidden=\"true\"\n                    className=\"size-2.5 rounded-[2px] border border-dashed border-muted-foreground/60\"\n                  />\n                  Offline\n                </span>\n              </span>\n            </>\n          ) : (\n            <div\n              role=\"group\"\n              aria-label={`Highlight ${unit[1]} by status`}\n              className=\"flex flex-wrap items-center gap-1\"\n            >\n              {statusOrder.map((status) => (\n                <button\n                  key={status}\n                  type=\"button\"\n                  aria-pressed={isolated === status}\n                  onClick={() =>\n                    setIsolated((current) =>\n                      current === status ? null : status,\n                    )\n                  }\n                  className={cn(\n                    \"inline-flex h-7 items-center gap-1.5 rounded-md border border-transparent px-2 text-xs transition-colors outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none\",\n                    \"aria-pressed:border-border aria-pressed:bg-muted aria-pressed:text-foreground\",\n                  )}\n                >\n                  <span\n                    aria-hidden=\"true\"\n                    className={cn(\"size-2.5 rounded-[2px]\", statusFill[status])}\n                  />\n                  <span>{statusLabel[status]}</span>\n                  <span className=\"font-medium text-foreground tabular-nums\">\n                    {counts[status]}\n                  </span>\n                </button>\n              ))}\n            </div>\n          )}\n        </div>\n      ) : null}\n\n      <style href=\"overtrue-host-map\" precedence=\"default\">\n        {`@keyframes host-map-pulse{0%{opacity:.9;transform:scale(.85)}70%,100%{opacity:0;transform:scale(1.25)}}`}\n      </style>\n    </div>\n  );\n}\n\nexport { HostMap };\n"
    },
    {
      "path": "src/registry/overtrue/log-stream.tsx",
      "type": "registry:component",
      "target": "components/overtrue/log-stream.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconArrowDown as ArrowDown,\n  IconPlayerPause as Pause,\n  IconPlayerPlay as Play,\n  IconSearch as Search,\n  IconTextWrap as TextWrap,\n  IconTrash as Trash,\n  IconX as X,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LogEntry {\n  id: string;\n  time: Date | number | string;\n  level: LogLevel;\n  /** Service, job or component that emitted the line. */\n  source?: string;\n  message: string;\n}\n\nexport interface LogStreamProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"children\" | \"title\"\n> {\n  /** Events, oldest first. Append new entries to the end. */\n  entries: LogEntry[];\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Height of the scrolling log in pixels. */\n  height?: number;\n  /** Render at most this many of the newest matching rows. */\n  maxEntries?: number;\n  /** Follow the tail. Pass with `onFollowChange` to control it. */\n  follow?: boolean;\n  defaultFollow?: boolean;\n  onFollowChange?: (follow: boolean) => void;\n  /** Called by the clear action. Without it, clearing hides the current entries locally. */\n  onClear?: () => void;\n  /** A live source shows a Live/Paused badge, a follow control, and a cursor. Set false for archived logs. */\n  live?: boolean;\n  /** Levels shown initially. */\n  defaultLevels?: LogLevel[];\n  /** Initial text filter, matched against messages and sources. */\n  defaultQuery?: string;\n  /** Wrap long messages instead of truncating them. Rows can still be expanded one at a time. */\n  defaultWrap?: boolean;\n  /** Format timestamps in local time or UTC. */\n  timeZone?: \"local\" | \"utc\";\n}\n\nconst LEVELS: LogLevel[] = [\"debug\", \"info\", \"warn\", \"error\"];\n\nconst levelStyle: Record<LogLevel, { label: string; pill: string; dot: string }> = {\n  debug: {\n    label: \"Debug\",\n    pill: \"bg-muted text-muted-foreground\",\n    dot: \"bg-muted-foreground/50\",\n  },\n  info: {\n    label: \"Info\",\n    pill: \"bg-sky-500/10 text-sky-700 dark:text-sky-300\",\n    dot: \"bg-sky-500\",\n  },\n  warn: {\n    label: \"Warn\",\n    pill: \"bg-amber-500/12 text-amber-700 dark:text-amber-400\",\n    dot: \"bg-amber-500\",\n  },\n  error: {\n    label: \"Error\",\n    pill: \"bg-destructive/12 text-rose-700 dark:text-rose-400\",\n    dot: \"bg-destructive\",\n  },\n};\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-1 focus-visible:ring-offset-card\";\n\nfunction lastIndexOfId(entries: LogEntry[], id: string) {\n  for (let i = entries.length - 1; i >= 0; i--) if (entries[i].id === id) return i;\n  return -1;\n}\n\nconst pad = (value: number, size = 2) => String(value).padStart(size, \"0\");\n\nfunction formatTime(time: LogEntry[\"time\"], zone: \"local\" | \"utc\") {\n  const date = time instanceof Date ? time : new Date(time);\n  if (Number.isNaN(date.getTime())) return [\"--:--:--\", \".---\", undefined] as const;\n  const utc = zone === \"utc\";\n  const hms = `${pad(utc ? date.getUTCHours() : date.getHours())}:${pad(utc ? date.getUTCMinutes() : date.getMinutes())}:${pad(utc ? date.getUTCSeconds() : date.getSeconds())}`;\n  return [hms, `.${pad(utc ? date.getUTCMilliseconds() : date.getMilliseconds(), 3)}`, date.toISOString()] as const;\n}\n\nfunction highlight(text: string, query: string) {\n  if (!query) return text;\n  const lower = text.toLowerCase();\n  const parts: React.ReactNode[] = [];\n  let from = 0;\n  let at = lower.indexOf(query, from);\n  while (at !== -1) {\n    if (at > from) parts.push(text.slice(from, at));\n    parts.push(\n      <mark key={at} className=\"rounded-[2px] bg-amber-300/50 text-inherit dark:bg-amber-400/30\">\n        {text.slice(at, at + query.length)}\n      </mark>,\n    );\n    from = at + query.length;\n    at = lower.indexOf(query, from);\n  }\n  if (from < text.length) parts.push(text.slice(from));\n  return parts;\n}\n\ninterface RowProps {\n  entry: LogEntry;\n  query: string;\n  wrap: boolean;\n  expanded: boolean;\n  enter: boolean;\n  zone: \"local\" | \"utc\";\n  onToggle: (id: string) => void;\n}\n\nconst LogRow = React.memo(function LogRow({\n  entry,\n  query,\n  wrap,\n  expanded,\n  enter,\n  zone,\n  onToggle,\n}: RowProps) {\n  const [hms, ms, iso] = formatTime(entry.time, zone);\n  const open = wrap || expanded;\n  const level = levelStyle[entry.level] ?? levelStyle.info;\n  return (\n    <div\n      data-level={entry.level}\n      data-expanded={expanded || undefined}\n      onClick={wrap ? undefined : () => onToggle(entry.id)}\n      className={cn(\n        \"relative flex items-start gap-3 px-4 py-[5px] leading-[18px]\",\n        entry.level === \"error\"\n          ? \"bg-destructive/[0.06] hover:bg-destructive/10 dark:bg-destructive/10 dark:hover:bg-destructive/15\"\n          : \"hover:bg-muted/60\",\n        enter &&\n          \"transition-[opacity,translate] duration-300 ease-out starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none\",\n      )}\n    >\n      {entry.level === \"error\" && (\n        <span aria-hidden=\"true\" className=\"absolute inset-y-0 left-0 w-0.5 bg-destructive\" />\n      )}\n      <time\n        dateTime={iso}\n        className=\"w-[84px] shrink-0 text-muted-foreground tabular-nums\"\n      >\n        {hms}\n        <span className=\"opacity-55\">{ms}</span>\n      </time>\n      <span\n        className={cn(\n          \"mt-px inline-flex h-4 w-12 shrink-0 items-center justify-center rounded-[4px] text-[10.5px] leading-none font-semibold tracking-wide uppercase\",\n          level.pill,\n        )}\n      >\n        {entry.level}\n      </span>\n      {entry.source !== undefined && (\n        <span className=\"hidden w-16 shrink-0 truncate text-muted-foreground @md/log:block\" title={entry.source}>\n          {entry.source}\n        </span>\n      )}\n      <span\n        className={cn(\n          \"min-w-0 flex-1 text-foreground\",\n          open ? \"break-words whitespace-pre-wrap\" : \"truncate\",\n          entry.level === \"debug\" && \"text-muted-foreground\",\n        )}\n        title={open ? undefined : entry.message}\n      >\n        {entry.source !== undefined && (\n          <span className=\"text-muted-foreground @md/log:hidden\">{entry.source} · </span>\n        )}\n        {highlight(entry.message, query)}\n      </span>\n    </div>\n  );\n});\n\n/** A live, terminal-style event stream that follows the tail until someone scrolls up to read. */\nexport function LogStream({\n  entries,\n  title = \"Events\",\n  description,\n  height = 320,\n  maxEntries = 500,\n  follow: followProp,\n  defaultFollow = true,\n  onFollowChange,\n  onClear,\n  live = true,\n  defaultLevels = LEVELS,\n  defaultQuery = \"\",\n  defaultWrap = false,\n  timeZone = \"local\",\n  className,\n  onKeyDown,\n  ...props\n}: LogStreamProps) {\n  const id = React.useId();\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const searchRef = React.useRef<HTMLInputElement>(null);\n  const pausedBy = React.useRef<\"scroll\" | \"user\" | null>(null);\n\n  const [followState, setFollowState] = React.useState(defaultFollow);\n  const following = followProp ?? followState;\n  const [frozen, setFrozen] = React.useState<LogEntry[] | null>(null);\n  const [levels, setLevels] = React.useState<ReadonlySet<LogLevel>>(() => new Set(defaultLevels));\n  const [search, setSearch] = React.useState(defaultQuery);\n  const [wrap, setWrap] = React.useState(defaultWrap);\n  const [expanded, setExpanded] = React.useState<ReadonlySet<string>>(() => new Set());\n  const [clearedAfter, setClearedAfter] = React.useState<string | null>(null);\n  const [mounted, setMounted] = React.useState(false);\n  React.useEffect(() => setMounted(true), []);\n\n  const setFollowing = React.useCallback(\n    (next: boolean, reason: \"scroll\" | \"user\" = \"user\") => {\n      pausedBy.current = next ? null : reason;\n      // Freeze what is on screen so reading is never interrupted by the stream.\n      setFrozen(next ? null : entries);\n      if (followProp === undefined) setFollowState(next);\n      onFollowChange?.(next);\n    },\n    [entries, followProp, onFollowChange],\n  );\n\n  // Keep a controlled `follow={false}` frozen too.\n  React.useLayoutEffect(() => {\n    if (!following && !frozen) setFrozen(entries);\n    if (following && frozen) setFrozen(null);\n  }, [following, frozen, entries]);\n\n  const visibleSource = React.useMemo(() => {\n    const source = frozen ?? entries;\n    if (clearedAfter === null) return source;\n    const index = lastIndexOfId(source, clearedAfter);\n    return index === -1 ? source : source.slice(index + 1);\n  }, [frozen, entries, clearedAfter]);\n\n  const query = search.trim().toLowerCase();\n  const { rows, counts, matching } = React.useMemo(() => {\n    const counts: Record<LogLevel, number> = { debug: 0, info: 0, warn: 0, error: 0 };\n    const rows: LogEntry[] = [];\n    for (const entry of visibleSource) {\n      if (\n        query &&\n        !entry.message.toLowerCase().includes(query) &&\n        !entry.source?.toLowerCase().includes(query)\n      )\n        continue;\n      counts[entry.level] = (counts[entry.level] ?? 0) + 1;\n      if (levels.has(entry.level)) rows.push(entry);\n    }\n    const matching = rows.length;\n    return { rows: rows.length > maxEntries ? rows.slice(-maxEntries) : rows, counts, matching };\n  }, [visibleSource, query, levels, maxEntries]);\n\n  const pending = React.useMemo(() => {\n    if (following || !frozen) return 0;\n    const last = frozen[frozen.length - 1];\n    const index = last ? lastIndexOfId(entries, last.id) : -1;\n    let count = 0;\n    for (let i = index + 1; i < entries.length; i++) if (levels.has(entries[i].level)) count++;\n    return count;\n  }, [following, frozen, entries, levels]);\n\n  // Stay pinned to the newest row while following.\n  React.useLayoutEffect(() => {\n    const element = scrollRef.current;\n    if (following && element) element.scrollTop = element.scrollHeight;\n  }, [following, rows]);\n\n  const handleScroll = () => {\n    const element = scrollRef.current;\n    if (!element) return;\n    const distance = element.scrollHeight - element.scrollTop - element.clientHeight;\n    if (following && distance > 24) setFollowing(false, \"scroll\");\n    else if (!following && pausedBy.current === \"scroll\" && distance < 2) setFollowing(true);\n  };\n\n  const toggleRow = React.useCallback((rowId: string) => {\n    if (window.getSelection()?.toString()) return;\n    setExpanded((current) => {\n      const next = new Set(current);\n      if (!next.delete(rowId)) next.add(rowId);\n      return next;\n    });\n  }, []);\n\n  const toggleLevel = (level: LogLevel) =>\n    setLevels((current) => {\n      const next = new Set(current);\n      if (!next.delete(level)) next.add(level);\n      return next;\n    });\n\n  const clear = () => {\n    setExpanded(new Set());\n    if (onClear) onClear();\n    else setClearedAfter(entries[entries.length - 1]?.id ?? null);\n    if (!following) setFollowing(true);\n  };\n\n  const resetFilters = () => {\n    setSearch(\"\");\n    setLevels(new Set(LEVELS));\n  };\n\n  const total = visibleSource.length;\n  const filtered = query !== \"\" || levels.size < LEVELS.length;\n\n  return (\n    <div\n      data-slot=\"log-stream\"\n      data-following={following || undefined}\n      className={cn(\n        \"@container/log flex min-w-0 flex-col overflow-hidden rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        const target = event.target as HTMLElement;\n        if (\n          event.key === \"/\" &&\n          !event.defaultPrevented &&\n          !(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement)\n        ) {\n          event.preventDefault();\n          searchRef.current?.focus();\n        }\n      }}\n      {...props}\n    >\n      <div className=\"flex items-start gap-3 px-4 pt-3.5 pb-3\">\n        <div className=\"min-w-0 flex-1\">\n          <div className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1\">\n            <p id={`${id}-title`} className=\"min-w-0 text-sm leading-6 font-semibold tracking-tight break-words\">\n              {title}\n            </p>\n            {live && (\n              <span\n                className={cn(\n                  \"inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2 py-px text-[11px] leading-4 font-medium\",\n                  following ? \"text-emerald-700 dark:text-emerald-400\" : \"text-amber-700 dark:text-amber-400\",\n                )}\n              >\n                <span className=\"relative flex size-1.5\" aria-hidden=\"true\">\n                  {following && (\n                    <span className=\"absolute inline-flex size-full animate-ping rounded-full bg-emerald-500 opacity-70 motion-reduce:hidden\" />\n                  )}\n                  <span\n                    className={cn(\n                      \"relative inline-flex size-1.5 rounded-full\",\n                      following ? \"bg-emerald-500\" : \"bg-amber-500\",\n                    )}\n                  />\n                </span>\n                {following ? \"Live\" : \"Paused\"}\n              </span>\n            )}\n          </div>\n          {description && <p className=\"truncate text-xs text-muted-foreground\">{description}</p>}\n        </div>\n        <div className=\"flex shrink-0 items-center gap-1\">\n          <button\n            type=\"button\"\n            aria-pressed={wrap}\n            title=\"Wrap long lines\"\n            onClick={() => setWrap((value) => !value)}\n            className={cn(\n              \"inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground aria-pressed:bg-muted aria-pressed:text-foreground motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <TextWrap className=\"size-4\" aria-hidden=\"true\" />\n            <span className=\"sr-only\">Wrap long lines</span>\n          </button>\n          <button\n            type=\"button\"\n            title=\"Clear\"\n            onClick={clear}\n            className={cn(\n              \"inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <Trash className=\"size-4\" aria-hidden=\"true\" />\n            <span className=\"sr-only\">Clear events</span>\n          </button>\n          {live && (\n            <button\n              type=\"button\"\n              title={following ? \"Pause the tail\" : \"Resume following\"}\n              aria-label={following ? \"Pause following\" : \"Resume following\"}\n              onClick={() => setFollowing(!following)}\n              className={cn(\n                \"ml-1 inline-flex h-7 items-center gap-1.5 rounded-md border bg-card px-2 text-xs font-medium shadow-xs transition-colors hover:bg-muted motion-reduce:transition-none @md/log:px-2.5\",\n                focusRing,\n              )}\n            >\n              {following ? (\n                <Pause className=\"size-3.5\" aria-hidden=\"true\" />\n              ) : (\n                <Play className=\"size-3.5\" aria-hidden=\"true\" />\n              )}\n              <span className=\"sr-only @md/log:not-sr-only\">{following ? \"Pause\" : \"Resume\"}</span>\n            </button>\n          )}\n        </div>\n      </div>\n\n      <div className=\"flex flex-wrap items-center gap-2 border-y bg-muted/30 px-4 py-2\">\n        <div role=\"group\" aria-label=\"Levels\" className=\"flex flex-wrap items-center gap-1\">\n          {LEVELS.map((level) => {\n            const active = levels.has(level);\n            return (\n              <button\n                key={level}\n                type=\"button\"\n                aria-pressed={active}\n                onClick={() => toggleLevel(level)}\n                className={cn(\n                  \"inline-flex h-6 items-center gap-1 rounded-md border px-1.5 text-xs transition-colors motion-reduce:transition-none @md/log:gap-1.5 @md/log:px-2\",\n                  active\n                    ? \"border-border bg-card text-foreground shadow-xs\"\n                    : \"border-transparent text-muted-foreground hover:text-foreground\",\n                  focusRing,\n                )}\n              >\n                <span\n                  aria-hidden=\"true\"\n                  className={cn(\n                    \"size-1.5 rounded-full\",\n                    active ? levelStyle[level].dot : \"bg-transparent ring-1 ring-muted-foreground/50 ring-inset\",\n                  )}\n                />\n                {levelStyle[level].label}\n                <span className=\"font-mono text-[11px] text-muted-foreground tabular-nums\">{counts[level]}</span>\n              </button>\n            );\n          })}\n        </div>\n        <div className=\"relative ml-auto min-w-36 flex-1 @lg/log:max-w-60\">\n          <Search\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground\"\n          />\n          <input\n            ref={searchRef}\n            type=\"text\"\n            value={search}\n            onChange={(event) => setSearch(event.target.value)}\n            onKeyDown={(event) => {\n              if (event.key === \"Escape\" && search) {\n                event.stopPropagation();\n                setSearch(\"\");\n              }\n            }}\n            placeholder=\"Filter…\"\n            aria-label=\"Filter messages\"\n            spellCheck={false}\n            className=\"h-7 w-full rounded-md border border-input bg-card pr-7 pl-7 text-xs text-foreground shadow-xs transition-[border-color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 motion-reduce:transition-none\"\n          />\n          {search ? (\n            <button\n              type=\"button\"\n              onClick={() => {\n                setSearch(\"\");\n                searchRef.current?.focus();\n              }}\n              className={cn(\n                \"absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:text-foreground\",\n                focusRing,\n              )}\n            >\n              <X className=\"size-3\" aria-hidden=\"true\" />\n              <span className=\"sr-only\">Clear filter</span>\n            </button>\n          ) : (\n            <kbd className=\"pointer-events-none absolute top-1/2 right-1.5 hidden -translate-y-1/2 rounded border bg-muted px-1 font-mono text-[10px] leading-4 text-muted-foreground @md/log:block\">\n              /\n            </kbd>\n          )}\n        </div>\n      </div>\n\n      <div className=\"relative\">\n        <div\n          ref={scrollRef}\n          role=\"log\"\n          aria-live=\"polite\"\n          aria-relevant=\"additions\"\n          aria-labelledby={`${id}-title`}\n          tabIndex={0}\n          onScroll={handleScroll}\n          className=\"overflow-y-auto overscroll-contain py-1.5 font-mono text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset\"\n          style={{ height }}\n        >\n          {rows.map((entry) => (\n            <LogRow\n              key={entry.id}\n              entry={entry}\n              query={query}\n              wrap={wrap}\n              expanded={expanded.has(entry.id)}\n              enter={mounted}\n              zone={timeZone}\n              onToggle={toggleRow}\n            />\n          ))}\n          {rows.length === 0 && (\n            <div className=\"flex h-full flex-col items-center justify-center gap-2 px-4 text-center font-sans\">\n              {total === 0 ? (\n                <p className=\"text-xs text-muted-foreground\">\n                  {live ? \"Waiting for events…\" : \"No events yet.\"}\n                </p>\n              ) : (\n                <>\n                  <p className=\"text-xs text-muted-foreground\">No events match these filters.</p>\n                  <button\n                    type=\"button\"\n                    onClick={resetFilters}\n                    className={cn(\"rounded-md px-2 py-1 text-xs font-medium text-primary hover:bg-muted\", focusRing)}\n                  >\n                    Show all events\n                  </button>\n                </>\n              )}\n            </div>\n          )}\n          {rows.length > 0 && live && following && (\n            <div aria-hidden=\"true\" className=\"px-4 py-[5px] leading-[18px]\">\n              <span className=\"inline-block h-3.5 w-[7px] translate-y-[3px] animate-pulse bg-foreground/35 motion-reduce:animate-none\" />\n            </div>\n          )}\n        </div>\n        <div\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-x-0 top-0 h-4 bg-linear-to-b from-card to-transparent\"\n        />\n        {!following && (\n          <button\n            type=\"button\"\n            onClick={() => setFollowing(true)}\n            className={cn(\n              \"absolute bottom-3 left-1/2 inline-flex h-7 -translate-x-1/2 items-center gap-1.5 rounded-full bg-foreground px-3 text-xs font-medium text-background shadow-lg transition-[opacity,translate] duration-200 starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <ArrowDown className=\"size-3.5\" aria-hidden=\"true\" />\n            Jump to latest\n            {pending > 0 && (\n              <span className=\"rounded-full bg-background/20 px-1.5 font-mono text-[11px] tabular-nums\">\n                {pending > 999 ? \"999+\" : pending} new\n              </span>\n            )}\n          </button>\n        )}\n      </div>\n\n      <div className=\"flex items-center justify-between gap-3 border-t px-4 py-1.5 font-mono text-[11px] text-muted-foreground tabular-nums\">\n        <span>\n          {filtered ? `${matching.toLocaleString(\"en-US\")} of ${total.toLocaleString(\"en-US\")}` : total.toLocaleString(\"en-US\")}{\" \"}\n          {total === 1 ? \"event\" : \"events\"}\n          {rows.length < matching && ` · showing last ${rows.length.toLocaleString(\"en-US\")}`}\n        </span>\n        <span>{timeZone === \"utc\" ? \"UTC\" : \"Local time\"}</span>\n      </div>\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/bullet-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/bullet-chart.tsx",
      "content": "\"use client\";\nimport { useId, type ComponentProps, type ReactNode } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\n/** Ascending thresholds that split the scale into three qualitative ranges. */\nexport type BulletChartRanges = [number, number, number];\nexport type BulletChartQuality = \"poor\" | \"satisfactory\" | \"good\";\n\nexport interface BulletChartItem {\n  id: string;\n  label: string;\n  sublabel?: string;\n  value: number;\n  target: number;\n  /**\n   * Upper bounds of the poor, satisfactory and good ranges, e.g. [600, 800, 1000].\n   * With `invert` the same bounds read good, satisfactory, poor.\n   */\n  ranges?: BulletChartRanges;\n  /** End of the scale. Defaults to the last range, or a rounded value above the data. */\n  max?: number;\n  /** Lower is better, e.g. response time, churn or cost. */\n  invert?: boolean;\n  /** Formats this row's value, target and gap. Overrides the chart's formatter. */\n  valueFormatter?: (value: number) => string;\n}\n\nexport interface BulletChartProps extends Omit<\n  ComponentProps<\"section\">,\n  \"title\" | \"children\"\n> {\n  items: BulletChartItem[];\n  title?: ReactNode;\n  description?: ReactNode;\n  valueFormatter?: (value: number, item: BulletChartItem) => string;\n  size?: \"default\" | \"compact\";\n  /** Paint the measure in the primary color, or by whether it meets its target. */\n  tone?: \"primary\" | \"status\";\n  showLegend?: boolean;\n}\n\nconst numberFormat = new Intl.NumberFormat(\"en-US\", {\n  maximumFractionDigits: 1,\n});\nconst wholePercent = new Intl.NumberFormat(\"en-US\", {\n  style: \"percent\",\n  maximumFractionDigits: 0,\n});\nconst precisePercent = new Intl.NumberFormat(\"en-US\", {\n  style: \"percent\",\n  maximumFractionDigits: 1,\n});\n\nconst bandShade: Record<BulletChartQuality, string> = {\n  poor: \"bg-foreground/[0.15]\",\n  satisfactory: \"bg-foreground/[0.085]\",\n  good: \"bg-foreground/[0.04]\",\n};\n\ntype Status = \"met\" | \"behind\" | \"at-risk\";\n\nconst statusFill: Record<Status, string> = {\n  met: \"bg-emerald-700 dark:bg-emerald-500\",\n  behind: \"bg-amber-700 dark:bg-amber-400\",\n  \"at-risk\": \"bg-red-600 dark:bg-red-400\",\n};\n\nfunction niceCeil(value: number) {\n  if (!(value > 0)) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(value));\n  const step = [1, 2, 2.5, 5, 10].find((n) => value <= n * magnitude) ?? 10;\n  return step * magnitude;\n}\n\nconst finite = (value: number) => (Number.isFinite(value) ? value : 0);\nconst clampPercent = (value: number, max: number) =>\n  Math.min(100, Math.max(0, (value / max) * 100));\n\nfunction measure(item: BulletChartItem, format: (value: number) => string) {\n  const value = finite(item.value);\n  const target = finite(item.target);\n  const ranges = item.ranges\n    ? ([...item.ranges].map(finite).sort((a, b) => a - b) as BulletChartRanges)\n    : undefined;\n  const peak = Math.max(value, target);\n  const max =\n    item.max && item.max > 0\n      ? item.max\n      : ranges && ranges[2] >= peak && ranges[2] > 0\n        ? ranges[2]\n        : niceCeil(Math.max(peak, ranges?.[2] ?? 0) * 1.1);\n\n  const order: BulletChartQuality[] = item.invert\n    ? [\"good\", \"satisfactory\", \"poor\"]\n    : [\"poor\", \"satisfactory\", \"good\"];\n  const bands = ranges\n    ? ranges.map((end, index) => ({\n        quality: order[index],\n        from: clampPercent(index ? ranges[index - 1] : 0, max),\n        to: clampPercent(end, max),\n      }))\n    : [];\n  const quality = ranges\n    ? order[value < ranges[0] ? 0 : value < ranges[1] ? 1 : 2]\n    : undefined;\n\n  const met = item.invert ? value <= target : value >= target;\n  const status: Status = met\n    ? \"met\"\n    : quality === \"poor\"\n      ? \"at-risk\"\n      : \"behind\";\n  const ratio = target ? value / target : undefined;\n  const gap = value - target;\n  const gapShort =\n    gap === 0\n      ? \"on target\"\n      : `${format(Math.abs(gap))} ${gap > 0 ? \"above\" : \"below\"}`;\n\n  const formattedValue = format(value);\n  const formattedTarget = format(target);\n  const summary = [\n    `${item.label}: ${formattedValue} of ${formattedTarget} target`,\n    ratio !== undefined ? ` (${wholePercent.format(ratio)})` : \"\",\n    item.invert ? \", lower is better\" : \"\",\n    quality ? `, ${quality} range` : \"\",\n    gap === 0 ? \". On target.\" : `. ${gapShort} target.`,\n  ].join(\"\");\n\n  return {\n    value,\n    target,\n    bands,\n    status,\n    ratio,\n    gapShort,\n    formattedValue,\n    formattedTarget,\n    summary,\n    valuePercent: clampPercent(value, max),\n    targetPercent: clampPercent(target, max),\n  };\n}\n\n/** Stephen Few's bullet graph: a measure against its target over qualitative ranges. */\nexport function BulletChart({\n  items,\n  title,\n  description,\n  valueFormatter,\n  size = \"default\",\n  tone = \"primary\",\n  showLegend = true,\n  className,\n  ...props\n}: BulletChartProps) {\n  const titleId = useId();\n  const compact = size === \"compact\";\n  const hasHeader = Boolean(title || description || showLegend);\n\n  return (\n    <section\n      data-slot=\"bullet-chart\"\n      data-size={size}\n      aria-labelledby={title ? titleId : undefined}\n      className={cn(\n        \"@container/bullet rounded-xl border bg-card text-card-foreground shadow-xs\",\n        compact ? \"p-4\" : \"p-5 @lg/bullet:p-6\",\n        className,\n      )}\n      {...props}\n    >\n      {hasHeader && (\n        <header\n          className={cn(\n            \"flex flex-wrap items-start justify-between gap-x-6 gap-y-3\",\n            compact ? \"mb-3\" : \"mb-5\",\n          )}\n        >\n          {(title || description) && (\n            <div className=\"min-w-0\">\n              {title && (\n                <h3\n                  id={titleId}\n                  className={cn(\n                    \"leading-tight font-semibold tracking-tight\",\n                    compact ? \"text-sm\" : \"text-base\",\n                  )}\n                >\n                  {title}\n                </h3>\n              )}\n              {description && (\n                <p\n                  className={cn(\n                    \"mt-1 text-muted-foreground\",\n                    compact ? \"text-xs\" : \"text-sm\",\n                  )}\n                >\n                  {description}\n                </p>\n              )}\n            </div>\n          )}\n          {showLegend && <Legend tone={tone} />}\n        </header>\n      )}\n\n      <ul\n        role=\"list\"\n        className={cn(\n          \"grid grid-cols-[minmax(0,1fr)_auto] gap-x-4\",\n          \"@min-[25rem]/bullet:grid-cols-[fit-content(11rem)_minmax(0,1fr)_auto] @lg/bullet:gap-x-5\",\n          compact ? \"gap-y-0.5\" : \"gap-y-1\",\n        )}\n      >\n        {items.map((item, index) => {\n          const format = item.valueFormatter\n            ? item.valueFormatter\n            : valueFormatter\n              ? (value: number) => valueFormatter(value, item)\n              : (value: number) => numberFormat.format(value);\n          const row = measure(item, format);\n          return (\n            <li\n              key={item.id}\n              tabIndex={0}\n              data-status={row.status}\n              className={cn(\n                \"group relative col-span-2 -mx-3 grid grid-cols-subgrid items-center gap-y-2 rounded-lg px-3 outline-none\",\n                \"transition-colors hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring/50\",\n                \"@min-[25rem]/bullet:col-span-3\",\n                compact ? \"py-2\" : \"py-2.5\",\n              )}\n            >\n              <span className=\"sr-only\">{row.summary}</span>\n\n              <div\n                aria-hidden=\"true\"\n                className=\"col-start-1 row-start-1 min-w-0\"\n              >\n                {compact ? (\n                  <p className=\"truncate text-[13px] leading-5\">\n                    <span className=\"font-medium\">{item.label}</span>\n                    {item.sublabel && (\n                      <span className=\"ml-1.5 text-xs text-muted-foreground\">\n                        {item.sublabel}\n                      </span>\n                    )}\n                  </p>\n                ) : (\n                  <>\n                    <p className=\"truncate text-sm leading-5 font-medium\">\n                      {item.label}\n                    </p>\n                    {item.sublabel && (\n                      <p className=\"truncate text-xs leading-4 text-muted-foreground\">\n                        {item.sublabel}\n                      </p>\n                    )}\n                  </>\n                )}\n              </div>\n\n              <div\n                aria-hidden=\"true\"\n                className=\"col-start-2 row-start-1 text-right tabular-nums @min-[25rem]/bullet:col-start-3\"\n              >\n                {compact ? (\n                  <p className=\"text-[13px] leading-5 whitespace-nowrap\">\n                    <span className=\"font-semibold\">{row.formattedValue}</span>\n                    <span className=\"text-muted-foreground\">\n                      {\" \"}\n                      / {row.formattedTarget}\n                    </span>\n                  </p>\n                ) : (\n                  <>\n                    <p className=\"text-sm leading-5 font-semibold whitespace-nowrap\">\n                      {row.formattedValue}\n                    </p>\n                    <p className=\"text-xs leading-4 whitespace-nowrap text-muted-foreground\">\n                      of {row.formattedTarget}\n                    </p>\n                  </>\n                )}\n              </div>\n\n              <div\n                aria-hidden=\"true\"\n                className={cn(\n                  \"relative col-span-2 row-start-2 @min-[25rem]/bullet:col-span-1 @min-[25rem]/bullet:col-start-2 @min-[25rem]/bullet:row-start-1\",\n                  compact ? \"h-4\" : \"h-6\",\n                )}\n              >\n                <div\n                  className={cn(\n                    \"absolute inset-0 overflow-hidden rounded-[3px]\",\n                    row.bands.length ? \"bg-foreground/[0.02]\" : \"bg-muted\",\n                  )}\n                >\n                  {row.bands.map((band) => (\n                    <div\n                      key={band.quality}\n                      className={cn(\n                        \"absolute inset-y-0\",\n                        bandShade[band.quality],\n                      )}\n                      style={{\n                        left: `${band.from}%`,\n                        width: `${band.to - band.from}%`,\n                      }}\n                    />\n                  ))}\n                </div>\n                <div\n                  className={cn(\n                    \"absolute left-0 origin-left rounded-[2px] transition-[width,transform,background-color] duration-700 ease-[cubic-bezier(0.22,1,0.36,1)] starting:[transform:scaleX(0)] motion-reduce:transition-none\",\n                    compact ? \"top-[5px] h-1.5\" : \"top-2 h-2\",\n                    tone === \"status\" ? statusFill[row.status] : \"bg-primary\",\n                  )}\n                  style={{\n                    width: `${row.valuePercent}%`,\n                    transitionDelay: `${80 + index * 70}ms`,\n                  }}\n                />\n                <div\n                  className={cn(\n                    \"absolute w-0.5 -translate-x-1/2 rounded-full bg-foreground transition-[left,opacity] duration-500 starting:opacity-0 motion-reduce:transition-none\",\n                    compact ? \"inset-y-0.5\" : \"inset-y-1\",\n                  )}\n                  style={{\n                    left: `${row.targetPercent}%`,\n                    transitionDelay: `${360 + index * 70}ms`,\n                  }}\n                />\n\n                {/* The readout slides along with the measure: at X% it is shifted\n                    by X% of its own width, so it never leaves the track and its\n                    caret always points at the end of the bar. */}\n                <div\n                  className={cn(\n                    \"pointer-events-none absolute bottom-full z-10 mb-2.5 translate-y-1 rounded-md bg-foreground px-2.5 py-1.5 font-mono text-[11px] leading-4 whitespace-nowrap text-background tabular-nums opacity-0 shadow-lg shadow-black/10 transition-[opacity,translate] duration-150\",\n                    \"group-hover:translate-y-0 group-hover:opacity-100 group-focus-visible:translate-y-0 group-focus-visible:opacity-100 motion-reduce:transition-none\",\n                  )}\n                  style={{\n                    left: `${row.valuePercent}%`,\n                    transform: `translateX(-${row.valuePercent}%)`,\n                  }}\n                >\n                  <p>\n                    <span className=\"font-semibold\">{row.formattedValue}</span>\n                    <span className=\"opacity-60\"> / {row.formattedTarget}</span>\n                  </p>\n                  <p>\n                    <span>\n                      {row.ratio !== undefined\n                        ? precisePercent.format(row.ratio)\n                        : \"—\"}\n                    </span>\n                    <span className=\"opacity-40\"> · </span>\n                    <span\n                      className={\n                        row.status === \"met\"\n                          ? \"text-emerald-400 dark:text-emerald-700\"\n                          : row.status === \"behind\"\n                            ? \"text-amber-300 dark:text-amber-800\"\n                            : \"text-red-400 dark:text-red-700\"\n                      }\n                    >\n                      {row.gapShort}\n                    </span>\n                  </p>\n                  <span\n                    className=\"absolute top-full size-2 -translate-x-1/2 -translate-y-1/2 rotate-45 rounded-[1px] bg-foreground\"\n                    style={{\n                      left: `clamp(8px, ${row.valuePercent}%, calc(100% - 8px))`,\n                    }}\n                  />\n                </div>\n              </div>\n            </li>\n          );\n        })}\n      </ul>\n    </section>\n  );\n}\n\nfunction Legend({ tone }: { tone: \"primary\" | \"status\" }) {\n  return (\n    <ul className=\"flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-muted-foreground\">\n      <li className=\"flex items-center gap-1.5\">\n        <span\n          aria-hidden=\"true\"\n          className=\"flex h-2.5 w-9 overflow-hidden rounded-[2px]\"\n        >\n          <span className={cn(\"flex-1\", bandShade.poor)} />\n          <span className={cn(\"flex-1\", bandShade.satisfactory)} />\n          <span className={cn(\"flex-1\", bandShade.good)} />\n        </span>\n        Poor → good\n      </li>\n      {tone === \"status\" ? (\n        (\n          [\n            [\"met\", \"Met\"],\n            [\"behind\", \"Behind\"],\n            [\"at-risk\", \"At risk\"],\n          ] as const\n        ).map(([status, label]) => (\n          <li key={status} className=\"flex items-center gap-1.5\">\n            <span\n              aria-hidden=\"true\"\n              className={cn(\"h-1.5 w-3 rounded-[1px]\", statusFill[status])}\n            />\n            {label}\n          </li>\n        ))\n      ) : (\n        <li className=\"flex items-center gap-1.5\">\n          <span\n            aria-hidden=\"true\"\n            className=\"h-1.5 w-3 rounded-[1px] bg-primary\"\n          />\n          Actual\n        </li>\n      )}\n      <li className=\"flex items-center gap-1.5\">\n        <span\n          aria-hidden=\"true\"\n          className=\"h-3 w-0.5 rounded-full bg-foreground\"\n        />\n        Target\n      </li>\n    </ul>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/blocks/realtime-monitor. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
