Skip to content
Shaken UI
Sign in

Stat Card

Save

A metric with its label, a tabular value, the change against the previous period colored by whether it is good, and a sparkline that draws in as the number counts up.

Category
Data display
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Stat Card preview
Monthly recurring revenue
$48,210
Up 7.4%vs. October
Active workspaces
1,284
Up 6.4%vs. October
Agent runs failed
3.1%
Down 26.2%vs. October
p95 response time
412 ms
Up 6.2%vs. October

Installation

npx @shakenui/cli add stat-card

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add stat-card --dry-run

Usage

stat-card-example.tsx
import { StatCard, StatGroup } from "@/components/shaken/ui/stat-card";

const usd = { style: "currency", currency: "USD", maximumFractionDigits: 0 } as const;

export default function StatCardExample() {
  return (
    <StatGroup label="Workspace metrics for November" className="w-full max-w-4xl">
      <StatCard
        label="Monthly recurring revenue"
        value={48_210}
        previous={44_870}
        period="vs. October"
        format={usd}
        trend={[38_400, 39_150, 40_020, 41_880, 41_300, 43_120, 44_870, 48_210]}
      />
      <StatCard
        label="Active workspaces"
        value={1_284}
        previous={1_207}
        period="vs. October"
        trend={[1_002, 1_048, 1_090, 1_131, 1_160, 1_189, 1_207, 1_284]}
      />
      <StatCard
        label="Agent runs failed"
        value={0.031}
        previous={0.042}
        goodDirection="down"
        period="vs. October"
        format={{ style: "percent", minimumFractionDigits: 1, maximumFractionDigits: 1 }}
        trend={[0.058, 0.051, 0.049, 0.047, 0.044, 0.045, 0.042, 0.031]}
      />
      <StatCard
        label="p95 response time"
        value={412}
        previous={388}
        goodDirection="down"
        period="vs. October"
        format={{ style: "unit", unit: "millisecond", unitDisplay: "short" }}
        trend={[361, 372, 365, 380, 377, 391, 388, 412]}
      />
    </StatGroup>
  );
}

States

Every state, rendered from local fixture data.

Stat Card states
Monthly recurring revenue
$48,210
Up 7.4%vs. October
Cost per agent run
$0.184
Up 14.3%vs. last week
Paid seats
240
No change, 0%vs. last month
Plan limit 250
Open approvals
17
Loading Monthly recurring revenue
Tokens used today
18.4M
Up 12.6%vs. yesterday

API

PropTypeDefaultDescription
labelReactNode—StatCard: what the number measures.
valuenumber—StatCard: the current value.
previousnumber—StatCard: the previous period's value. Sets the change and where the count-up starts.
changenumber—StatCard: the change as a fraction (0.074 for 7.4%) when there is no previous value.
goodDirection"up" | "down" | "neither""up"StatCard: which direction is an improvement. Use down for churn, latency or cost.
periodReactNode—StatCard: what the change compares against, such as "vs. last month".
comparisonReactNode—StatCard: a secondary line, such as a target or plan limit.
trendnumber[]—StatCard: recent values for the sparkline, oldest first.
format / localeIntl.NumberFormatOptions / string—StatCard: number formatting for the value, such as currency, percent or a unit.
formatValue(value: number) => string—StatCard: formats the value yourself; also used while counting.
loadingbooleanfalseStatCard: a skeleton in the card's final shape.
animatebooleantrueStatCard: count up and draw the sparkline the first time the card scrolls into view.
StatGroup labelstring—Accessible name for the group of stats.

Accessibility

  • Each card is a group named by its label; the label and value are a description list term and definition.
  • Screen readers get the final value once, in a visually hidden span, while the visible counting digits are hidden from them.
  • The change is read as "Up 7.4%" or "Down 26.2%" so direction does not depend on the arrow or its color.
  • The sparkline is an image with a text summary of its first and last values, or your own trendLabel.
  • While loading the card is aria-busy and names what is loading.
  • With reduced motion the value and sparkline render final at once, with no counting and no draw-in.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/stat-card.tsxstat-card
  • Also installs skeleton@0.1.0registry dependency
  • npm packages: motion@^14.14.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/stat-card/0.1.0.json.

ui/stat-card.tsxShow
ui/stat-card.tsx
"use client";

import { animate, motion, useInView } from "motion/react";
import {
  Children,
  createContext,
  useContext,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type ComponentProps,
  type ReactNode,
} from "react";
import { Skeleton } from "./skeleton";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = [0.23, 1, 0.32, 1] as const;
/** One entrance for the number and the sparkline, so they read as a single change. */
const ENTRANCE_MS = 800;

