Try 'magnetic button'
View code

Specification

Catalogue
No. 80 of 110
Interaction
Hover, Press
Element
Chart, Tabs, Counter
Preview
Live component
Imports
react 19.3.1, @number-flow/react 0.6.2, framer-motion 12.40.0
Added

Notes

A donut of visits by source with Week, Month and Year. Switching the period moves every arc to its new share while the total in the centre rolls; pointing at a slice or a legend row puts its own value in the centre.

A calm, readable chart for a finance or SaaS client's dashboard, with a legend that is also the table: every value is written out, so nothing depends on reading an angle or a colour.

On the entry page the arcs grow from nothing one after another (40ms, then 35ms apart). On a change of period each arc's two ends travel from where they were to their new angles on a 0.3s spring with no bounce, and a source keeps its colour in every period. Three hues (green, blue, ochre) and a grey for Other, checked with a palette validator for colour-blind separation and contrast on both stage surfaces; arcs keep a 2px gap and the legend names each slice, so colour is never the only cue. The legend is an HTML table with a caption. The centre figure rolls with NumberFlow. Instant under reduced motion.

The figures are sample content.

Code

React and plain CSS
"use client";

import { useEffect, useRef, useState } from "react";
import { animate } from "framer-motion";
import type { LivePreviewProps } from "@/components/live/types";
import { physicalSpring } from "@/components/pieces/kit/physical-spring";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { Num, radioArrows } from "@/components/pieces/shared";
import { useStageMode } from "@/components/pieces/stage/mode";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./donut-periods.css";

type Key = "search" | "direct" | "social" | "other";
type Period = "week" | "month" | "year";

const KEYS: { key: Key; label: string }[] = [
  { key: "search", label: "Search" },
  { key: "direct", label: "Direct" },
  { key: "social", label: "Social" },
  { key: "other", label: "Other" },
];
const DATA: Record<Period, Record<Key, number>> = {
  week: { search: 1240, direct: 860, social: 410, other: 190 },
  month: { search: 5120, direct: 2980, social: 2240, other: 760 },
  year: { search: 58400, direct: 41200, social: 17900, other: 9300 },
};
const PERIODS: { id: Period; label: string }[] = [
  { id: "week", label: "Week" },
  { id: "month", label: "Month" },
  { id: "year", label: "Year" },
];

const R = 70;
const STROKE = 22;
const C = 90;
/** A 2px gap of surface between neighbouring arcs, as an angle at this radius. */
const GAP = 2 / R;
const SETTLE = physicalSpring(0.3);

/** One slice's start and end angles. */
type ArcSpan = { a: number; b: number };
type Arcs = Record<Key, ArcSpan>;

function targetArcs(period: Period): Arcs {
  const d = DATA[period];
  const total = KEYS.reduce((s, k) => s + d[k.key], 0);
  let at = 0;
  const out = {} as Arcs;
  for (const { key } of KEYS) {
    const span = (d[key] / total) * Math.PI * 2;
    out[key] = { a: at, b: at + span };
    at += span;
  }
  return out;
}

function arcPath({ a, b }: ArcSpan): string {
  const s = a + GAP / 2;
  const e = b - GAP / 2;
  if (e - s <= 0.001) return "";
  const p = (t: number) => `${(C + R * Math.sin(t)).toFixed(2)} ${(C - R * Math.cos(t)).toFixed(2)}`;
  return `M ${p(s)} A ${R} ${R} 0 ${e - s > Math.PI ? 1 : 0} 1 ${p(e)}`;
}

const ZERO: Arcs = { search: { a: 0, b: 0 }, direct: { a: 0, b: 0 }, social: { a: 0, b: 0 }, other: { a: 0, b: 0 } };
const fmt = (n: number) => new Intl.NumberFormat("en-GB").format(n);

