@tldraw/utils
Version:
A tiny little drawing app (private utilities).
106 lines (105 loc) • 2.78 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var throttle_exports = {};
__export(throttle_exports, {
fpsThrottle: () => fpsThrottle,
throttleToNextFrame: () => throttleToNextFrame
});
module.exports = __toCommonJS(throttle_exports);
const isTest = () => typeof process !== "undefined" && process.env.NODE_ENV === "test" && // @ts-expect-error
!globalThis.__FORCE_RAF_IN_TESTS__;
const fpsQueue = [];
const targetFps = 60;
const targetTimePerFrame = Math.ceil(1e3 / targetFps);
let frame;
let time = 0;
let last = 0;
const flush = () => {
const queue = fpsQueue.splice(0, fpsQueue.length);
for (const fn of queue) {
fn();
}
};
function tick() {
if (frame) {
return;
}
const now = Date.now();
const elapsed = now - last;
if (time + elapsed < targetTimePerFrame) {
frame = requestAnimationFrame(() => {
frame = void 0;
tick();
});
return;
}
frame = requestAnimationFrame(() => {
frame = void 0;
last = now;
time = Math.min(time + elapsed - targetTimePerFrame, targetTimePerFrame * 10);
flush();
});
}
let started = false;
function fpsThrottle(fn) {
if (isTest()) {
fn.cancel = () => frame && cancelAnimationFrame(frame);
return fn;
}
const throttledFn = () => {
if (fpsQueue.includes(fn)) {
return;
}
fpsQueue.push(fn);
if (!started) {
started = true;
last = Date.now() - targetTimePerFrame - 1;
}
tick();
};
throttledFn.cancel = () => {
const index = fpsQueue.indexOf(fn);
if (index > -1) {
fpsQueue.splice(index, 1);
}
};
return throttledFn;
}
function throttleToNextFrame(fn) {
if (isTest()) {
fn();
return () => {
};
}
if (!fpsQueue.includes(fn)) {
fpsQueue.push(fn);
if (!started) {
started = true;
last = Date.now() - targetTimePerFrame - 1;
}
tick();
}
return () => {
const index = fpsQueue.indexOf(fn);
if (index > -1) {
fpsQueue.splice(index, 1);
}
};
}
//# sourceMappingURL=throttle.js.map