Realtime stream
Append real readings through a chart event, pause or inspect the buffered line, and announce named anomalies as they arrive.
pnpm dlx shadcn@latest add @haze/realtime-stream---
import { ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Reading{label:string;value:number;note?:string}
interface Props{label?:string;readings?:Reading[];unit?:string;capacity?:number;class?:string}
const{label="Edge response time",unit="ms",capacity=40,readings=[{label:"14:01:00",value:42},{label:"14:01:05",value:45},{label:"14:01:10",value:41},{label:"14:01:15",value:56,note:"Cache miss"},{label:"14:01:20",value:46},{label:"14:01:25",value:43},{label:"14:01:30",value:44}],class:className}=Astro.props;
const limit=Number.isFinite(capacity)?Math.max(2,Math.min(500,Math.floor(capacity))):40,points=readings.filter(point=>Number.isFinite(point.value)).slice(-limit);
const lo=points.length?Math.min(...points.map(point=>point.value)):0,hi=points.length?Math.max(...points.map(point=>point.value)):1,scale=Math.max(Math.abs(lo),Math.abs(hi),1),y=(value:number)=>hi===lo?100:180-(value/scale-lo/scale)/(hi/scale-lo/scale)*160;
const path=points.map((point,index)=>(index?"L":"M")+(points.length===1?150:index/(points.length-1)*300)+" "+y(point.value)).join(" ");
---
<figure data-haze-realtime-stream data-readings={JSON.stringify(points)} data-capacity={limit} data-unit={unit} class={cn("grid min-w-0 gap-3 rounded-xl border border-border bg-card p-4.5 text-card-foreground",className)}>
<figcaption class="flex min-w-0 flex-wrap items-center justify-between gap-2"><span class="text-sm/5 font-medium wrap-anywhere">{label}</span><button data-stream-pause type="button" disabled aria-pressed="false" class="h-8 rounded-lg border border-frame bg-field px-3 text-[0.8125rem]/5 font-medium transition-colors duration-150 ease-snappy enabled:hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">Live · pause</button></figcaption>
<p data-live-current class="font-mono text-xl/7 font-medium tabular-nums wrap-anywhere" aria-label={"Latest "+label}>{points.at(-1)?.value.toLocaleString("en")??"No reading"} {unit}</p>
<svg data-live-plot aria-hidden="true" viewBox="0 0 300 200" preserveAspectRatio="none" class="h-44 w-full"><path d="M0 20H300M0 100H300M0 180H300" vector-effect="non-scaling-stroke" class="stroke-border"/><path data-live-line d={path} fill="none" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" class="stroke-brand"/><g data-live-markers>{points.map((point,index)=>point.note&&<path d={"M"+(points.length===1?150:index/(points.length-1)*300)+" "+y(point.value)+"h0"} stroke-width="9" stroke-linecap="round" vector-effect="non-scaling-stroke" class="stroke-warning"/>)}</g><path data-live-crosshair d="M300 15V185" vector-effect="non-scaling-stroke" class="stroke-muted-foreground" stroke-dasharray="3 3"/></svg>
<label hidden data-live-control class="grid gap-1 text-xs/5 text-muted-foreground">Read buffered points<input data-live-cursor aria-label="Buffered reading" type="range" min="0" max={Math.max(0,points.length-1)} value={Math.max(0,points.length-1)} step="1" class="h-10 w-full min-w-0 cursor-pointer appearance-none rounded-md bg-transparent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-not-allowed [&::-webkit-slider-runnable-track]:h-1.5 [&::-webkit-slider-runnable-track]:rounded-full [&::-webkit-slider-runnable-track]:bg-input [&::-webkit-slider-thumb]:-mt-2 [&::-webkit-slider-thumb]:size-5.5 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:border-0 [&::-webkit-slider-thumb]:bg-foreground [&::-webkit-slider-thumb]:shadow-key [&::-webkit-slider-thumb]:transition-[scale] [&::-webkit-slider-thumb]:duration-150 [&::-webkit-slider-thumb]:ease-snappy enabled:active:[&::-webkit-slider-thumb]:scale-95 [&::-moz-range-track]:h-1.5 [&::-moz-range-track]:rounded-full [&::-moz-range-track]:bg-input [&::-moz-range-thumb]:size-5.5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-foreground [&::-moz-range-thumb]:shadow-key [&::-moz-range-thumb]:transition-[scale] [&::-moz-range-thumb]:duration-150 [&::-moz-range-thumb]:ease-snappy enabled:active:[&::-moz-range-thumb]:scale-95 forced-colors:appearance-auto"/></label>
<p data-live-readout class="min-h-10 text-xs/5 text-muted-foreground">Accepts finite readings through the haze:reading event on this chart. Pausing freezes the view while the buffer continues.</p>
<p data-live-announce role="status" aria-live="polite" class="sr-only"></p>
<details class="group min-w-0 border-t border-border pt-3"><summary class="flex min-h-7 cursor-pointer list-none items-center justify-between gap-2 rounded-sm text-[0.8125rem]/5 font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">Latest 20 readings<ChevronDown aria-hidden="true" class="size-3.5 shrink-0 transition-[rotate] duration-200 ease-snappy group-open:rotate-180" /></summary><table class="mt-3 w-full table-fixed text-left text-xs/5"><caption class="sr-only">{label}</caption><thead><tr><th scope="col" class="p-1">Time</th><th scope="col" class="p-1">Value / note</th></tr></thead><tbody data-live-table>{points.slice(-20).map(point=><tr class="border-t border-border"><th scope="row" class="p-1 font-normal wrap-anywhere">{point.label}</th><td class="p-1 tabular-nums wrap-anywhere">{point.value} {unit}{point.note?" · "+point.note:""}</td></tr>)}</tbody></table></details>
</figure>
<script>
function initRealtime(){document.querySelectorAll<HTMLElement>("[data-haze-realtime-stream]:not([data-enhanced])").forEach(root=>{
root.dataset.enhanced="";type Reading={label:string;value:number;note?:string};let buffer:Reading[]=JSON.parse(root.dataset.readings||"[]"),view=[...buffer],paused=false,holding=false,visible=true,raf=0,previous:number[][]=[];const capacity=Number(root.dataset.capacity),unit=root.dataset.unit||"",pause=root.querySelector<HTMLButtonElement>("[data-stream-pause]")!,cursor=root.querySelector<HTMLInputElement>("[data-live-cursor]")!,line=root.querySelector<SVGPathElement>("[data-live-line]")!,plot=root.querySelector<SVGSVGElement>("[data-live-plot]")!,reduced=matchMedia("(prefers-reduced-motion: reduce)");
const geometry=()=>{if(!view.length)return Array.from({length:65},(_,i)=>[i/64*300,100]);const lo=Math.min(...view.map(p=>p.value)),hi=Math.max(...view.map(p=>p.value)),scale=Math.max(Math.abs(lo),Math.abs(hi),1);return Array.from({length:65},(_,i)=>{const at=i/64*Math.max(0,view.length-1),j=Math.floor(at),t=at-j,value=(view[j]?.value??0)/scale*(1-t)+(view[Math.min(j+1,view.length-1)]?.value??0)/scale*t;return[i/64*300,hi===lo?100:180-(value-lo/scale)/(hi/scale-lo/scale)*160];});};
let said="",timer=0;const say=(text:string)=>{clearTimeout(timer);if(text===said)return;said=text;root.querySelector("[data-live-announce]")!.textContent=text;};const sayLater=(text:string)=>{clearTimeout(timer);timer=window.setTimeout(()=>say(text),1000);};const read=()=>{const index=Number(cursor.value),point=view[index];if(!point)return;const text=point.label+": "+point.value+" "+unit+(point.note?". "+point.note:"");root.querySelector("[data-live-readout]")!.textContent=text;cursor.setAttribute("aria-valuetext",text);root.querySelector("[data-live-crosshair]")!.setAttribute("d","M"+(view.length===1?150:index/(view.length-1)*300)+" 15V185");};
const draw=()=>{view=[...buffer];cursor.max=String(Math.max(0,view.length-1));cursor.value=cursor.max;root.querySelector("[data-live-current]")!.textContent=(view.at(-1)?.value.toLocaleString("en")??"No reading")+" "+unit;const target=geometry(),from=previous.length?previous:target,began=performance.now();cancelAnimationFrame(raf);const frame=(now:number)=>{const t=reduced.matches?1:Math.min(1,(now-began)/200);previous=target.map((p,i)=>p.map((v,j)=>from[i][j]+(v-from[i][j])*t));line.setAttribute("d",view.length?previous.map((p,i)=>(i?"L":"M")+p.join(" ")).join(" "):"");if(t<1)raf=requestAnimationFrame(frame);};raf=requestAnimationFrame(frame);
const markers=root.querySelector("[data-live-markers]")!;markers.replaceChildren();const lo=Math.min(...view.map(p=>p.value)),hi=Math.max(...view.map(p=>p.value)),scale=Math.max(Math.abs(lo),Math.abs(hi),1);view.forEach((point,index)=>{if(!point.note)return;const dot=document.createElementNS("http://www.w3.org/2000/svg","path");dot.setAttribute("d","M"+(view.length===1?150:index/(view.length-1)*300)+" "+(hi===lo?100:180-(point.value/scale-lo/scale)/(hi/scale-lo/scale)*160)+"h0");dot.style.strokeWidth="9";dot.style.strokeLinecap="round";dot.setAttribute("vector-effect","non-scaling-stroke");dot.setAttribute("class","stroke-warning");markers.append(dot);});
const table=root.querySelector("[data-live-table]")!;table.replaceChildren();view.slice(-20).forEach(point=>{const tr=document.createElement("tr"),th=document.createElement("th"),td=document.createElement("td");tr.className="border-t border-border";th.scope="row";th.className="p-1 font-normal wrap-anywhere";th.textContent=point.label;td.className="p-1 tabular-nums wrap-anywhere";td.textContent=point.value+" "+unit+(point.note?" · "+point.note:"");tr.append(th,td);table.append(tr);});read();};
const status=()=>{pause.setAttribute("aria-pressed",String(paused));pause.textContent=paused?"Paused · resume":holding?"Inspecting · pause":"Live · pause";};
pause.disabled=false;root.querySelector("[data-live-control]")?.removeAttribute("hidden");pause.addEventListener("click",()=>{paused=!paused;status();if(!paused)draw();});cursor.addEventListener("focus",()=>{holding=true;status();});cursor.addEventListener("blur",()=>{holding=false;status();if(!paused)draw();});cursor.addEventListener("input",()=>{read();sayLater(root.querySelector("[data-live-readout]")!.textContent||"");});plot.addEventListener("pointerup",()=>say(root.querySelector("[data-live-readout]")!.textContent||""));plot.addEventListener("pointerenter",event=>{if(event.pointerType==="mouse"){holding=true;status();}});plot.addEventListener("pointermove",event=>{if(!view.length)return;const bounds=plot.getBoundingClientRect();cursor.value=String(Math.round(Math.max(0,Math.min(1,(event.clientX-bounds.left)/bounds.width))*(view.length-1)));read();});plot.addEventListener("pointerleave",()=>{holding=false;status();if(!paused)draw();});
root.addEventListener("haze:reading",((event:CustomEvent<Reading>)=>{const point=event.detail;if(!point||typeof point.label!=="string"||!Number.isFinite(point.value))return;buffer=[...buffer,{label:point.label,value:point.value,note:typeof point.note==="string"?point.note:undefined}].slice(-capacity);if(!paused&&!holding&&visible&&!document.hidden)draw();if(point.note){const text="Anomaly at "+point.label+": "+point.note+", "+point.value+" "+unit;root.querySelector("[data-live-readout]")!.textContent=text;say(text);}}) as EventListener);
const observer=new IntersectionObserver(entries=>{visible=entries[0].isIntersecting;if(visible&&!paused&&!holding)draw();});observer.observe(root);draw();
});}
initRealtime();if(!document.documentElement.hasAttribute("data-haze-realtime-stream-listener")){document.documentElement.setAttribute("data-haze-realtime-stream-listener","");document.addEventListener("astro:page-load",initRealtime);}
</script>When to use
- A monitoring panel receives timestamped readings from a real event source.
- Readers need a frozen inspection view while the live buffer continues collecting.
When not to use
- The full dataset is static and already available. Use line-chart.
Installation
Add the Haze registry to components.json once, then install Realtime stream with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/realtime-streamnpx shadcn@latest add @haze/realtime-streamyarn dlx shadcn@latest add @haze/realtime-streambunx --bun shadcn@latest add @haze/realtime-streamFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| label | string | Edge response time | Caption and accessible current-value name. |
| readings | { label: string; value: number; note?: string }[] | – | Initial ordered finite readings; append by dispatching haze:reading with the same object as event detail on the figure. |
| unit | string | ms | Reading suffix. |
| capacity | number | 40 | Maximum buffered readings, clamped from 2 to 500. |
| class | string | – | Additional classes on the chart figure. |
Keyboard interactions
- Arrow keysHomeEnd
- Inspect buffered readings while the view is held.
- EnterSpace
- Toggle live display and paused inspection.
Accessibility
- The live/paused toggle uses text and pressed state. Focusing the native reading range holds the view until focus leaves.
- Named anomalies are announced on arrival; the data disclosure follows the latest 20 displayed readings and reduced motion removes interpolation.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Realtime stream" with `npx shadcn@latest add @haze/realtime-stream`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import RealtimeStream from "@/components/haze/ui/realtime-stream.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/realtime-stream.md
Customize with real content
Adapt the Haze realtime-stream ui for our product. Replace the demo values of these props with our real content: label, readings, unit, capacity, class. Keep the layout, the heading level rules and these accessibility details: The live/paused toggle uses text and pressed state. Focusing the native reading range holds the view until focus leaves. Named anomalies are announced on arrival; the data disclosure follows the latest 20 displayed readings and reduced motion removes interpolation. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using realtime-stream, check it fits: use it when a monitoring panel receives timestamped readings from a real event source.; readers need a frozen inspection view while the live buffer continues collecting.. Avoid it when the full dataset is static and already available. use line-chart.. Alternatives: @haze/line-chart, @haze/brush-chart, @haze/sparkline.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.