Stat cards

KPI cards for dashboards. Each card shows a label, a value, a signed change against a named period and an optional sparkline. Changes are coloured by whether the move is good (set invert for churn or cost), carry an arrow icon and screen-reader text, and the cards come as separate tiles or one joined panel.

DashboardsBlockTailwind v4

Source

"use client";

import * as React from "react";
import { ArrowDownRight, ArrowUpRight, Minus, type LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";

export interface Stat {
  id: string;
  label: string;
  /** Pre-formatted value, e.g. "$48,210" or "3.24%". */
  value: string;
  /** Relative change in percent, e.g. 12.4 or -3.1. */
  delta?: number;
  /** What the delta compares against, e.g. "vs last month". */
  period?: string;
  /** Set when a decrease is good news (churn, latency, cost). */
  invert?: boolean;
  /** Recent values, oldest first. Drawn as a sparkline. */
  trend?: number[];
  icon?: LucideIcon;
  /** Sparkline colour. Defaults to var(--chart-1). */
  color?: string;
}

const round = (n: number) => Math.round(n * 100) / 100;

/* Monotone cubic interpolation: smooth, but never overshoots the data. */
function smoothPath(points: [number, number][]) {
  const n = points.length;
  if (n < 3) return points.map(([x, y], i) => `${i ? "L" : "M"}${x},${y}`).join("");
  const slopes: number[] = [];
  for (let i = 0; i < n - 1; i++) slopes.push((points[i + 1][1] - points[i][1]) / (points[i + 1][0] - points[i][0]));
  const tangents = [slopes[0]];
  for (let i = 1; i < n - 1; i++) tangents.push(slopes[i - 1] * slopes[i] <= 0 ? 0 : (slopes[i - 1] + slopes[i]) / 2);
  tangents.push(slopes[n - 2]);
  let d = `M${points[0][0]},${points[0][1]}`;
  for (let i = 0; i < n - 1; i++) {
    const [x0, y0] = points[i];
    const [x1, y1] = points[i + 1];
    const h = (x1 - x0) / 3;
    d += `C${round(x0 + h)},${round(y0 + tangents[i] * h)},${round(x1 - h)},${round(y1 - tangents[i + 1] * h)},${x1},${y1}`;
  }
  return d;
}

export interface SparklineProps {
  data: number[];
  color?: string;
  /** Accessible summary. Without it the sparkline is decorative. */
  label?: string;
  className?: string;
}

export function Sparkline({ data, color = "var(--chart-1)", label, className }: SparklineProps) {
  const id = React.useId().replace(/[^a-zA-Z0-9_-]/g, "");
  if (data.length < 2) return null;
  const width = 100;
  const height = 40;
  const pad = 5;
  const min = Math.min(...data);
  const max = Math.max(...data);
  const span = max - min || 1;
  const points = data.map(
    (value, i) => [round((i / (data.length - 1)) * width), round(pad + (1 - (value - min) / span) * (height - pad * 2))] as [number, number],
  );
  const line = smoothPath(points);
  const [lastX, lastY] = points[points.length - 1];

  return (
    <div className={cn("relative", className)}>
      <svg
        viewBox={`0 0 ${width} ${height}`}
        preserveAspectRatio="none"
        className="block size-full overflow-visible"
        role={label ? "img" : undefined}
        aria-label={label}
        aria-hidden={label ? undefined : true}
      >
        <defs>
          <linearGradient id={`${id}-fill`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" style={{ stopColor: color, stopOpacity: 0.2 }} />
            <stop offset="100%" style={{ stopColor: color, stopOpacity: 0 }} />
          </linearGradient>
        </defs>
        <path d={`${line}L${width},${height}L0,${height}Z`} fill={`url(#${id}-fill)`} />
        <path
          d={line}
          fill="none"
          style={{ stroke: color }}
          strokeWidth={2}
          strokeLinecap="round"
          strokeLinejoin="round"
          vectorEffect="non-scaling-stroke"
        />
      </svg>
      {/* An HTML dot keeps its round shape while the SVG stretches. */}
      <span
        aria-hidden
        className="absolute size-2 -translate-x-1/2 -translate-y-1/2 rounded-full ring-2 ring-card"
        style={{ left: `${lastX}%`, top: `${(lastY / height) * 100}%`, background: color }}
      />
    </div>
  );
}

export function StatDelta({ delta, period, invert = false, className }: Pick<Stat, "delta" | "period" | "invert"> & { className?: string }) {
  if (delta === undefined) return null;
  const flat = Math.abs(delta) < 0.05;
  const good = invert ? delta < 0 : delta > 0;
  const Icon = flat ? Minus : delta > 0 ? ArrowUpRight : ArrowDownRight;
  const amount = `${Math.abs(delta).toFixed(1)}%`;
  return (
    <span className={cn("inline-flex items-center gap-2 text-xs", className)}>
      <span
        aria-hidden
        className={cn(
          "inline-flex items-center gap-0.5 rounded-md px-1.5 py-0.5 font-medium tabular-nums",
          flat
            ? "bg-muted text-muted-foreground"
            : good
              ? "bg-emerald-500/10 text-emerald-700 dark:bg-emerald-400/10 dark:text-emerald-400"
              : "bg-rose-500/10 text-rose-700 dark:bg-rose-400/10 dark:text-rose-400",
        )}
      >
        <Icon className="size-3.5" strokeWidth={2.25} />
        {amount}
      </span>
      <span className="sr-only">
        {flat ? "No change" : `${delta > 0 ? "Up" : "Down"} ${amount}`} {period}
      </span>
      {period && (
        <span aria-hidden className="text-muted-foreground">
          {period}
        </span>
      )}
    </span>
  );
}

function trendLabel(stat: Stat) {
  if (!stat.trend || stat.trend.length < 2) return undefined;
  const lo = Math.min(...stat.trend);
  const hi = Math.max(...stat.trend);
  return `${stat.label} trend over ${stat.trend.length} periods, low ${lo.toLocaleString()}, high ${hi.toLocaleString()}`;
}

export function StatCard({ stat, joined = false, className }: { stat: Stat; joined?: boolean; className?: string }) {
  const Icon = stat.icon;
  return (
    <div
      data-stat={stat.id}
      className={cn(
        "flex min-w-0 flex-col bg-card p-5 text-card-foreground",
        !joined && "rounded-xl border shadow-xs",
        className,
      )}
    >
      <dt className="flex min-h-8 items-start justify-between gap-3 text-sm font-medium text-muted-foreground">
        <span className="truncate pt-0.5">{stat.label}</span>
        {Icon && (
          <span aria-hidden className="grid size-8 shrink-0 place-items-center rounded-lg border bg-background">
            <Icon className="size-4" />
          </span>
        )}
      </dt>
      <dd className="contents">
        <span className="mt-1 block text-[1.75rem] leading-9 font-semibold tracking-tight">{stat.value}</span>
        <StatDelta delta={stat.delta} period={stat.period} invert={stat.invert} className="mt-1.5" />
        {stat.trend && stat.trend.length > 1 && (
          <Sparkline data={stat.trend} color={stat.color} label={trendLabel(stat)} className="mt-5 h-11" />
        )}
      </dd>
    </div>
  );
}

export interface StatCardsProps {
  stats: Stat[];
  /** "cards": separate cards. "joined": one panel split by hairlines. */
  variant?: "cards" | "joined";
  className?: string;
}

export function StatCards({ stats, variant = "cards", className }: StatCardsProps) {
  const joined = variant === "joined";
  return (
    <dl
      className={cn(
        "grid sm:grid-cols-2 xl:grid-cols-4",
        joined ? "gap-px overflow-hidden rounded-xl border bg-border shadow-xs" : "gap-4",
        className,
      )}
    >
      {stats.map((stat) => (
        <StatCard key={stat.id} stat={stat} joined={joined} />
      ))}
    </dl>
  );
}