dxbh-uiGitHub

Stat

Label, figure, delta: the unit for a number shown on its own. StatStrip splits a row of them on hairlines and StatRow fits one on a line.

Preview

Visitors

18,240

Up9.2%

Signups

1,204

Down2.4%

Cost per signup

$3.10

Down6.0%

Failed payments

7

of 1,204

Storage

62%

of 500 GB
Mobile58%Up3.0%
Desktop39%Down2.1%
Tablet3%

Install

npx shadcn@latest add @dxbh-ui/stat

Add the @dxbh-ui registry to components.json once:

{
  "registries": {
    "@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
  }
}

Usage

demo.tsx
"use client";

import { useState } from "react";
import { Stat, StatRow, StatStrip } from "@/components/ui/stat/stat";
import { Meter } from "@/components/ui/meter/meter";

const fmt = new Intl.NumberFormat("en-US");

export default function StatDemo() {
  const [visitors, setVisitors] = useState(18_240);

  return (
    <div className="grid w-full max-w-2xl gap-6">
      <StatStrip
        surface
        columns={4}
        items={[
          { label: "Visitors", value: fmt.format(visitors), delta: { dir: "up", value: "9.2%" } },
          { label: "Signups", value: "1,204", delta: { dir: "down", value: "2.4%" } },
          { label: "Cost per signup", value: "$3.10", delta: { dir: "down", value: "6.0%", tone: "positive" } },
          { label: "Failed payments", value: "7", tone: "negative", hint: "of 1,204" },
        ]}
      />
      <div className="grid gap-6 sm:grid-cols-2">
        <Stat label="Storage" value="62%" hint="of 500 GB">
          <Meter value={62} size="sm" />
        </Stat>
        <div className="grid content-start gap-2">
          <StatRow label="Mobile" value="58%" delta={{ dir: "up", value: "3.0%" }} />
          <StatRow label="Desktop" value="39%" delta={{ dir: "down", value: "2.1%" }} />
          <StatRow label="Tablet" value="3%" />
        </div>
      </div>
      <button
        type="button"
        onClick={() => setVisitors((v) => v + Math.round(40 + Math.random() * 400))}
        className="h-8 justify-self-start rounded-md border px-3 text-sm font-medium transition-transform duration-(--duration-press) ease-out hover:bg-muted active:scale-[0.97]"
      >
        Simulate live update
      </button>
    </div>
  );
}

Props

PropTypeDefault
label*

What the figure is.

ReactNode—
value*

The formatted figure.

ReactNode—
delta

Signed change, rendered with Delta.

DeltaProps—
hint

Quiet context under the figure.

ReactNode—
tone

Colour the figure itself; reserve for counts that signal a problem or success.

"neutral" | "positive" | "negative""neutral"
size

Figure size.

"sm" | "md" | "lg""md"
valueKey

Identity for the update tick when value is a node.

string | number—

Polish

  • The figure ticks (a short opacity, blur and 0.3em rise via @starting-style) only when its value changes on the client; server render and hydration never animate.
  • The tick rises when a number grows and drops when it shrinks.
  • Reduced motion keeps the fade and drops the movement and blur.
  • Tabular digits so an updating figure doesn't jitter.
  • Brand label and ink classes replaced with shadcn foreground tokens and --positive / --negative.
  • StatStrip hides its outer rules at any column count with a 1px pull inside a clipping box.

Source

stat.tsx
"use client";

import { useState, type ReactNode } from "react";
import { Delta, type DeltaProps } from "@/components/ui/delta/delta";
import { cn } from "@/lib/utils";

export type StatDelta = Omit<DeltaProps, "className">;
export type StatTone = "neutral" | "positive" | "negative";

export type StatProps = {
  label: ReactNode;
  value: ReactNode;
  delta?: StatDelta;
  /** Quiet context under the figure: "of 50,000", "across 3 regions". */
  hint?: ReactNode;
  /**
   * Colour the figure itself. Reserve it for counts that mean something is
   * wrong or right; a plain count stays neutral so colour keeps its signal.
   */
  tone?: StatTone;
  size?: "sm" | "md" | "lg";
  /**
   * Identity of the figure for the update tick. Defaults to `value` when it is
   * a string or number; pass it when `value` is a node.
   */
  valueKey?: string | number;
  /** A meter or sparkline that belongs to this figure. */
  children?: ReactNode;
  className?: string;
};

const VALUE_SIZE = {
  sm: "text-base",
  md: "text-2xl tracking-tight",
  lg: "text-3xl tracking-[-0.03em]",
} as const;

