html-srcset-parser.js 11 KB

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