CountUp.tsx 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { useEffect, useRef, useState } from 'react'
  2. import { animate, useReducedMotion } from 'framer-motion'
  3. import { fmtEs } from '@/data/mock'
  4. import { numLocale } from '@/i18n'
  5. interface CountUpProps {
  6. value: number
  7. decimals?: number
  8. duration?: number
  9. /** Al cambiar, re-anima desde 0 (p. ej. refresh global) */
  10. nonce?: number
  11. className?: string
  12. }
  13. /** Cifra con count-up 800ms easeOutCubic (design.md §8). Respeta reduced-motion. */
  14. export function CountUp({ value, decimals = 0, duration = 0.8, nonce, className }: CountUpProps) {
  15. const [display, setDisplay] = useState(0)
  16. const prev = useRef(0)
  17. const reduce = useReducedMotion()
  18. useEffect(() => {
  19. const from = nonce !== undefined ? 0 : prev.current
  20. if (reduce) {
  21. setDisplay(value)
  22. prev.current = value
  23. return
  24. }
  25. const controls = animate(from, value, {
  26. duration,
  27. ease: [0.33, 1, 0.68, 1], // easeOutCubic
  28. onUpdate: (v) => setDisplay(v),
  29. })
  30. prev.current = value
  31. return () => controls.stop()
  32. }, [value, duration, reduce, nonce])
  33. return <span className={className}>{decimals > 0 ? fmtEs(display, decimals) : Math.round(display).toLocaleString(numLocale())}</span>
  34. }