Race bar chart
Play or scrub ranked values over time with interpolated bars, moving ranks and a complete period-by-period table.
pnpm dlx shadcn@latest add @haze/race-bar-chart---
import { ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Item{key:string;label:string}
interface Frame{label:string;values:Record<string,number>}
interface Props{label?:string;items?:Item[];frames?:Frame[];unit?:string;interval?:number;class?:string}
const{label="Package adoption",unit="teams",interval=1600,items=[{key:"core",label:"Core"},{key:"studio",label:"Studio"},{key:"cli",label:"CLI"},{key:"cloud",label:"Cloud"}],frames=[{label:"January",values:{core:120,studio:70,cli:90,cloud:35}},{label:"February",values:{core:150,studio:130,cli:105,cloud:80}},{label:"March",values:{core:175,studio:195,cli:145,cloud:125}},{label:"April",values:{core:205,studio:245,cli:185,cloud:230}}],class:className}=Astro.props;
const seen=new Set<string>(),fields=items.filter(item=>{if(!item.key||seen.has(item.key))return false;seen.add(item.key);return true;}),periods=frames.map(frame=>({...frame,values:fields.map(item=>Number.isFinite(frame.values[item.key])&&frame.values[item.key]>0?frame.values[item.key]:0)}));
const values=periods[0]?.values??fields.map(()=>0),order=fields.map((_,i)=>i).sort((a,b)=>values[b]-values[a]||a-b),max=Math.max(0,...values);
const colors=["fill-brand","fill-success","fill-warning","fill-muted-foreground","fill-destructive"];
---
<figure data-haze-race-bar-chart data-fields={JSON.stringify(fields)} data-frames={JSON.stringify(periods)} data-unit={unit} data-interval={Number.isFinite(interval)?Math.max(500,interval):1600} class={cn("grid min-w-0 gap-3 rounded-xl border border-border bg-card p-4.5 text-card-foreground",className)}>
<figcaption class="text-[0.9375rem]/5 font-medium tracking-[-0.01em] wrap-anywhere">{label}</figcaption>
<p data-race-period class="font-mono text-xs/5 text-muted-foreground">{periods[0]?.label??"No periods"}</p>
{periods.length&&fields.length?<svg data-race-plot aria-hidden="true" viewBox={"0 0 300 "+Math.max(50,fields.length*38)} class="w-full">{fields.map((item,index)=><g data-race-row={index} transform={"translate(0 "+order.indexOf(index)*38+")"}><rect data-race-bar x="100" y="0" width={max?values[index]/max*140:0} height="26" rx="3" class={colors[index%colors.length]}/><text data-race-name x="0" y="17" class="fill-foreground text-[12px]/4">{item.label}</text><text data-race-value x="295" y="17" text-anchor="end" class="fill-muted-foreground text-[12px]/4">{values[index].toLocaleString("en")}</text></g>)}</svg>:<p class="text-[0.8125rem]/5 text-muted-foreground">Add ranked items and at least one period.</p>}
{periods.length>0&&<div hidden data-race-controls class="grid gap-2"><div class="flex flex-wrap gap-2"><button data-race-play type="button" aria-pressed="false" class="h-8 rounded-lg border border-frame bg-secondary px-3 text-[0.8125rem]/5 font-medium transition-colors duration-150 ease-snappy hover:bg-accent active:scale-[0.97] focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">Play timeline</button><button data-race-reset type="button" class="h-8 rounded-lg border border-frame bg-field px-3 text-[0.8125rem]/5 font-medium transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">First period</button></div><label class="grid gap-1 text-xs/5 text-muted-foreground">Timeline<input data-race-cursor aria-label="Ranking period" type="range" min="0" max={periods.length-1} value="0" 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></div>}
<p data-race-readout role="status" aria-live="polite" class="min-h-10 text-xs/5 text-muted-foreground">Play or scrub the timeline to compare rankings. Playback starts only when requested.</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">Every ranking period<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">Period</th><th scope="col" class="p-1">Ranked values ({unit})</th></tr></thead><tbody>{periods.map(frame=><tr class="border-t border-border"><th scope="row" class="p-1 font-normal wrap-anywhere">{frame.label}</th><td class="p-1 tabular-nums wrap-anywhere">{fields.map((_,i)=>i).sort((a,b)=>frame.values[b]-frame.values[a]||a-b).map((i,rank)=>(rank+1)+". "+fields[i].label+": "+frame.values[i]).join("; ")}</td></tr>)}</tbody></table></details>
</figure>
<script>
function initRace(){document.querySelectorAll<HTMLElement>("[data-haze-race-bar-chart]:not([data-enhanced])").forEach(root=>{
root.dataset.enhanced="";const fields:{label:string}[]=JSON.parse(root.dataset.fields||"[]"),frames:{label:string;values:number[]}[]=JSON.parse(root.dataset.frames||"[]"),cursor=root.querySelector<HTMLInputElement>("[data-race-cursor]"),play=root.querySelector<HTMLButtonElement>("[data-race-play]"),rows=Array.from(root.querySelectorAll<SVGGElement>("[data-race-row]"));if(!cursor||!play||!frames.length||!rows.length)return;root.querySelector("[data-race-controls]")?.removeAttribute("hidden");
let current=[...frames[0].values],positions=fields.map((_,i)=>fields.map((_,j)=>j).sort((a,b)=>current[b]-current[a]||a-b).indexOf(i)*38),raf=0,timer=0,playing=false,visible=true;const reduced=matchMedia("(prefers-reduced-motion: reduce)");
const plot=root.querySelector<SVGSVGElement>("[data-race-plot]")!;const fitLabels=()=>{const font=12*300/Math.max(1,plot.getBoundingClientRect().width),characters=Math.max(3,Math.floor(94/(font*.6)));rows.forEach((row,i)=>{const name=row.querySelector<SVGTextElement>("[data-race-name]")!,value=row.querySelector<SVGTextElement>("[data-race-value]")!;name.style.fontSize=font+"px";value.style.fontSize=font+"px";name.textContent=fields[i].label.length>characters?fields[i].label.slice(0,characters-1)+"…":fields[i].label;});};new ResizeObserver(fitLabels).observe(plot);fitLabels();
const stop=()=>{clearInterval(timer);playing=false;play.setAttribute("aria-pressed","false");play.textContent="Play timeline";};
const show=(index:number)=>{cursor.value=String(index);const target=frames[index].values,order=fields.map((_,i)=>i).sort((a,b)=>target[b]-target[a]||a-b),targetPositions=fields.map((_,i)=>order.indexOf(i)*38),from=[...current],oldPositions=[...positions],began=performance.now();cancelAnimationFrame(raf);const frame=(now:number)=>{const t=reduced.matches?1:Math.min(1,(now-began)/250),ease=1-Math.pow(1-t,3);current=target.map((v,i)=>from[i]*(1-ease)+v*ease);positions=targetPositions.map((p,i)=>oldPositions[i]*(1-ease)+p*ease);const runningMax=Math.max(0,...current);rows.forEach((row,i)=>{row.setAttribute("transform","translate(0 "+positions[i]+")");row.querySelector("[data-race-bar]")!.setAttribute("width",String(runningMax?current[i]/runningMax*140:0));row.querySelector("[data-race-value]")!.textContent=current[i].toLocaleString("en",{maximumFractionDigits:0});});if(t<1)raf=requestAnimationFrame(frame);};raf=requestAnimationFrame(frame);root.querySelector("[data-race-period]")!.textContent=frames[index].label;const leader=order[0],text=frames[index].label+(leader===undefined?"":": leader "+fields[leader].label+", "+target[leader]+" "+(root.dataset.unit||""))+".";cursor.setAttribute("aria-valuetext",text);root.querySelector("[data-race-readout]")!.textContent=text;};
play.addEventListener("click",()=>{if(playing){stop();return;}if(Number(cursor.value)===frames.length-1)show(0);playing=true;play.setAttribute("aria-pressed","true");play.textContent="Pause timeline";timer=window.setInterval(()=>{if(!root.isConnected){stop();return;}if(document.hidden||!visible)return;const next=Number(cursor.value)+1;if(next>=frames.length){stop();return;}show(next);if(next===frames.length-1)stop();},Number(root.dataset.interval)||1600);});cursor.addEventListener("input",()=>{stop();show(Number(cursor.value));});root.querySelector("[data-race-reset]")?.addEventListener("click",()=>{stop();show(0);});const observer=new IntersectionObserver(entries=>{visible=entries[0].isIntersecting;});observer.observe(root);reduced.addEventListener("change",()=>{if(reduced.matches)stop();});show(0);
});}
initRace();if(!document.documentElement.hasAttribute("data-haze-race-bar-chart-listener")){document.documentElement.setAttribute("data-haze-race-bar-chart-listener","");document.addEventListener("astro:page-load",initRace);}
</script>When to use
- The identity of a ranking's leader changes over multiple periods.
- Readers should replay a ranking and stop at any exact period.
When not to use
- One static ranking is sufficient. Use bar-chart.
Installation
Add the Haze registry to components.json once, then install Race bar chart with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/race-bar-chartnpx shadcn@latest add @haze/race-bar-chartyarn dlx shadcn@latest add @haze/race-bar-chartbunx --bun shadcn@latest add @haze/race-bar-chartFirst 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 | Package adoption | Ranking caption. |
| items | { key: string; label: string }[] | – | Stable uniquely keyed ranked items. |
| frames | { label: string; values: Record<string, number> }[] | – | Ordered ranking periods; negative, missing and nonfinite counts become zero. |
| unit | string | teams | Ranked measurement unit. |
| interval | number | 1600 | Playback delay in milliseconds, with a 500 ms minimum. |
| class | string | – | Additional classes on the chart figure. |
Keyboard interactions
- Arrow keysHomeEnd
- Scrub ranking periods and pause playback.
- EnterSpace
- Play, pause or reset the ranking timeline.
Accessibility
- Playback is explicitly started, pauses while offscreen or hidden, and stops at the final period; reduced motion skips interpolation.
- A native timeline announces the period and leader. Names and values remain printed on bars and every period is in the table.
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 "Race bar chart" with `npx shadcn@latest add @haze/race-bar-chart`. 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 RaceBarChart from "@/components/haze/ui/race-bar-chart.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/race-bar-chart.md
Customize with real content
Adapt the Haze race-bar-chart ui for our product. Replace the demo values of these props with our real content: label, items, frames, unit, interval, class. Keep the layout, the heading level rules and these accessibility details: Playback is explicitly started, pauses while offscreen or hidden, and stops at the final period; reduced motion skips interpolation. A native timeline announces the period and leader. Names and values remain printed on bars and every period is in the table. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using race-bar-chart, check it fits: use it when the identity of a ranking's leader changes over multiple periods.; readers should replay a ranking and stop at any exact period.. Avoid it when one static ranking is sufficient. use bar-chart.. Alternatives: @haze/bar-chart, @haze/line-chart, @haze/slope-chart.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.