Donut Morph
A donut chart whose slices slide and grow on springs, with the total rolling in the middle and a legend in percent.
Preview
"use client";
import { useState } from "react";
import { useAutoplay } from "../demo-context";
import { DonutMorph } from "./DonutMorph";
const sets = [
[420, 260, 180, 90],
[300, 380, 140, 160],
[520, 200, 260, 60],
];
const names = ["Direct", "Search", "Social", "Email"];
export default function Demo() {
const [turn, setTurn] = useState(0);
useAutoplay(() => setTurn((t) => t + 1), 2000);
const values = sets[turn % sets.length];
return <DonutMorph label="Visits" parts={names.map((label, i) => ({ label, value: values[i] }))} locale="en-US" />;
}Installation
npx @usefluid/cli add donut-morphpnpm dlx @usefluid/cli add donut-morphyarn dlx @usefluid/cli add donut-morphbunx @usefluid/cli add donut-morphInstall the engine.
Terminal npm i @usefluid/motionCopy these files into your project.
components/fluid/donut-morph/DonutMorph.tsx "use client"; import { useSpring } from "@usefluid/motion/react"; import { type CSSProperties, useMemo, useRef, useState } from "react"; import { slices } from "./donut"; import styles from "./DonutMorph.module.css"; const R = 48; const LENGTH = 2 * Math.PI * R; const GAP = 0.012; const PALETTE = ["#7c5cff", "#14b8a6", "#ff8a3d", "#ff4d8d", "#3b82f6"]; type Part = { label: string; value: number; color?: string }; type Props = { label: string; parts: Part[]; format?: Intl.NumberFormatOptions; locale?: string; }; function Arc({ start, share, index, color }: { start: number; share: number; index: number; color: string }) { const arc = useRef<SVGCircleElement>(null); useSpring( { s: start, l: share }, ({ s, l }) => { if (!arc.current) return; const visible = Math.max(0, l - (l > GAP * 2 ? GAP : 0)) * LENGTH; arc.current.style.strokeDasharray = `${visible} ${LENGTH}`; arc.current.style.strokeDashoffset = `${-s * LENGTH}`; }, { w: Math.max(9, 14 - index * 0.8), z: 0.7 }, ); return <circle ref={arc} cx={60} cy={60} r={R} className={styles.arc} style={{ stroke: color }} />; } export function DonutMorph({ label, parts, format, locale }: Props) { const total = parts.reduce((a, p) => a + Math.max(0, p.value), 0); const key = JSON.stringify(format ?? {}); const number = useMemo(() => new Intl.NumberFormat(locale, JSON.parse(key)), [locale, key]); const percent = useMemo(() => new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 0 }), [locale]); const out = useRef<HTMLSpanElement>(null); const [first] = useState(() => number.format(total)); useSpring( { v: total }, ({ v }) => { if (out.current) out.current.textContent = number.format(Math.round(v)); }, { w: 9, z: 1 }, ); const cut = slices(parts.map((p) => p.value)); const colorOf = (p: Part, i: number) => p.color ?? PALETTE[i % PALETTE.length]; return ( <figure className={styles.root} aria-label={label}> <div className={styles.ring}> <svg viewBox="0 0 120 120" aria-hidden> <circle cx={60} cy={60} r={R} className={styles.track} /> {parts.map((p, i) => ( <Arc key={p.label} start={cut[i].start} share={cut[i].share} index={i} color={colorOf(p, i)} /> ))} </svg> <span className={styles.center} aria-hidden> <span ref={out} className={styles.total}> {first} </span> <span className={styles.caption}>{label}</span> </span> </div> <ul className={styles.legend}> {parts.map((p, i) => ( <li key={p.label} style={{ "--part": colorOf(p, i) } as CSSProperties}> <span className={styles.name}>{p.label}</span> <span className={styles.share}>{percent.format(cut[i].share)}</span> <span className={styles.hidden}>{number.format(p.value)}</span> </li> ))} </ul> </figure> ); }components/fluid/donut-morph/donut.test.ts import { describe, expect, it } from "vitest"; import { slices } from "./donut"; describe("slices", () => { it("turns values into shares that start where the last one ended", () => { const s = slices([1, 1, 2]); expect(s.map((x) => x.share)).toEqual([0.25, 0.25, 0.5]); expect(s.map((x) => x.start)).toEqual([0, 0.25, 0.5]); }); it("treats negative values as zero and an empty total as all zeros", () => { expect(slices([-3, 1]).map((x) => x.share)).toEqual([0, 1]); expect(slices([0, 0]).map((x) => x.share)).toEqual([0, 0]); }); });components/fluid/donut-morph/donut.ts export type Slice = { start: number; share: number }; export function slices(values: number[]): Slice[] { const clean = values.map((v) => Math.max(0, v)); const total = clean.reduce((a, b) => a + b, 0); let start = 0; return clean.map((v) => { const share = total > 0 ? v / total : 0; const slice = { start, share }; start += share; return slice; }); }components/fluid/donut-morph/DonutMorph.module.css .root { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 24px; width: min(100%, 460px); margin: 0; padding: 22px; border-radius: 24px; background: var(--fluid-surface); color: var(--fluid-text); font-family: var(--fluid-font); } .ring { position: relative; display: grid; place-items: center; width: 170px; aspect-ratio: 1; } .ring svg { width: 100%; height: 100%; transform: rotate(-90deg); } .track, .arc { fill: none; stroke-width: 16; } .track { stroke: color-mix(in srgb, var(--fluid-text) 7%, transparent); } .arc { stroke-linecap: butt; } .center { position: absolute; display: grid; justify-items: center; gap: 2px; max-width: 60%; text-align: center; } .total { font-size: 26px; font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: -0.02em; line-height: 1; } .caption { color: var(--fluid-text-2); font-size: 12px; } .legend { display: grid; flex: 1; gap: 10px; min-width: 150px; margin: 0; padding: 0; list-style: none; } .legend li { display: flex; align-items: center; gap: 10px; font-size: 14px; } .legend li::before { width: 10px; height: 10px; border-radius: 999px; background: var(--part); content: ""; } .name { flex: 1; } .share { font-weight: 600; font-variant-numeric: tabular-nums; } .hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }Import the theme once, then point its variables at your own tokens.
layout.tsx import "@usefluid/motion/theme.css";
Usage
import { DonutMorph } from "./DonutMorph";
<DonutMorph label="Visits" parts={[{ label: "Direct", value: 420 }, { label: "Search", value: 260 }]} />API reference
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | — | What is counted. Shown under the total and used as the accessible name. |
parts | { label, value, color? }[] | — | One slice per part. Labels must be unique. Without a colour, parts take violet, teal, orange, pink and blue in order. |
format | Intl.NumberFormatOptions | — | How the total and values are written, as in Intl.NumberFormat. |
locale | string | the browser's | Locale for numbers and percents. |
Keyboard and screen readers
The ring is decoration; the legend is a list that reads each part with its percent and value. With reduced motion slices change at once.
Notes
Each slice has a slightly slower spring than the one before, so a change travels around the ring. slices in donut.ts turns values into starts and shares. Every colour is yours to change.
How it is made
Each slice has two springs, where it starts and how long it is, so when the numbers change the slices push each other around the ring instead of jumping. Later slices are a little slower, so the change travels around. The legend is a list that screen readers read with each percent.
For your agent
For your agent
Add Donut Morph to my project with the Fluid library. Use DonutMorph for the breakdowns of my dashboard, such as channels or plans, with my colours. Read my project first. Use my logo, my colours and my font through the --fluid-* variables. Keep 44px touch targets, visible focus and reduced motion. If I have no SVG logo, ask before making one up.