2019-07-24 22:56:20 +08:00
|
|
|
import raf from 'raf';
|
|
|
|
import getScroll from './getScroll';
|
2019-07-30 11:02:16 +08:00
|
|
|
import { easeInOutCubic } from './easings';
|
2019-07-24 22:56:20 +08:00
|
|
|
|
|
|
|
interface ScrollToOptions {
|
2019-07-24 23:56:20 +08:00
|
|
|
/** Scroll container, default as window */
|
2019-07-24 22:56:20 +08:00
|
|
|
getContainer?: () => HTMLElement | Window;
|
|
|
|
/** Scroll end callback */
|
|
|
|
callback?: () => any;
|
|
|
|
/** Animation duration, default as 450 */
|
|
|
|
duration?: number;
|
|
|
|
}
|
|
|
|
|
2019-07-30 12:34:12 +08:00
|
|
|
export default function scrollTo(y: number, options: ScrollToOptions = {}) {
|
2019-07-30 11:02:16 +08:00
|
|
|
const { getContainer = () => window, callback, duration = 450 } = options;
|
2019-07-24 22:56:20 +08:00
|
|
|
|
|
|
|
const container = getContainer();
|
|
|
|
const scrollTop = getScroll(container, true);
|
|
|
|
const startTime = Date.now();
|
|
|
|
|
|
|
|
const frameFunc = () => {
|
|
|
|
const timestamp = Date.now();
|
|
|
|
const time = timestamp - startTime;
|
2019-07-30 11:02:16 +08:00
|
|
|
const nextScrollTop = easeInOutCubic(time > duration ? duration : time, scrollTop, y, duration);
|
2019-07-24 22:56:20 +08:00
|
|
|
if (container === window) {
|
2019-07-30 12:34:12 +08:00
|
|
|
window.scrollTo(window.pageXOffset, nextScrollTop);
|
2019-07-24 22:56:20 +08:00
|
|
|
} else {
|
|
|
|
(container as HTMLElement).scrollTop = nextScrollTop;
|
|
|
|
}
|
|
|
|
if (time < duration) {
|
|
|
|
raf(frameFunc);
|
2019-08-16 18:15:28 +08:00
|
|
|
} else if (typeof callback === 'function') {
|
|
|
|
callback();
|
2019-07-24 22:56:20 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
raf(frameFunc);
|
|
|
|
}
|