@revolist/revogrid
Version:
Virtual reactive data grid spreadsheet component - RevoGrid.
81 lines (80 loc) • 3 kB
JavaScript
/*!
* Built by Revolist OU ❤️
*/
/**
* Apply changes only if mousewheel event happened some time ago (scrollThrottling)
*/
export class LocalScrollTimer {
constructor(scrollThrottling = 10) {
this.scrollThrottling = scrollThrottling;
/**
* Last mw event time for trigger scroll function below
* If mousewheel function was ignored we still need to trigger render
*/
this.mouseWheelScrollTimestamp = {
rgCol: 0,
rgRow: 0,
};
this.lastKnownScrollCoordinate = {
rgCol: 0,
rgRow: 0,
};
/**
* Check if scroll is ready to accept new value
* this is an edge case for scroll events
* when we need to apply scroll after throttling
*/
this.lastScrollUpdateCallbacks = {};
}
setCoordinate(e) {
this.lastKnownScrollCoordinate[e.dimension] = e.coordinate;
}
/**
* Remember last mw event time
*/
latestScrollUpdate(dimension) {
this.mouseWheelScrollTimestamp[dimension] = new Date().getTime();
}
isReady(type, coordinate) {
// if there is a callback, clear it
if (this.lastScrollUpdateCallbacks[type]) {
this.clearLastScrollUpdate(type);
}
// apply after throttling
return this.verifyChange(type, coordinate);
}
verifyChange(type, coordinate) {
const now = new Date().getTime();
const change = now - this.mouseWheelScrollTimestamp[type];
return change > this.scrollThrottling &&
coordinate !== this.lastKnownScrollCoordinate[type];
}
clearLastScrollUpdate(type) {
var _a, _b;
clearTimeout((_b = (_a = this.lastScrollUpdateCallbacks[type]) === null || _a === void 0 ? void 0 : _a.timeout) !== null && _b !== void 0 ? _b : 0);
delete this.lastScrollUpdateCallbacks[type];
}
throttleLastScrollUpdate(type, coordinate, lastScrollUpdate) {
// if scrollThrottling is set
// we need to throttle the last scroll event
if (this.scrollThrottling) {
this.clearLastScrollUpdate(type);
// save lastScrollUpdate callback
const callback = this.lastScrollUpdateCallbacks[type] = {
callback: lastScrollUpdate,
timestamp: new Date().getTime(),
coordinate,
timeout: 0,
};
callback.timeout = setTimeout(() => {
// clear timeout
this.clearLastScrollUpdate(type);
// if scrollThrottling is set, and the last scroll event happened before the timeout started
// we need to throttle the last scroll event
if (this.mouseWheelScrollTimestamp[type] < callback.timestamp && this.verifyChange(type, callback.coordinate)) {
callback.callback();
}
}, this.scrollThrottling + 50);
}
}
}