css-matched-rules.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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.matchedRules = this.matchedRules || (() => {
  24. const MEDIA_ALL = "all";
  25. const IGNORED_PSEUDO_ELEMENTS = ["after", "before", "first-letter", "first-line", "placeholder", "selection"];
  26. const REGEXP_VENDOR_IDENTIFIER = /-(ms|webkit|moz|o)-/;
  27. const DEBUG = false;
  28. let cssTree;
  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. const cssRules = stylesheetInfo.stylesheet.children;
  39. if (cssRules) {
  40. if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
  41. const mediaInfo = createMediaInfo(stylesheetInfo.mediaText);
  42. this.mediaAllInfo.medias.set("style-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaInfo);
  43. getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, styles, matchedElementsCache, workStyleElement);
  44. } else {
  45. getMatchedElementsRules(doc, cssRules, this.mediaAllInfo, sheetIndex, styles, matchedElementsCache, workStyleElement);
  46. }
  47. }
  48. sheetIndex++;
  49. });
  50. let startTime;
  51. if (DEBUG) {
  52. startTime = Date.now();
  53. log(" -- STARTED sortRules");
  54. }
  55. sortRules(this.mediaAllInfo);
  56. if (DEBUG) {
  57. log(" -- ENDED sortRules", Date.now() - startTime);
  58. startTime = Date.now();
  59. log(" -- STARTED computeCascade");
  60. }
  61. computeCascade(this.mediaAllInfo, [], this.mediaAllInfo, workStyleElement);
  62. workStyleElement.remove();
  63. if (DEBUG) {
  64. log(" -- ENDED computeCascade", Date.now() - startTime);
  65. }
  66. }
  67. getMediaAllInfo() {
  68. return this.mediaAllInfo;
  69. }
  70. }
  71. return {
  72. getInstance(...args) {
  73. [cssTree] = args;
  74. return {
  75. getMediaAllInfo(doc, stylesheets, styles) {
  76. return new MatchedRules(doc, stylesheets, styles).getMediaAllInfo();
  77. }
  78. };
  79. }
  80. };
  81. function createMediaInfo(media) {
  82. const mediaInfo = { media: media, elements: new Map(), medias: new Map(), rules: new Map(), pseudoRules: new Map() };
  83. if (media == MEDIA_ALL) {
  84. mediaInfo.matchedStyles = new Map();
  85. }
  86. return mediaInfo;
  87. }
  88. function getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, styles, matchedElementsCache, workStylesheet) {
  89. let mediaIndex = 0;
  90. let ruleIndex = 0;
  91. let startTime;
  92. if (DEBUG && cssRules.length > 1) {
  93. startTime = Date.now();
  94. log(" -- STARTED getMatchedElementsRules", " index =", sheetIndex, "rules.length =", cssRules.length);
  95. }
  96. cssRules.forEach(ruleData => {
  97. if (ruleData.block && ruleData.block.children && ruleData.prelude && ruleData.prelude.children) {
  98. if (ruleData.type == "Atrule" && ruleData.name == "media") {
  99. const mediaText = cssTree.generate(ruleData.prelude);
  100. const ruleMediaInfo = createMediaInfo(mediaText);
  101. mediaInfo.medias.set("rule-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, ruleMediaInfo);
  102. mediaIndex++;
  103. getMatchedElementsRules(doc, ruleData.block.children, ruleMediaInfo, sheetIndex, styles, matchedElementsCache, workStylesheet);
  104. } else if (ruleData.type == "Rule") {
  105. const selectors = ruleData.prelude.children.toArray();
  106. const selectorsText = ruleData.prelude.children.toArray().map(selector => cssTree.generate(selector));
  107. const ruleInfo = { ruleData, mediaInfo, ruleIndex, sheetIndex, matchedSelectors: new Set(), declarations: new Set(), selectors, selectorsText };
  108. if (!invalidSelector(selectorsText.join(","), workStylesheet)) {
  109. for (let selector = ruleData.prelude.children.head, selectorIndex = 0; selector; selector = selector.next, selectorIndex++) {
  110. const selectorText = selectorsText[selectorIndex];
  111. const selectorInfo = { selector, selectorText, ruleInfo };
  112. getMatchedElementsSelector(doc, selectorInfo, styles, matchedElementsCache);
  113. }
  114. }
  115. ruleIndex++;
  116. }
  117. }
  118. });
  119. if (DEBUG && cssRules.length > 1) {
  120. log(" -- ENDED getMatchedElementsRules", "delay =", Date.now() - startTime);
  121. }
  122. }
  123. function invalidSelector(selectorText, workStylesheet) {
  124. workStylesheet.textContent = selectorText + "{}";
  125. return !workStylesheet.sheet.cssRules.length;
  126. }
  127. function getMatchedElementsSelector(doc, selectorInfo, styles, matchedElementsCache) {
  128. let selectorText;
  129. const filteredSelectorText = getFilteredSelector(selectorInfo.selector, selectorInfo.selectorText);
  130. if (filteredSelectorText != selectorInfo.selectorText) {
  131. selectorText = filteredSelectorText;
  132. } else {
  133. selectorText = selectorInfo.selectorText;
  134. }
  135. const cachedMatchedElements = matchedElementsCache.get(selectorText);
  136. let matchedElements = cachedMatchedElements;
  137. if (!matchedElements) {
  138. try {
  139. matchedElements = doc.querySelectorAll(selectorText);
  140. } catch (error) {
  141. // ignored
  142. console.warn("(SingleFile) Invalid selector", selectorText); // eslint-disable-line no-console
  143. }
  144. }
  145. if (matchedElements) {
  146. if (!cachedMatchedElements) {
  147. matchedElementsCache.set(selectorText, matchedElements);
  148. }
  149. if (matchedElements.length) {
  150. if (filteredSelectorText == selectorInfo.selectorText) {
  151. matchedElements.forEach(element => addRule(element, selectorInfo, styles));
  152. } else {
  153. let pseudoSelectors = selectorInfo.ruleInfo.mediaInfo.pseudoRules.get(selectorInfo.ruleInfo.ruleData);
  154. if (!pseudoSelectors) {
  155. pseudoSelectors = new Set();
  156. selectorInfo.ruleInfo.mediaInfo.pseudoRules.set(selectorInfo.ruleInfo.ruleData, pseudoSelectors);
  157. }
  158. pseudoSelectors.add(selectorInfo.selectorText);
  159. }
  160. }
  161. }
  162. }
  163. function getFilteredSelector(selector, selectorText) {
  164. const removedSelectors = [];
  165. selector = { data: cssTree.parse(cssTree.generate(selector.data), { context: "selector" }) };
  166. filterPseudoClasses(selector);
  167. if (removedSelectors.length) {
  168. removedSelectors.forEach(({ parentSelector, selector }) => {
  169. if (parentSelector.data.children.getSize() == 0 || !selector.prev || selector.prev.data.type == "Combinator") {
  170. parentSelector.data.children.replace(selector, cssTree.parse("*", { context: "selector" }).children.head);
  171. } else {
  172. parentSelector.data.children.remove(selector);
  173. }
  174. });
  175. selectorText = cssTree.generate(selector.data).trim();
  176. }
  177. return selectorText;
  178. function filterPseudoClasses(selector, parentSelector) {
  179. if (selector.data.children) {
  180. for (let childSelector = selector.data.children.head; childSelector; childSelector = childSelector.next) {
  181. filterPseudoClasses(childSelector, selector);
  182. }
  183. }
  184. if ((selector.data.type == "PseudoClassSelector") ||
  185. (selector.data.type == "PseudoElementSelector" && (testVendorPseudo(selector) || IGNORED_PSEUDO_ELEMENTS.includes(selector.data.name)))) {
  186. removedSelectors.push({ parentSelector, selector });
  187. }
  188. }
  189. function testVendorPseudo(selector) {
  190. const name = selector.data.name;
  191. return name.startsWith("-") || name.startsWith("\\-");
  192. }
  193. }
  194. function addRule(element, selectorInfo, styles) {
  195. const mediaInfo = selectorInfo.ruleInfo.mediaInfo;
  196. const elementStyle = styles.get(element);
  197. let elementInfo = mediaInfo.elements.get(element);
  198. if (!elementInfo) {
  199. elementInfo = [];
  200. if (elementStyle) {
  201. elementInfo.push({ styleInfo: { styleData: elementStyle, declarations: new Set() } });
  202. }
  203. mediaInfo.elements.set(element, elementInfo);
  204. }
  205. const specificity = computeSpecificity(selectorInfo.selector.data);
  206. specificity.ruleIndex = selectorInfo.ruleInfo.ruleIndex;
  207. specificity.sheetIndex = selectorInfo.ruleInfo.sheetIndex;
  208. selectorInfo.specificity = specificity;
  209. elementInfo.push(selectorInfo);
  210. }
  211. function computeCascade(mediaInfo, parentMediaInfo, mediaAllInfo, workStylesheet) {
  212. mediaInfo.elements.forEach((elementInfo/*, element*/) =>
  213. getDeclarationsInfo(elementInfo, workStylesheet/*, element*/).forEach((declarationsInfo, property) => {
  214. if (declarationsInfo.selectorInfo.ruleInfo || mediaInfo == mediaAllInfo) {
  215. let info;
  216. if (declarationsInfo.selectorInfo.ruleInfo) {
  217. info = declarationsInfo.selectorInfo.ruleInfo;
  218. const ruleData = info.ruleData;
  219. const ascendantMedia = [mediaInfo, ...parentMediaInfo].find(media => media.rules.get(ruleData)) || mediaInfo;
  220. ascendantMedia.rules.set(ruleData, info);
  221. if (ruleData) {
  222. info.matchedSelectors.add(declarationsInfo.selectorInfo.selectorText);
  223. }
  224. } else {
  225. info = declarationsInfo.selectorInfo.styleInfo;
  226. const styleData = info.styleData;
  227. const matchedStyleInfo = mediaAllInfo.matchedStyles.get(styleData);
  228. if (!matchedStyleInfo) {
  229. mediaAllInfo.matchedStyles.set(styleData, info);
  230. }
  231. }
  232. if (!info.declarations.has(property)) {
  233. info.declarations.add(property);
  234. }
  235. }
  236. }));
  237. delete mediaInfo.elements;
  238. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfo], mediaAllInfo, workStylesheet));
  239. }
  240. function getDeclarationsInfo(elementInfo, workStylesheet/*, element*/) {
  241. const declarationsInfo = new Map();
  242. const processedProperties = new Set();
  243. elementInfo.forEach(selectorInfo => {
  244. let declarations;
  245. if (selectorInfo.styleInfo) {
  246. declarations = selectorInfo.styleInfo.styleData.children;
  247. } else {
  248. declarations = selectorInfo.ruleInfo.ruleData.block.children;
  249. }
  250. processDeclarations(declarationsInfo, declarations, selectorInfo, processedProperties, workStylesheet);
  251. });
  252. return declarationsInfo;
  253. }
  254. function processDeclarations(declarationsInfo, declarations, selectorInfo, processedProperties, workStylesheet) {
  255. for (let declaration = declarations.tail; declaration; declaration = declaration.prev) {
  256. const declarationData = declaration.data;
  257. const declarationText = cssTree.generate(declarationData);
  258. if (declarationData.type == "Declaration" &&
  259. (declarationText.match(REGEXP_VENDOR_IDENTIFIER) || !processedProperties.has(declarationData.property) || declarationData.important) && !invalidDeclaration(declarationText, workStylesheet)) {
  260. const declarationInfo = declarationsInfo.get(declarationData);
  261. if (!declarationInfo || (declarationData.important && !declarationInfo.important)) {
  262. declarationsInfo.set(declarationData, { selectorInfo, important: declarationData.important });
  263. if (!declarationText.match(REGEXP_VENDOR_IDENTIFIER)) {
  264. processedProperties.add(declarationData.property);
  265. }
  266. }
  267. }
  268. }
  269. }
  270. function invalidDeclaration(declarationText, workStylesheet) {
  271. let invalidDeclaration;
  272. workStylesheet.textContent = "single-file-declaration { " + declarationText + "}";
  273. if (!workStylesheet.sheet.cssRules[0].style.length) {
  274. if (!declarationText.match(REGEXP_VENDOR_IDENTIFIER)) {
  275. invalidDeclaration = true;
  276. }
  277. }
  278. return invalidDeclaration;
  279. }
  280. function sortRules(media) {
  281. media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
  282. ruleInfo1.styleInfo && !ruleInfo2.styleInfo ? -1 :
  283. !ruleInfo1.styleInfo && ruleInfo2.styleInfo ? 1 :
  284. compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
  285. media.medias.forEach(sortRules);
  286. }
  287. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  288. if (selector.type == "IdSelector") {
  289. specificity.a++;
  290. }
  291. if (selector.type == "ClassSelector" || selector.type == "AttributeSelector" || (selector.type == "PseudoClassSelector" && selector.name != "not")) {
  292. specificity.b++;
  293. }
  294. if ((selector.type == "TypeSelector" && selector.name != "*") || selector.type == "PseudoElementSelector") {
  295. specificity.c++;
  296. }
  297. if (selector.children) {
  298. selector.children.forEach(selector => computeSpecificity(selector, specificity));
  299. }
  300. return specificity;
  301. }
  302. function compareSpecificity(specificity1, specificity2) {
  303. if (specificity1.a > specificity2.a) {
  304. return -1;
  305. } else if (specificity1.a < specificity2.a) {
  306. return 1;
  307. } else if (specificity1.b > specificity2.b) {
  308. return -1;
  309. } else if (specificity1.b < specificity2.b) {
  310. return 1;
  311. } else if (specificity1.c > specificity2.c) {
  312. return -1;
  313. } else if (specificity1.c < specificity2.c) {
  314. return 1;
  315. } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
  316. return -1;
  317. } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
  318. return 1;
  319. } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
  320. return -1;
  321. } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
  322. return 1;
  323. } else {
  324. return -1;
  325. }
  326. }
  327. function log(...args) {
  328. console.log("S-File <css-mat>", ...args); // eslint-disable-line no-console
  329. }
  330. })();