Ring chart

A dependency-free SVG donut that can also be a half-ring gauge, drawn in the theme's chart colours with small gaps between slices. It sweeps in on mount, and the centre shows the total or the hovered slice's value and label. The legend lists each slice's value and share, and clicking an item hides that slice while the rest smoothly re-share the ring. A hovered slice moves outward while the others dim. The gauge can take a target, drawn as a tick on the ring with the distance to it in the centre. Legend buttons are the keyboard path, a hidden table carries the data for screen readers, and motion stops when reduced motion is on.

DashboardsComponentTailwind v4

Source

"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

export type RingDatum = { id: string; label: string; value: number; color?: string };

export type RingChartProps = {
  data: RingDatum[];
  /** "ring" is a full donut; "gauge" is a half ring filled against `max`. */
  variant?: "ring" | "gauge";
  /** Accessible title, also the hidden table caption. */
  title: string;
  /** Ring thickness in pixels (at the chart's own size). */
  thickness?: number;
  size?: number;
  roundCaps?: boolean;
  format?: (value: number) => string;
  /** Small text under the total in the centre. */
  centerLabel?: string;
  /** Gauge only: the full scale. Defaults to the sum of the data. */
  max?: number;
  /** Gauge only: draws a tick on the ring and shows the distance to it in the centre. */
  target?: number;
  /** Controlled list of hidden slice ids. */
  hidden?: string[];
  defaultHidden?: string[];
  onHiddenChange?: (hidden: string[]) => void;
  showLegend?: boolean;
  className?: string;
};

const PALETTE = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)"];
const GAP_PX = 2;
const PUSH_PX = 4;
const plain = new Intl.NumberFormat("en", { maximumFractionDigits: 1 });
const percent = (share: number) => `${share >= 0.0995 || share === 0 ? Math.round(share * 100) : (share * 100).toFixed(1)}%`;

function reducedMotion() {
  return typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
}

/** Next animation frame, with a timer fallback for pages that are not painting (background tabs, headless capture). */
function nextFrame(callback: (now: number) => void) {
  let done = false;
  const run = () => {
    if (done) return;
    done = true;
    cancelAnimationFrame(frame);
    clearTimeout(timer);
    callback(performance.now());
  };
  const frame = requestAnimationFrame(run);
  const timer = setTimeout(run, 34);
  return () => {
    done = true;
    cancelAnimationFrame(frame);
    clearTimeout(timer);
  };
}

