forked from MicrosoftEdge/css-usage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cssUsage.src.js
2342 lines (1906 loc) · 89.5 KB
/
cssUsage.src.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
void function() {
var _ = (a => new ArrayWrapper(a));
_.mapInline = mapInline;
_.map = map; /*.......*/ map.bind = (()=>map);
_.filter = filter; /*.*/ filter.bind = (()=>filter);
_.reduce = reduce; /*.*/ reduce.bind = (()=>reduce);
window.CSSUsageLodash = _;
// test case:
// 35 = CSSUsageLodash([1,2,3,4,5]).map(v => v*v).filter(v => v%2).reduce(0, (a,b)=>(a+b)).value()
function ArrayWrapper(array) {
this.source = array;
this.mapInline = function(f) { mapInline(this.source, f); return this; };
this.map = function(f) { this.source = map(this.source, f); return this; };
this.filter = function(f) { this.source = filter(this.source, f); return this; };
this.reduce = function(v,f) { this.source = reduce(this.source, f, v); return this; };
this.value = function() { return this.source };
}
function map(source, transform) {
var clone = new Array(source.length);
for(var i = source.length; i--;) {
clone[i] = transform(source[i]);
}
return clone;
}
function mapInline(source, transform) {
for(var i = source.length; i--;) {
source[i] = transform(source[i]);
}
return source;
}
function filter(source, shouldValueBeIncluded) {
var clone = new Array(source.length), i=0;
for(var s = 0; s <= source.length; s++) {
var value = source[s];
if(shouldValueBeIncluded(value)) {
clone[i++] = value
}
}
clone.length = i;
return clone;
}
function reduce(source, computeReduction, reduction) {
for(var s = 0; s <= source.length; s++) {
var value = source[s];
reduction = computeReduction(reduction, value);
}
return reduction;
}
}();
/*!
* Based on:
* https://github.com/gilmoreorless/css-shorthand-properties
* MIT Licensed: http://gilmoreorless.mit-license.org/
*/
void function () {
/**
* Data collated from multiple W3C specs: http://www.w3.org/Style/CSS/current-work
*/
var shorthands = this.shorthandProperties = {
// CSS 2.1: http://www.w3.org/TR/CSS2/propidx.html
'list-style': ['-type', '-position', '-image'],
'margin': ['-top', '-right', '-bottom', '-left'],
'outline': ['-width', '-style', '-color'],
'padding': ['-top', '-right', '-bottom', '-left'],
// CSS Backgrounds and Borders Module Level 3: http://www.w3.org/TR/css3-background/
'background': ['-image', '-position', '-size', '-repeat', '-origin', '-clip', '-attachment', '-color'],
'background-repeat': ['-x','-y'],
'background-position': ['-x','-y'],
'border': ['-width', '-style', '-color'],
'border-color': ['border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color'],
'border-style': ['border-top-style', 'border-right-style', 'border-bottom-style', 'border-left-style'],
'border-width': ['border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width'],
'border-top': ['-width', '-style', '-color'],
'border-right': ['-width', '-style', '-color'],
'border-bottom': ['-width', '-style', '-color'],
'border-left': ['-width', '-style', '-color'],
'border-radius': ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'],
'border-image': ['-source', '-slice', '-width', '-outset', '-repeat'],
// CSS Fonts Module Level 3: http://www.w3.org/TR/css3-fonts/
'font': ['-style', '-variant', '-weight', '-stretch', '-size', 'line-height', '-family'],
'font-variant': ['-ligatures', '-alternates', '-caps', '-numeric', '-east-asian'],
// CSS Masking Module Level 1: http://www.w3.org/TR/css-masking/
'mask': ['-image', '-mode', '-position', '-size', '-repeat', '-origin', '-clip'],
'mask-border': ['-source', '-slice', '-width', '-outset', '-repeat', '-mode'],
// CSS Multi-column Layout Module: http://www.w3.org/TR/css3-multicol/
'columns': ['column-width', 'column-count'],
'column-rule': ['-width', '-style', '-color'],
// CSS Speech Module: http://www.w3.org/TR/css3-speech/
'cue': ['-before', '-after'],
'pause': ['-before', '-after'],
'rest': ['-before', '-after'],
// CSS Text Decoration Module Level 3: http://www.w3.org/TR/css-text-decor-3/
'text-decoration': ['-line', '-style', '-color'],
'text-emphasis': ['-style', '-color'],
// CSS Animations (WD): http://www.w3.org/TR/css3-animations
'animation': ['-name', '-duration', '-timing-function', '-delay', '-iteration-count', '-direction', '-fill-mode', '-play-state'],
// CSS Transitions (WD): http://www.w3.org/TR/css3-transitions/
'transition': ['-property', '-duration', '-timing-function', '-delay'],
// CSS Flexible Box Layout Module Level 1 (WD): http://www.w3.org/TR/css3-flexbox/
'flex': ['-grow', '-shrink', '-basis'],
// CSS Grid: https://drafts.csswg.org/css-grid/#grid-shorthand
'grid': ['-template', '-auto-flow', '-auto-rows','-auto-columns'],
'grid-template': ['-rows', '-columns', '-areas'],
// Others:
'overflow': ['-x','-y','-style'], // https://drafts.csswg.org/css-overflow-3/
};
var expandCache = Object.create(null);
var unexpandCache = Object.create(null);
/**
* Expand a shorthand property into an array of longhand properties which are set by it
* @param {string} property CSS property name
* @return {array} List of longhand properties, or an empty array if it's not a shorthand
*/
this.expand = function (property) {
var result = expandCache[property];
if(result) { return result; }
var prefixData = property.match(/^(-[a-zA-Z]+-)?(.*)$/);
var prefix = prefixData[1]||'', prefixFreeProperty = prefixData[2]||'';
if (!shorthands.hasOwnProperty(prefixFreeProperty)) {
return [];
}
result = [];
shorthands[prefixFreeProperty].forEach((p) => {
var longhand = p[0] === '-' ? property + p : prefix + p;
result.push(longhand);
result.push.apply(result, this.expand(longhand));
});
return expandCache[property] = result;
};
/**
* Expand a longhand property into an array of shorthand which may set the value
* @param {string} property CSS property name
* @return {array} List of shorthand properties, or the original property if it's not a shorthand
*/
this.unexpand = function unexpand(property) {
var result = unexpandCache[property];
if(result) { return result; }
var prefixData = property.match(/^(-[a-zA-Z]+-)?(.*)$/);
var prefix = prefixData[1]||'', prefixFreeProperty = prefixData[2]||'';
result = [];
for(var sh = 0; sh <= shorthands.length; sh++) {
var shorthand = shorthands[sh];
if(this.expand(shorthand).indexOf(prefixFreeProperty) >= 0) {
result.push(prefix+shorthand);
result.push.apply(result,this.unexpand(prefix+shorthand));
}
}
return unexpandCache[property] = result;
}
}.call(window.CSSShorthands={});
// http://blueprintcss.org/tests/parts/grid.html
var hasBluePrintUsage = function() {
if(!document.querySelector(".container")) {
return false;
}
for(var i = 24+1; --i;) {
if(document.querySelector(".container > .span-"+i)) {
return true;
}
}
return false;
}
//
// report how many times the classes in the following arrays have been used in the dom
// (bootstrap stats)
//
var detectedBootstrapGridUsages = function(domClasses) {
var _ = window.CSSUsageLodash;
var reduce = _.reduce.bind(_);
var trackedClasses = [];
var sizes = ['xs','sm','md','lg'];
for(var i = sizes.length; i--;) { var size = sizes[i];
for(var j = 12+1; --j;) {
trackedClasses.push('col-'+size+'-'+j);
for(var k = 12+1; --k;) {
trackedClasses.push('col-'+size+'-'+j+'-offset-'+k);
trackedClasses.push('col-'+size+'-'+j+'-push-'+k);
trackedClasses.push('col-'+size+'-'+j+'-pull-'+k);
}
}
}
return reduce(trackedClasses, (a,b) => a+(domClasses[b]|0), 0);
};
var detectedBootstrapFormUsages = function(domClasses) {
var _ = window.CSSUsageLodash;
var reduce = _.reduce.bind(_);
var trackedClasses = [
'form-group', 'form-group-xs', 'form-group-sm', 'form-group-md', 'form-group-lg',
'form-control', 'form-horizontal', 'form-inline',
'btn','btn-primary','btn-secondary','btn-success','btn-warning','btn-danger','btn-error'
];
return reduce(trackedClasses, (a,b) => a+(domClasses[b]|0), 0);
};
var detectedBootstrapAlertUsages = function(domClasses) {
var _ = window.CSSUsageLodash;
var reduce = _.reduce.bind(_);
var trackedClasses = [
'alert','alert-primary','alert-secondary','alert-success','alert-warning','alert-danger','alert-error'
];
return reduce(trackedClasses, (a,b) => a+(domClasses[b]|0), 0);
};
var detectedBootstrapFloatUsages = function(domClasses) {
var _ = window.CSSUsageLodash;
var reduce = _.reduce.bind(_);
var trackedClasses = [
'pull-left','pull-right',
];
return reduce(trackedClasses, (a,b) => a+(domClasses[b]|0), 0);
};
// https://github.com/Dogfalo/materialize/blob/master/sass/components/_grid.scss
var hasDogfaloMaterializeUsage = function() {
if(!document.querySelector(".container > .row > .col")) {
return false;
}
for(var i = 12+1; --i;) {
var classesToLookUp = ['s','m','l'];
for(var d = 0; d < classesToLookUp.length; d++) {
var s = classesToLookUp[d];
if(document.querySelector(".container > .row > .col."+s+""+i)) {
return true;
}
}
}
return false;
}
// http://www.gumbyframework.com/docs/grid/#!/basic-grid
var hasGrumbyUsage = function() {
if(!document.querySelector(".row .columns")) {
return false;
}
var classesToLookUp = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"];
for(var cl = 0; cl < classesToLookUp.length; cl++ ) {
var fraction = classesToLookUp[cl];
if(document.querySelector(".row > .columns."+fraction)) {
return true;
}
}
return false;
}
// https://raw.githubusercontent.com/csswizardry/inuit.css/master/generic/_widths.scss
var hasInuitUsage = function() {
if(!document.querySelector(".grid .grid__item")) {
return false;
}
var classesToLookUp = ["one-whole","one-half","one-third","two-thirds","one-quarter","two-quarters","one-half","three-quarters","one-fifth","two-fifths","three-fifths","four-fifths","one-sixth","two-sixths","one-third","three-sixths","one-half","four-sixths","two-thirds","five-sixths","one-eighth","two-eighths","one-quarter","three-eighths","four-eighths","one-half","five-eighths","six-eighths","three-quarters","seven-eighths","one-tenth","two-tenths","one-fifth","three-tenths","four-tenths","two-fifths","five-tenths","one-half","six-tenths","three-fifths","seven-tenths","eight-tenths","four-fifths","nine-tenths","one-twelfth","two-twelfths","one-sixth","three-twelfths","one-quarter","four-twelfths","one-third","five-twelfths","six-twelfths","one-half","seven-twelfths","eight-twelfths","two-thirds","nine-twelfths","three-quarters","ten-twelfths","five-sixths","eleven-twelfths"];
for(var cu = 0; cu < classesToLookUp.length; cu++ ) {
var fraction = classesToLookUp[cu];
var subClassesToLookUp = ["","palm-","lap-","portable-","desk-"];
for(var sc = 0; sc < subClassesToLookUp.length; sc++) {
var ns = subClassesToLookUp[sc];
if(document.querySelector(".grid > .grid__item."+ns+fraction)) {
return true;
}
}
}
return false;
}
var getLonelyGatesUsage = function (cssLonelyClassGates, domClasses, domIds, cssLonelyIdGates) {
var _ = window.CSSUsageLodash;
if((cssLonelyClassGates || domClasses || domIds || cssLonelyIdGates) == undefined) return;
// get arrays of the .class gates used ({"hover":5} => ["hover"]), filter irrelevant entries
var cssUniqueLonelyClassGatesArray = Object.keys(cssLonelyClassGates);
var cssUniqueLonelyClassGatesUsedArray = _(cssUniqueLonelyClassGatesArray).filter((c) => domClasses[c]).value();
var cssUniqueLonelyClassGatesUsedWorthArray = _(cssUniqueLonelyClassGatesUsedArray).filter((c)=>(cssLonelyClassGates[c]>9)).value();
if(window.debugCSSUsage) if(window.debugCSSUsage) console.log(cssLonelyClassGates);
if(window.debugCSSUsage) if(window.debugCSSUsage) console.log(cssUniqueLonelyClassGatesUsedWorthArray);
// get arrays of the #id gates used ({"hover":5} => ["hover"]), filter irrelevant entries
var cssUniqueLonelyIdGatesArray = Object.keys(cssLonelyIdGates);
var cssUniqueLonelyIdGatesUsedArray = _(cssUniqueLonelyIdGatesArray).filter((c) => domIds[c]).value();
var cssUniqueLonelyIdGatesUsedWorthArray = _(cssUniqueLonelyIdGatesUsedArray).filter((c)=>(cssLonelyIdGates[c]>9)).value();
if(window.debugCSSUsage) if(window.debugCSSUsage) console.log(cssLonelyIdGates);
if(window.debugCSSUsage) if(window.debugCSSUsage) console.log(cssUniqueLonelyIdGatesUsedWorthArray);
}
//
// report how many times the classes in the following arrays have been used as css gate
// (modernizer stats)
//
// https://modernizr.com/docs#features
var detectedModernizerUsages = function(cssLonelyClassGates) {
if((cssLonelyClassGates) == undefined) return;
var ModernizerUsages = {count:0,values:{/* "js":1, "no-js":2 */}};
var trackedClasses = ["js","ambientlight","applicationcache","audio","batteryapi","blobconstructor","canvas","canvastext","contenteditable","contextmenu","cookies","cors","cryptography","customprotocolhandler","customevent","dart","dataview","emoji","eventlistener","exiforientation","flash","fullscreen","gamepads","geolocation","hashchange","hiddenscroll","history","htmlimports","ie8compat","indexeddb","indexeddbblob","input","search","inputtypes","intl","json","olreversed","mathml","notification","pagevisibility","performance","pointerevents","pointerlock","postmessage","proximity","queryselector","quotamanagement","requestanimationframe","serviceworker","svg","templatestrings","touchevents","typedarrays","unicoderange","unicode","userdata","vibrate","video","vml","webintents","animation","webgl","websockets","xdomainrequest","adownload","audioloop","audiopreload","webaudio","lowbattery","canvasblending","todataurljpeg,todataurlpng,todataurlwebp","canvaswinding","getrandomvalues","cssall","cssanimations","appearance","backdropfilter","backgroundblendmode","backgroundcliptext","bgpositionshorthand","bgpositionxy","bgrepeatspace,bgrepeatround","backgroundsize","bgsizecover","borderimage","borderradius","boxshadow","boxsizing","csscalc","checked","csschunit","csscolumns","cubicbezierrange","display-runin","displaytable","ellipsis","cssescape","cssexunit","cssfilters","flexbox","flexboxlegacy","flexboxtweener","flexwrap","fontface","generatedcontent","cssgradients","hsla","csshyphens,softhyphens,softhyphensfind","cssinvalid","lastchild","cssmask","mediaqueries","multiplebgs","nthchild","objectfit","opacity","overflowscrolling","csspointerevents","csspositionsticky","csspseudoanimations","csspseudotransitions","cssreflections","regions","cssremunit","cssresize","rgba","cssscrollbar","shapes","siblinggeneral","subpixelfont","supports","target","textalignlast","textshadow","csstransforms","csstransforms3d","preserve3d","csstransitions","userselect","cssvalid","cssvhunit","cssvmaxunit","cssvminunit","cssvwunit","willchange","wrapflow","classlist","createelementattrs,createelement-attrs","dataset","documentfragment","hidden","microdata","mutationobserver","bdi","datalistelem","details","outputelem","picture","progressbar,meter","ruby","template","time","texttrackapi,track","unknownelements","es5array","es5date","es5function","es5object","es5","strictmode","es5string","es5syntax","es5undefined","es6array","contains","generators","es6math","es6number","es6object","promises","es6string","devicemotion,deviceorientation","oninput","filereader","filesystem","capture","fileinput","directory","formattribute","localizednumber","placeholder","requestautocomplete","formvalidation","sandbox","seamless","srcdoc","apng","jpeg2000","jpegxr","sizes","srcset","webpalpha","webpanimation","webplossless,webp-lossless","webp","inputformaction","inputformenctype","inputformmethod","inputformtarget","beacon","lowbandwidth","eventsource","fetch","xhrresponsetypearraybuffer","xhrresponsetypeblob","xhrresponsetypedocument","xhrresponsetypejson","xhrresponsetypetext","xhrresponsetype","xhr2","scriptasync","scriptdefer","speechrecognition","speechsynthesis","localstorage","sessionstorage","websqldatabase","stylescoped","svgasimg","svgclippaths","svgfilters","svgforeignobject","inlinesvg","smil","textareamaxlength","bloburls","datauri","urlparser","videoautoplay","videoloop","videopreload","webglextensions","datachannel","getusermedia","peerconnection","websocketsbinary","atob-btoa","framed","matchmedia","blobworkers","dataworkers","sharedworkers","transferables","webworkers"];
for(var tc = 0; tc < trackedClasses.length; tc++) {
var c = trackedClasses[tc];
countInstancesOfTheClass(c);
countInstancesOfTheClass('no-'+c);
}
return ModernizerUsages;
function countInstancesOfTheClass(c) {
var count = cssLonelyClassGates[c]; if(!count) return;
ModernizerUsages.count += count;
ModernizerUsages.values[c]=count;
}
}
function getFwkUsage(results, cssLonelyClassGates, domClasses, domIds, cssLonelyIdGates, cssClasses) {
// Modernizer
getLonelyGatesUsage(cssLonelyClassGates, domClasses, domIds, cssLonelyIdGates);
detectedModernizerUsages(cssLonelyClassGates);
results.FwkModernizer = !!window.Modernizer;
results.FwkModernizerDOMUsages = detectedModernizerUsages(domClasses);
results.FwkModernizerCSSUsages = detectedModernizerUsages(cssLonelyClassGates);
// Bootstrap
results.FwkBootstrap = !!((window.jQuery||window.$) && (window.jQuery||window.$).fn && (window.jQuery||window.$).fn.modal)|0;
results.FwkBootstrapGridUsage = detectedBootstrapGridUsages(domClasses);
results.FwkBootstrapFormUsage = detectedBootstrapFormUsages(domClasses);
results.FwkBootstrapFloatUsage = detectedBootstrapFloatUsages(domClasses);
results.FwkBootstrapAlertUsage = detectedBootstrapAlertUsages(domClasses);
results.FwkBootstrapGridRecognized = detectedBootstrapGridUsages(cssClasses);
results.FwkBootstrapFormRecognized = detectedBootstrapFormUsages(cssClasses);
results.FwkBootstrapFloatRecognized = detectedBootstrapFloatUsages(cssClasses);
results.FwkBootstrapAlertRecognized = detectedBootstrapAlertUsages(cssClasses);
// Grumby
results.FwkGrumby = hasGrumbyUsage()|0;
// Inuit
results.FwkInuit = hasInuitUsage()|0;
// Blueprint
results.FwkBluePrint = hasBluePrintUsage()|0;
// Dog Falo
results.FwkDogfaloMaterialize = hasDogfaloMaterializeUsage()|0;
return results;
}
//
// report how many times the classes in the following arrays have been used in the dom
// (general stats)
//
/** count how many times the usual clearfix classes are used */
var detectedClearfixUsages = function(domClasses) {
var _ = window.CSSUsageLodash;
var reduce = _.reduce.bind(_);
var trackedClasses = [
'clearfix','clear',
];
return reduce(trackedClasses, (a,b) => a+(domClasses[b]|0), 0);
};
/** count how many times the usual hide/show classes are used */
var detectedVisibilityUsages = function(domClasses) {
var _ = window.CSSUsageLodash;
var reduce = _.reduce.bind(_);
var trackedClasses = [
'show', 'hide', 'visible', 'hidden',
];
return reduce(trackedClasses, (a,b) => a+(domClasses[b]|0), 0);
};
function getPatternUsage(results, domClasses, cssClasses) {
results.PatClearfixUsage = detectedClearfixUsages(domClasses);
results.PatVisibilityUsage = detectedVisibilityUsages(domClasses);
results.PatClearfixRecognized = detectedClearfixUsages(cssClasses);
results.PatVisibilityRecognized = detectedVisibilityUsages(cssClasses);
return results;
}
void function() {
window.HtmlUsage = {};
// This function has been added to the elementAnalyzers in
// CSSUsage.js under onready()
// <param name="element"> is an HTMLElement passed in by elementAnalyzers
window.HtmlUsage.GetNodeName = function (element) {
// If the browser doesn't recognize the element - throw it away
if(element instanceof HTMLUnknownElement) {
return;
}
var node = element.nodeName;
var tags = HtmlUsageResults.tags || (HtmlUsageResults.tags = {});
var tag = tags[node] || (tags[node] = 0);
tags[node]++;
GetAttributes(element, node);
}
function GetAttributes(element, node) {
for(var i = 0; i < element.attributes.length; i++) {
var att = element.attributes[i];
if(IsValidAttribute(element, att.nodeName)) {
var attributes = HtmlUsageResults.attributes || (HtmlUsageResults.attributes = {});
var attribute = attributes[att.nodeName] || (attributes[att.nodeName] = {});
var attributeTag = attribute[node] || (attribute[node] = {count: 0});
attributeTag.count++;
}
}
}
function IsValidAttribute(element, attname) {
// We need to convert className
if(attname == "class") {
attname = "className";
}
if(attname == "classname") {
return false;
}
// Only keep attributes that are not data
if(attname.indexOf('data-') != -1) {
return false;
}
if(typeof(element[attname]) == "undefined") {
return false;
}
return true;
}
}();
void function() { try {
var _ = window.CSSUsageLodash;
var map = _.map.bind(_);
var mapInline = _.mapInline ? _.mapInline : map;
var reduce = _.reduce.bind(_);
var filter = _.filter.bind(_);
var browserIsEdge = navigator.userAgent.indexOf('Edge')>=0;
var browserIsFirefox = navigator.userAgent.indexOf('Firefox')>=0;
//
// Guards execution against invalid conditions
//
void function() {
// Don't run in subframes for now
if (top.location.href !== location.href) throw new Error("CSSUsage: the script doesn't run in frames for now");
// Don't run if already ran
if (window.CSSUsage) throw new Error("CSSUsage: second execution attempted; only one run can be executed; if you specified parameters, check the right ones were chosen");
// Don't run if we don't have lodash
if (!window.CSSUsageLodash) throw new Error("CSSUsage: missing CSSUsageLodash dependency");
if (!window.HtmlUsage) throw new Error("APIUsage: missing HtmlUsage dependancy");
// Do not allow buggy trim() to bother usage
if((''+String.prototype.trim).indexOf("[native code]") == -1) {
console.warn('Replaced custom trim function with something known to work. Might break website.');
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
}();
//
// Prepare our global namespace
//
void function() {
if(window.debugCSSUsage) console.log("STAGE: Building up namespace");
window.HtmlUsageResults = {
// this will contain all of the HTML tags used on a page
tags: {}, /*
tags ~= [nodeName] */
// this will contain all of the attributes used on an HTML tag
// and their values if they are in the whitelist
attributes: {} /*
attributes ~= {
name: <string>, // The name of the attribute
tag: <string>, // The tag that the attr was used on
value: <string> // The value of the attr
} */
};
window.RecipeResults = {};
window.Recipes = {
recipes: []
};
window.CSSUsage = {};
window.CSSUsageResults = {
// this will contain the usage stats of various at-rules and rules
types: [ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, ], /*
types ~= {
"unknown":0, //0
"style":0, //1
"charset": 0, //2
"import":0, //3
"media":0, //4
"font-face":0, //5
"page":0, //6
"keyframes":0, //7 This is the @keyframe at rule
"keyframe":0, //8 This is the individual 0%, or from/to
"reserved9":0, //9
"namespace":0, //10
"reserved11":0,//11
"supports":0, //12
"reserved13":0,//13
"reserved14":0,//14
"viewport":0, //15
}*/
// this will contain the usage stats of various css properties and values
props: Object.create(null), /*
props ~= {
"background-color": {
count: 10,
values: {
"<color-keyword>": 9,
"inherit": 1
}
}
}*/
// this will contains the various datapoints we measure on css selector usage
usages: {"SuccessfulCrawls":1},
// this will contain selectors and the properties they refer to
rules: {"@stylerule":0,"@atrule":0,"@inline":0}, /*
rules ~= {
"#id:hover .class": {
count: 10,
props: {
"background-color": 5,
"color": 4,
"opacity": 3,
"transform": 3
}
}
}*/
}
}();
//
// The StyleWalker API cover the extraction of style in the browser
//
void function() { "use strict";
CSSUsage.StyleWalker = {
// This array contains the list of functions being run on each CSSStyleDeclaration
// [ function(style, selectorText, matchedElements, ruleType) { ... }, ... ]
ruleAnalyzers: [],
// This array contains the list of functions being run on each DOM element of the page
// [ function(element) { ...} ]
elementAnalyzers: [],
recipesToRun: [],
runRecipes: false,
//
walkOverCssStyles: walkOverCssStyles,
walkOverDomElements: walkOverDomElements,
// Those stats are being collected while walking over the css style rules
amountOfInlineStyles: 0,
amountOfSelectorsUnused: 0,
amountOfSelectors: 0,
}
var hasWalkedDomElementsOnce = false;
// holds @keyframes temporarily while we wait to know how much they are used
var keyframes = Object.create(null);
/**
* For all stylesheets of the document,
* walk through the stylerules and run analyzers
*/
function walkOverCssStyles() {
if(window.debugCSSUsage) console.log("STAGE: Walking over styles");
var styleSheets = document.styleSheets;
// Loop through StyeSheets
for (var ssIndex = styleSheets.length; ssIndex--;) {
var styleSheet = styleSheets[ssIndex];
try {
if(styleSheet.cssRules) {
walkOverCssRules(styleSheet.cssRules, styleSheet);
} else {
console.warn("No content loaded for stylesheet: ", styleSheet.href||styleSheet);
}
}
catch (e) {
if(window.debugCSSUsage) console.log(e, e.stack);
}
}
// Hack: rely on the results to find out which
// animations actually run, and parse their keyframes
var animations = (CSSUsageResults.props['animation-name']||{}).values||{};
for(var animation in keyframes) {
var keyframe = keyframes[animation];
var matchCount = animations[animation]|0;
var fakeElements = initArray(matchCount, (i)=>({tagName:'@keyframes '+animation+' ['+i+']'}));
processRule(keyframe, fakeElements);
}
}
/**
* This is the css work horse, this will will loop over the
* rules and then call the rule analyzers currently registered
*/
function walkOverCssRules(/*CSSRuleList*/ cssRules, styleSheet, parentMatchedElements) {
if(window.debugCSSUsage) console.log("STAGE: Walking over rules");
for (var ruleIndex = cssRules.length; ruleIndex--;) {
// Loop through the rules
var rule = cssRules[ruleIndex];
// Until we can correlate animation usage
// to keyframes do not parse @keyframe rules
if(rule.type == 7) {
keyframes[rule.name] = rule;
continue;
}
// Filter "@supports" which the current browser doesn't support
if(rule.type == 12 && (!CSS.supports || !CSS.supports(rule.conditionText))) {
continue;
}
// Other rules should be processed immediately
processRule(rule,parentMatchedElements);
}
}
/**
* This function takes a css rule and:
* [1] walk over its child rules if needed
* [2] call rule analyzers for that rule if it has style data
*/
function processRule(rule, parentMatchedElements) {
// Increment the rule type's counter
CSSUsageResults.types[rule.type|0]++;
// Some CssRules have nested rules to walk through:
if (rule.cssRules && rule.cssRules.length>0) {
walkOverCssRules(rule.cssRules, rule.parentStyleSheet, parentMatchedElements);
}
// Some CssRules have style we can ananlyze
if(rule.style) {
// find what the rule applies to
var selectorText;
var matchedElements;
if(rule.selectorText) {
selectorText = CSSUsage.PropertyValuesAnalyzer.cleanSelectorText(rule.selectorText);
try {
if(parentMatchedElements) {
matchedElements = [].slice.call(document.querySelectorAll(selectorText));
matchedElements.parentMatchedElements = parentMatchedElements;
} else {
matchedElements = [].slice.call(document.querySelectorAll(selectorText));
}
} catch(ex) {
matchedElements = [];
console.warn(ex.stack||("Invalid selector: "+selectorText+" -- via "+rule.selectorText));
}
} else {
selectorText = '@atrule:'+rule.type;
if(parentMatchedElements) {
matchedElements = parentMatchedElements;
} else {
matchedElements = [];
}
}
// run an analysis on it
runRuleAnalyzers(rule.style, selectorText, matchedElements, rule.type);
}
}
/**
* This is the dom work horse, this will will loop over the
* dom elements and then call the element analyzers currently registered,
* as well as rule analyzers for inline styles
*/
function walkOverDomElements(obj, index) {
if(window.debugCSSUsage) console.log("STAGE: Walking over DOM elements");
var recipesToRun = CSSUsage.StyleWalker.recipesToRun;
obj = obj || document.documentElement; index = index|0;
// Loop through the elements
var elements = [].slice.call(document.all,0);
for(var i = 0; i < elements.length; i++) {
var element=elements[i];
// Analyze its style, if any
if(!CSSUsage.StyleWalker.runRecipes) {
// Analyze the element
runElementAnalyzers(element, index);
if (element.hasAttribute('style')) {
// Inline styles count like a style rule with no selector but one matched element
var ruleType = 1;
var isInline = true;
var selectorText = '@inline:'+element.tagName;
var matchedElements = [element];
runRuleAnalyzers(element.style, selectorText, matchedElements, ruleType, isInline);
}
} else { // We've already walked the DOM crawler and need to run the recipes
for(var r = 0; r < recipesToRun.length ; r++) {
var recipeToRun = recipesToRun[r];
var results = RecipeResults[recipeToRun.name] || (RecipeResults[recipeToRun.name]={});
recipeToRun(element, results, true);
}
}
}
}
/**
* Given a rule and its data, send it to all rule analyzers
*/
function runRuleAnalyzers(style, selectorText, matchedElements, type, isInline) {
// Keep track of the counters
if(isInline) {
CSSUsage.StyleWalker.amountOfInlineStyles++;
} else {
CSSUsage.StyleWalker.amountOfSelectors++;
}
// Run all rule analyzers
for(var i = 0; i < CSSUsage.StyleWalker.ruleAnalyzers.length; i++) {
var runAnalyzer = CSSUsage.StyleWalker.ruleAnalyzers[i];
runAnalyzer(style, selectorText, matchedElements, type, isInline);
}
}
/**
* Given an element and its data, send it to all element analyzers
*/
function runElementAnalyzers(element, index, depth) {
for(var i = 0; i < CSSUsage.StyleWalker.elementAnalyzers.length; i++) {
var runAnalyzer = CSSUsage.StyleWalker.elementAnalyzers[i];
runAnalyzer(element, index, depth);
}
}
/**
* Creates an array of "length" elements, by calling initializer for each cell
*/
function initArray(length, initializer) {
var array = Array(length);
for(var i = length; i--;) {
array[i] = initializer(i);
}
return array;
}
}();
//
// helper to work with css values
//
void function() {
CSSUsage.CSSValues = {
createValueArray: createValueArray,
parseValues: parseValues,
normalizeValue: createValueArray
};
/**
* This will take a string value and reduce it down
* to only the aspects of the value we wish to keep
*/
function parseValues(value,propertyName) {
// Trim value on the edges
value = value.trim();
// Normalize letter-casing
value = value.toLowerCase();
// Map colors to a standard value (eg: white, blue, yellow)
if (isKeywordColor(value)) { return "<color-keyword>"; }
value = value.replace(/[#][0-9a-fA-F]+/g, '#xxyyzz');
// Escapce identifiers containing numbers
var numbers = ['ZERO','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT','NINE'];
value = value.replace(
/([_a-z][-_a-z]|[_a-df-z])[0-9]+[-_a-z0-9]*/g,
s=>numbers.reduce(
(m,nstr,nint)=>m.replace(RegExp(nint,'g'),nstr),
s
)
);
// Remove any digits eg: 55px -> px, 1.5 -> 0.0, 1 -> 0
value = value.replace(/(?:[+]|[-]|)(?:(?:[0-9]+)(?:[.][0-9]+|)|(?:[.][0-9]+))(?:[e](?:[+]|[-]|)(?:[0-9]+))?(%|e[a-z]+|[a-df-z][a-z]*)/g, "$1");
value = value.replace(/(?:[+]|[-]|)(?:[0-9]+)(?:[.][0-9]+)(?:[e](?:[+]|[-]|)(?:[0-9]+))?/g, " <float> ");
value = value.replace(/(?:[+]|[-]|)(?:[.][0-9]+)(?:[e](?:[+]|[-]|)(?:[0-9]+))?/g, " <float> ");
value = value.replace(/(?:[+]|[-]|)(?:[0-9]+)(?:[e](?:[+]|[-]|)(?:[0-9]+))/g, " <float> ");
value = value.replace(/(?:[+]|[-]|)(?:[0-9]+)/g, " <int> ");
// Unescapce identifiers containing numbers
value = numbers.reduce(
(m,nstr,nint)=>m.replace(RegExp(nstr,'g'),nint),
value
)
// Remove quotes
value = value.replace(/('|‘|’|")/g, "");
//
switch(propertyName) {
case 'counter-increment':
case 'counter-reset':
// Anonymize the user identifier
value = value.replace(/[-_a-zA-Z0-9]+/g,' <custom-ident> ');
break;
case 'grid':
case 'grid-template':
case 'grid-template-rows':
case 'grid-template-columns':
case 'grid-template-areas':
// Anonymize line names
value = value.replace(/\[[-_a-zA-Z0-9 ]+\]/g,' <line-names> ');
break;
case '--var':
// Replace (...), {...} and [...]
value = value.replace(/[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]*)[)])*[)])*[)])*[)])*[)]/g, " <parentheses-block> ");
value = value.replace(/[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]*)[)])*[)])*[)])*[)])*[)]/g, " <parentheses-block> ");
value = value.replace(/\[(?:[^()]+|\[(?:[^()]+|\[(?:[^()]+|\[(?:[^()]+|\[(?:[^()]*)\])*\])*\])*\])*\]/g, " <curly-brackets-block> ");
value = value.replace(/\[(?:[^()]+|\[(?:[^()]+|\[(?:[^()]+|\[(?:[^()]+|\[(?:[^()]*)\])*\])*\])*\])*\]/g, " <curly-brackets-block> ");
value = value.replace(/\{(?:[^()]+|\{(?:[^()]+|\{(?:[^()]+|\{(?:[^()]+|\{(?:[^()]*)\})*\})*\})*\})*\}/g, " <square-brackets-block> ");
value = value.replace(/\{(?:[^()]+|\{(?:[^()]+|\{(?:[^()]+|\{(?:[^()]+|\{(?:[^()]*)\})*\})*\})*\})*\}/g, " <square-brackets-block> ");
break;
}
return value.trim();
}
//-----------------------------------------------------------------------------
/**
* This will transform a value into an array of value identifiers
*/
function createValueArray(value, propertyName) {
// Trim value on the edges
value = value.trim();
// Normalize letter-casing
value = value.toLowerCase();
// Remove comments and !important
value = value.replace(/([/][*](?:.|\r|\n)*[*][/]|[!]important.*)/g,'');
// Do the right thing in function of the property
switch(propertyName) {
case 'font-family':
// Remove various quotes
if (value.indexOf("'") != -1 || value.indexOf("‘") != -1 || value.indexOf('"')) {
value = value.replace(/('|‘|’|")/g, "");
}
// Divide at commas to separate different font names
value = value.split(/\s*,\s*/g);
return value;
case '--var':
// Replace strings by dummies
value = value.replace(/"([^"\\]|\\[^"\\]|\\\\|\\")*"/g,' <string> ')
value = value.replace(/'([^'\\]|\\[^'\\]|\\\\|\\')*'/g,' <string> ');
// Replace url(...) functions by dummies
value = value.replace(/([a-z]?)[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]*)[)])*[)])*[)])*[)])*[)]/g, "$1()");
value = value.replace(/([a-z]?)[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]*)[)])*[)])*[)])*[)])*[)]/g, "$1()");
// Remove group contents (...), {...} and [...]
value = value.replace(/[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]*)[)])*[)])*[)])*[)])*[)]/g, " <parentheses-block> ");
value = value.replace(/[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]*)[)])*[)])*[)])*[)])*[)]/g, " <parentheses-block> ");
value = value.replace(/[{](?:[^{}]+|[{](?:[^{}]+|[{](?:[^{}]+|[{](?:[^{}]+|[{](?:[^{}]*)[}])*[}])*[}])*[}])*[}]/g, " <curly-brackets-block> ");
value = value.replace(/[{](?:[^{}]+|[{](?:[^{}]+|[{](?:[^{}]+|[{](?:[^{}]+|[{](?:[^{}]*)[}])*[}])*[}])*[}])*[}]/g, " <curly-brackets-block> ");
value = value.replace(/[\[](?:[^\[\]]+|[\[](?:[^\[\]]+|[\[](?:[^\[\]]+|[\[](?:[^\[\]]+|[\[](?:[^\[\]]*)[\]])*[\]])*[\]])*[\]])*[\]]/g, " <square-brackets-block> ");
value = value.replace(/[\[](?:[^\[\]]+|[\[](?:[^\[\]]+|[\[](?:[^\[\]]+|[\[](?:[^\[\]]+|[\[](?:[^\[\]]*)[\]])*[\]])*[\]])*[\]])*[\]]/g, " <square-brackets-block> ");
break;
default:
// Replace strings by dummies
value = value.replace(/"([^"\\]|\\[^"\\]|\\\\|\\")*"/g,' <string> ')
.replace(/'([^'\\]|\\[^'\\]|\\\\|\\')*'/g,' <string> ');
// Replace url(...) functions by dummies
if (value.indexOf("(") != -1) {
value = value.replace(/([a-z]?)[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]*)[)])*[)])*[)])*[)])*[)]/g, "$1() ");
value = value.replace(/([a-z]?)[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]+|[(](?:[^()]*)[)])*[)])*[)])*[)])*[)]/g, "$1() ");
}
}
// Collapse whitespace
value = value.trim().replace(/\s+/g, " ");
// Divide at commas and spaces to separate different values
value = value.split(/\s*(?:,|[/])\s*|\s+/g);