1
0

css-media-query-parser.js 14 KB

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