parse-srcset.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /**
  2. * Srcset Parser
  3. *
  4. * By Alex Bell | MIT License
  5. *
  6. * JS Parser for the string value that appears in markup <img srcset="here">
  7. *
  8. * @returns Array [{url: _, d: _, w: _, h:_}, ...]
  9. *
  10. * Based super duper closely on the reference algorithm at:
  11. * https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute
  12. *
  13. * Most comments are copied in directly from the spec
  14. * (except for comments in parens).
  15. */
  16. /* global window */
  17. (function (root, factory) {
  18. if (typeof module === "object" && module.exports) {
  19. // Node. Does not work with strict CommonJS, but
  20. // only CommonJS-like environments that support module.exports,
  21. // like Node.
  22. module.exports = factory();
  23. } else {
  24. // Browser globals (root is window)
  25. root.parseSrcset = factory();
  26. }
  27. }(window, function () {
  28. // 1. Let input be the value passed to this algorithm.
  29. return function (input) {
  30. // UTILITY FUNCTIONS
  31. // Manual is faster than RegEx
  32. // http://bjorn.tipling.com/state-and-regular-expressions-in-javascript
  33. // http://jsperf.com/whitespace-character/5
  34. function isSpace(c) {
  35. return (c === "\u0020" || // space
  36. c === "\u0009" || // horizontal tab
  37. c === "\u000A" || // new line
  38. c === "\u000C" || // form feed
  39. c === "\u000D"); // carriage return
  40. }
  41. function collectCharacters(regEx) {
  42. var chars,
  43. match = regEx.exec(input.substring(pos));
  44. if (match) {
  45. chars = match[0];
  46. pos += chars.length;
  47. return chars;
  48. }
  49. }
  50. var inputLength = input.length,
  51. // (Don"t use \s, to avoid matching non-breaking space)
  52. /* eslint-disable no-control-regex */
  53. regexLeadingSpaces = /^[ \t\n\r\u000c]+/, //
  54. regexLeadingCommasOrSpaces = /^[, \t\n\r\u000c]+/,
  55. regexLeadingNotSpaces = /^[^ \t\n\r\u000c]+/,
  56. regexTrailingCommas = /[,]+$/,
  57. regexNonNegativeInteger = /^\d+$/,
  58. /* eslint-enable no-control-regex */
  59. // ( Positive or negative or unsigned integers or decimals, without or without exponents.
  60. // Must include at least one digit.
  61. // According to spec tests any decimal point must be followed by a digit.
  62. // No leading plus sign is allowed.)
  63. // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number
  64. regexFloatingPoint = /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/,
  65. url,
  66. descriptors,
  67. currentDescriptor,
  68. state,
  69. c,
  70. // 2. Let position be a pointer into input, initially pointing at the start
  71. // of the string.
  72. pos = 0,
  73. // 3. Let candidates be an initially empty source set.
  74. candidates = [];
  75. // 4. Splitting loop: Collect a sequence of characters that are space
  76. // characters or U+002C COMMA characters. If any U+002C COMMA characters
  77. // were collected, that is a parse error.
  78. while (true) { // eslint-disable-line no-constant-condition
  79. collectCharacters(regexLeadingCommasOrSpaces);
  80. // 5. If position is past the end of input, return candidates and abort these steps.
  81. if (pos >= inputLength) {
  82. return candidates; // (we"re done, this is the sole return path)
  83. }
  84. // 6. Collect a sequence of characters that are not space characters,
  85. // and let that be url.
  86. url = collectCharacters(regexLeadingNotSpaces);
  87. // 7. Let descriptors be a new empty list.
  88. descriptors = [];
  89. // 8. If url ends with a U+002C COMMA character (,), follow these substeps:
  90. // (1). Remove all trailing U+002C COMMA characters from url. If this removed
  91. // more than one character, that is a parse error.
  92. if (url.slice(-1) === ",") {
  93. url = url.replace(regexTrailingCommas, "");
  94. // (Jump ahead to step 9 to skip tokenization and just push the candidate).
  95. parseDescriptors();
  96. // Otherwise, follow these substeps:
  97. } else {
  98. tokenize();
  99. } // (close else of step 8)
  100. // 16. Return to the step labeled splitting loop.
  101. } // (Close of big while loop.)
  102. /**
  103. * Tokenizes descriptor properties prior to parsing
  104. * Returns undefined.
  105. */
  106. function tokenize() {
  107. // 8.1. Descriptor tokeniser: Skip whitespace
  108. collectCharacters(regexLeadingSpaces);
  109. // 8.2. Let current descriptor be the empty string.
  110. currentDescriptor = "";
  111. // 8.3. Let state be in descriptor.
  112. state = "in descriptor";
  113. while (true) { // eslint-disable-line no-constant-condition
  114. // 8.4. Let c be the character at position.
  115. c = input.charAt(pos);
  116. // Do the following depending on the value of state.
  117. // For the purpose of this step, "EOF" is a special character representing
  118. // that position is past the end of input.
  119. // In descriptor
  120. if (state === "in descriptor") {
  121. // Do the following, depending on the value of c:
  122. // Space character
  123. // If current descriptor is not empty, append current descriptor to
  124. // descriptors and let current descriptor be the empty string.
  125. // Set state to after descriptor.
  126. if (isSpace(c)) {
  127. if (currentDescriptor) {
  128. descriptors.push(currentDescriptor);
  129. currentDescriptor = "";
  130. state = "after descriptor";
  131. }
  132. // U+002C COMMA (,)
  133. // Advance position to the next character in input. If current descriptor
  134. // is not empty, append current descriptor to descriptors. Jump to the step
  135. // labeled descriptor parser.
  136. } else if (c === ",") {
  137. pos += 1;
  138. if (currentDescriptor) {
  139. descriptors.push(currentDescriptor);
  140. }
  141. parseDescriptors();
  142. return;
  143. // U+0028 LEFT PARENTHESIS (()
  144. // Append c to current descriptor. Set state to in parens.
  145. } else if (c === "\u0028") {
  146. currentDescriptor = currentDescriptor + c;
  147. state = "in parens";
  148. // EOF
  149. // If current descriptor is not empty, append current descriptor to
  150. // descriptors. Jump to the step labeled descriptor parser.
  151. } else if (c === "") {
  152. if (currentDescriptor) {
  153. descriptors.push(currentDescriptor);
  154. }
  155. parseDescriptors();
  156. return;
  157. // Anything else
  158. // Append c to current descriptor.
  159. } else {
  160. currentDescriptor = currentDescriptor + c;
  161. }
  162. // (end "in descriptor"
  163. // In parens
  164. } else if (state === "in parens") {
  165. // U+0029 RIGHT PARENTHESIS ())
  166. // Append c to current descriptor. Set state to in descriptor.
  167. if (c === ")") {
  168. currentDescriptor = currentDescriptor + c;
  169. state = "in descriptor";
  170. // EOF
  171. // Append current descriptor to descriptors. Jump to the step labeled
  172. // descriptor parser.
  173. } else if (c === "") {
  174. descriptors.push(currentDescriptor);
  175. parseDescriptors();
  176. return;
  177. // Anything else
  178. // Append c to current descriptor.
  179. } else {
  180. currentDescriptor = currentDescriptor + c;
  181. }
  182. // After descriptor
  183. } else if (state === "after descriptor") {
  184. // Do the following, depending on the value of c:
  185. // Space character: Stay in this state.
  186. if (isSpace(c)) {
  187. // EOF: Jump to the step labeled descriptor parser.
  188. } else if (c === "") {
  189. parseDescriptors();
  190. return;
  191. // Anything else
  192. // Set state to in descriptor. Set position to the previous character in input.
  193. } else {
  194. state = "in descriptor";
  195. pos -= 1;
  196. }
  197. }
  198. // Advance position to the next character in input.
  199. pos += 1;
  200. // Repeat this step.
  201. } // (close while true loop)
  202. }
  203. /**
  204. * Adds descriptor properties to a candidate, pushes to the candidates array
  205. * @return undefined
  206. */
  207. // Declared outside of the while loop so that it"s only created once.
  208. function parseDescriptors() {
  209. // 9. Descriptor parser: Let error be no.
  210. var pError = false,
  211. // 10. Let width be absent.
  212. // 11. Let density be absent.
  213. // 12. Let future-compat-h be absent. (We"re implementing it now as h)
  214. w, d, h, i,
  215. candidate = {},
  216. desc, lastChar, value, intVal, floatVal;
  217. // 13. For each descriptor in descriptors, run the appropriate set of steps
  218. // from the following list:
  219. for (i = 0; i < descriptors.length; i++) {
  220. desc = descriptors[i];
  221. lastChar = desc[desc.length - 1];
  222. value = desc.substring(0, desc.length - 1);
  223. intVal = parseInt(value, 10);
  224. floatVal = parseFloat(value);
  225. // If the descriptor consists of a valid non-negative integer followed by
  226. // a U+0077 LATIN SMALL LETTER W character
  227. if (regexNonNegativeInteger.test(value) && (lastChar === "w")) {
  228. // If width and density are not both absent, then let error be yes.
  229. if (w || d) { pError = true; }
  230. // Apply the rules for parsing non-negative integers to the descriptor.
  231. // If the result is zero, let error be yes.
  232. // Otherwise, let width be the result.
  233. if (intVal === 0) { pError = true; } else { w = intVal; }
  234. // If the descriptor consists of a valid floating-point number followed by
  235. // a U+0078 LATIN SMALL LETTER X character
  236. } else if (regexFloatingPoint.test(value) && (lastChar === "x")) {
  237. // If width, density and future-compat-h are not all absent, then let error
  238. // be yes.
  239. if (w || d || h) { pError = true; }
  240. // Apply the rules for parsing floating-point number values to the descriptor.
  241. // If the result is less than zero, let error be yes. Otherwise, let density
  242. // be the result.
  243. if (floatVal < 0) { pError = true; } else { d = floatVal; }
  244. // If the descriptor consists of a valid non-negative integer followed by
  245. // a U+0068 LATIN SMALL LETTER H character
  246. } else if (regexNonNegativeInteger.test(value) && (lastChar === "h")) {
  247. // If height and density are not both absent, then let error be yes.
  248. if (h || d) { pError = true; }
  249. // Apply the rules for parsing non-negative integers to the descriptor.
  250. // If the result is zero, let error be yes. Otherwise, let future-compat-h
  251. // be the result.
  252. if (intVal === 0) { pError = true; } else { h = intVal; }
  253. // Anything else, Let error be yes.
  254. } else { pError = true; }
  255. } // (close step 13 for loop)
  256. // 15. If error is still no, then append a new image source to candidates whose
  257. // URL is url, associated with a width width if not absent and a pixel
  258. // density density if not absent. Otherwise, there is a parse error.
  259. if (!pError) {
  260. candidate.url = url;
  261. if (w) { candidate.w = w; }
  262. if (d) { candidate.d = d; }
  263. if (h) { candidate.h = h; }
  264. candidates.push(candidate);
  265. } else if (console && console.log) { // eslint-disable-line no-console
  266. console.log("Invalid srcset descriptor found in \"" + input + "\" at \"" + desc + "\"."); // eslint-disable-line no-console
  267. }
  268. } // (close parseDescriptors fn)
  269. };
  270. }));