css-matched-rules.js 14 KB

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