dxbh-uiGitHub

Trend Chart

A smoothed line chart with no chart library. Hover, touch or arrow-key through it and a crosshair and tooltip follow 1:1.

Preview
Revenue
2026
Target
This year vs last year
20262025

Install

npx shadcn@latest add @dxbh-ui/trend-chart

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 { TrendChart } from "@/components/ui/trend-chart/trend-chart";

const labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const revenue = [42, 45, 44, 51, 49, 56, 61, 59, 66, 71, 69, 78].map((v) => v * 1000);
const lastYear = [38, 40, 41, 43, 44, 47, 49, 50, 52, 55, 57, 60].map((v) => v * 1000);

export default function TrendChartDemo() {
  return (
    <div className="grid w-full max-w-xl gap-10">
      <TrendChart
        title="Revenue"
        meta="2026"
        values={revenue}
        label="Revenue"
        labels={labels}
        format="currency"
        benchmark={{ value: 60000, label: "Target" }}
        ariaLabel="Monthly revenue in 2026, rising from $42,000 in January to $78,000 in December"
      />
      <TrendChart
        title="This year vs last year"
        series={[
          { key: "this", label: "2026", values: revenue },
          { key: "last", label: "2025", values: lastYear },
        ]}
        labels={labels}
        format="compact"
        height="sm"
        ariaLabel="Monthly revenue, 2026 compared with 2025; 2026 is ahead every month"
      />
    </div>
  );
}

Props

PropTypeDefault
values

A single series. Use series for several.

number[]—
series

Several lines, up to four distinct styles.

{ key: string; label: string; values: number[] }[]—
ariaLabel*

What the chart shows and its headline.

string—
labels

One x label per point.

string[]—
format

How readout values print.

"number" | "integer" | "compact" | "currency" | "percent" | "multiplier""number"
formatOptions

Locale and currency for formatting.

{ locale?: string; currency?: string }—
benchmark

Dashed reference line.

{ value: number; label?: string }—
height

Plot height.

"sm" | "md" | "lg""md"
interactive

Pointer and keyboard inspection.

booleantrue
reveal

Wipe in on first view. Marketing surfaces only.

booleanfalse
onActiveChange

Inspected point changed.

(index: number | null) => void—

Polish

  • Crosshair, point rings and tooltip position follow the pointer 1:1 with no transition: lag would read as a slow chart.
  • The tooltip fades in once (popover duration); re-showing it within 400ms skips the fade, like warm toolbar tooltips.
  • Keyboard inspection (arrows, Home, End, Escape) never fades in.
  • The tooltip flips to the far side of the crosshair so it never covers the point it describes.
  • Readout announced through a polite status region; the chart's accessible name stays put.
  • Series told apart by ink weight and dash with shadcn foreground tokens, not brand hues.
  • Optional reveal wipes in with clip-path once on first intersection, for marketing pages only; reduced motion makes it a fade.
  • Data doesn't animate on first paint by default.
  • touch-pan-y keeps vertical page scrolling working over the chart on touch.

Source

trend-chart.tsx
"use client";

import {
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
  type KeyboardEvent,
  type PointerEvent,
  type ReactNode,
} from "react";
import {
  areaPath,
  axisIndices,
  chartDomain,
  indexToX,
  nearestIndex,
  seriesToPoints,
  smoothPath,
  valueToY,
} from "@/lib/chart-geometry";
import { formatValue, type FormatOptions, type ValueFormat } from "@/lib/chart-format";
import { cn } from "@/lib/utils";

export type TrendSeries = { key: string; label: string; values: number[] };

const W = 1000;
const H = 300;

/**
 * Series are told apart by ink weight and dash, not hue, so the chart stays
 * neutral inside any palette. Past four the styles repeat; past four a reader
 * can't hold the lines apart anyway.
 */
const SERIES_STYLE = [
  { ink: "text-foreground", width: 2, dash: undefined },
  { ink: "text-muted-foreground", width: 1.5, dash: undefined },
  { ink: "text-foreground", width: 1.5, dash: "6 4" },
  { ink: "text-muted-foreground", width: 1.5, dash: "2 4" },
] as const;

const style = (i: number) => SERIES_STYLE[i % SERIES_STYLE.length];

const HEIGHT = { sm: "h-16", md: "h-28", lg: "h-48" } as const;

/** Re-showing the tooltip within this window skips its fade, like a toolbar's tooltips. */
const SKIP_DELAY_MS = 400;

