Skip to content
Thrum

Sparkline

A word-sized trend line with no axes and built-in hover scrubbing. Put it in a table cell or beside a number to show direction at a glance and inspect points on demand. When readers need axes or a full data table, use the area chart.

Install

npx shadcn@latest add https://thrumui.dev/r/sparkline.json

Adds components/ui/sparkline.tsx and installs motion. Nothing else in your project changes.

import { Sparkline } from "@/components/ui/sparkline";

Data shape

Type
readonly (number | null)[] // oldest first; null leaves a gap
Sample
[12, 14, 13, null, 19, 18, 22]

Props

PropTypeDefaultDescription
datareadonly (number | null)[]RequiredValues in order, oldest first.
labelstringRequiredWhat the line measures. Screen readers hear it with the first, last, lowest and highest value.
areabooleanDefault falseFill the area under the line.
endDotbooleanDefault trueMark the latest value with a dot.
interactivebooleanDefault trueScrub points on pointer hover (and arrow keys when tabIndex is set) with a compact floating readout.
tabIndexnumber–Make a standalone sparkline focusable (for example 0) for arrow-key scrubbing. Left unset by default so table cells and cards stay uncluttered.
soundbooleanDefault truePlay a soft tick as the pointer or keyboard cursor moves between points, if the visitor has sound on.
colorstringDefault var(--chart-1)Any CSS colour.
formatIntl.NumberFormatOptionsDefault compactHow numbers are written in the screen-reader summary.
localestringDefault "en-US"Locale for number formatting.
classNamestring–Sets the size. The default is 96 by 32 pixels.

Motion and sound

Motion

  • First draw: revealed left to right in 700 ms at constant speed. The end dot fades in when the line arrives.
  • New data with the same number of points: the line morphs in 400 ms with no overshoot.
  • Reduced motion: the line appears complete and changes instantly.

Sound

  • A soft tick when scrubbing across points by pointer or keyboard.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • Exposed as a single image named with the label and a summary: “Signups, last 7 days: starts at 12, ends at 22, low 12, high 22”.
  • Pointer scrubbing is on by default for quick inspection; pass tabIndex={0} on a standalone sparkline for keyboard arrow scrubbing while keeping table cells and cards free of extra tab stops.
  • It renders on the server at its final size, so it never shifts the row it sits in.
KeysAction
TabFocus the sparkline when tabIndex={0} is set. Opens the readout on the latest point.
← →Move between points.
Home / EndJump to the first or last point.
EscHide the readout.

Source

components/ui/sparkline.tsx
"use client";

import { useId, useRef, useState, type KeyboardEvent } from "react";
import { motion } from "motion/react";

import { cn } from "@/lib/utils";
import { areaPath, extent, formatValue, linePath, nearestIndex, scaleLinear, seriesColor } from "@/lib/thrum-chart";
import { DUR, FAST, REVEAL, SPRING, useReducedMotion } from "@/lib/thrum-motion";
import { play } from "@/lib/thrum-sound";

export type SparklineProps = {
  /** Values in order, oldest first. `null` leaves a gap in the line. */
  data: readonly (number | null)[];
  /** What the line measures, for screen readers. Example: "Revenue, last 30 days". */
  label: string;
  /** Fill the area under the line. */
  area?: boolean;
  /** Mark the latest value with a dot. */
  endDot?: boolean;
  /** Scrub values on pointer hover (and keyboard arrows when `tabIndex` is set) with a compact floating readout. */
  interactive?: boolean;
  /** Make a standalone sparkline focusable (for example `0`) so keyboard users can scrub points. Left unset by default for table cells and cards. */
  tabIndex?: number;
  /** Play a soft tick as the pointer or keyboard cursor moves between points, if the visitor has sound on. */
  sound?: boolean;
  /** Any CSS colour. Defaults to the theme's first chart colour. */
  color?: string;
  /** How numbers are written in the screen-reader summary. */
  format?: Intl.NumberFormatOptions;
  locale?: string;
  /** Size it with classes. The default is 96 by 32 pixels. */
  className?: string;
};

