-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathcssregions.js
1657 lines (1398 loc) · 59.3 KB
/
cssregions.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
/*!
Copyright 2012 Adobe Systems Inc.;
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Various shims for missing functionality in older browsers
!function() {
if (typeof String.prototype.trim !== "function") {
String.prototype.trim = function(string) {
return string.replace(/^\s+/,"").replace(/\s+$/,"");
}
}
if (typeof Array.prototype.forEach !== 'function') {
Array.prototype.forEach = function(iterator, thisArg) {
if (typeof iterator !== 'function') {
throw new TypeError("Invalid parameter. Expected 'function', got " + typeof iterator)
}
var self = Object(this),
len = self.length,
i = 0;
for (i; i < len; i++) {
// call the iterator function within the requested context with the current value, index and source array
iterator.call(thisArg, this[i], i, self)
}
}
}
if (typeof Array.prototype.indexOf !== 'function') {
Array.prototype.indexOf = function(value) {
var self = Object(this),
matchedIndex = -1;
self.forEach(function(item, index) {
if (item === value) {
matchedIndex = index
return
}
})
return matchedIndex
}
}
}()
/*!
Copyright 2012 Adobe Systems Inc.;
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
!(function(scope){
function getStyleSheetElements() {
var doc = document,
stylesheets = [];
if (typeof doc.querySelectorAll == 'function') {
// shiny new browsers
stylesheets = doc.querySelectorAll('link[rel="stylesheet"], style');
// make it an array
stylesheets = Array.prototype.slice.call(stylesheets, 0);
} else {
// old and busted browsers
// <link rel="stylesheet">
var tags = doc.getElementsByTagName("link");
if (tags.length) {
for (var i = 0, len = tags.length; i < len; i++) {
if (tags[i].getAttribute('rel') === "stylesheet") {
stylesheets.push(tags[i]);
}
}
}
// <style>
tags = doc.getElementsByTagName("style");
for (var i=0, len = tags.length; i < len; i++) {
stylesheets.push(tags[i]);
}
}
return stylesheets;
}
function StyleSheet(source){
this.source = source;
this.url = source.href || null;
this.cssText = '';
}
StyleSheet.prototype.load = function(onSuccess, onError, scope) {
var self = this;
// Loading external stylesheet
if (this.url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if (xhr.status === 200) {
self.cssText = xhr.responseText;
onSuccess.call(scope, self);
} else{
onError.call(scope, self);
}
}
}
// forced sync to keep Regions CSSOM working sync
xhr.open('GET', this.url, false);
xhr.send(null);
} else {
this.cssText = this.source.textContent;
onSuccess.call(scope, self);
}
};
function StyleLoader(callback) {
if (!(this instanceof StyleLoader)) {
return new StyleLoader(callback);
}
this.stylesheets = [];
this.queueCount = 0;
this.callback = callback || function(){};
this.init();
}
StyleLoader.prototype.init = function() {
var els = getStyleSheetElements(),
len = els.length,
stylesheet,
i;
this.queueCount = len;
for ( i = 0; i < len; i++) {
stylesheet = new StyleSheet(els[i]);
this.stylesheets.push(stylesheet);
stylesheet.load(this.onStyleSheetLoad, this.onStyleSheetError, this);
}
}
StyleLoader.prototype.onStyleSheetLoad = function(stylesheet) {
this.queueCount--;
this.onComplete.call(this);
}
StyleLoader.prototype.onStyleSheetError = function(stylesheet) {
var len = this.stylesheets.length,
i;
for ( i = 0; i < len; i++) {
if (stylesheet.source === this.stylesheets[i].source) {
// remove the faulty stylesheet
this.stylesheets.splice(i, 1);
this.queueCount--;
this.onComplete.call(this);
return;
}
}
}
StyleLoader.prototype.onComplete = function() {
if (this.queueCount === 0) {
// run the callback after all stylesheet contents have loaded
this.callback.call(this, this.stylesheets);
}
}
scope["StyleLoader"] = StyleLoader;
})(window);
/*!
Copyright 2012 Adobe Systems Inc.;
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Real developers learn from source. Welcome!
Light JavaScript CSS Parser
Author: Razvan Caliman ([email protected], twitter: @razvancaliman)
This is a lightweight, naive and blind CSS Parser. It's meant to be used as a
building-block for experiments with unsupported CSS rules and properties.
This experimental parser is not intended to fully comply with any CSS Standard.
Use it responsibly and have fun! ;)
*/
!function(scope) {
function CSSRule() {
this.selectorText = null;
this.style = {};
this.type = "rule";
}
CSSRule.prototype = {
setSelector: function(string) {
this.selectorText = string;
// detect @-rules in the following format: @rule-name identifier{ }
var ruleType = string.match(/^@([^\s]+)\s*([^{]+)?/);
if (ruleType && ruleType[1]) {
switch (ruleType[1]){
case "template":
this.type = "template";
this.cssRules = [];
break
case "slot":
this.type = "slot";
break
default:
this.type = "unknown";
}
// set the identifier of the rule
this.identifier = ruleType[2] || "auto";
}
},
setStyle: function(properties) {
if (!properties){
throw new TypeError("CSSRule.setStyles(). Invalid input. Expected 'object', got " + properties);
}
this.style = properties || {};
return this.style;
},
setParentRule: function(rule) {
if (!rule){
throw new TypeError("CSSRule.setParentRule(). Invalid input. Expected 'object', got " + properties);
}
this.parentRule = rule;
return this.parentRule;
}
}
/*
Naive and blind CSS syntax parser.
The constructor returns a CSSParser object with the following members:
.parse(string) - method to parse a CSS String into an array of CSSRule objects
.clear() - method to remove any previously parsed data
.cssRules - array with CSSRule objects extracted from the parser input string
*/
function CSSParser() {
/*
Extracts the selector-like part of a string.
Matches anything after the last semicolon ";". If no semicolon is found, the input string is returned.
This is an optimistic matching. No selector validation is perfomed.
@param {String} string The string where to match a selector
@return {String} The selelector-like string
*/
function getSelector(string) {
var sets = string.trim().split(";");
if (sets.length) {
return sets.pop().trim();
}
return null;
}
/*
Parse a string and return an object with CSS-looking property sets.
Matches all key/value pairs separated by ":",
themselves separated between eachother by semicolons ";"
This is an optimistic matching. No key/valye validation is perfomed other than 'undefined'.
@param {String} string The CSS string where to match property pairs
@return {Obect} The object with key/value pairs that look like CSS properties
*/
function parseCSSProperties(string) {
var properties = {},
sets = string.trim().split(";");
if (!sets || !sets.length) {
return properties;
}
sets.forEach(function(set) {
// invalid key/valye pair
if (set.indexOf(":") == -1){
return;
}
var key,
value,
parts = set.split(":");
if (parts[0] !== undefined && parts[1] !== undefined) {
key = parts[0].trim();
value = parts[1].trim().replace(/[\"\']/g, "");
properties[key] = value;
}
})
return properties;
}
/*
Parse a string and create CSSRule objects from constructs looking like CSS rules with valid grammar.
CSSRule objects are added to the 'cssRules' Array of the CSSParser object.
This is an optimistic matching. Minor syntax validation is used.
Supports nested rules.
Example:
@template{
@slot{
}
}
*/
function parseBlocks(string, set, parent) {
var start = string.indexOf("{"),
properties,
rule = new CSSRule,
token = string.substring(0, start),
selector = getSelector(token),
remainder = string.substr(start + 1, string.length),
end = remainder.indexOf("}"),
nextStart = remainder.indexOf("{");
if (start > 0) {
rule.setSelector(selector);
if (parent) {
rule.setParentRule(parent);
/*
If it's a nested structure (a parent exists) properties might be mixed in with nested rules.
Make sure the parent gets both its styles and nested rules
Example:
@template{
background: green;
@slot{
}
}
*/
properties = parseCSSProperties(token);
parent.setStyle(properties);
}
// nested blocks! the next "{" occurs before the next "}"
if (nextStart > -1 && nextStart < end) {
// find where the block ends
end = getBalancingBracketIndex(remainder, 1);
// extract the nested block cssText
var block = remainder.substring(0, end);
properties = parseCSSProperties(token);
rule.setStyle(properties);
rule.cssRules = rule.cssRules || [];
// parse the rules of this block, and assign them to this block's rule object
parseBlocks(block, rule.cssRules, rule);
// get unparsed remainder of the CSS string, without the block
remainder = remainder.substring(end + 1, remainder.length);
} else {
properties = parseCSSProperties(remainder.substring(0, end));
rule.setStyle(properties);
// get the unparsed remainder of the CSS string
remainder = remainder.substring(end + 1, string.length);
}
// continue parsing the remainder of the CSS string
parseBlocks(remainder, set);
// prepend this CSSRule to the cssRules array
set.unshift(rule);
}
function getBalancingBracketIndex(string, depth) {
var index = 0;
while(depth){
switch (string.charAt(index)){
case "{":
depth++;
break;
case "}":
depth--;
break;
}
index++;
}
return (index - 1);
}
}
function cascadeRules(rules) {
if (!rules) {
throw new Error("CSSParser.cascadeRules(). No css rules available for cascade");
}
if (!rules.length) {
return rules;
}
var cascaded = [],
temp = {},
selectors = [];
rules.forEach(function(rule) {
if (rule.cssRules){
rule.cssRules = cascadeRules(rule.cssRules);
}
// isDuplicate
if (!temp[rule.selectorText]) {
// store this selector in the order that was matched
// we'll use this to sort rules after the cascade
selectors.push(rule.selectorText);
// create the reference for cascading into
temp[rule.selectorText] = rule;
} else {
// cascade rules into the matching selector
temp[rule.selectorText] = extend({}, temp[rule.selectorText], rule);
}
});
// expose cascaded rules in the order the parser got them
selectors.forEach(function(selectorText) {
cascaded.push(temp[selectorText]);
}, this);
// cleanup
temp = null;
selectors = null;
return cascaded;
}
function extend(target) {
var sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function(source) {
for (var key in source) {
// prevent an infinite loop trying to merge parent rules
// TODO: grow a brain and do this more elegantly
if (key === "parentRule") {
return;
}
// is the property pointing to an object that's not falsy?
if (typeof target[key] === 'object' && target[key]) {
// dealing with an array?
if (typeof target[key].slice === "function") {
target[key] = cascadeRules(target[key].concat(source[key]));
} else {
// dealing with an object
target[key] = extend({}, target[key], source[key]);
}
} else {
target[key] = source[key];
}
}
});
return target;
}
return {
cssRules: [],
parse: function(string) {
// inline css text and remove comments
string = string.replace(/[\n\t]+/g, "").replace(/\/\*[\s\S]*?\*\//g,'').trim();
parseBlocks.call(this, string, this.cssRules);
},
/*
Parse a single css block declaration and return a CSSRule.
@return {CSSRule} if valid css declaration
@return {null} if invalid css declaration
*/
parseCSSDeclaration: function(string) {
var set = [];
parseBlocks.call(this, string, set);
if (set.length && set.length === 1) {
return set.pop();
} else {
return null;
}
},
clear: function() {
this.cssRules = [];
},
cascade: function(rules) {
if (!rules || !rules.length) {
// TODO: externalize this rule
this.cssRules = cascadeRules.call(this, this.cssRules);
return;
}
return cascadeRules.call(this, rules);
},
doExtend: extend
}
}
scope = scope || window;
scope["CSSParser"] = CSSParser;
}(window);
/*!
Copyright 2012 Adobe Systems Inc.;
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
CSS Regions support
Author: Mihai Corlan ([email protected], @mcorlan)
*/
/**
* This is the object responsible for parsing the regions extracted by CSSParser.
* Retrieves the DOM elements that formed the named flows and regions chains.
* Flows the content into the region chain.
* Listens for changes: region chains size or visibility changes and re-flows
* the content.
*
*/
window.CSSRegions = function(scope) {
function Polyfill() {
this.setup();
}
Polyfill.prototype = {
// flag if CSS Regions is natively supported in the browser
hasNativeSupport: false,
// parse only adobe prefix for now
prefixes: {
css: '-adobe-',
om: 'adobe'
},
getPrefixedProperty: function(property){
return this.prefixes.css.concat(property)
},
getPrefixedOMProperty: function(property){
return this.prefixes.om.concat((property.charAt(0).toUpperCase() + property.slice(1)))
},
getPrefixedEvent: function(eventName){
return this.prefixes.om.concat(eventName)
},
init: function() {
var self = this
if (!window.StyleLoader){
console.error("Missing StyleLoader.js")
return
}
/* Load all stylesheets then feed them to the parser */
new StyleLoader(function(){
return function(stylesheets){
self.onStylesLoaded(stylesheets)
}
}())
},
setup: function(){
// Array of NamedFlow objects.
this.namedFlows = [];
// instance of Collection
this.namedFlowCollection = null;
},
onStylesLoaded: function(stylesheets){
if (!window.CSSParser){
console.error("Missing CSSParser.js")
return
}
var rules, flowName, contentNodesSelectors, regionsSelectors,
parser = new CSSParser();
// setup or reset everything
this.setup();
stylesheets.forEach(function(sheet){
// Parse the stylesheet for rules
parser.parse(sheet.cssText);
})
if (parser.cssRules.length === 0) {
console.log("There is no inline CSS for CSS Regions!");
return;
}
// Parse the rules and look for "flow-into" and "flow-from" rules;
rules = this.getNamedFlowRules(parser.cssRules);
for (flowName in rules) {
contentNodesSelectors = rules[flowName].contentNodesSelectors;
regionsSelectors = rules[flowName].regionsSelectors;
// The NamedFlow will collect and sort the DOM nodes based on selectors provided
this.namedFlows.push(new NamedFlow(flowName, contentNodesSelectors, regionsSelectors));
}
this.namedFlowCollection = new Collection(this.namedFlows, 'name');
// Expose methods to window/document as defined by the CSS Regions spec
this.exposeGlobalOM();
// If there are CSS regions move the content from named flows into region chains
this.doLayout();
},
getNamedFlowRules: function(cssRules) {
var rule, property, value,
l = cssRules.length,
rules = {},
flowProperty = this.getPrefixedProperty('flow'),
flowIntoProperty = this.getPrefixedProperty('flow-into'),
flowFromProperty = this.getPrefixedProperty('flow-from');
for (var i = 0; i < l; i++) {
rule = cssRules[i];
for (property in rule.style) {
if (property.indexOf(flowProperty) !== -1) {
value = rule.style[property];
rules[value] = rules[value] || {contentNodesSelectors: [], regionsSelectors: []};
// collect content nodes
if (property.indexOf(flowIntoProperty) !== -1) {
rules[value].contentNodesSelectors.push(rule.selectorText);
}
// collect regions
if (property.indexOf(flowFromProperty) !== -1) {
rules[value].regionsSelectors.push(rule.selectorText);
}
break;
}
}
}
return rules;
},
doLayout: function() {
if (!this.namedFlows || !this.namedFlows.length) {
console.warn("No named flow / regions CSS rules");
return;
}
executionQueue++;
if (executionQueue > 1) {
return;
}
while (executionQueue > 0) {
flowContentIntoRegions();
executionQueue--;
}
},
// Polyfill necesary objects/methods on the document/window as specified by the CSS Regions spec
exposeGlobalOM: function() {
// keeping non-prefixed value on document because part of the polyfill logic access it directly from the document
// TODO: rewrite rogue layout methods to sit inside the polyfill scope and avoid global queries to the document.
var namedFlowsAccessor = 'getNamedFlows',
prefixedNamedFlowsAccessor = this.getPrefixedOMProperty(namedFlowsAccessor);
document[namedFlowsAccessor] = document[prefixedNamedFlowsAccessor] = this.getNamedFlows.bind(this);
},
/*
Returns a map of NamedFlow objects where their 'name' attribute are the map keys.
Also accessible from window.getNamedFlows()
*/
getNamedFlows: function() {
return this.namedFlowCollection;
},
addSourceToNamedFlow: function(flowName, el) {
var namedFlow = this.getNamedFlows().namedItem(flowName);
if (!namedFlow) {
namedFlow = new NamedFlow(flowName);
this.namedFlows.push(namedFlow);
this.namedFlowCollection = new Collection(this.namedFlows, 'name');
}
namedFlow.contentNodes.push(el);
regionsValidFlag[namedFlow.name] = false;
},
addRegionToNamedFlow: function(flowName, el) {
var namedFlow = this.getNamedFlows().namedItem(flowName);
if (!namedFlow) {
namedFlow = new NamedFlow(flowName);
this.namedFlows.push(namedFlow);
this.namedFlowCollection = new Collection(this.namedFlows, 'name');
}
namedFlow.regions.push(el);
regionsValidFlag[namedFlow.name] = false;
},
"NamedFlow": NamedFlow,
"Collection": Collection
};
var executionQueue = 0;
var regionsValidFlag = {};
/**
* Returns the nodes ordered by their DOM order
* @param arrSelectors
* @return {Array}
*/
var orderNodes = function(arrSelectors) {
var i, j, m, nodeList,
tmp = [],
l = arrSelectors.length;
for (i = 0; i<l; i++) {
nodeList = document.querySelectorAll(arrSelectors[i]);
for (j = 0, m = nodeList.length; j < m; ++j) {
tmp.push(nodeList[j]);
}
}
return getFilteredDOMElements(
document.body,
NodeFilter.SHOW_ELEMENT,
{ acceptNode: function(node) {
if (tmp.indexOf(node) >= 0) {
return NodeFilter.FILTER_ACCEPT;
} else {
return NodeFilter.FILTER_SKIP;
}
}
});
};
/**
* Returns an array of elements that will be used as the source
* @param namedFlows
* @return {Array}
*/
var getNodesForFlow = function(sourceElements) {
var i, l, el,
sourceNodes = [];
for (i = 0, l = sourceElements.length; i < l; i++) {
el = sourceElements[i].cloneNode(true);
sourceNodes.push(el);
if (el.style.display === "none") {
el.style.display = el["data-display"] || "";
}
if (getComputedStyle(sourceElements[i]).display !== "none") {
sourceElements[i]["data-display"] = sourceElements[i].style.display;
sourceElements[i].style.display = "none";
}
}
return sourceNodes;
};
/**
* Returns an array of elements that forms the regions. If an element is hidden (display:none) it is excluded.
* @param regions
* @return {Array}
*/
var getRegionsForFlow = function(regions, namedFlow) {
var i, l, el,
destinationNodes = [];
for (i = 0, l = regions.length; i < l; i++) {
el = regions[i];
if (getComputedStyle(el).display !== "none") {
destinationNodes.push(el);
el["data-display"] = true;
if (namedFlow.lastRegionWithContentIndex < i
&& ( el["data-w"] !== getComputedStyle(el).width
|| el["data-h"] !== getComputedStyle(el).height) ) {
invalidateRegions([namedFlow.name]);
}
} else if (el["data-display"]) {
invalidateRegions([namedFlow.name]);
delete(el["data-display"]);
}
}
return destinationNodes;
};
/**
* This is where the regions parsed by the CSS parser are actually put to used.
* For each region rule we flow the content.
* @param regions
*/
var flowContentIntoRegions = function() {
var currentRegion, currentFlow, j, m, i, l, destinationNodes, el, tmp, nextSibling,
sourceNodes = [],
flows = document.getNamedFlows();
var regionOversetProperty = polyfill.getPrefixedOMProperty('regionOverset')
for (j = 0, m = flows.length; j < m; j++) {
currentFlow = flows[j];
currentFlow.regionsByContent = {content: [], regions: []};
currentFlow.firstEmptyRegionIndex = -1;
// Remove regions with display:none;
destinationNodes = getRegionsForFlow(currentFlow.getRegions(), currentFlow);
currentFlow.overset = false;
if (regionsValidFlag[currentFlow.name]) { // Can we skip some of the layout?
tmp = destinationNodes[currentFlow.lastRegionWithContentIndex].childNodes;
for (i = 0, l = tmp.length; i < l; ++i) {
sourceNodes.push(tmp[i]);
}
i = currentFlow.lastRegionWithContentIndex;
} else { // Build the source to be flown from the region names
sourceNodes = getNodesForFlow(currentFlow.contentNodes);
i = 0;
}
// Flow the source into regions
for (l = destinationNodes.length; i < l; i++) {
currentRegion = destinationNodes[i];
currentRegion.innerHTML = "";
// We still have to clear the possible content for the remaining regions
// even when we don't have anymore content to flow.
if (sourceNodes.length === 0) {
if (currentFlow.firstEmptyRegionIndex === -1) {
currentFlow.firstEmptyRegionIndex = i;
}
currentRegion[regionOversetProperty] = "empty";
continue;
}
el = sourceNodes.shift();
// The last region gets all the remaining content
if ((i + 1) === l) {
nextSibling = currentRegion.nextSibling || null;
tmp = currentRegion.parentNode;
tmp.removeChild(currentRegion);
while (el) {
currentRegion.appendChild(el.cloneNode(true));
addRegionsByContent(el, -1, currentRegion, currentFlow);
el = sourceNodes.shift();
}
if (nextSibling) {
tmp.insertBefore(currentRegion, nextSibling);
nextSibling = null;
} else {
tmp.appendChild(currentRegion);
}
tmp = null;
currentFlow.lastRegionWithContentIndex = i;
// Check if overflows
if (checkForOverflow(currentRegion)) {
currentRegion[regionOversetProperty] = "overset";
currentFlow.overset = true;
}
} else {
while (el) {
el = addContentToRegion(el, currentRegion, currentFlow);
currentRegion["data-w"] = getComputedStyle(currentRegion).width;
currentRegion["data-h"] = getComputedStyle(currentRegion).height;
if (el) {
// If current region is filled, time to move to the next one
sourceNodes.unshift(el);
break;
} else {
el = sourceNodes.shift();
}
}
currentRegion[regionOversetProperty] = "fit";
}
regionsValidFlag[currentFlow.name] = true;
}
// Dispatch regionLayoutUpdate event
if (currentFlow.regions.length > 0) {
// TODO: DO NOT access the polyfill like this. This whole method needs to go in the polyfill scope
var eventName = polyfill.getPrefixedEvent('regionlayoutupdate')
currentFlow.fire({type: eventName, target: currentFlow});
}
}
};
/**
* Adds the elemContent into region. If the content to be consumed overflows the region
* returns the overflow part as a DOM element. If not returns null.
* @param elemContent
* @param region
* @return null or a DOM element
*/
var addContentToRegion = function(elemContent, region, namedFlow) {
var currentNode, l, arrString, txt,
indexOverflowPoint = -1,
ret = null,
nodes = [],
removedContent = [],
el = elemContent;
region.appendChild(el);
// Oops it overflows. Can we split the content or is it a lost battle?
if ( checkForOverflow(region) ) {
region.removeChild(el);
// Find all the textNodes, IMG, and FIG
nodes = getFilteredDOMElements(el,
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,