Last active
January 27, 2019 17:28
-
-
Save dagda1/79dd983ae61e1b8d6bb19ad7cb35ce9b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { EasingName, easing } from './easingMap'; | |
import { useLayoutEffect, useState, useRef } from 'react'; | |
export interface AnimationIncreaseProps { | |
easingName?: EasingName; | |
duration?: number; | |
diff: number; | |
} | |
export const useIncreaseAnimation = ({ | |
easingName = EasingName.linear, | |
diff: end, | |
duration = 500 | |
}: AnimationIncreaseProps) => { | |
const [increase, setIncrease] = useState(0); | |
const start = useRef<number>(null); | |
useLayoutEffect(() => { | |
let raf: number; | |
const frame = (timestamp: number) => { | |
if (!start.current) { | |
(start as any).current = timestamp; | |
} | |
if (!start.current) { | |
throw new Error('no start'); | |
} | |
const time = timestamp - start.current; | |
const percentRange = Math.min(time / duration, 1); | |
const percent = easing[easingName as string](percentRange); | |
setIncrease(increase + end * percent); | |
if (time < duration) { | |
raf = requestAnimationFrame(frame); | |
} | |
}; | |
raf = requestAnimationFrame(frame); | |
return () => { | |
cancelAnimationFrame(raf); | |
}; | |
}, [end]); | |
return increase; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment