ant-design/components/_util/scrollTo.ts

39 lines
1.3 KiB
TypeScript
Raw Normal View History

import raf from 'rc-util/lib/raf';
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';
interface ScrollToOptions {
2019-07-24 23:56:20 +08:00
/** Scroll container, default as window */
getContainer?: () => HTMLElement | Window | Document;
/** Scroll end callback */
2023-05-29 01:26:23 +08:00
callback?: () => void;
/** 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;
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);
if (isWindow(container)) {
(container as Window).scrollTo(window.pageXOffset, nextScrollTop);
} else if (container instanceof Document || container.constructor.name === 'HTMLDocument') {
(container as Document).documentElement.scrollTop = nextScrollTop;
} 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();
}
};
raf(frameFunc);
}