UNPKG

count-up-es-react

Version:
61 lines (52 loc) 1.89 kB
import { useFormattedValue } from '../hooks/useFormattedValue'; import { getEasing, defaultEasing } from '../utils/index'; import { useElapsedTime } from '../elapsed'; import { useEffect } from 'react'; export var DEFAULT_DURATION = 2; // 默认为2s export var DEFAULT_START = 0; // 默认从0开始 var getDuration = function getDuration(end, duration) { if (typeof end !== 'number') { return undefined; } return typeof duration === 'number' ? duration : DEFAULT_DURATION; }; var useCountUp = function useCountUp(props) { var _props$isCounting = props.isCounting, isCounting = _props$isCounting === void 0 ? true : _props$isCounting, _props$start = props.start, start = _props$start === void 0 ? DEFAULT_START : _props$start, end = props.end, duration = props.duration, _props$easing = props.easing, easing = _props$easing === void 0 ? defaultEasing : _props$easing, onComplete = props.onComplete, autoResetKey = props.autoResetKey; var durationValue = getDuration(end, duration); var _useElapsedTime = useElapsedTime({ isPlaying: isCounting, duration: durationValue, onComplete: onComplete }), elapsedTime = _useElapsedTime.elapsedTime, reset = _useElapsedTime.reset; useEffect(function () { reset(); }, [autoResetKey, reset]); var rawValue; if (durationValue === 0 && typeof end === 'number') { rawValue = end; } else if (typeof end === 'number' && typeof durationValue === 'number') { var easingFn = getEasing(easing); var time = elapsedTime < durationValue ? elapsedTime : durationValue; rawValue = easingFn(time, start, end - start, durationValue); } else { rawValue = start + elapsedTime; } var value = useFormattedValue(rawValue, props); return { value: value, reset: reset, rawValue: rawValue }; }; export { useCountUp };