forked from silicakes/scrollio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrollTo.ts
45 lines (39 loc) · 1.31 KB
/
scrollTo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { EasingFunction } from "./abstraction";
//@ts-ignore
const root: any = typeof window !== "undefined" ? window : global;
const reqAnimationFramePolyfill = function(callback: () => void) {
root.setTimeout(callback, 1000 / 60);
};
const requestAnimFrame = () =>
root.requestAnimationFrame ||
root.webkitRequestAnimationFrame ||
root.mozRequestAnimationFrame ||
reqAnimationFramePolyfill;
const move = (scrollElement: Element, amount: number) => {
scrollElement.scrollTop = amount;
};
const position = (scrollElement: Element): number => scrollElement.scrollTop;
//@ts-ignore to avoid: https://github.com/Microsoft/vscode/issues/22436
export function scrollTo(scrollElement: Element, to: number, duration: number, easingFunction: EasingFunction) {
let start = position(scrollElement),
currentTime = 0,
increment = 20;
const reqAnimation = requestAnimFrame();
return new Promise<void>(resolve => {
if(start === to) {
resolve();
}
let animateScroll = function() {
currentTime += increment;
let val = easingFunction(currentTime / duration) * (to - start) + start;
// console.log(val);
move(scrollElement, val);
if (currentTime < duration) {
reqAnimation(animateScroll);
} else {
resolve();
}
};
animateScroll();
});
}