/** Eases a set of numbers towards their targets on each change; jumps when motion is reduced. */
function useTweenedNumbers(targets: number[], ms: number, startFromZero: boolean) {
  const [values, setValues] = React.useState(() => (startFromZero ? targets.map(() => 0) : targets));
  const current = React.useRef(values);
  const key = targets.join("|");
  React.useEffect(() => {
    if (reducedMotion()) {
      current.current = targets;
      setValues(targets);
      return;
    }
    const from = targets.map((_, index) => current.current[index] ?? 0);
    const start = performance.now();
    let cancel = () => {};
    const tick = (now: number) => {
      const t = Math.min(1, (now - start) / ms);
      const eased = t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;
      const next = targets.map((target, index) => from[index] + (target - from[index]) * eased);
      current.current = next;
      setValues(next);
      if (t < 1) cancel = nextFrame(tick);
    };
    cancel = nextFrame(tick);
    return () => cancel();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [key, ms]);
  return values;
}

const polar = (cx: number, cy: number, r: number, angle: number) => [cx + r * Math.cos(angle), cy + r * Math.sin(angle)] as const;

function arcPath(cx: number, cy: number, r: number, a0: number, a1: number) {
  const [x0, y0] = polar(cx, cy, r, a0);
  const [x1, y1] = polar(cx, cy, r, a1);
  const large = a1 - a0 > Math.PI ? 1 : 0;
  return `M ${x0.toFixed(3)} ${y0.toFixed(3)} A ${r} ${r} 0 ${large} 1 ${x1.toFixed(3)} ${y1.toFixed(3)}`;
}

export function RingChart({
  data,
  variant = "ring",
  title,
  thickness,
  size = 220,
  roundCaps = false,
  format = (value) => plain.format(value),
  centerLabel = "Total",
  max,
  target,
  hidden: hiddenProp,
  defaultHidden = [],
  onHiddenChange,
  showLegend = true,
  className,
}: RingChartProps) {
  const uid = React.useId();
  const gauge = variant === "gauge";
  const [innerHidden, setInnerHidden] = React.useState<string[]>(defaultHidden);
  const hidden = hiddenProp ?? innerHidden;
  const toggle = (id: string) => {
    const next = hidden.includes(id) ? hidden.filter((item) => item !== id) : [...hidden, id];
    if (!hiddenProp) setInnerHidden(next);
    onHiddenChange?.(next);
  };
  const [hot, setHot] = React.useState<string | null>(null);

  const colors = data.map((item, index) => item.color ?? PALETTE[index % PALETTE.length]);
  const shown = data.map((item) => (hidden.includes(item.id) ? 0 : Math.max(0, item.value)));
  const visibleTotal = shown.reduce((sum, value) => sum + value, 0);
  const fullTotal = data.reduce((sum, item) => sum + Math.max(0, item.value), 0);
  const scale = gauge ? Math.max(max ?? fullTotal, 1e-9) : Math.max(visibleTotal, 1e-9);

  // Mount sweep: the whole ring grows from nothing, then slices re-share it on every toggle.
  const [sweep] = useTweenedNumbers([1], 900, true);
  const weights = useTweenedNumbers(shown, 520, false);

  /* ---------- geometry ---------- */
  const stroke = thickness ?? Math.round(size * (gauge ? 0.09 : 0.13));
  const pad = PUSH_PX + 2;
  const r = size / 2 - stroke / 2 - pad;
  const cx = size / 2;
  const cy = size / 2;
  const height = gauge ? size / 2 + pad + 2 : size;
  const span = gauge ? Math.PI : Math.PI * 2;
  const start = gauge ? Math.PI : -Math.PI / 2;
  const capAngle = roundCaps ? stroke / 2 / r : 0;
  const gapAngle = GAP_PX / r + capAngle * 2;

  const weightTotal = gauge ? scale : weights.reduce((sum, value) => sum + value, 0) || 1;
  const visibleCount = weights.filter((value) => value > 1e-6).length;
  const arcs: { index: number; a0: number; a1: number; mid: number }[] = [];
  let cursor = start;
  const usable = span * sweep;
  weights.forEach((value, index) => {
    const angle = (value / weightTotal) * usable;
    const a0 = cursor;
    const a1 = cursor + angle;
    cursor = a1;
    if (angle <= 1e-4) return;
    // Trim half the gap from each end, unless the slice is the only one on a full ring.
    const trim = !gauge && visibleCount === 1 ? 0 : Math.min(gapAngle / 2, angle / 2 - 1e-4);
    arcs.push({ index, a0: a0 + trim, a1: a1 - trim, mid: (a0 + a1) / 2 });
  });

  const hotIndex = hot ? data.findIndex((item) => item.id === hot) : -1;
  const hotItem = hotIndex >= 0 && !hidden.includes(data[hotIndex].id) ? data[hotIndex] : null;
  const shareOf = (value: number) => (gauge ? value / scale : visibleTotal ? value / visibleTotal : 0);

  /* ---------- centre ---------- */
  let centreValue = format(visibleTotal);
  let centreLabel = centerLabel;
  let centreNote: React.ReactNode = gauge ? `of ${format(scale)}` : null;
  if (hotItem) {
    centreValue = format(hotItem.value);
    centreLabel = hotItem.label;
    centreNote = percent(shareOf(hotItem.value));
  } else if (gauge && target != null) {
    const delta = target - visibleTotal;
    centreNote = (
      <span className={delta >= 0 ? "text-emerald-700 dark:text-emerald-400" : "text-destructive"}>
        {delta >= 0 ? `${format(delta)} to goal` : `${format(-delta)} over goal`}
      </span>
    );
  }

  const summary = `${title}. ${gauge ? `${format(visibleTotal)} of ${format(scale)} used. ` : `Total ${format(visibleTotal)}. `}${data
    .filter((item) => !hidden.includes(item.id))
    .map((item) => `${item.label} ${percent(shareOf(item.value))}`)
    .join(", ")}.`;

  const targetAngle = gauge && target != null ? start + Math.min(1, Math.max(0, target / scale)) * span : null;

  return (
    <figure className={cn("flex min-w-0 flex-col items-center gap-5", className)}>
      <div className="relative w-full" style={{ maxWidth: size }}>
        <svg role="img" aria-label={summary} viewBox={`0 0 ${size} ${height}`} className="block h-auto w-full overflow-visible">
          {/* Track */}
          <path
            d={gauge ? arcPath(cx, cy, r, start, start + span - 1e-4) : arcPath(cx, cy, r, 0, Math.PI * 2 - 1e-4)}
            fill="none"
            stroke="var(--muted)"
            strokeWidth={stroke}
            strokeLinecap={gauge && roundCaps ? "round" : "butt"}
          />
          {arcs.map(({ index, a0, a1, mid }) => {
            const item = data[index];
            const isHot = hot === item.id;
            const [dx, dy] = isHot ? [Math.cos(mid) * PUSH_PX, Math.sin(mid) * PUSH_PX] : [0, 0];
            return (
              <path
                key={item.id}
                d={arcPath(cx, cy, r, a0, a1)}
                fill="none"
                stroke={colors[index]}
                strokeWidth={stroke}
                strokeLinecap={roundCaps ? "round" : "butt"}
                onPointerEnter={() => setHot(item.id)}
                onPointerLeave={() => setHot((current) => (current === item.id ? null : current))}
                className="cursor-pointer motion-safe:transition-[transform,opacity] motion-safe:duration-200 motion-safe:ease-out"
                style={{ transform: `translate(${dx}px, ${dy}px)`, opacity: hot && !isHot ? 0.35 : 1 }}
              />
            );
          })}
          {targetAngle != null && (
            <g aria-hidden="true">
              {(() => {
                const [x0, y0] = polar(cx, cy, r - stroke / 2 - 4, targetAngle);
                const [x1, y1] = polar(cx, cy, r + stroke / 2 + 4, targetAngle);
                return <line x1={x0} y1={y0} x2={x1} y2={y1} stroke="var(--foreground)" strokeWidth={2.5} strokeLinecap="round" />;
              })()}
            </g>
          )}
        </svg>

        <div
          aria-hidden="true"
          className={cn(
            "pointer-events-none absolute left-0 right-0 grid justify-items-center gap-0 text-center",
            gauge ? "bottom-0 content-end" : "top-0 bottom-0 content-center",
          )}
        >
          <span className="max-w-[60%] truncate text-xs text-muted-foreground">{centreLabel}</span>
          <span className="text-2xl font-semibold tabular-nums tracking-tight text-foreground sm:text-3xl">{centreValue}</span>
          {centreNote && <span className="mt-0.5 text-xs font-medium tabular-nums text-muted-foreground">{centreNote}</span>}
        </div>
      </div>

      {showLegend && (
        <figcaption className="w-full">
          <ul className="grid gap-1" aria-label={`${title} legend`}>
            {data.map((item, index) => {
              const off = hidden.includes(item.id);
              return (
                <li key={item.id}>
                  <button
                    type="button"
                    aria-pressed={!off}
                    aria-label={`${item.label}, ${format(item.value)}, ${off ? "hidden" : percent(shareOf(item.value))}`}
                    onClick={() => toggle(item.id)}
                    onPointerEnter={() => setHot(item.id)}
                    onPointerLeave={() => setHot((current) => (current === item.id ? null : current))}
                    onFocus={() => setHot(item.id)}
                    onBlur={() => setHot(null)}
                    className={cn(
                      "flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-left text-sm outline-none",
                      "hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring motion-safe:transition-colors",
                      hot === item.id && !off && "bg-accent",
                    )}
                  >
                    <span
                      aria-hidden="true"
                      className={cn("size-2.5 shrink-0 rounded-[3px] border-2 motion-safe:transition-colors")}
                      style={{ borderColor: colors[index], background: off ? "transparent" : colors[index] }}
                    />
                    <span className={cn("min-w-0 flex-1 truncate", off ? "text-muted-foreground line-through decoration-muted-foreground/60" : "text-foreground")}>
                      {item.label}
                    </span>
                    <span className={cn("tabular-nums", off ? "text-muted-foreground" : "text-foreground")}>{format(item.value)}</span>
                    <span className="w-11 text-right text-xs tabular-nums text-muted-foreground">{off ? "–" : percent(shareOf(item.value))}</span>
                  </button>
                </li>
              );
            })}
          </ul>
        </figcaption>
      )}

      <table className="sr-only" id={`${uid}-table`}>
        <caption>{title}</caption>
        <thead>
          <tr>
            <th scope="col">Item</th>
            <th scope="col">Value</th>
            <th scope="col">Share</th>
          </tr>
        </thead>
        <tbody>
          {data.map((item) => (
            <tr key={item.id}>
              <th scope="row">{item.label}</th>
              <td>{format(item.value)}</td>
              <td>{hidden.includes(item.id) ? "hidden" : percent(shareOf(item.value))}</td>
            </tr>
          ))}
          {gauge && target != null && (
            <tr>
              <th scope="row">Goal</th>
              <td>{format(target)}</td>
              <td>{percent(target / scale)}</td>
            </tr>
          )}
        </tbody>
      </table>
    </figure>
  );
}