function prefersReducedMotion() {
  return typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}

/** Which direction of change is an improvement. `neither` keeps the change neutral. */
export type StatGoodDirection = "up" | "down" | "neither";

type Tone = "good" | "bad" | "neutral";

const toneText: Record<Tone, string> = {
  good: "text-emerald-600 dark:text-emerald-400",
  bad: "text-red-600 dark:text-red-400",
  neutral: "text-zinc-500 dark:text-zinc-400",
};

const toneFill: Record<Tone, string> = {
  good: "fill-emerald-500",
  bad: "fill-red-500",
  neutral: "fill-zinc-400 dark:fill-zinc-500",
};

// Inside a StatGroup the group draws the container and the dividers, so cards drop their own box.
const GroupContext = createContext(false);

export interface StatCardProps extends Omit<ComponentProps<"div">, "children"> {
  /** What the number measures, such as "Monthly recurring revenue". */
  label: ReactNode;
  /** The current value. */
  value: number;
  /** The value for the previous period. Sets the change and where the count-up starts. */
  previous?: number;
  /** The change as a fraction (0.074 for 7.4%), when there is no `previous` to compute it from. */
  change?: number;
  /** Which direction is good. `down` suits churn, latency or cost. Defaults to `up`. */
  goodDirection?: StatGoodDirection;
  /** The period the change compares against, such as "vs. last month". */
  period?: ReactNode;
  /** A secondary line under the change, such as a target or the previous value. */
  comparison?: ReactNode;
  /** Recent values for the inline sparkline, oldest first. Needs two or more points. */
  trend?: number[];
  /** Accessible description of the sparkline. Defaults to a summary of the first and last points. */
  trendLabel?: string;
  /** `Intl.NumberFormat` options for the value, such as `{ style: "currency", currency: "USD" }`. */
  format?: Intl.NumberFormatOptions;
  /** Locale for number formatting. Defaults to the runtime locale. */
  locale?: string;
  /** Formats the value yourself; overrides `format`. Also used while counting up. */
  formatValue?: (value: number) => string;
  /** Shows a skeleton in the card's final shape. */
  loading?: boolean;
  /**
   * Counts the number up from `previous` (or zero) and draws the sparkline once, the first time
   * the card scrolls into view. Off, or with reduced motion preferred, everything renders final.
   */
  animate?: boolean;
}

/**
 * One metric: a label, the value in tabular numbers, the change against the previous period
 * colored by whether it is good, and an optional sparkline. The first time it scrolls into view,
 * the number counts from the previous value to the current one while the sparkline draws in.
 */
export function StatCard({
  label,
  value,
  previous,
  change: changeProp,
  goodDirection = "up",
  period,
  comparison,
  trend,
  trendLabel,
  format,
  locale,
  formatValue,
  loading = false,
  animate: animated = true,
  className,
  ...props
}: StatCardProps) {
  const grouped = useContext(GroupContext);
  const labelId = useId();
  const root = useRef<HTMLDivElement>(null);
  const inView = useInView(root, { once: true, amount: 0.5 });
  const run = animated && inView && !loading;

  const display = useMemo(() => {
    if (formatValue) return formatValue;
    const formatter = new Intl.NumberFormat(locale, format);
    return (n: number) => formatter.format(n);
  }, [formatValue, locale, format]);

  const change = changeProp ?? (previous != null && previous !== 0 ? (value - previous) / Math.abs(previous) : undefined);
  const direction = change == null || Math.abs(change) < 0.0005 ? "flat" : change > 0 ? "up" : "down";
  const tone: Tone = direction === "flat" || goodDirection === "neither" ? "neutral" : direction === goodDirection ? "good" : "bad";
  const percent = useMemo(
    () => new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 1, signDisplay: "never" }),
    [locale],
  );

  const box = grouped
    ? "bg-white dark:bg-black"
    : "rounded-xl border border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]";

  if (loading) {
    return (
      <div
        ref={root}
        role="group"
        aria-busy="true"
        aria-labelledby={labelId}
        className={cx("grid min-w-0 gap-3 p-5", box, className)}
        {...props}
      >
        <span id={labelId} className="sr-only">
          Loading {typeof label === "string" ? label : "metric"}
        </span>
        <Skeleton className="h-4 w-28" />
        <Skeleton className="-mt-0.5 h-8 w-32" />
        <Skeleton className="h-4 w-36" />
        {trend ? <Skeleton className="mt-1 h-9 w-full" /> : null}
      </div>
    );
  }

  return (
    <div ref={root} role="group" aria-labelledby={labelId} className={cx("grid min-w-0 gap-3 p-5 text-left", box, className)} {...props}>
      <dl className="contents">
        <dt id={labelId} className="truncate text-sm text-zinc-600 dark:text-zinc-400">
          {label}
        </dt>
        <dd className="-mt-1 min-w-0">
          <CountUp value={value} from={previous ?? 0} display={display} run={run} animated={animated} />
        </dd>
        {change != null || period != null ? (
          <dd className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs">
            {change != null ? (
              <span className={cx("inline-flex items-center gap-0.5 font-medium tabular-nums", toneText[tone])}>
                <ChangeGlyph direction={direction} />
                <span className="sr-only">{direction === "up" ? "Up" : direction === "down" ? "Down" : "No change,"} </span>
                {percent.format(Math.abs(change))}
              </span>
            ) : null}
            {period != null ? <span className="text-zinc-500">{period}</span> : null}
          </dd>
        ) : null}
        {comparison != null ? <dd className="-mt-1.5 text-xs text-zinc-500 tabular-nums">{comparison}</dd> : null}
        {trend && trend.length > 1 ? (
          <dd className="mt-1">
            <Sparkline data={trend} tone={tone} run={run} animated={animated} label={trendLabel ?? describeTrend(trend, display)} />
          </dd>
        ) : null}
      </dl>
    </div>
  );
}