function Swatch({ index }: { index: number }) {
  const s = style(index);
  return (
    <svg viewBox="0 0 16 4" className={cn("h-1 w-4 shrink-0 overflow-visible", s.ink)} aria-hidden="true">
      <line x1="0" y1="2" x2="16" y2="2" stroke="currentColor" strokeWidth={s.width} strokeDasharray={s.dash} strokeLinecap="round" />
    </svg>
  );
}

export type TrendChartProps = {
  /** Several lines. Use `values` for the common single-line case. */
  series?: TrendSeries[];
  values?: number[];
  /** Name of the `values` series, used in the readout. */
  label?: string;
  /** One x label per point (dates, months). */
  labels?: string[];
  format?: ValueFormat;
  formatOptions?: FormatOptions;
  title?: ReactNode;
  /** Quiet context on the right of the heading. */
  meta?: ReactNode;
  /** A dashed reference line, always kept inside the domain. */
  benchmark?: { value: number; label?: string };
  height?: keyof typeof HEIGHT;
  /** Print x labels under the chart. */
  axis?: boolean;
  /** Area under the line. Defaults on for one series, off for several. */
  fill?: boolean;
  /** Dot on the latest point of the first series. */
  marker?: boolean;
  /** Pointer and keyboard scrubbing with a crosshair and tooltip. */
  interactive?: boolean;
  /**
   * Wipe the lines in the first time the chart scrolls into view. For rarely
   * seen marketing surfaces only; dashboards are seen too often to animate.
   */
  reveal?: boolean;
  /** Describes the chart for assistive tech: what it shows and its headline. */
  ariaLabel: string;
  emptyLabel?: ReactNode;
  /** Called when the inspected point changes (null when inspection ends). */
  onActiveChange?: (index: number | null) => void;
  className?: string;
};

/**
 * A smoothed line chart with no chart library.
 *
 * Point at it, or focus it and use the arrow keys, and a crosshair and tooltip
 * follow 1:1: nothing in the scrub transitions, because lag reads as a slow
 * chart. The tooltip fades in the first time and appears instantly after that
 * while you keep inspecting. Markers and the crosshair are HTML positioned by
 * the same unit fractions as the SVG, so they stay round at any width.
 */
