@gravity-ui/graph
Version:
Modern graph editor component
87 lines (86 loc) • 2.8 kB
JavaScript
const rAF = typeof window !== "undefined" ? window.requestAnimationFrame : (fn) => global.setTimeout(fn, 16);
const cAF = typeof window !== "undefined" ? window.cancelAnimationFrame : global.clearTimeout;
const getNow = typeof window !== "undefined" ? window.performance.now.bind(window.performance) : global.Date.now.bind(global.Date);
export var ESchedulerPriority;
(function (ESchedulerPriority) {
ESchedulerPriority[ESchedulerPriority["HIGHEST"] = 0] = "HIGHEST";
ESchedulerPriority[ESchedulerPriority["HIGH"] = 1] = "HIGH";
ESchedulerPriority[ESchedulerPriority["MEDIUM"] = 2] = "MEDIUM";
ESchedulerPriority[ESchedulerPriority["LOW"] = 3] = "LOW";
ESchedulerPriority[ESchedulerPriority["LOWEST"] = 4] = "LOWEST";
})(ESchedulerPriority || (ESchedulerPriority = {}));
export class GlobalScheduler {
constructor() {
this.tick = this.tick.bind(this);
this.schedulers = [[], [], [], [], []];
}
getSchedulers() {
return this.schedulers;
}
addScheduler(scheduler, index = ESchedulerPriority.MEDIUM) {
this.schedulers[index].push(scheduler);
return () => this.removeScheduler(scheduler, index);
}
removeScheduler(scheduler, index = ESchedulerPriority.MEDIUM) {
const i = this.schedulers[index].indexOf(scheduler);
if (i !== -1) {
this.schedulers[index].splice(i, 1);
}
}
start() {
if (!this._cAFID) {
this._cAFID = rAF(this.tick);
}
}
stop() {
cAF(this._cAFID);
this._cAFID = undefined;
}
tick() {
this.performUpdate();
this._cAFID = rAF(this.tick);
}
performUpdate() {
const startTime = getNow();
let schedulers = [];
for (let i = 0; i < this.schedulers.length; i += 1) {
schedulers = this.schedulers[i];
for (let j = 0; j < schedulers.length; j += 1) {
schedulers[j].performUpdate(getNow() - startTime);
}
}
}
}
export const globalScheduler = new GlobalScheduler();
export const scheduler = globalScheduler;
export class Scheduler {
constructor() {
this.performUpdate = this.performUpdate.bind(this);
this.sheduled = false;
globalScheduler.addScheduler(this);
}
setRoot(root) {
this.root = root;
}
start() {
globalScheduler.addScheduler(this);
}
stop() {
globalScheduler.removeScheduler(this);
}
update() {
this.root?.traverseDown(this.iterator);
}
iterator(node) {
return node.data.iterate();
}
scheduleUpdate() {
this.sheduled = true;
}
performUpdate() {
if (this.sheduled) {
this.sheduled = false;
this.update();
}
}
}