- 新增 hooks/components/lib 共 9 个测试文件,覆盖边界条件与异常路径 - 补充 animations.test.tsx 用例(RotatingBorder、CounterWithEffect 等) - 修复 useCountUp 结束时 toFixed 精度问题 - 调整 jest 覆盖率配置为渐进式阈值,收缩收集范围 - 新增 docs/lessons-learned.md(经验教训汇总)与 docs/troubleshooting.md(问题排查索引) - 更新 README.md 文档索引
64 lines
1.4 KiB
TypeScript
64 lines
1.4 KiB
TypeScript
'use client';
|
|
|
|
import { useState, useEffect, useRef } from 'react';
|
|
|
|
interface UseCountUpOptions {
|
|
end: number;
|
|
duration?: number;
|
|
start?: number;
|
|
decimals?: number;
|
|
easing?: (t: number) => number;
|
|
enabled?: boolean;
|
|
}
|
|
|
|
const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3);
|
|
|
|
export function useCountUp({
|
|
end,
|
|
duration = 1800,
|
|
start = 0,
|
|
decimals = 0,
|
|
easing = easeOutCubic,
|
|
enabled = true,
|
|
}: UseCountUpOptions) {
|
|
const [value, setValue] = useState(start);
|
|
const startTimeRef = useRef<number | null>(null);
|
|
const frameRef = useRef<number>(0);
|
|
|
|
useEffect(() => {
|
|
if (!enabled) {
|
|
setValue(end);
|
|
return;
|
|
}
|
|
|
|
setValue(start);
|
|
startTimeRef.current = null;
|
|
|
|
const animate = (now: number) => {
|
|
if (startTimeRef.current === null) {
|
|
startTimeRef.current = now;
|
|
}
|
|
|
|
const progress = Math.min((now - startTimeRef.current) / duration, 1);
|
|
const eased = easing(progress);
|
|
const current = start + (end - start) * eased;
|
|
|
|
setValue(Number(current.toFixed(decimals)));
|
|
|
|
if (progress < 1) {
|
|
frameRef.current = requestAnimationFrame(animate);
|
|
} else {
|
|
setValue(Number(end.toFixed(decimals)));
|
|
}
|
|
};
|
|
|
|
frameRef.current = requestAnimationFrame(animate);
|
|
|
|
return () => {
|
|
cancelAnimationFrame(frameRef.current);
|
|
};
|
|
}, [end, duration, start, decimals, easing, enabled]);
|
|
|
|
return value;
|
|
}
|