2020-11-20 12:11:50 +08:00
|
|
|
import raf from 'rc-util/lib/raf';
|
2024-04-08 14:04:08 +08:00
|
|
|
|
2019-07-30 11:02:16 +08:00
|
|
|
import { easeInOutCubic } from './easings';
|
2022-06-22 14:57:09 +08:00
|
|
|
import getScroll, { isWindow } from './getScroll';
|
2019-07-24 22:56:20 +08:00
|
|
|
|
|
|
|
interface ScrollToOptions {
|
2019-07-24 23:56:20 +08:00
|
|
|
/** Scroll container, default as window */
|
2020-04-01 17:38:21 +08:00
|
|
|
getContainer?: () => HTMLElement | Window | Document;
|
2019-07-24 22:56:20 +08:00
|
|
|
/** Scroll end callback */
|
2023-05-29 01:26:23 +08:00
|
|
|
callback?: () => void;
|
2019-07-24 22:56:20 +08:00
|
|
|
/** 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);
|
2020-04-01 17:38:21 +08:00
|
|
|
if (isWindow(container)) {
|
|
|
|
(container as Window).scrollTo(window.pageXOffset, nextScrollTop);
|
2022-10-12 22:46:16 +08:00
|
|
|
} else if (container instanceof Document || container.constructor.name === 'HTMLDocument') {
|
|
|
|
(container as Document).documentElement.scrollTop = 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);
|
|
|
|
}
|