1"use client"
2
3import { useEffect, useRef, type ComponentPropsWithoutRef } from "react"
4import { useInView, useMotionValue, useSpring } from "motion/react"
5
6import { cn } from "@/lib/utils"
7
8interface NumberTickerProps extends ComponentPropsWithoutRef<"span"> {
9 value: number
10 startValue?: number
11 direction?: "up" | "down"
12 delay?: number
13 decimalPlaces?: number
14}
15
16export function NumberTicker({
17 value,
18 startValue = 0,
19 direction = "up",
20 delay = 0,
21 className,
22 decimalPlaces = 0,
23 ...props
24}: NumberTickerProps) {
25 const ref = useRef<HTMLSpanElement>(null)
26 const motionValue = useMotionValue(direction === "down" ? value : startValue)
27 const springValue = useSpring(motionValue, {
28 damping: 60,
29 stiffness: 100,
30 })
31 const isInView = useInView(ref, { once: true, margin: "0px" })
32
33 useEffect(() => {
34 let timer: ReturnType<typeof setTimeout> | null = null
35
36 if (isInView) {
37 timer = setTimeout(() => {
38 motionValue.set(direction === "down" ? startValue : value)
39 }, delay * 1000)
40 }
41
42 return () => {
43 if (timer !== null) {
44 clearTimeout(timer)
45 }
46 }
47 }, [motionValue, isInView, delay, value, direction, startValue])
48
49 useEffect(
50 () =>
51 springValue.on("change", (latest) => {
52 if (ref.current) {
53 ref.current.textContent = Intl.NumberFormat("en-US", {
54 minimumFractionDigits: decimalPlaces,
55 maximumFractionDigits: decimalPlaces,
56 }).format(Number(latest.toFixed(decimalPlaces)))
57 }
58 }),
59 [springValue, decimalPlaces]
60 )
61
62 return (
63 <span
64 ref={ref}
65 className={cn(
66 "inline-block tracking-wider text-black tabular-nums dark:text-white",
67 className
68 )}
69 {...props}
70 >
71 {startValue}
72 </span>
73 )
74}
75