-
-
Notifications
You must be signed in to change notification settings - Fork 151
/
Base.mjs
648 lines (564 loc) · 20.2 KB
/
Base.mjs
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
import {buffer, debounce, intercept, throttle} from '../util/Function.mjs';
import IdGenerator from './IdGenerator.mjs'
const configSymbol = Symbol.for('configSymbol'),
forceAssignConfigs = Symbol('forceAssignConfigs'),
isInstance = Symbol('isInstance');
/**
* The base class for (almost) all classes inside the Neo namespace
* Exceptions are e.g. core.IdGenerator, vdom.VNode
* @class Neo.core.Base
*/
class Base {
/**
* You can define methods which should get delayed.
* Types are buffer, debounce & throttle.
* @example
* delayable: {
* fireChangeEvent: {
* type : 'debounce',
* timer: 300
* }
* }
* @member {Object} delayable={}
* @protected
* @static
*/
static delayable = {}
/**
* Flag which will get set to true once manager.Instance got created
* @member {Boolean} instanceManagerAvailable=false
* @static
*/
static instanceManagerAvailable = false
/**
* Regex to grab the MethodName from an error
* which is a second generation function
* @member {RegExp} methodNameRegex
* @static
*/
static methodNameRegex = /\n.*\n\s+at\s+.*\.(\w+)\s+.*/
/**
* True automatically applies the core.Observable mixin
* @member {Boolean} observable=false
* @static
*/
static observable = false
/**
* Keep the overwritten methods
* @member {Object} overwrittenMethods={}
* @protected
* @static
*/
static overwrittenMethods = {}
/**
* Set this one to false in case you don't want to stick
* to the "anti-pattern" to apply classes to the global Neo or App namespace
* @member {Boolean} registerToGlobalNs=true
* @protected
* @static
*/
static registerToGlobalNs = true
/**
* Configs will get merged throughout the class hierarchy
* @returns {Object} config
* @tutorial 02_ClassSystem
*/
static config = {
/**
* The class name which will get mapped into the Neo or app namespace
* @member {String} className='Neo.core.Base'
* @protected
*/
className: 'Neo.core.Base',
/**
* The class shortcut-name to use for e.g. creating child components inside a JSON-format
* @member {String} ntype='base'
* @protected
*/
ntype: 'base',
/**
* While it is recommended to change the static delayable configs on class level,
* you can change it on instance level too. If not null, we will do a deep merge.
* @member {Object} delayable=null
*/
delayable: null,
/**
* The unique component id
* @member {String|null} id_=null
*/
id_: null,
/**
* Neo.create() will change this flag to true after the onConstructed() chain is done.
* @member {Boolean} isConstructed=false
* @protected
*/
isConstructed: false,
/**
* Add mixins as an array of classNames, imported modules or a mixed version
* @member {String[]|Neo.core.Base[]|null} mixins=null
*/
mixins: null,
/**
* You can create a new instance by passing an imported class (JS module default export)
* @member {Class} module=null
* @protected
*/
module: null
}
/**
* Internal cache for all timeout ids when using this.timeout()
* @member {Number[]} timeoutIds=[]
* @private
*/
#timeoutIds = []
/**
* Applies the observable mixin if needed, grants remote access if needed.
* @param {Object} config={}
*/
construct(config={}) {
let me = this;
Object.defineProperties(me, {
[configSymbol]: {
configurable: true,
enumerable : false,
value : {},
writable : true
},
[isInstance]: {
enumerable: false,
value : true
}
});
me.createId(config.id || me.id);
delete config.id;
if (me.constructor.config) {
delete me.constructor.config.id;
}
me.getStaticConfig('observable') && me.initObservable(config);
// assign class field values prior to configs
config = me.setFields(config);
me.initConfig(config);
Object.defineProperty(me, 'configsApplied', {
enumerable: false,
value : true
});
me.applyDelayable();
/*
* We do not want to force devs to check for the `isDestroyed` flag in every possible class extension.
* So, we are intercepting the top-most `destroy()` call to check for the flag there.
* Rationale: `destroy()` must only get called once.
*/
intercept(me, 'destroy', me.isDestroyedCheck, me);
me.remote && setTimeout(me.initRemote.bind(me), 1)
}
/**
* Triggered after the id config got changed.
* You can dynamically change instance ids if needed. They need to stay unique at any given point.
* Use case: e.g. component based lists, where you want to re-use item instances.
* @param {String|null} value
* @param {String|null} oldValue
* @protected
*/
afterSetId(value, oldValue) {
let me = this,
hasManager = Base.instanceManagerAvailable === true;
if (oldValue) {
if (hasManager) {
Neo.manager.Instance.unregister(oldValue)
} else {
delete Neo.idMap[oldValue]
}
}
if (hasManager) {
Neo.manager.Instance.register(me);
} else {
Neo.idMap = Neo.idMap || {};
Neo.idMap[me.id] = me
}
}
/**
* Adjusts all methods inside static delayable
*/
applyDelayable() {
let me = this,
ctorDelayable = me.constructor.delayable,
delayable = me.delayable ? Neo.merge({}, me.delayable, ctorDelayable) : ctorDelayable;
Object.entries(delayable).forEach(([key, value]) => {
if (value) {
let map = {
buffer() {me[key] = new buffer(me[key], me, value.timer)},
debounce() {me[key] = new debounce(me[key], me, value.timer)},
throttle() {me[key] = new throttle(me[key], me, value.timer)}
};
map[value.type]?.()
}
})
}
/**
* Applying overwrites and adding overwrittenMethods to the class constructors
* @param {Object} cfg
* @protected
*/
static applyOverwrites(cfg) {
let overwrites = Neo.ns(cfg.className, false, Neo.overwrites),
cls, item;
if (overwrites) {
// Apply all methods
for (item in overwrites) {
if (Neo.isFunction(overwrites[item])) {
// Already existing ones
cls = this.prototype;
if (cls[item]) {
// add to overwrittenMethods
cls.constructor.overwrittenMethods[item] = cls[item]
}
}
}
// Apply configs to prototype
Object.assign(cfg, overwrites)
}
}
/**
* Convenience method for beforeSet functions which test if a given value is inside a static array
* @param {String|Number} value
* @param {String|Number} oldValue
* @param {String} name config name
* @param {Array|String} [staticName=name + 's'] name of the static config array
* @returns {String|Number} value or oldValue
*/
beforeSetEnumValue(value, oldValue, name, staticName = name + 's') {
let values = Array.isArray(staticName) ? staticName : this.getStaticConfig(staticName);
if (!values.includes(value)) {
console.error(`Supported values for ${name} are:`, ...values, this);
return oldValue
}
return value
}
/**
* From within an overwrite, a method can call a parent method, by using callOverwritten.
*
* @example
* afterSetHeight(value, oldValue) {
* // do the standard
* this.callOverwritten(...arguments);
* // do you own stuff
* }
*
* We create an error to get the caller.name and then run that method on the constructor.
* This is based on the following error structure, e.g. afterSetHeight.
*
* Error
* at Base.callOverwritten (Base.mjs:176:21)
* at Base.afterSetHeight (Overrides.mjs:19:26)
*
* @param args
*/
callOverwritten(...args) {
let stack = new Error().stack,
regex = Base.methodNameRegex,
methodName = stack.match(regex)[1];
this.__proto__.constructor.overwrittenMethods[methodName].call(this, ...args)
}
/**
* Uses the IdGenerator to create an id if a static one is not explicitly set.
* Registers the instance to manager.Instance if this one is already created,
* otherwise stores it inside a tmp map.
* @param {String} id
*/
createId(id) {
this.id = id || IdGenerator.getId(this.getIdKey())
}
/**
* Unregisters this instance from Neo.manager.Instance
* and removes all object entries from this instance
*/
destroy() {
let me = this;
me.#timeoutIds.forEach(id => {
clearTimeout(id)
});
if (Base.instanceManagerAvailable === true) {
Neo.manager.Instance.unregister(me)
} else if (Neo.idMap) {
delete Neo.idMap[me.id]
}
Object.keys(me).forEach(key => {
if (Object.getOwnPropertyDescriptor(me, key).writable) {
// We must not delete the custom destroy() interceptor
if (key !== 'destroy' && key !== '_id') {
delete me[key]
}
}
});
// We do want to prevent delayed event calls after an observable instance got destroyed.
if (Neo.isFunction(me.fire)) {
me.fire = Neo.emptyFn
}
me.isDestroyed = true
}
/**
* Used inside createId() as the default value passed to the IdGenerator.
* Override this method as needed.
* @returns {String}
*/
getIdKey() {
return this.ntype
}
/**
* Returns the value of a static config key or the staticConfig object itself in case no value is set
* @param {String} key The key of a staticConfig defined inside static getStaticConfig
* @returns {*}
*/
getStaticConfig(key) {
return this.constructor[key]
}
/**
* Check if a given ntype exists inside the proto chain, including the top level class
* @param {String} ntype
* @returns {Boolean}
*/
hasNtype(ntype) {
return this.constructor.ntypeChain.includes(ntype)
}
/**
* Gets triggered after onConstructed() is done
* @see {@link Neo.core.Base#onConstructed onConstructed}
* @tutorial 02_ClassSystem
*/
init() {}
/**
* Applies all class configs to this instance
* @param {Object} config
* @param {Boolean} [preventOriginalConfig] True prevents the instance from getting an originalConfig property
* @protected
*/
initConfig(config, preventOriginalConfig) {
let me = this;
me.isConfiguring = true;
Object.assign(me[configSymbol], me.mergeConfig(config, preventOriginalConfig));
me.processConfigs()
me.isConfiguring = false;
}
/**
* Does get triggered with a delay to ensure that Neo.workerId & Neo.worker.Manager are defined
* Remote method access via promises
* @protected
*/
initRemote() {
let me = this,
{className, remote} = me,
{currentWorker} = Neo;
if (!me.singleton && !me.isMainThreadAddon) {
throw new Error('Remote method access is only functional for Singleton classes ' + className)
}
if (!Neo.config.unitTestMode && Neo.isObject(remote)) {
if (Neo.workerId !== 'main' && currentWorker.isSharedWorker && !currentWorker.isConnected) {
currentWorker.on('connected', () => {
Base.sendRemotes(className, remote)
}, me, {once: true})
} else {
Base.sendRemotes(className, remote)
}
}
}
/**
* Intercepts destroy() calls to ensure they will only get called once
* @returns {Boolean}
*/
isDestroyedCheck() {
return !this.isDestroyed
}
/**
* Override this method to change the order configs are applied to this instance.
* @param {Object} config
* @param {Boolean} [preventOriginalConfig] True prevents the instance from getting an originalConfig property
* @returns {Object} config
* @protected
*/
mergeConfig(config, preventOriginalConfig) {
let me = this,
ctor = me.constructor;
if (!ctor.config) {
throw new Error('Neo.applyClassConfig has not been run on ' + me.className)
}
if (!preventOriginalConfig) {
me.originalConfig = Neo.clone(config, true, true)
}
return {...ctor.config, ...config}
}
/**
*
*/
onAfterConstructed() {
let me = this;
me.isConstructed = true;
// We can only fire the event in case the Observable mixin is included.
me.getStaticConfig('observable') && me.fire('constructed', me)
}
/**
* Gets triggered after all constructors are done
* @tutorial 02_ClassSystem
*/
onConstructed() {}
/**
* Helper method to replace string based values containing "@config:" with the matching config value
* of this instance.
* @param {Object|Object[]} items
*/
parseItemConfigs(items) {
let me = this,
ns, nsArray, nsKey, symbolNs;
if (items) {
if (!Array.isArray(items)) {
items = [items]
}
items.forEach(item => {
item && Object.entries(item).forEach(([key, value]) => {
if (Array.isArray(value)) {
me.parseItemConfigs(value);
} else if (typeof value === 'string' && value.startsWith('@config:')) {
nsArray = value.substring(8).trim().split('.');
nsKey = nsArray.pop();
ns = Neo.ns(nsArray, false, me);
if (ns[nsKey] === undefined) {
console.error('The used @config does not exist:', nsKey, nsArray.join('.'))
} else {
symbolNs = Neo.ns(nsArray, false, me[configSymbol]);
// The config might not be processed yet, especially for configs
// not ending with an underscore, so we need to check the configSymbol first.
if (symbolNs && Object.hasOwn(symbolNs, nsKey)) {
item[key] = symbolNs[nsKey]
} else {
item[key] = ns[nsKey]
}
}
}
})
})
}
}
/**
* When using set(), configs without a trailing underscore can already be assigned,
* so the hasOwnProperty() check will return true
* @param {Boolean} [forceAssign=false]
* @protected
*/
processConfigs(forceAssign=false) {
let me = this,
keys = Object.keys(me[configSymbol]);
me[forceAssignConfigs] = forceAssign;
// We do not want to iterate over the keys, since 1 config can remove more than 1 key (beforeSetX, afterSetX)
if (keys.length > 0) {
// The hasOwnProperty check is intended for configs without a trailing underscore
// => they could already have been assigned inside an afterSet-method
if (forceAssign || !me.hasOwnProperty(keys[0])) {
me[keys[0]] = me[configSymbol][keys[0]]
}
// there is a delete-call inside the config getter as well (Neo.mjs => autoGenerateGetSet())
// we need to keep this one for configs, which do not use getters (no trailing underscore)
delete me[configSymbol][keys[0]];
me.processConfigs(forceAssign)
}
}
/**
* @param {String} className
* @param {Object} remote
* @protected
*/
static sendRemotes(className, remote) {
let origin;
Object.entries(remote).forEach(([worker, methods]) => {
if (Neo.workerId !== worker) {
origin = Neo.workerId === 'main' ? Neo.worker.Manager : Neo.currentWorker;
origin.sendMessage(worker, {
action: 'registerRemote',
className,
methods
})
}
})
}
/**
* Change multiple configs at once, ensuring that all afterSet methods get all new assigned values
* @param {Object} values={}
*/
set(values={}) {
let me = this;
values = me.setFields(values);
// If the initial config processing is still running,
// finish this one first before dropping new values into the configSymbol.
// see: https://github.com/neomjs/neo/issues/2201
if (me[forceAssignConfigs] !== true && Object.keys(me[configSymbol]).length > 0) {
me.processConfigs()
}
Object.assign(me[configSymbol], values);
me.processConfigs(true)
}
/**
* We want to assign class fields first and remove them from the config object,
* so that afterSet(), beforeGet() and beforeSet() methods can get the new values right away
* @param {Object} config
* @returns {Object}
* @protected
*/
setFields(config) {
let me = this,
configNames = me.constructor.config;
Object.entries(config).forEach(([key, value]) => {
if (!configNames.hasOwnProperty(key) && !Neo.hasPropertySetter(me, key)) {
me[key] = value;
delete config[key]
}
})
return config
}
/**
* Sets the value of a static config by a given key
* @param {String} key The key of a staticConfig defined inside static getStaticConfig
* @param {*} value
* @returns {Boolean} true in case the config exists and got changed
*/
setStaticConfig(key, value) {
let staticConfig = this.constructor.staticConfig;
if (staticConfig.hasOwnProperty(key)) {
staticConfig[key] = value;
return true
}
return false
}
/**
* Stores timeoutIds internally, so that destroy() can clear them if needed
* @param {Number} time in milliseconds
* @returns {Promise<any>}
*/
timeout(time) {
return new Promise(resolve => {
let timeoutIds = this.#timeoutIds,
timeoutId = setTimeout(() => {timeoutIds.splice(timeoutIds.indexOf(timeoutId, 1)); resolve()}, time);
timeoutIds.push(timeoutId)
})
}
/**
* <p>Enhancing the toString() method, e.g.</p>
* `Neo.create('Neo.button.Base').toString() => "[object Neo.button.Base (neo-button-1)]"`
* @returns {String}
*/
get [Symbol.toStringTag]() {
return `${this.className} (id: ${this.id})`
}
/**
* <p>Enhancing the instanceof method. Without this change:</p>
* `Neo.collection.Base.prototype instanceof Neo.core.Base => true`
* <p>With this change:</p>
* `Neo.collection.Base.prototype instanceof Neo.core.Base => false`<br>
* `Neo.create(Neo.collection.Base) instanceof Neo.core.Base => true`
* @returns {Boolean}
*/
static [Symbol.hasInstance](instance) {
if (!instance) {
return false
}
return instance[isInstance] === true ? super[Symbol.hasInstance](instance) : false
}
}
export default Neo.setupClass(Base);