forked from slimjs/slim.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Slim.js
1560 lines (1408 loc) · 58.6 KB
/
Slim.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
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _CustomElement() {
return Reflect.construct(HTMLElement, [], this.__proto__.constructor);
}
;
Object.setPrototypeOf(_CustomElement.prototype, HTMLElement.prototype);
Object.setPrototypeOf(_CustomElement, HTMLElement);
var Slim = function (_CustomElement2) {
_inherits(Slim, _CustomElement2);
_createClass(Slim, null, [{
key: 'polyfill',
/**
* Auto-detect if the browser supports web-components. If it does not,
* it will add a script tag with the required url.
* Best practice to call polyfill in <head> section of the HTML
* @example
* <head>
* <script src="./path/to/slim/Slim.min.js"></script>
* <script>
* Slim.polyfill('./path/to/web-components-polyfill.js');
* </script>
* </head>
* @param url
*/
value: function polyfill(url) {
if (Slim.__isWCSupported) return;
var scriptTag = document.createElement('script');
scriptTag.src = url;
document.getElementsByTagName('head')[0].appendChild(scriptTag);
}
/**
* Declares a slim component
*
* @param {String} tag html tag name
* @param {String|class|function} clazzOrTemplate the template string or the class itself
* @param {class|function} clazz if not given as second argument, mandatory after the template
*/
}, {
key: 'tag',
value: function tag(_tag, clazzOrTemplate, clazz) {
if (clazz === undefined) {
clazz = clazzOrTemplate;
} else {
Slim.__templateDict[_tag] = clazzOrTemplate;
}
Slim.__prototypeDict[_tag] = clazz;
// window.customElements.define(tag, clazz);
if (Slim.__prototypeDict['slim-repeat'] === undefined) {
Slim.__initRepeater();
}
customElements.define(_tag, clazz);
}
//noinspection JSUnusedGlobalSymbols
/**
*
* @param {class|function} clazz returns the tag declared for a given class or constructor
* @returns {string}
*/
}, {
key: 'getTag',
value: function getTag(clazz) {
for (var tag in Slim.__prototypeDict) {
if (Slim.__prototypeDict[tag] === clazz) return tag;
}
}
}, {
key: 'getClass',
value: function getClass(tag) {
return Slim.__prototypeDict[tag];
}
}, {
key: '__createUqIndex',
value: function __createUqIndex() {
Slim.__uqIndex++;
return Slim.__uqIndex.toString(16);
}
/**
* Supported HTML events built-in on slim components
* @returns {Array<String>}
*/
}, {
key: 'plugin',
/**
* Aspect oriented functions to handle lifecycle phases of elements. The plugin function should gets the element as an argument.
* This is used to extend elements' capabilities or data injections across the application
* @param {String} phase
* @param {function} plugin
*/
value: function plugin(phase, _plugin) {
if (['create', 'beforeRender', 'beforeRemove', 'afterRender'].indexOf(phase) === -1) {
throw "Supported phase can be create, beforeRemove, beforeRender or afterRender only";
}
Slim.__plugins[phase].push(_plugin);
}
//noinspection JSUnusedGlobalSymbols
/**
* This is used to extend Slim. All custom attributes handlers would recieve the function and the value of the attribute when relevant.
* @param {String} attr attribute name
* @param {function} fn
*/
}, {
key: 'registerCustomAttribute',
value: function registerCustomAttribute(attr, fn) {
Slim.__customAttributeProcessors[attr] = Slim.__customAttributeProcessors[attr] || [];
Slim.__customAttributeProcessors[attr].push(fn);
}
/**
* @param phase
* @param element
* @private
*/
}, {
key: '__runPlugins',
value: function __runPlugins(phase, element) {
Slim.__plugins[phase].forEach(function (fn) {
fn(element);
});
}
/**
* Polyfill for IE11 support
* @param target
*/
}, {
key: 'removeChild',
value: function removeChild(target) {
if (target.remove) {
target.remove();
}
if (target.parentNode) {
target.parentNode.removeChild(target);
}
if (target.__ieClone) {
Slim.removeChild(target.__ieClone);
}
if (target._boundChildren) {
target._boundChildren.forEach(function (child) {
if (child.__ieClone) {
Slim.removeChild(child.__ieClone);
}
});
}
}
/**
*
* @param source
* @param target
* @param activate
* @private
*/
}, {
key: '__moveChildrenBefore',
value: function __moveChildrenBefore(source, target, activate) {
while (source.firstChild) {
target.parentNode.insertBefore(source.firstChild, target);
}
var children = Slim.selectorToArr(target, '*');
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var child = _step.value;
if (activate && child.isSlim) {
child.createdCallback();
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
/**
*
* @param source
* @param target
* @param activate
* @private
*/
}, {
key: '__moveChildren',
value: function __moveChildren(source, target, activate) {
while (source.firstChild) {
target.appendChild(source.firstChild);
}
var children = Slim.selectorToArr(target, '*');
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = children[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var child = _step2.value;
if (activate && child.isSlim) {
child.createdCallback();
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
/**
*
* @param obj
* @param desc
* @returns {{source: *, prop: *, obj: *}}
* @private
*/
}, {
key: '__lookup',
value: function __lookup(obj, desc) {
var arr = desc.split(".");
var prop = arr[0];
while (arr.length && obj) {
obj = obj[prop = arr.shift()];
}
return { source: desc, prop: prop, obj: obj };
}
}, {
key: '__inject',
value: function __inject(descriptor) {
try {
descriptor.target[Slim.__dashToCamel(descriptor.attribute)] = Slim.__injections[descriptor.factory](descriptor.target);
} catch (err) {
console.error('Could not inject ' + descriptor.attribute + ' into ' + descriptor.target);
console.info('Descriptor ', descriptor);
throw err;
}
}
}, {
key: 'inject',
value: function inject(name, injector) {
Slim.__injections[name] = injector;
}
/**
*
* @param descriptor
* @private
*/
}, {
key: '__createRepeater',
value: function __createRepeater(descriptor) {
var repeater = void 0;
repeater = document.createElement('slim-repeat');
repeater.sourceNode = descriptor.target;
descriptor.target.repeater = repeater;
descriptor.target.parentNode.insertBefore(repeater, descriptor.target);
descriptor.repeater = repeater;
repeater._boundParent = descriptor.source;
descriptor.target.parentNode.removeChild(descriptor.target);
repeater._isAdjacentRepeater = descriptor.repeatAdjacent;
repeater.setAttribute('source', descriptor.properties[0]);
repeater.setAttribute('target-attr', descriptor.targetAttribute);
descriptor.repeater = repeater;
}
/**
*
* @param dash
* @returns {XML|void|string|*}
* @private
*/
}, {
key: '__dashToCamel',
value: function __dashToCamel(dash) {
return dash.indexOf('-') < 0 ? dash : dash.replace(/-[a-z]/g, function (m) {
return m[1].toUpperCase();
});
}
//noinspection JSUnusedGlobalSymbols
/**
*
* @param camel
* @returns {string}
* @private
*/
}, {
key: '__camelToDash',
value: function __camelToDash(camel) {
return camel.replace(/([A-Z])/g, '-$1').toLowerCase();
}
}, {
key: 'interactionEventNames',
get: function get() {
return ['click', 'mouseover', 'mouseout', 'mousemove', 'mouseenter', 'mousedown', 'mouseup', 'dblclick', 'contextmenu', 'wheel', 'mouseleave', 'select', 'pointerlockchange', 'pointerlockerror', 'focus', 'blur', 'input', 'error', 'invalid', 'animationstart', 'animationend', 'animationiteration', 'reset', 'submit', 'resize', 'scroll', 'keydown', 'keypress', 'keyup', 'change'];
}
}]);
function Slim() {
_classCallCheck(this, Slim);
var _this = _possibleConstructorReturn(this, (Slim.__proto__ || Object.getPrototypeOf(Slim)).call(this));
Slim.__invokeAsap(_this.createdCallback.bind(_this));
return _this;
}
_createClass(Slim, [{
key: 'find',
value: function find(selector) {
return this.rootElement.querySelector(selector);
}
//noinspection JSUnusedGlobalSymbols
}, {
key: 'findAll',
value: function findAll(selector) {
return Slim.selectorToArr(this.rootElement, selector);
}
}, {
key: 'watch',
value: function watch(prop, executor) {
var descriptor = {
type: 'W',
properties: [prop],
executor: executor,
target: this,
source: this
};
this._bindings = this._bindings || {};
this._boundParent = this._boundParent || this;
this.__bind(descriptor);
}
/**
* Function delegation in the DOM chain is supported by this function. All slim components are capable of triggering
* delegated methods using callAttribute and send any payload as they define in their API.
* @param {String} attributeName
* @param {any} value
*/
}, {
key: 'callAttribute',
value: function callAttribute(attributeName, value) {
if (!this._boundParent) {
throw 'Unable to call attribute-bound method when no bound parent available';
}
var fnName = this.getAttribute(attributeName);
if (fnName === null) {
console.warn && console.warn('Unable to call null attribute-bound method on bound parent ' + this._boundParent.outerHTML);
return;
}
if (typeof this._boundParent[fnName] === 'function') {
this._boundParent[fnName](value);
} else if (this._boundParent && this._boundParent._boundParent && typeof this._boundParent._boundParent[fnName] === 'function') {
// safari, firefox
this._boundParent._boundParent[fnName](value);
} else if (this._boundRepeaterParent && typeof this._boundRepeaterParent[fnName] === 'function') {
this._boundRepeaterParent[fnName](value);
} else {
throw "Unable to call attribute-bound method: " + fnName + ' on bound parent ' + this._boundParent.outerHTML + ' with value ' + value;
}
if (typeof this.update === 'function' && (this.isInteractive || Slim.autoAttachInteractionEvents || this.getAttribute('interactive'))) {
this.update();
}
}
}, {
key: '__propertyChanged',
value: function __propertyChanged(property, value, oldValue) {
if (typeof this[property + 'Changed'] === 'function') {
this[property + 'Changed'](value, oldValue);
}
}
/**
*
* @param descriptor
* @private
*/
}, {
key: '__bind',
value: function __bind(descriptor) {
descriptor.properties.forEach(function (prop) {
var rootProp = void 0;
if (prop.indexOf('.') > 0) {
rootProp = prop.split('.')[0];
} else {
rootProp = prop;
}
var source = descriptor.source || descriptor.target._boundParent || descriptor.parentNode;
source._bindings = source._bindings || {};
source._bindings[rootProp] = source._bindings[rootProp] || {
value: source[rootProp],
executors: []
};
var originalValue = source[rootProp];
var originalSetter = source.__lookupSetter__(rootProp);
if (!source.__lookupGetter__(rootProp)) source.__defineGetter__(rootProp, function () {
return this._bindings[rootProp].value;
});
var newSetter = function newSetter(x) {
var oldValue = this._bindings[rootProp].value;
this._bindings[rootProp].value = x;
if (descriptor.sourceText) {
descriptor.target.innerText = descriptor.sourceText;
}
this._executeBindings(rootProp);
this.__propertyChanged(rootProp, x, oldValue);
};
newSetter.isBindingSetter = true;
if (!originalSetter) {
source.__defineSetter__(rootProp, newSetter);
} else if (originalSetter && !originalSetter.isBindingSetter) {
source.__defineSetter__(rootProp, function (x) {
originalSetter.call(this, x);
newSetter.call(this, x);
});
source.__lookupSetter__(rootProp).isBindingSetter = true;
}
var executor = void 0;
if (descriptor.type === 'C') {
executor = function executor() {
descriptor.executor();
};
} else if (descriptor.type === 'P') {
executor = function executor() {
var targets = void 0;
if (!descriptor.target.hasAttribute('slim-repeat')) {
targets = [descriptor.target];
} else {
targets = descriptor.target.repeater.clones;
}
if (targets) {
var sourceRef = descriptor.target._boundRepeaterParent || descriptor.target._boundParent;
var value = Slim.__lookup(sourceRef || source, prop).obj || Slim.__lookup(descriptor.target, prop).obj;
var attrName = Slim.__dashToCamel(descriptor.attribute);
targets.forEach(function (target) {
target[attrName] = value;
target.setAttribute(descriptor.attribute, value);
});
}
};
} else if (descriptor.type === 'M') {
executor = function executor() {
var targets = [descriptor.target];
if (descriptor.target.hasAttribute('slim-repeat')) {
targets = descriptor.target.repeater.clones;
}
var sourceRef = descriptor.target._boundRepeaterParent || source;
var value = sourceRef[descriptor.method].apply(sourceRef, descriptor.properties.map(function (prop) {
return descriptor.target[prop] || sourceRef[prop];
}));
var attrName = Slim.__dashToCamel(descriptor.attribute);
targets.forEach(function (target) {
target[attrName] = value;
target.setAttribute(descriptor.attribute, value);
});
};
} else if (descriptor.type === 'T') {
executor = function executor() {
var source = descriptor.target._boundParent;
descriptor.target._innerText = descriptor.target._innerText.replace('[[' + prop + ']]', Slim.__lookup(source, prop).obj);
};
} else if (descriptor.type === 'TM') {
executor = function executor() {
var values = descriptor.properties.map(function (compoundProp) {
return Slim.__lookup(source, compoundProp).obj;
});
try {
var value = source[descriptor.methodName].apply(source, values);
descriptor.target._innerText = descriptor.target._innerText.replace(descriptor.expression, value);
} catch (exc) {
console.error('Could not execute function ' + descriptor.methodName + ' in element ' + descriptor.source.localName);
console.info(exc);
}
};
} else if (descriptor.type === 'R') {
executor = function executor() {
descriptor.repeater.registerForRender();
// !descriptor.repeater.isRendering && descriptor.repeater.renderList()
};
} else if (descriptor.type === 'W') {
executor = function executor() {
descriptor.executor(Slim.__lookup(source, prop).obj);
};
} else if (descriptor.type === 'F') {
executor = function executor() {
var value = !!Slim.__lookup(descriptor.source, prop).obj;
if (descriptor.reversed) {
value = !value;
}
if (!value) {
if (descriptor.target.parentNode) {
descriptor.target.insertAdjacentElement('beforeBegin', descriptor.helper);
Slim.removeChild(descriptor.target);
}
} else {
if (!descriptor.target.parentNode) {
descriptor.helper.insertAdjacentElement('beforeBegin', descriptor.target);
if (descriptor.target.isSlim) {
descriptor.target.createdCallback();
}
Slim.removeChild(descriptor.helper);
}
}
};
}
executor.descriptor = descriptor;
source._bindings[rootProp].executors.push(executor);
newSetter.call(source, originalValue);
});
}
}, {
key: 'createdCallback',
/**
* Part of the standard web-component lifecycle. Overriding it is not recommended.
*/
value: function createdCallback() {
// __createdCallbackRunOnce is required for babel louzy transpiling
if (this.isVirtual) return;
if (this.__createdCallbackRunOnce) return;
this.__createdCallbackRunOnce = true;
this.initialize();
this.onBeforeCreated();
this._captureBindings();
Slim.__runPlugins('create', this);
this.onCreated();
this.__onCreatedComplete = true;
this.onBeforeRender();
Slim.__runPlugins('beforeRender', this);
Slim.__moveChildren(this._virtualDOM, this.rootElement, true);
this.onAfterRender();
Slim.__runPlugins('afterRender', this);
this.update();
}
/**
*
* @private
*/
}, {
key: '_initInteractiveEvents',
value: function _initInteractiveEvents() {
var _this2 = this;
if (!this.__eventsInitialized && (Slim.autoAttachInteractionEvents || this.isInteractive || this.hasAttribute('interactive'))) Slim.interactionEventNames.forEach(function (eventType) {
_this2.addEventListener(eventType, function (e) {
_this2.handleEvent(e);
});
});
}
/**
* Part of the non-standard slim web-component's lifecycle. Overriding it is not recommended.
*/
}, {
key: 'initialize',
value: function initialize() {
var _this3 = this;
this.uq_index = Slim.__createUqIndex();
this.setAttribute('slim-uq', this.uq_index);
this.constructor.observedAttributes && this.constructor.observedAttributes.forEach(function (attr) {
_this3[Slim.__dashToCamel(attr)] = _this3.getAttribute(attr);
});
this._bindings = this._bindings || {};
this._boundChildren = this._boundChildren || [];
this._initInteractiveEvents();
this.__eventsInitialized = true;
this.alternateTemplate = this.alternateTemplate || null;
this._virtualDOM = this._virtualDOM || document.createDocumentFragment();
}
/**
* Simple test if an HTML element is a Slim elememnt.
* @returns {boolean}
*/
}, {
key: 'handleEvent',
/**
* Handles interactive events, overriding this is not recommended.
* @param e
*/
value: function handleEvent(e) {
if (this.hasAttribute('on' + e.type)) {
this.callAttribute('on' + e.type, e);
} else if (this.hasAttribute(e.type)) {
this.callAttribute(e.type, e);
}
}
/**
* Part of the standard web-component lifecycle. Overriding it is not recommended.
*/
}, {
key: 'connectedCallback',
value: function connectedCallback() {
this.onAdded();
}
/**
* Part of the standard web-component lifecycle. Overriding it is not recommended.
*/
}, {
key: 'disconnectedCallback',
value: function disconnectedCallback() {
Slim.__runPlugins('beforeRemove', this);
this.onRemoved();
}
}, {
key: 'attributeChangedCallback',
value: function attributeChangedCallback(attr, oldValue, newValue) {
var camelCased = Slim.__dashToCamel(attr);
if (oldValue === newValue) return;
if (!this._bindings) return;
if (this._bindings[camelCased] || this._bindables && this._bindables.hasOwnProperty(camelCased)) {
this[camelCased] = newValue;
this._executeBindings(camelCased);
}
}
}, {
key: 'onAdded',
value: function onAdded() {/* abstract */}
}, {
key: 'onRemoved',
value: function onRemoved() {/* abstract */}
}, {
key: 'onBeforeCreated',
value: function onBeforeCreated() {/* abstract */}
}, {
key: 'onCreated',
value: function onCreated() {/* abstract */}
}, {
key: 'onBeforeRender',
value: function onBeforeRender() {/* abstract */}
}, {
key: 'onAfterRender',
value: function onAfterRender() {/* abstract */}
}, {
key: 'onBeforeUpdate',
value: function onBeforeUpdate() {/* abstract */}
}, {
key: 'onAfterUpdate',
value: function onAfterUpdate() {} /* abstract */
/**
* Part of Slim's lifecycle, overriding is not recommended without calling super.update()
*/
}, {
key: 'update',
value: function update() {
this.onBeforeUpdate();
this._executeBindings();
this.onAfterUpdate();
}
/**
* Part of Slim's lifecycle, overriding is not recommended without calling super.render()
*/
}, {
key: 'render',
value: function render(template) {
Slim.__runPlugins('beforeRender', this);
this.onBeforeRender();
this.alternateTemplate = template;
this.initialize();
this.rootElement.innerHTML = '';
this._captureBindings();
this._executeBindings();
Slim.__moveChildren(this._virtualDOM, this.rootElement, true);
this.onAfterRender();
Slim.__runPlugins('afterRender', this);
}
/**
*
* @param prop
* @private
*/
}, {
key: '_executeBindings',
value: function _executeBindings(prop) {
var _this4 = this;
if (!this._bindings) return;
// reset bound texts
this._boundChildren.forEach(function (child) {
// this._boundChildren.forEach( child => {
if (child.hasAttribute('bind') && child.sourceText !== undefined) {
child._innerText = child.sourceText;
}
});
// execute specific binding or all
var properties = prop ? [prop] : Object.keys(this._bindings);
properties.forEach(function (property) {
_this4._bindings[property].executors.forEach(function (fn) {
if (fn.descriptor.type !== 'T' && fn.descriptor.type !== 'TM') fn();
});
});
// execute text bindings always
Object.keys(this._bindings).forEach(function (property) {
_this4._bindings[property].executors.forEach(function (fn) {
if (fn.descriptor.type === 'T' || fn.descriptor.type === 'TM') {
fn();
}
});
_this4._bindings[property].executors.forEach(function (fn) {
if (fn.descriptor.type === 'T' || fn.descriptor.type === 'TM') {
fn.descriptor.target.innerText = fn.descriptor.target._innerText;
if (fn.descriptor.target.__ieClone) {
fn.descriptor.target.__ieClone.innerText = fn.descriptor.target.innerText;
}
}
});
});
}
/**
*
* @private
*/
}, {
key: '_captureBindings',
value: function _captureBindings() {
var _this5 = this;
var self = this;
var $tpl = this.alternateTemplate || this.template;
if (!$tpl) {
while (this.firstChild) {
// TODO: find why this line is needed for babel!!!
self._virtualDOM = this._virtualDOM || document.createDocumentFragment();
self._virtualDOM.appendChild(this.firstChild);
}
} else if (typeof $tpl === 'string') {
var frag = document.createRange().createContextualFragment($tpl);
while (frag.firstChild) {
this._virtualDOM.appendChild(frag.firstChild);
}
var virtualContent = this._virtualDOM.querySelector('slim-content');
if (virtualContent) {
while (self.firstChild) {
self.firstChild._boundParent = this.firstChild._boundParent || this;
virtualContent.appendChild(this.firstChild);
}
}
}
var allChildren = Slim.selectorToArr(this._virtualDOM, '*');
var _loop = function _loop(child) {
child._sourceOuterHTML = child.outerHTML;
child._boundParent = child._boundParent || _this5;
self._boundChildren = _this5._boundChildren || [];
self._boundChildren.push(child);
if (child.localName === 'style' && _this5.useShadow) {
Slim.__processStyleNode(child, _this5.localName, _this5.uq_index);
}
if (child.getAttribute('slim-id')) {
child._boundParent[Slim.__dashToCamel(child.getAttribute('slim-id'))] = child;
}
var slimID = child.getAttribute('slim-id');
if (slimID) _this5[slimID] = child;
var descriptors = [];
if (child.attributes) for (var i = 0; i < child.attributes.length; i++) {
if (!child.isSlim && !child.__eventsInitialized && Slim.interactionEventNames.indexOf(child.attributes[i].nodeName) >= 0) {
child.isInteractive = true;
child.handleEvent = self.handleEvent.bind(child);
child.callAttribute = self.callAttribute.bind(child);
child.addEventListener(child.attributes[i].nodeName, child.handleEvent);
child.__eventsInitialized = true;
}
var desc = Slim.__processAttribute(child.attributes[i], child);
if (desc) descriptors.push(desc);
child[Slim.__dashToCamel(child.attributes[i].nodeName)] = child.attributes[i].nodeValue;
if (child.attributes[i].nodeName.indexOf('#') == '0') {
var refName = child.attributes[i].nodeName.slice(1);
_this5[refName] = child;
}
}
descriptors = descriptors.sort(function (a) {
if (a.type === 'I') {
return -1;
} else if (a.type === 'R') return 1;else if (a.type === 'C') return 2;
return 0;
});
child._boundProperties = {};
descriptors.forEach(function (descriptor) {
descriptor.properties && descriptor.properties.forEach(function (prop) {
child._boundProperties[prop] = true;
});
if (descriptor.type === 'P' || descriptor.type === 'M' || descriptor.type === 'C') {
_this5.__bind(descriptor);
} else if (descriptor.type === 'I') {
Slim.__inject(descriptor);
} else if (descriptor.type === 'R') {
Slim.__createRepeater(descriptor);
_this5.__bind(descriptor);
} else if (descriptor.type === 'F') {
_this5.__bind(descriptor);
}
});
};
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = allChildren[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var child = _step3.value;
_loop(child);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
allChildren = Slim.selectorToArr(this._virtualDOM, '*[bind]');
// bind method-based text binds
var _loop2 = function _loop2(child) {
var match = child.innerText.match(/\[\[(\w+)\((.+)\)]\]/g);
if (match) {
match.forEach(function (expression) {
// group 1 -> method
// group 2 -> propertie(s), separated by comma, may have space
var matches = expression.match(Slim.rxMethod);
var methodName = matches[1];
var props = matches[3].split(' ').join('').split(',');
var descriptor = {
type: 'TM',
properties: props,
target: child,
expression: expression,
source: child._boundParent,
sourceText: child.innerText,
methodName: methodName
};
child.sourceText = child.innerText;
_this5.__bind(descriptor);
});
}
};
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = allChildren[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var child = _step4.value;
_loop2(child);
}
// bind property based text binds
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = allChildren[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var child = _step5.value;
var _match = child.innerText.match(/\[\[([\w|.]+)\]\]/g);
if (_match && child.children.firstChild) {
throw 'Bind Error: Illegal bind attribute use on element type ' + child.localName + ' with nested children.\n' + child.outerHTML;
}
if (_match) {
var properties = [];
for (var i = 0; i < _match.length; i++) {
var lookup = _match[i].match(/([^\[].+[^\]])/)[0];
properties.push(lookup);
}
var descriptor = {
type: 'T',
properties: properties,
target: child,
sourceText: child.innerText
};
child.sourceText = child.innerText;
this.__bind(descriptor);
}
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
}