/* ═══════════════════════════════════════════════════════════════ STATS BAND The numbers from the admin's Front page editor, counted by the API or typed in. Each one counts up from zero the first time the band scrolls into view; a value that isn't a plain number ("Since 2004", "Coast to coast") just appears. Reduced motion skips the count and shows the number. ═══════════════════════════════════════════════════════════════ */ import { useEffect, useRef, useState } from 'react' import type { FrontPageStat } from '../../../lib/useFrontPage.ts' const COUNT_MS = 1400 type StatsBandProps = { id: string title: string blurb?: string | null stats: FrontPageStat[] } export default function StatsBand({ id, title, blurb, stats }: StatsBandProps) { const ref = useRef(null) const [seen, setSeen] = useState(false) useEffect(() => { const el = ref.current if (!el || seen) return const observer = new IntersectionObserver( ([entry]) => { if (entry.isIntersecting) { setSeen(true) observer.disconnect() } }, { threshold: 0.35 }, ) observer.observe(el) return () => observer.disconnect() }, [seen]) return (
) } /* "1,200" counts to 1,200 and keeps its comma; "12.5" keeps its decimal. Anything that isn't just a number renders as given. */ function CountUp({ value, run }: { value: string; run: boolean }) { const numeric = /^\d[\d,]*(\.\d+)?$/.test(value) const target = numeric ? Number(value.replace(/,/g, '')) : 0 const decimals = value.split('.')[1]?.length ?? 0 const grouped = value.includes(',') const reduced = typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches const [shown, setShown] = useState(0) useEffect(() => { if (!numeric || !run || reduced) return let frame = 0 const start = performance.now() const tick = (t: number) => { const p = Math.min(1, (t - start) / COUNT_MS) // Ease out: fast at first, settling onto the number. setShown(target * (1 - Math.pow(1 - p, 3))) if (p < 1) frame = requestAnimationFrame(tick) } frame = requestAnimationFrame(tick) return () => cancelAnimationFrame(frame) }, [numeric, run, reduced, target]) if (!numeric) return <>{value} const n = reduced || !run ? (run ? target : 0) : shown return ( {n.toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals, useGrouping: grouped || target >= 10_000, })} ) }