Tally
Animated Dot Chart for React
A chart where every dot is a fixed amount (a job, a vote, a hundred dollars), packed into one round cluster per category. When the numbers change, the dots that moved fly from the clusters that shrank to the ones that grew on hairline trails, and the counts underneath step as they land. Units you mark hollow, like retries, sit among the dots as rings.
- Chart
- Data
- Canvas
Uses clsx, tailwind-merge
<Tally />replays the demo when you let go.
"use client";
import * as React from "react";
import { Tally, type TallyItem } from "@/components/ui/tally";
// Jobs Corvid ran in the last hour, by region. Hollow rings are jobs that had to be retried.
// No item sets a color, so the regions take Tally's palette in order: orange, violet, green, pink.
const HEALTHY: TallyItem[] = [
{ id: "us-east", label: "us-east", value: 4800, hollow: 120 },
{ id: "eu-west", label: "eu-west", value: 3600, hollow: 80 },
{ id: "ap-south", label: "ap-south", value: 2200, hollow: 60 },
{ id: "sa-east", label: "sa-east", value: 1200, hollow: 40 },
];
// eu-west goes dark: its 3,600 jobs move to the other three, and retries climb while they do.
const OUTAGE: TallyItem[] = [
{ id: "us-east", label: "us-east", value: 6500, hollow: 220 },
{ id: "eu-west", label: "eu-west", value: 0 },
{ id: "ap-south", label: "ap-south", value: 3400, hollow: 140 },
{ id: "sa-east", label: "sa-east", value: 1900, hollow: 80 },
];
// Seconds the healthy chart holds before the outage plays on its own, if nobody has touched it.
const HOLD = 1.4;
export function TallyDemo() {
const [down, setDown] = React.useState(false);
const touched = React.useRef(false);
const played = React.useRef(false);
const timer = React.useRef(0);
React.useEffect(() => () => window.clearTimeout(timer.current), []);
// After the first settle, show the outage once, unless the visitor got there first.
const onSettle = React.useCallback(() => {
if (played.current || touched.current) return;
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
played.current = true;
timer.current = window.setTimeout(() => {
if (!touched.current) setDown(true);
}, HOLD * 1000);
}, []);
const toggle = () => {
touched.current = true;
window.clearTimeout(timer.current);
setDown((d) => !d);
};
return (
<div className="w-full max-w-3xl overflow-hidden rounded-2xl border border-zinc-950/10 bg-white text-zinc-950 dark:border-white/10 dark:bg-zinc-950 dark:text-white">
<div className="flex flex-wrap items-start justify-between gap-3 px-5 pt-5">
<div>
<h3 className="text-[15px] font-medium tracking-tight">Jobs by region</h3>
<p className="mt-0.5 font-mono text-[11px] tracking-wide text-zinc-500 uppercase dark:text-zinc-400">Corvid inference · last 60 min</p>
</div>
<p
aria-live="polite"
className="flex items-center gap-2 rounded-full border border-zinc-950/10 px-3 py-1 font-mono text-[11px] text-zinc-600 dark:border-white/10 dark:text-zinc-300"
>
<span aria-hidden className={down ? "size-1.5 rounded-full bg-red-500" : "size-1.5 rounded-full bg-emerald-500"} />
{down ? "eu-west down" : "All regions up"}
</p>
</div>
<Tally
items={down ? OUTAGE : HEALTHY}
unit="jobs"
hollowLabel="retried"
label="Jobs by region in the last hour"
onSettle={onSettle}
className="mx-5 mt-5 h-[25rem] sm:h-72"
/>
<div className="mt-2 flex flex-col gap-3 border-t border-zinc-950/10 px-5 py-4 sm:flex-row sm:items-center sm:justify-between dark:border-white/10">
<p className="font-mono text-xs leading-relaxed text-zinc-600 dark:text-zinc-400">
{down
? "3,600 jobs moved to the nearest healthy regions."
: "Every job runs in the region closest to its caller."}
</p>
<button
type="button"
onClick={toggle}
className="shrink-0 rounded-full bg-zinc-950 px-4 py-2 font-mono text-xs text-white transition-colors hover:bg-zinc-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#2f45e8] dark:bg-white dark:text-zinc-950 dark:hover:bg-zinc-200 dark:focus-visible:outline-[#8b98ff]"
>
{down ? "Bring eu-west back" : "Take eu-west offline"}
</button>
</div>
</div>
);
}
Add this moment from KeyframeUI to our project and adapt it to our content. Tally: A chart where every dot is a fixed amount (a job, a vote, a hundred dollars), packed into one round cluster per category. When the numbers change, the dots that moved fly from the clusters that shrank to the ones that grew on hairline trails, and the counts underneath step as they land. Units you mark hollow, like retries, sit among the dots as rings. This demo, Failover: Jobs by region for an inference platform. Take eu-west offline and its jobs fly to the other three regions, while retries show up as rings. 1. Install it: npx shadcn@latest add @keyframeui/tally-demo (If the CLI can't find @keyframeui, use https://keyframeui.com/r/tally-demo.json instead.) It adds the demo, components/tally-demo.tsx, and the component, components/ui/tally.tsx. 2. Make it ours: our copy, data, images and colors. Keep the structure the motion depends on. If we only need the effect, use <Tally> on its own. 3. These props set its feel. Change them before you change the file: - layout (default "row"): `row` sets the clusters side by side over one line of labels, wrapping onto more rows when columns would get narrower than about 130px. `free` puts each cluster at its item's `x` and `y`, like places on a map, with its label under it. - dotSize (default 6): Diameter of a dot, in px. When a cluster would outgrow its room, every dot shrinks together instead, so the clusters stay comparable. - gap (default 1.5): Space between neighbouring dots, in px. - trails (default true): Draw each dot's path behind it as a hairline that reels in once it lands. - duration (default 1.1): Seconds a dot takes to fly: in from the edge, or across to another cluster. Each one varies by a quarter either way. - stagger (default 0.9): Seconds between the first dot leaving the edge and the last, on the way in. - trailLength (default 0.55): How far a trail lags behind its dot, as a share of the flight, from 0 (none) to 1 (the whole path so far). - legend (default true): Show the legend above the clusters: what one dot is worth, and what a ring means. It takes a 28px band at the top. 4. Don't change, in components/ui/tally.tsx: - Every dot's position is a closed-form function of time (a cubic from where it was to its slot), so it lands exactly, a new update starts from where each dot is, and the loop stops once nothing moves. - A cluster fills its hex spiral from the middle out, so it grows and shrinks at its rim and stays round; a shrinking cluster hands its outermost dots to the nearest growing cluster first. - Dots keep their identity and `per` stays fixed once picked: a unit that moved between categories flies between clusters and is never swapped for a new dot. Only a change in the total brings dots in from the edge or sends them out through it. - Each cluster draws in its item's color, read from a swatch beside its label, and a dot crossing to another cluster shades from the old color to the new one as it flies. - Under reduced motion nothing flies: the chart crossfades to the new numbers and counts jump. Its timing is all in the TIMING block at the top of that file. Docs: https://keyframeui.com/components/tally.md
Installation
Add the component on its own with the CLI, or copy the file in by hand.
The CLI writes components/ui/tally.tsx and installs clsx and tailwind-merge. It needs the @keyframeui registry in components.json; add it once per project.
npx shadcn@latest add @keyframeui/tallyInstall the dependencies
npm i clsx tailwind-mergeAdd the cn helper
Skip this if you already use shadcn/ui.
lib/utils.tsimport { clsx, type ClassValue } from "clsx"; import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }Copy the source into your project
components/ui/tally.tsx"use client"; import * as React from "react"; import { cn } from "@/lib/utils"; /** * Keep: * - Every dot's position is a closed-form function of time (a cubic from where it was to its slot), * so it lands exactly, a new update starts from where each dot is, and the loop stops once nothing * moves. * - A cluster fills its hex spiral from the middle out, so it grows and shrinks at its rim and stays * round; a shrinking cluster hands its outermost dots to the nearest growing cluster first. * - Dots keep their identity and `per` stays fixed once picked: a unit that moved between categories * flies between clusters and is never swapped for a new dot. Only a change in the total brings dots * in from the edge or sends them out through it. * - Each cluster draws in its item's color, read from a swatch beside its label, and a dot crossing * to another cluster shades from the old color to the new one as it flies. * - Under reduced motion nothing flies: the chart crossfades to the new numbers and counts jump. */ const TIMING = { /** Dots gathering along the edge before the first one leaves, on the way in, in seconds. */ gather: 0.45, /** A dot's flight, in seconds (the `duration` prop): in from the edge, or across to another cluster. Each varies ±25%. */ flight: 1.1, /** Seconds between the first launch and the last on the way in (the `stagger` prop). */ spread: 0.9, /** Seconds between the first launch and the last when the numbers change. */ moveSpread: 0.5, /** Longest a dot waits on the edge before it leaves, in seconds. */ lead: 0.4, /** A waiting dot growing in on the edge, in seconds. */ pop: 0.18, /** Share of its flight time a trail lags behind its dot (the `trailLength` prop). */ trail: 0.55, /** A dot sliding to a new place in its own cluster when the chart relays out, in seconds. */ shift: 0.6, /** Clusters other than the pointed one dimming, in seconds. */ dim: 0.2, /** The labels dimming with them. */ labelDim: "duration-200", /** A label under a `free` cluster sliding as the cluster grows or shrinks. */ labelSlide: "transform 0.6s cubic-bezier(0.65, 0, 0.35, 1)", /** Under reduced motion, the crossfade that replaces every flight, in seconds. */ fade: 0.3, } as const; /* ───────────────────────────────────────────────────────── * TALLY STORYBOARD * * rest one round cluster per category, every dot a * fixed amount (`per`), packed on a hex lattice * from the middle out; units you mark `hollow` * (failed, refunded) are rings among the dots. * Labels sit under the clusters with exact counts * gather the first time a quarter of it scrolls into view, * dots pop onto the box's edge, up to three deep, * each behind the cluster it's bound for * flight 0.45s in they leave over 0.9s, each bowing in on * a cubic for about 1.1s and growing from 62% to * full size; its trail is its own path, lagging 55% * of the flight, reeling in once it lands * move new numbers: each shrinking cluster gives its * outermost dots to the nearest growing one, which * takes them at its rim. They fly across on bowed * curves, launched over 0.5s. Counts step as dots * leave and land, and read exact when it's over * total a bigger total brings the extra dots in from the * edge; a smaller one sends dots out through it * relay when clusters no longer fit (one grew past its * room), the whole lattice tightens and dots slide * to their new places in 0.6s * point the pointer over a cluster or its label dims the * others to 22% in 0.2s; a tap does the same on touch * resize the layout is laid again and snaps; nothing replays * sleep off screen or in a hidden tab nothing draws; * flights finish on time while hidden * reduced no flights: the chart crossfades to the new numbers * in 0.3s and counts jump * ───────────────────────────────────────────────────────── */ const TALLY = { targetDots: 600, // dots in all, when `per` is picked for you headroom: 1.6, // area a cluster can grow into at full dot size, as a multiple of its first size minCell: 132, // px, narrowest column in a row before clusters wrap onto another row labelBand: 46, // px under each row of clusters for its labels legendBand: 28, // px above the clusters for the legend margin: 8, // px between a cluster and the edge of its room labelGap: 8, // px between a `free` cluster and its label rings: 44, // hex rings in the spiral a cluster fills rim: 0.55, // pitch, noise on the spiral order, so a rim fills unevenly instead of as a perfect hexagon jitter: 1.6, // rad, spread of a dot's start around the line from the middle through its cluster band: 3, // rows deep the edge band can stack swirl: [0.1, 0.32], // sideways bow of a long flight, share of its length swirlShort: [0.04, 0.14], // and of a short slide launch: 0.3, // share of its length a flight heads straight out before it bends land: 0.22, // share of its length a flight comes straight in at the end flightSize: 0.62, // a dot's size mid-flight, share of its landed size ring: 1, // px, stroke of a hollow ring trailWidth: 0.6, // px trailAlpha: 0.32, dim: 0.22, // opacity of the clusters you're not pointing at tints: 8, // color steps a dot crossing between clusters shades through maxDpr: 2, } as const; const REDUCED = "(prefers-reduced-motion: reduce)"; const subscribeReduced = (onChange: () => void) => { const query = window.matchMedia(REDUCED); query.addEventListener("change", onChange); return () => query.removeEventListener("change", onChange); }; /** Reduced motion from the media query, false on the server and in the hydration render. */ function useReduced() { return React.useSyncExternalStore( subscribeReduced, () => window.matchMedia(REDUCED).matches, () => false, ); } const clamp01 = (t: number) => (t < 0 ? 0 : t > 1 ? 1 : t); /** In-out cubic: a dot eases off where it was and settles into its slot without a snap. */ const ease = (u: number) => (u < 0.5 ? 4 * u * u * u : 1 - (-2 * u + 2) ** 3 / 2); /** A seeded generator, so a cluster always marks the same dots hollow. */ function seeded(key: string) { let h = 2166136261; for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 16777619); return () => { h = (h + 0x6d2b79f5) | 0; let t = Math.imul(h ^ (h >>> 15), 1 | h); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } /** Point on the cubic `c` (x0 y0 x1 y1 x2 y2 x3 y3) at parameter t, written into `out`. */ function at(c: Float64Array, t: number, out: Float64Array) { const m = 1 - t; const a = m * m * m; const b = 3 * m * m * t; const d = 3 * m * t * t; const e = t * t * t; out[0] = a * c[0] + b * c[2] + d * c[4] + e * c[6]; out[1] = a * c[1] + b * c[3] + d * c[5] + e * c[7]; } /** Adds the piece of cubic `c` between parameters a and b to `path` (de Casteljau, twice). */ function addPiece(path: Path2D, c: Float64Array, a: number, b: number) { const lerp = (p: number, q: number, t: number) => p + (q - p) * t; const q0x = lerp(c[0], c[2], b), q0y = lerp(c[1], c[3], b); const q1x = lerp(c[2], c[4], b), q1y = lerp(c[3], c[5], b); const q2x = lerp(c[4], c[6], b), q2y = lerp(c[5], c[7], b); const r0x = lerp(q0x, q1x, b), r0y = lerp(q0y, q1y, b); const r1x = lerp(q1x, q2x, b), r1y = lerp(q1y, q2y, b); const sx = lerp(r0x, r1x, b), sy = lerp(r0y, r1y, b); const t = b > 0 ? a / b : 0; const u0x = lerp(c[0], q0x, t), u0y = lerp(c[1], q0y, t); const u1x = lerp(q0x, r0x, t), u1y = lerp(q0y, r0y, t); const u2x = lerp(r0x, sx, t), u2y = lerp(r0y, sy, t); const v0x = lerp(u0x, u1x, t), v0y = lerp(u0y, u1y, t); const v1x = lerp(u1x, u2x, t), v1y = lerp(u1y, u2y, t); path.moveTo(lerp(v0x, v1x, t), lerp(v0y, v1y, t)); path.bezierCurveTo(v1x, v1y, u2x, u2y, sx, sy); } /* ── Spiral ───────────────────────────────────────────── */ // The order a cluster fills its lattice: hex points sorted by distance from the middle, with a // little fixed noise so the rim grows unevenly. In pitch units; built once. let spiralXY: Float32Array | null = null; let spiralReach: Float32Array | null = null; // farthest point among the first i + 1, for fitting function spiral() { if (spiralXY && spiralReach) return { xy: spiralXY, reach: spiralReach }; const K = TALLY.rings; const pts: [number, number, number, number][] = []; for (let q = -K; q <= K; q++) { for (let r = Math.max(-K, -q - K); r <= Math.min(K, -q + K); r++) { const x = q + r / 2; const y = (r * Math.sqrt(3)) / 2; const d = Math.hypot(x, y); const noise = (Math.imul((q * 73856093) ^ (r * 19349663), 2654435761) >>> 0) / 4294967296; pts.push([x, y, d, d + noise * TALLY.rim]); } } pts.sort((a, b) => a[3] - b[3]); spiralXY = new Float32Array(pts.length * 2); spiralReach = new Float32Array(pts.length); let far = 0; pts.forEach(([x, y, d], i) => { spiralXY![i * 2] = x; spiralXY![i * 2 + 1] = y; far = Math.max(far, d); spiralReach![i] = far; }); return { xy: spiralXY, reach: spiralReach }; } /** How many dots fit within `radius` pitches of the middle, dot edges included. */ function capacity(radius: number) { const { reach } = spiral(); let lo = 0; let hi = reach.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (reach[mid] + 0.5 <= radius) lo = mid + 1; else hi = mid; } return lo; } /** The smallest of 1, 2, 2.5, 5 × 10^k at or above `x`, so the legend reads cleanly. */ function niceUp(x: number) { if (!(x > 0)) return 1; const k = Math.pow(10, Math.floor(Math.log10(x))); for (const m of [1, 2, 2.5, 5, 10]) if (m * k >= x * 0.9999) return m * k; return 10 * k; } /** Item colors when an item doesn't set one, by position: vivid on white and on zinc-950 alike. */ const PALETTE = [ "text-[#ff5a1f] dark:text-[#ff7a45]", // hot orange "text-[#7c3aed] dark:text-[#a78bfa]", // electric violet "text-[#00b25d] dark:text-[#34d399]", // vivid green "text-[#ff2d87] dark:text-[#ff5ca8]", // hot pink "text-[#2f45e8] dark:text-[#8b98ff]", // electric blue "text-[#f59e0b] dark:text-[#fbbf24]", // amber ] as const; type RGB = [number, number, number]; let parser: CanvasRenderingContext2D | null = null; /** Any CSS color as RGB, read back from a 1px canvas so oklch and friends work too. */ function rgbOf(css: string): RGB { parser ??= document.createElement("canvas").getContext("2d", { willReadFrequently: true }); if (!parser) return [47, 69, 232]; parser.clearRect(0, 0, 1, 1); parser.fillStyle = "#2f45e8"; parser.fillStyle = css; parser.fillRect(0, 0, 1, 1); const [r, g, b] = parser.getImageData(0, 0, 1, 1).data; return [r, g, b]; } export interface TallyItem { /** Stable id. The same id keeps its cluster, its dots and its place across updates. */ id: string; /** Shown under the cluster. */ label: string; /** The amount; the cluster holds `value / per` dots, rounded. */ value: number; /** How much of `value` is drawn as hollow rings instead of solid dots, like failed requests. */ hollow?: number; /** For `layout="free"`: where the cluster sits across the box, 0–1. */ x?: number; /** For `layout="free"`: where it sits down the box, 0–1. */ y?: number; /** A `text-*` color for this cluster's dots and its label's swatch. Without it, the next color of the built-in palette. */ dotClassName?: string; } type Layout = "row" | "free"; type Options = { per: number | undefined; layout: Layout; legend: boolean; dotSize: number; gap: number; trails: boolean; flight: number; spread: number; trail: number; reduced: boolean; }; type Cluster = { id: string; item: TallyItem; n: number; // dots it holds once settled h: number; // of which hollow cx: number; cy: number; room: number; // px, the radius it may fill reach: number; // px, the radius it does fill once settled dots: Dot[]; // in spiral order: dots[i] rests on spiral point i keys: Float32Array | null; // per spiral point, which ones turn hollow first hollow: Uint8Array; alpha: number; alphaFrom: number; alphaTo: number; alphaT0: number; rgb: RGB; // its color css: string; }; type Dot = { home: Cluster | null; // the cluster it belongs to; null while it leaves the box from: Cluster | null; // a cluster it left that still counts it until it launches index: number; x: number; // where it rests: its slot, or the point past the edge it leaves for y: number; c: Float64Array | null; // its flight, while it has one appear: number; t0: number; dur: number; landed: boolean; // flight over; the trail may still be reeling in stay: boolean; // sliding inside its own cluster, so it still counts there intro: boolean; // flying in with the entrance; counts already show it tint: Cluster | null; // the cluster whose color it shades from while it flies kind: number; // for a dot leaving the box }; const SOLID = 2; const HOLLOW = 1; type TallySnapshot = { /** Units per dot, once picked. */ per: number | null; /** Each label's anchor (x, top) and width, in px, once laid out. */ labels: Record<string, [number, number, number]> | null; /** Each cluster's count while dots are moving; null when every count is exact. */ counts: Record<string, number> | null; /** The cluster the pointer is on. */ active: string | null; layout: Layout; }; const SERVER_SNAPSHOT: TallySnapshot = { per: null, labels: null, counts: null, active: null, layout: "row" }; function createTally() { let root: HTMLElement | null = null; let canvas: HTMLCanvasElement | null = null; let ctx: CanvasRenderingContext2D | null = null; let options: Options = { per: undefined, layout: "row", legend: true, dotSize: 6, gap: 1.5, trails: true, flight: TIMING.flight, spread: TIMING.spread, trail: TIMING.trail, reduced: false, }; let onSettle: (() => void) | null = null; let width = 0; let height = 0; let dpr = 1; let pitch = 7.5; let radius = 3; let per: number | null = null; let items: TallyItem[] = []; let signature = ""; let clusters: Cluster[] = []; let flying: Dot[] = []; let counting = false; let cache: HTMLCanvasElement | null = null; let cacheDirty = true; let prev: HTMLCanvasElement | null = null; let fadeT0 = -1; let raf = 0; let inView = false; let pageVisible = true; let played = false; let settling = false; let active: string | null = null; const random = seeded("tally"); const point = new Float64Array(2); const cleanups: (() => void)[] = []; let snapshot: TallySnapshot = { ...SERVER_SNAPSHOT }; const listeners = new Set<() => void>(); const publish = (patch: Partial<TallySnapshot>) => { snapshot = { ...snapshot, ...patch }; listeners.forEach((fn) => fn()); }; const now = () => performance.now() / 1000; const awake = () => inView && pageVisible; const vary = (dur: number, by = 0.25) => dur * (1 - by + random() * by * 2); /** Each cluster's color, from the swatch beside its label. */ function readTints() { for (const c of clusters) { const swatch = root?.querySelector<HTMLElement>(`[data-tally-swatch="${CSS.escape(c.id)}"]`); if (!swatch) continue; c.rgb = rgbOf(getComputedStyle(swatch).color); c.css = `rgb(${c.rgb.join(", ")})`; } cacheDirty = true; } function readColors() { readTints(); draw(); } /** A dot's color `mix` of the way from one cluster's color to another's, in a few steps so dots batch. */ function tint(from: Cluster, to: Cluster, mix: number) { if (from === to || mix >= 1) return to.css; if (mix <= 0) return from.css; const k = Math.round(mix * TALLY.tints) / TALLY.tints; const a = from.rgb; const b = to.rgb; return `rgb(${Math.round(a[0] + (b[0] - a[0]) * k)}, ${Math.round(a[1] + (b[1] - a[1]) * k)}, ${Math.round(a[2] + (b[2] - a[2]) * k)})`; } function newCluster(item: TallyItem): Cluster { return { id: item.id, item, n: 0, h: 0, cx: width / 2, cy: height / 2, room: 0, reach: 0, dots: [], keys: null, hollow: new Uint8Array(0), alpha: 1, alphaFrom: 1, alphaTo: 1, alphaT0: -1, rgb: [47, 69, 232], css: "rgb(47, 69, 232)", }; } /** Each cluster's middle and the room it has, from the layout. */ function rooms() { const N = clusters.length; if (!N || !width || !height) return; const top = options.legend ? TALLY.legendBand : 0; const labels: Record<string, [number, number, number]> = {}; if (options.layout === "row") { let cols = Math.max(1, Math.min(N, Math.floor(width / TALLY.minCell))); const rows = Math.ceil(N / cols); cols = Math.ceil(N / rows); const cellW = width / cols; const cellH = (height - top) / rows; const areaH = Math.max(0, cellH - TALLY.labelBand); clusters.forEach((c, k) => { const row = Math.floor(k / cols); const col = k % cols; const inRow = Math.min(cols, N - row * cols); const x0 = ((cols - inRow) * cellW) / 2 + col * cellW; const y0 = top + row * cellH; c.cx = x0 + cellW / 2; c.cy = y0 + areaH / 2; c.room = Math.max(0, Math.min(cellW, areaH) / 2 - TALLY.margin); labels[c.id] = [c.cx, y0 + areaH + 2, cellW - 8]; }); } else { const areaH = Math.max(0, height - top - TALLY.labelBand); clusters.forEach((c, k) => { c.cx = clamp01(c.item.x ?? (k + 0.5) / N) * width; c.cy = top + clamp01(c.item.y ?? 0.5) * areaH; }); clusters.forEach((c) => { let room = Math.min(c.cx, width - c.cx, c.cy - top + TALLY.margin, top + areaH - c.cy + TALLY.margin); for (const o of clusters) if (o !== c) room = Math.min(room, Math.hypot(o.cx - c.cx, o.cy - c.cy) / 2); c.room = Math.max(0, room - TALLY.margin); }); } return labels; } /** Picks units per dot once: about `targetDots` in all, with room for each cluster to grow. */ function pickPer() { if (options.per && options.per > 0) { per = options.per; return; } if (per !== null) return; const base = options.dotSize + options.gap; let total = 0; let need = 0; for (const c of clusters) { const v = Math.max(0, c.item.value); total += v; const cap = capacity(c.room / base); if (v > 0) need = Math.max(need, cap > 0 ? (v * TALLY.headroom) / cap : Infinity); } if (!total) return; per = niceUp(Math.max(total / TALLY.targetDots, Number.isFinite(need) ? need : total)); } /** The pitch every cluster fits at, and each cluster's settled radius and label. */ function fit(labels: Record<string, [number, number, number]>) { const { reach } = spiral(); const base = Math.max(1, options.dotSize + options.gap); pitch = base; for (const c of clusters) if (c.n > 0) pitch = Math.min(pitch, c.room / (reach[c.n - 1] + 0.5)); pitch = Math.max(1.5, pitch); radius = (options.dotSize / 2) * (pitch / base); for (const c of clusters) { c.reach = c.n > 0 ? (reach[c.n - 1] + 0.5) * pitch : 0; if (options.layout === "free") labels[c.id] = [c.cx, c.cy + c.reach + TALLY.labelGap, Math.max(96, c.reach * 2 + 32)]; } publish({ labels, per, layout: options.layout }); } function counts() { if (!per) return; const max = spiral().reach.length; for (const c of clusters) { c.n = Math.min(max, Math.max(0, Math.round(c.item.value / per))); c.h = Math.min(c.n, Math.max(0, Math.round((c.item.hollow ?? 0) / per))); if (!c.keys) { const r = seeded(`tally:${c.id}`); c.keys = Float32Array.from({ length: max }, () => r()); } // The h points with the lowest keys among the first n are hollow. const keys = c.keys; const order = Array.from({ length: c.n }, (_, i) => i).sort((a, b) => keys[a] - keys[b]); c.hollow = new Uint8Array(c.n); for (let i = 0; i < c.h; i++) c.hollow[order[i]] = 1; } } function slot(c: Cluster, i: number): [number, number] { const { xy } = spiral(); return [c.cx + xy[i * 2] * pitch, c.cy + xy[i * 2 + 1] * pitch]; } /** Where a dot is at time t. */ function where(d: Dot, t: number) { if (d.c && t < d.t0 + d.dur) at(d.c, t <= d.t0 ? 0 : ease((t - d.t0) / d.dur), point); else { point[0] = d.x; point[1] = d.y; } return point; } /** * The point on the plot's edge at `angle` from its middle, `inset` px in (negative: past it). * The plot leaves out the legend above and, in a row, the labels below, so dots never wait on * top of text. */ function edgeAt(angle: number, inset: number, plot = true): [number, number] { const top = plot && options.legend ? TALLY.legendBand : 0; const bottom = height - (plot && options.layout === "row" ? TALLY.labelBand : 0); const mx = width / 2; const my = (top + bottom) / 2; const ux = Math.cos(angle); const uy = Math.sin(angle); const hw = width / 2 - inset; const hh = Math.max(0, (bottom - top) / 2 - inset); const t = Math.min(ux ? hw / Math.abs(ux) : Infinity, uy ? hh / Math.abs(uy) : Infinity); return [mx + ux * t, my + uy * t]; } /** The angle from the plot's middle to (x, y). */ function angleTo(x: number, y: number) { const top = options.legend ? TALLY.legendBand : 0; const bottom = height - (options.layout === "row" ? TALLY.labelBand : 0); return Math.atan2(y - (top + bottom) / 2, x - width / 2); } /** A cubic from (x0, y0) to (x3, y3): straight out, a sideways bow, straight in. */ function curve(x0: number, y0: number, x3: number, y3: number, bowRange: readonly [number, number]) { const dx = x3 - x0; const dy = y3 - y0; const d = Math.hypot(dx, dy) || 1; const ux = dx / d; const uy = dy / d; const bow = d * (bowRange[0] + random() * (bowRange[1] - bowRange[0])); // Every dot bows the same way, so a burst turns like one swirl instead of crossing itself. const nx = -uy * bow; const ny = ux * bow; return Float64Array.of( x0, y0, x0 + ux * d * TALLY.launch + nx, y0 + uy * d * TALLY.launch + ny, x3 - ux * d * TALLY.land + nx * 0.35, y3 - uy * d * TALLY.land + ny * 0.35, x3, y3, ); } function fly(d: Dot, x: number, y: number, bow: readonly [number, number], t0: number, dur: number, appear: number) { const [sx, sy] = where(d, Math.max(appear, now())); d.c = curve(sx, sy, x, y, bow); d.x = x; d.y = y; d.t0 = t0; d.dur = dur; d.appear = appear; d.landed = false; if (!flying.includes(d)) flying.push(d); } /** Every cluster holds exactly its dots, each resting on its slot. Nothing flies. */ function snap() { for (const c of clusters) { if (c.dots.length > c.n) c.dots.length = c.n; while (c.dots.length < c.n) c.dots.push(blank(c, c.dots.length)); c.dots.forEach((d, i) => { const [x, y] = slot(c, i); Object.assign(d, { home: c, from: null, index: i, x, y, c: null, landed: true, stay: false, intro: false, tint: c }); }); } flying = []; counting = false; cacheDirty = true; if (snapshot.counts) publish({ counts: null }); } function blank(c: Cluster, index: number): Dot { const [x, y] = slot(c, index); return { home: c, from: null, index, x, y, c: null, appear: 0, t0: 0, dur: 0, landed: true, stay: false, intro: false, tint: c, kind: SOLID }; } /** A dot for `c` coming in from the edge behind it. */ function arrive(c: Cluster, t0: number, dur: number, appear: number) { const index = c.dots.length; const d = blank(c, index); const angle = angleTo(c.cx, c.cy) + (random() - 0.5) * TALLY.jitter; const [ex, ey] = edgeAt(angle, radius + Math.floor(random() * TALLY.band) * pitch * 0.9); d.x = ex; d.y = ey; c.dots.push(d); const [x, y] = slot(c, index); d.c = null; fly(d, x, y, TALLY.swirl, t0, dur, appear); } function play() { played = true; snap(); if (!clusters.some((c) => c.n)) return; if (options.reduced) { crossfade(false); return; } const t = now(); for (const c of clusters) { const n = c.n; c.dots = []; for (let i = 0; i < n; i++) { const t0 = t + TIMING.gather + random() * options.spread; arrive(c, t0, vary(options.flight), Math.max(t + random() * TIMING.gather, t0 - TIMING.lead * (0.3 + random() * 0.7))); c.dots[c.dots.length - 1].intro = true; } } settling = true; wake(); } /** New numbers, a new layout or new items: move what moved, from where it is now. */ function apply(removed: Cluster[]) { if (!width || !height) return; const labels = rooms() ?? {}; pickPer(); if (!per) { publish({ labels, per: null, layout: options.layout }); return; } counts(); fit(labels); if (!played) { snap(); draw(); return; } if (options.reduced) { keepCopy(); snap(); crossfade(true); return; } const t = now(); // What each shrinking or removed cluster gives up: its outermost dots first. const pool: { from: Cluster; dots: Dot[] }[] = []; for (const c of clusters) if (c.dots.length > c.n) pool.push({ from: c, dots: c.dots.splice(c.n).reverse() }); for (const c of removed) pool.push({ from: c, dots: c.dots.splice(0).reverse() }); const needs = clusters.filter((c) => c.dots.length < c.n); const pairs: [number, { from: Cluster; dots: Dot[] }, Cluster][] = []; for (const p of pool) for (const c of needs) pairs.push([Math.hypot(p.from.cx - c.cx, p.from.cy - c.cy), p, c]); pairs.sort((a, b) => a[0] - b[0]); const counted = (d: Dot) => !d.c || d.landed || d.stay || d.intro; let moved = 0; for (const [, p, c] of pairs) { while (p.dots.length && c.dots.length < c.n) { const d = p.dots.shift()!; if (counted(d)) d.from = p.from; d.tint = p.from; d.home = c; d.index = c.dots.length; d.stay = false; d.intro = false; c.dots.push(d); const [x, y] = slot(c, d.index); fly(d, x, y, TALLY.swirl, t + random() * TIMING.moveSpread, vary(options.flight), t); moved++; } } // A bigger total comes in from the edge; a smaller one leaves through it. for (const c of needs) { while (c.dots.length < c.n) { arrive(c, t + TIMING.lead * 0.5 + random() * TIMING.moveSpread, vary(options.flight), t + random() * TIMING.lead * 0.5); moved++; } } for (const p of pool) { for (const d of p.dots) { const [x, y] = where(d, t); if (counted(d)) d.from = p.from; d.kind = p.from.hollow[d.index] ? HOLLOW : SOLID; d.tint = p.from; d.home = null; d.stay = false; d.intro = false; const angle = angleTo(x, y) + (random() - 0.5) * TALLY.jitter * 0.4; const [ex, ey] = edgeAt(angle, -radius * 3, false); fly(d, ex, ey, TALLY.swirlShort, t + random() * TIMING.moveSpread, vary(options.flight), t); moved++; } } // Dots whose slot moved (a new layout, a tighter lattice) slide to it. for (const c of clusters) { c.dots.forEach((d, i) => { d.index = i; const [x, y] = slot(c, i); if (Math.abs(d.x - x) < 0.01 && Math.abs(d.y - y) < 0.01) return; const resting = !d.c || d.landed; d.stay = resting || d.stay; if (resting) d.tint = c; fly(d, x, y, TALLY.swirlShort, resting ? t : Math.max(t, d.t0), resting ? vary(TIMING.shift, 0.15) : vary(options.flight), t); }); } cacheDirty = true; counting = moved > 0; settling = true; wake(); } function keepCopy() { if (!canvas || !cache) return; prev ??= document.createElement("canvas"); prev.width = canvas.width; prev.height = canvas.height; prev.getContext("2d")?.drawImage(cache, 0, 0); } function crossfade(withPrev: boolean) { if (!withPrev) prev = null; fadeT0 = now(); settling = true; wake(); } function setActive(id: string | null) { if (id === active) return; active = id; const t = now(); for (const c of clusters) { c.alphaFrom = alphaOf(c, t); c.alphaTo = id === null || c.id === id ? 1 : TALLY.dim; c.alphaT0 = t; } publish({ active: id }); wake(); } function alphaOf(c: Cluster, t: number) { if (c.alphaT0 < 0) return c.alphaTo; const u = options.reduced ? 1 : clamp01((t - c.alphaT0) / TIMING.dim); c.alpha = c.alphaFrom + (c.alphaTo - c.alphaFrom) * ease(u); if (u >= 1) c.alphaT0 = -1; return c.alpha; } function drawCache(t: number) { cacheDirty = false; if (!canvas) return; cache ??= document.createElement("canvas"); if (cache.width !== canvas.width || cache.height !== canvas.height) { cache.width = canvas.width; cache.height = canvas.height; } const c = cache.getContext("2d"); if (!c) return; c.setTransform(1, 0, 0, 1, 0, 0); c.clearRect(0, 0, cache.width, cache.height); // Nothing shows before the entrance: the dots arrive with it. if (!played) return; c.setTransform(dpr, 0, 0, dpr, 0, 0); c.lineWidth = TALLY.ring; const r = radius; const rr = Math.max(0.5, r - TALLY.ring / 2); for (const cl of clusters) { const fill = new Path2D(); const rings = new Path2D(); cl.dots.forEach((d, i) => { if (d.c && !d.landed) return; if (cl.hollow[i]) { rings.moveTo(d.x + rr, d.y); rings.arc(d.x, d.y, rr, 0, Math.PI * 2); } else { fill.moveTo(d.x + r, d.y); fill.arc(d.x, d.y, r, 0, Math.PI * 2); } }); c.globalAlpha = alphaOf(cl, t); c.fillStyle = cl.css; c.strokeStyle = cl.css; c.fill(fill); c.stroke(rings); } c.globalAlpha = 1; } function frame() { raf = 0; draw(); } function draw() { if (!ctx || !canvas) return; const t = now(); const span = options.trails ? options.trail : 0; for (const d of flying) { if (!d.landed && t >= d.t0 + d.dur) { d.landed = true; d.stay = false; d.intro = false; d.from = null; if (d.home) cacheDirty = true; } } flying = flying.filter((d) => { if (t < d.t0 + d.dur * (1 + span)) return true; d.c = null; return false; }); let tweening = false; for (const c of clusters) { if (c.alphaT0 >= 0) { tweening = true; cacheDirty = true; } } ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); if (cacheDirty) drawCache(t); let fading = false; if (cache) { if (fadeT0 >= 0) { const a = clamp01((t - fadeT0) / TIMING.fade); if (prev) { ctx.globalAlpha = 1 - a; ctx.drawImage(prev, 0, 0); } ctx.globalAlpha = a; ctx.drawImage(cache, 0, 0); ctx.globalAlpha = 1; if (a >= 1) { fadeT0 = -1; prev = null; } else fading = true; } else ctx.drawImage(cache, 0, 0); } ctx.setTransform(dpr, 0, 0, dpr, 0, 0); // Moving dots and their trails, batched by color and by the opacity of the cluster they're bound for. type Group = { css: string; alpha: number; fill: Path2D; rings: Path2D; trail: Path2D; traced: boolean }; const groups = new Map<string, Group>(); for (const d of flying) { if (t < d.appear || !d.c) continue; const u = (t - d.t0) / d.dur; const head = u <= 0 ? 0 : u >= 1 ? 1 : ease(u); const to = d.home ?? d.tint; const from = d.tint ?? to; const css = from && to ? tint(from, to, head) : "currentColor"; const alpha = d.home ? Math.round(alphaOf(d.home, t) * 20) / 20 : 1; const key = `${css}|${alpha}`; let g = groups.get(key); if (!g) groups.set(key, (g = { css, alpha, fill: new Path2D(), rings: new Path2D(), trail: new Path2D(), traced: false })); if (span > 0 && u > 0) { const tail = ease(clamp01(u - span)); if (head - tail > 0.001) { addPiece(g.trail, d.c, tail, head); g.traced = true; } } if (d.landed) continue; at(d.c, head, point); const grow = u <= 0 ? clamp01((t - d.appear) / TIMING.pop) : 1; const leaving = !d.home; const scale = d.stay ? 1 : leaving ? 1 - (1 - TALLY.flightSize) * head : u <= 0 ? 1 : TALLY.flightSize + (1 - TALLY.flightSize) * head; const r = radius * scale * grow; if (r < 0.3) continue; const hollow = d.home ? d.home.hollow[d.index] : d.kind === HOLLOW; if (hollow) { const rr = Math.max(0.4, r - TALLY.ring / 2); g.rings.moveTo(point[0] + rr, point[1]); g.rings.arc(point[0], point[1], rr, 0, Math.PI * 2); } else { g.fill.moveTo(point[0] + r, point[1]); g.fill.arc(point[0], point[1], r, 0, Math.PI * 2); } } for (const g of groups.values()) { ctx.fillStyle = g.css; ctx.strokeStyle = g.css; if (g.traced) { ctx.globalAlpha = TALLY.trailAlpha * g.alpha; ctx.lineWidth = TALLY.trailWidth; ctx.stroke(g.trail); } ctx.globalAlpha = g.alpha; ctx.lineWidth = TALLY.ring; ctx.fill(g.fill); ctx.stroke(g.rings); } ctx.globalAlpha = 1; if (counting) writeCounts(t); const moving = flying.some((d) => !d.landed); if (settling && !moving && !fading) { settling = false; onSettle?.(); } // Called outside the loop too (a color change), so never start a second loop. if (!raf && (flying.length || fading || tweening) && awake()) raf = requestAnimationFrame(frame); } /** Counts while dots move: a dot counts where it rests, and where it left until it launches. */ function writeCounts(t: number) { if (!per) return; let busy = false; const n: Record<string, number> = {}; for (const c of clusters) { let k = 0; for (const d of c.dots) { if (!d.c || d.landed || d.stay || d.intro) k++; else busy = true; } n[c.id] = k; } for (const d of flying) { if (d.from && !d.landed && t < d.t0 && d.from.id in n) n[d.from.id]++; if (!d.landed) busy = true; } if (!busy) { counting = false; publish({ counts: null }); return; } const next: Record<string, number> = {}; let changed = !snapshot.counts; for (const c of clusters) { next[c.id] = n[c.id] * per; if (!changed && snapshot.counts?.[c.id] !== next[c.id]) changed = true; } if (changed) publish({ counts: next }); } function wake() { if (raf || !awake() || !ctx) return; raf = requestAnimationFrame(frame); } function layout() { if (!root || !canvas) return; const w = root.clientWidth; const h = root.clientHeight; const nextDpr = Math.min(window.devicePixelRatio || 1, TALLY.maxDpr); if (w === width && h === height && nextDpr === dpr) return; width = w; height = h; dpr = nextDpr; canvas.width = Math.max(1, Math.round(w * dpr)); canvas.height = Math.max(1, Math.round(h * dpr)); relay(); } /** Lays everything out again and snaps to it; an entrance that hasn't played waits. */ function relay() { if (!width || !height) return; const labels = rooms() ?? {}; pickPer(); if (per) { counts(); fit(labels); } else publish({ labels, per: null, layout: options.layout }); prev = null; fadeT0 = -1; // A resize mid-flight snaps to the settled chart, and still reports it as settled. const interrupted = played && settling; settling = false; snap(); draw(); if (interrupted) onSettle?.(); if (!played && awake()) play(); } function setAwake() { if (awake()) { if (!played && width && per) play(); wake(); } else { cancelAnimationFrame(raf); raf = 0; } } /** The cluster under (x, y), if any. */ function hit(x: number, y: number) { let best: Cluster | null = null; let bestD = Infinity; for (const c of clusters) { if (!c.n) continue; const d = Math.hypot(x - c.cx, y - c.cy); if (d <= c.reach + pitch * 1.5 && d < bestD) { best = c; bestD = d; } } return best?.id ?? null; } return { connect(el: { root: HTMLElement; canvas: HTMLCanvasElement }) { root = el.root; canvas = el.canvas; ctx = canvas.getContext("2d"); width = 0; pageVisible = document.visibilityState === "visible"; readColors(); layout(); const resize = new ResizeObserver(() => layout()); resize.observe(root); const io = new IntersectionObserver( ([entry]) => { inView = entry.isIntersecting; setAwake(); }, { threshold: 0.25 }, ); io.observe(root); const visibility = () => { pageVisible = document.visibilityState === "visible"; setAwake(); }; document.addEventListener("visibilitychange", visibility); const scheme = window.matchMedia("(prefers-color-scheme: dark)"); scheme.addEventListener("change", readColors); const themeAttrs = new MutationObserver(readColors); themeAttrs.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-theme", "style"] }); cleanups.push( () => resize.disconnect(), () => io.disconnect(), () => document.removeEventListener("visibilitychange", visibility), () => scheme.removeEventListener("change", readColors), () => themeAttrs.disconnect(), ); return () => { cancelAnimationFrame(raf); raf = 0; flying = []; inView = false; cleanups.splice(0).forEach((fn) => fn()); root = canvas = null; ctx = null; }; }, setOptions(next: Options) { const relayout = next.dotSize !== options.dotSize || next.gap !== options.gap || next.legend !== options.legend || next.reduced !== options.reduced; const reshape = next.layout !== options.layout || next.per !== options.per; if (next.per !== options.per) per = null; options = next; if (relayout) relay(); else if (reshape) apply([]); }, setItems(next: TallyItem[]) { const sig = next.map((i) => `${i.id}\u0001${i.value}\u0001${i.hollow ?? 0}\u0001${i.x ?? ""}\u0001${i.y ?? ""}\u0001${i.label}`).join("\u0002"); if (sig === signature) return; signature = sig; items = next; const old = new Map(clusters.map((c) => [c.id, c])); clusters = items.map((item) => { const c = old.get(item.id) ?? newCluster(item); old.delete(item.id); c.item = item; if (active && c.id !== active) c.alpha = c.alphaTo = TALLY.dim; return c; }); if (active && !clusters.some((c) => c.id === active)) setActive(null); readTints(); apply([...old.values()]); if (!played && awake() && per) play(); }, point(x: number | null, y = 0) { setActive(x === null ? null : hit(x, y)); }, toggle(x: number, y: number) { const id = hit(x, y); setActive(id === active ? null : id); }, activate(id: string | null) { setActive(id); }, setOnSettle(fn: (() => void) | null) { onSettle = fn; }, subscribe(fn: () => void) { listeners.add(fn); return () => { listeners.delete(fn); }; }, getSnapshot: () => snapshot, }; } type Engine = ReturnType<typeof createTally>; const NUMBER = new Intl.NumberFormat("en-US", { maximumFractionDigits: 1 }); const formatNumber = (value: number) => NUMBER.format(value); const getServerSnapshot = () => SERVER_SNAPSHOT; export interface TallyProps extends React.HTMLAttributes<HTMLDivElement> { /** The categories, in order: `{ id, label, value, hollow?, x?, y? }`. Change a value and the dots that moved fly between clusters. */ items: TallyItem[]; /** How much one dot stands for. Picked for you on first layout (about 600 dots in all, rounded to 1, 2, 2.5 or 5 × 10ⁿ), then kept, so a dot means the same thing after every update. */ per?: number; /** `row` puts clusters side by side under one baseline of labels, wrapping onto more rows in a narrow box; `free` puts each one at its item's `x` and `y`, like places on a map. */ layout?: Layout; /** Diameter of a dot, in px. Clusters that would outgrow their room shrink every dot together instead. */ dotSize?: number; /** Space between neighbouring dots, in px. */ gap?: number; /** Draw each dot's path behind it as a hairline that reels in once it lands. */ trails?: boolean; /** Seconds a dot takes to fly: in from the edge, or across to another cluster. Each varies by a quarter either way. */ duration?: number; /** Seconds between the first dot leaving the edge and the last, on the way in. */ stagger?: number; /** How far a trail lags behind its dot, as a share of the flight. */ trailLength?: number; /** Formats the counts under the clusters and in the legend. */ format?: (value: number) => string; /** What a unit is called ("jobs", "votes"), for the legend and screen readers. */ unit?: string; /** What a hollow ring means ("retried"). Adds it to the legend. */ hollowLabel?: string; /** Show the legend above the clusters: what one dot is worth, and what a ring means. */ legend?: boolean; /** Names the chart for screen readers. */ label?: string; /** One `text-*` color for every cluster, for a one-color chart. Items' own `dotClassName` still win; without either, each cluster takes the next palette color. The canvas reads it, so `dark:` variants work. */ dotClassName?: string; /** Classes for each label under a cluster (its color, mostly). */ labelClassName?: string; /** Called each time every dot has landed: after the entrance and after each update. */ onSettle?: () => void; } export function Tally({ items, per, layout = "row", dotSize = 6, gap = 1.5, trails = true, duration = TIMING.flight, stagger = TIMING.spread, trailLength = TIMING.trail, format = formatNumber, unit, hollowLabel, legend = true, label, dotClassName, labelClassName, onSettle, className, children, onPointerMove, onPointerDown, onPointerLeave, ...props }: TallyProps) { const rootRef = React.useRef<HTMLDivElement>(null); const canvasRef = React.useRef<HTMLCanvasElement>(null); const [engine] = React.useState<Engine>(createTally); const reduced = useReduced(); const snap = React.useSyncExternalStore(engine.subscribe, engine.getSnapshot, getServerSnapshot); React.useLayoutEffect(() => { const root = rootRef.current; const canvas = canvasRef.current; if (!root || !canvas) return; return engine.connect({ root, canvas }); }, [engine]); React.useEffect(() => { engine.setOptions({ per: per && per > 0 ? per : undefined, layout, legend, dotSize: Math.max(1.5, dotSize), gap: Math.max(0, gap), trails, flight: Math.max(0.1, duration), spread: Math.max(0, stagger), trail: clamp01(trailLength), reduced, }); }, [engine, per, layout, legend, dotSize, gap, trails, duration, stagger, trailLength, reduced]); React.useEffect(() => { engine.setItems(items); }, [engine, items]); const onSettleRef = React.useRef(onSettle); React.useEffect(() => { onSettleRef.current = onSettle; }); React.useEffect(() => { engine.setOnSettle(() => onSettleRef.current?.()); return () => engine.setOnSettle(null); }, [engine]); const local = (event: React.PointerEvent<HTMLDivElement>) => { const box = event.currentTarget.getBoundingClientRect(); return [event.clientX - box.left, event.clientY - box.top] as const; }; const unitText = unit ? ` ${unit}` : ""; return ( <div ref={rootRef} className={cn("relative isolate", className)} onPointerMove={(event) => { onPointerMove?.(event); // Over a label, the label's own handlers decide. if ((event.target as HTMLElement).closest("[data-tally-label]")) return; if (event.pointerType === "mouse") engine.point(...local(event)); }} onPointerDown={(event) => { onPointerDown?.(event); if (event.pointerType !== "mouse") engine.toggle(...local(event)); }} onPointerLeave={(event) => { onPointerLeave?.(event); if (event.pointerType === "mouse") engine.point(null); }} {...props} > <canvas ref={canvasRef} aria-hidden className="pointer-events-none absolute inset-0 -z-10 size-full" /> {legend && snap.per !== null && ( <div aria-hidden className="absolute top-0 left-0 flex items-center gap-4 font-mono text-[11px] leading-5 text-zinc-500 dark:text-zinc-400"> <span className="flex items-center gap-1.5"> <span className={cn("size-1.5 rounded-full bg-current", dotClassName)} /> {`= ${format(snap.per)}${unitText}`} </span> {hollowLabel && ( <span className="flex items-center gap-1.5"> <span className={cn("size-1.5 rounded-full border border-current", dotClassName)} /> {hollowLabel} </span> )} </div> )} {items.map((item, k) => { // The item's own color, then the chart's, then the palette. The canvas reads it from the swatch. const tone = item.dotClassName ?? dotClassName ?? PALETTE[k % PALETTE.length]; const anchor = snap.labels?.[item.id]; const count = snap.counts?.[item.id]; const style: React.CSSProperties = anchor ? { left: 0, top: 0, width: anchor[2], transform: `translate(${anchor[0] - anchor[2] / 2}px, ${anchor[1]}px)`, transition: snap.layout === "free" && !reduced ? TIMING.labelSlide : undefined, } : { left: `${((k + 0.5) / items.length) * 100}%`, top: `calc(100% - ${TALLY.labelBand - 2}px)`, transform: "translateX(-50%)" }; return ( <div key={item.id} aria-hidden data-tally-label="" onPointerEnter={(event) => event.pointerType === "mouse" && engine.activate(item.id)} onPointerLeave={(event) => event.pointerType === "mouse" && engine.activate(null)} data-dim={snap.active !== null && snap.active !== item.id} className={cn( `absolute flex flex-col items-center px-1 text-center transition-opacity ${TIMING.labelDim} data-[dim=true]:opacity-35`, "text-zinc-950 dark:text-white", labelClassName, )} style={style} > <span className="flex max-w-full items-center gap-1.5"> <span data-tally-swatch={item.id} className={cn("size-2 shrink-0 bg-current", tone)} /> <span className="truncate font-mono text-[11px] leading-4 tracking-wide uppercase opacity-60">{item.label}</span> </span> <span className="text-[15px] leading-6 font-medium tabular-nums">{format(count ?? item.value)}</span> </div> ); })} <ul aria-label={label} aria-live="polite" className="sr-only"> {items.map((item) => ( <li key={item.id}> {`${item.label}: ${format(item.value)}${unitText}`} {item.hollow ? `, ${format(item.hollow)} ${hollowLabel ?? "hollow"}` : ""} </li> ))} </ul> {children} </div> ); }Update the import paths
The file imports
cnfrom@/lib/utils. Change the path if your project uses a different alias.
Examples
Finished sections built with Tally. Each one installs whole, with the component included.
Live Poll
A naming poll where every vote is a dot that flies in from the edge as it's cast, yours included.
"use client";
import * as React from "react";
import { Tally } from "@/components/ui/tally";
const QUESTION = "What should we call the new model?";
const OPTIONS = [
{ id: "juniper", label: "Juniper", votes: 46, color: "text-[#00b25d] dark:text-[#34d399]" },
{ id: "halcyon", label: "Halcyon", votes: 38, color: "text-[#2f45e8] dark:text-[#8b98ff]" },
{ id: "ember", label: "Ember", votes: 27, color: "text-[#ff5a1f] dark:text-[#ff7a45]" },
{ id: "quill", label: "Quill", votes: 19, color: "text-[#ff2d87] dark:text-[#ff5ca8]" },
];
// A vote from someone else every ~0.8s, until the poll has this many.
const EVERY = 0.8;
const CLOSE_AT = 260;
export function TallyPollDemo() {
const [votes, setVotes] = React.useState(() => Object.fromEntries(OPTIONS.map((o) => [o.id, o.votes])));
const [mine, setMine] = React.useState<string | null>(null);
const total = Object.values(votes).reduce((a, b) => a + b, 0);
const open = total < CLOSE_AT;
// Other people voting, leaning toward what's already ahead.
React.useEffect(() => {
if (!open) return;
const id = window.setTimeout(
() => {
setVotes((v) => {
const sum = Object.values(v).reduce((a, b) => a + b, 0);
let pick = Math.random() * (sum + OPTIONS.length * 20);
for (const o of OPTIONS) {
pick -= v[o.id] + 20;
if (pick <= 0) return { ...v, [o.id]: v[o.id] + 1 };
}
return v;
});
},
EVERY * (0.5 + Math.random()) * 1000,
);
return () => window.clearTimeout(id);
}, [votes, open]);
const items = React.useMemo(
() => OPTIONS.map((o) => ({ id: o.id, label: o.label, value: votes[o.id], dotClassName: o.color })),
[votes],
);
const vote = (id: string) => {
if (mine) return;
setMine(id);
setVotes((v) => ({ ...v, [id]: v[id] + 1 }));
};
return (
<div className="w-full max-w-3xl overflow-hidden rounded-2xl border border-zinc-950/10 bg-white text-zinc-950 dark:border-white/10 dark:bg-zinc-950 dark:text-white">
<div className="flex flex-wrap items-start justify-between gap-3 px-5 pt-5">
<div>
<p className="font-mono text-[11px] tracking-wide text-zinc-500 uppercase dark:text-zinc-400">Orrery team poll</p>
<h3 className="mt-1 text-[17px] font-medium tracking-tight text-balance">{QUESTION}</h3>
</div>
<p className="flex items-center gap-2 font-mono text-[11px] text-zinc-500 tabular-nums dark:text-zinc-400">
<span aria-hidden className={open ? "size-1.5 rounded-full bg-emerald-500" : "size-1.5 rounded-full bg-zinc-400"} />
{total} votes · {open ? "live" : "closed"}
</p>
</div>
<Tally items={items} per={1} unit="vote" dotSize={11} gap={2.5} label={QUESTION} className="mx-5 mt-4 h-[24rem] sm:h-72" />
<div className="mt-2 border-t border-zinc-950/10 px-5 py-4 dark:border-white/10">
<p aria-live="polite" className="font-mono text-xs text-zinc-600 dark:text-zinc-400">
{mine ? `Thanks. Your vote went to ${OPTIONS.find((o) => o.id === mine)?.label}.` : "Cast yours:"}
</p>
<div className="mt-3 flex flex-wrap gap-2">
{OPTIONS.map((o) => (
<button
key={o.id}
type="button"
disabled={!!mine && mine !== o.id}
aria-pressed={mine === o.id}
onClick={() => vote(o.id)}
className="flex items-center gap-2 rounded-full border border-zinc-950/15 px-3.5 py-1.5 text-sm transition-colors enabled:hover:border-zinc-950/40 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 disabled:opacity-40 aria-pressed:border-transparent aria-pressed:bg-zinc-950 aria-pressed:text-white dark:border-white/15 dark:enabled:hover:border-white/40 dark:focus-visible:outline-white dark:aria-pressed:bg-white dark:aria-pressed:text-zinc-950"
>
<span aria-hidden className={`size-2 bg-current ${o.color}`} />
{o.label}
</button>
))}
</div>
</div>
</div>
);
}
Add this moment from KeyframeUI to our project and adapt it to our content. Tally: A chart where every dot is a fixed amount (a job, a vote, a hundred dollars), packed into one round cluster per category. When the numbers change, the dots that moved fly from the clusters that shrank to the ones that grew on hairline trails, and the counts underneath step as they land. Units you mark hollow, like retries, sit among the dots as rings. This demo, Live Poll: A naming poll where every vote is a dot that flies in from the edge as it's cast, yours included. 1. Install it: npx shadcn@latest add @keyframeui/tally-poll-demo (If the CLI can't find @keyframeui, use https://keyframeui.com/r/tally-poll-demo.json instead.) It adds the demo, components/tally-poll-demo.tsx, and the component, components/ui/tally.tsx. 2. Make it ours: our copy, data, images and colors. Keep the structure the motion depends on. If we only need the effect, use <Tally> on its own. 3. These props set its feel. Change them before you change the file: - layout (default "row"): `row` sets the clusters side by side over one line of labels, wrapping onto more rows when columns would get narrower than about 130px. `free` puts each cluster at its item's `x` and `y`, like places on a map, with its label under it. - dotSize (default 6): Diameter of a dot, in px. When a cluster would outgrow its room, every dot shrinks together instead, so the clusters stay comparable. - gap (default 1.5): Space between neighbouring dots, in px. - trails (default true): Draw each dot's path behind it as a hairline that reels in once it lands. - duration (default 1.1): Seconds a dot takes to fly: in from the edge, or across to another cluster. Each one varies by a quarter either way. - stagger (default 0.9): Seconds between the first dot leaving the edge and the last, on the way in. - trailLength (default 0.55): How far a trail lags behind its dot, as a share of the flight, from 0 (none) to 1 (the whole path so far). - legend (default true): Show the legend above the clusters: what one dot is worth, and what a ring means. It takes a 28px band at the top. 4. Don't change, in components/ui/tally.tsx: - Every dot's position is a closed-form function of time (a cubic from where it was to its slot), so it lands exactly, a new update starts from where each dot is, and the loop stops once nothing moves. - A cluster fills its hex spiral from the middle out, so it grows and shrinks at its rim and stays round; a shrinking cluster hands its outermost dots to the nearest growing cluster first. - Dots keep their identity and `per` stays fixed once picked: a unit that moved between categories flies between clusters and is never swapped for a new dot. Only a change in the total brings dots in from the edge or sends them out through it. - Each cluster draws in its item's color, read from a swatch beside its label, and a dot crossing to another cluster shades from the old color to the new one as it flies. - Under reduced motion nothing flies: the chart crossfades to the new numbers and counts jump. Its timing is all in the TIMING block at the top of that file. Docs: https://keyframeui.com/components/tally.md
Budget Split
One monthly ad budget split three ways. Switching plans moves the dollars between channels instead of redrawing the chart.
"use client";
import * as React from "react";
import { Tally } from "@/components/ui/tally";
const CHANNELS = [
{ id: "search", label: "Search", color: "text-[#2f45e8] dark:text-[#8b98ff]" },
{ id: "social", label: "Social", color: "text-[#ff2d87] dark:text-[#ff5ca8]" },
{ id: "video", label: "Video", color: "text-[#f59e0b] dark:text-[#fbbf24]" },
{ id: "podcasts", label: "Podcasts", color: "text-[#7c3aed] dark:text-[#a78bfa]" },
];
// Fieldnote's monthly ad budget: the same $48,000 split three ways.
const PLANS = [
{ id: "launch", label: "Launch", note: "Loud for six weeks: social and video carry the news.", split: { search: 12000, social: 18000, video: 14000, podcasts: 4000 } },
{ id: "steady", label: "Steady", note: "Catch the people already looking: most of it goes to search.", split: { search: 24000, social: 10000, video: 8000, podcasts: 6000 } },
{ id: "brand", label: "Brand", note: "Be remembered: long video and podcast reads.", split: { search: 8000, social: 10000, video: 18000, podcasts: 12000 } },
] as const;
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
const format = (value: number) => usd.format(value);
export function TallyBudgetDemo() {
const [planId, setPlanId] = React.useState<(typeof PLANS)[number]["id"]>("steady");
const plan = PLANS.find((p) => p.id === planId) ?? PLANS[1];
const items = React.useMemo(
() =>
CHANNELS.map((c) => ({
id: c.id,
label: c.label,
value: plan.split[c.id as keyof typeof plan.split],
dotClassName: c.color,
})),
[plan],
);
const onKeyDown = (event: React.KeyboardEvent) => {
const step = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0;
if (!step) return;
event.preventDefault();
const i = PLANS.findIndex((p) => p.id === planId);
const next = PLANS[(i + step + PLANS.length) % PLANS.length];
setPlanId(next.id);
document.getElementById(`tally-budget-${next.id}`)?.focus();
};
return (
<div className="w-full max-w-3xl overflow-hidden rounded-2xl border border-zinc-950/10 bg-white text-zinc-950 dark:border-white/10 dark:bg-zinc-950 dark:text-white">
<div className="flex flex-col gap-4 px-5 pt-5 sm:flex-row sm:items-start sm:justify-between">
<div>
<p className="font-mono text-[11px] tracking-wide text-zinc-500 uppercase dark:text-zinc-400">Fieldnote · monthly ads</p>
<h3 className="mt-1 text-[17px] font-medium tracking-tight">$48,000, three ways</h3>
</div>
<div
role="radiogroup"
aria-label="Budget plan"
onKeyDown={onKeyDown}
className="flex shrink-0 self-start rounded-full border border-zinc-950/10 p-1 dark:border-white/10"
>
{PLANS.map((p) => (
<button
key={p.id}
id={`tally-budget-${p.id}`}
type="button"
role="radio"
aria-checked={p.id === planId}
tabIndex={p.id === planId ? 0 : -1}
onClick={() => setPlanId(p.id)}
className="rounded-full px-3.5 py-1.5 font-mono text-xs text-zinc-500 transition-colors hover:text-zinc-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#2f45e8] aria-checked:bg-zinc-950 aria-checked:text-white dark:text-zinc-400 dark:hover:text-white dark:focus-visible:outline-[#8b98ff] dark:aria-checked:bg-white dark:aria-checked:text-zinc-950"
>
{p.label}
</button>
))}
</div>
</div>
<Tally items={items} per={100} format={format} label="Monthly ad budget by channel" className="mx-5 mt-4 h-[24rem] sm:h-72" />
<p aria-live="polite" className="mt-2 border-t border-zinc-950/10 px-5 py-4 font-mono text-xs leading-relaxed text-zinc-600 dark:border-white/10 dark:text-zinc-400">
{plan.note}
</p>
</div>
);
}
Add this moment from KeyframeUI to our project and adapt it to our content. Tally: A chart where every dot is a fixed amount (a job, a vote, a hundred dollars), packed into one round cluster per category. When the numbers change, the dots that moved fly from the clusters that shrank to the ones that grew on hairline trails, and the counts underneath step as they land. Units you mark hollow, like retries, sit among the dots as rings. This demo, Budget Split: One monthly ad budget split three ways. Switching plans moves the dollars between channels instead of redrawing the chart. 1. Install it: npx shadcn@latest add @keyframeui/tally-budget-demo (If the CLI can't find @keyframeui, use https://keyframeui.com/r/tally-budget-demo.json instead.) It adds the demo, components/tally-budget-demo.tsx, and the component, components/ui/tally.tsx. 2. Make it ours: our copy, data, images and colors. Keep the structure the motion depends on. If we only need the effect, use <Tally> on its own. 3. These props set its feel. Change them before you change the file: - layout (default "row"): `row` sets the clusters side by side over one line of labels, wrapping onto more rows when columns would get narrower than about 130px. `free` puts each cluster at its item's `x` and `y`, like places on a map, with its label under it. - dotSize (default 6): Diameter of a dot, in px. When a cluster would outgrow its room, every dot shrinks together instead, so the clusters stay comparable. - gap (default 1.5): Space between neighbouring dots, in px. - trails (default true): Draw each dot's path behind it as a hairline that reels in once it lands. - duration (default 1.1): Seconds a dot takes to fly: in from the edge, or across to another cluster. Each one varies by a quarter either way. - stagger (default 0.9): Seconds between the first dot leaving the edge and the last, on the way in. - trailLength (default 0.55): How far a trail lags behind its dot, as a share of the flight, from 0 (none) to 1 (the whole path so far). - legend (default true): Show the legend above the clusters: what one dot is worth, and what a ring means. It takes a 28px band at the top. 4. Don't change, in components/ui/tally.tsx: - Every dot's position is a closed-form function of time (a cubic from where it was to its slot), so it lands exactly, a new update starts from where each dot is, and the loop stops once nothing moves. - A cluster fills its hex spiral from the middle out, so it grows and shrinks at its rim and stays round; a shrinking cluster hands its outermost dots to the nearest growing cluster first. - Dots keep their identity and `per` stays fixed once picked: a unit that moved between categories flies between clusters and is never swapped for a new dot. Only a change in the total brings dots in from the edge or sends them out through it. - Each cluster draws in its item's color, read from a swatch beside its label, and a dot crossing to another cluster shades from the old color to the new one as it flies. - Under reduced motion nothing flies: the chart crossfades to the new numbers and counts jump. Its timing is all in the TIMING block at the top of that file. Docs: https://keyframeui.com/components/tally.md
Props
| Prop | Type | Default | Description |
|---|---|---|---|
items Required | TallyItem[] | None | The categories, in order: { id, label, value, hollow?, x?, y?, dotClassName? }. A cluster holds value / per dots, rounded, and hollow of that amount is drawn as rings (failed, refunded, retried). Keep each id stable: change a value and the dots that moved fly between clusters, shading from the old cluster's color to the new one's; a bigger total brings dots in from the edge and a smaller one sends them out. x and y (0–1) place the cluster when layout is "free". dotClassName is the cluster's own text-* color (dots, rings and the swatch by its label, dark: variants included); without it, clusters take a vivid palette in order: orange, violet, green, pink, blue, amber. |
per | number | None | How much one dot stands for. Without it, it's picked on first layout (about 600 dots in all, rounded to 1, 2, 2.5 or 5 × 10ⁿ, with room for each cluster to grow) and then kept, so a dot means the same amount after every update. |
layout | "row" | "free" | "row" | row sets the clusters side by side over one line of labels, wrapping onto more rows when columns would get narrower than about 130px. free puts each cluster at its item's x and y, like places on a map, with its label under it. |
dotSize | number | 6 | Diameter of a dot, in px. When a cluster would outgrow its room, every dot shrinks together instead, so the clusters stay comparable. |
gap | number | 1.5 | Space between neighbouring dots, in px. |
trails | boolean | true | Draw each dot's path behind it as a hairline that reels in once it lands. |
duration | number | 1.1 | Seconds a dot takes to fly: in from the edge, or across to another cluster. Each one varies by a quarter either way. |
stagger | number | 0.9 | Seconds between the first dot leaving the edge and the last, on the way in. |
trailLength | number | 0.55 | How far a trail lags behind its dot, as a share of the flight, from 0 (none) to 1 (the whole path so far). |
format | (value: number) => string | None | Formats the counts under the clusters and the legend's amount. Defaults to grouped digits (4,800). |
unit | string | None | What one unit is called ("jobs", "votes"), after the amount in the legend and for screen readers. |
hollowLabel | string | None | What a hollow ring means ("retried"). Adds a ring to the legend with it. |
legend | boolean | true | Show the legend above the clusters: what one dot is worth, and what a ring means. It takes a 28px band at the top. |
label | string | None | Names the chart for screen readers. They read a list of every item and its value, announced again when the numbers change. |
dotClassName | string | None | One text-* color for every cluster, for a one-color chart; it also colors the legend's marks. An item's own dotClassName still wins. Without either, each cluster takes the next color of the built-in palette. The canvas reads it, so dark: variants work. |
labelClassName | string | None | Classes for each label under a cluster. Its color sets the count's; the category name draws at 60% of it. |
onSettle | () => void | None | Called each time every dot has landed: after the entrance and after each update. |
children | React.ReactNode | None | Content drawn over the chart. |
className | string | None | Classes for the box. Give it a height: clusters fill it above a 46px band of labels per row, and pointing at a cluster or its label dims the rest. |
itemsRequiredType
TallyItem[]The categories, in order:
{ id, label, value, hollow?, x?, y?, dotClassName? }. A cluster holdsvalue / perdots, rounded, andhollowof that amount is drawn as rings (failed, refunded, retried). Keep eachidstable: change a value and the dots that moved fly between clusters, shading from the old cluster's color to the new one's; a bigger total brings dots in from the edge and a smaller one sends them out.xandy(0–1) place the cluster whenlayoutis"free".dotClassNameis the cluster's owntext-*color (dots, rings and the swatch by its label,dark:variants included); without it, clusters take a vivid palette in order: orange, violet, green, pink, blue, amber.perType
numberHow much one dot stands for. Without it, it's picked on first layout (about 600 dots in all, rounded to 1, 2, 2.5 or 5 × 10ⁿ, with room for each cluster to grow) and then kept, so a dot means the same amount after every update.
layoutType
"row" | "free"Default"row"rowsets the clusters side by side over one line of labels, wrapping onto more rows when columns would get narrower than about 130px.freeputs each cluster at its item'sxandy, like places on a map, with its label under it.dotSizeType
numberDefault6Diameter of a dot, in px. When a cluster would outgrow its room, every dot shrinks together instead, so the clusters stay comparable.
gapType
numberDefault1.5Space between neighbouring dots, in px.
trailsType
booleanDefaulttrueDraw each dot's path behind it as a hairline that reels in once it lands.
durationType
numberDefault1.1Seconds a dot takes to fly: in from the edge, or across to another cluster. Each one varies by a quarter either way.
staggerType
numberDefault0.9Seconds between the first dot leaving the edge and the last, on the way in.
trailLengthType
numberDefault0.55How far a trail lags behind its dot, as a share of the flight, from 0 (none) to 1 (the whole path so far).
formatType
(value: number) => stringFormats the counts under the clusters and the legend's amount. Defaults to grouped digits (
4,800).unitType
stringWhat one unit is called ("jobs", "votes"), after the amount in the legend and for screen readers.
hollowLabelType
stringWhat a hollow ring means ("retried"). Adds a ring to the legend with it.
legendType
booleanDefaulttrueShow the legend above the clusters: what one dot is worth, and what a ring means. It takes a 28px band at the top.
labelType
stringNames the chart for screen readers. They read a list of every item and its value, announced again when the numbers change.
dotClassNameType
stringOne
text-*color for every cluster, for a one-color chart; it also colors the legend's marks. An item's owndotClassNamestill wins. Without either, each cluster takes the next color of the built-in palette. The canvas reads it, sodark:variants work.labelClassNameType
stringClasses for each label under a cluster. Its color sets the count's; the category name draws at 60% of it.
onSettleType
() => voidCalled each time every dot has landed: after the entrance and after each update.
childrenType
React.ReactNodeContent drawn over the chart.
classNameType
stringClasses for the box. Give it a height: clusters fill it above a 46px band of labels per row, and pointing at a cluster or its label dims the rest.





