UNPKG

@vnmfify/core

Version:

```shell npm i @vnmfify/core -S ```

45 lines (38 loc) 1.27 kB
import _isNaN from "lodash/isNaN"; import { useEffect, useState } from "react"; import { cancelRaf, raf } from "../utils/raf"; import { useToRef } from "../utils/state"; function format(rate) { return Math.min(Math.max(rate, 0), 100); } export function useAnimatePercent(percentProp, speed) { var [percent, setPercent] = useState(percentProp); var currentRateRef = useToRef(percent); useEffect(() => { var rafId; var startTime = Date.now(); var startRate = currentRateRef.current; var endRate = format(percentProp); var duration = Math.abs((startRate - endRate) * 1000 / speed); var animate = () => { var now = Date.now(); var progress = (now - startTime) / duration; progress = Math.min(_isNaN(progress) ? 1 : progress, 1); var rate = progress * (endRate - startRate) + startRate; setPercent(rate); if (endRate > startRate ? rate < endRate : rate > endRate) { rafId = raf(animate); } }; if (speed) { if (rafId) { cancelRaf(rafId); } rafId = raf(animate); } else { setPercent(endRate); } }, [currentRateRef, speed, percentProp]); return percent; } //# sourceMappingURL=circle.hooks.js.map