Bar chart
Inspect signed columns against their arithmetic mean with a value readout, pointer and keyboard scrubbing, and an exact data table.
pnpm dlx shadcn@latest add @haze/bar-chart---
import { cn } from "../../../lib/haze/utils";
import Collapsible from "./collapsible.astro";
import Table from "./table.astro";
interface Props {
label?: string;
data?: { label: string; value: number }[];
unit?: string;
categoryLabel?: string;
averageLabel?: string;
showAverage?: boolean;
detailsLabel?: string;
emptyLabel?: string;
class?: string;
}
const {
label = "Merged pull requests", unit = "", categoryLabel = "Day", averageLabel = "Daily average",
showAverage = true, detailsLabel = "View data", emptyLabel = "No counts for this period.", class: className,
data = [{ label: "Mon", value: 18 }, { label: "Tue", value: 32 }, { label: "Wed", value: 26 },
{ label: "Thu", value: 43 }, { label: "Fri", value: 36 }, { label: "Sat", value: 12 }, { label: "Sun", value: 16 }],
} = Astro.props;
const items = data.filter(({ value }) => Number.isFinite(value));
const low = items.reduce((min, item) => Math.min(min, item.value), 0);
const high = items.reduce((max, item) => Math.max(max, item.value), 0);
const scale = Math.max(Math.abs(low), high) || 1;
const span = high / scale - low / scale;
const y = (value: number) => span === 0 ? 95 : 5 + 90 * (high / scale - value / scale) / span;
const zero = y(0);
const average = items.length ? items.reduce((sum, item) => sum + item.value / scale, 0) / items.length * scale : 0;
const grouped = new Intl.NumberFormat("en");
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumSignificantDigits: 3 });
const tickLabel = (value: number) => {
const text = compact.format(value);
return text.length > 10 ? value.toExponential(2) : text;
};
const averageFormat = new Intl.NumberFormat("en", { maximumSignificantDigits: 4 });
const withUnit = (value: string) => unit ? `${value} ${unit}` : value;
const averageText = withUnit(averageFormat.format(average));
const columns = items.map(({ label: period, value }, index) => {
const at = y(value);
return { label: period, value: withUnit(Number.isSafeInteger(value) ? grouped.format(value) : String(value)),
center: (index + 0.5) * 100 / items.length, top: Math.min(zero, at), height: Math.abs(zero - at) };
});
const width = Math.min(7.5, 67 / Math.max(1, columns.length));
const ticks = high === low ? [0] : [high, high > 0 && low < 0 ? 0 : high / 2 + low / 2, low];
---
<figure data-haze-bar-chart data-values={JSON.stringify(columns.map(({ label, value, center }) => ({ label, value, center })))}
class={cn("grid min-w-0 gap-4 rounded-xl border border-border bg-card p-4.5 text-card-foreground", className)}>
<figcaption class="text-[1.0625rem]/6 font-medium tracking-[-0.01em] wrap-anywhere">{label}</figcaption>
{columns.length ? (
<>
<div class="flex min-w-0 flex-wrap items-baseline justify-between gap-2">
<span data-bar-value data-rest={averageText} class="text-3xl/9 font-medium tracking-[-0.01em] wrap-anywhere tabular-nums">{averageText}</span>
<span data-bar-label data-rest={averageLabel} class="text-xs/5 font-medium wrap-anywhere text-muted-foreground">{averageLabel}</span>
</div>
<div class="grid min-w-0 grid-cols-[fit-content(28%)_minmax(0,1fr)] items-start gap-x-2">
<div aria-hidden="true" class="relative h-40 min-w-0 font-mono text-xs/4 text-muted-foreground sm:h-48">
{ticks.map((tick) => <span style={`top:${y(tick)}%`} class="absolute inset-e-0 -translate-y-1/2">{tickLabel(tick)}</span>)}
<span class="invisible">{ticks.map(tickLabel).reduce((longest, text) => text.length > longest.length ? text : longest, "")}</span>
</div>
<div class="min-w-0">
<div data-bar-plot dir="ltr" class="@container/plot relative mx-1 h-40 touch-pan-y rounded-sm has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-4 has-[:focus-visible]:outline-ring [[data-enhanced]_&]:cursor-crosshair sm:h-48">
<svg aria-hidden="true" viewBox="0 0 100 100" preserveAspectRatio="none" class="absolute inset-0 size-full overflow-visible">
{ticks.map((tick) => <path d={`M0 ${y(tick)}h100`} class="fill-none stroke-border" vector-effect="non-scaling-stroke" stroke-dasharray={tick === 0 ? undefined : "2 4"} />)}
{columns.map((column) => (
<rect data-bar-shape x={column.center - width / 2} y={column.top} width={width} height={column.height}
style={`transform-origin: center ${zero}%`} class="fill-brand/55 motion-safe:transition-colors motion-safe:duration-150 motion-safe:ease-snappy data-[active]:fill-brand" />
))}
{showAverage && <path d={`M0 ${y(average)}h100`} class="fill-none stroke-foreground/70" stroke-width="1.5" stroke-dasharray="4 4" vector-effect="non-scaling-stroke" />}
</svg>
<span data-bar-cursor aria-hidden="true" class="pointer-events-none absolute inset-y-0 left-0 w-0 translate-x-(--point) border-s border-border-strong opacity-0 motion-safe:transition-[translate,opacity] motion-safe:duration-150 motion-safe:ease-snappy data-[active]:opacity-100"></span>
<input data-bar-input hidden type="range" min="0" max={columns.length} step="1" value="0" aria-label={`Inspect ${label} by ${categoryLabel}`}
class="pointer-events-none absolute inset-0 m-0 size-full opacity-0" />
</div>
<div dir="ltr" class="mt-2 flex min-w-0 justify-between gap-2 font-mono text-xs/4 text-muted-foreground">
<span class="min-w-0 wrap-anywhere">{columns[0].label}</span>
{columns.length > 1 && <span class="min-w-0 text-end wrap-anywhere">{columns[columns.length - 1].label}</span>}
</div>
</div>
</div>
{showAverage && <div class="flex min-w-0 items-center gap-2 text-xs/4 text-muted-foreground">
<span aria-hidden="true" class="w-5 shrink-0 border-t border-dashed border-muted-foreground"></span>
<span class="wrap-anywhere">{averageLabel} · {averageText}</span>
</div>}
<Collapsible title={detailsLabel} class="min-w-0 rounded-lg bg-background/40">
<Table caption={label} hideCaption columns={[{ key: "label", label: categoryLabel }, { key: "value", label, align: "right" }]}
rows={columns.map(({ label, value }) => ({ label, value }))} rowHeader="label" class="min-w-0 rounded-md" />
</Collapsible>
</>
) : <p class="text-[0.8125rem]/5 text-muted-foreground">{emptyLabel}</p>}
</figure>
<script>
interface Bar { label: string; value: string; center: number }
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const plot = root.querySelector<HTMLElement>("[data-bar-plot]");
const input = root.querySelector<HTMLInputElement>("[data-bar-input]");
const headline = root.querySelector<HTMLElement>("[data-bar-value]");
const period = root.querySelector<HTMLElement>("[data-bar-label]");
const cursor = root.querySelector<HTMLElement>("[data-bar-cursor]");
if (!plot || !input || !headline || !period || !cursor) return;
const data: Bar[] = JSON.parse(root.dataset.values ?? "[]");
const bars = root.querySelectorAll<SVGRectElement>("[data-bar-shape]");
const motion = matchMedia("(prefers-reduced-motion: reduce)");
const easing = getComputedStyle(root).getPropertyValue("--ease-snappy").trim() || "ease";
let headlineMotion: Animation | undefined;
let selected = -1;
const show = (index: number) => {
if (selected >= 0) bars[selected].removeAttribute("data-active");
const bar = data[index];
selected = index;
const nextValue = bar?.value ?? headline.dataset.rest ?? "";
if (headline.textContent !== nextValue) {
headline.textContent = nextValue;
headlineMotion?.cancel();
if (!motion.matches) headlineMotion = headline.animate([{ opacity: 0.65, translate: "0 12%" }, { opacity: 1, translate: "0 0" }], { duration: 150, easing });
}
period.textContent = bar?.label ?? period.dataset.rest ?? "";
input.value = String(index + 1);
input.setAttribute("aria-valuetext", `${period.textContent}, ${headline.textContent}`);
cursor.toggleAttribute("data-active", Boolean(bar));
if (bar) {
bars[index].setAttribute("data-active", "");
cursor.style.setProperty("--point", `${bar.center}cqw`);
}
};
const inspect = (event: PointerEvent) => {
const box = plot.getBoundingClientRect();
const index = Math.min(data.length - 1, Math.max(0, Math.floor((event.clientX - box.left) / box.width * data.length)));
if (index !== selected) show(index);
};
plot.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
input.focus({ preventScroll: true });
inspect(event);
});
plot.addEventListener("pointermove", inspect);
plot.addEventListener("pointerleave", () => { if (document.activeElement !== input) show(-1); });
input.hidden = false;
input.addEventListener("input", () => show(Number(input.value) - 1));
input.addEventListener("blur", () => show(-1));
input.addEventListener("keydown", (event) => { if (event.key === "Escape") show(-1); });
show(-1);
root.setAttribute("data-enhanced", "");
const initially = plot.getBoundingClientRect();
if ("IntersectionObserver" in window && !motion.matches && (initially.top >= innerHeight || initially.bottom <= 0)) {
const observer = new IntersectionObserver(([entry]) => {
if (!entry.isIntersecting) return;
observer.disconnect();
if (motion.matches) return;
bars.forEach((bar, index) => bar.animate([{ scale: "1 0" }, { scale: "1 1" }], {
duration: 200, delay: Math.min(index, 8) * 9, easing, fill: "backwards",
}));
});
observer.observe(plot);
}
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-bar-chart]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-bar-chart-listener")) {
document.documentElement.setAttribute("data-haze-bar-chart-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- A report compares one measurement across distinct periods or categories.
- The mean gives readers a reference point for individual counts.
When not to use
- Several series share the same time axis. Use line-chart.
- Long category names need to appear alongside horizontal bars. Use bar-list.
Installation
Add the Haze registry to components.json once, then install Bar chart with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/bar-chartnpx shadcn@latest add @haze/bar-chartyarn dlx shadcn@latest add @haze/bar-chartbunx --bun shadcn@latest add @haze/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 | Merged pull requests | Name of the measure and the caption of the data table. |
| data | { label: string; value: number }[] | – | Finite positive, negative or zero values in display order. Nonfinite entries are excluded. |
| unit | string | empty string | Suffix on the headline and table values. |
| categoryLabel | string | Day | Name of the categories in the table and scrubber. |
| averageLabel | string | Daily average | Name of the reference line and resting value. |
| showAverage | boolean | true | Draw the dashed mean line and its legend. |
| detailsLabel | string | View data | Disclosure label for the original category values. |
| emptyLabel | string | – | Message when there are no finite categories to compare. |
| class | string | – | Additional classes on the chart figure. |
Keyboard interactions
- Arrow keys
- Move between the mean and individual columns.
- HomeEscape
- Return to the arithmetic mean.
- End
- Inspect the last column.
- EnterSpace
- Open or close the focused data disclosure.
Accessibility
- The native range control announces each category and amount. Opening the data table also works with JavaScript disabled.
- The dashed reference line has a textual legend. Reduced motion shows the finished columns immediately.
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 "Bar chart" with `npx shadcn@latest add @haze/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 BarChart from "@/components/haze/ui/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/bar-chart.md
Customize with real content
Adapt the Haze bar-chart ui for our product. Replace the demo values of these props with our real content: label, data, unit, categoryLabel, averageLabel, showAverage, detailsLabel, emptyLabel, class. Keep the layout, the heading level rules and these accessibility details: The native range control announces each category and amount. Opening the data table also works with JavaScript disabled. The dashed reference line has a textual legend. Reduced motion shows the finished columns immediately. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using bar-chart, check it fits: use it when a report compares one measurement across distinct periods or categories.; the mean gives readers a reference point for individual counts.. Avoid it when several series share the same time axis. use line-chart.; long category names need to appear alongside horizontal bars. use bar-list.. Alternatives: @haze/bar-list, @haze/line-chart, @haze/bento-growth.
Dependencies
- @haze/collapsible
- @haze/table
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.