smooth-scroll-to
Version:
73 lines (71 loc) • 1.81 kB
JavaScript
// @ts-check
import { getScrollNode } from "get-scroll-info";
import callfunc from "call-func";
import { easeInOutCubic, aniTimer } from "easing-lib";
import { NEW_OBJ } from "reshow-constant";
var isRunning = NEW_OBJ();
/**
* !!Important!! any logic change need take care isRunning
*
* @param {number} to
* @param {number} [duration]
* @param {HTMLElement} [el]
* @param {function} [callback]
* @param {string} [scrollKey]
* @returns {function} cancel handler
*/
var smoothScrollTo = function smoothScrollTo(to, duration, el, callback, scrollKey) {
if (duration === void 0) {
duration = 500;
}
if (scrollKey === void 0) {
scrollKey = "scrollTop";
}
var scrollNode = getScrollNode(el);
var cb = function cb() {
if (isRunning[scrollKey]) {
callfunc(callback, [{
scrollNode,
from,
to,
go
}]);
isRunning[scrollKey] = false;
}
};
var cancel = function cancel() {
clearTimeout(isRunning[scrollKey]);
isRunning[scrollKey] = false;
};
if (isRunning[scrollKey]) {
clearTimeout(isRunning[scrollKey]);
isRunning[scrollKey] = setTimeout(function () {
scrollNode[scrollKey] = to;
cb();
});
return cancel;
}
var from = scrollNode[scrollKey];
var go = to - from;
if (!go) {
return function () {};
}
aniTimer({
isContinue: function isContinue( /**@type number*/elapsedTime) {
if (isRunning[scrollKey]) {
var progress = easeInOutCubic(elapsedTime, from, go, duration);
scrollNode[scrollKey] = progress;
return true;
}
},
cancel: function cancel() {
return cb();
},
done: function done() {
return cb();
}
}, duration);
isRunning[scrollKey] = true;
return cancel;
};
export default smoothScrollTo;