-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpicturefill.js
1471 lines (1218 loc) · 41.6 KB
/
picturefill.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
/*! Picturefill - v3.0.2
* http://scottjehl.github.io/picturefill
* Copyright (c) 2015 https://github.com/scottjehl/picturefill/blob/master/Authors.txt;
* License: MIT
*/
(function( window, document, undefined ) {
// Enable strict mode
"use strict";
// HTML shim|v it for old IE (IE9 will still need the HTML video tag workaround)
document.createElement( "picture" );
var warn, eminpx, alwaysCheckWDescriptor, evalId;
// local object for method references and testing exposure
var pf = {};
var isSupportTestReady = false;
var noop = function() {};
var image = document.createElement( "img" );
var getImgAttr = image.getAttribute;
var setImgAttr = image.setAttribute;
var removeImgAttr = image.removeAttribute;
var docElem = document.documentElement;
var types = {};
var cfg = {
//resource selection:
algorithm: ""
};
var srcAttr = "data-pfsrc";
var srcsetAttr = srcAttr + "set";
// ua sniffing is done for undetectable img loading features,
// to do some non crucial perf optimizations
var ua = navigator.userAgent;
var supportAbort = (/rident/).test(ua) || ((/ecko/).test(ua) && ua.match(/rv\:(\d+)/) && RegExp.$1 > 35 );
var curSrcProp = "currentSrc";
var regWDesc = /\s+\+?\d+(e\d+)?w/;
var regSize = /(\([^)]+\))?\s*(.+)/;
var setOptions = window.picturefillCFG;
/**
* Shortcut property for https://w3c.github.io/webappsec/specs/mixedcontent/#restricts-mixed-content ( for easy overriding in tests )
*/
// baseStyle also used by getEmValue (i.e.: width: 1em is important)
var baseStyle = "position:absolute;left:0;visibility:hidden;display:block;padding:0;border:none;font-size:1em;width:1em;overflow:hidden;clip:rect(0px, 0px, 0px, 0px)";
var fsCss = "font-size:100%!important;";
var isVwDirty = true;
var cssCache = {};
var sizeLengthCache = {};
var DPR = window.devicePixelRatio;
var units = {
px: 1,
"in": 96
};
var anchor = document.createElement( "a" );
/**
* alreadyRun flag used for setOptions. is it true setOptions will reevaluate
* @type {boolean}
*/
var alreadyRun = false;
// Reusable, non-"g" Regexes
// (Don't use \s, to avoid matching non-breaking space.)
var regexLeadingSpaces = /^[ \t\n\r\u000c]+/,
regexLeadingCommasOrSpaces = /^[, \t\n\r\u000c]+/,
regexLeadingNotSpaces = /^[^ \t\n\r\u000c]+/,
regexTrailingCommas = /[,]+$/,
regexNonNegativeInteger = /^\d+$/,
// ( Positive or negative or unsigned integers or decimals, without or without exponents.
// Must include at least one digit.
// According to spec tests any decimal point must be followed by a digit.
// No leading plus sign is allowed.)
// https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number
regexFloatingPoint = /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/;
var on = function(obj, evt, fn, capture) {
if ( obj.addEventListener ) {
obj.addEventListener(evt, fn, capture || false);
} else if ( obj.attachEvent ) {
obj.attachEvent( "on" + evt, fn);
}
};
/**
* simple memoize function:
*/
var memoize = function(fn) {
var cache = {};
return function(input) {
if ( !(input in cache) ) {
cache[ input ] = fn(input);
}
return cache[ input ];
};
};
// UTILITY FUNCTIONS
// Manual is faster than RegEx
// http://jsperf.com/whitespace-character/5
function isSpace(c) {
return (c === "\u0020" || // space
c === "\u0009" || // horizontal tab
c === "\u000A" || // new line
c === "\u000C" || // form feed
c === "\u000D"); // carriage return
}
/**
* gets a mediaquery and returns a boolean or gets a css length and returns a number
* @param css mediaqueries or css length
* @returns {boolean|number}
*
* based on: https://gist.github.com/jonathantneal/db4f77009b155f083738
*/
var evalCSS = (function() {
var regLength = /^([\d\.]+)(em|vw|px)$/;
var replace = function() {
var args = arguments, index = 0, string = args[0];
while (++index in args) {
string = string.replace(args[index], args[++index]);
}
return string;
};
var buildStr = memoize(function(css) {
return "return " + replace((css || "").toLowerCase(),
// interpret `and`
/\band\b/g, "&&",
// interpret `,`
/,/g, "||",
// interpret `min-` as >=
/min-([a-z-\s]+):/g, "e.$1>=",
// interpret `max-` as <=
/max-([a-z-\s]+):/g, "e.$1<=",
//calc value
/calc([^)]+)/g, "($1)",
// interpret css values
/(\d+[\.]*[\d]*)([a-z]+)/g, "($1 * e.$2)",
//make eval less evil
/^(?!(e.[a-z]|[0-9\.&=|><\+\-\*\(\)\/])).*/ig, ""
) + ";";
});
return function(css, length) {
var parsedLength;
if (!(css in cssCache)) {
cssCache[css] = false;
if (length && (parsedLength = css.match( regLength ))) {
cssCache[css] = parsedLength[ 1 ] * units[parsedLength[ 2 ]];
} else {
/*jshint evil:true */
try{
cssCache[css] = new Function("e", buildStr(css))(units);
} catch(e) {}
/*jshint evil:false */
}
}
return cssCache[css];
};
})();
var setResolution = function( candidate, sizesattr ) {
if ( candidate.w ) { // h = means height: || descriptor.type === 'h' do not handle yet...
candidate.cWidth = pf.calcListLength( sizesattr || "100vw" );
candidate.res = candidate.w / candidate.cWidth ;
} else {
candidate.res = candidate.d;
}
return candidate;
};
/**
*
* @param opt
*/
var picturefill = function( opt ) {
if (!isSupportTestReady) {return;}
var elements, i, plen;
var options = opt || {};
if ( options.elements && options.elements.nodeType === 1 ) {
if ( options.elements.nodeName.toUpperCase() === "IMG" ) {
options.elements = [ options.elements ];
} else {
options.context = options.elements;
options.elements = null;
}
}
elements = options.elements || pf.qsa( (options.context || document), ( options.reevaluate || options.reselect ) ? pf.sel : pf.selShort );
if ( (plen = elements.length) ) {
pf.setupRun( options );
alreadyRun = true;
// Loop through all elements
for ( i = 0; i < plen; i++ ) {
pf.fillImg(elements[ i ], options);
}
pf.teardownRun( options );
}
};
/**
* outputs a warning for the developer
* @param {message}
* @type {Function}
*/
warn = ( window.console && console.warn ) ?
function( message ) {
console.warn( message );
} :
noop
;
if ( !(curSrcProp in image) ) {
curSrcProp = "src";
}
// Add support for standard mime types.
types[ "image/jpeg" ] = true;
types[ "image/gif" ] = true;
types[ "image/png" ] = true;
function detectTypeSupport( type, typeUri ) {
// based on Modernizr's lossless img-webp test
// note: asynchronous
var image = new window.Image();
image.onerror = function() {
types[ type ] = false;
picturefill();
};
image.onload = function() {
types[ type ] = image.width === 1;
picturefill();
};
image.src = typeUri;
return "pending";
}
// test svg support
types[ "image/svg+xml" ] = document.implementation.hasFeature( "http://www.w3.org/TR/SVG11/feature#Image", "1.1" );
/**
* updates the internal vW property with the current viewport width in px
*/
function updateMetrics() {
isVwDirty = false;
DPR = window.devicePixelRatio;
cssCache = {};
sizeLengthCache = {};
pf.DPR = DPR || 1;
units.width = Math.max(window.innerWidth || 0, docElem.clientWidth);
units.height = Math.max(window.innerHeight || 0, docElem.clientHeight);
units.vw = units.width / 100;
units.vh = units.height / 100;
evalId = [ units.height, units.width, DPR ].join("-");
units.em = pf.getEmValue();
units.rem = units.em;
}
function chooseLowRes( lowerValue, higherValue, dprValue, isCached ) {
var bonusFactor, tooMuch, bonus, meanDensity;
//experimental
if (cfg.algorithm === "saveData" ){
if ( lowerValue > 2.7 ) {
meanDensity = dprValue + 1;
} else {
tooMuch = higherValue - dprValue;
bonusFactor = Math.pow(lowerValue - 0.6, 1.5);
bonus = tooMuch * bonusFactor;
if (isCached) {
bonus += 0.1 * bonusFactor;
}
meanDensity = lowerValue + bonus;
}
} else {
meanDensity = (dprValue > 1) ?
Math.sqrt(lowerValue * higherValue) :
lowerValue;
}
return meanDensity > dprValue;
}
function applyBestCandidate( img ) {
var srcSetCandidates;
var matchingSet = pf.getSet( img );
var evaluated = false;
if ( matchingSet !== "pending" ) {
evaluated = evalId;
if ( matchingSet ) {
srcSetCandidates = pf.setRes( matchingSet );
pf.applySetCandidate( srcSetCandidates, img );
}
}
img[ pf.ns ].evaled = evaluated;
}
function ascendingSort( a, b ) {
return a.res - b.res;
}
function setSrcToCur( img, src, set ) {
var candidate;
if ( !set && src ) {
set = img[ pf.ns ].sets;
set = set && set[set.length - 1];
}
candidate = getCandidateForSrc(src, set);
if ( candidate ) {
src = pf.makeUrl(src);
img[ pf.ns ].curSrc = src;
img[ pf.ns ].curCan = candidate;
if ( !candidate.res ) {
setResolution( candidate, candidate.set.sizes );
}
}
return candidate;
}
function getCandidateForSrc( src, set ) {
var i, candidate, candidates;
if ( src && set ) {
candidates = pf.parseSet( set );
src = pf.makeUrl(src);
for ( i = 0; i < candidates.length; i++ ) {
if ( src === pf.makeUrl(candidates[ i ].url) ) {
candidate = candidates[ i ];
break;
}
}
}
return candidate;
}
function getAllSourceElements( picture, candidates ) {
var i, len, source, srcset;
// SPEC mismatch intended for size and perf:
// actually only source elements preceding the img should be used
// also note: don't use qsa here, because IE8 sometimes doesn't like source as the key part in a selector
var sources = picture.getElementsByTagName( "source" );
for ( i = 0, len = sources.length; i < len; i++ ) {
source = sources[ i ];
source[ pf.ns ] = true;
srcset = source.getAttribute( "srcset" );
// if source does not have a srcset attribute, skip
if ( srcset ) {
candidates.push( {
srcset: srcset,
media: source.getAttribute( "media" ),
type: source.getAttribute( "type" ),
sizes: source.getAttribute( "sizes" )
} );
}
}
}
/**
* Srcset Parser
* By Alex Bell | MIT License
*
* @returns Array [{url: _, d: _, w: _, h:_, set:_(????)}, ...]
*
* Based super duper closely on the reference algorithm at:
* https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute
*/
// 1. Let input be the value passed to this algorithm.
// (TO-DO : Explain what "set" argument is here. Maybe choose a more
// descriptive & more searchable name. Since passing the "set" in really has
// nothing to do with parsing proper, I would prefer this assignment eventually
// go in an external fn.)
function parseSrcset(input, set) {
function collectCharacters(regEx) {
var chars,
match = regEx.exec(input.substring(pos));
if (match) {
chars = match[ 0 ];
pos += chars.length;
return chars;
}
}
var inputLength = input.length,
url,
descriptors,
currentDescriptor,
state,
c,
// 2. Let position be a pointer into input, initially pointing at the start
// of the string.
pos = 0,
// 3. Let candidates be an initially empty source set.
candidates = [];
/**
* Adds descriptor properties to a candidate, pushes to the candidates array
* @return undefined
*/
// (Declared outside of the while loop so that it's only created once.
// (This fn is defined before it is used, in order to pass JSHINT.
// Unfortunately this breaks the sequencing of the spec comments. :/ )
function parseDescriptors() {
// 9. Descriptor parser: Let error be no.
var pError = false,
// 10. Let width be absent.
// 11. Let density be absent.
// 12. Let future-compat-h be absent. (We're implementing it now as h)
w, d, h, i,
candidate = {},
desc, lastChar, value, intVal, floatVal;
// 13. For each descriptor in descriptors, run the appropriate set of steps
// from the following list:
for (i = 0 ; i < descriptors.length; i++) {
desc = descriptors[ i ];
lastChar = desc[ desc.length - 1 ];
value = desc.substring(0, desc.length - 1);
intVal = parseInt(value, 10);
floatVal = parseFloat(value);
// If the descriptor consists of a valid non-negative integer followed by
// a U+0077 LATIN SMALL LETTER W character
if (regexNonNegativeInteger.test(value) && (lastChar === "w")) {
// If width and density are not both absent, then let error be yes.
if (w || d) {pError = true;}
// Apply the rules for parsing non-negative integers to the descriptor.
// If the result is zero, let error be yes.
// Otherwise, let width be the result.
if (intVal === 0) {pError = true;} else {w = intVal;}
// If the descriptor consists of a valid floating-point number followed by
// a U+0078 LATIN SMALL LETTER X character
} else if (regexFloatingPoint.test(value) && (lastChar === "x")) {
// If width, density and future-compat-h are not all absent, then let error
// be yes.
if (w || d || h) {pError = true;}
// Apply the rules for parsing floating-point number values to the descriptor.
// If the result is less than zero, let error be yes. Otherwise, let density
// be the result.
if (floatVal < 0) {pError = true;} else {d = floatVal;}
// If the descriptor consists of a valid non-negative integer followed by
// a U+0068 LATIN SMALL LETTER H character
} else if (regexNonNegativeInteger.test(value) && (lastChar === "h")) {
// If height and density are not both absent, then let error be yes.
if (h || d) {pError = true;}
// Apply the rules for parsing non-negative integers to the descriptor.
// If the result is zero, let error be yes. Otherwise, let future-compat-h
// be the result.
if (intVal === 0) {pError = true;} else {h = intVal;}
// Anything else, Let error be yes.
} else {pError = true;}
} // (close step 13 for loop)
// 15. If error is still no, then append a new image source to candidates whose
// URL is url, associated with a width width if not absent and a pixel
// density density if not absent. Otherwise, there is a parse error.
if (!pError) {
candidate.url = url;
if (w) { candidate.w = w;}
if (d) { candidate.d = d;}
if (h) { candidate.h = h;}
if (!h && !d && !w) {candidate.d = 1;}
if (candidate.d === 1) {set.has1x = true;}
candidate.set = set;
candidates.push(candidate);
}
} // (close parseDescriptors fn)
/**
* Tokenizes descriptor properties prior to parsing
* Returns undefined.
* (Again, this fn is defined before it is used, in order to pass JSHINT.
* Unfortunately this breaks the logical sequencing of the spec comments. :/ )
*/
function tokenize() {
// 8.1. Descriptor tokeniser: Skip whitespace
collectCharacters(regexLeadingSpaces);
// 8.2. Let current descriptor be the empty string.
currentDescriptor = "";
// 8.3. Let state be in descriptor.
state = "in descriptor";
while (true) {
// 8.4. Let c be the character at position.
c = input.charAt(pos);
// Do the following depending on the value of state.
// For the purpose of this step, "EOF" is a special character representing
// that position is past the end of input.
// In descriptor
if (state === "in descriptor") {
// Do the following, depending on the value of c:
// Space character
// If current descriptor is not empty, append current descriptor to
// descriptors and let current descriptor be the empty string.
// Set state to after descriptor.
if (isSpace(c)) {
if (currentDescriptor) {
descriptors.push(currentDescriptor);
currentDescriptor = "";
state = "after descriptor";
}
// U+002C COMMA (,)
// Advance position to the next character in input. If current descriptor
// is not empty, append current descriptor to descriptors. Jump to the step
// labeled descriptor parser.
} else if (c === ",") {
pos += 1;
if (currentDescriptor) {
descriptors.push(currentDescriptor);
}
parseDescriptors();
return;
// U+0028 LEFT PARENTHESIS (()
// Append c to current descriptor. Set state to in parens.
} else if (c === "\u0028") {
currentDescriptor = currentDescriptor + c;
state = "in parens";
// EOF
// If current descriptor is not empty, append current descriptor to
// descriptors. Jump to the step labeled descriptor parser.
} else if (c === "") {
if (currentDescriptor) {
descriptors.push(currentDescriptor);
}
parseDescriptors();
return;
// Anything else
// Append c to current descriptor.
} else {
currentDescriptor = currentDescriptor + c;
}
// (end "in descriptor"
// In parens
} else if (state === "in parens") {
// U+0029 RIGHT PARENTHESIS ())
// Append c to current descriptor. Set state to in descriptor.
if (c === ")") {
currentDescriptor = currentDescriptor + c;
state = "in descriptor";
// EOF
// Append current descriptor to descriptors. Jump to the step labeled
// descriptor parser.
} else if (c === "") {
descriptors.push(currentDescriptor);
parseDescriptors();
return;
// Anything else
// Append c to current descriptor.
} else {
currentDescriptor = currentDescriptor + c;
}
// After descriptor
} else if (state === "after descriptor") {
// Do the following, depending on the value of c:
// Space character: Stay in this state.
if (isSpace(c)) {
// EOF: Jump to the step labeled descriptor parser.
} else if (c === "") {
parseDescriptors();
return;
// Anything else
// Set state to in descriptor. Set position to the previous character in input.
} else {
state = "in descriptor";
pos -= 1;
}
}
// Advance position to the next character in input.
pos += 1;
// Repeat this step.
} // (close while true loop)
}
// 4. Splitting loop: Collect a sequence of characters that are space
// characters or U+002C COMMA characters. If any U+002C COMMA characters
// were collected, that is a parse error.
while (true) {
collectCharacters(regexLeadingCommasOrSpaces);
// 5. If position is past the end of input, return candidates and abort these steps.
if (pos >= inputLength) {
return candidates; // (we're done, this is the sole return path)
}
// 6. Collect a sequence of characters that are not space characters,
// and let that be url.
url = collectCharacters(regexLeadingNotSpaces);
// 7. Let descriptors be a new empty list.
descriptors = [];
// 8. If url ends with a U+002C COMMA character (,), follow these substeps:
// (1). Remove all trailing U+002C COMMA characters from url. If this removed
// more than one character, that is a parse error.
if (url.slice(-1) === ",") {
url = url.replace(regexTrailingCommas, "");
// (Jump ahead to step 9 to skip tokenization and just push the candidate).
parseDescriptors();
// Otherwise, follow these substeps:
} else {
tokenize();
} // (close else of step 8)
// 16. Return to the step labeled splitting loop.
} // (Close of big while loop.)
}
/*
* Sizes Parser
*
* By Alex Bell | MIT License
*
* Non-strict but accurate and lightweight JS Parser for the string value <img sizes="here">
*
* Reference algorithm at:
* https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-sizes-attribute
*
* Most comments are copied in directly from the spec
* (except for comments in parens).
*
* Grammar is:
* <source-size-list> = <source-size># [ , <source-size-value> ]? | <source-size-value>
* <source-size> = <media-condition> <source-size-value>
* <source-size-value> = <length>
* http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#attr-img-sizes
*
* E.g. "(max-width: 30em) 100vw, (max-width: 50em) 70vw, 100vw"
* or "(min-width: 30em), calc(30vw - 15px)" or just "30vw"
*
* Returns the first valid <css-length> with a media condition that evaluates to true,
* or "100vw" if all valid media conditions evaluate to false.
*
*/
function parseSizes(strValue) {
// (Percentage CSS lengths are not allowed in this case, to avoid confusion:
// https://html.spec.whatwg.org/multipage/embedded-content.html#valid-source-size-list
// CSS allows a single optional plus or minus sign:
// http://www.w3.org/TR/CSS2/syndata.html#numbers
// CSS is ASCII case-insensitive:
// http://www.w3.org/TR/CSS2/syndata.html#characters )
// Spec allows exponential notation for <number> type:
// http://dev.w3.org/csswg/css-values/#numbers
var regexCssLengthWithUnits = /^(?:[+-]?[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?(?:ch|cm|em|ex|in|mm|pc|pt|px|rem|vh|vmin|vmax|vw)$/i;
// (This is a quick and lenient test. Because of optional unlimited-depth internal
// grouping parens and strict spacing rules, this could get very complicated.)
var regexCssCalc = /^calc\((?:[0-9a-z \.\+\-\*\/\(\)]+)\)$/i;
var i;
var unparsedSizesList;
var unparsedSizesListLength;
var unparsedSize;
var lastComponentValue;
var size;
// UTILITY FUNCTIONS
// (Toy CSS parser. The goals here are:
// 1) expansive test coverage without the weight of a full CSS parser.
// 2) Avoiding regex wherever convenient.
// Quick tests: http://jsfiddle.net/gtntL4gr/3/
// Returns an array of arrays.)
function parseComponentValues(str) {
var chrctr;
var component = "";
var componentArray = [];
var listArray = [];
var parenDepth = 0;
var pos = 0;
var inComment = false;
function pushComponent() {
if (component) {
componentArray.push(component);
component = "";
}
}
function pushComponentArray() {
if (componentArray[0]) {
listArray.push(componentArray);
componentArray = [];
}
}
// (Loop forwards from the beginning of the string.)
while (true) {
chrctr = str.charAt(pos);
if (chrctr === "") { // ( End of string reached.)
pushComponent();
pushComponentArray();
return listArray;
} else if (inComment) {
if ((chrctr === "*") && (str[pos + 1] === "/")) { // (At end of a comment.)
inComment = false;
pos += 2;
pushComponent();
continue;
} else {
pos += 1; // (Skip all characters inside comments.)
continue;
}
} else if (isSpace(chrctr)) {
// (If previous character in loop was also a space, or if
// at the beginning of the string, do not add space char to
// component.)
if ( (str.charAt(pos - 1) && isSpace( str.charAt(pos - 1) ) ) || !component ) {
pos += 1;
continue;
} else if (parenDepth === 0) {
pushComponent();
pos +=1;
continue;
} else {
// (Replace any space character with a plain space for legibility.)
chrctr = " ";
}
} else if (chrctr === "(") {
parenDepth += 1;
} else if (chrctr === ")") {
parenDepth -= 1;
} else if (chrctr === ",") {
pushComponent();
pushComponentArray();
pos += 1;
continue;
} else if ( (chrctr === "/") && (str.charAt(pos + 1) === "*") ) {
inComment = true;
pos += 2;
continue;
}
component = component + chrctr;
pos += 1;
}
}
function isValidNonNegativeSourceSizeValue(s) {
if (regexCssLengthWithUnits.test(s) && (parseFloat(s) >= 0)) {return true;}
if (regexCssCalc.test(s)) {return true;}
// ( http://www.w3.org/TR/CSS2/syndata.html#numbers says:
// "-0 is equivalent to 0 and is not a negative number." which means that
// unitless zero and unitless negative zero must be accepted as special cases.)
if ((s === "0") || (s === "-0") || (s === "+0")) {return true;}
return false;
}
// When asked to parse a sizes attribute from an element, parse a
// comma-separated list of component values from the value of the element's
// sizes attribute (or the empty string, if the attribute is absent), and let
// unparsed sizes list be the result.
// http://dev.w3.org/csswg/css-syntax/#parse-comma-separated-list-of-component-values
unparsedSizesList = parseComponentValues(strValue);
unparsedSizesListLength = unparsedSizesList.length;
// For each unparsed size in unparsed sizes list:
for (i = 0; i < unparsedSizesListLength; i++) {
unparsedSize = unparsedSizesList[i];
// 1. Remove all consecutive <whitespace-token>s from the end of unparsed size.
// ( parseComponentValues() already omits spaces outside of parens. )
// If unparsed size is now empty, that is a parse error; continue to the next
// iteration of this algorithm.
// ( parseComponentValues() won't push an empty array. )
// 2. If the last component value in unparsed size is a valid non-negative
// <source-size-value>, let size be its value and remove the component value
// from unparsed size. Any CSS function other than the calc() function is
// invalid. Otherwise, there is a parse error; continue to the next iteration
// of this algorithm.
// http://dev.w3.org/csswg/css-syntax/#parse-component-value
lastComponentValue = unparsedSize[unparsedSize.length - 1];
if (isValidNonNegativeSourceSizeValue(lastComponentValue)) {
size = lastComponentValue;
unparsedSize.pop();
} else {
continue;
}
// 3. Remove all consecutive <whitespace-token>s from the end of unparsed
// size. If unparsed size is now empty, return size and exit this algorithm.
// If this was not the last item in unparsed sizes list, that is a parse error.
if (unparsedSize.length === 0) {
return size;
}
// 4. Parse the remaining component values in unparsed size as a
// <media-condition>. If it does not parse correctly, or it does parse
// correctly but the <media-condition> evaluates to false, continue to the
// next iteration of this algorithm.
// (Parsing all possible compound media conditions in JS is heavy, complicated,
// and the payoff is unclear. Is there ever an situation where the
// media condition parses incorrectly but still somehow evaluates to true?
// Can we just rely on the browser/polyfill to do it?)
unparsedSize = unparsedSize.join(" ");
if (!(pf.matchesMedia( unparsedSize ) ) ) {
continue;
}
// 5. Return size and exit this algorithm.
return size;
}
// If the above algorithm exhausts unparsed sizes list without returning a
// size value, return 100vw.
return "100vw";
}
// namespace
pf.ns = ("pf" + new Date().getTime()).substr(0, 9);
// srcset support test
pf.supSrcset = "srcset" in image;
pf.supSizes = "sizes" in image;
pf.supPicture = !!window.HTMLPictureElement;
// UC browser does claim to support srcset and picture, but not sizes,
// this extended test reveals the browser does support nothing
if (pf.supSrcset && pf.supPicture && !pf.supSizes) {
(function(image2) {
image.srcset = "data:,a";
image2.src = "data:,a";
pf.supSrcset = image.complete === image2.complete;
pf.supPicture = pf.supSrcset && pf.supPicture;
})(document.createElement("img"));
}
// Safari9 has basic support for sizes, but does't expose the `sizes` idl attribute
if (pf.supSrcset && !pf.supSizes) {
(function() {
var width2 = "data:image/gif;base64,R0lGODlhAgABAPAAAP///wAAACH5BAAAAAAALAAAAAACAAEAAAICBAoAOw==";
var width1 = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
var img = document.createElement("img");
var test = function() {
var width = img.width;
if (width === 2) {
pf.supSizes = true;
}
alwaysCheckWDescriptor = pf.supSrcset && !pf.supSizes;
isSupportTestReady = true;
// force async
setTimeout(picturefill);
};
img.onload = test;
img.onerror = test;
img.setAttribute("sizes", "9px");
img.srcset = width1 + " 1w," + width2 + " 9w";
img.src = width1;
})();
} else {
isSupportTestReady = true;
}
// using pf.qsa instead of dom traversing does scale much better,
// especially on sites mixing responsive and non-responsive images
pf.selShort = "picture>img,img[srcset]";
pf.sel = pf.selShort;
pf.cfg = cfg;
/**
* Shortcut property for `devicePixelRatio` ( for easy overriding in tests )
*/
pf.DPR = (DPR || 1 );
pf.u = units;
// container of supported mime types that one might need to qualify before using
pf.types = types;
pf.setSize = noop;
/**
* Gets a string and returns the absolute URL
* @param src
* @returns {String} absolute URL
*/
pf.makeUrl = memoize(function(src) {
anchor.href = src;
return anchor.href;
});
/**
* Gets a DOM element or document and a selctor and returns the found matches
* Can be extended with jQuery/Sizzle for IE7 support
* @param context
* @param sel
* @returns {NodeList|Array}
*/
pf.qsa = function(context, sel) {
return ( "querySelector" in context ) ? context.querySelectorAll(sel) : [];
};
/**
* Shortcut method for matchMedia ( for easy overriding in tests )
* wether native or pf.mMQ is used will be decided lazy on first call
* @returns {boolean}
*/
pf.matchesMedia = function() {
if ( window.matchMedia && (matchMedia( "(min-width: 0.1em)" ) || {}).matches ) {
pf.matchesMedia = function( media ) {
return !media || ( matchMedia( media ).matches );
};
} else {
pf.matchesMedia = pf.mMQ;
}
return pf.matchesMedia.apply( this, arguments );
};
/**
* A simplified matchMedia implementation for IE8 and IE9
* handles only min-width/max-width with px or em values
* @param media
* @returns {boolean}
*/