dxbh-uiGitHub

Sparkline

A trend line with nothing around it, for a tile where the shape matters and the figure is printed beside it. Server-renderable, no chart library.

Preview

Requests

48.2k

Conversion

3.9%

Error rate

1.4%

Install

npx shadcn@latest add @dxbh-ui/sparkline

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 { Sparkline } from "@/components/ui/sparkline/sparkline";

const rows = [
  { label: "Requests", value: "48.2k", tone: "neutral" as const, values: [31, 34, 33, 38, 36, 41, 44, 43, 47, 48] },
  { label: "Conversion", value: "3.9%", tone: "positive" as const, values: [3.1, 3.0, 3.3, 3.2, 3.4, 3.6, 3.5, 3.7, 3.8, 3.9] },
  { label: "Error rate", value: "1.4%", tone: "negative" as const, values: [0.6, 0.7, 0.6, 0.8, 0.9, 1.1, 1.0, 1.2, 1.3, 1.4] },
];

export default function SparklineDemo() {
  return (
    <div className="grid w-full max-w-md gap-3">
      {rows.map((row) => (
        <div key={row.label} className="flex items-center gap-4 rounded-lg border bg-card px-4 py-3">
          <div className="w-24 shrink-0">
            <p className="text-xs text-muted-foreground">{row.label}</p>
            <p className="text-lg font-semibold tabular-nums">{row.value}</p>
          </div>
          <Sparkline values={row.values} tone={row.tone} className="h-9" />
        </div>
      ))}
    </div>
  );
}

Props

PropTypeDefault
values*

The series, oldest first.

number[]—
tone

Ink colour.

"neutral" | "positive" | "negative""neutral"
fill

Faint area under the line.

booleantrue
marker

Dot on the latest point.

booleantrue
ariaLabel

Describe the trend when nothing beside it does.

string—

Polish

  • Brand inks replaced with currentColor and the shared --positive / --negative tokens.
  • Never animates, on first paint or after: data people read doesn't move.
  • End marker is HTML positioned by the same unit fractions as the path, so it stays round at any width.
  • Non-finite values are dropped instead of drawing NaN paths.
  • Hidden from assistive tech unless given an ariaLabel, since the figure beside it already speaks.

Source

sparkline.tsx
import { useId } from "react";
import { areaPath, chartDomain, seriesToPoints, smoothPath } from "@/lib/chart-geometry";
import { cn } from "@/lib/utils";

const W = 100;
const H = 32;

export type SparklineTone = "neutral" | "positive" | "negative";

export type SparklineProps = {
  values: number[];
  tone?: SparklineTone;
  /** Faint area under the line. */
  fill?: boolean;
  /** Dot on the latest point. */
  marker?: boolean;
  /**
   * Accessible description, e.g. "Revenue, rising over 30 days". Omit when
   * the figure it illustrates is printed next to it; the line is then hidden
   * from assistive tech.
   */
  ariaLabel?: string;
  className?: string;
};

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

/**
 * The trend line with nothing around it: no axis, no grid, no interaction.
 * Same geometry as TrendChart, so it reads as a small version of the big
 * chart. Server-renderable, and it never animates: people read it, they
 * don't watch it.
 */
export function Sparkline({ values, tone = "neutral", fill = true, marker = true, ariaLabel, className }: SparklineProps) {
  const gradientId = useId();
  const finite = values.filter(Number.isFinite);
  if (finite.length === 0) return null;

  const points = seriesToPoints(finite, chartDomain([finite]));
  const last = points[points.length - 1];

  return (
    <div
      data-slot="sparkline"
      role={ariaLabel ? "img" : undefined}
      aria-label={ariaLabel}
      aria-hidden={ariaLabel ? undefined : true}
      className={cn("relative h-10 w-full", TONE[tone], className)}
    >
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" className="absolute inset-0 size-full overflow-visible">
        {fill ? (
          <>
            <defs>
              <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="currentColor" stopOpacity="0.16" />
                <stop offset="100%" stopColor="currentColor" stopOpacity="0" />
              </linearGradient>
            </defs>
            <path d={areaPath(points, W, H)} fill={`url(#${gradientId})`} />
          </>
        ) : null}
        <path
          d={smoothPath(points, W, H)}
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
          vectorEffect="non-scaling-stroke"
        />
      </svg>
      {marker ? (
        // HTML, so it stays round however the SVG stretches.
        <span
          className="absolute size-[5px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-current"
          style={{ left: `${last.x * 100}%`, top: `${last.y * 100}%` }}
        />
      ) : null}
    </div>
  );
}

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