Stat card
A KPI with a count-up and a sparkline.
Installation
Run the CLI
Run
pnpm dlx asta-ui@latest initonce, then this. The file lands incomponents/astabyte/and the colour tokens go into your CSS.$ pnpm dlx asta-ui@latest add stat-cardOr install the package
Don’t want the file? Import from
asta-ui/stat-cardand update withpnpm update asta-ui. Add the stylesheet once. More.$ pnpm add asta-uiimport { StatCard } from "asta-ui/stat-card";Or copy it by hand
Copy this file. Keep the paths, or fix the
@/imports. Then add the tokens fromglobals.css."use client"; import { useLayoutEffect, useMemo, useRef } from "react"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const KEYFRAMES = `@keyframes asta-stat-draw { from { stroke-dashoffset: 1 } } @keyframes asta-stat-fade { from { opacity: 0 } } @keyframes asta-stat-dot { from { opacity: 0; transform: scale(0) } } /* perf-ok: 4px end-of-line dot, not a surface */ .asta-stat[data-inview="false"] .asta-stat-a { animation-play-state: paused } @media (prefers-reduced-motion: reduce) { .asta-stat .asta-stat-a { animation: none !important } }`; const W = 96; const H = 32; export interface StatCardProps { label: string; value: number; /** Number format, e.g. `{ style: "currency", currency: "USD", maximumFractionDigits: 0 }`. */ format?: Intl.NumberFormatOptions; locale?: string; prefix?: string; suffix?: string; /** Change in percent. Up is blue, down stays neutral. */ delta?: number; /** What the delta compares against, e.g. "vs last week". */ deltaLabel?: string; /** Points for the sparkline, oldest first. */ data?: number[]; /** Count-up length in ms. */ duration?: number; className?: string; } /** A smooth path through the points (quadratic curves through the midpoints). */ function spark(data: number[]) { const min = Math.min(...data); const span = Math.max(...data) - min || 1; const pts = data.map((v, i) => [(i / Math.max(1, data.length - 1)) * (W - 4) + 2, H - 3 - ((v - min) / span) * (H - 6)] as const); let d = `M${pts[0][0].toFixed(1)} ${pts[0][1].toFixed(1)}`; for (let i = 1; i < pts.length - 1; i++) { const mx = (pts[i][0] + pts[i + 1][0]) / 2; const my = (pts[i][1] + pts[i + 1][1]) / 2; d += ` Q${pts[i][0].toFixed(1)} ${pts[i][1].toFixed(1)} ${mx.toFixed(1)} ${my.toFixed(1)}`; } const end = pts[pts.length - 1]; d += ` L${end[0].toFixed(1)} ${end[1].toFixed(1)}`; return { line: d, area: `${d} L${end[0].toFixed(1)} ${H} L${pts[0][0].toFixed(1)} ${H} Z`, end }; } /** * A KPI tile: a label, a value that counts up when the card scrolls into view (and from the old value to the * new one when it changes), a delta and a tiny sparkline that draws itself in. Up reads blue, down stays neutral. */ export function StatCard({ label, value, format, locale = "en-US", prefix = "", suffix = "", delta, deltaLabel, data, duration = 1100, className }: StatCardProps) { const root = useRef<HTMLDivElement>(null); const num = useRef<HTMLSpanElement>(null); const shown = useRef(0); const started = useRef(false); const fmtKey = JSON.stringify(format ?? {}); const fmt = useMemo(() => new Intl.NumberFormat(locale, JSON.parse(fmtKey) as Intl.NumberFormatOptions), [locale, fmtKey]); const text = `${prefix}${fmt.format(value)}${suffix}`; // Count up. Writes straight to the text node, so a frame never re-renders React. useLayoutEffect(() => { const node = num.current?.firstChild; const el = root.current; if (!node || !el) return; const f = new Intl.NumberFormat(locale, JSON.parse(fmtKey) as Intl.NumberFormatOptions); const write = (v: number) => { shown.current = v; node.nodeValue = `${prefix}${f.format(v)}${suffix}`; }; let raf = 0; const run = (from: number) => { if (from === value || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return write(value); const t0 = performance.now(); const tick = (now: number) => { const t = Math.min(1, (now - t0) / duration); write(t < 1 ? from + (value - from) * (1 - Math.pow(1 - t, 4)) : value); if (t < 1) raf = requestAnimationFrame(tick); }; write(from); raf = requestAnimationFrame(tick); }; if (started.current || typeof IntersectionObserver === "undefined") { started.current = true; el.dataset.inview = "true"; run(shown.current); return () => cancelAnimationFrame(raf); } // First time: wait until the card is on screen, and start the sparkline with it. write(0); const io = new IntersectionObserver( ([e]) => { if (!e.isIntersecting) return; io.disconnect(); started.current = true; el.dataset.inview = "true"; run(0); }, { threshold: 0.3 }, ); io.observe(el); return () => { io.disconnect(); cancelAnimationFrame(raf); }; }, [value, locale, fmtKey, prefix, suffix, duration]); const trend = delta ?? (data && data.length > 1 ? data[data.length - 1] - data[0] : 0); const up = trend > 0; const path = data && data.length > 1 ? spark(data) : null; return ( <div ref={root} data-inview="false" className={cx("asta-stat flex flex-col gap-3 rounded-xl bg-paper-2 p-5", className)}> <style href="asta-stat-card" precedence="asta">{KEYFRAMES}</style> <p className="text-[13px] text-mute">{label}</p> <div className="flex items-end justify-between gap-4"> <p className="text-[28px] font-medium leading-none tracking-[-0.04em] text-ink tabular-nums"> <span ref={num} aria-hidden> {text} </span> <span className="sr-only">{text}</span> </p> {path && ( <svg key={data!.join(",")} viewBox={`0 0 ${W} ${H}`} width={W} height={H} className={cx("shrink-0 overflow-visible", up ? "text-brand" : "text-mute")} aria-hidden> <path d={path.area} fill="currentColor" className="asta-stat-a animate-[asta-stat-fade_.9s_cubic-bezier(.16,1,.3,1)_.5s_both]" opacity={0.1} /> <path d={path.line} fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" pathLength={1} strokeDasharray={1} className="asta-stat-a animate-[asta-stat-draw_1.2s_cubic-bezier(.16,1,.3,1)_both]" /> <circle cx={path.end[0]} cy={path.end[1]} r="2.25" fill="currentColor" className="asta-stat-a origin-center animate-[asta-stat-dot_.5s_cubic-bezier(.16,1,.3,1)_.9s_both] [transform-box:fill-box]" /> </svg> )} </div> {delta !== undefined && ( <p className="flex items-center gap-1.5 text-[12.5px]"> <span className={cx("inline-flex items-center gap-0.5 font-medium tabular-nums", up ? "text-brand" : "text-mute")}> <svg viewBox="0 0 24 24" className={cx("h-3 w-3", !up && delta !== 0 && "rotate-180", delta === 0 && "hidden")} fill="none" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="M12 20V5" /> <path d="m6 11 6-6 6 6" /> </svg> <span className="sr-only">{up ? "Up" : delta < 0 ? "Down" : "No change"}</span> {`${delta > 0 ? "+" : delta < 0 ? "−" : ""}${Math.abs(delta).toFixed(1)}%`} </span> {deltaLabel && <span className="text-mute">{deltaLabel}</span>} </p> )} </div> ); } export default StatCard;Or ask your AI agent
Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.
Add the Astabyte UI Stat card component to my project. A KPI with a count-up and a sparkline. It includes: count-up, format, delta, sparkline, prefix/suffix. Install it: ```sh pnpm dlx asta-ui@latest add stat-card --radix ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/stat-card.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Button } from "@/components/astabyte/button"; import { StatCard } from "@/components/astabyte/stat-card"; ``` Usage example and props: https://ui.astabyte.com/stat-card Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Or use plain HTML + CSS
Not on React? Use it from Django, Rails, Laravel, Go
html/template, htmx or a static page. Loadasta.cssandasta.jsonce (thehead.htmltab), then paste the markup. Theui.astabyte.com/cdnlink is temporary: pin a version from jsDelivr for production. More in HTML + CSS.<!-- Sparkline paths and the trend class are computed on the server. --> <div style="display:flex;flex-wrap:wrap;align-items:center;gap:12px"> <div class="asta-stat-card"><p class="asta-stat-card-label">Revenue</p><div class="asta-stat-card-row"><p class="asta-stat-card-value">$48.2k</p><svg class="asta-stat-card-spark" viewBox="0 0 96 32" width="96" height="32" aria-hidden="true"><g><path class="asta-stat-card-area" d="M2.0 29.0 Q17.3 20.3 25.0 22.5 Q32.7 24.7 40.3 20.3 Q48.0 16.0 55.7 11.7 Q63.3 7.3 71.0 9.5 Q78.7 11.7 86.3 7.3 L94.0 3.0 L94.0 32 L2.0 32 Z"/><path class="asta-stat-card-line" d="M2.0 29.0 Q17.3 20.3 25.0 22.5 Q32.7 24.7 40.3 20.3 Q48.0 16.0 55.7 11.7 Q63.3 7.3 71.0 9.5 Q78.7 11.7 86.3 7.3 L94.0 3.0"/></g><circle class="asta-stat-card-dot" cx="94.0" cy="3.0" r="2.25"/></svg></div><p class="asta-stat-card-delta"><span class="asta-stat-card-change" aria-label="Up 12.4%"><svg viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 9.5v-7M2.75 5.5 6 2.25 9.25 5.5"/></svg>+12.4%</span><span class="asta-stat-card-note">vs last month</span></p></div><div class="asta-stat-card asta-stat-card-down"><p class="asta-stat-card-label">Churn</p><div class="asta-stat-card-row"><p class="asta-stat-card-value">2.1%</p><svg class="asta-stat-card-spark" viewBox="0 0 96 32" width="96" height="32" aria-hidden="true"><g><path class="asta-stat-card-area" d="M2.0 3.0 Q32.7 16.0 48.0 16.0 Q63.3 16.0 78.7 22.5 L94.0 29.0 L94.0 32 L2.0 32 Z"/><path class="asta-stat-card-line" d="M2.0 3.0 Q32.7 16.0 48.0 16.0 Q63.3 16.0 78.7 22.5 L94.0 29.0"/></g><circle class="asta-stat-card-dot" cx="94.0" cy="29.0" r="2.25"/></svg></div><p class="asta-stat-card-delta"><span class="asta-stat-card-change" aria-label="Down 0.4%"><svg viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 9.5v-7M2.75 5.5 6 2.25 9.25 5.5"/></svg>−0.4%</span></p></div> </div>
Usage
The demo above, as code.
"use client";
import { useState } from "react";
import { Button } from "@/components/astabyte/button";
import { StatCard } from "@/components/astabyte/stat-card";
const WEEKS = [
{ revenue: 48250, orders: 1284, refunds: 1.8, trend: [31, 34, 33, 38, 36, 41, 44, 48] },
{ revenue: 52910, orders: 1391, refunds: 1.6, trend: [34, 33, 38, 36, 41, 44, 48, 53] },
];
export default function StatCardDemo() {
const [w, setW] = useState(0);
const week = WEEKS[w];
return (
<div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
<div className="flex w-full max-w-3xl flex-col gap-4">
<div className="flex items-center justify-between gap-4">
<p className="text-[15px] font-medium tracking-[-0.01em] text-ink">{w ? "This week" : "Last week"}</p>
<Button size="sm" variant="outline" onClick={() => setW(w ? 0 : 1)}>
{w ? "Show last week" : "Show this week"}
</Button>
</div>
<div className="grid gap-3 sm:grid-cols-3">
<StatCard label="Revenue" value={week.revenue} format={{ style: "currency", currency: "USD", maximumFractionDigits: 0 }} delta={w ? 9.7 : 12.4} deltaLabel="vs prior week" data={week.trend} />
<StatCard label="Orders" value={week.orders} delta={w ? 8.3 : 4.1} deltaLabel="vs prior week" data={[9, 11, 10, 12, 11, 13, 12, w ? 14 : 13]} />
<StatCard label="Refund rate" value={week.refunds} suffix="%" format={{ maximumFractionDigits: 1, minimumFractionDigits: 1 }} delta={w ? -11.1 : -0.4} deltaLabel="vs prior week" data={[2.4, 2.2, 2.3, 2.0, 1.9, 2.0, 1.8, week.refunds]} />
</div>
</div>
</div>
);
}