// The line is drawn in a 100 by 100 box and stretched to the element, so it renders on the server
// and never shifts layout. `vector-effect` keeps the stroke the same thickness however it is stretched.
const BOX = 100;

/**
 * A small trend line with no axes, for a table cell or a stat card.
 * It draws itself left to right once, then morphs when the data changes.
 */
export function Sparkline({ data, label, area = false, endDot = true, interactive = true, tabIndex, sound = true, color, format, locale, className }: SparklineProps) {
  const clipId = useId();
  const reduced = useReducedMotion();
  const stroke = color ?? seriesColor(0);
  const [hovered, setHovered] = useState<number | null>(null);
  const lastHovered = useRef<number | null>(null);

  const [min, max] = extent(data);
  const x = scaleLinear([0, Math.max(1, data.length - 1)], [0, BOX]);
  const y = scaleLinear([min, max], [BOX, 0]);
  const points = data.map((v, i) => (typeof v === "number" && Number.isFinite(v) ? { x: data.length === 1 ? BOX / 2 : x(i), y: y(v) } : null));
  const finite = data.filter((v): v is number => typeof v === "number" && Number.isFinite(v));
  const xs = points.map((p, i) => (p ? p.x : data.length === 1 ? BOX / 2 : x(i)));
  const last = points.findLast((p) => p !== null) ?? null;

  const line = linePath(points);
  const fill = area ? areaPath(points, BOX) : "";
  const say = (v: number) => formatValue(v, format, locale);
  const summary = finite.length
    ? `${label}: starts at ${say(finite[0])}, ends at ${say(finite[finite.length - 1])}, low ${say(Math.min(...finite))}, high ${say(Math.max(...finite))}`
    : `${label}: no data`;

  const morph = reduced ? { duration: 0 } : SPRING.data;
  const finiteIndices: number[] = [];
  points.forEach((p, i) => {
    if (p) finiteIndices.push(i);
  });
  const activePoint = hovered !== null ? points[hovered] ?? null : null;
  const activeValue = hovered !== null ? data[hovered] : null;
  const canScrub = interactive && finiteIndices.length > 0;

  const selectPoint = (next: number | null) => {
    if (next === lastHovered.current) return;
    lastHovered.current = next;
    setHovered(next);
    if (sound && next !== null) play("tick");
  };

  const onKeyDown = (event: KeyboardEvent<HTMLSpanElement>) => {
    if (!canScrub) return;
    const pos = hovered !== null ? finiteIndices.indexOf(hovered) : -1;
    if (event.key === "ArrowLeft" || event.key === "ArrowDown") {
      event.preventDefault();
      selectPoint(pos === -1 ? finiteIndices[finiteIndices.length - 1] : finiteIndices[Math.max(0, pos - 1)]);
    } else if (event.key === "ArrowRight" || event.key === "ArrowUp") {
      event.preventDefault();
      selectPoint(pos === -1 ? finiteIndices[finiteIndices.length - 1] : finiteIndices[Math.min(finiteIndices.length - 1, pos + 1)]);
    } else if (event.key === "Home") {
      event.preventDefault();
      selectPoint(finiteIndices[0]);
    } else if (event.key === "End") {
      event.preventDefault();
      selectPoint(finiteIndices[finiteIndices.length - 1]);
    } else if (event.key === "Escape") {
      selectPoint(null);
    }
  };

  return (
    <span
      data-slot="sparkline"
      role="img"
      aria-label={summary}
      tabIndex={canScrub ? tabIndex : undefined}
      onKeyDown={canScrub && tabIndex !== undefined ? onKeyDown : undefined}
      onFocus={
        canScrub && tabIndex !== undefined
          ? () => {
              if (lastHovered.current === null) selectPoint(finiteIndices[finiteIndices.length - 1]);
            }
          : undefined
      }
      onBlur={canScrub && tabIndex !== undefined ? () => selectPoint(null) : undefined}
      onPointerMove={
        canScrub
          ? (event) => {
              const rect = event.currentTarget.getBoundingClientRect();
              if (rect.width <= 0) return;
              const pct = ((event.clientX - rect.left) / rect.width) * BOX;
              const idx = nearestIndex(xs, pct);
              selectPoint(idx >= 0 && points[idx] ? idx : null);
            }
          : undefined
      }
      onPointerLeave={interactive ? () => selectPoint(null) : undefined}
      className={cn(
        "relative inline-block h-8 w-24 align-middle",
        canScrub && "cursor-crosshair",
        canScrub && tabIndex !== undefined && "rounded-xs outline-none focus-visible:ring-2 focus-visible:ring-ring",
        className,
      )}
    >
      <svg viewBox={`0 0 ${BOX} ${BOX}`} preserveAspectRatio="none" className="absolute inset-0 size-full overflow-visible" aria-hidden="true">
        <defs>
          <clipPath id={clipId}>
            {/* The wipe: a recorder pen moving at constant speed. Taller and wider than the box so the stroke is never cut. */}
            <motion.rect
              x={-10}
              y={-50}
              height={200}
              initial={reduced ? false : { width: 0 }}
              animate={{ width: BOX + 20 }}
              transition={reduced ? { duration: 0 } : REVEAL}
            />
          </clipPath>
        </defs>
        <g clipPath={`url(#${clipId})`}>
          {fill && <motion.path d={fill} initial={false} animate={{ d: fill }} transition={morph} fill={stroke} fillOpacity={0.14} />}
          <motion.path
            d={line}
            initial={false}
            animate={{ d: line }}
            transition={morph}
            fill="none"
            stroke={stroke}
            strokeWidth={1.5}
            strokeLinecap="round"
            strokeLinejoin="round"
            vectorEffect="non-scaling-stroke"
          />
        </g>
      </svg>
      {endDot && last && !activePoint && (
        // An HTML dot, placed by percentage, so it stays round when the line is stretched.
        <motion.span
          aria-hidden="true"
          className="pointer-events-none absolute size-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full ring-1 ring-[var(--thrum-base-background,var(--background))]"
          style={{ backgroundColor: stroke }}
          initial={reduced ? false : { opacity: 0, left: `${last.x}%`, top: `${last.y}%` }}
          animate={{ opacity: 1, left: `${last.x}%`, top: `${last.y}%` }}
          transition={reduced ? { duration: 0 } : { ...morph, opacity: { ...FAST, delay: DUR.reveal } }}
        />
      )}
      {activePoint && typeof activeValue === "number" && (
        <>
          <span aria-hidden="true" className="pointer-events-none absolute inset-y-0 border-l border-foreground/30" style={{ left: `${activePoint.x}%` }} />
          <span
            aria-hidden="true"
            className="pointer-events-none absolute size-2 -translate-x-1/2 -translate-y-1/2 rounded-full ring-1 ring-[var(--thrum-base-background,var(--background))]"
            style={{ backgroundColor: stroke, left: `${activePoint.x}%`, top: `${activePoint.y}%` }}
          />
          <span
            aria-hidden="true"
            data-surface="floating"
            className="pointer-events-none absolute -top-7 z-20 -translate-x-1/2 rounded-sm border bg-popover px-1.5 py-0.5 font-mono text-[11px] leading-tight whitespace-nowrap text-popover-foreground shadow-sm tabular-nums"
            style={{ left: `${Math.min(92, Math.max(8, activePoint.x))}%` }}
          >
            {say(activeValue)}
          </span>
        </>
      )}
    </span>
  );
}

Files and dependencies

Adds
components/ui/sparkline.tsx
Packages
motion
Brings along
Chart foundationsMotion tokensSound engine

Changelog

  1. 1.0.0 · 2026-12-02First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor