Skip to content
Shaken UI
Sign in

Chart

Save

Line, area, and grouped bar charts in plain SVG with axes, gridlines, a hover crosshair and tooltip, a toggleable legend, and a draw-in entrance.

Category
Data display
Version
0.1.1
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Chart preview

Agent runs per week

Agent runs per week by outcome, September 22 to November 10
weekSucceededNeeded approvalFailed
Sep 2281212064
Sep 2990514158
Oct 687013371
Oct 131,03416049
Oct 201,12017242
Oct 271,08815855
Nov 31,24119038
Nov 101,30620431

Installation

npx @shakenui/cli add chart

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add chart --dry-run

Usage

chart-example.tsx
import { Chart } from "@/components/shaken/ui/chart";

const days = ["Nov 1", "Nov 2", "Nov 3", "Nov 4", "Nov 5", "Nov 6", "Nov 7", "Nov 8", "Nov 9", "Nov 10", "Nov 11", "Nov 12", "Nov 13", "Nov 14"];
const current = [18_400, 21_050, 19_870, 24_310, 26_920, 15_480, 13_960, 22_740, 25_160, 27_830, 26_410, 30_220, 31_870, 29_640];
const previous = [16_900, 18_200, 18_950, 20_400, 22_100, 14_300, 12_800, 19_600, 21_300, 22_900, 23_400, 24_100, 25_800, 24_900];

const data = days.map((day, i) => ({ day, requests: current[i]!, previous: previous[i]! }));
const total = current.reduce((sum, value) => sum + value, 0);

export default function ChartExample() {
  return (
    <section className="grid w-full max-w-2xl gap-4 rounded-xl border border-zinc-950/10 bg-white p-5 shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]">
      <header className="grid gap-1">
        <h3 className="text-sm font-medium text-zinc-600 dark:text-zinc-400">API requests</h3>
        <p className="flex items-baseline gap-2">
          <span className="text-2xl font-semibold tracking-tight text-zinc-950 tabular-nums dark:text-white">{total.toLocaleString("en-US")}</span>
          <span className="text-xs font-medium text-emerald-700 tabular-nums dark:text-emerald-400">+14.2% vs previous 14 days</span>
        </p>
      </header>
      <Chart
        type="area"
        label="API requests per day, November 1 to 14, compared with the previous 14 days"
        data={data}
        index="day"
        series={[
          { key: "requests", label: "This period" },
          { key: "previous", label: "Previous period", tone: "muted", dashed: true },
        ]}
        height={220}
      />
    </section>
  );
}

API

PropTypeDefaultDescription
type"line" | "area" | "bar""line"Chart kind. Bars group side by side per index.
dataRow[]—One object per x position.
indexkeyof Row—The field holding the x-axis label.
series{ key, label, tone?, dashed? }[]—Series to plot. tone is ink, sky, amber, emerald, violet, red, or muted; dashed suits forecasts and previous periods.
labelstring—Accessible name for the chart.
heightnumber240Plot height in pixels; width follows the container.
curve"smooth" | "linear""smooth"Monotone smoothing that never overshoots, or straight segments.
gridbooleantrueDotted gridlines at each y tick.
legendboolean—Legend whose entries toggle series. On by default for two or more series.
yTicksnumber4About how many y steps to draw.
valueFormatter / axisFormatter(value: number) => string—Tooltip and y-axis number formatting. The axis defaults to compact notation.
loadingbooleanfalseShows the frame with a loading note instead of marks.

Accessibility

  • The plot is focusable with a descriptive name; Left and Right arrows step through points, Home and End jump to the ends, Escape clears, and each step is announced in a polite live region.
  • A visually hidden table carries every value, so the data is available without the picture.
  • Legend entries are toggle buttons with aria-pressed; the last visible series cannot be hidden.
  • Lines draw in and bars grow once on mount; under reduced motion the marks appear without motion.
  • Series differ by color and, where needed, by dashing, and the tooltip names every series in text.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/chart.tsxchart
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/chart/0.1.1.json.

ui/chart.tsxShow
ui/chart.tsx
"use client";

import { type FocusEvent, type KeyboardEvent, type PointerEvent, useEffect, useId, useMemo, useRef, useState } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

// Series colors: ink first, then a few restrained hues. Each is a text color so SVG marks,
// legend swatches, and tooltip keys can all use `currentColor`.
const tones = {
  ink: "text-zinc-950 dark:text-white",
  sky: "text-sky-500",
  amber: "text-amber-500",
  emerald: "text-emerald-500",
  violet: "text-violet-500",
  red: "text-red-500",
  muted: "text-zinc-400 dark:text-zinc-500",
} as const;

export type ChartTone = keyof typeof tones;
const toneOrder: ChartTone[] = ["ink", "sky", "amber", "emerald", "violet", "muted"];

export interface ChartSeries {
  /** The row field that holds this series' numbers. */
  key: string;
  label: string;
  /** Color. Defaults to the next in the series order: ink, sky, amber, emerald, violet, muted. */
  tone?: ChartTone;
  /** Draws the line dashed, for a forecast or a previous period. Line and area charts only. */
  dashed?: boolean;
}

export interface ChartProps<Row extends Record<string, unknown>> {
  type?: "line" | "area" | "bar";
  data: Row[];
  /** The row field holding the x-axis label, for example `"month"`. */
  index: keyof Row & string;
  series: ChartSeries[];
  /** Accessible name, for example "Requests per day, last 14 days". */
  label: string;
  /** Plot height in pixels. Width follows the container. */
  height?: number;
  /** Line shape. `smooth` uses a monotone curve that never overshoots the data. */
  curve?: "smooth" | "linear";
  /** Horizontal gridlines at each y tick. */
  grid?: boolean;
  /** Shows the legend. Each entry toggles its series. Defaults to on for two or more series. */
  legend?: boolean;
  /** About how many y-axis steps to draw. */
  yTicks?: number;
  /** Formats values in the tooltip and screen reader output. */
  valueFormatter?: (value: number) => string;
  /** Formats y-axis labels. Defaults to compact notation (12K). */
  axisFormatter?: (value: number) => string;
  /** Shows empty gridlines and a loading note instead of data. */
  loading?: boolean;
  className?: string;
}

const compact = new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 });
const standard = new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 });

function niceStep(range: number, count: number) {
  const raw = range / Math.max(1, count);
  const magnitude = 10 ** Math.floor(Math.log10(raw));
  const normalized = raw / magnitude;
  const nice = normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 2.5 ? 2.5 : normalized <= 5 ? 5 : 10;
  return nice * magnitude;
}

type Point = { x: number; y: number };

/** Monotone cubic interpolation (Fritsch and Carlson): smooth, and never overshoots a data point. */
function smoothPath(points: Point[]) {
  const n = points.length;
  if (n === 0) return "";
  const first = points[0]!;
  if (n === 1) return `M${first.x},${first.y}`;
  if (n === 2) return `M${first.x},${first.y}L${points[1]!.x},${points[1]!.y}`;
  const slopes: number[] = [];
  for (let i = 0; i < n - 1; i++) slopes.push((points[i + 1]!.y - points[i]!.y) / (points[i + 1]!.x - points[i]!.x));
  const tangents = points.map((_, i) => {
    if (i === 0) return slopes[0]!;
    if (i === n - 1) return slopes[n - 2]!;
    const a = slopes[i - 1]!;
    const b = slopes[i]!;
    return a * b <= 0 ? 0 : (a + b) / 2;
  });
  for (let i = 0; i < n - 1; i++) {
    const slope = slopes[i]!;
    if (slope === 0) {
      tangents[i] = 0;
      tangents[i + 1] = 0;
      continue;
    }
    const a = tangents[i]! / slope;
    const b = tangents[i + 1]! / slope;
    const s = a * a + b * b;
    if (s > 9) {
      const t = 3 / Math.sqrt(s);
      tangents[i] = t * a * slope;
      tangents[i + 1] = t * b * slope;
    }
  }
  let d = `M${first.x},${first.y}`;
  for (let i = 0; i < n - 1; i++) {
    const p0 = points[i]!;
    const p1 = points[i + 1]!;
    const dx = (p1.x - p0.x) / 3;
    d += `C${p0.x + dx},${p0.y + tangents[i]! * dx},${p1.x - dx},${p1.y - tangents[i + 1]! * dx},${p1.x},${p1.y}`;
  }
  return d;
}

function linearPath(points: Point[]) {
  return points.map((point, i) => `${i ? "L" : "M"}${point.x},${point.y}`).join("");
}

