2025-04-22 11:31:10 +02:00
|
|
|
"use client"
|
2025-04-18 17:05:46 +02:00
|
|
|
|
2025-04-22 11:31:10 +02:00
|
|
|
import { useInView, useMotionValue, useSpring } from "motion/react"
|
|
|
|
|
import { type ComponentPropsWithoutRef, useEffect, useRef } from "react"
|
2025-04-18 17:05:46 +02:00
|
|
|
|
2025-04-22 11:31:10 +02:00
|
|
|
import { cn } from "@/lib/utils"
|
2025-04-18 17:05:46 +02:00
|
|
|
|
|
|
|
|
interface NumberTickerProps extends ComponentPropsWithoutRef<"span"> {
|
2025-04-22 11:31:10 +02:00
|
|
|
value: number
|
|
|
|
|
startValue?: number
|
|
|
|
|
direction?: "up" | "down"
|
|
|
|
|
delay?: number
|
|
|
|
|
decimalPlaces?: number
|
2025-04-18 17:05:46 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function NumberTicker({
|
2025-04-22 11:31:10 +02:00
|
|
|
value,
|
|
|
|
|
startValue = 0,
|
|
|
|
|
direction = "up",
|
|
|
|
|
delay = 0,
|
|
|
|
|
className,
|
|
|
|
|
decimalPlaces = 0,
|
|
|
|
|
...props
|
2025-04-18 17:05:46 +02:00
|
|
|
}: NumberTickerProps) {
|
2025-04-22 11:31:10 +02:00
|
|
|
const ref = useRef<HTMLSpanElement>(null)
|
|
|
|
|
const motionValue = useMotionValue(direction === "down" ? value : startValue)
|
|
|
|
|
const springValue = useSpring(motionValue, {
|
|
|
|
|
damping: 30,
|
|
|
|
|
stiffness: 200,
|
|
|
|
|
})
|
|
|
|
|
const isInView = useInView(ref, { once: true, margin: "0px" })
|
2025-04-18 17:05:46 +02:00
|
|
|
|
2025-04-22 11:31:10 +02:00
|
|
|
useEffect(() => {
|
|
|
|
|
if (isInView) {
|
|
|
|
|
const timer = setTimeout(() => {
|
|
|
|
|
motionValue.set(direction === "down" ? startValue : value)
|
|
|
|
|
}, delay * 1000)
|
|
|
|
|
return () => clearTimeout(timer)
|
|
|
|
|
}
|
|
|
|
|
}, [motionValue, isInView, delay, value, direction, startValue])
|
2025-04-18 17:05:46 +02:00
|
|
|
|
2025-04-22 11:31:10 +02:00
|
|
|
useEffect(
|
|
|
|
|
() =>
|
|
|
|
|
springValue.on("change", (latest) => {
|
|
|
|
|
if (ref.current) {
|
|
|
|
|
ref.current.textContent = Number(latest.toFixed(decimalPlaces)).toString()
|
|
|
|
|
}
|
|
|
|
|
}),
|
|
|
|
|
[springValue, decimalPlaces],
|
|
|
|
|
)
|
2025-04-18 17:05:46 +02:00
|
|
|
|
2025-04-22 11:31:10 +02:00
|
|
|
return (
|
|
|
|
|
<span ref={ref} className={cn("inline-block tabular-nums tracking-wider", className)} {...props}>
|
|
|
|
|
{startValue}
|
|
|
|
|
</span>
|
|
|
|
|
)
|
2025-04-18 17:05:46 +02:00
|
|
|
}
|