css-matched-rules.js 13 KB

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