css-media-query-parser.js 14 KB

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