2020-02-01 11:15:58 +01:00
|
|
|
import utils from '../services/utils.js';
|
2020-02-12 20:07:04 +01:00
|
|
|
import Mutex from "../services/mutex.js";
|
2020-02-01 11:15:58 +01:00
|
|
|
|
2020-01-15 21:36:01 +01:00
|
|
|
export default class Component {
|
|
|
|
/** @param {AppContext} appContext */
|
|
|
|
constructor(appContext) {
|
2020-02-02 18:46:50 +01:00
|
|
|
this.componentId = `comp-${this.constructor.name}-` + utils.randomString(6);
|
2020-02-07 21:43:02 +01:00
|
|
|
/** @type AppContext */
|
2020-01-15 21:36:01 +01:00
|
|
|
this.appContext = appContext;
|
2020-02-07 21:43:02 +01:00
|
|
|
/** @type TabManager */
|
|
|
|
this.tabManager = appContext.tabManager;
|
2020-01-15 21:36:01 +01:00
|
|
|
/** @type Component[] */
|
|
|
|
this.children = [];
|
2020-01-18 18:01:16 +01:00
|
|
|
this.initialized = Promise.resolve();
|
2020-02-12 20:07:04 +01:00
|
|
|
this.mutex = new Mutex();
|
2020-01-15 21:36:01 +01:00
|
|
|
}
|
|
|
|
|
2020-02-12 20:31:31 +01:00
|
|
|
async eventReceived(name, data) {
|
2020-01-18 18:01:16 +01:00
|
|
|
await this.initialized;
|
|
|
|
|
2020-01-15 21:36:01 +01:00
|
|
|
const fun = this[name + 'Listener'];
|
|
|
|
|
2020-02-02 11:44:08 +01:00
|
|
|
const start = Date.now();
|
|
|
|
|
2020-01-15 21:36:01 +01:00
|
|
|
if (typeof fun === 'function') {
|
2020-02-12 20:07:04 +01:00
|
|
|
let release;
|
|
|
|
|
|
|
|
try {
|
|
|
|
release = await this.mutex.acquire();
|
|
|
|
|
2020-02-12 20:31:31 +01:00
|
|
|
await fun.call(this, data);
|
2020-02-12 20:07:04 +01:00
|
|
|
}
|
|
|
|
finally {
|
|
|
|
if (release) {
|
|
|
|
release();
|
|
|
|
}
|
|
|
|
}
|
2020-01-15 21:36:01 +01:00
|
|
|
}
|
|
|
|
|
2020-02-02 11:44:08 +01:00
|
|
|
const end = Date.now();
|
|
|
|
|
2020-02-08 10:40:58 +01:00
|
|
|
if (end - start > 10 && glob.PROFILING_LOG) {
|
2020-02-02 11:44:08 +01:00
|
|
|
console.log(`Event ${name} in component ${this.componentId} took ${end-start}ms`);
|
|
|
|
}
|
|
|
|
|
2020-02-12 20:31:31 +01:00
|
|
|
await this.triggerChildren(name, data);
|
2020-01-15 21:36:01 +01:00
|
|
|
}
|
|
|
|
|
2020-02-12 20:31:31 +01:00
|
|
|
async trigger(name, data) {
|
|
|
|
await this.appContext.trigger(name, data);
|
2020-01-15 21:36:01 +01:00
|
|
|
}
|
2020-01-24 20:15:53 +01:00
|
|
|
|
2020-02-12 20:31:31 +01:00
|
|
|
async triggerChildren(name, data) {
|
2020-02-12 20:07:04 +01:00
|
|
|
const promises = [];
|
|
|
|
|
2020-01-24 20:15:53 +01:00
|
|
|
for (const child of this.children) {
|
2020-02-12 20:31:31 +01:00
|
|
|
promises.push(child.eventReceived(name, data));
|
2020-02-12 20:07:04 +01:00
|
|
|
}
|
2020-01-24 20:15:53 +01:00
|
|
|
|
2020-02-12 20:31:31 +01:00
|
|
|
await Promise.all(promises);
|
2020-01-24 20:15:53 +01:00
|
|
|
}
|
2020-01-15 21:36:01 +01:00
|
|
|
}
|