function CountUp({
  value,
  from,
  display,
  run,
  animated,
}: {
  value: number;
  from: number;
  display: (n: number) => string;
  run: boolean;
  animated: boolean;
}) {
  // Server and first client render show the final value; the start value is swapped in before paint.
  const [shown, setShown] = useState(value);
  const played = useRef(false);
  const last = useRef(value);

  useLayoutEffect(() => {
    if (!played.current && animated && !prefersReducedMotion()) setShown(from);
    // Only the first mount decides the starting frame.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useLayoutEffect(() => {
    if (!run && !played.current) return;
    const start = played.current ? last.current : from;
    played.current = true;
    last.current = value;
    if (!animated || prefersReducedMotion() || start === value) {
      setShown(value);
      return;
    }
    // The entrance counts from the previous period; later updates take a shorter count.
    const controls = animate(start, value, {
      duration: (start === from ? ENTRANCE_MS : 400) / 1000,
      ease,
      onUpdate: (n) => setShown(n),
    });
    return () => controls.stop();
  }, [run, value, from, animated]);

  const decimals = Number.isInteger(value) && Number.isInteger(from);
  const text = display(decimals ? Math.round(shown) : shown);

  return (
    // The invisible final value holds the width, so counting never reflows the row.
    <span className="grid min-w-0 text-[28px] leading-9 font-semibold tracking-tight text-zinc-950 tabular-nums dark:text-white">
      <span aria-hidden="true" className="invisible col-start-1 row-start-1 truncate">
        {display(value)}
      </span>
      <span aria-hidden="true" className="col-start-1 row-start-1 truncate">
        {text}
      </span>
      <span className="sr-only">{display(value)}</span>
    </span>
  );
}

function ChangeGlyph({ direction }: { direction: "up" | "down" | "flat" }) {
  return (
    <svg aria-hidden="true" viewBox="0 0 12 12" className="size-3 shrink-0">
      {direction === "flat" ? (
        <path d="M2.5 6h7" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      ) : (
        <path
          d={direction === "up" ? "M6 9.5v-7M3 5.5l3-3 3 3" : "M6 2.5v7M3 6.5l3 3 3-3"}
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      )}
    </svg>
  );
}

const SPARK_H = 36;
const PAD = 3;