export function TrendChart({
  series: seriesProp,
  values,
  label = "Value",
  labels,
  format = "number",
  formatOptions,
  title,
  meta,
  benchmark,
  height = "md",
  axis = true,
  fill,
  marker = true,
  interactive = true,
  reveal = false,
  ariaLabel,
  emptyLabel = "No data for this range yet.",
  onActiveChange,
  className,
}: TrendChartProps) {
  const series = useMemo<TrendSeries[]>(
    () => seriesProp ?? [{ key: "value", label, values: values ?? [] }],
    [seriesProp, values, label],
  );
  const count = Math.max(0, ...series.map((s) => s.values.length));
  const empty = count === 0;
  const live = interactive && !empty;
  const showFill = fill ?? series.length === 1;
  const benchValue = benchmark?.value;

  const geometry = useMemo(() => {
    const domain = chartDomain(
      series.map((s) => s.values),
      benchValue === undefined ? [] : [benchValue],
    );
    return { domain, lines: series.map((s) => seriesToPoints(s.values, domain)) };
  }, [series, benchValue]);

  const gradientId = useId();
  const tooltipId = useId();

  // --- inspection ------------------------------------------------------------
  const [active, setActiveState] = useState<number | null>(null);
  // Whether this showing of the tooltip should fade in, decided when it opens.
  const [fadeIn, setFadeIn] = useState(true);
  const hiddenAt = useRef(-Infinity);

  // Keyboard inspection never fades: keyboard actions repeat, and motion makes them feel slow.
  const setActive = (next: number | null, fade = true) => {
    if (next === active) return;
    if (active === null && next !== null) setFadeIn(fade && performance.now() - hiddenAt.current > SKIP_DELAY_MS);
    if (active !== null && next === null) hiddenAt.current = performance.now();
    setActiveState(next);
    onActiveChange?.(next);
  };

  // Clamp after the data shrinks under an inspected point.
  const index = active === null || empty ? null : Math.min(active, count - 1);

  const fromPointer = (e: PointerEvent<HTMLDivElement>) => {
    const rect = e.currentTarget.getBoundingClientRect();
    return nearestIndex((e.clientX - rect.left) / (rect.width || 1), count);
  };

  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    const last = count - 1;
    const current = index ?? last;
    let next: number | null | undefined;
    if (e.key === "ArrowLeft" || e.key === "ArrowDown") next = Math.max(0, index === null ? last : current - 1);
    else if (e.key === "ArrowRight" || e.key === "ArrowUp") next = Math.min(last, index === null ? last : current + 1);
    else if (e.key === "Home") next = 0;
    else if (e.key === "End") next = last;
    else if (e.key === "Escape" && index !== null) next = null;
    if (next === undefined) return;
    e.preventDefault();
    setActive(next, false);
  };

  // --- reveal, once, on first intersection -------------------------------------
  const plotRef = useRef<HTMLDivElement>(null);
  const [revealed, setRevealed] = useState(!reveal);
  useEffect(() => {
    if (!reveal || revealed) return;
    const el = plotRef.current;
    if (!el || typeof IntersectionObserver === "undefined") {
      setRevealed(true);
      return;
    }
    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry?.isIntersecting) {
          setRevealed(true);
          io.disconnect();
        }
      },
      { threshold: 0.4 },
    );
    io.observe(el);
    return () => io.disconnect();
  }, [reveal, revealed]);

  // --- derived drawing ---------------------------------------------------------
  const inspecting = live && index !== null;
  const x = index === null ? 0 : indexToX(index, count);
  const first = geometry.lines[0] ?? [];
  const lastPoint = first[first.length - 1];
  const benchY = benchValue === undefined ? null : valueToY(benchValue, geometry.domain);
  const ticks = axis && labels ? axisIndices(Math.min(labels.length, count)) : [];
  const fmt = (v: number) => formatValue(v, format, formatOptions);
  const pointLabel = (i: number) => labels?.[i] ?? `Point ${i + 1}`;

  const readout =
    index === null
      ? ""
      : `${pointLabel(index)}: ${series
          .filter((s) => s.values[index] !== undefined)
          .map((s) => (series.length > 1 ? `${s.label} ${fmt(s.values[index])}` : fmt(s.values[index])))
          .join(", ")}`;

  return (
    <figure data-slot="trend-chart" className={cn("min-w-0", className)}>
      {title || meta ? (
        <div className="flex items-baseline justify-between gap-4">
          {title ? <figcaption className="min-w-0 truncate text-sm font-medium text-foreground">{title}</figcaption> : <span />}
          {meta ? <div className="shrink-0 text-xs text-muted-foreground tabular-nums">{meta}</div> : null}
        </div>
      ) : null}

      <div
        ref={plotRef}
        role={live ? "application" : "img"}
        aria-roledescription={live ? "chart" : undefined}
        aria-label={live ? `${ariaLabel}. Use the arrow keys to inspect points.` : ariaLabel}
        aria-describedby={inspecting ? tooltipId : undefined}
        tabIndex={live ? 0 : undefined}
        onPointerMove={live ? (e) => setActive(fromPointer(e)) : undefined}
        onPointerDown={live ? (e) => setActive(fromPointer(e)) : undefined}
        onPointerLeave={live ? (e) => e.pointerType !== "touch" && setActive(null) : undefined}
        onPointerCancel={live ? () => setActive(null) : undefined}
        onKeyDown={live ? onKeyDown : undefined}
        onBlur={live ? () => setActive(null) : undefined}
        className={cn(
          "relative w-full rounded-sm outline-none",
          (title || meta) && "mt-4",
          HEIGHT[height],
          live && "cursor-crosshair touch-pan-y select-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-background",
        )}
      >
        {/* The grid draws even when empty so the frame keeps its shape. */}
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" className="absolute inset-0 size-full text-border" aria-hidden="true">
          {[0.25, 0.5, 0.75].map((t) => (
            <line key={t} x1="0" y1={H * t} x2={W} y2={H * t} stroke="currentColor" strokeWidth="1" vectorEffect="non-scaling-stroke" />
          ))}
        </svg>

        {empty ? (
          <p className="absolute inset-0 grid place-items-center text-xs text-muted-foreground">{emptyLabel}</p>
        ) : (
          <div
            data-slot="trend-chart-plot"
            data-revealed={revealed}
            className={cn(
              "absolute inset-0",
              reveal &&
                "transition-[clip-path,opacity] duration-[900ms] ease-out motion-reduce:duration-(--duration-modal,240ms) data-[revealed=false]:[clip-path:inset(0_100%_0_0)] data-[revealed=false]:motion-reduce:[clip-path:none] data-[revealed=false]:motion-reduce:opacity-0",
            )}
          >
            <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" className="absolute inset-0 size-full overflow-visible" aria-hidden="true">
              {showFill && first.length > 0 ? (
                <>
                  <defs>
                    <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="currentColor" stopOpacity="0.14" />
                      <stop offset="100%" stopColor="currentColor" stopOpacity="0" />
                    </linearGradient>
                  </defs>
                  <path d={areaPath(first, W, H)} fill={`url(#${gradientId})`} className="text-foreground" />
                </>
              ) : null}

              {benchY !== null ? (
                <line
                  x1="0"
                  y1={benchY * H}
                  x2={W}
                  y2={benchY * H}
                  stroke="currentColor"
                  strokeWidth="1.5"
                  strokeDasharray="4 4"
                  vectorEffect="non-scaling-stroke"
                  className="text-muted-foreground/60"
                />
              ) : null}

              {/* Back to front, so the primary series sits on top. */}
              {series
                .map((s, i) => ({ s, i }))
                .reverse()
                .map(({ s, i }) => {
                  const st = style(i);
                  return (
                    <path
                      key={s.key}
                      d={smoothPath(geometry.lines[i], W, H)}
                      fill="none"
                      stroke="currentColor"
                      strokeWidth={st.width}
                      strokeDasharray={st.dash}
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      vectorEffect="non-scaling-stroke"
                      className={st.ink}
                    />
                  );
                })}
            </svg>

            {benchY !== null && benchmark?.label ? (
              <span
                className="absolute right-0 -translate-y-full pb-1 text-[10px] font-medium text-muted-foreground"
                style={{ top: `${benchY * 100}%` }}
              >
                {benchmark.label}
              </span>
            ) : null}

            {marker && lastPoint && !inspecting ? (
              <span
                data-slot="trend-chart-marker"
                className="absolute size-[7px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground"
                style={{ left: `${lastPoint.x * 100}%`, top: `${lastPoint.y * 100}%` }}
                aria-hidden="true"
              />
            ) : null}
          </div>
        )}

        {inspecting ? (
          // No transitions on anything that moves with the pointer.
          <div className="pointer-events-none absolute inset-0" aria-hidden="true">
            <span data-slot="trend-chart-crosshair" className="absolute inset-y-0 w-px -translate-x-1/2 bg-border" style={{ left: `${x * 100}%` }} />
            {geometry.lines.map((pts, i) => {
              const p = pts[index];
              if (!p) return null;
              return (
                <span
                  key={series[i].key}
                  className={cn("absolute size-[9px] -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-background bg-current", style(i).ink)}
                  style={{ left: `${p.x * 100}%`, top: `${p.y * 100}%` }}
                />
              );
            })}
          </div>
        ) : null}

        {inspecting ? (
          <div
            id={tooltipId}
            role="tooltip"
            data-slot="trend-chart-tooltip"
            data-fade={fadeIn || undefined}
            className={cn(
              "pointer-events-none absolute top-0 z-10 rounded-md border bg-popover px-2.5 py-1.5 text-xs text-popover-foreground shadow-md whitespace-nowrap",
              // Flip to the far side of the crosshair so it never covers the point it describes.
              x > 0.5 ? "-translate-x-[calc(100%+10px)]" : "translate-x-[10px]",
              fadeIn && "transition-opacity duration-(--duration-popover,180ms) ease-out starting:opacity-0",
            )}
            style={{ left: `${x * 100}%` }}
          >
            <div className="text-muted-foreground">{pointLabel(index)}</div>
            <div className="mt-0.5 flex flex-col gap-0.5">
              {series.map((s, i) =>
                s.values[index] === undefined ? null : (
                  <span key={s.key} className="flex items-center gap-1.5">
                    {series.length > 1 ? (
                      <>
                        <Swatch index={i} />
                        <span className="text-muted-foreground">{s.label}</span>
                      </>
                    ) : null}
                    <span className="ml-auto font-medium text-foreground tabular-nums">{fmt(s.values[index])}</span>
                  </span>
                ),
              )}
            </div>
          </div>
        ) : null}
      </div>

      {live ? (
        <span role="status" aria-live="polite" className="sr-only">
          {readout}
        </span>
      ) : null}

      {ticks.length > 0 && labels ? (
        <div className="relative mt-2 h-4 text-[11px] text-muted-foreground tabular-nums" aria-hidden="true">
          {ticks.map((i, n) => (
            <span
              key={i}
              className={cn(
                "absolute top-0 whitespace-nowrap",
                ticks.length === 1 ? "-translate-x-1/2" : n === 0 ? "translate-x-0" : n === ticks.length - 1 ? "-translate-x-full" : "-translate-x-1/2",
              )}
              style={{ left: `${indexToX(i, count) * 100}%` }}
            >
              {labels[i]}
            </span>
          ))}
        </div>
      ) : null}

      {series.length > 1 ? (
        <div className="mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-muted-foreground">
          {series.map((s, i) => (
            <span key={s.key} className="flex items-center gap-1.5">
              <Swatch index={i} />
              {s.label}
            </span>
          ))}
        </div>
      ) : null}
    </figure>
  );
}

Extracted from Vesrelle/components/data/trend-chart.tsx at 4619651.