css-media-query-parser.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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/dryoma/postcss-media-query-parser
  23. /*
  24. * The MIT License (MIT)
  25. *
  26. * Permission is hereby granted, free of charge, to any person obtaining a copy
  27. * of this software and associated documentation files (the "Software"), to deal
  28. * in the Software without restriction, including without limitation the rights
  29. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  30. * copies of the Software, and to permit persons to whom the Software is
  31. * furnished to do so, subject to the following conditions:
  32. *
  33. * The above copyright notice and this permission notice shall be included in
  34. * all copies or substantial portions of the Software.
  35. *
  36. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  39. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  42. * THE SOFTWARE.
  43. */
  44. this.singlefile.lib.vendor.mediaQueryParser = this.singlefile.lib.vendor.mediaQueryParser || (() => {
  45. /**
  46. * Parses a media feature expression, e.g. `max-width: 10px`, `(color)`
  47. *
  48. * @param {string} string - the source expression string, can be inside parens
  49. * @param {Number} index - the index of `string` in the overall input
  50. *
  51. * @return {Array} an array of Nodes, the first element being a media feature,
  52. * the second - its value (may be missing)
  53. */
  54. function parseMediaFeature(string, index = 0) {
  55. const modesEntered = [{
  56. mode: "normal",
  57. character: null,
  58. }];
  59. const result = [];
  60. let lastModeIndex = 0, mediaFeature = "", colon = null, mediaFeatureValue = null, indexLocal = index;
  61. let stringNormalized = string;
  62. // Strip trailing parens (if any), and correct the starting index
  63. if (string[0] === "(" && string[string.length - 1] === ")") {
  64. stringNormalized = string.substring(1, string.length - 1);
  65. indexLocal++;
  66. }
  67. for (let i = 0; i < stringNormalized.length; i++) {
  68. const character = stringNormalized[i];
  69. // If entering/exiting a string
  70. if (character === "'" || character === "\"") {
  71. if (modesEntered[lastModeIndex].isCalculationEnabled === true) {
  72. modesEntered.push({
  73. mode: "string",
  74. isCalculationEnabled: false,
  75. character,
  76. });
  77. lastModeIndex++;
  78. } else if (modesEntered[lastModeIndex].mode === "string" &&
  79. modesEntered[lastModeIndex].character === character &&
  80. stringNormalized[i - 1] !== "\\"
  81. ) {
  82. modesEntered.pop();
  83. lastModeIndex--;
  84. }
  85. }
  86. // If entering/exiting interpolation
  87. if (character === "{") {
  88. modesEntered.push({
  89. mode: "interpolation",
  90. isCalculationEnabled: true,
  91. });
  92. lastModeIndex++;
  93. } else if (character === "}") {
  94. modesEntered.pop();
  95. lastModeIndex--;
  96. }
  97. // If a : is met outside of a string, function call or interpolation, than
  98. // this : separates a media feature and a value
  99. if (modesEntered[lastModeIndex].mode === "normal" && character === ":") {
  100. const mediaFeatureValueStr = stringNormalized.substring(i + 1);
  101. mediaFeatureValue = {
  102. type: "value",
  103. before: /^(\s*)/.exec(mediaFeatureValueStr)[1],
  104. after: /(\s*)$/.exec(mediaFeatureValueStr)[1],
  105. value: mediaFeatureValueStr.trim(),
  106. };
  107. // +1 for the colon
  108. mediaFeatureValue.sourceIndex =
  109. mediaFeatureValue.before.length + i + 1 + indexLocal;
  110. colon = {
  111. type: "colon",
  112. sourceIndex: i + indexLocal,
  113. after: mediaFeatureValue.before,
  114. value: ":", // for consistency only
  115. };
  116. break;
  117. }
  118. mediaFeature += character;
  119. }
  120. // Forming a media feature node
  121. mediaFeature = {
  122. type: "media-feature",
  123. before: /^(\s*)/.exec(mediaFeature)[1],
  124. after: /(\s*)$/.exec(mediaFeature)[1],
  125. value: mediaFeature.trim(),
  126. };
  127. mediaFeature.sourceIndex = mediaFeature.before.length + indexLocal;
  128. result.push(mediaFeature);
  129. if (colon !== null) {
  130. colon.before = mediaFeature.after;
  131. result.push(colon);
  132. }
  133. if (mediaFeatureValue !== null) {
  134. result.push(mediaFeatureValue);
  135. }
  136. return result;
  137. }
  138. /**
  139. * Parses a media query, e.g. `screen and (color)`, `only tv`
  140. *
  141. * @param {string} string - the source media query string
  142. * @param {Number} index - the index of `string` in the overall input
  143. *
  144. * @return {Array} an array of Nodes and Containers
  145. */
  146. function parseMediaQuery(string, index = 0) {
  147. const result = [];
  148. // How many times the parser entered parens/curly braces
  149. let localLevel = 0;
  150. // Has any keyword, media type, media feature expression or interpolation
  151. // ('element' hereafter) started
  152. let insideSomeValue = false, node;
  153. function resetNode() {
  154. return {
  155. before: "",
  156. after: "",
  157. value: "",
  158. };
  159. }
  160. node = resetNode();
  161. for (let i = 0; i < string.length; i++) {
  162. const character = string[i];
  163. // If not yet entered any element
  164. if (!insideSomeValue) {
  165. if (character.search(/\s/) !== -1) {
  166. // A whitespace
  167. // Don't form 'after' yet; will do it later
  168. node.before += character;
  169. } else {
  170. // Not a whitespace - entering an element
  171. // Expression start
  172. if (character === "(") {
  173. node.type = "media-feature-expression";
  174. localLevel++;
  175. }
  176. node.value = character;
  177. node.sourceIndex = index + i;
  178. insideSomeValue = true;
  179. }
  180. } else {
  181. // Already in the middle of some element
  182. node.value += character;
  183. // Here parens just increase localLevel and don't trigger a start of
  184. // a media feature expression (since they can't be nested)
  185. // Interpolation start
  186. if (character === "{" || character === "(") { localLevel++; }
  187. // Interpolation/function call/media feature expression end
  188. if (character === ")" || character === "}") { localLevel--; }
  189. }
  190. // If exited all parens/curlies and the next symbol
  191. if (insideSomeValue && localLevel === 0 &&
  192. (character === ")" || i === string.length - 1 ||
  193. string[i + 1].search(/\s/) !== -1)
  194. ) {
  195. if (["not", "only", "and"].indexOf(node.value) !== -1) {
  196. node.type = "keyword";
  197. }
  198. // if it's an expression, parse its contents
  199. if (node.type === "media-feature-expression") {
  200. node.nodes = parseMediaFeature(node.value, node.sourceIndex);
  201. }
  202. result.push(Array.isArray(node.nodes) ?
  203. new Container(node) : new Node(node));
  204. node = resetNode();
  205. insideSomeValue = false;
  206. }
  207. }
  208. // Now process the result array - to specify undefined types of the nodes
  209. // and specify the `after` prop
  210. for (let i = 0; i < result.length; i++) {
  211. node = result[i];
  212. if (i > 0) { result[i - 1].after = node.before; }
  213. // Node types. Might not be set because contains interpolation/function
  214. // calls or fully consists of them
  215. if (node.type === undefined) {
  216. if (i > 0) {
  217. // only `and` can follow an expression
  218. if (result[i - 1].type === "media-feature-expression") {
  219. node.type = "keyword";
  220. continue;
  221. }
  222. // Anything after 'only|not' is a media type
  223. if (result[i - 1].value === "not" || result[i - 1].value === "only") {
  224. node.type = "media-type";
  225. continue;
  226. }
  227. // Anything after 'and' is an expression
  228. if (result[i - 1].value === "and") {
  229. node.type = "media-feature-expression";
  230. continue;
  231. }
  232. if (result[i - 1].type === "media-type") {
  233. // if it is the last element - it might be an expression
  234. // or 'and' depending on what is after it
  235. if (!result[i + 1]) {
  236. node.type = "media-feature-expression";
  237. } else {
  238. node.type = result[i + 1].type === "media-feature-expression" ?
  239. "keyword" : "media-feature-expression";
  240. }
  241. }
  242. }
  243. if (i === 0) {
  244. // `screen`, `fn( ... )`, `#{ ... }`. Not an expression, since then
  245. // its type would have been set by now
  246. if (!result[i + 1]) {
  247. node.type = "media-type";
  248. continue;
  249. }
  250. // `screen and` or `#{...} (max-width: 10px)`
  251. if (result[i + 1] &&
  252. (result[i + 1].type === "media-feature-expression" ||
  253. result[i + 1].type === "keyword")
  254. ) {
  255. node.type = "media-type";
  256. continue;
  257. }
  258. if (result[i + 2]) {
  259. // `screen and (color) ...`
  260. if (result[i + 2].type === "media-feature-expression") {
  261. node.type = "media-type";
  262. result[i + 1].type = "keyword";
  263. continue;
  264. }
  265. // `only screen and ...`
  266. if (result[i + 2].type === "keyword") {
  267. node.type = "keyword";
  268. result[i + 1].type = "media-type";
  269. continue;
  270. }
  271. }
  272. if (result[i + 3]) {
  273. // `screen and (color) ...`
  274. if (result[i + 3].type === "media-feature-expression") {
  275. node.type = "keyword";
  276. result[i + 1].type = "media-type";
  277. result[i + 2].type = "keyword";
  278. continue;
  279. }
  280. }
  281. }
  282. }
  283. }
  284. return result;
  285. }
  286. /**
  287. * Parses a media query list. Takes a possible `url()` at the start into
  288. * account, and divides the list into media queries that are parsed separately
  289. *
  290. * @param {string} string - the source media query list string
  291. *
  292. * @return {Array} an array of Nodes/Containers
  293. */
  294. function parseMediaList(string) {
  295. const result = [];
  296. let interimIndex = 0, levelLocal = 0;
  297. // Check for a `url(...)` part (if it is contents of an @import rule)
  298. const doesHaveUrl = /^(\s*)url\s*\(/.exec(string);
  299. if (doesHaveUrl !== null) {
  300. let i = doesHaveUrl[0].length;
  301. let parenthesesLv = 1;
  302. while (parenthesesLv > 0) {
  303. const character = string[i];
  304. if (character === "(") { parenthesesLv++; }
  305. if (character === ")") { parenthesesLv--; }
  306. i++;
  307. }
  308. result.unshift(new Node({
  309. type: "url",
  310. value: string.substring(0, i).trim(),
  311. sourceIndex: doesHaveUrl[1].length,
  312. before: doesHaveUrl[1],
  313. after: /^(\s*)/.exec(string.substring(i))[1],
  314. }));
  315. interimIndex = i;
  316. }
  317. // Start processing the media query list
  318. for (let i = interimIndex; i < string.length; i++) {
  319. const character = string[i];
  320. // Dividing the media query list into comma-separated media queries
  321. // Only count commas that are outside of any parens
  322. // (i.e., not part of function call params list, etc.)
  323. if (character === "(") { levelLocal++; }
  324. if (character === ")") { levelLocal--; }
  325. if (levelLocal === 0 && character === ",") {
  326. const mediaQueryString = string.substring(interimIndex, i);
  327. const spaceBefore = /^(\s*)/.exec(mediaQueryString)[1];
  328. result.push(new Container({
  329. type: "media-query",
  330. value: mediaQueryString.trim(),
  331. sourceIndex: interimIndex + spaceBefore.length,
  332. nodes: parseMediaQuery(mediaQueryString, interimIndex),
  333. before: spaceBefore,
  334. after: /(\s*)$/.exec(mediaQueryString)[1],
  335. }));
  336. interimIndex = i + 1;
  337. }
  338. }
  339. const mediaQueryString = string.substring(interimIndex);
  340. const spaceBefore = /^(\s*)/.exec(mediaQueryString)[1];
  341. result.push(new Container({
  342. type: "media-query",
  343. value: mediaQueryString.trim(),
  344. sourceIndex: interimIndex + spaceBefore.length,
  345. nodes: parseMediaQuery(mediaQueryString, interimIndex),
  346. before: spaceBefore,
  347. after: /(\s*)$/.exec(mediaQueryString)[1],
  348. }));
  349. return result;
  350. }
  351. function Container(opts) {
  352. this.constructor(opts);
  353. this.nodes = opts.nodes;
  354. if (this.after === undefined) {
  355. this.after = this.nodes.length > 0 ?
  356. this.nodes[this.nodes.length - 1].after : "";
  357. }
  358. if (this.before === undefined) {
  359. this.before = this.nodes.length > 0 ?
  360. this.nodes[0].before : "";
  361. }
  362. if (this.sourceIndex === undefined) {
  363. this.sourceIndex = this.before.length;
  364. }
  365. this.nodes.forEach(node => {
  366. node.parent = this; // eslint-disable-line no-param-reassign
  367. });
  368. }
  369. Container.prototype = Object.create(Node.prototype);
  370. Container.constructor = Node;
  371. /**
  372. * Iterate over descendant nodes of the node
  373. *
  374. * @param {RegExp|string} filter - Optional. Only nodes with node.type that
  375. * satisfies the filter will be traversed over
  376. * @param {function} cb - callback to call on each node. Takes these params:
  377. * node - the node being processed, i - it's index, nodes - the array
  378. * of all nodes
  379. * If false is returned, the iteration breaks
  380. *
  381. * @return (boolean) false, if the iteration was broken
  382. */
  383. Container.prototype.walk = function walk(filter, cb) {
  384. const hasFilter = typeof filter === "string" || filter instanceof RegExp;
  385. const callback = hasFilter ? cb : filter;
  386. const filterReg = typeof filter === "string" ? new RegExp(filter) : filter;
  387. for (let i = 0; i < this.nodes.length; i++) {
  388. const node = this.nodes[i];
  389. const filtered = hasFilter ? filterReg.test(node.type) : true;
  390. if (filtered && callback && callback(node, i, this.nodes) === false) {
  391. return false;
  392. }
  393. if (node.nodes && node.walk(filter, cb) === false) { return false; }
  394. }
  395. return true;
  396. };
  397. /**
  398. * Iterate over immediate children of the node
  399. *
  400. * @param {function} cb - callback to call on each node. Takes these params:
  401. * node - the node being processed, i - it's index, nodes - the array
  402. * of all nodes
  403. * If false is returned, the iteration breaks
  404. *
  405. * @return (boolean) false, if the iteration was broken
  406. */
  407. Container.prototype.each = function each(cb = () => { }) {
  408. for (let i = 0; i < this.nodes.length; i++) {
  409. const node = this.nodes[i];
  410. if (cb(node, i, this.nodes) === false) { return false; }
  411. }
  412. return true;
  413. };
  414. /**
  415. * A very generic node. Pretty much any element of a media query
  416. */
  417. function Node(opts) {
  418. this.after = opts.after;
  419. this.before = opts.before;
  420. this.type = opts.type;
  421. this.value = opts.value;
  422. this.sourceIndex = opts.sourceIndex;
  423. }
  424. return {
  425. parseMediaList
  426. };
  427. })();