"use client"; import { useEffect, useRef, useState } from "react"; /** Decimals needed to show `value` exactly, capped at 2 (totals are rounded to 2dp). */ const decimalsOf = (value: number) => { const [, fraction = ""] = value.toFixed(2).replace(/0+$/, "").split("."); return fraction.length; }; /** Shows a number, counting up (or down) to each new value. Instant with reduced motion. */ export function CountUp({ value, durationMs }: { value: number; durationMs: number }) { const [shown, setShown] = useState(value); // Where the display currently is, so an update mid-count continues from there. const shownRef = useRef(value); useEffect(() => { const from = shownRef.current; if (from === value) return; const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches; const start = performance.now(); let frame = requestAnimationFrame(function tick(now) { const progress = reduced ? 1 : Math.min(1, (now - start) / durationMs); const eased = 1 - (1 - progress) ** 3; const next = progress === 1 ? value : from + (value - from) * eased; shownRef.current = next; setShown(next); if (progress < 1) frame = requestAnimationFrame(tick); }); return () => cancelAnimationFrame(frame); }, [value, durationMs]); // Count in whole numbers when the target is whole, so digits don't flicker with decimals. return <>{shown.toFixed(decimalsOf(value))}; }