-
-
Notifications
You must be signed in to change notification settings - Fork 161
/
Neo.mjs
819 lines (689 loc) · 24 KB
/
Neo.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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
import DefaultConfig from './DefaultConfig.mjs';
const
camelRegex = /-./g,
configSymbol = Symbol.for('configSymbol'),
getSetCache = Symbol('getSetCache'),
typeDetector = {
function: (item) => {
if (item.prototype?.constructor.isClass) {
return 'NeoClass'
}
},
object: (item) => {
if (item.constructor.isClass && item instanceof Neo.core.Base) {
return 'NeoInstance'
}
}
};
/**
* The base module to enhance classes, create instances and the Neo namespace
* @module Neo
* @singleton
* @borrows Neo.core.Util.bindMethods as bindMethods
* @borrows Neo.core.Util.capitalize as capitalize
* @borrows Neo.core.Util.createStyleObject as createStyleObject
* @borrows Neo.core.Util.createStyles as createStyles
* @borrows Neo.core.Util.decamel as decamel
* @borrows Neo.core.Util.isArray as isArray
* @borrows Neo.core.Util.isBoolean as isBoolean
* @borrows Neo.core.Util.isDefined as isDefined
* @borrows Neo.core.Compare.isEqual as isEqual
* @borrows Neo.core.Util.isNumber as isNumber
* @borrows Neo.core.Util.isObject as isObject
* @borrows Neo.core.Util.isString as isString
* @borrows Neo.core.Util.toArray as toArray
* @tutorial 01_Concept
*/
let Neo = globalThis.Neo || {};
Neo = globalThis.Neo = Object.assign({
/**
* A map containing ntypes as key and Neo classes or singletons as values
* @memberOf! module:Neo
* @protected
* @type Object
*/
ntypeMap: {},
/**
* Needed for Neo.create. False for the main thread, true for the App, Data & Vdom worker
* @memberOf! module:Neo
* @protected
* @type Boolean
*/
insideWorker: typeof DedicatedWorkerGlobalScope !== 'undefined' || typeof WorkerGlobalScope !== 'undefined',
/**
* Maps methods from one namespace to another one
* @example
* // aliases
* Neo.applyFromNs(Neo, Util, {
* createStyleObject: 'createStyleObject',
* createStyles : 'createStyles',
* capitalize : 'capitalize'
* }, true);
*
* // e.g. Neo.core.Util.isObject => Neo.isObject
* @memberOf module:Neo
* @param {Neo|Neo.core.Base} target The target class or singleton Instance or Neo
* @param {Neo.core.Base} namespace The class containing the methods
* @param {Object} config
* @param {Boolean} [bind] set this to true in case you want to bind methods to the "from" namespace
* @returns {Object} target
*/
applyFromNs(target, namespace, config, bind) {
let fnName;
if (target && Neo.typeOf(config) === 'Object') {
Object.entries(config).forEach(([key, value]) => {
fnName = namespace[value];
target[key] = bind ? fnName.bind(namespace) : fnName
})
}
return target
},
/**
* Maps a class to the global Neo or App namespace.
* Can get called for classes and singleton instances
* @memberOf module:Neo
* @param {Neo.core.Base} cls
*/
applyToGlobalNs(cls) {
let proto = typeof cls === 'function' ? cls.prototype : cls,
className = proto.isClass ? proto.config.className : proto.className,
nsArray = className.split('.'),
key = nsArray.pop(),
ns = Neo.ns(nsArray, true);
ns[key] = cls
},
/**
* Copies all keys of defaults into target, in case they don't already exist
* @memberOf module:Neo
* @param {Object} target The target object
* @param {Object} defaults The object containing the keys you want to copy
* @returns {Object} target
*/
assignDefaults(target, defaults) {
if (target && Neo.typeOf(defaults) === 'Object') {
Object.entries(defaults).forEach(([key, value]) => {
if (!Object.hasOwn(target, key)) {
target[key] = value
}
})
}
return target
},
/**
* Converts kebab-case strings into camel-case
* @memberOf module:Neo
* @param {String} value The target object
* @returns {String}
*/
camel(value) {
return value.replace(camelRegex, match => match[1].toUpperCase())
},
/**
* Makes the first character of a string uppercase
* @memberOf module:Neo
* @param {String} value
* @returns {Boolean|String} Returns false for non string inputs
*/
capitalize(value) {
return value[0].toUpperCase() + value.slice(1)
},
/**
* @memberOf module:Neo
* @param {Object|Array|*} obj
* @param {Boolean} deep=false Set this to true in case you want to clone nested objects as well
* @param {Boolean} ignoreNeoInstances=false returns existing instances if set to true
* @returns {Object|Array|*} the cloned input
*/
clone(obj, deep=false, ignoreNeoInstances=false) {
let out;
return {
Array : () => !deep ? [...obj] : [...obj.map(val => Neo.clone(val, deep, ignoreNeoInstances))],
Date : () => new Date(obj.valueOf()),
Map : () => new Map(obj), // shallow copy
NeoInstance: () => ignoreNeoInstances ? obj : this.cloneNeoInstance(obj),
Set : () => new Set(obj),
Object: () => {
out = {};
Object.entries(obj).forEach(([key, value]) => {
out[key] = !deep ? value : Neo.clone(value, deep, ignoreNeoInstances)
});
return out
}
}[Neo.typeOf(obj)]?.() || obj
},
/**
* Creates a new instance using the originalConfig without the id
* @memberOf module:Neo
* @param {Neo.core.Base} instance
* @returns {Neo.core.Base} the cloned instance
*/
cloneNeoInstance(instance) {
let config = {...instance.originalConfig};
delete config._id;
delete config.id;
return Neo.create(instance.className, config)
},
/**
* Use Neo.create() instead of "new" to create instances of all Neo classes
* @example
* import Button from '../button/Base.mjs';
*
* Neo.create(Button, {
* iconCls: 'fa fa-home',
* text : 'Home'
* });
* @example
* import Button from '../button/Base.mjs';
*
* Neo.create({
* module : Button,
* iconCls: 'fa fa-home',
* text : 'Home'
* });
* @example
* Neo.create('Neo.button.Base' {
* iconCls: 'fa fa-home',
* text : 'Home'
* });
* @example
* Neo.create({
* className: 'Neo.button.Base',
* iconCls : 'fa fa-home',
* text : 'Home'
* });
* @memberOf module:Neo
* @param {String|Object|Neo.core.Base} className
* @param {Object} [config]
* @returns {Neo.core.Base|null} The new class instance
* @tutorial 02_ClassSystem
*/
create(className, config) {
let type = Neo.typeOf(className),
cls, instance;
if (type === 'NeoClass') {
cls = className
} else {
if (type === 'Object') {
config = className;
if (!config.className && !config.module) {
// using console.error instead of throw to show the config object
console.error('Class created with object configuration missing className or module property', config);
return null
}
className = config.className || config.module.prototype.className;
}
if (!exists(className)) {
throw new Error('Class ' + className + ' does not exist')
}
cls = Neo.ns(className)
}
instance = new cls();
instance.construct(config);
instance.onConstructed();
instance.onAfterConstructed();
instance.init();
return instance
},
/**
*
*/
emptyFn() {},
/**
* Checks if there is a set method for a given property key inside the prototype chain
* @memberOf module:Neo
* @param {Neo.core.Base} proto The top level prototype of a class
* @param {String} key the property key to test
* @returns {Boolean}
*/
hasPropertySetter(proto, key) {
let descriptor;
while (proto.__proto__) {
descriptor = Object.getOwnPropertyDescriptor(proto, key);
if (typeof descriptor === 'object' && typeof descriptor.set === 'function') {
return true
}
proto = proto.__proto__
}
return false
},
/**
* Deep-merges a source object into a target object
* @memberOf module:Neo
* @param {Object} target
* @param {Object} source
* @param {Object} defaults
* @returns {Object} target
*/
merge(target, source, defaults) {
if (defaults) {
return Neo.merge(Neo.merge(target, defaults), source)
}
for (const key in source) {
const value = source[key];
if (Neo.typeOf(value) === 'Object') {
target[key] = Neo.merge(target[key] || {}, value)
} else {
target[key] = value
}
}
return target
},
/**
* Maps a className string into a given or global namespace
* @example
* Neo.ns('Neo.button.Base', true);
* // =>
* // globalThis.Neo = globalThis.Neo || {};
* // globalThis.Neo.button = globalThis.Neo.button || {};
* // globalThis.Neo.button.Base = globalThis.Neo.button.Base || {};
* // return globalThis.Neo.button.Base;
*
* @memberOf module:Neo
* @param {Array|String} names The class name string containing dots or an Array of the string parts
* @param {Boolean} [create] Set create to true to create empty objects for non-existing parts
* @param {Object} [scope] Set a different starting point as globalThis
* @returns {Object} reference to the toplevel namespace
*/
ns(names, create, scope) {
names = Array.isArray(names) ? names : names.split('.');
return names.reduce((prev, current) => {
if (create && !prev[current]) {
prev[current] = {}
}
if (prev) {
return prev[current]
}
}, scope || globalThis)
},
/**
* Extended version of Neo.ns() which supports mapping into arrays.
* @memberOf module:Neo
* @param {Array|String} names The class name string containing dots or an Array of the string parts
* @param {Boolean} [create] Set create to true to create empty objects for non-existing parts
* @param {Object} [scope] Set a different starting point as globalThis
* @returns {Object} reference to the toplevel namespace
*/
nsWithArrays(names, create, scope) {
names = Array.isArray(names) ? names : names.split('.');
return names.reduce((prev, current) => {
if (create && !prev[current]) {
if (current.endsWith(']')) {
return createArrayNs(true, current, prev)
}
prev[current] = {}
}
if (prev) {
if (current.endsWith(']')) {
return createArrayNs(false, current, prev)
}
return prev[current]
}
}, scope || globalThis)
},
/**
* Creates instances of Neo classes using their ntype instead of the class name
* @example
* Neo.ntype('button' {
* iconCls: 'fa fa-home',
* text : 'Home'
* });
* @example
* Neo.ntype({
* ntype : 'button',
* iconCls: 'fa fa-home',
* text : 'Home'
* });
* @memberOf module:Neo
* @param {String|Object} ntype
* @param {Object} [config]
* @returns {Neo.core.Base}
* @see {@link module:Neo.create create}
*/
ntype(ntype, config) {
if (typeof ntype === 'object') {
config = ntype;
if (!config.ntype) {
throw new Error('Class defined with object configuration missing ntype property. ' + config.ntype)
}
ntype = config.ntype
}
let className = Neo.ntypeMap[ntype];
if (!className) {
throw new Error('ntype ' + ntype + ' does not exist')
}
return Neo.create(className, config)
},
/**
* Internally used at the end of each class / module definition
* @memberOf module:Neo
* @template T
* @param {T} cls
* @returns {T}
*/
setupClass(cls) {
let baseCfg = null,
ntypeChain = [],
{ntypeMap} = Neo,
proto = cls.prototype || cls,
ns = Neo.ns(proto.constructor.config.className, false),
protos = [],
cfg, config, ctor, ntype;
/*
* If the namespace already exists, directly return it.
* This can happen when using different versions of neo.mjs
* => Especially singletons (IdGenerator) must stay unique.
*
* This can also happen when using different environments of neo.mjs in parallel.
* Example: code.LivePreview running inside a dist/production app.
*/
if (ns) {
return ns
}
while (proto.__proto__) {
ctor = proto.constructor;
if (Object.hasOwn(ctor, 'classConfigApplied')) {
baseCfg = Neo.clone(ctor.config, true);
ntypeChain = [...ctor.ntypeChain];
break
}
protos.unshift(proto);
proto = proto.__proto__
}
config = baseCfg || {};
protos.forEach(element => {
let mixins;
ctor = element.constructor;
cfg = ctor.config || {};
if (Neo.overwrites) {
ctor.applyOverwrites?.(cfg)
}
Object.entries(cfg).forEach(([key, value]) => {
if (key.slice(-1) === '_') {
delete cfg[key];
key = key.slice(0, -1);
cfg[key] = value;
autoGenerateGetSet(element, key)
}
// only apply properties which have no setters inside the prototype chain
// those will get applied on create (Neo.core.Base -> initConfig)
else if (!Neo.hasPropertySetter(element, key)) {
Object.defineProperty(element, key, {
enumerable: true,
value,
writable : true
})
}
});
if (Object.hasOwn(cfg, 'ntype')) {
ntype = cfg.ntype;
ntypeChain.unshift(ntype);
// Running the docs app inside a workspace can pull in the same classes from different roots,
// so we want to check for different class names as well
if (Object.hasOwn(ntypeMap, ntype) && cfg.className !== ntypeMap[ntype]) {
throw new Error(`ntype conflict for '${ntype}' inside the classes:\n${ntypeMap[ntype]}\n${cfg.className}`)
}
ntypeMap[ntype] = cfg.className
}
mixins = Object.hasOwn(config, 'mixins') && config.mixins || [];
if (ctor.observable) {
mixins.push('Neo.core.Observable')
}
if (Object.hasOwn(cfg, 'mixins') && Array.isArray(cfg.mixins) && cfg.mixins.length > 0) {
mixins.push(...cfg.mixins)
}
if (mixins.length > 0) {
applyMixins(ctor, mixins);
if (Neo.ns('Neo.core.Observable', false, ctor.prototype.mixins)) {
ctor.observable = true
}
}
delete cfg.mixins;
delete config.mixins;
Object.assign(config, cfg);
Object.assign(ctor, {
classConfigApplied: true,
config : Neo.clone(config, true),
isClass : true,
ntypeChain
});
!config.singleton && this.applyToGlobalNs(cls)
});
proto = cls.prototype || cls;
ntypeChain.forEach(ntype => {
proto[`is${Neo.capitalize(Neo.camel(ntype))}`] = true
});
if (proto.singleton) {
cls = Neo.create(cls);
Neo.applyToGlobalNs(cls)
}
return cls
},
/**
* @param {*} item
* @returns {String|null}
*/
typeOf(item) {
if (item === null || item === undefined) {
return null
}
return typeDetector[typeof item]?.(item) || item.constructor.name
}
}, Neo);
/**
* List of class properties which are not supposed to get mixed into other classes
* @type {string[]}
* @private
*/
const ignoreMixin = [
'_name',
'classConfigApplied',
'className',
'constructor',
'isClass',
'mixin',
'ntype',
'observable'
],
charsRegex = /\d+/g,
extractArraysRegex = /^(\w+)\s*((?:\[\s*\d+\s*\]\s*)*)$/;
/**
* @param {Neo.core.Base} cls
* @param {Array} mixins
* @private
*/
function applyMixins(cls, mixins) {
if (!Array.isArray(mixins)) {
mixins = [mixins];
}
let i = 0,
len = mixins.length,
mixinClasses = {},
mixin, mixinCls, mixinProto;
for (;i < len;i++) {
mixin = mixins[i];
if (mixin.isClass) {
mixinProto = mixin.prototype;
mixinCls = Neo.ns(mixinProto.className)
} else {
if (!exists(mixin)) {
throw new Error('Attempting to mixin an undefined class: ' + mixin + ', ' + cls.prototype.className)
}
mixinCls = Neo.ns(mixin);
mixinProto = mixinCls.prototype;
}
mixinProto.className.split('.').reduce(mixReduce(mixinCls), mixinClasses);
Object.getOwnPropertyNames(mixinProto).forEach(mixinProperty(cls.prototype, mixinProto))
}
cls.prototype.mixins = mixinClasses // todo: we should do a deep merge
}
/**
* Creates get / set methods for class configs ending with an underscore
* @param {Neo.core.Base} proto
* @param {String} key
* @private
* @tutorial 02_ClassSystem
*/
function autoGenerateGetSet(proto, key) {
if (Neo.hasPropertySetter(proto, key)) {
throw('Config ' + key + '_ (' + proto.className + ') already has a set method, use beforeGet, beforeSet & afterSet instead')
}
if (!Neo[getSetCache]) {
Neo[getSetCache] = {}
}
if (!Neo[getSetCache][key]) {
Neo[getSetCache][key] = {
get() {
let me = this,
beforeGet = `beforeGet${key[0].toUpperCase() + key.slice(1)}`,
hasNewKey = Object.hasOwn(me[configSymbol], key),
newKey = me[configSymbol][key],
value = hasNewKey ? newKey : me['_' + key];
if (Array.isArray(value)) {
if (key !== 'items') {
value = [...value]
}
} else if (value instanceof Date) {
value = new Date(value.valueOf())
}
if (hasNewKey) {
me[key] = value; // we do want to trigger the setter => beforeSet, afterSet
value = me['_' + key]; // return the value parsed by the setter
delete me[configSymbol][key]
}
if (typeof me[beforeGet] === 'function') {
value = me[beforeGet](value)
}
return value
},
set(value) {
if (value === undefined) {
return
}
let me = this,
_key = '_' + key,
uKey = key[0].toUpperCase() + key.slice(1),
beforeSet = 'beforeSet' + uKey,
afterSet = 'afterSet' + uKey,
oldValue = me[_key];
// every set call has to delete the matching symbol
delete me[configSymbol][key];
if (key !== 'items') {
value = Neo.clone(value, true, true)
}
// we do want to store the value before the beforeSet modification as well,
// since it could get pulled by other beforeSet methods of different configs
me[_key] = value;
if (typeof me[beforeSet] === 'function') {
value = me[beforeSet](value, oldValue);
// If they don't return a value, that means no change
if (value === undefined) {
me[_key] = oldValue;
return
}
me[_key] = value;
}
if (
(key === 'vnode' && value !== oldValue) || // vnode trees can be huge, avoid a deep comparison
!Neo.isEqual(value, oldValue)
) {
me[afterSet]?.(value, oldValue);
me.afterSetConfig?.(key, value, oldValue)
}
}
}
}
Object.defineProperty(proto, key, Neo[getSetCache][key])
}
/**
* @param {Boolean} create
* @param {Object} current
* @param {Object} prev
* @returns {Object|undefined}
*/
function createArrayNs(create, current, prev) {
let arrDetails = parseArrayFromString(current),
i = 1,
len = arrDetails.length,
arrItem, arrRoot;
if (create) {
prev[arrDetails[0]] = arrRoot = prev[arrDetails[0]] || []
} else {
arrRoot = prev[arrDetails[0]]
}
if (!arrRoot) {
return
}
for (; i < len; i++) {
arrItem = parseInt(arrDetails[i]);
if (create) {
arrRoot[arrItem] = arrRoot[arrItem] || {}
}
arrRoot = arrRoot[arrItem]
}
return arrRoot
}
/**
* Checks if the class name exists inside the Neo or app namespace
* @param {String} className
* @returns {Boolean}
* @private
*/
function exists(className) {
try {
return !!className.split('.').reduce((prev, current) => {
return prev[current]
}, globalThis)
} catch(e) {
return false
}
}
/**
* @param {Neo.core.Base} proto
* @param {Neo.core.Base} mixinProto
* @returns {Function}
* @private
*/
function mixinProperty(proto, mixinProto) {
return function(key) {
if (~ignoreMixin.indexOf(key)) {
return
}
if (proto[key]?._from) {
if (mixinProto.className === proto[key]._from) {
console.warn('Mixin set multiple times or already defined on a Base Class', proto.className, mixinProto.className, key);
return
}
throw new Error(
`${proto.className}: Multiple mixins defining same property (${mixinProto.className}, ${proto[key]._from}) => ${key}`
)
}
proto[key] = mixinProto[key];
Object.getOwnPropertyDescriptor(proto, key)._from = mixinProto.className;
if (typeof proto[key] === 'function') {
proto[key]._name = key
}
}
}
/**
* @param mixinCls
* @returns {Function}
* @private
*/
function mixReduce(mixinCls) {
return (prev, current, idx, arr) => {
return prev[current] = idx !== arr.length -1 ? prev[current] || {} : mixinCls
}
}
/**
* @param {String} str
* @returns {Function}
* @private
*/
function parseArrayFromString(str) {
return (extractArraysRegex.exec(str) || [null]).slice(1).reduce(
(fun, args) => [fun].concat(args.match(charsRegex))
)
}
Neo.config = Neo.config || {};
Neo.assignDefaults(Neo.config, DefaultConfig);
export default Neo;