function DonutDemo() {
  const reduce = useSafeReducedMotion();
  const { context } = useStageMode();
  const [period, setPeriod] = useState<Period>("month");
  const [hot, setHot] = useState<Key | null>(null);
  // Arrive on the entry page by growing each arc from nothing, one after another; a resting card shows the finished donut.
  const arrive = context === "detail" && !reduce;
  const [arcs, setArcs] = useState<Arcs>(() => (arrive ? ZERO : targetArcs("month")));
  const shown = useRef<Arcs>(arcs);

  useEffect(() => {
    const to = targetArcs(period);
    const from = shown.current;
    const first = from === ZERO || KEYS.every((k) => from[k.key].b === 0);
    const runs = KEYS.map(({ key }, i) => {
      const f = first ? { a: to[key].a, b: to[key].a } : from[key];
      // Each arc's two ends travel from where they were to their new angles.
      return animate(0, 1, {
        ...(reduce ? { duration: 0 } : SETTLE),
        delay: first && !reduce ? 0.04 + i * 0.035 : 0,
        onUpdate: (t) => {
          const next = { ...shown.current, [key]: { a: f.a + (to[key].a - f.a) * t, b: f.b + (to[key].b - f.b) * t } };
          shown.current = next;
          setArcs(next);
        },
      });
    });
    return () => runs.forEach((r) => r.stop());
  }, [period, reduce]);

  const d = DATA[period];
  const total = KEYS.reduce((s, k) => s + d[k.key], 0);
  const focus = hot ? KEYS.find((k) => k.key === hot) : null;

  return (
    <div className="dm dp">
      <div className="dp-periods" role="radiogroup" aria-label="Period" onKeyDown={radioArrows}>
        {PERIODS.map((p) => (
          <button key={p.id} type="button" role="radio" aria-checked={period === p.id} tabIndex={period === p.id ? 0 : -1} className="dp-period" onClick={() => setPeriod(p.id)}>
            {p.label}
          </button>
        ))}
      </div>
      <div className="dp-body">
        <figure className="dp-chart" aria-label={`Visits by source this ${period}`}>
          <svg viewBox="0 0 180 180" width="180" height="180" aria-hidden="true" onPointerLeave={() => setHot(null)}>
            <circle cx={C} cy={C} r={R} className="dp-track" strokeWidth={STROKE} />
            {KEYS.map(({ key }) => (
              <path key={key} d={arcPath(arcs[key])} className="dp-arc" data-key={key} data-dim={(hot && hot !== key) || undefined} strokeWidth={STROKE} onPointerEnter={() => setHot(key)} />
            ))}
          </svg>
          <figcaption className="dp-centre" aria-hidden="true">
            <span className="dp-value">
              <Num value={focus ? d[focus.key] : total} />
            </span>
            <span className="dp-what">{focus ? focus.label : "Visits"}</span>
          </figcaption>
        </figure>
        <table className="dp-legend">
          <caption className="sr-only">Visits by source this {period}</caption>
          <thead className="sr-only">
            <tr>
              <th scope="col">Source</th>
              <th scope="col">Visits</th>
              <th scope="col">Share</th>
            </tr>
          </thead>
          <tbody>
            {KEYS.map(({ key, label }) => (
              <tr key={key} className="dp-row" data-key={key} data-hot={hot === key || undefined} onPointerEnter={() => setHot(key)} onPointerLeave={() => setHot(null)}>
                <th scope="row">
                  <span className="dp-swatch" aria-hidden="true" />
                  {label}
                </th>
                <td className="dp-num">{fmt(d[key])}</td>
                <td className="dp-num dp-share">{Math.round((d[key] / total) * 100)}%</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// What a hovered card shows: the week, one source picked out in the centre, then the year.
const TOUR: Tour = [
  { click: ".dp-period", text: "Week", wait: 1200 },
  { hover: ".dp-row", nth: 1, wait: 900 },
  { click: ".dp-period", text: "Year", wait: 1200 },
];

export default function DonutPeriodsEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Donut that changes period" tour={TOUR} sample>
      <DonutDemo />
    </PieceStage>
  );
}

More like this

Traffic in stacked bars

HoverCharts and numbers

Context window meter

Hover, PressCharts and numbers

Slope chart for before and after

Hover, PressCharts and numbers

Trend line with a gliding crosshair

HoverCharts and numbers

Comparison bars

Layout AnimationCharts and numbers

How the tools connect

HoverCharts and numbers