{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"tick-tape","type":"registry:component","title":"Tick tape","description":"Events as they happen, one hairline each: as tall as its latency, bright when it lands and cooling as it travels, with errors in red. Point at it to hold it still and read one.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/tick-tape.tsx","type":"registry:component","content":"// Hairline UI · tick-tape · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\n\n/* ─────────────────────────────────────────────────────────\n * TICK TAPE: events as they happen, one hairline each\n *\n *   arrive    every event you push lands at the right edge as an\n *             upright hairline, as tall as its value (a request's\n *             latency, a job's duration), rising into place\n *   age       it arrives at full light and cools as it travels\n *             left, so how recent something is reads as how bright\n *             it is. Errors are red and stay lit longer\n *   read      point at the tape and it holds still; the event under\n *             the pointer lights with a readout of what it was.\n *             Let go and the tape catches up on what arrived\n *             meanwhile at an even, quicker pace, never a jump\n *   pause     the Live pill holds it until you press it again\n *   figures   events per second, p95 and the error share over the\n *             last half minute, as plain figures updated once a second\n *\n * Push from your own stream through a ref: tape.current.push({...}).\n * One canvas, one frame loop that sleeps off screen and while held.\n * ───────────────────────────────────────────────────────── */\n\nexport interface TickTapeEvent {\n  value: number;\n  status?: \"ok\" | \"error\";\n  /** In the readout, e.g. \"GET /v1/orders · 200\". */\n  label?: string;\n  /** When it happened (ms since epoch). Defaults to now. */\n  time?: number;\n}\n\nexport interface TickTapeHandle {\n  push: (event: TickTapeEvent | TickTapeEvent[]) => void;\n  clear: () => void;\n}\n\nexport interface TickTapeProps extends React.HTMLAttributes<HTMLDivElement> {\n  ref?: React.Ref<TickTapeHandle>;\n  title?: string;\n  /** How many seconds the tape shows. */\n  seconds?: number;\n  /** How the value reads, e.g. milliseconds. */\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\n  /** Any CSS colour for ok events. Defaults to your first chart colour. */\n  color?: string;\n}\n\ntype Tick = { t: number; v: number; err: boolean; label?: string };\n\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\nconst LINE = 2;\nconst PITCH = 4;\nconst MS: Intl.NumberFormatOptions = { style: \"unit\", unit: \"millisecond\", unitDisplay: \"short\", maximumFractionDigits: 0 };\nconst KEEP = 30_000; // the figures look back this far\nconst CATCH_UP = 2.2; // while catching up, time runs this much faster\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () =>\n  React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\n// Formatting waits for hydration: the server and the hydrating render share one fixed locale, then the visitor's takes over.\nconst subscribeNothing = () => () => {};\nconst useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);\n\nfunction niceMax(value: number) {\n  if (value <= 0) return 1;\n  const step = 10 ** Math.floor(Math.log10(value));\n  for (const m of [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) if (m * step >= value) return m * step;\n  return 10 * step;\n}\n\nexport function TickTape({\n  ref,\n  title = \"Requests\",\n  seconds = 12,\n  format = MS,\n  locales,\n  color = \"var(--chart-1, var(--primary))\",\n  className = \"\",\n  ...props\n}: TickTapeProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  const [paused, setPaused] = React.useState(false);\n  const [stats, setStats] = React.useState({ rate: 0, p95: 0, errors: 0 });\n  const [picked, setPicked] = React.useState<Tick | null>(null);\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const probeRef = React.useRef<HTMLSpanElement>(null);\n  const inkRef = React.useRef<HTMLSpanElement>(null);\n  const errRef = React.useRef<HTMLSpanElement>(null);\n  const tagRef = React.useRef<HTMLDivElement>(null);\n\n  const engine = React.useRef({\n    ticks: [] as Tick[],\n    width: 0,\n    height: 0,\n    dpr: 1,\n    accent: \"currentColor\",\n    ink: \"currentColor\",\n    error: \"red\",\n    lag: 0, // how far the tape shows behind real time, in ms\n    frozen: null as number | null, // the tape's time while held or paused\n    held: false, // the pointer is on it\n    paused: false, // the Live pill\n    pointerX: null as number | null,\n    picked: null as Tick | null,\n    scale: 0,\n    last: 0,\n    frame: 0,\n    onScreen: false,\n    reduced: false,\n    secondsMs: seconds * 1000,\n    lastStep: 0,\n    loop: null as ((now: number) => void) | null,\n  });\n\n  const paint = React.useCallback((now: number) => {\n    const e = engine.current;\n    const canvas = canvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!canvas || !ctx || !e.width || !e.height) return;\n    const dt = e.last ? Math.min(now - e.last, 100) : 0;\n    e.last = now;\n    // Held or paused, the tape's clock stops while real time runs on; let go and it catches up at an even pace.\n    let view: number;\n    if (e.held || e.paused) {\n      if (e.frozen === null) e.frozen = Date.now() - e.lag;\n      view = e.frozen;\n    } else {\n      if (e.frozen !== null) {\n        e.lag = Date.now() - e.frozen;\n        e.frozen = null;\n      }\n      if (e.lag > 0) e.lag = Math.max(0, e.lag - dt * (CATCH_UP - 1));\n      view = Date.now() - e.lag;\n    }\n    const span = e.secondsMs;\n    const W = e.width;\n    const H = e.height;\n\n    // The scale eases toward a round number over what's on the tape.\n    let top = 0;\n    for (const k of e.ticks) if (k.t > view - span && k.t <= view && k.v > top) top = k.v;\n    const target = niceMax(top * 1.1 || 1);\n    e.scale = e.scale ? e.scale + (target - e.scale) * Math.min(1, dt / 220) : target;\n\n    ctx.setTransform(e.dpr, 0, 0, e.dpr, 0, 0);\n    ctx.clearRect(0, 0, W, H);\n    const rule = new Path2D();\n    for (let k = 0; ; k++) {\n      const y = Math.round((H - LINE - k * PITCH) * e.dpr) / e.dpr;\n      if (y < -LINE) break;\n      rule.rect(0, y, W, LINE);\n    }\n    ctx.save();\n    ctx.clip(rule);\n    ctx.fillStyle = e.ink;\n    ctx.globalAlpha = 0.04;\n    ctx.fillRect(0, 0, W, H);\n\n    // Find the event under the pointer while the tape is held.\n    let near: Tick | null = null;\n    let nearX = 0;\n    if (e.held && e.pointerX !== null) {\n      let best = 8;\n      for (const k of e.ticks) {\n        const x = W - ((view - k.t) / span) * W;\n        const d = Math.abs(x - e.pointerX);\n        if (k.t <= view && d < best) {\n          best = d;\n          near = k;\n          nearX = x;\n        }\n      }\n    }\n\n    for (const k of e.ticks) {\n      if (k.t > view || k.t < view - span - 1000) continue;\n      const age = view - k.t;\n      const x = W - (age / span) * W;\n      // Arrival: it rises into place over its first 220ms.\n      const rise = e.reduced ? 1 : Math.min(1, age / 220);\n      const h = Math.max(LINE, (Math.min(k.v, e.scale) / e.scale) * H * (1 - (1 - rise) ** 3));\n      // Recency is light: full on arrival, cooling over a few seconds; errors keep theirs longer.\n      const glow = k.err ? 0.5 + 0.5 * Math.exp(-age / 6000) : 0.22 + 0.78 * Math.exp(-age / 1800);\n      ctx.globalAlpha = near ? (k === near ? 1 : glow * 0.45) : glow;\n      ctx.fillStyle = k.err ? e.error : e.accent;\n      ctx.fillRect(Math.round((x - 1) * e.dpr) / e.dpr, H - h, 2, h);\n    }\n    ctx.restore();\n    ctx.globalAlpha = 1;\n\n    if (near !== e.picked) {\n      e.picked = near;\n      setPicked(near);\n    }\n    const tag = tagRef.current;\n    if (tag) {\n      tag.style.opacity = near ? \"1\" : \"0\";\n      if (near) {\n        const half = tag.offsetWidth / 2;\n        tag.style.transform = `translate3d(${Math.min(Math.max(nearX - half, 0), W - half * 2)}px,0,0)`;\n      }\n    }\n\n    // Keep the buffer to what the figures and the tape need.\n    const oldest = Date.now() - Math.max(KEEP, span) - e.lag - 2000;\n    let drop = 0;\n    while (drop < e.ticks.length && e.ticks[drop].t < oldest) drop++;\n    if (drop) e.ticks.splice(0, drop);\n  }, []);\n\n  // The frame loop lives on the engine, so it can schedule itself.\n  React.useLayoutEffect(() => {\n    const e = engine.current;\n    const loop = (now: number) => {\n      e.frame = 0;\n      // With reduced motion the tape steps once a second instead of gliding.\n      if (!e.reduced || now - e.lastStep >= 1000 || e.held) {\n        e.lastStep = now;\n        paint(now);\n      }\n      // Sleep off screen, and while held or paused: the tape only redraws when the pointer moves.\n      if (e.onScreen && !e.held && !e.paused) e.frame = requestAnimationFrame(loop);\n    };\n    e.loop = loop;\n  }, [paint]);\n\n  const wake = React.useCallback(() => {\n    const e = engine.current;\n    if (!e.frame && e.onScreen && e.loop) {\n      e.last = 0;\n      e.frame = requestAnimationFrame(e.loop);\n    }\n  }, []);\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      push(input) {\n        const e = engine.current;\n        const list = Array.isArray(input) ? input : [input];\n        const now = Date.now();\n        for (const ev of list) e.ticks.push({ t: ev.time ?? now, v: Math.max(0, ev.value), err: ev.status === \"error\", label: ev.label });\n        if (list.some((ev) => ev.time !== undefined)) e.ticks.sort((a, b) => a.t - b.t);\n        wake();\n      },\n      clear() {\n        engine.current.ticks = [];\n        wake();\n      },\n    }),\n    [wake],\n  );\n\n  React.useEffect(() => {\n    const e = engine.current;\n    e.reduced = reduced;\n    e.secondsMs = seconds * 1000;\n    e.paused = paused;\n    wake();\n  }, [reduced, seconds, paused, wake]);\n\n  // Size the canvas; sleep when off screen or in a hidden tab.\n  React.useEffect(() => {\n    const plot = plotRef.current;\n    const canvas = canvasRef.current;\n    const root = rootRef.current;\n    if (!plot || !canvas || !root) return;\n    const e = engine.current;\n    const measure = () => {\n      const w = plot.clientWidth;\n      const h = canvas.clientHeight;\n      const dpr = Math.min(window.devicePixelRatio || 1, 3);\n      if (w === e.width && h === e.height && dpr === e.dpr) return;\n      e.width = w;\n      e.height = h;\n      e.dpr = dpr;\n      canvas.width = Math.round(w * dpr);\n      canvas.height = Math.round(h * dpr);\n      paint(performance.now());\n    };\n    measure();\n    const resize = new ResizeObserver(measure);\n    resize.observe(plot);\n    let seen = false;\n    const sync = () => {\n      e.onScreen = seen && !document.hidden;\n      if (e.onScreen) wake();\n      else if (e.frame) {\n        cancelAnimationFrame(e.frame);\n        e.frame = 0;\n      }\n    };\n    const io = new IntersectionObserver(([entry]) => {\n      seen = entry.isIntersecting;\n      sync();\n    });\n    io.observe(root);\n    document.addEventListener(\"visibilitychange\", sync);\n    return () => {\n      resize.disconnect();\n      io.disconnect();\n      document.removeEventListener(\"visibilitychange\", sync);\n      if (e.frame) cancelAnimationFrame(e.frame);\n      e.frame = 0;\n    };\n  }, [paint, wake]);\n\n  React.useEffect(() => {\n    const read = () => {\n      const e = engine.current;\n      if (probeRef.current) e.accent = getComputedStyle(probeRef.current).color;\n      if (inkRef.current) e.ink = getComputedStyle(inkRef.current).color;\n      if (errRef.current) e.error = getComputedStyle(errRef.current).color;\n      paint(performance.now());\n    };\n    read();\n    const observer = new MutationObserver(read);\n    observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n    const media = window.matchMedia(\"(prefers-color-scheme: dark)\");\n    media.addEventListener(\"change\", read);\n    return () => {\n      observer.disconnect();\n      media.removeEventListener(\"change\", read);\n    };\n  }, [color, paint]);\n\n  // The figures, once a second, from what arrived in the last half minute.\n  React.useEffect(() => {\n    const timer = window.setInterval(() => {\n      const e = engine.current;\n      if (!e.onScreen) return;\n      const now = Date.now();\n      const recent = e.ticks.filter((k) => k.t > now - KEEP && k.t <= now);\n      const last5 = recent.filter((k) => k.t > now - 5000).length / 5;\n      const sorted = recent.map((k) => k.v).sort((a, b) => a - b);\n      const p95 = sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95))] : 0;\n      const errors = recent.length ? recent.filter((k) => k.err).length / recent.length : 0;\n      setStats((s) => (s.rate === last5 && s.p95 === p95 && s.errors === errors ? s : { rate: last5, p95, errors }));\n    }, 1000);\n    return () => window.clearInterval(timer);\n  }, []);\n\n  const hold = (x: number | null) => {\n    const e = engine.current;\n    e.held = x !== null;\n    e.pointerX = x;\n    wake();\n  };\n\n  const fmt = (v: number) => new Intl.NumberFormat(locale, format).format(v);\n  const live = !paused;\n\n  return (\n    <div ref={rootRef} className={`w-full rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`} {...props}>\n      <span ref={probeRef} aria-hidden=\"true\" className=\"hidden\" style={{ color }} />\n      <span ref={inkRef} aria-hidden=\"true\" className=\"hidden text-foreground\" />\n      <span ref={errRef} aria-hidden=\"true\" className=\"hidden text-red-500 dark:text-red-400\" />\n      {/* Its natural width where the parent sizes to its content (a centred flex column), without forcing it on narrow screens. */}\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 600px)\" }} />\n      <div className=\"@container w-full\">\n        <div className=\"p-4 @md:p-5 [--plot:120px] @md:[--plot:150px]\">\n          <div className=\"flex items-center justify-between gap-3\">\n            <p className=\"text-[12px] text-muted-foreground @md:text-[13px]\">{title}</p>\n            <button\n              type=\"button\"\n              aria-pressed={paused}\n              onClick={() => setPaused((p) => !p)}\n              className={`-my-1 inline-flex h-7 shrink-0 cursor-pointer items-center gap-1.5 rounded-full px-2.5 text-[12px] font-medium shadow-[inset_0_0_0_1px_var(--border)] transition-colors duration-200 @md:text-[12.5px] ${FOCUS} ${\n                live ? \"text-foreground\" : \"text-muted-foreground hover:text-foreground\"\n              }`}\n            >\n              <span aria-hidden=\"true\" className=\"relative flex size-2\">\n                {live && !reduced && <span className=\"absolute inset-0 animate-ping rounded-full bg-emerald-500/50\" />}\n                <span className={`relative size-2 rounded-full transition-colors duration-200 ${live ? \"bg-emerald-500\" : \"bg-foreground/30\"}`} />\n              </span>\n              {live ? \"Live\" : \"Paused\"}\n            </button>\n          </div>\n\n          {/* Three figures over the last half minute, as a compact strip. */}\n          <div className=\"mt-1.5 grid grid-cols-3 gap-3\">\n            {[\n              { label: \"per second\", node: new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(stats.rate) },\n              { label: \"p95\", node: fmt(stats.p95) },\n              {\n                label: \"errors\",\n                node: new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 1 }).format(stats.errors),\n                warn: stats.errors > 0,\n              },\n            ].map((f) => (\n              <div key={f.label} className=\"min-w-0\">\n                <p\n                  className={`text-[19px] font-medium leading-tight tracking-[-0.03em] tabular-nums @md:text-[22px] ${\n                    f.warn ? \"text-red-600 dark:text-red-400\" : \"text-foreground\"\n                  }`}\n                >\n                  {f.node}\n                </p>\n                <p className=\"truncate text-[11px] text-muted-foreground @md:text-[12px]\">{f.label}</p>\n              </div>\n            ))}\n          </div>\n\n          <div\n            ref={plotRef}\n            role=\"img\"\n            aria-label={`${title}: the last ${seconds} seconds of events, newest on the right. Point at the tape to hold it and read an event.`}\n            onPointerMove={(ev) => {\n              const r = ev.currentTarget.getBoundingClientRect();\n              hold(ev.clientX - r.left);\n            }}\n            onPointerLeave={() => hold(null)}\n            onPointerCancel={() => hold(null)}\n            className=\"relative mt-4 cursor-crosshair touch-pan-y select-none @md:mt-5\"\n          >\n            <canvas ref={canvasRef} aria-hidden=\"true\" className=\"block w-full\" style={{ height: \"var(--plot)\" }} />\n            <div aria-hidden=\"true\" className=\"absolute inset-x-0 bottom-0 border-t border-border\" />\n            <div\n              ref={tagRef}\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute left-0 top-0 flex h-[24px] items-center gap-1.5 whitespace-nowrap rounded-full bg-background px-2.5 text-[11.5px] shadow-[0_0_0_1px_var(--border)]\"\n              style={{ opacity: 0 }}\n            >\n              {picked?.err && <span className=\"size-1.5 rounded-full bg-red-500\" />}\n              <span className=\"font-medium tabular-nums text-foreground\">{picked ? fmt(picked.v) : \" \"}</span>\n              {picked?.label && <span className=\"text-muted-foreground\">{picked.label}</span>}\n            </div>\n          </div>\n          <div aria-hidden=\"true\" className=\"mt-1.5 flex justify-between text-[10.5px] leading-4 text-muted-foreground\">\n            <span>{seconds}s ago</span>\n            <span>now</span>\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/tick-tape. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}