Dashboard
A whole dashboard where changing the range rolls every number, raises the bars, flows the trend and reorders the ranking together.
Preview
"use client";
import { useState } from "react";
import { useAutoplay } from "../demo-context";
import { Dashboard, type Range } from "./Dashboard";
const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const money = { style: "currency", currency: "USD", maximumFractionDigits: 0 } as const;
const channels = (v: number[]) => ["Direct", "Search", "Social", "Email"].map((label, i) => ({ label, value: v[i] }));
const activity = (seed: number) =>
Array.from({ length: 84 }, (_, i) => Math.max(0, Math.round(50 + 48 * Math.sin(i * 0.41 + seed) * Math.cos(i * 0.13 + seed))));
const people = (values: number[]) => ["Ana", "Bruno", "Carla", "Diego"].map((label, i) => ({ id: label, label, value: values[i] }));
const ranges: Range[] = [
{
id: "week",
label: "Week",
stats: [
{ label: "Revenue", value: 18420, previous: 16100, format: money },
{ label: "Orders", value: 342, previous: 365 },
{ label: "Refunds", value: 12, previous: 18, upIsGood: false },
],
trend: [22, 30, 26, 44, 40, 58, 54],
trendMax: 100,
trendLabels: ["Mon", "Wed", "Fri", "Sun"],
bars: DAYS.map((label, i) => ({ label, value: [32, 48, 41, 66, 58, 80, 72][i] })),
barsMax: 100,
goal: { label: "Weekly goal", value: 64, max: 100 },
leaders: people([42, 38, 51, 29]),
channels: channels([420, 260, 180, 90]),
activity: activity(0),
},
{
id: "month",
label: "Month",
stats: [
{ label: "Revenue", value: 76980, previous: 70210, format: money },
{ label: "Orders", value: 1490, previous: 1322 },
{ label: "Refunds", value: 41, previous: 37, upIsGood: false },
],
trend: [40, 34, 52, 48, 66, 60, 78],
trendMax: 100,
trendLabels: ["W1", "W2", "W3", "W4"],
bars: DAYS.map((label, i) => ({ label, value: [54, 62, 70, 52, 88, 61, 46][i] })),
barsMax: 100,
goal: { label: "Monthly goal", value: 88, max: 100 },
leaders: people([180, 214, 196, 150]),
channels: channels([300, 380, 140, 160]),
activity: activity(1.9),
},
{
id: "year",
label: "Year",
stats: [
{ label: "Revenue", value: 912400, previous: 744000, format: money },
{ label: "Orders", value: 17820, previous: 15040 },
{ label: "Refunds", value: 402, previous: 455, upIsGood: false },
],
trend: [18, 26, 38, 34, 56, 72, 94],
trendMax: 100,
trendLabels: ["Q1", "Q2", "Q3", "Q4"],
bars: DAYS.map((label, i) => ({ label, value: [28, 64, 50, 44, 76, 92, 84][i] })),
barsMax: 100,
goal: { label: "Yearly goal", value: 100, max: 100 },
leaders: people([2210, 2480, 1990, 2620]),
channels: channels([520, 200, 260, 60]),
activity: activity(3.4),
},
];
export default function Demo() {
const [value, setValue] = useState("week");
const [turn, setTurn] = useState(0);
useAutoplay(() => {
setTurn((t) => t + 1);
setValue(ranges[(turn + 1) % ranges.length].id);
}, 2600);
return <Dashboard title="Store" ranges={ranges} value={value} onChange={setValue} locale="en-US" />;
}Installation
npx @usefluid/cli add dashboardpnpm dlx @usefluid/cli add dashboardyarn dlx @usefluid/cli add dashboardbunx @usefluid/cli add dashboardInstall the engine.
Terminal npm i @usefluid/motionCopy these files into your project.
components/fluid/dashboard/Dashboard.tsx "use client"; import { AreaMorph } from "../area-morph/AreaMorph"; import { DonutMorph } from "../donut-morph/DonutMorph"; import { DotGrid } from "../dot-grid/DotGrid"; import { PillTabs } from "../pill-tabs/PillTabs"; import { ProgressRing } from "../progress-ring/ProgressRing"; import { RankList } from "../rank-list/RankList"; import type { Ranked } from "../rank-list/rank"; import { SpringBars } from "../spring-bars/SpringBars"; import { StatCounter } from "../stat-counter/StatCounter"; import styles from "./Dashboard.module.css"; export type Stat = { label: string; value: number; previous?: number; format?: Intl.NumberFormatOptions; upIsGood?: boolean }; export type Range = { id: string; label: string; stats: Stat[]; trend: number[]; trendLabels?: string[]; trendMax?: number; bars: { label: string; value: number }[]; barsMax?: number; goal: { label: string; value: number; max: number }; leaders: Ranked[]; channels?: { label: string; value: number }[]; activity?: number[]; }; type Props = { title: string; ranges: Range[]; value: string; onChange(id: string): void; colors?: string[]; locale?: string; }; const PALETTE = ["#7c5cff", "#14b8a6", "#ff8a3d", "#ff4d8d"]; export function Dashboard({ title, ranges, value, onChange, colors = PALETTE, locale }: Props) { const range = ranges.find((r) => r.id === value) ?? ranges[0]; const color = (i: number) => colors[i % colors.length]; return ( <section className={styles.root} aria-label={title}> <header className={styles.head}> <h2 className={styles.title}>{title}</h2> <PillTabs label="Range" tabs={ranges.map((r) => ({ value: r.id, label: r.label }))} value={range.id} onChange={onChange} /> </header> <div className={styles.stats}> {range.stats.map((s, i) => ( <StatCounter key={s.label} {...s} locale={locale} color={color(i)} /> ))} </div> <div className={styles.wide}> <AreaMorph label="Trend" values={range.trend} max={range.trendMax} labels={range.trendLabels} color={color(0)} /> <div className={styles.goal}> <ProgressRing label={range.goal.label} value={range.goal.value} max={range.goal.max} locale={locale} color={color(2)} /> </div> </div> <div className={styles.split}> <SpringBars label="Activity" data={range.bars} max={range.barsMax} locale={locale} color={color(1)} /> <RankList label="Top sellers" items={range.leaders} locale={locale} color={color(3)} /> </div> {(range.channels || range.activity) && ( <div className={styles.split}> {range.channels && <DonutMorph label="Visits" parts={range.channels.map((c, i) => ({ ...c, color: color(i) }))} locale={locale} />} {range.activity && <DotGrid label="Activity" values={range.activity} summary={`${range.label}: ${range.activity.length} days`} color={color(1)} />} </div> )} </section> ); }components/fluid/dashboard/Dashboard.module.css .root { display: grid; gap: 14px; width: min(100%, 980px); padding: 18px; border-radius: 32px; background: var(--fluid-surface-2); color: var(--fluid-text); font-family: var(--fluid-font); } .head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; padding: 4px 6px; } .title { margin: 0; font-size: 22px; font-weight: 600; letter-spacing: -0.02em; } .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; } .stats > * { min-width: 0; } .wide, .split { display: grid; gap: 14px; } .wide { grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); } .split { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } .wide > *, .split > * { width: 100%; max-width: none; } .goal { display: grid; place-items: center; padding: 18px; border-radius: 24px; background: var(--fluid-surface); } @media (max-width: 720px) { .wide, .split { grid-template-columns: minmax(0, 1fr); } }It uses these pieces too, so copy them alongside:
components/fluid/area-morph/AreaMorph.tsx "use client"; import { MorphPath } from "@usefluid/motion/react"; import { type CSSProperties, useId } from "react"; import { areaPath } from "./area"; import styles from "./AreaMorph.module.css"; const FLOW = { w: 11, z: 0.72, spread: 0.35 }; type Props = { label: string; values: number[]; max?: number; labels?: string[]; color?: string; }; export function AreaMorph({ label, values, max, labels, color }: Props) { const gradient = `fluid-area-${useId().replace(/[^a-zA-Z0-9]/g, "")}`; const d = areaPath(values, max); return ( <figure className={styles.root} style={color ? ({ "--fluid-accent": color, "--fluid-on-accent": "#ffffff" } as CSSProperties) : undefined}> <svg viewBox="0 0 120 120" preserveAspectRatio="none" className={styles.chart} role="img" aria-label={`${label}: ${values.join(", ")}`}> <defs> <linearGradient id={gradient} x1="0" y1="0" x2="0" y2="1"> <stop offset="0" style={{ stopColor: "var(--fluid-accent)" }} /> <stop offset="1" style={{ stopColor: "var(--fluid-accent)", stopOpacity: 0.12 }} /> </linearGradient> </defs> <MorphPath d={d} fill={`url(#${gradient})`} config={FLOW} /> </svg> {labels && ( <div className={styles.axis} aria-hidden> {labels.map((l) => ( <span key={l}>{l}</span> ))} </div> )} </figure> ); }components/fluid/area-morph/area.test.ts import { describe, expect, it } from "vitest"; import { parsePath, sampleContours } from "../../packages/motion/src/index"; import { areaPath } from "./area"; describe("areaPath", () => { it("draws one closed shape that fills the 120 box from edge to edge", () => { const d = areaPath([3, 8, 5, 12, 9], 12); expect(() => parsePath(d)).not.toThrow(); const [c] = sampleContours(d); expect(sampleContours(d)).toHaveLength(1); expect(Math.min(...c.x)).toBeCloseTo(0, 1); expect(Math.max(...c.x)).toBeCloseTo(120, 1); expect(Math.max(...c.y)).toBeCloseTo(120, 1); }); it("puts the highest value near the top and keeps a floor for zeros", () => { const [c] = sampleContours(areaPath([0, 10, 0], 10)); expect(Math.min(...c.y)).toBeLessThan(20); expect(Math.min(...c.y)).toBeGreaterThanOrEqual(0); const [flat] = sampleContours(areaPath([0, 0, 0], 10)); expect(Math.min(...flat.y)).toBeLessThan(120); }); it("handles a single value and an empty list", () => { expect(() => sampleContours(areaPath([4], 10))).not.toThrow(); expect(() => sampleContours(areaPath([], 10))).not.toThrow(); }); });components/fluid/area-morph/area.ts const BOX = 120; const TOP = 8; const FLOOR = 6; const clamp = (v: number) => Math.min(BOX, Math.max(0, v)); const r = (v: number) => Math.round(v * 100) / 100; export function areaPath(values: number[], max = Math.max(1, ...values)): string { const span = BOX - TOP - FLOOR; const heightOf = (v: number) => clamp(BOX - FLOOR - (Math.max(0, v) / (max || 1)) * span); const ys = values.length ? values.map(heightOf) : [BOX - FLOOR]; if (ys.length === 1) ys.push(ys[0]); const step = BOX / (ys.length - 1); const pts = ys.map((y, i) => [i * step, y] as const); let d = `M0 ${BOX}L0 ${r(pts[0][1])}`; for (let i = 0; i < pts.length - 1; i++) { const p0 = pts[Math.max(0, i - 1)]; const p1 = pts[i]; const p2 = pts[i + 1]; const p3 = pts[Math.min(pts.length - 1, i + 2)]; const c1x = p1[0] + (p2[0] - p0[0]) / 6; const c1y = clamp(p1[1] + (p2[1] - p0[1]) / 6); const c2x = p2[0] - (p3[0] - p1[0]) / 6; const c2y = clamp(p2[1] - (p3[1] - p1[1]) / 6); d += `C${r(c1x)} ${r(c1y)} ${r(c2x)} ${r(c2y)} ${r(p2[0])} ${r(p2[1])}`; } return `${d}L${BOX} ${BOX}Z`; }components/fluid/area-morph/AreaMorph.module.css .root { display: grid; gap: 10px; width: min(100%, 460px); margin: 0; padding: 22px 22px 16px; border-radius: 24px; background: var(--fluid-surface); color: var(--fluid-text); font-family: var(--fluid-font); } .chart { display: block; width: 100%; height: 170px; overflow: visible; } .axis { display: flex; justify-content: space-between; color: var(--fluid-text-2); font-size: 12px; }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; }components/fluid/dot-grid/DotGrid.tsx "use client"; import { useSpring } from "@usefluid/motion/react"; import { type CSSProperties, useRef } from "react"; import { levelOf } from "./grid"; import styles from "./DotGrid.module.css"; type Props = { label: string; values: number[]; max?: number; rows?: number; summary?: string; color?: string; }; function Cell({ level, wave }: { level: number; wave: number }) { const dot = useRef<HTMLSpanElement>(null); useSpring( { s: level / 4 }, ({ s }) => { if (dot.current) dot.current.style.transform = `scale(${0.38 + Math.max(0, s) * 0.62})`; }, { w: Math.max(8, 18 - wave * 0.45), z: 0.55 }, ); return <span ref={dot} className={styles.dot} data-level={level} />; } export function DotGrid({ label, values, max, rows = 7, summary, color }: Props) { const top = max ?? Math.max(1, ...values); return ( <figure className={styles.root} style={color ? ({ "--fluid-accent": color } as CSSProperties) : undefined}> <div className={styles.grid} style={{ gridTemplateRows: `repeat(${rows}, auto)` }} role="img" aria-label={summary ? `${label}: ${summary}` : label}> {values.map((v, i) => ( <Cell key={i} level={levelOf(v, top)} wave={Math.floor(i / rows) + (i % rows)} /> ))} </div> <figcaption className={styles.caption}> <span>{label}</span> <span className={styles.scale} aria-hidden> {[0, 1, 2, 3, 4].map((l) => ( <span key={l} className={styles.dot} data-level={l} /> ))} </span> </figcaption> </figure> ); }components/fluid/dot-grid/grid.test.ts import { describe, expect, it } from "vitest"; import { levelOf } from "./grid"; describe("levelOf", () => { it("maps a value to one of five levels against the max", () => { expect([0, 1, 25, 50, 75, 100].map((v) => levelOf(v, 100))).toEqual([0, 1, 1, 2, 3, 4]); }); it("never leaves the range", () => { expect(levelOf(-5, 10)).toBe(0); expect(levelOf(50, 10)).toBe(4); expect(levelOf(3, 0)).toBe(0); }); });components/fluid/dot-grid/grid.ts export function levelOf(value: number, max: number): number { if (!(value > 0) || !(max > 0)) return 0; return Math.min(4, Math.max(1, Math.ceil((value / max) * 4))); }components/fluid/dot-grid/DotGrid.module.css .root { display: grid; gap: 14px; width: min(100%, 520px); margin: 0; padding: 22px; border-radius: 24px; background: var(--fluid-surface); color: var(--fluid-text); font-family: var(--fluid-font); } .grid { display: grid; grid-auto-columns: minmax(0, 1fr); grid-auto-flow: column; gap: 5px; } .dot { display: block; aspect-ratio: 1; border-radius: 999px; background: color-mix(in srgb, var(--fluid-text) 8%, transparent); transition: background 300ms ease; } .dot[data-level="1"] { background: color-mix(in srgb, var(--fluid-accent) 30%, var(--fluid-surface)); } .dot[data-level="2"] { background: color-mix(in srgb, var(--fluid-accent) 55%, var(--fluid-surface)); } .dot[data-level="3"] { background: color-mix(in srgb, var(--fluid-accent) 78%, var(--fluid-surface)); } .dot[data-level="4"] { background: var(--fluid-accent); } .caption { display: flex; align-items: center; justify-content: space-between; color: var(--fluid-text-2); font-size: 13px; } .scale { display: flex; gap: 4px; } .scale .dot { width: 10px; }components/fluid/pill-tabs/PillTabs.tsx "use client"; import { useSpring } from "@usefluid/motion/react"; import { type KeyboardEvent, type ReactNode, useEffect, useLayoutEffect, useRef, useState } from "react"; import styles from "./PillTabs.module.css"; const LEAD = { w: 30, z: 0.82 }; const TRAIL = { w: 16, z: 0.8 }; type Tab = { value: string; label: ReactNode; count?: number }; type Props = { label: string; tabs: Tab[]; value: string; onChange(value: string): void }; export function PillTabs({ label, tabs, value, onChange }: Props) { const list = useRef<HTMLDivElement>(null); const pill = useRef<HTMLSpanElement>(null); const [box, setBox] = useState<{ left: number; right: number } | null>(null); const last = useRef({ left: 0, placed: false }); useLayoutEffect(() => { const measure = () => { const el = list.current?.querySelector<HTMLElement>('[aria-selected="true"]'); if (el) setBox({ left: el.offsetLeft, right: el.offsetLeft + el.offsetWidth }); }; measure(); const observer = new ResizeObserver(measure); if (list.current) observer.observe(list.current); return () => observer.disconnect(); }, [value]); useEffect(() => { if (box) last.current = { left: box.left, placed: true }; }, [box]); const right = !box || box.left >= last.current.left; const immediate = !last.current.placed; const edges = useRef({ left: 0, right: 0 }); const paint = () => { if (!pill.current) return; pill.current.style.transform = `translateX(${edges.current.left}px)`; pill.current.style.width = `${Math.max(0, edges.current.right - edges.current.left)}px`; }; useSpring( { v: box?.left ?? 0 }, ({ v }) => { edges.current.left = v; paint(); }, { ...(right ? TRAIL : LEAD), immediate }, ); useSpring( { v: box?.right ?? 0 }, ({ v }) => { edges.current.right = v; paint(); }, { ...(right ? LEAD : TRAIL), immediate }, ); const move = (e: KeyboardEvent, i: number) => { const d = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0; if (!d) return; e.preventDefault(); const next = (i + d + tabs.length) % tabs.length; onChange(tabs[next].value); list.current?.querySelectorAll<HTMLElement>('[role="tab"]')[next]?.focus(); }; return ( <div ref={list} role="tablist" aria-label={label} className={styles.list}> <span ref={pill} className={styles.pill} data-on={box ? "" : undefined} aria-hidden /> {tabs.map((tab, i) => ( <button key={tab.value} type="button" role="tab" aria-selected={tab.value === value} tabIndex={tab.value === value ? 0 : -1} className={styles.tab} onClick={() => onChange(tab.value)} onKeyDown={(e) => move(e, i)} > {tab.label} {tab.count !== undefined && <span className={styles.count}>{tab.count}</span>} </button> ))} </div> ); }components/fluid/pill-tabs/PillTabs.module.css .list { position: relative; display: inline-flex; max-width: 100%; padding: 6px; overflow-x: auto; border-radius: 999px; background: var(--fluid-accent); scrollbar-width: none; isolation: isolate; } .pill { position: absolute; z-index: -1; top: 6px; bottom: 6px; left: 0; border-radius: 999px; background: var(--fluid-on-accent); opacity: 0; } .pill[data-on] { opacity: 1; } .tab { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 0 18px; border: 0; border-radius: 999px; background: none; color: var(--fluid-on-accent); font: 500 15px / 1 var(--fluid-font); white-space: nowrap; cursor: pointer; transition: color 200ms ease; } .tab[aria-selected="true"] { color: var(--fluid-accent); } .tab:focus-visible { outline: 2px solid var(--fluid-focus); outline-offset: 2px; } .count { display: grid; place-items: center; min-width: 24px; height: 22px; padding: 0 7px; border-radius: 999px; background: color-mix(in srgb, currentColor 16%, transparent); font-size: 12px; font-variant-numeric: tabular-nums; }components/fluid/progress-ring/ProgressRing.tsx "use client"; import { useSpring } from "@usefluid/motion/react"; import { useMemo, useRef, useState } from "react"; import styles from "./ProgressRing.module.css"; const R = 52; const LENGTH = 2 * Math.PI * R; const FILL = { w: 8, z: 0.72 }; type Props = { label: string; value: number; max?: number; size?: number; locale?: string; color?: string; }; export function ProgressRing({ label, value, max = 100, size = 168, locale, color }: Props) { const arc = useRef<SVGCircleElement>(null); const out = useRef<HTMLSpanElement>(null); const percent = useMemo(() => new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 0 }), [locale]); const share = max > 0 ? Math.min(1, Math.max(0, value / max)) : 0; const [first] = useState(() => percent.format(share)); useSpring( { s: share }, ({ s }) => { const shown = Math.min(1.04, Math.max(0, s)); if (arc.current) arc.current.style.strokeDashoffset = `${LENGTH * (1 - shown)}`; if (out.current) out.current.textContent = percent.format(Math.min(1, Math.max(0, s))); }, FILL, ); return ( <div className={styles.root} role="progressbar" aria-label={label} aria-valuemin={0} aria-valuemax={max} aria-valuenow={Math.min(max, Math.max(0, value))} data-done={share >= 1 ? "" : undefined} style={{ width: size, ...(color ? { "--fluid-accent": color, "--fluid-on-accent": "#ffffff" } : {}) }} > <svg viewBox="0 0 120 120" className={styles.ring} aria-hidden> <circle cx={60} cy={60} r={R} className={styles.track} /> <circle ref={arc} cx={60} cy={60} r={R} className={styles.arc} strokeDasharray={LENGTH} strokeDashoffset={LENGTH * (1 - share)} /> </svg> <span className={styles.center} aria-hidden> <span ref={out} className={styles.value}> {first} </span> <span className={styles.label}>{label}</span> </span> </div> ); }components/fluid/progress-ring/ProgressRing.module.css .root { position: relative; display: grid; place-items: center; aspect-ratio: 1; color: var(--fluid-text); font-family: var(--fluid-font); } .ring { width: 100%; height: 100%; transform: rotate(-90deg); } .track, .arc { fill: none; stroke-width: 12; } .track { stroke: color-mix(in srgb, var(--fluid-text) 9%, transparent); } .arc { stroke: var(--fluid-accent); stroke-linecap: round; } .center { position: absolute; display: grid; justify-items: center; gap: 2px; max-width: 62%; text-align: center; } .value { font-size: 34px; font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: -0.03em; line-height: 1; } .label { color: var(--fluid-text-2); font-size: 12px; font-weight: 500; } .root[data-done] .arc { animation: done 600ms cubic-bezier(0.3, 1.6, 0.5, 1); } @keyframes done { 40% { stroke-width: 16; } } @media (prefers-reduced-motion: reduce) { .root[data-done] .arc { animation: none; } }components/fluid/rank-list/RankList.tsx "use client"; import { useSpring } from "@usefluid/motion/react"; import { type CSSProperties, useMemo, useRef, useState } from "react"; import { type Ranked, rank, roundLike } from "./rank"; import styles from "./RankList.module.css"; const ROW = 60; const MOVE = { w: 13, z: 0.74 }; const ROLL = { w: 9, z: 1 }; type Props = { label: string; items: Ranked[]; order?: "desc" | "asc"; format?: Intl.NumberFormatOptions; locale?: string; color?: string; }; function Row({ item, place, number }: { item: Ranked; place: number; number: Intl.NumberFormat }) { const row = useRef<HTMLLIElement>(null); const out = useRef<HTMLSpanElement>(null); const [first] = useState(() => number.format(item.value)); useSpring( { y: place }, ({ y }, { y: v }) => { if (!row.current) return; row.current.style.transform = `translateY(${y * ROW}px) scale(${1 + Math.min(0.04, Math.abs(v) * 0.01)})`; row.current.style.zIndex = v < -0.05 ? "2" : "1"; }, MOVE, ); useSpring( { v: item.value }, ({ v }) => { if (out.current) out.current.textContent = number.format(roundLike(v, item.value)); }, ROLL, ); return ( <li ref={row} className={styles.row} data-top={place === 0 ? "" : undefined}> <span className={styles.place} aria-hidden> {place + 1} </span> <span className={styles.name}>{item.label}</span> <span ref={out} className={styles.value} aria-hidden> {first} </span> <span className={styles.hidden}>{number.format(item.value)}</span> </li> ); } export function RankList({ label, items, order = "desc", format, locale, color }: Props) { const key = JSON.stringify(format ?? {}); const number = useMemo(() => new Intl.NumberFormat(locale, JSON.parse(key)), [locale, key]); const ranked = rank(items, order); return ( <figure className={styles.root} style={color ? ({ "--fluid-accent": color, "--fluid-on-accent": "#ffffff" } as CSSProperties) : undefined}> <figcaption className={styles.label}>{label}</figcaption> <ol className={styles.list} style={{ height: ranked.length * ROW }}> {ranked.map((item, place) => ( <Row key={item.id} item={item} place={place} number={number} /> ))} </ol> </figure> ); }components/fluid/rank-list/rank.test.ts import { describe, expect, it } from "vitest"; import { rank, roundLike } from "./rank"; describe("rank", () => { it("orders by value, highest first", () => { const items = [ { id: "a", label: "Ana", value: 3 }, { id: "b", label: "Bia", value: 9 }, { id: "c", label: "Caio", value: 5 }, ]; expect(rank(items).map((i) => i.id)).toEqual(["b", "c", "a"]); }); it("keeps ties in the order they were given, so rows do not swap back and forth", () => { const items = [ { id: "x", label: "Xu", value: 4 }, { id: "y", label: "Yan", value: 4 }, ]; expect(rank(items).map((i) => i.id)).toEqual(["x", "y"]); expect(rank([...items].reverse()).map((i) => i.id)).toEqual(["y", "x"]); }); it("orders lowest first when asked, and does not change the input", () => { const items = [ { id: "a", label: "A", value: 2 }, { id: "b", label: "B", value: 1 }, ]; expect(rank(items, "asc").map((i) => i.id)).toEqual(["b", "a"]); expect(items[0].id).toBe("a"); }); }); describe("roundLike", () => { it("rounds a rolling number to the decimals of where it is going", () => { expect(roundLike(511.344, 540)).toBe(511); expect(roundLike(12.3456, 19.5)).toBe(12.3); expect(roundLike(0.12345, 0.25)).toBe(0.12); }); });components/fluid/rank-list/rank.ts export type Ranked = { id: string; label: string; value: number }; export function rank<T extends Ranked>(items: T[], order: "desc" | "asc" = "desc"): T[] { const sign = order === "desc" ? -1 : 1; return items .map((item, i) => ({ item, i })) .sort((a, b) => sign * (a.item.value - b.item.value) || a.i - b.i) .map(({ item }) => item); } export function roundLike(value: number, target: number): number { const decimals = Number.isFinite(target) ? (String(target).split(".")[1] ?? "").length : 0; return Number(value.toFixed(Math.min(decimals, 6))); }components/fluid/rank-list/RankList.module.css .root { display: grid; gap: 12px; width: min(100%, 380px); margin: 0; padding: 20px; border-radius: 24px; background: var(--fluid-surface); color: var(--fluid-text); font-family: var(--fluid-font); } .label { padding-left: 4px; color: var(--fluid-text-2); font-size: 14px; font-weight: 500; } .list { position: relative; margin: 0; padding: 0; list-style: none; } .row { position: absolute; top: 0; right: 0; left: 0; display: flex; align-items: center; gap: 14px; height: 52px; padding: 0 16px 0 10px; border-radius: 16px; background: color-mix(in srgb, var(--fluid-text) 5%, var(--fluid-surface)); will-change: transform; } .row[data-top] { background: var(--fluid-accent); color: var(--fluid-on-accent); } .place { display: grid; place-items: center; width: 32px; height: 32px; border-radius: 999px; background: color-mix(in srgb, currentColor 10%, transparent); font-size: 13px; font-weight: 600; font-variant-numeric: tabular-nums; } .name { flex: 1; min-width: 0; overflow: hidden; font-size: 15px; font-weight: 500; text-overflow: ellipsis; white-space: nowrap; } .value { font-size: 15px; font-weight: 600; font-variant-numeric: tabular-nums; } .hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }components/fluid/spring-bars/SpringBars.tsx "use client"; import { useSpring } from "@usefluid/motion/react"; import { type CSSProperties, type KeyboardEvent, useMemo, useRef, useState } from "react"; import styles from "./SpringBars.module.css"; type Datum = { label: string; value: number; color?: string }; type Props = { label: string; data: Datum[]; max?: number; format?: Intl.NumberFormatOptions; locale?: string; color?: string; }; function Bar({ share, index }: { share: number; index: number }) { const fill = useRef<HTMLSpanElement>(null); useSpring( { h: share }, ({ h }) => { if (fill.current) fill.current.style.height = `${Math.max(0, h) * 100}%`; }, { w: Math.max(9, 15 - index * 0.45), z: 0.6 }, ); return <span ref={fill} className={styles.fill} />; } export function SpringBars({ label, data, max, format, locale, color }: Props) { const plot = useRef<HTMLDivElement>(null); const bubble = useRef<HTMLSpanElement>(null); const [active, setActive] = useState(data.length - 1); const key = JSON.stringify(format ?? {}); const number = useMemo(() => new Intl.NumberFormat(locale, JSON.parse(key)), [locale, key]); const top = max ?? Math.max(1, ...data.map((d) => d.value)); const current = Math.min(active, data.length - 1); const shareOf = (v: number) => Math.min(1, Math.max(0, v / top)); useSpring( { x: data.length ? (current + 0.5) / data.length : 0.5, y: data.length ? shareOf(data[current].value) : 0 }, ({ x, y }) => { if (!bubble.current) return; bubble.current.style.left = `${x * 100}%`; bubble.current.style.bottom = `${y * 100}%`; }, { w: 16, z: 0.72 }, ); const move = (e: KeyboardEvent, i: number) => { const next = e.key === "ArrowRight" ? i + 1 : e.key === "ArrowLeft" ? i - 1 : e.key === "Home" ? 0 : e.key === "End" ? data.length - 1 : -1; if (next < 0 || next >= data.length) return; e.preventDefault(); setActive(next); plot.current?.querySelectorAll<HTMLElement>("button")[next]?.focus(); }; return ( <figure className={styles.root} aria-label={label} style={color ? ({ "--fluid-accent": color, "--fluid-on-accent": "#ffffff" } as CSSProperties) : undefined} > <div ref={plot} className={styles.plot} role="group" aria-label={label}> {data.map((d, i) => ( <button key={d.label} type="button" className={styles.column} style={d.color ? ({ "--bar": d.color } as CSSProperties) : undefined} data-active={i === current ? "" : undefined} tabIndex={i === current ? 0 : -1} aria-label={`${d.label}: ${number.format(d.value)}`} onPointerEnter={() => setActive(i)} onFocus={() => setActive(i)} onKeyDown={(e) => move(e, i)} > <Bar share={shareOf(d.value)} index={i} /> </button> ))} {data.length > 0 && ( <span ref={bubble} className={styles.bubble} aria-hidden> {number.format(data[current].value)} </span> )} </div> <div className={styles.axis} aria-hidden> {data.map((d) => ( <span key={d.label}>{d.label}</span> ))} </div> </figure> ); }components/fluid/spring-bars/SpringBars.module.css .root { display: grid; gap: 10px; width: min(100%, 420px); margin: 0; padding: 24px 22px 18px; border-radius: 24px; background: var(--fluid-surface); color: var(--fluid-text); font-family: var(--fluid-font); } .plot { position: relative; display: flex; align-items: stretch; gap: 8px; height: 180px; margin-top: 36px; } .column { position: relative; display: flex; flex: 1; align-items: flex-end; min-width: 0; padding: 0; border: 0; border-radius: 12px; background: color-mix(in srgb, var(--fluid-text) 5%, transparent); cursor: pointer; } .column:focus-visible { outline: 2px solid var(--fluid-focus); outline-offset: 2px; } .fill { width: 100%; min-height: 8px; border-radius: 12px; background: color-mix(in srgb, var(--bar, var(--fluid-accent)) 45%, var(--fluid-surface)); transition: background 250ms ease; } .column[data-active] .fill { background: var(--bar, var(--fluid-accent)); } .bubble { position: absolute; z-index: 1; padding: 6px 10px; border-radius: 999px; background: var(--fluid-text); color: var(--fluid-surface); font-size: 13px; font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; transform: translate(-50%, -8px); pointer-events: none; } .axis { display: flex; gap: 8px; color: var(--fluid-text-2); font-size: 12px; } .axis span { flex: 1; min-width: 0; overflow: hidden; text-align: center; text-overflow: ellipsis; }components/fluid/stat-counter/StatCounter.tsx "use client"; import { MorphPath, useSpring } from "@usefluid/motion/react"; import { type CSSProperties, useMemo, useRef, useState } from "react"; import styles from "./StatCounter.module.css"; const UP = "M60 18L102 64H74V102H46V64H18Z"; const DOWN = "M60 102L18 56H46V18H74V56H102Z"; const ROLL = { w: 9, z: 1 }; const tint = (color?: string) => (color ? ({ "--fluid-accent": color, "--fluid-on-accent": "#ffffff" } as CSSProperties) : undefined); const roundLike = (v: number, target: number) => Number(v.toFixed(Math.min(6, (String(target).split(".")[1] ?? "").length))); type Props = { label: string; value: number; previous?: number; format?: Intl.NumberFormatOptions; locale?: string; upIsGood?: boolean; color?: string; }; export function StatCounter({ label, value, previous, format, locale, upIsGood = true, color }: Props) { const out = useRef<HTMLSpanElement>(null); 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: 1 }), [locale]); const [first] = useState(() => number.format(value)); useSpring( { v: value }, ({ v }) => { if (out.current) out.current.textContent = number.format(roundLike(v, value)); }, ROLL, ); const change = previous === undefined || previous === 0 ? null : (value - previous) / Math.abs(previous); const up = change !== null && change >= 0; const good = up === upIsGood; return ( <div className={styles.card} style={tint(color)}> <span className={styles.label}>{label}</span> <span ref={out} className={styles.value} aria-hidden> {first} </span> <span className={styles.hidden}>{number.format(value)}</span> {change !== null && ( <span className={styles.delta} data-good={good ? "" : undefined}> <svg viewBox="0 0 120 120" width={12} height={12} aria-hidden> <MorphPath d={up ? UP : DOWN} fill="currentColor" config={{ w: 18, z: 0.62 }} /> </svg> <span className={styles.hidden}>{up ? "up" : "down"}</span> {percent.format(Math.abs(change))} </span> )} </div> ); }components/fluid/stat-counter/StatCounter.module.css .card { display: grid; gap: 10px; justify-items: start; min-width: 220px; padding: 22px 24px; border-radius: 24px; background: var(--fluid-surface); color: var(--fluid-text); font-family: var(--fluid-font); } .label { display: inline-flex; align-items: center; gap: 8px; color: var(--fluid-text-2); font-size: 14px; font-weight: 500; } .label::before { width: 8px; height: 8px; border-radius: 999px; background: var(--fluid-accent); content: ""; } .value { font-size: 44px; font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: -0.03em; line-height: 1; } .delta { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 12px 0 10px; border-radius: 999px; background: color-mix(in srgb, #e5484d 16%, transparent); color: #e5484d; font-size: 13px; font-weight: 600; font-variant-numeric: tabular-nums; transition: background 300ms ease, color 300ms ease; } .delta[data-good] { background: color-mix(in srgb, #30a46c 16%, transparent); color: #30a46c; } .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 { Dashboard } from "./Dashboard";
const [range, setRange] = useState("week");
<Dashboard title="Store" ranges={ranges} value={range} onChange={setRange} />API reference
| Prop | Type | Default | Description |
|---|---|---|---|
title | string | — | The heading of the dashboard. |
ranges | Range[] | — | One entry per tab, such as week, month and year, each with its stats, trend, bars, goal and leaders. See the Range type. |
value | string | — | The id of the range shown. |
onChange | (id) => void | — | Called when another range is picked. |
colors | string[] | violet, teal, orange, pink | The colours of the stats and charts, in order. |
locale | string | the browser's | Locale for numbers and percents. |
Keyboard and screen readers
The range is a tab list: arrow keys move between ranges. Every piece keeps its own reading: stats read their final values, bars are buttons, the trend is an image, the goal is a progress bar and the ranking is an ordered list. With reduced motion every change is immediate.
Notes
It is a starting point: copy it, drop the parts you do not need, and feed it your real numbers. Keep trendMax and barsMax the same across ranges when the numbers are comparable. Every piece inside is yours to change.
How it is made
It is made of the Data pieces: Stat Counter, Area Morph, Spring Bars, Progress Ring, Rank List, Donut Morph and Dot Grid, with Pill Tabs for the range. Each keeps its own springs, so one change spreads through the page at slightly different speeds, like a single motion. Colours come in order from a palette you can replace.
For your agent
For your agent
Add Dashboard to my project with the Fluid library. Build my dashboard with Dashboard, using my real metrics for each range and my brand 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.