-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodular-ui.js
1582 lines (1394 loc) · 56.3 KB
/
modular-ui.js
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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =====================================
// modular-ui base classes
//
// Copyright BCC South Africa
// =====================================
// Map of element types, attributes and matching events supported for automatic data binding.
// For attributes that can be changed from the web-page, the event name is included.
// For attributes that only should be set in JavaScript (i.e removed from the element HTML), jsOnly is set to true.
// If a element type cannot be found or an attribute is not listed under the specified element type, modular-ui will try to find the attribute in _default.
const __bindingMap = {
_default: {
textContent: {},
title: {},
hidden: { jsOnly: true },
disabled: { jsOnly: true },
},
a: {
href: {},
},
input: {
value: { event: 'change' },
checked: { event: 'change', jsOnly: true },
max: {},
min: {},
step: {},
placeholder: {},
},
textarea: {
value: { event: 'change', jsOnly: true },
},
select: {
value: { event: 'change', jsOnly: true },
},
img: {
src: {},
},
progress: {
max: {},
value: {},
},
video: {
src: {},
},
}
// Map of element types and attributes to be ignored
const __ignoreMap = {
elements: {
},
attributes: {
for: true,
},
}
/* #region Dispatcher Event */
// Code adapted from https://labs.k.io/creating-a-simple-custom-event-system-in-javascript/
class DispatcherEvent {
constructor(eventName) {
this.eventName = eventName;
this.callbacks = [];
}
registerCallback(callback, once) {
this.callbacks.push({ callback: callback, once: once });
}
unregisterCallback(callback) {
const index = this.callbacks.findIndex(c => Object.is(c.callback, callback));
if (index > -1) {
this.callbacks.splice(index, 1);
}
}
unregisterAll() {
this.callbacks.splice(0, this.callbacks.length);
}
fire(data) {
const callbacks = this.callbacks.slice(0);
var once = [];
callbacks.forEach((c) => {
c.callback(data);
if (c.once) {
once.push(c);
}
});
// Unregister callbacks for all "once" events
once.forEach((c) => {
this.unregisterCallback(c.callback);
});
}
}
// code adapted from https://labs.k.io/creating-a-simple-custom-event-system-in-javascript/
class Dispatcher {
constructor() {
this.events = {};
}
/**
* Emit an event
* @param {string} eventName
* @param {*} data
*/
emit(eventName, data) {
const event = this.events[eventName];
if (event) {
event.fire(data);
}
}
/**
* Subscribe to event
* @param {string} eventName
* @param {*} callback
*/
on(eventName, callback) {
let event = this.events[eventName];
if (!event) {
event = new DispatcherEvent(eventName);
this.events[eventName] = event;
}
event.registerCallback(callback);
}
/**
* Subscribe to the event only for one fire
* @param {string} eventName
* @param {*} callback
*/
once(eventName, callback) {
let event = this.events[eventName];
if (!event) {
event = new DispatcherEvent(eventName);
this.events[eventName] = event;
}
event.registerCallback(callback, true);
}
/**
* Depreciated. Use once()
* @param {*} eventName
* @param {*} callback
*/
one(eventName, callback) {
this.once(eventName, callback);
}
/**
* Unsubscribe from event
* @param {string} eventName
* @param {*} callback
*/
off(eventName, callback) {
const event = this.events[eventName];
event.unregisterCallback(callback);
if (event.callbacks.length === 0) {
delete this.events[eventName];
}
}
/**
* Unsubscribe from all events.
*/
clearEvents() {
Object.values(this.events).forEach(e => {
e.unregisterAll();
});
}
}
/* #endregion */
/* #region modular-ui base class */
/**
* modular-ui base class
*/
class ui extends Dispatcher {
/**
* modular-ui base class
* @property {string} name - Special property indicating the name of the control. This property should not be set in code.
* @property {string} controlType - The name of the class. This property should not be set in code.
* @property {string} parentElement - Reference object name of the HTML element in which child controls should be added. Default: "_controlsDiv".
* @property {boolean} hideData - When true, excludes this control and subsequent child controls' data from GetData() results and 'data' events.
* @property {boolean} remove - When set to true through SetData(), removes this control (or the child control passed to) from the DOM and from the modular-ui data model.
* @property {string} cssText - CSS style text to be applied to the control's containing HTML element (div).
* @property {string} cssClass - CSS class or list of space separated classes to be applied to the control's containg HTML element (div).
* @property {boolean} visible - Sets the control's visibility in the DOM. Visibility is controlled by setting the "display" CSS parameter of the control's containing HTML element (div) according to the customisable values "control.visibleDisplayCss" and "control.hiddenDisplayCss". Default: true.
* @property {string} visibleDisplayCss - Visible CSS display setting. Default: "inherit".
* @property {string} hiddenDisplayCss - Hidden CSS display setting. Default: "none".
*/
constructor() {
super();
this.name = "controlName"; // Special property indicating the name of the control. This cannot be changed in runtime.
this._path = ""; // Special property containing the path to the modular-ui control classes.
this.controlType = this.constructor.name; // The name of the class. This property should not be set in code.
this._parent = undefined; // Reference to the parent control (if any)
this._topLevelParent = undefined; // Reference to the top level parent. Undefined if this control is the top level parent.
this._element = document.createElement('div'); // Control's top level element. All custom html is added inside this element (see get html())
this._controls = {}; // List of child controls
this._properties = {}; // List of properties populated for properties with getters and setters
this._controlsQueue = []; // Queue child controls to be created
this._htmlControlQueue = []; // Queue child controls to be initialized while this control is not yet initialized
this._styles = []; // Add css style paths to this array
this._appliedStyles = []; // List of applied CSS style sheets
this._pendingScripts = {}; // List of controls waiting for the loaded script to be applied
this._htmlElementQueue = {}; // List of controls waiting to be be added to the DOM.
this._uuid = this._generateUuid(); // Unique ID for this control
this._init = false; // True when the control has been initialized (DOM linkup complete)
this._elementIdQueue = []; // List of element object names (to be added as class properties) and element ID's
this._elementAttributeQueue = []; // List of element attributes to be bound to class properties
this.parentElement = '_controlsDiv'; // Reference object name of the HTML element in which child controls should be added.
this.hideData = false; // Set to true if the control's data should be excluded from GetData() and from _notify();
this.remove = undefined; // When control.remove : true is passed to the control via SetData(), the control is removed by it's parent.
this.cssText = ''; // CSS style to be applied to the control's containing element.
this.cssClass = ''; // CSS class or list of space separated classes to be applied to the control's containg element.
this.visible = true; // Visibility of the control.
this._element.id = this._uuid;
this.visibleDisplayCss = 'inherit'; // Visible css display setting.
this.hiddenDisplayCss = 'none'; // Hidden css display setting.
this._elementPollCounter = 0; // Counter used by fallbackTimer when polling if container element is added to the DOM
// Hide control's containing html div element on creation
this._element.style.display = 'none';
this.orderBy = ''; // Property name by which the child controls should be sorted. Sorting is currently only supported in the default child controls element (_controlsDiv).
this.orderAsc = true; // true: Sort asceding. False, sort decending. Sorting is currently only supported in the default child controls element (_controlsDiv).
this._sorted = []; // Internal array used for sorting of sortable child controls. (Sortable = contains a property with name as per orderBy value)
this._sortVal = ''; // Internal sort property string value
this.__sortCallback; // Internal reference to a control's sorting callback
this._orderByPrev = ''; // Internal previous orderBy property value to keep track of changes
/**
* Used internally to bypass updates notifications through the 'data' event when properties are set by Set();
*/
this._bypassNotify = false;
/**
* Internal property used to store filter function set through this.filter();
*/
this._filterFunction = undefined;
/**
* Internal list for keeping track of filter property monitor event subscriptions
*/
this._filterMonitorProperties = {};
/**
* Cached property event callbacks used by the parent's parent.filter() function
*/
this._filterCallbacks = {};
}
// -------------------------------------
// Overridden functions
// -------------------------------------
/**
* Emit an event
* @param {string} eventName
* @param {*} data - Data to be emitted
* @param {string} scope - [Optional] local: Only emit on this control; bubble: Emit on this control and all parent controls; top: Only emit on top level parent control; local_top: Emit on both this control and top level parent control; (Default: local)
*/
emit(eventName, data, scope = 'local') {
// local emit
if (scope == 'local' || scope == 'local_top' || scope == 'bubble') {
super.emit(eventName, data);
}
// parent control emit
if (scope == 'bubble' && this._parent) {
this._parent.emit(eventName, data, scope);
}
// top level control emit
if (scope == 'top' || scope == 'local_top') {
this._topLevelParent.emit(eventName, data);
}
}
/**
* Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple times.
* @param {string} eventName
* @param {*} listener - callback function
* @param {*} options - Optional: { immediate: true, caller: [caller control] } - immediate: true: (only for class property change events) Calls the 'listener' callback function immediately on subscription with the current value of the property (if existing); caller: [caller control]: Subscribes to the 'remove' event of the caller, and automatically unsubscribes from the event when the caller is removed. This helps to prevent uncleared references to the removed control's callback functions.
* @returns - Returns a reference to passed callback (listener) function.
*/
on(eventName, listener, options) {
super.on(eventName, listener);
if (options) {
// Call the immediate callback
if (options.immediate && this[eventName] != undefined) {
listener(this[eventName]);
}
// Automatically unsubscribe from event if the caller is removed
if (options.caller && options.caller.on) {
options.caller.on('remove', () => {
this.off(eventName, listener);
});
}
}
return listener;
}
/**
* Adds a one-timelistener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.
* @param {string} eventName
* @param {*} listener - callback function
* @param {*} options - Optional: { caller: [caller control] } - caller: [caller control]: Subscribes to the 'remove' event of the caller, and automatically unsubscribes from the event when the caller is removed. This helps to prevent memory uncleared references to the removed control's callback functions.
* @returns - Returns a reference to passed callback (listener) function.
*/
once(eventName, listener, options) {
super.once(eventName, listener);
if (options) {
// Automatically unsubscribe from event if the caller is removed
if (options.caller && options.caller.on) {
options.caller.on('remove', () => {
this.off(eventName, listener);
});
}
}
return listener;
}
// -------------------------------------
// Override Getters & setters
// -------------------------------------
/**
* Override this getter in the implementing class
*/
get html() {
return `
<div id="${this._uuid}_main" >
<!-- ${this.name} -->
<div id="${this._uuid}_controls"></div>
</div>`;
}
// -------------------------------------
// Override Functions
// -------------------------------------
/**
* Implementing class should override this function
* This function is called by the parent control when the child's (this control) html has been printed to the DOM.
*/
Init() {
this._mainDiv = document.getElementById(`${this._uuid}_main`);
// Element containing child controls. Controls that should not be able to host child controls
// should not include this line.
this._controlsDiv = document.getElementById(`${this._uuid}_controls`);
}
/**
* Depreciated. Controls now includes a containing HTML element which modular-ui identifies automatically, and which is used to remove the control's HTML from the DOM.
*/
RemoveHtml() {
this._element.remove();
}
// -------------------------------------
// Core functions
// -------------------------------------
/**
* Gets a list of child controls
*/
get childControls() {
return this._controls;
}
/**
* Sets a javascript data object, and updates values, creates and removes controls as applicable.
* @param {object} data - Object data to be set
*/
Set(data) {
if (data && typeof data == 'object') {
Object.keys(data).forEach((k) => {
// Check for remove command
if (k == "remove") {
if (data[k] == true) {
this._parent.RemoveChild(this.name);
}
}
// Ignore invalid and special keys
else if (k[0] != "_" && k != "controlType") {
// Update this control's settable (not starting with "_") properties
if (
this[k] != undefined &&
(typeof this[k] == "number" ||
typeof this[k] == "string" ||
typeof this[k] == "boolean" ||
Array.isArray(this[k]))) {
if (data[k] != null && data[k] != undefined) {
this._bypassNotify = true;
this[k] = data[k];
}
else {
// Prevent properties to be set to undefined or null
this._bypassNotify = true;
this[k] = `${data[k]}`;
}
}
// Update child controls. If a child control shares the name of a settable property, the child control will not receive data.
else if (this._controls[k] != undefined) {
this._controls[k].Set(data[k]);
}
// Create a new child control if the passed data has controlType set. If this control is not ready yet (Init did not run yet),
// add new child controls to a controls queue.
else if (data[k] != null && data[k].controlType != undefined) {
// Wait 1ms before creating the control to prevent "freezing up" the browser (gives the event Javascript loop time to process other logic).
setTimeout(() => { this._createControl(data[k], k) }, 1);
}
}
});
}
}
/**
* Depreciated. Use Set().
*/
SetData(data) {
return this.Set(data);
}
/**
* Create a new control from data
* @param {object} data - Control data structure. (May include child controls.)
* @param {string} name - Control name
*/
async _createControl(data, name) {
// Pre-load script
this._loadScript(data.controlType).catch(err => {
console.log(err);
});
// Add to queue
this._controlsQueue.push({ data: data, name: name });
// Only start processing with first control. Subsequent controls will be processed from the queue
if (this._controlsQueue.length == 1) {
// Process queue
while (this._controlsQueue.length > 0) {
let c = this._controlsQueue[0];
// Check if control already exists. This is needed to prevent creation of duplicate controls if SetData() is executed more than once for the same control, resulting in more than one control in the _controlsQueue.
if (this._controls[c.name]) {
// Set control child data
this._controls[c.name].Set(c.data);
} else {
// Child control does not exist: continue to create control.
let controlClass = this._getDynamicClass(c.data.controlType);
// Load script if class does not exists
if (!controlClass) {
await this._loadScript(c.data.controlType).then(result => {
if (result) {
controlClass = this._getDynamicClass(c.data.controlType);
}
}).catch(err => {
console.log(err);
});
}
// Check that the class is loaded
if (controlClass) {
// Create new control
let control = new controlClass();
control.name = c.name;
control._parent = this;
control._path = this._path;
// Set reference to top level parent
if (this._topLevelParent) {
control._topLevelParent = this._topLevelParent;
} else {
control._topLevelParent = this;
}
// Apply css style sheets_controlsQueue
control._styles.forEach(async s => {
await this.ApplyStyle(s);
// To do: test if styles are loaded before continuing.
});
// Create getters and setters
Object.getOwnPropertyNames(control).forEach((k) => {
// Only return settable (not starting with "_") properties
if (
k[0] != "_" &&
(typeof control[k] == "number" ||
typeof control[k] == "string" ||
typeof control[k] == "boolean" ||
Array.isArray(control[k]))
) {
// Store property value in _properties list
control._properties[k] = control[k];
// Create getter and setter
Object.defineProperty(control, k, {
get: function () {
return this._properties[k];
},
set: function (val) {
// Only emit property changes
if (this._properties[k] != val) {
this._properties[k] = val;
if (!this._bypassNotify) {
this.NotifyProperty(k);
} else {
this._bypassNotify = false;
}
this.emit(k, val);
} else {
this._bypassNotify = false;
}
}
});
}
});
// Add new control to controls list
this._controls[c.name] = control;
// Add a direct reference to the control in this control
this[c.name] = control;
// Subscribe to the orderBy and orderAsc events on child controls (used for sorting their child controls)
control.on('orderBy', this._order.bind(control), { caller: control });
control.on('orderAsc', this._order.bind(control), { caller: control });
// Check if sorting is enabled on the parent (this)
let orderBy = this.orderBy;
let subscribeChildOrderProp;
if (orderBy && c.data[orderBy] != undefined || control[orderBy] != undefined &&
!c.data._parentElement || c.data._parentElement == '_controlsDiv' &&
!control._parentElement || control._parentElement == '_controlsDiv') {
// Add sortable string value
if (c.data[orderBy] != undefined) {
if (typeof c.data[orderBy] == 'number') {
control._sortVal = c.data[orderBy];
} else {
control._sortVal = c.data[orderBy].toString().toLowerCase();
}
} else {
// handle cases where orderBy property value is excluded due to sparse data.
if (typeof c.data[orderBy] == 'number') {
control._sortVal = control[orderBy];
} else {
control._sortVal = control[orderBy].toString().toLowerCase();
}
}
// Calculate index for inserting in _sorted array
let insertIndex;
if (this.orderAsc) {
insertIndex = this._sorted.findIndex(t => t._sortVal > control._sortVal);
} else {
insertIndex = this._sorted.findIndex(t => t._sortVal < control._sortVal);
}
if (insertIndex < 0) insertIndex = this._sorted.length;
// Insert into the _sorted array
this._sorted.splice(insertIndex, 0, control);
subscribeChildOrderProp = true;
}
// Set control child data
control.Set(c.data);
// Subscribe to the child control's order property after control.Set() to avoid triggering prop event on control creation (sorting on control creation is handled by _addHtml())
if (subscribeChildOrderProp) {
control.__sortCallback = function () {
this._orderSingle(control);
}.bind(this);
control.on(orderBy, control.__sortCallback, { caller: this });
}
// Control interal event subscriptions. Event subscriptions deliberately are done after control data is set
// (i.e. they will not emit on control creation).
// This is done to prevent unexpected behavior before the control is completely initialised. Any initial values are
// set individually where needed.
control.on('visible', visible => {
if (visible) {
control._show();
} else {
control._hide();
}
});
this.on('cssText', val => {
element.style.cssText = val;
});
this.on('cssClass', val => {
element.className = val;
});
// Determine destination element
let e = "_controlsDiv"; // default div
if (c.data.parentElement && typeof c.data.parentElement === 'string') {
e = c.data.parentElement;
}
// Initialize child controls, or add to html controls queue if this control is not initialized yet
if (!this._init) {
this._htmlControlQueue.push(control);
} else {
this._addHtmlQueue(control);
}
}
}
// Remove control from queue
this._controlsQueue.shift();
}
}
}
/**
* Add control to _addHtml queue
* @param {object} control - Control to be added
*/
_addHtmlQueue(control) {
if (control != undefined && control.name != undefined) {
// Create queue for the passed element
if (this._htmlElementQueue[control.parentElement] == undefined) {
this._htmlElementQueue[control.parentElement] = [];
}
this._htmlElementQueue[control.parentElement].push(control);
if (this._htmlElementQueue[control.parentElement].length == 1) {
// This is the first control to be added to the element. Start the _addHtml loop
this._addHtml(control.parentElement)
}
}
else {
console.log(`Unable to add control "${control.name}" to element "${control.parentElement}"`)
}
}
/**
* Adds HTML to the giving element from the initMutationCache
* @param {string} element - Element object name
*/
_addHtml(element) {
try {
let control = this._htmlElementQueue[element][0];
let parentControl = this;
let observer;
// Wait for HTML to be printed in the element before initializing control
// Fallback timer as workaround when mutation observer is not triggering (sometimes occurs when Chrome dev-tools is open)
let fallbackTimer = setInterval(() => {
// Try counter
control._elementPollCounter += 1;
// Check if containing element exists in DOM
if (document.getElementById(control._element.id)) {
console.log(`Falling back to polling mechanism for control "${control.name}"`);
this._htmlInit(observer, parentControl, element, control, fallbackTimer);
}
// Element not created. Stop polling
else if (control._elementPollCounter >= 10) {
// Stop fallback interval timer and mutation observer
if (observer) observer.disconnect();
clearInterval(fallbackTimer);
delete control._elementPollCounter;
console.log(`Unable to add HTML to element "${element}" in control "${parentControl.name}". Element ID not found in DOM.`);
}
}, 20);
// Mutation observer
observer = new MutationObserver(function (mutationsList, observer) {
parentControl._htmlInit(observer, parentControl, element, control, fallbackTimer);
});
// Observe controls element for changes to contents
observer.observe(parentControl[element], { childList: true, attributes: false });
// Parse control html
let p = this._parseHtml(control);
// Add element ids for data binding
control._elementIdQueue.push(...p.idData);
// Add element attributes for data binding
control._elementAttributeQueue.push(...p.elementData);
// Print HTML of child control into it's own top level element
control._element.innerHTML = p.html;
// Check if sorting is enabled
if (parentControl.orderBy) {
// Sorted list if initialized sibling controls and this control
let sorted = parentControl._sorted.filter(f => f._init || f.name == control.name);
// Get control index position
let i = sorted.findIndex(t => t.name == control.name);
if (sorted.length <= 1 || i >= sorted.length - 1 || i < 0) {
// Add the child control's top level element to the end of the parent's controls div
parentControl[element].appendChild(control._element);
} else {
let nextControl = parentControl[sorted[i + 1].name];
// Insert the child control's top level element in it's sorted position
parentControl[element].insertBefore(control._element, nextControl._element);
}
} else {
// Add the child control's top level element to the parent's controls div
parentControl[element].appendChild(control._element);
}
}
catch (error) {
console.log(`Unable to add HTML to element "${element}" in control "${this.name}". ${error.message}`);
}
}
// Initialize control after added to the DOM
_htmlInit(observer, parentControl, element, control, fallbackTimer) {
// Disconnect mutation observer and stop fallback interval timer
observer.disconnect();
clearInterval(fallbackTimer);
delete control._elementPollCounter;
// Data bind values from @{identifier} tags
control._createDataBindings();
// Apply css to the control's containing _element
control._element.style.cssText = control.cssText;
control._element.className = control.cssClass;
control._visibleDisplayCss = control._element.style.display;
// Set initial visibility
if (control.visible) {
if (parentControl._filterFunction) {
if (parentControl._filterFunction(control)) {
control._show();
} else {
control._hide();
}
} else {
control._show();
}
} else {
control._hide();
}
// Subscribe to filter property events for newly created controls
Object.keys(parentControl._filterMonitorProperties).forEach(propertyName => {
control._filterCallbacks[propertyName] = control.on(propertyName, () => {
if (parentControl._filterFunction && parentControl._filterFunction(control)) {
control._show();
} else {
control._hide();
}
}, { caller: parentControl });
});
// Run (overridden) control initialisation logic
control.Init();
control._init = true;
// Notify that initialization is done
control.emit("init", control);
parentControl.emit(control.name, control);
parentControl.emit('newChildControl', control);
// Remove control from the queue
parentControl._htmlElementQueue[element].shift();
// Add html of subsequent controls in the queue
if (parentControl._htmlElementQueue[element] != undefined && parentControl._htmlElementQueue[element].length > 0) {
parentControl._addHtml(element);
}
// Add queued child controls
while (control._htmlControlQueue.length > 0) {
control._addHtmlQueue(control._htmlControlQueue.shift());
}
}
_htmlPollElementId(id) {
document.getElementById(id);
}
/**
* Checks if the passed object is an array.
* @returns Array with passed array elements. If passed element is not an array, passes an array with one element.
*/
__array(data) {
if (data != null && data != undefined) {
if (Array.isArray(data)) {
return data;
} else {
let a = [];
a.push(data);
return a;
}
} else {
return [];
}
}
/**
* Parse html of a control, and creates properties for parsed elements identified with @{identifier} tags.
* Currently only html element id's are supported.
* @param {string} html
* @returns {Object} - Object with modified html (identifier tags replaced with unique ID's) and data binding data.
*/
_parseHtml(control) {
var html = control.html;
let eDataList = []; // element data list
let idList = {}; // id list
// Extract HTML elements with class properties inserted with @{identifier} tags
let eList = this.__array(html.match(/<[^<]*>[ |\t|\n]*@{[_a-zA-Z0-9]*}[ |\t|\n]*<\/[^<]*>|<[^<]*@{[_a-zA-Z0-9]*}[^<]*(>[^>]*<\/[^<]*>|[\/]?>)/gmi));
eList.forEach(elementHtml => {
var elementHtml_new = elementHtml;
// Extract the element type
let eType = this.__array(elementHtml.match(/^<[a-zA-Z]*[0-9]?/gmi));
if (eType.length > 0) {
eType = eType[0].replace('<', '').toLowerCase();
} else {
console.log(`${control.name}: Unable to parse element: Element type not set.`);
return;
}
// Ignore elements in ignore map
if (__ignoreMap.elements[eType]) return;
// Element data
let eData = { elementType: eType, attributes: {} };
let tagList = [];
// Extract all instances of @{identifier} tags
this.__array(elementHtml.match(/[a-zA-Z]*\=["|']?@{[_a-zA-Z0-9]*}|>[ |\t|\n]*@{[_a-zA-Z0-9]*}[ |\t|\n]*</gmi)).forEach(tData => {
// Get attribute type
let aType = this.__array(tData.match(/[a-zA-Z]+=/gmi));
if (aType.length > 0) {
aType = aType[0].replace('=', '');
} else {
aType = 'textContent';
}
// Ignore attributes in ignore map
if (__ignoreMap.attributes[aType]) return;
// Get the indentifier tag
let tag = this.__array(tData.match(/@{[_a-zA-Z0-9]*}/gmi))[0].replace('@{', '').replace('}', '');
tagList.push(tag);
// Add attribute
if (!eData.attributes[aType]) {
eData.attributes[aType] = tag;
} else {
console.log(`${control.name}: Unable to link property "${tag}" to element "${eType}" attribute "${aType}": duplicate attribute`);
}
});
if (!eData.attributes.id) {
// Check element for existing (invalid) ID
if (elementHtml.match(/[ |\t]+id=/gmi)) {
console.log(`${control.name}: Unable to link properties to element "${eType}": Invalid element ID - ID not an @{identifier} tag)`);
return;
} else {
// Create element ID if element does not have an ID specified
// Use the same name for the element object reference (to be created) and the element id
let id = `${control._uuid}_id_${this._generateUuid()}`;
eData.attributes.id = id;
idList[id] = id;
elementHtml_new = elementHtml_new.replace(/^<[a-zA-Z]*/gmi, `<${eType} id="${id}"`);
}
} else if (!idList[eData.attributes.id]) {
idList[eData.attributes.id] = `${eData.attributes.id}_${control._uuid}`;
}
// Remove JavaScript only attributes from HTML
Object.keys(eData.attributes).forEach(attribute => {
if (__bindingMap[eType] && __bindingMap[eType][attribute] && __bindingMap[eType][attribute].jsOnly) {
// Update element html
let r = new RegExp(`${attribute}=[ |\t]*["|']?@\{${eData.attributes[attribute]}\}["|']?`, 'gmi');
elementHtml_new = elementHtml_new.replace(r, '');
}
});
// Update element with tag values
// filter unique values tags assigned to the element ID
tagList.filter((v, i, a) => a.indexOf(v) === i).filter(t => t != eData.attributes.id).forEach(tag => {
// Validate tag
if (control[tag] != undefined) {
// Update element html
let r = new RegExp(`@\{${tag}\}`, 'gmi');
elementHtml_new = elementHtml_new.replace(r, control[tag]);
}
});
// Update html with updated element
html = html.replace(elementHtml, elementHtml_new);
eDataList.push(eData);
});
// Replace all id @{identifier} tags with the generated element id's
let idArr = [];
Object.keys(idList).forEach(id => {
let r = new RegExp(`@\{${id}\}`, 'gmi');
html = html.replace(r, idList[id]);
// Convert id list to array
idArr.push({ id: id, elementID: idList[id] });
});
return { html: html, idData: idArr, elementData: eDataList }
}
/**
* Create data bindings from @{identifier} tags
*/
_createDataBindings() {
// Create element references
while (this._elementIdQueue.length > 0) {
let i = this._elementIdQueue.shift();
if (this[i.id] == undefined) {
this[i.id] = document.getElementById(i.elementID);
if (!this[i.id]) {
console.log(`${this.name}: Unable to create element reference "${i.id}": Element not found`);
}
} else {
console.log(`${this.name}: Unable to create element reference "${i.id}": Class property already exists`);
}
}
// Attribute data binding
while (this._elementAttributeQueue.length > 0) {
let eData = this._elementAttributeQueue.shift();
Object.keys(eData.attributes).forEach(a => {
let prop = eData.attributes[a]; // Property name
let elem = this[eData.attributes.id]; // Element reference
// Subscribe to element changes for supported elements
this._bind(eData.elementType, elem, a, prop);
});
}
}
/**
* Bind a property value to an element attribute. Changes are also notified
* @param {*} elementType
* @param {*} element
* @param {*} attribute
* @param {*} property
*/
_bind(elementType, element, attribute, property) {
if (attribute != 'id' && (typeof this[property] != 'object' || Array.isArray(this[property]))) {
let e = elementType;
// Set element type to _default if element + attribute combination is not found in map.
if (!__bindingMap[e] || !__bindingMap[e][attribute]) e = '_default';
if (__bindingMap[e] && __bindingMap[e][attribute]) {
// Set initial value for JavaScript only attributes
if (__bindingMap[e][attribute].jsOnly) element[attribute] = this[property];
this.__bind(element, attribute, __bindingMap[e][attribute].event, property);
} else {
console.log(`${this.name}: Unable to bind element "${elementType}" attribute "${attribute}" to property "${property}": Unsupported attribute`);
}
}
}
__bind(element, attribute, event, property) {
// Flags to prevent double events
let block1 = false;
let block2 = false;
// Subscribe to property change
this.on(property, val => {
if (!block1) {
block2 = true;
element[attribute] = val;
block2 = false;
}
});
if (event) {
if (!element || !element.addEventListener) {
console.log(`${this.name}: Unable to add event listner "${event}" for property "${property}": Invalid element`);
return;
}
// Subscribe to element event