parse-srcset.js 10 KB

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