function Sparkline({ data, tone, run, animated, label }: { data: number[]; tone: Tone; run: boolean; animated: boolean; label: string }) {
  // The line spans the card's width, drawn in real pixels so the stroke and the end dot stay round.
  const box = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);
  useLayoutEffect(() => {
    const el = box.current;
    if (!el) return;
    setWidth(Math.round(el.getBoundingClientRect().width));
    const observer = new ResizeObserver(([entry]) => setWidth(Math.round(entry!.contentRect.width)));
    observer.observe(el);
    return () => observer.disconnect();
  }, []);
  const shape = useMemo(() => (width > 0 ? sparkPath(data, width) : null), [data, width]);
  // It starts hidden in every render pass so server and client markup match;
  // reduced motion and animate={false} reveal it with a zero-length transition.
  const instant = !animated || prefersReducedMotion();
  const shown = run || !animated;

  return (
    <div ref={box} role="img" aria-label={label} className="h-9 w-full text-zinc-950/30 dark:text-white/35">
      {shape ? (
        <svg aria-hidden="true" width={width} height={SPARK_H} viewBox={`0 0 ${width} ${SPARK_H}`} className="block overflow-visible">
          <motion.path
            d={shape.path}
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            initial={{ pathLength: 0, opacity: 0 }}
            animate={shown ? { pathLength: 1, opacity: 1 } : { pathLength: 0, opacity: 0 }}
            transition={instant ? { duration: 0 } : { pathLength: { duration: ENTRANCE_MS / 1000, ease }, opacity: { duration: 0.15 } }}
          />
          <motion.circle
            cx={shape.end.x}
            cy={shape.end.y}
            r="2.5"
            className={toneFill[tone]}
            style={{ transformOrigin: `${shape.end.x}px ${shape.end.y}px` }}
            initial={{ opacity: 0, scale: 0.5 }}
            animate={shown ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0.5 }}
            transition={instant ? { duration: 0 } : { delay: (ENTRANCE_MS - 120) / 1000, duration: 0.2, ease }}
          />
        </svg>
      ) : null}
    </div>
  );
}

/** A monotone cubic curve through the points, so the line never overshoots the data. */
function sparkPath(data: number[], width: number) {
  const min = Math.min(...data);
  const max = Math.max(...data);
  const span = max - min || 1;
  const pts = data.map((v, i) => ({
    x: PAD + (i / (data.length - 1)) * (width - PAD * 2),
    y: max === min ? SPARK_H / 2 : PAD + (1 - (v - min) / span) * (SPARK_H - PAD * 2),
  }));
  const n = pts.length;
  const slopes: number[] = [];
  for (let i = 0; i < n - 1; i++) slopes.push((pts[i + 1]!.y - pts[i]!.y) / (pts[i + 1]!.x - pts[i]!.x));
  const tangents = pts.map((_, i) => {
    if (i === 0) return slopes[0]!;
    if (i === n - 1) return slopes[n - 2]!;
    const a = slopes[i - 1]!;
    const b = slopes[i]!;
    return a * b <= 0 ? 0 : (2 * a * b) / (a + b);
  });
  let d = `M${pts[0]!.x.toFixed(2)},${pts[0]!.y.toFixed(2)}`;
  for (let i = 0; i < n - 1; i++) {
    const p = pts[i]!;
    const q = pts[i + 1]!;
    const dx = (q.x - p.x) / 3;
    d += `C${(p.x + dx).toFixed(2)},${(p.y + tangents[i]! * dx).toFixed(2)} ${(q.x - dx).toFixed(2)},${(q.y - tangents[i + 1]! * dx).toFixed(2)} ${q.x.toFixed(2)},${q.y.toFixed(2)}`;
  }
  return { path: d, end: pts[n - 1]! };
}

function describeTrend(data: number[], display: (n: number) => string) {
  return `Trend over ${data.length} periods, from ${display(data[0]!)} to ${display(data[data.length - 1]!)}`;
}

export interface StatGroupProps extends ComponentProps<"div"> {
  /** Accessible name for the group, such as "Revenue this month". */
  label?: string;
}

const columns: Record<number, string> = {
  1: "",
  2: "@md:grid-cols-2",
  3: "@2xl:grid-cols-3",
  4: "@md:grid-cols-2 @3xl:grid-cols-4",
};

/**
 * Three or four StatCards in one container, separated by hairline dividers instead of boxed cards.
 * Columns follow the group's own width (container queries), so it fits a sidebar or a full page.
 */
export function StatGroup({ label, className, children, ...props }: StatGroupProps) {
  const count = Math.min(Children.count(children), 4);
  return (
    <GroupContext.Provider value={true}>
      <div
        role={label ? "group" : undefined}
        aria-label={label}
        className={cx(
          "@container overflow-hidden rounded-xl border border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
          "dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
          className,
        )}
        {...props}
      >
        {/* The 1px gaps show the divider color through, so dividers stay right at any column count. */}
        <div className={cx("grid gap-px bg-zinc-950/[0.07] dark:bg-white/[0.1]", columns[count])}>{children}</div>
      </div>
    </GroupContext.Provider>
  );
}