-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxcss.js
1210 lines (1024 loc) · 42.9 KB
/
xcss.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
/*global console,fetch*/
(function xcss(_evaluate) {
"use strict";
var MAX_NESTING_LEVEL = 100;
var allCSSRules = {};
var visitedRules = {};
var evtBindings = {};
var classBindings = {};
var contentBindings = {};
var pullBindings = {};
var sizeBindings = {};
var timerBindings = {};
var modelBindings = {};
var stateListeners = [];
// var WHEN = 'when';
// var AND = 'and';
// var EXTENDS = 'extends';
// var APPLIES = 'applies';
var EVENTS = [];
// var LOGICAL = 'LOGICAL';
var prevState = {};
var KEYWORD_FUNCTIONS = {
EXTENDS: extendRule,
APPLIES: applyRule,
COMPONENT: componentRule,
WHEN: stateRule,
PULL: alignRule,
SIZE: sizeRule,
AND: LogicKeyword,
OR: LogicKeyword,
TIMER: timerRule,
MODEL: modelRule
};
//fetch all possible events
for (var evtKey in HTMLElement.prototype) {
if (evtKey.indexOf('on') === 0) {
EVENTS.push(evtKey.toUpperCase());
//console.log(evtKey);
}
}
//make keyword split expression
var keyWordsRegExp = Object.keys(KEYWORD_FUNCTIONS).concat(EVENTS).join('|');
var KEYWORDS = new RegExp('\\s+(' + keyWordsRegExp + '),?\\s+', 'i');
var EVENTEXPR = new RegExp('\\W+(' + EVENTS.join('|') + ')\\W*=\\W*[\'\"]', 'i');
var SCRIPTEXPR = /<script[>\W]/i;
var styleSheet = addNewStylesheet();
var components = {};
document.addEventListener('DOMContentLoaded', processCSSRulesAsync);
//document.addEventListener('onload', processCSSRules);
window.addEventListener('hashchange', stateChanged);
window.addEventListener('resize', pullBoundElements);
window.addEventListener('resize', sizeBoundElements);
return;
////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////
function stateChanged() {
var state = location.hash.replace(/^#\/?/, '').split('/').map(
function (state) {
var parts = state.split('?');//pseudo querystring
var parms = (parts[1] || '').split('&');
var path = parts[0];
var result = {};
result[path] = {};
parms.forEach(function (parm) {
var keyVal = parm.split('=');
var key = keyVal[0];
var val = decodeURIComponent(keyVal[1]);
result[path][key] = val;
});
return result;
}
);
//collect path
state.path = state.map(function (s) {
return Object.keys(s)[0];
}).join('/');
//collect all parameter key/values in the state object
state.params = {};
state.forEach(
function (s) {
var parms = s[Object.keys(s)[0]];
Object.keys(parms).forEach(
function (k) {
state.params[k] = parms[k];
}
);
}
);
console.log('state:', state);
//invoke all stateChangeListeners
stateListeners.forEach(
function (listener) {
listener(state);
}
);
//rebind all events after state change
window.setTimeout(
function () {
//bindAllEvents();
//bindAllClasses();
//bindAllContent();
pullBoundElements();
}, 100
);
prevState = state;
}
function bindAllContent(parent, level) {
if (level && level > MAX_NESTING_LEVEL) {
console.log('Max nesting level is: ' + MAX_NESTING_LEVEL);
return;
}
level++;
Object.keys(contentBindings).forEach(
function (selector) {
insertContent(contentBindings, selector, null, null, null, parent, level);
}
);
}
function bindAllEvents(parent) {
Object.keys(evtBindings).forEach(
function bind(target) {
//console.log('binding message events: ' + msg + ' to ' + targets);
var scope = parent || document;
var elms = scope.querySelectorAll(target);
for (var i = 0; i < elms.length; i++) {
//elms[i].addEventListener(event, makeEventListener(key));
var handler = evtBindings[target];
if (!elms[i].xcssHandler) {
console.log('binding message events: ' + handler.hash + ' to ' + target);
if (handler.hash === 'prevent') {
elms[i].xcssHandler = function (evt) {
evt.preventDefault();
evt.stopPropagation();
}
} else {
elms[i].xcssHandler = makeEventListener(handler.hash);
}
elms[i].addEventListener(handler.event, elms[i].xcssHandler);
}
}
}
);
}
function bindAllClasses(parent) {
Object.keys(classBindings).forEach(
function (target) {
var scope = parent || document;
var targetElms = scope.querySelectorAll(target) || [];
var sources = classBindings[target] || [];
[].slice.call(targetElms).forEach(
function (elm) {
sources.forEach(
function (className) {
console.log('applying ' + className + ' to ' + target);
elm.classList.add(className);
}
);
}
);
}
);
}
function bindAllModels(parent) {
function updateGUI(modelObj, modelExpr) {
var sameModels = document.querySelectorAll('[data-model="' + modelExpr + '"]');
if (modelObj instanceof Object) {
[].slice.call(sameModels).forEach(
function (peer) {
var name = peer.getAttribute('name') || '';
if (peer.constructor.prototype.hasOwnProperty('value')) {
peer.value = modelObj[name];
} else {
peer.innerHTML = modelObj[name];
}
}
);
}
}
Object.keys(modelBindings).forEach(
function (target) {
var scope = parent || document;
var targetElms = scope.querySelectorAll(target) || [];
var sources = modelBindings[target] || [];
var parts = (sources[0] || '').split('[');
var modelExpr = parts.shift().trim();
//var initExpr= parts.shift().split('=');
//var variable = initExpr[0];
//var expression = initExpr[1];
[].slice.call(targetElms).forEach(
function (elm) {
if (elm.getAttribute('data-model') !== modelExpr) {
var modelObj = _evaluate(modelExpr, elm);
elm.setAttribute('data-model', modelExpr);
updateGUI(modelObj, modelExpr);
elm.addEventListener('input', function () {
modelObj[elm.name || ''] = elm.value;
updateGUI(modelObj, modelExpr);
});
console.log('bound model ', modelExpr, ' to ', elm.name);
}
}
);
}
);
}
function processCSSRulesAsync() {
//wait 10 ms before collecting the stylesheet rules
//so they can be loaded by the browser
window.setTimeout(processCSSRules, 10);
}
/**
*
*/
function processCSSRules() {
//collect all style rules
console.time('processCSSRules');
collectRules(document).then(
function () {
compileRules(allCSSRules);
console.timeEnd('processCSSRules');
stateChanged();
}
);
}
/**
*
* @param cssRules
*/
function compileRules(cssRules) {
Object.keys(cssRules).forEach(
function (selector) {
var keyword = '', target = '', sources = [], invalidKeyword, ucKeyword, lcKeyword;
var strings = {};
var encodedSelector = selector.split('"').map(
function (w, i) {
if (i % 2 === 1) {
strings['$' + i] = w;
return '$' + i;
}
;
return w;
}
).join('"');
var parts = encodedSelector.split(KEYWORDS);
if (visitedRules[selector]) {
//console.log('skipping visited selector: ' + selector);
return;
}
visitedRules[selector] = cssRules[selector];
console.log('parts: [' + parts.join(' : '), '] selector:', selector);
//initially the rule is valid
invalidKeyword = '';
if (parts.length > 2) {
//read first three fields
target = parts.shift().trim().replace(/"\$(\d+)"/g, '"' + strings['$1'] + '"');
keyword = parts.shift().trim();
ucKeyword = keyword.toUpperCase();
lcKeyword = keyword.toLowerCase();
sources = parts.filter(
function (part) {
var keywordType = KEYWORD_FUNCTIONS[part.toUpperCase()];
invalidKeyword = (keywordType && LogicKeyword !== keywordType) ? keyword : invalidKeyword;
return !keywordType;
}
).map(
function (x) {
return x.replace(/"\$\d+"/g, function (key) {
return '"' + strings[key.replace(/"/g, '')] + '"'
});
}
);
if (invalidKeyword) {
console.error('cannot proces invalid xcss rule: "' + selector + '" unexpected keyword "' + invalidKeyword + '"');
return;
}
if (KEYWORD_FUNCTIONS[ucKeyword]) {
//apply the right function for a keyword
KEYWORD_FUNCTIONS[ucKeyword](cssRules, selector, target, sources, keyword);
}
else if (EVENTS.indexOf(ucKeyword) >= 0) {
eventRule(cssRules, selector, target, sources, lcKeyword);
extendRule(cssRules, selector, target, [selector], keyword);
}
} else if (cssRules[selector].style && cssRules[selector].style.content) {
insertContent(cssRules, selector, target, sources, keyword);
}
}
);
}
//insertContent for any css role having a content property without before/after pseudo selector
function insertContent(cssRules, selector, target, sources, keyword, parent, level) {
var url, matches;
var content = cssRules[selector].style.content || '';
var targetElms = document.querySelectorAll(target || selector);
if (parent) {
targetElms = parent.querySelectorAll(target || selector);
}
//only handle rules without :before/:after
if (!/:(before|after)/.test(selector)) {
if (!contentBindings[selector]) {
contentBindings[selector] = {style: {content: allCSSRules[selector].style.content}};
}
console.trace('inserting content for: ' + selector);
if (matches = content.match(/^"?url\(([^)]*)\)"?$/)) {
url = matches[1];
if (matches = url.match(/^"(.*)"$/)) {
url = url.slice(1, -1);
}
if (matches = content.match(/^"(.*)"$/)) {
content = content.slice(1, -1);
}
}
// important to remove content from style rule
allCSSRules[selector].style.content = '';
//for each element matching the rule insertContent
[].slice.call(targetElms).forEach(
function (elm) {
if (elm.insertedContent !== content) {
elm.insertedContent = content;
if (url) {
if (/^@/.test(url)) {
url = "'" + url + "'";
}
loadContent(_evaluate(url, elm), elm, level);
} else {
try {
var html = _evaluate(content.slice(1, -1), elm);
setHtmlContent(elm, html, level)
} catch (e) {
console.error('Could not evaluate expression: ' + content);
}
}
}
}
);
}
}
function pullElements(target, direction) {
var targetElms = document.querySelectorAll(target);
[].slice.call(targetElms).forEach(
function (elm) {
//console.log('pulling ' + target + ' to ' + direction);
elm.style.boxSizing = 'border-box';
var lm = parseInt(elm.style.marginLeft || '0');
var pullRight = elm.parentNode.offsetWidth + elm.parentNode.offsetLeft - (elm.offsetLeft + elm.offsetWidth);
//console.log('l ' + elm.offsetLeft);
//console.log('w ' + elm.offsetWidth);
//console.log('pw ' + elm.offsetParent.offsetWidth);
//console.log('lm ' + lm);
//console.log('pl ' + pullRight);
elm.style.marginLeft = (lm + pullRight) + 'px';
elm.style.marginRight = '0px';
elm.style.marginTop = '-70px';
}
);
}
function sizeElements(target, cssRules) {
console.log('sizeElements');
if (!cssRules) {
return
}
;
cssRules.forEach(
function (cssRule) {
var style = cssRule.style;
var cssText = style.cssText.split('; ').filter(
function (cssLine) {
return cssLine.trim().indexOf('content:') < 0;
}
).join(';\n');
var content = style.content;
var targetElms = document.querySelectorAll(target);
[].slice.call(targetElms).forEach(
function (elm) {
var pos = cssRule.selectorText.toUpperCase().indexOf(' SIZE ');
var condition = cssRule.selectorText.substring(pos + 6);
var result = false;
var matches = condition.match(/(widthFor|heightFor)\[([^=]*)="(.*)"\]/);
if (matches) {
var tekst = matches[3];
var div = document.createElement('div');
div.style.cssText = "position='absolute';width:auto;height:auto;white-space: nowrap;display:inline-block";
div.innerHTML = tekst;
elm.appendChild(div);
elm.width = elm.offsetWidth;
elm.height = elm.offsetHeight;
elm.widthFor = {};
elm.heightFor = {};
elm.widthFor[tekst] = div.offsetWidth;
elm.heightFor[tekst] = div.offsetHeight;
elm.removeChild(div);
}
try {
result = _evaluate(condition, elm);
} catch (e) {
console.error('invalid SIZE condition! ' + condition + ', error: ' + e);
}
if (!result) {
return;
}
console.log('SIZE condition: ' + condition);
elm.style.cssText = cssText.replace(/\$\{[^\}]*\}/g, function (v) {
var expr = v.substring(2, v.length - 1);
return _evaluate(expr, elm);
});
if (content) {
var html = '' + _evaluate(content.slice(1, -1), elm);
setHtmlContent(elm, html);
}
}
);
});
}
function alignRule(cssRules, selector, target, sources, keyword) {
pullBindings[target] = sources;
pullElements(target, sources[0]);
pullBoundElements();
}
function pullBoundElements() {
Object.keys(pullBindings).forEach(
function (target) {
window.setTimeout(
function () {
pullElements(target, pullBindings[target]);
}, 100
);
}
)
}
function sizeRule(cssRules, selector, target, sources, keyword) {
if (!sizeBindings[target]) {
sizeBindings[target] = [];
}
sizeBindings[target].push(cssRules[selector]);
sizeBoundElements();
}
function sizeBoundElements() {
Object.keys(sizeBindings).forEach(
function (target) {
window.setTimeout(
function () {
sizeElements(target, sizeBindings[target]);
}, 100
);
}
)
}
function timerRule(cssRules, selector, target, sources, keyword) {
if (!sizeBindings[target]) {
sizeBindings[target] = [];
}
timerBindings[target].push(cssRules[selector]);
timeoutBoundElements(sources);
}
function timeoutBoundElements() {
Object.keys(timerBindings).forEach(
function (target) {
window.setTimeout(
function () {
styleElements(target, sizeBindings[target]);
}, parsetInt(sources[0])
);
}
)
}
function styleElements(target, cssRule) {
console.log('timer event for : ' + target);
}
function componentRule(cssRules, selector, target, sources, keyword) {
//make multiple registrations possible
var key;
var proto = Object.create(HTMLElement.prototype);
var comp = {};
var tplExpr = /\[template(Id|Url)="([\w-\/\.]*)"\]/i;
var template = sources[0].match(tplExpr);
//extract url of id
if (template) {
comp.template = {};
template.shift();
key = template.shift().toLowerCase();
comp.template[key] = template.shift();
} else {
comp.content = cssRules[selector].style.content.replace(/^"/, '').replace(/"$/, '');
}
components[target.toUpperCase()] = comp;
//default templateid = name of tag
proto.createdCallback = function () {
// Adding a Shadow DOM
var root = this.createShadowRoot();
var comp = components[this.tagName];
// Adding a template
if (comp.template) {
if (comp.template.id) {
var tpl = document.querySelector('#' + comp.template.id);
var clone = document.importNode(tpl.content, true);
root.appendChild(clone);
} else if (comp.template.url) {
fetch(comp.template.url).then(
function (response) {
return response.text();
}
).then(
function (html) {
root.innerHTML = html;
}
)
}
} else {
root.innerHTML = comp.content;
}
}
if (document.registerElement) {
document.registerElement(target, {
prototype: proto
});
}
var self = cssRules[selector];
styleSheet.insertRule(target + '{' + self.style.cssText + '}', styleSheet.cssRules.length);
}
/**
*/
function extendRule(cssRules, selector, target, sources, keyword) {
var newCssText = sources.map(
function (fromSelector) {
//resolve fromSelector when not found in currenttly resolved rules
if (!cssRules[fromSelector]) {
console.log('resolving rule fromSelector: ' + fromSelector);
compileRules(cssRules);
}
if (!cssRules[fromSelector]) {
console.error('Could not resolve rule fromSelector: ' + fromSelector);
} else {
console.debug('Resolved rule fromSelector: ' + fromSelector + ' = ' + cssRules[fromSelector].style.cssText);
}
return (cssRules[fromSelector]) ? cssRules[fromSelector].style.cssText : '';
}
).join(' ');
var self = cssRules[selector];
console.log('adding rule: ' + target + '{' + newCssText + self.style.cssText + '}');
var idx = styleSheet.insertRule(target + '{' + newCssText + self.style.cssText + '}', styleSheet.cssRules.length);
cssRules[target] = styleSheet.cssRules[idx];
//load content is defined
if (cssRules[target].style.content) {
var level = 0;
insertContent(cssRules, target, target, sources, keyword, document, level)
}
}
/**
* adds found classes after keyword APPLIES to the elements for the selector
* @param cssRules
* @param selector
* @param target
* @param sources
* @param keyword
*/
function applyRule(cssRules, selector, target, sources, keyword) {
var targetElms = document.querySelectorAll(target);
classBindings[target] = sources;
[].slice.call(targetElms).forEach(
function (elm) {
sources.forEach(
function (src) {
var m;
if (m = src.match(/^\[(.*)\]$/)) {
var attr = m[1].split('=');
console.log('applying attr: ' + m[1] + ' to ' + target);
elm.setAttribute(attr[0], attr[1] || attr[0]);
} else {
console.log('applying class: ' + src + ' to ' + target);
elm.classList.add(src);
}
}
);
}
);
}
/**
*
* @param cssRules
* @param selector
* @param target
* @param sources
* @param keyword
*/
function stateRule(cssRules, selector, target, sources, keyword) {
console.log('binding message WHEN listener: ' + sources + ' to ' + selector);
console.log('binding message listener: ' + sources);
stateListeners.push(makeStateChangeListener(target, sources, selector, cssRules));
}
/**
*
* @param cssRules
* @param selector
* @param target
* @param sources
* @param keyword
*/
function eventRule(cssRules, selector, target, sources, keyword) {
var newHash = sources[0] || keyword;
console.log('binding message events: ' + newHash + ' to ' + target + ' for ' + keyword);
evtBindings[target] = {hash: newHash, event: keyword.substring(2)};
var targetElms = document.querySelectorAll(target);
[].slice.call(targetElms).forEach(
function (elm) {
//console.log('adding eventlistener for ' + newHash);
if (newHash === 'prevent') {
elm.xcssHandler = function (evt) {
evt.preventDefault();
evt.stopPropagation();
}
} else {
elm.xcssHandler = makeEventListener(newHash);
}
elm.addEventListener(keyword.substring(2), elm.xcssHandler);
}
);
}
/**
* logicRule is a marker function
*/
function LogicKeyword() {
}
function loadContent(url, elm, level) {
// resolve url from any attribute recursively
// example content:url(@attrUrl) , <elm attrUrl="http:// etc"> => url = http://etc
while (url.indexOf('@') === 0) {
url = elm.getAttribute(url.substring(1));
}
url = encodeURI(url);
fetch(url).then(
function (response) {
response.text().then(function (data) {
if (url.indexOf('://') > 0 && SCRIPTEXPR.test(data) || EVENTEXPR.test(data)) {
console.error('unsafe content ignored!');
} else {
setHtmlContent(elm, data, level);
}
});
}
);
}
/**
* handle async or sync result
* @param elm
* @param html
*/
function setHtmlContent(elm, html, level) {
if (typeof html == "string") {
insertHTML(html, level);
} else if (html && html.then) {
html.then(
function (data) {
insertHTML(data, level);
}
)
}
function insertHTML(html, level) {
var tagName = elm.tagName.toLowerCase();
if (elm.constructor.prototype.hasOwnProperty('value') && tagName !== 'select') {
if (!Array.isArray(elm.orgValue)) {
elm.orgValue = [elm.value];
}
elm.value = html;
} else {
if (!Array.isArray(elm.orgValue)) {
elm.orgValue = [elm.innerHTML];
}
//only update if needed so we keep element events working
//no need to bind events again if the content is not changed
if (html !== elm.dataHtml) {
elm.dataHtml = html;
if (elm.innerHTML.indexOf('<!--slot-->') >= 0) {
html = elm.innerHTML.replace('<!--slot-->', html);
}
elm.innerHTML = html;
//if we have a change in the html rebind all events if needed
//so events bind seems to work as styles whenever an element
//matches the css rule the event is present
bindAllContent(elm, level || 0);
bindAllEvents(elm);
bindAllClasses(elm);
bindAllModels(elm);
}
}
}
}
function makeStateChangeListener(targetKey, sources, selector, cssRules) {
console.log('makeStateChangeListener for: ' + targetKey + ', sources: ' + sources);
var targetStates = sources.map(
function (source) {
var parts = source.split(/[\[\]]/);
var path = parts.shift().trim();
var pattern = path.replace(/\s*\*\s*/g, '.*').replace(/>/g, '\/');
return {
path: path,
pattern: new RegExp('^' + pattern + '$'),
params: parts.filter(function (p) {
return !!p.trim();
}) //filter out empty parms
};
}
);
//var stateKey = msgParts[0];
//var parms = msgParts[1];
var cssText = '';
var target = targetKey + '';
return stateChangeListener;
////////////////////////////////////////////////////////
function stateChangeListener(newState) {
var matches, parms;
var url;
var cssKey;
var value;
var placeholder;
var replacer;
var VAR_EXPR = /var\(--([^\)]*)\)/;
console.log('event received: ' + targetKey, 'evt:', newState);
var path = newState.path;
var state = newState.params;
//replace parameter placeholders in target selector with state parameter values
var elmQuery = target;
Object.keys(state).forEach(
function (key) {
elmQuery = elmQuery.replace('${' + key + '}', state[key]);
}
);
var content = cssRules[selector].style.content;
var match = targetStates.filter(function (s) {
return s.pattern.test(path);
})[0];
console.log(prevState);
var prevMatch = targetStates.filter(function (s) {
return s.pattern.test(prevState.path || '');
})[0];
console.log(prevMatch);
var elms = document.querySelectorAll(elmQuery);
for (var i = 0; i < elms.length; i++) {
var elm = elms[i];
console.log('event handled by ', elmQuery + '[' + i + ']');
if (elm.cssText === undefined) {
elm.cssText = elm.style.cssText || '';
}
if (match) {
parms = match.params;
//calculate templated values and expressions and store them in the state
parms.forEach(
function (parm) {
var parts = parm.split('=');
//simple case : /path[propertyname] just replace content with value
if (parts.length === 1 && content) {
placeholder = new RegExp('\\$\\{' + parm + '\\}', 'g');
replacer = (state || {})[parm] || '';
content = content.replace(placeholder, replacer);
return;
}
cssKey = parts.shift();
//reconstruct right side of the = sign
value = parts.join('=').replace(/^"/, '').replace(/"$/, ''); //Edge escape quotes in attributes
value = value.replace(/^\\'/, "'").replace(/\\'$/, "'"); //firefox escape quotes in attributes
if (value) {
//replace template variables
value = value.replace(/\$\{[^\}]*\}/g, function (v) {
return state[v.substring(2, v.length - 1)];
});
value = value.replace(/\\'/g, "'"); //firefox escape quotes in attributes
try {
state[cssKey] = _evaluate(value, elm) || '';
//support direct js manipulation of css variables
if (/^--/.test(cssKey)) {
elm.style.setProperty(cssKey, state[cssKey]);
}
} catch (e) {
console.error('could not evaluate', value);
}
}
}
);
//filter content property out before adding the cssText
//because an inline style does not behave well having a content property
cssText = cssRules[selector].style.cssText.split('; ').filter(
function (cssLine) {
return cssLine.trim().indexOf('content:') < 0;
}
).join(';\n');
elm.style.cssText = cssText.replace(/\$\{[^\}]*\}/g, function (v) {
return state[v.substring(2, v.length - 1)];
});
//replace var(--xx) with state param
[].slice.call(cssRules[selector].style, 0).forEach(
function (p) {
var styleExpr = cssRules[selector].style[p];
var matches = styleExpr.match(VAR_EXPR);
if (matches && matches[1]) {
var variables = matches[1].split(',');
var match1 = variables.shift();
var state1 = state[match1] || variables[0];
if (state1) {
var jsKey = p.replace(/(-\w)/, function (v) {
return v.substring(1).toUpperCase();
});
if (typeof state1.then === 'function') {
state1.then(function (r) {
setStyle(jsKey, r || variables[0]);
});
} else {
setStyle(jsKey, state1);
}
}
}
function setStyle(jsKey, value) {
var value = styleExpr.replace(VAR_EXPR, value);
elm.style[jsKey] = value;
}
}
);
if (content) {
console.log(prevMatch);
//chrome parses the content with " around the url
if (matches = content.match(/^url\("([^)]*)"\)$/)) {
url = evaluate(matches[1], state, elm);
loadContent(url, elm);
//Edge does not add " signs around the urk
} else if (matches = content.match(/^url\(([^)]*)\)$/)) {
url = evaluate(matches[1], state, elm);
loadContent(url, elm);
} else if (matches = content.match(/^"([^"]*)"$/)) {
var html = evaluate(matches[1], state, elm);
setHtmlContent(elm, html);
}
}
} else {
elms[i].style.cssText = elms[i].cssText;
if (content && Array.isArray(elm.orgValue)) {
var p = (['input', 'textarea'].indexOf(elm.tagName) < 0 ) ? 'innerHTML' : 'value';
elm[p] = elm.orgValue[0];
elm.dataHtml = elm.orgValue[0];
}
}
}
}
}
function evaluate(text, env, elm) {
var result = text.replace(/\$\{[^\}]*\}/g, function (v) {
return env[v.substring(2, v.length - 1)];
});
try {
return _evaluate(result, elm);
} catch (e) {
console.error(e);