File size: 1,348 Bytes
589f639
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { useEffect, useRef, useState } from 'react';

/** A number that counts up from 0 to its value when it first shows, with an expo ease (the Sheryians feel). The final

 * value is what screen readers and copy/paste get; reduced motion shows it straight away. */
export function CountUp({ value, suffix = '', duration = 1100 }: { value: number; suffix?: string; duration?: number }) {
  const [shown, setShown] = useState(value);
  const from = useRef(0);
  useEffect(() => {
    const still = typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
    if (still || typeof requestAnimationFrame === 'undefined') { setShown(value); return; }
    const start = performance.now();
    const a = from.current;
    let id = 0;
    const tick = (t: number) => {
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(2, -10 * p);   // expo out
      setShown(Math.round(a + (value - a) * (p === 1 ? 1 : eased)));
      if (p < 1) id = requestAnimationFrame(tick); else from.current = value;
    };
    id = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(id);
  }, [value, duration]);
  return (
    <span className="pw-countup" aria-label={`${value}${suffix}`}>

      <span aria-hidden>{shown}{suffix}</span>

    </span>
  );
}