html-srcset-parser.js 11 KB

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