@arolariu/components
Version:
A collection of reusable components for React applications, built as ESM & CJS modules with tree shake, minify and bundler optimizations enabled, for the lowest bundle size (import cost)! 😍
61 lines (60 loc) • 3.07 kB
JavaScript
"use client";
import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_225474f2__ from "react/jsx-runtime";
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE_motion_react_9decfa63__ from "motion/react";
const CountingNumber = /*#__PURE__*/ __WEBPACK_EXTERNAL_MODULE_react__.forwardRef(({ number, fromNumber = 0, padStart = false, inView = false, inViewMargin = "0px", inViewOnce = true, decimalSeparator = ".", transition = {
stiffness: 90,
damping: 50
}, decimalPlaces = 0, className, ...props }, ref)=>{
const localRef = __WEBPACK_EXTERNAL_MODULE_react__.useRef(null);
__WEBPACK_EXTERNAL_MODULE_react__.useImperativeHandle(ref, ()=>localRef.current);
const numberStr = number.toString();
const decimals = "number" == typeof decimalPlaces ? decimalPlaces : numberStr.includes(".") ? numberStr.split(".")[1].length : 0;
const motionVal = (0, __WEBPACK_EXTERNAL_MODULE_motion_react_9decfa63__.useMotionValue)(fromNumber);
const springVal = (0, __WEBPACK_EXTERNAL_MODULE_motion_react_9decfa63__.useSpring)(motionVal, transition);
const inViewResult = (0, __WEBPACK_EXTERNAL_MODULE_motion_react_9decfa63__.useInView)(localRef, {
once: inViewOnce,
margin: inViewMargin
});
const isInView = !inView || inViewResult;
__WEBPACK_EXTERNAL_MODULE_react__.useEffect(()=>{
if (isInView) motionVal.set(number);
}, [
isInView,
number,
motionVal
]);
__WEBPACK_EXTERNAL_MODULE_react__.useEffect(()=>{
const unsubscribe = springVal.on("change", (latest)=>{
if (localRef.current) {
let formatted = decimals > 0 ? latest.toFixed(decimals) : Math.round(latest).toString();
if (decimals > 0) formatted = formatted.replace(".", decimalSeparator);
if (padStart) {
const finalIntLength = Math.floor(Math.abs(number)).toString().length;
const [intPart, fracPart] = formatted.split(decimalSeparator);
const paddedInt = intPart.padStart(finalIntLength, "0");
formatted = fracPart ? `${paddedInt}${decimalSeparator}${fracPart}` : paddedInt;
}
localRef.current.textContent = formatted;
}
});
return ()=>unsubscribe();
}, [
springVal,
decimals,
padStart,
number,
decimalSeparator
]);
const finalIntLength = Math.floor(Math.abs(number)).toString().length;
const initialText = padStart ? "0".padStart(finalIntLength, "0") + (decimals > 0 ? decimalSeparator + "0".repeat(decimals) : "") : "0" + (decimals > 0 ? decimalSeparator + "0".repeat(decimals) : "");
return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_225474f2__.jsx)("span", {
ref: localRef,
className: className,
...props,
children: initialText
});
});
CountingNumber.displayName = "CountingNumber";
export { CountingNumber };
//# sourceMappingURL=counting-number.js.map