-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappPlugins.js
More file actions
335 lines (280 loc) · 9.73 KB
/
appPlugins.js
File metadata and controls
335 lines (280 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
class IPlugin {
constructor(aliasName, data) {
this.aliasName = aliasName || '';
this.config = data;
this.unsubscribersToEB = [];
this.eventIdStrict = false;
this.eventDefinitions = [];
this.eventCallsMap = new Map();
this.storageName = undefined;
}
_bindConfig() {
// set configuration options from configuration data
const prefixConfigOptionS = 'DEFAULT_KEY_CFG_';
const prefixConfigOption = new RegExp(`^${prefixConfigOptionS}`);
const prefLen = prefixConfigOptionS.length;
browsePrototypesDeep(this, (instance, definitions) =>
definitions.filter(name => prefixConfigOption.test(name)).forEach(name => {
const cfgKey = name.substring(prefLen);
const defVal = instance[name];
const cfgVal = instance.config[cfgKey];
instance[`cfg${cfgKey}`] = cfgVal || defVal;
})
);
}
init() {
// attach event handlers
const prefixEventHandler = /^onET/;
var _handleFunctionToSubscription = (instance, name) => {
browseMemberDeep(instance, name, (desc) => {
if (typeof desc.value !== 'function') return;
var nameBase = name.replace(prefixEventHandler, '');
if (nameBase.startsWith('_')) {
nameBase = nameBase.slice(1);
this._subscribeHandler(nameBase, this.aliasName, desc.value.bind(this));
} else {
this._prepareFilteredHandler(nameBase, desc.value.bind(this));
}
});
};
// var proto = Object.getPrototypeOf(this);
// Object.getOwnPropertyNames(proto).filter(name => prefixEventHandler.test(name)).forEach(name => _handleFunctionToSubscription(proto, name));
browsePrototypesDeep(Object.getPrototypeOf(this), (type, definitions) =>
definitions.filter(name => prefixEventHandler.test(name)).forEach(name => _handleFunctionToSubscription(type, name)));
this.eventDefinitions.forEach(([name, cls, fn]) => {
this.createEvent(name, fn, cls);
});
}
deInit() {
// const defs = this.eventDefinitions;
// if (Array.isArray(defs)) {
// for (const [eventName] of defs) {
// removeEventDefinition(eventName);
// }
// }
for (const one of this.unsubscribersToEB)
one();
this.unsubscribersToEB = [];
const siblingDeInitParents = getSubmodulesInModule(this);
const siblingDeInit = siblingDeInitParents.map(x => x.deInit.bind(x)).filter(x => x);
log(`Plugin deInit ${this.constructor.name} found ${siblingDeInit.length} (${siblingDeInitParents.map(x => `${x.constructor.name}:${x.aliasName}` || x.constructor.name).join(', ')}) ... calling deInit also for them.`);
siblingDeInit.forEach(x => x());
log(`Plugin deInit ${this.constructor.name} siblings finished.`);
}
createEvent(name, handler, dataClass = IEvent) {
this._prepareFilteredHandler(name, handler);
addEventDefinition(name, new EventDefinition(dataClass, name));
}
_prepareFilteredHandler(name, handler) {
if (handler != null) {
const alias = this.aliasName;
const strictSwitch = this.eventIdStrict;
var handlerFilterId = (d) => {
if (isEventHandlerOpened(alias, strictSwitch, d.id))
{
log(`[Plugins] Event "${name}" with id "${d.id}" forwarded to plugin ${this.constructor.name} with id: "${alias}".`);
handler(d);
}
else
log(`W [Plugins] Event "${name}" with id "${d.id}" was not forwarded to plugin ${this.constructor.name} with id: "${alias}".`);
};
this._subscribeHandler(name, alias, handlerFilterId);
handlerFilterId.__pluginPath = `${this.constructor.name}:${alias}:${handler.name};${handlerFilterId.name}`;
}
}
_subscribeHandler(name, alias, handler) {
var unsubscribe = EventBus.sub(name, handler);
handler.__pluginPath = `${this.constructor.name}:${alias}:${handler.name}`;
log(`[Plugins] Subscription for event "${name}" in plugin "${this.constructor.name}" with id: "${alias}" created.`);
this.unsubscribersToEB.push(unsubscribe);
}
static wrapAsyncHandler(fn) {
var reply = function(data) {
const reply = fn(data);
data.result = reply;
if (reply && typeof reply.then === "function") {
reply.then(res => {
data.result = res;
data.doneHandler?.(data);
});
}
};
reply.__name = fn.name;
return reply;
}
catalogizeEventCall(fn, eventName, eventId = '') {
const key = eventName;
if (!this.eventCallsMap.has(key))
this.eventCallsMap.set(key, new Set());
const val = `${fn.__name || fn.name || fn}:${eventId}`;
this.eventCallsMap.get(key).add(val);
}
}
function getSubmodulesInModule(pluginInstance) {
return Object.values(pluginInstance).filter((x) => typeof x?.['deInit'] === "function");
}
function isEventHandlerOpened(alias, strictSwitch, eventId) {
return eventId == alias || (!strictSwitch && (!eventId || alias == ''));
}
class Resource extends IPlugin {
constructor(aliasName, data, source = STO_DATA, fileList = '') {
super(aliasName, data);
this.fileList = fileList.split(';');
this.source = source;
this._fileLength = 0;
this.licenseFile = this.fileList.filter(x => /licen[cs]e/i.test(x));
this.readmeFile = this.fileList.filter(x => /readme/i.test(x));
Promise.all(
this.fileList.map(async f => {
const content = await _Storage.search(source, f);
return new TextEncoder().encode(content).length;
})
).then(lengths => this._fileLength = lengths.reduce((sum, len) => sum + len, 0));
}
init(resultI) {
const promises = this.fileList
.filter(one => !$(one))
.map(one =>
storageSearch(this.source, one).then(x => {
if (one.endsWith('.js')) appendJavaScript(one, x, document.head);
if (one.endsWith('.css')) appendCSS(one, x);
})
);
return Promise.all(promises);
}
deInit() {
this.fileList.forEach(one => $(one)?.remove());
}
}
function browsePrototypesDeep(instance, handler) {
var proto = instance;
var lastFound = false;
while (!lastFound && proto && proto !== Object.prototype) {
handler(proto, Object.getOwnPropertyNames(proto));
proto = Object.getPrototypeOf(proto);
}
};
function browseMemberDeep(instance, name, handler) {
var proto = instance;
var lastFound = false;
while (!lastFound && proto && proto !== Object.prototype) {
lastFound = browseMember(proto, name, handler);
proto = Object.getPrototypeOf(proto);
}
};
function browseMember(instance, name, handler) {
const desc = Object.getOwnPropertyDescriptor(instance, name);
if (desc)
handler(desc);
return !!desc;
};
const Plugins = {
plugins: new Map(),
pluginsClasses: new Map(),
catalogize(plugin) {
if (typeof plugin !== 'function') {
log('E Plugins: object is not a class/constructor: ', plugin);
return;
}
const name = plugin.name;
if (!name) {
log('E Plugins: class is anonymous!');
return;
}
if (!inheritsFrom(plugin, IPlugin)) {
log(`E Plugins: ${name} class not inherits from IPlugin!`);
return;
}
this.pluginsClasses.set(name, plugin);
log(`Plugins: registered '${name}'`);
return name;
},
activate(pluginName, aliasName, data) {
var plugin = this.pluginsClasses.get(pluginName);
var key = this.getKey(pluginName, aliasName);
if (this.plugins.get(key)) {
log(`W Plugin ${key} already instantiated.`);
return;
}
var p = null;
try {
p = new plugin(aliasName, data);
p._bindConfig();
} catch (error) {
p = null;
plugin = pluginName;
log(`E Plugin ${plugin} error!`, error);
}
if (!p) {
log(`E Plugin ${plugin} establishment failed!`);
return;
}
p.init();
this.plugins.set(key, p);
log(`Plugins: activated '${key}'`);
return [key, p];
},
getKey(pluginName, aliasName) {
return `${pluginName}:${aliasName}`;
},
deactivate(pluginName, aliasName = '') {
var key = this.getKey(pluginName, aliasName);
var plugin = this.plugins.get(key);
if (!plugin)
return;
plugin.deInit();
this.plugins.delete(key);
return [key, plugin];
}
};
function inheritsFrom(cls, base) {
while (cls && cls !== Function.prototype) {
if (cls === base) return true;
cls = Object.getPrototypeOf(cls);
}
return false;
}
function getAllParents(cls) {
const chain = [];
while (cls && cls !== Object) {
chain.push(cls.name || undefined);
cls = Object.getPrototypeOf(cls);
}
chain.push("Object");
return chain;
}
class SystemEventHandler extends IPlugin {
constructor(aliasName, data, target, eventName, handler) {
super(aliasName, data);
this.target = target;
this.eventName = eventName;
this.handler = handler;
this.aliasName = this.aliasName || `${this.getTargetName(target)}.${eventName}`;
}
init() {
this.target.addEventListener(this.eventName, this.handler);
}
deInit() {
this.target.removeEventListener(this.eventName, this.handler);
}
getTargetName(target) {
if (target === window) return "window";
if (target instanceof Document) return "Document";
if (target instanceof HTMLElement)
return this.target.id || this.target.tagName;
if (target instanceof EventTarget) return "EventTarget";
return Object.prototype.toString.call(target);
}
static getTargetFromName(target) {
const targetType = target.toLowerCase();
if (targetType == 'window') return window;
if (targetType == 'document') return document;
if (targetType == 'body') return document.body;
if (target.startsWith('#')) return $(target.substring(1));
log(`E Target ${target} could not be mapped to any element! ... returns undefined`);
return undefined;
}
}
Plugins.catalogize(IPlugin);
Plugins.catalogize(Resource);
Plugins.catalogize(SystemEventHandler);