/** A bar with its two far corners rounded, growing up from (or down from) the baseline. */
function barPath(x: number, y: number, width: number, height: number, up: boolean) {
  const r = Math.min(3, width / 2, Math.abs(height));
  if (height === 0) return "";
  if (up) return `M${x},${y + height}V${y + r}Q${x},${y} ${x + r},${y}H${x + width - r}Q${x + width},${y} ${x + width},${y + r}V${y + height}Z`;
  return `M${x},${y}V${y + height - r}Q${x},${y + height} ${x + r},${y + height}H${x + width - r}Q${x + width},${y + height} ${x + width},${y + height - r}V${y}Z`;
}

/**
 * Line, area, and grouped bar charts drawn in SVG with no chart library. Width follows the
 * container; a crosshair and tooltip follow the pointer, and arrow keys step through points
 * when the plot has focus. Lines draw in and bars grow on first render, except under reduced motion.
 */
export function Chart<Row extends Record<string, unknown>>({
  type = "line",
  data,
  index,
  series,
  label,
  height = 240,
  curve = "smooth",
  grid = true,
  legend = series.length > 1,
  yTicks = 4,
  valueFormatter = (value) => standard.format(value),
  axisFormatter = (value) => compact.format(value),
  loading = false,
  className,
}: ChartProps<Row>) {
  const id = useId();
  const wrapRef = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);
  const [hidden, setHidden] = useState<Set<string>>(() => new Set());
  const [active, setActive] = useState<number | null>(null);
  const [announcement, setAnnouncement] = useState("");
  // Bars stagger their entrance; once settled, hover dimming should answer without that delay.
  const [settled, setSettled] = useState(false);

  useEffect(() => {
    const node = wrapRef.current;
    if (!node) return;
    const observer = new ResizeObserver(([entry]) => entry && setWidth(Math.round(entry.contentRect.width)));
    observer.observe(node);
    setWidth(Math.round(node.getBoundingClientRect().width));
    return () => observer.disconnect();
  }, []);

  const toned = series.map((item, i) => ({ ...item, tone: item.tone ?? toneOrder[i % toneOrder.length]! }));
  const visible = toned.filter((item) => !hidden.has(item.key));
  const value = (row: Row | undefined, key: string) => {
    const raw = row?.[key];
    return typeof raw === "number" && Number.isFinite(raw) ? raw : null;
  };
  const labels = data.map((row) => String(row[index] ?? ""));

  // Y domain over the visible series, always including zero, rounded out to nice steps.
  const scale = useMemo(() => {
    let min = 0;
    let max = 0;
    for (const row of data)
      for (const item of visible) {
        const v = value(row, item.key);
        if (v === null) continue;
        min = Math.min(min, v);
        max = Math.max(max, v);
      }
    if (max === min) max = min + 1;
    const step = niceStep(max - min, yTicks);
    const lo = Math.floor(min / step) * step;
    const hi = Math.ceil(max / step) * step;
    const ticks: number[] = [];
    for (let tick = lo; tick <= hi + step / 2; tick += step) ticks.push(Number(tick.toPrecision(12)));
    return { lo, hi, ticks };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data, visible.map((item) => item.key).join(), yTicks]);

  const tickLabels = scale.ticks.map(axisFormatter);
  const longest = Math.max(...tickLabels.map((text) => text.length), 1);
  const pad = { top: 10, right: 12, bottom: 28, left: Math.ceil(longest * 6.6) + 14 };
  const innerW = Math.max(0, width - pad.left - pad.right);
  const innerH = Math.max(0, height - pad.top - pad.bottom);
  const n = data.length;
  const y = (v: number) => pad.top + innerH - ((v - scale.lo) / (scale.hi - scale.lo)) * innerH;
  const baseline = y(Math.max(scale.lo, Math.min(0, scale.hi)));
  const band = type === "bar" ? innerW / Math.max(1, n) : 0;
  const xAt = (i: number) => (type === "bar" ? pad.left + band * i + band / 2 : n === 1 ? pad.left + innerW / 2 : pad.left + (i * innerW) / (n - 1));

  const labelEvery = Math.max(1, Math.ceil(n / Math.max(1, Math.floor(innerW / 64))));

  function indexFromPointer(event: PointerEvent<SVGRectElement>) {
    const rect = event.currentTarget.getBoundingClientRect();
    const px = event.clientX - rect.left;
    if (n === 0) return null;
    if (type === "bar") return Math.max(0, Math.min(n - 1, Math.floor(px / band)));
    if (n === 1) return 0;
    return Math.max(0, Math.min(n - 1, Math.round((px / innerW) * (n - 1))));
  }

  function describe(i: number) {
    const row = data[i];
    const parts = visible.map((item) => {
      const v = value(row, item.key);
      return `${item.label} ${v === null ? "no data" : valueFormatter(v)}`;
    });
    return `${labels[i]}: ${parts.join(", ")}`;
  }

  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    if (n === 0) return;
    let next: number | null = active;
    if (event.key === "ArrowRight") next = active === null ? 0 : Math.min(n - 1, active + 1);
    else if (event.key === "ArrowLeft") next = active === null ? n - 1 : Math.max(0, active - 1);
    else if (event.key === "Home") next = 0;
    else if (event.key === "End") next = n - 1;
    else if (event.key === "Escape") next = null;
    else return;
    event.preventDefault();
    setActive(next);
    setAnnouncement(next === null ? "" : describe(next));
  }

  function onFocus(event: FocusEvent<HTMLDivElement>) {
    if (active === null && n > 0 && event.currentTarget.matches(":focus-visible")) {
      setActive(n - 1);
      setAnnouncement(describe(n - 1));
    }
  }

  function toggle(key: string) {
    setHidden((current) => {
      const next = new Set(current);
      if (next.has(key)) next.delete(key);
      else if (toned.length - next.size > 1) next.add(key);
      return next;
    });
  }

  const ready = width > 0;
  useEffect(() => {
    if (!ready || settled) return;
    const timer = setTimeout(() => setSettled(true), 900);
    return () => clearTimeout(timer);
  }, [ready, settled]);
  const empty = !loading && n === 0;
  const activeRow = active !== null ? data[active] : undefined;
  const activeX = active !== null ? xAt(active) : 0;
  const tooltipLeft = activeX > width / 2;
  const groupW = Math.min(band * 0.72, visible.length * 28 + (visible.length - 1) * 3);
  const barW = visible.length ? (groupW - (visible.length - 1) * 3) / visible.length : 0;

  return (
    <figure data-slot="chart" data-type={type} className={cx("m-0 grid min-w-0 gap-3", className)}>
      {legend ? (
        <div role="group" aria-label="Series" className="flex flex-wrap items-center gap-x-1 gap-y-1">
          {toned.map((item) => {
            const on = !hidden.has(item.key);
            return (
              <button
                key={item.key}
                type="button"
                aria-pressed={on}
                onClick={() => toggle(item.key)}
                className={cx(
                  "inline-flex h-7 items-center gap-2 rounded-md px-2 text-xs",
                  "transition-[background-color,color,opacity] duration-150 ease-out motion-reduce:transition-none",
                  "hover:bg-zinc-950/[0.04] dark:hover:bg-white/[0.06]",
                  "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
                  on ? "text-zinc-600 dark:text-zinc-400" : "text-zinc-400 opacity-60 dark:text-zinc-600",
                )}
              >
                <span aria-hidden="true" className={cx("flex", tones[item.tone])}>
                  {type === "bar" ? (
                    <span className="size-2.5 rounded-[3px] bg-current" />
                  ) : item.dashed ? (
                    <svg viewBox="0 0 14 4" className="h-1 w-3.5">
                      <path d="M1 2h12" stroke="currentColor" strokeWidth="2" strokeDasharray="3 2" strokeLinecap="round" />
                    </svg>
                  ) : (
                    <span className="h-0.5 w-3.5 rounded-full bg-current" />
                  )}
                </span>
                {item.label}
              </button>
            );
          })}
        </div>
      ) : null}

      <div
        ref={wrapRef}
        role="img"
        aria-label={`${label}. Focus and use the arrow keys to read each point.`}
        aria-busy={loading || undefined}
        tabIndex={empty || loading ? undefined : 0}
        onKeyDown={onKeyDown}
        onFocus={onFocus}
        onBlur={() => setActive(null)}
        style={{ height }}
        className="relative w-full rounded-lg outline-none select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-4 focus-visible:outline-sky-500"
      >
        {ready ? (
          <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} aria-hidden="true" className="block overflow-visible">
            {/* Gridlines and y labels */}
            {scale.ticks.map((tick, i) => (
              <g key={tick}>
                {grid || tick === 0 ? (
                  <line
                    x1={pad.left}
                    x2={width - pad.right}
                    y1={Math.round(y(tick)) + 0.5}
                    y2={Math.round(y(tick)) + 0.5}
                    className={tick === 0 ? "stroke-zinc-950/15 dark:stroke-white/20" : "stroke-zinc-950/[0.07] dark:stroke-white/[0.08]"}
                    strokeDasharray={tick === 0 ? undefined : "2 3"}
                  />
                ) : null}
                <text x={pad.left - 10} y={y(tick)} dy="0.32em" textAnchor="end" className="fill-zinc-500 text-[11px] tabular-nums">
                  {loading ? "" : tickLabels[i]}
                </text>
              </g>
            ))}

            {/* X labels */}
            {labels.map((text, i) =>
              i % labelEvery === 0 || (type !== "bar" && i === n - 1 && (n - 1) % labelEvery > labelEvery / 2) ? (
                <text
                  key={i}
                  x={xAt(i)}
                  y={height - 8}
                  textAnchor={type === "bar" || n === 1 ? "middle" : i === 0 ? "start" : i === n - 1 ? "end" : "middle"}
                  className={cx(
                    "text-[11px] tabular-nums transition-[fill] duration-150 motion-reduce:transition-none",
                    active === i ? "fill-zinc-950 dark:fill-white" : "fill-zinc-500",
                  )}
                >
                  {text}
                </text>
              ) : null,
            )}

            {/* Hover band behind bars */}
            {type === "bar" && active !== null ? (
              <rect
                x={pad.left + band * active + 1}
                y={pad.top}
                width={Math.max(0, band - 2)}
                height={innerH}
                rx={6}
                className="fill-zinc-950/[0.035] dark:fill-white/[0.05]"
              />
            ) : null}

            {/* Marks */}
            {!loading
              ? visible.map((item, s) => {
                  if (type === "bar") {
                    return (
                      <g key={item.key} className={tones[item.tone]}>
                        {data.map((row, i) => {
                          const v = value(row, item.key);
                          if (v === null) return null;
                          const x = pad.left + band * i + (band - groupW) / 2 + s * (barW + 3);
                          const top = Math.min(y(v), baseline);
                          const h = Math.abs(y(v) - baseline);
                          return (
                            <path
                              key={i}
                              d={barPath(x, top, barW, h, v >= 0)}
                              style={settled ? undefined : { transitionDelay: `${Math.min(i * 28, 320)}ms` }}
                              className={cx(
                                "fill-current [transform-box:fill-box]",
                                v >= 0 ? "origin-bottom" : "origin-top",
                                "transition-[scale,opacity] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
                                "motion-safe:starting:scale-y-0",
                                active !== null && active !== i ? "opacity-55" : "opacity-100",
                              )}
                            />
                          );
                        })}
                      </g>
                    );
                  }
                  // Lines break at missing values instead of dropping to zero.
                  const segments: Point[][] = [[]];
                  data.forEach((row, i) => {
                    const v = value(row, item.key);
                    if (v === null) segments.push([]);
                    else segments[segments.length - 1]!.push({ x: xAt(i), y: y(v) });
                  });
                  const paths = segments.filter((segment) => segment.length > 0);
                  const draw = curve === "smooth" ? smoothPath : linearPath;
                  const gradientId = `${id}-${item.key}-fill`;
                  return (
                    <g key={item.key} className={tones[item.tone]}>
                      {type === "area" ? (
                        <>
                          <defs>
                            <linearGradient id={gradientId} x1="0" x2="0" y1="0" y2="1">
                              <stop offset="0%" stopColor="currentColor" stopOpacity={visible.length > 1 ? 0.14 : 0.2} />
                              <stop offset="100%" stopColor="currentColor" stopOpacity={0} />
                            </linearGradient>
                          </defs>
                          {paths.map((segment, k) => (
                            <path
                              key={`area-${k}`}
                              d={`${draw(segment)}L${segment[segment.length - 1]!.x},${baseline}L${segment[0]!.x},${baseline}Z`}
                              fill={`url(#${gradientId})`}
                              className="transition-opacity delay-150 duration-700 ease-out motion-reduce:transition-none motion-safe:starting:opacity-0"
                            />
                          ))}
                        </>
                      ) : null}
                      {paths.map((segment, k) => (
                        <path
                          key={`line-${k}`}
                          d={draw(segment)}
                          fill="none"
                          stroke="currentColor"
                          strokeWidth={1.75}
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          pathLength={item.dashed ? undefined : 1}
                          strokeDasharray={item.dashed ? "4 4" : "1"}
                          className={cx(
                            item.dashed
                              ? "transition-opacity duration-500 ease-out motion-reduce:transition-none motion-safe:starting:opacity-0"
                              : "[stroke-dashoffset:0] transition-[stroke-dashoffset] duration-[900ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none motion-safe:starting:[stroke-dashoffset:1]",
                          )}
                        />
                      ))}
                    </g>
                  );
                })
              : null}

            {/* Crosshair and active points */}
            {type !== "bar" && active !== null && !loading ? (
              <g>
                <line
                  x1={Math.round(activeX) + 0.5}
                  x2={Math.round(activeX) + 0.5}
                  y1={pad.top}
                  y2={pad.top + innerH}
                  className="stroke-zinc-950/25 dark:stroke-white/30"
                />
                {visible.map((item) => {
                  const v = value(activeRow, item.key);
                  return v === null ? null : (
                    <circle
                      key={item.key}
                      cx={activeX}
                      cy={y(v)}
                      r={3.75}
                      strokeWidth={2}
                      className={cx("fill-current stroke-white dark:stroke-black", tones[item.tone])}
                    />
                  );
                })}
              </g>
            ) : null}

            {/* Pointer target over the plot */}
            {!loading && n > 0 ? (
              <rect
                x={pad.left}
                y={pad.top}
                width={innerW}
                height={innerH}
                fill="transparent"
                className="touch-pan-y"
                onPointerMove={(event) => setActive(indexFromPointer(event))}
                onPointerDown={(event) => setActive(indexFromPointer(event))}
                onPointerLeave={(event) => event.pointerType === "mouse" && setActive(null)}
              />
            ) : null}
          </svg>
        ) : null}

        {loading || empty ? (
          <p className="absolute inset-0 flex items-center justify-center pb-6 text-xs text-zinc-500">
            {loading ? "Loading data" : "No data in this range"}
          </p>
        ) : null}

        {ready && active !== null && activeRow && !loading ? (
          <div
            aria-hidden="true"
            style={{
              left: activeX,
              top: pad.top,
              transform: tooltipLeft ? "translateX(calc(-100% - 14px))" : "translateX(14px)",
            }}
            className={cx(
              "pointer-events-none absolute z-10 grid min-w-36 gap-1.5 rounded-lg border px-3 py-2 text-xs",
              "border-zinc-950/10 bg-white shadow-[0_12px_32px_-8px_rgb(0_0_0/0.18)]",
              "dark:border-white/15 dark:bg-black dark:shadow-[0_16px_48px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
              "transition-opacity duration-150 ease-out motion-reduce:transition-none starting:opacity-0",
            )}
          >
            <p className="font-medium text-zinc-950 dark:text-white">{labels[active]}</p>
            {visible.map((item) => {
              const v = value(activeRow, item.key);
              return (
                <div key={item.key} className="flex items-center gap-2">
                  <span aria-hidden="true" className={cx("size-2 shrink-0 rounded-[3px] bg-current", tones[item.tone])} />
                  <span className="text-zinc-600 dark:text-zinc-400">{item.label}</span>
                  <span className="ms-auto ps-3 font-medium text-zinc-950 tabular-nums dark:text-white">{v === null ? "None" : valueFormatter(v)}</span>
                </div>
              );
            })}
          </div>
        ) : null}
      </div>

      <p aria-live="polite" className="sr-only">
        {announcement}
      </p>

      {/* The numbers behind the picture, for screen readers. */}
      <table className="sr-only">
        <caption>{label}</caption>
        <thead>
          <tr>
            <th scope="col">{String(index)}</th>
            {toned.map((item) => (
              <th key={item.key} scope="col">
                {item.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {data.map((row, i) => (
            <tr key={i}>
              <th scope="row">{labels[i]}</th>
              {toned.map((item) => {
                const v = value(row, item.key);
                return <td key={item.key}>{v === null ? "No data" : valueFormatter(v)}</td>;
              })}
            </tr>
          ))}
        </tbody>
      </table>
    </figure>
  );
}