css-media-query-parser.js 14 KB

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