const TONE: Record<StatTone, string> = {
  neutral: "text-foreground",
  positive: "text-positive",
  negative: "text-negative",
};

// The figure ticks in from the side it moved toward. It only runs when the
// value changes on the client: the server render and hydration mount with no
// starting style, so a page full of stats never animates on first paint.
const TICK =
  "inline-block transition-[opacity,transform,filter] duration-(--duration-popover,180ms) ease-out starting:opacity-0 starting:blur-[2px] motion-reduce:starting:translate-y-0 motion-reduce:starting:blur-none";
const TICK_DIR = { up: "starting:translate-y-[0.3em]", down: "starting:-translate-y-[0.3em]" } as const;

/** Count client-side changes of `key` and which way a numeric key moved. */
export function useValueTick(key: string | number | undefined) {
  const [state, setState] = useState({ key, tick: 0, dir: "up" as "up" | "down" });
  if (key !== state.key) {
    const dir = typeof key === "number" && typeof state.key === "number" && key < state.key ? "down" : "up";
    // Adjusting state during render: React re-renders before painting.
    setState({ key, tick: state.tick + 1, dir });
  }
  return state;
}

/**
 * Label, figure, delta: the house unit for a number shown on its own. The
 * figure is tabular so digits don't shuffle when it updates.
 */
export function Stat({ label, value, delta, hint, tone = "neutral", size = "md", valueKey, children, className }: StatProps) {
  const key = valueKey ?? (typeof value === "string" || typeof value === "number" ? value : undefined);
  const { tick, dir } = useValueTick(key);

  return (
    <div data-slot="stat" className={cn("min-w-0", className)}>
      <p className="truncate text-xs font-medium text-muted-foreground">{label}</p>
      <p className={cn("mt-1.5 leading-none font-semibold tabular-nums", VALUE_SIZE[size], TONE[tone])}>
        <span key={tick} data-tick={tick > 0 || undefined} className={cn(tick > 0 && [TICK, TICK_DIR[dir]])}>
          {value}
        </span>
      </p>
      {delta || hint ? (
        <div className="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1">
          {delta ? <Delta {...delta} /> : null}
          {hint ? <span className="text-xs text-muted-foreground tabular-nums">{hint}</span> : null}
        </div>
      ) : null}
      {children ? <div className="mt-3">{children}</div> : null}
    </div>
  );
}

const COLUMNS = {
  2: "sm:grid-cols-2",
  3: "sm:grid-cols-3",
  4: "sm:grid-cols-2 lg:grid-cols-4",
  6: "sm:grid-cols-3 lg:grid-cols-6",
} as const;

export type StatStripProps = {
  items: (StatProps & { id?: string })[];
  columns?: keyof typeof COLUMNS;
  /** Render as a standalone card. Leave off inside a Panel. */
  surface?: boolean;
  size?: StatProps["size"];
  className?: string;
};

/**
 * A row of figures split by hairlines. Each cell draws its own left and top
 * border and the grid is pulled up and left by a pixel inside a clipping box,
 * so no outer edge or stray rule shows at any column count or wrap point.
 */
export function StatStrip({ items, columns = 4, surface = false, size = "md", className }: StatStripProps) {
  return (
    <div data-slot="stat-strip" className={cn("overflow-hidden", surface && "rounded-xl border bg-card", className)}>
      <div className={cn("-mt-px -ml-px grid grid-cols-2", COLUMNS[columns])}>
        {items.map(({ id, className: itemClass, ...item }, i) => (
          <Stat
            key={id ?? (typeof item.label === "string" ? item.label : i)}
            {...item}
            size={item.size ?? size}
            className={cn("border-t border-l px-5 py-4 sm:px-6 sm:py-5", itemClass)}
          />
        ))}
      </div>
    </div>
  );
}

export type StatRowProps = {
  label: ReactNode;
  value: ReactNode;
  delta?: StatDelta;
  hint?: ReactNode;
  className?: string;
};

/** One figure on one line, for dense lists where a full Stat would shout. */
export function StatRow({ label, value, delta, hint, className }: StatRowProps) {
  return (
    <div data-slot="stat-row" className={cn("flex items-center justify-between gap-4 text-sm", className)}>
      <span className="min-w-0 truncate text-muted-foreground">{label}</span>
      <span className="flex shrink-0 items-center gap-2">
        <span className="font-medium text-foreground tabular-nums">{value}</span>
        {hint ? <span className="text-xs text-muted-foreground tabular-nums">{hint}</span> : null}
        {delta ? <Delta {...delta} /> : null}
      </span>
    </div>
  );
}

Extracted from Vesrelle/components/data/stat.tsx at 4619651.