css-matched-rules.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. this.singlefile.lib.modules.matchedRules = this.singlefile.lib.modules.matchedRules || (() => {
  24. const singlefile = this.singlefile;
  25. const MEDIA_ALL = "all";
  26. const IGNORED_PSEUDO_ELEMENTS = ["after", "before", "first-letter", "first-line", "placeholder", "selection"];
  27. const REGEXP_VENDOR_IDENTIFIER = /-(ms|webkit|moz|o)-/;
  28. const DEBUG = false;
  29. class MatchedRules {
  30. constructor(doc, stylesheets, styles) {
  31. this.doc = doc;
  32. this.mediaAllInfo = createMediaInfo(MEDIA_ALL);
  33. const matchedElementsCache = new Map();
  34. let sheetIndex = 0;
  35. const workStyleElement = doc.createElement("style");
  36. doc.body.appendChild(workStyleElement);
  37. stylesheets.forEach(stylesheetInfo => {
  38. if (!stylesheetInfo.scoped) {
  39. const cssRules = stylesheetInfo.stylesheet.children;
  40. if (cssRules) {
  41. if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
  42. const mediaInfo = createMediaInfo(stylesheetInfo.mediaText);
  43. this.mediaAllInfo.medias.set("style-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaInfo);
  44. getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, styles, matchedElementsCache, workStyleElement);
  45. } else {
  46. getMatchedElementsRules(doc, cssRules, this.mediaAllInfo, sheetIndex, styles, matchedElementsCache, workStyleElement);
  47. }
  48. }
  49. }
  50. sheetIndex++;
  51. });
  52. let startTime;
  53. if (DEBUG) {
  54. startTime = Date.now();
  55. log(" -- STARTED sortRules");
  56. }
  57. sortRules(this.mediaAllInfo);
  58. if (DEBUG) {
  59. log(" -- ENDED sortRules", Date.now() - startTime);
  60. startTime = Date.now();
  61. log(" -- STARTED computeCascade");
  62. }
  63. computeCascade(this.mediaAllInfo, [], this.mediaAllInfo, workStyleElement);
  64. workStyleElement.remove();
  65. if (DEBUG) {
  66. log(" -- ENDED computeCascade", Date.now() - startTime);
  67. }
  68. }
  69. getMediaAllInfo() {
  70. return this.mediaAllInfo;
  71. }
  72. }
  73. return {
  74. getMediaAllInfo(doc, stylesheets, styles) {
  75. return new MatchedRules(doc, stylesheets, styles).getMediaAllInfo();
  76. }
  77. };
  78. function createMediaInfo(media) {
  79. const mediaInfo = { media: media, elements: new Map(), medias: new Map(), rules: new Map(), pseudoRules: new Map() };
  80. if (media == MEDIA_ALL) {
  81. mediaInfo.matchedStyles = new Map();
  82. }
  83. return mediaInfo;
  84. }
  85. function getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, styles, matchedElementsCache, workStylesheet) {
  86. const cssTree = singlefile.lib.vendor.cssTree;
  87. let mediaIndex = 0;
  88. let ruleIndex = 0;
  89. let startTime;
  90. if (DEBUG && cssRules.length > 1) {
  91. startTime = Date.now();
  92. log(" -- STARTED getMatchedElementsRules", " index =", sheetIndex, "rules.length =", cssRules.length);
  93. }
  94. cssRules.forEach(ruleData => {
  95. if (ruleData.block && ruleData.block.children && ruleData.prelude && ruleData.prelude.children) {
  96. if (ruleData.type == "Atrule" && ruleData.name == "media") {
  97. const mediaText = cssTree.generate(ruleData.prelude);
  98. const ruleMediaInfo = createMediaInfo(mediaText);
  99. mediaInfo.medias.set("rule-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, ruleMediaInfo);
  100. mediaIndex++;
  101. getMatchedElementsRules(doc, ruleData.block.children, ruleMediaInfo, sheetIndex, styles, matchedElementsCache, workStylesheet);
  102. } else if (ruleData.type == "Rule") {
  103. const selectors = ruleData.prelude.children.toArray();
  104. const selectorsText = ruleData.prelude.children.toArray().map(selector => cssTree.generate(selector));
  105. const ruleInfo = { ruleData, mediaInfo, ruleIndex, sheetIndex, matchedSelectors: new Set(), declarations: new Set(), selectors, selectorsText };
  106. if (!invalidSelector(selectorsText.join(","), workStylesheet)) {
  107. for (let selector = ruleData.prelude.children.head, selectorIndex = 0; selector; selector = selector.next, selectorIndex++) {
  108. const selectorText = selectorsText[selectorIndex];
  109. const selectorInfo = { selector, selectorText, ruleInfo };
  110. getMatchedElementsSelector(doc, selectorInfo, styles, matchedElementsCache);
  111. }
  112. }
  113. ruleIndex++;
  114. }
  115. }
  116. });
  117. if (DEBUG && cssRules.length > 1) {
  118. log(" -- ENDED getMatchedElementsRules", "delay =", Date.now() - startTime);
  119. }
  120. }
  121. function invalidSelector(selectorText, workStylesheet) {
  122. workStylesheet.textContent = selectorText + "{}";
  123. return !workStylesheet.sheet.cssRules.length;
  124. }
  125. function getMatchedElementsSelector(doc, selectorInfo, styles, matchedElementsCache) {
  126. const filteredSelectorText = getFilteredSelector(selectorInfo.selector, selectorInfo.selectorText);
  127. const selectorText = filteredSelectorText != selectorInfo.selectorText ? filteredSelectorText : selectorInfo.selectorText;
  128. const cachedMatchedElements = matchedElementsCache.get(selectorText);
  129. let matchedElements = cachedMatchedElements;
  130. if (!matchedElements) {
  131. try {
  132. matchedElements = doc.querySelectorAll(selectorText);
  133. } catch (error) {
  134. // ignored
  135. }
  136. }
  137. if (matchedElements) {
  138. if (!cachedMatchedElements) {
  139. matchedElementsCache.set(selectorText, matchedElements);
  140. }
  141. if (matchedElements.length) {
  142. if (filteredSelectorText == selectorInfo.selectorText) {
  143. matchedElements.forEach(element => addRule(element, selectorInfo, styles));
  144. } else {
  145. let pseudoSelectors = selectorInfo.ruleInfo.mediaInfo.pseudoRules.get(selectorInfo.ruleInfo.ruleData);
  146. if (!pseudoSelectors) {
  147. pseudoSelectors = new Set();
  148. selectorInfo.ruleInfo.mediaInfo.pseudoRules.set(selectorInfo.ruleInfo.ruleData, pseudoSelectors);
  149. }
  150. pseudoSelectors.add(selectorInfo.selectorText);
  151. }
  152. }
  153. }
  154. }
  155. function getFilteredSelector(selector, selectorText) {
  156. const cssTree = singlefile.lib.vendor.cssTree;
  157. const removedSelectors = [];
  158. selector = { data: cssTree.parse(cssTree.generate(selector.data), { context: "selector" }) };
  159. filterPseudoClasses(selector);
  160. if (removedSelectors.length) {
  161. removedSelectors.forEach(({ parentSelector, selector }) => {
  162. if (parentSelector.data.children.getSize() == 0 || !selector.prev || selector.prev.data.type == "Combinator" || selector.prev.data.type == "WhiteSpace") {
  163. parentSelector.data.children.replace(selector, cssTree.parse("*", { context: "selector" }).children.head);
  164. } else {
  165. parentSelector.data.children.remove(selector);
  166. }
  167. });
  168. selectorText = cssTree.generate(selector.data).trim();
  169. }
  170. return selectorText;
  171. function filterPseudoClasses(selector, parentSelector) {
  172. if (selector.data.children) {
  173. for (let childSelector = selector.data.children.head; childSelector; childSelector = childSelector.next) {
  174. filterPseudoClasses(childSelector, selector);
  175. }
  176. }
  177. if ((selector.data.type == "PseudoClassSelector") ||
  178. (selector.data.type == "PseudoElementSelector" && (testVendorPseudo(selector) || IGNORED_PSEUDO_ELEMENTS.includes(selector.data.name)))) {
  179. removedSelectors.push({ parentSelector, selector });
  180. }
  181. }
  182. function testVendorPseudo(selector) {
  183. const name = selector.data.name;
  184. return name.startsWith("-") || name.startsWith("\\-");
  185. }
  186. }
  187. function addRule(element, selectorInfo, styles) {
  188. const mediaInfo = selectorInfo.ruleInfo.mediaInfo;
  189. const elementStyle = styles.get(element);
  190. let elementInfo = mediaInfo.elements.get(element);
  191. if (!elementInfo) {
  192. elementInfo = [];
  193. if (elementStyle) {
  194. elementInfo.push({ styleInfo: { styleData: elementStyle, declarations: new Set() } });
  195. }
  196. mediaInfo.elements.set(element, elementInfo);
  197. }
  198. const specificity = computeSpecificity(selectorInfo.selector.data);
  199. specificity.ruleIndex = selectorInfo.ruleInfo.ruleIndex;
  200. specificity.sheetIndex = selectorInfo.ruleInfo.sheetIndex;
  201. selectorInfo.specificity = specificity;
  202. elementInfo.push(selectorInfo);
  203. }
  204. function computeCascade(mediaInfo, parentMediaInfo, mediaAllInfo, workStylesheet) {
  205. mediaInfo.elements.forEach((elementInfo/*, element*/) =>
  206. getDeclarationsInfo(elementInfo, workStylesheet/*, element*/).forEach((declarationsInfo, property) => {
  207. if (declarationsInfo.selectorInfo.ruleInfo || mediaInfo == mediaAllInfo) {
  208. let info;
  209. if (declarationsInfo.selectorInfo.ruleInfo) {
  210. info = declarationsInfo.selectorInfo.ruleInfo;
  211. const ruleData = info.ruleData;
  212. const ascendantMedia = [mediaInfo, ...parentMediaInfo].find(media => media.rules.get(ruleData)) || mediaInfo;
  213. ascendantMedia.rules.set(ruleData, info);
  214. if (ruleData) {
  215. info.matchedSelectors.add(declarationsInfo.selectorInfo.selectorText);
  216. }
  217. } else {
  218. info = declarationsInfo.selectorInfo.styleInfo;
  219. const styleData = info.styleData;
  220. const matchedStyleInfo = mediaAllInfo.matchedStyles.get(styleData);
  221. if (!matchedStyleInfo) {
  222. mediaAllInfo.matchedStyles.set(styleData, info);
  223. }
  224. }
  225. if (!info.declarations.has(property)) {
  226. info.declarations.add(property);
  227. }
  228. }
  229. }));
  230. delete mediaInfo.elements;
  231. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfo], mediaAllInfo, workStylesheet));
  232. }
  233. function getDeclarationsInfo(elementInfo, workStylesheet/*, element*/) {
  234. const declarationsInfo = new Map();
  235. const processedProperties = new Set();
  236. elementInfo.forEach(selectorInfo => {
  237. let declarations;
  238. if (selectorInfo.styleInfo) {
  239. declarations = selectorInfo.styleInfo.styleData.children;
  240. } else {
  241. declarations = selectorInfo.ruleInfo.ruleData.block.children;
  242. }
  243. processDeclarations(declarationsInfo, declarations, selectorInfo, processedProperties, workStylesheet);
  244. });
  245. return declarationsInfo;
  246. }
  247. function processDeclarations(declarationsInfo, declarations, selectorInfo, processedProperties, workStylesheet) {
  248. const cssTree = singlefile.lib.vendor.cssTree;
  249. for (let declaration = declarations.tail; declaration; declaration = declaration.prev) {
  250. const declarationData = declaration.data;
  251. const declarationText = cssTree.generate(declarationData);
  252. if (declarationData.type == "Declaration" &&
  253. (declarationText.match(REGEXP_VENDOR_IDENTIFIER) || !processedProperties.has(declarationData.property) || declarationData.important) && !invalidDeclaration(declarationText, workStylesheet)) {
  254. const declarationInfo = declarationsInfo.get(declarationData);
  255. if (!declarationInfo || (declarationData.important && !declarationInfo.important)) {
  256. declarationsInfo.set(declarationData, { selectorInfo, important: declarationData.important });
  257. if (!declarationText.match(REGEXP_VENDOR_IDENTIFIER)) {
  258. processedProperties.add(declarationData.property);
  259. }
  260. }
  261. }
  262. }
  263. }
  264. function invalidDeclaration(declarationText, workStylesheet) {
  265. let invalidDeclaration;
  266. workStylesheet.textContent = "single-file-declaration { " + declarationText + "}";
  267. if (!workStylesheet.sheet.cssRules[0].style.length) {
  268. if (!declarationText.match(REGEXP_VENDOR_IDENTIFIER)) {
  269. invalidDeclaration = true;
  270. }
  271. }
  272. return invalidDeclaration;
  273. }
  274. function sortRules(media) {
  275. media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
  276. ruleInfo1.styleInfo && !ruleInfo2.styleInfo ? -1 :
  277. !ruleInfo1.styleInfo && ruleInfo2.styleInfo ? 1 :
  278. compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
  279. media.medias.forEach(sortRules);
  280. }
  281. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  282. if (selector.type == "IdSelector") {
  283. specificity.a++;
  284. }
  285. if (selector.type == "ClassSelector" || selector.type == "AttributeSelector" || (selector.type == "PseudoClassSelector" && selector.name != "not")) {
  286. specificity.b++;
  287. }
  288. if ((selector.type == "TypeSelector" && selector.name != "*") || selector.type == "PseudoElementSelector") {
  289. specificity.c++;
  290. }
  291. if (selector.children) {
  292. selector.children.forEach(selector => computeSpecificity(selector, specificity));
  293. }
  294. return specificity;
  295. }
  296. function compareSpecificity(specificity1, specificity2) {
  297. if (specificity1.a > specificity2.a) {
  298. return -1;
  299. } else if (specificity1.a < specificity2.a) {
  300. return 1;
  301. } else if (specificity1.b > specificity2.b) {
  302. return -1;
  303. } else if (specificity1.b < specificity2.b) {
  304. return 1;
  305. } else if (specificity1.c > specificity2.c) {
  306. return -1;
  307. } else if (specificity1.c < specificity2.c) {
  308. return 1;
  309. } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
  310. return -1;
  311. } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
  312. return 1;
  313. } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
  314. return -1;
  315. } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
  316. return 1;
  317. } else {
  318. return -1;
  319. }
  320. }
  321. function log(...args) {
  322. console.log("S-File <css-mat>", ...args); // eslint-disable-line no-console
  323. }
  324. })();