svrjs-nextjs-website/components/widgets/num-tick.tsx

58 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-06-15 14:55:33 +02:00
"use client";
import { useEffect, useRef } from "react";
2024-07-05 21:20:59 +02:00
import { useInView, useMotionValue, useSpring } from "framer-motion";
2024-06-15 14:55:33 +02:00
2024-07-05 21:20:59 +02:00
import { cn } from "@/lib/utils";
export default function NumberTicker({
value,
direction = "up",
delay = 0,
className
2024-06-15 14:55:33 +02:00
}: {
value: number;
direction?: "up" | "down";
className?: string;
delay?: number; // delay in s
2024-06-15 14:55:33 +02:00
}) {
const ref = useRef<HTMLSpanElement>(null);
const motionValue = useMotionValue(direction === "down" ? value : 0);
const springValue = useSpring(motionValue, {
damping: 60,
stiffness: 100
});
const isInView = useInView(ref, { once: true, margin: "0px" });
2024-06-15 14:55:33 +02:00
useEffect(() => {
isInView &&
setTimeout(() => {
motionValue.set(direction === "down" ? 0 : value);
}, delay * 1000);
}, [motionValue, isInView, delay, value, direction]);
2024-06-15 14:55:33 +02:00
useEffect(
() =>
springValue.on("change", (latest) => {
if (ref.current) {
ref.current.textContent = Intl.NumberFormat("en-US").format(
latest.toFixed(0)
);
}
}),
[springValue]
);
2024-06-15 14:55:33 +02:00
return (
<span
className={cn(
"inline-block tabular-nums text-black dark:text-white tracking-wider",
className
)}
ref={ref}
2024-09-07 11:28:16 +02:00
>
0
</span>
);
2024-06-15 14:55:33 +02:00
}