css-matched-rules.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /*
  2. * Copyright 2018 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. /* global cssTree */
  21. this.matchedRules = this.matchedRules || (() => {
  22. const MEDIA_ALL = "all";
  23. const IGNORED_PSEUDO_ELEMENTS = ["after", "before", "first-letter", "first-line", "selection"];
  24. const REGEXP_VENDOR_IDENTIFIER = /-(ms|webkit|moz|o)-/;
  25. const DEBUG = false;
  26. class MatchedRules {
  27. constructor(doc, docStyle) {
  28. this.doc = doc;
  29. this.mediaAllInfo = createMediaInfo(MEDIA_ALL);
  30. const matchedElementsCache = new Map();
  31. let sheetIndex = 0;
  32. const styleElement = doc.createElement("style");
  33. doc.body.appendChild(styleElement);
  34. docStyle.stylesheets.forEach(stylesheetInfo => {
  35. if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
  36. const mediaInfo = createMediaInfo(stylesheetInfo.mediaText);
  37. this.mediaAllInfo.medias.set("style-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaInfo);
  38. getMatchedElementsRules(doc, stylesheetInfo.stylesheet.children, mediaInfo, sheetIndex, docStyle, matchedElementsCache, styleElement.sheet);
  39. } else {
  40. getMatchedElementsRules(doc, stylesheetInfo.stylesheet.children, this.mediaAllInfo, sheetIndex, docStyle, matchedElementsCache, styleElement.sheet);
  41. }
  42. sheetIndex++;
  43. });
  44. let startTime;
  45. if (DEBUG) {
  46. startTime = Date.now();
  47. log(" -- STARTED sortRules");
  48. }
  49. sortRules(this.mediaAllInfo);
  50. if (DEBUG) {
  51. log(" -- ENDED sortRules", Date.now() - startTime);
  52. startTime = Date.now();
  53. log(" -- STARTED computeCascade");
  54. }
  55. computeCascade(this.mediaAllInfo, [], this.mediaAllInfo, styleElement.sheet);
  56. styleElement.remove();
  57. if (DEBUG) {
  58. log(" -- ENDED computeCascade", Date.now() - startTime);
  59. }
  60. }
  61. getMediaAllInfo() {
  62. return this.mediaAllInfo;
  63. }
  64. }
  65. return {
  66. getMediaAllInfo(doc, docStyle) {
  67. return new MatchedRules(doc, docStyle).getMediaAllInfo();
  68. }
  69. };
  70. function createMediaInfo(media) {
  71. const mediaInfo = { media: media, elements: new Map(), pseudos: new Map(), medias: new Map(), rules: new Map(), pseudoRules: new Map() };
  72. if (media == MEDIA_ALL) {
  73. mediaInfo.matchedStyles = new Map();
  74. }
  75. return mediaInfo;
  76. }
  77. function getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, docStyle, matchedElementsCache, stylesheet) {
  78. let mediaIndex = 0;
  79. let ruleIndex = 0;
  80. let startTime;
  81. if (DEBUG && cssRules.length > 1) {
  82. startTime = Date.now();
  83. log(" -- STARTED getMatchedElementsRules", " index =", sheetIndex, "rules.length =", cssRules.length);
  84. }
  85. cssRules.forEach(cssRule => {
  86. if (cssRule.block && cssRule.block.children && cssRule.prelude && cssRule.prelude.children) {
  87. if (cssRule.type == "Atrule" && cssRule.name == "media") {
  88. const mediaText = cssTree.generate(cssRule.prelude);
  89. const ruleMediaInfo = createMediaInfo(mediaText);
  90. mediaInfo.medias.set("rule-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, ruleMediaInfo);
  91. mediaIndex++;
  92. getMatchedElementsRules(doc, cssRule.block.children, ruleMediaInfo, sheetIndex, docStyle, matchedElementsCache, stylesheet);
  93. } else if (cssRule.type == "Rule" && cssRule.prelude.children) {
  94. const selectors = cssRule.prelude.children.toArray();
  95. const selectorsText = cssRule.prelude.children.toArray().map(selector => cssTree.generate(selector));
  96. const ruleInfo = { cssRule, mediaInfo, ruleIndex, sheetIndex, matchedSelectors: new Set(), style: new Map(), selectors, selectorsText };
  97. if (!invalidSelector(selectorsText.join(","), stylesheet)) {
  98. for (let selector = cssRule.prelude.children.head, selectorIndex = 0; selector; selector = selector.next, selectorIndex++) {
  99. const selectorText = selectorsText[selectorIndex];
  100. const selectorInfo = { selector, selectorText, ruleInfo };
  101. getMatchedElementsSelector(doc, selectorInfo, docStyle, matchedElementsCache);
  102. }
  103. }
  104. ruleIndex++;
  105. }
  106. }
  107. });
  108. if (DEBUG && cssRules.length > 1) {
  109. log(" -- ENDED getMatchedElementsRules", "delay =", Date.now() - startTime);
  110. }
  111. }
  112. function invalidSelector(selectorText, stylesheet) {
  113. let invalidSelector;
  114. try {
  115. stylesheet.insertRule(selectorText + "{}");
  116. stylesheet.deleteRule(0);
  117. } catch (error) {
  118. if (!selectorText.match(REGEXP_VENDOR_IDENTIFIER)) {
  119. invalidSelector = true;
  120. }
  121. }
  122. return invalidSelector;
  123. }
  124. function getMatchedElementsSelector(doc, selectorInfo, docStyle, 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, docStyle.styles));
  150. } else {
  151. let pseudoSelectors = selectorInfo.ruleInfo.mediaInfo.pseudoRules.get(selectorInfo.ruleInfo.cssRule);
  152. if (!pseudoSelectors) {
  153. pseudoSelectors = new Set();
  154. selectorInfo.ruleInfo.mediaInfo.pseudoRules.set(selectorInfo.ruleInfo.cssRule, pseudoSelectors);
  155. }
  156. pseudoSelectors.add(selectorInfo.selectorText);
  157. matchedElements.forEach(element => addPseudoRule(element, selectorInfo));
  158. }
  159. }
  160. }
  161. }
  162. function getFilteredSelector(selector) {
  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") {
  169. parentSelector.data.children.replace(selector, cssTree.parse("*", { context: "selector" }).children.head);
  170. } else {
  171. parentSelector.data.children.remove(selector);
  172. }
  173. });
  174. }
  175. const selectorText = cssTree.generate(selector.data).trim();
  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: { cssStyle: elementStyle, style: new Map() } });
  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 addPseudoRule(element, selectorInfo) {
  211. let elementInfo = selectorInfo.ruleInfo.mediaInfo.pseudos.get(element);
  212. if (!elementInfo) {
  213. elementInfo = [];
  214. selectorInfo.ruleInfo.mediaInfo.pseudos.set(element, elementInfo);
  215. }
  216. elementInfo.push(selectorInfo);
  217. }
  218. function computeCascade(mediaInfo, parentMediaInfo, mediaAllInfo, stylesheet) {
  219. mediaInfo.elements.forEach((elementInfo, element) => getStylesInfo(elementInfo, stylesheet, element).forEach((declarations, property) => {
  220. if (declarations.selectorInfo.ruleInfo || mediaInfo == mediaAllInfo) {
  221. let info;
  222. if (declarations.selectorInfo.ruleInfo) {
  223. info = declarations.selectorInfo.ruleInfo;
  224. const cssRule = info.cssRule;
  225. const ascendantMedia = [mediaInfo, ...parentMediaInfo].find(media => media.rules.get(cssRule)) || mediaInfo;
  226. ascendantMedia.rules.set(cssRule, info);
  227. if (cssRule) {
  228. info.matchedSelectors.add(declarations.selectorInfo.selectorText);
  229. }
  230. } else {
  231. info = declarations.selectorInfo.styleInfo;
  232. const cssStyle = info.cssStyle;
  233. const matchedStyleInfo = mediaAllInfo.matchedStyles.get(cssStyle);
  234. if (!matchedStyleInfo) {
  235. mediaAllInfo.matchedStyles.set(cssStyle, info);
  236. }
  237. }
  238. const styleValue = info.style.get(property);
  239. if (!styleValue) {
  240. info.style.set(property, declarations.styleValue);
  241. }
  242. }
  243. }));
  244. delete mediaInfo.elements;
  245. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfo], mediaAllInfo, stylesheet));
  246. }
  247. function getStylesInfo(elementInfo, stylesheet/*, element */) {
  248. const stylesInfo = new Map();
  249. elementInfo.forEach(selectorInfo => {
  250. if (selectorInfo.styleInfo) {
  251. processDeclarations(selectorInfo.styleInfo.cssStyle.children, selectorInfo);
  252. } else {
  253. processDeclarations(selectorInfo.ruleInfo.cssRule.block.children, selectorInfo);
  254. }
  255. });
  256. return stylesInfo;
  257. function processDeclarations(declarations, selectorInfo) {
  258. const processedProperties = new Set();
  259. for (let declaration = declarations.tail; declaration; declaration = declaration.prev) {
  260. const declarationData = declaration.data;
  261. if (declarationData.type == "Declaration" && !processedProperties.has(declarationData.property) && !invalidDeclaration(cssTree.generate(declarationData), stylesheet)) {
  262. const styleValue = cssTree.generate(declarationData.value);
  263. const elementStyleInfo = stylesInfo.get(declarationData);
  264. if (styleValue.trim() && (!elementStyleInfo || (declarationData.important && !elementStyleInfo.important))) {
  265. stylesInfo.set(declarationData, { selectorInfo, styleValue, important: declarationData.important });
  266. processedProperties.add(declarationData.property);
  267. }
  268. }
  269. }
  270. }
  271. }
  272. function invalidDeclaration(declarationText, stylesheet) {
  273. let invalidDeclaration;
  274. stylesheet.insertRule("single-file-declaration { " + declarationText + "}");
  275. if (!stylesheet.cssRules[0].style.length) {
  276. if (!declarationText.match(REGEXP_VENDOR_IDENTIFIER)) {
  277. invalidDeclaration = true;
  278. }
  279. }
  280. stylesheet.deleteRule(0);
  281. return invalidDeclaration;
  282. }
  283. function sortRules(media) {
  284. media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
  285. ruleInfo1.styleInfo && !ruleInfo2.styleInfo ? -1 :
  286. !ruleInfo1.styleInfo && ruleInfo2.styleInfo ? 1 :
  287. compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
  288. media.medias.forEach(sortRules);
  289. }
  290. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  291. if (selector.type == "IdSelector") {
  292. specificity.a++;
  293. }
  294. if (selector.type == "ClassSelector" || selector.type == "AttributeSelector" || (selector.type == "PseudoClassSelector" && selector.name != "not")) {
  295. specificity.b++;
  296. }
  297. if ((selector.type == "TypeSelector" && selector.name != "*") || selector.type == "PseudoElementSelector") {
  298. specificity.c++;
  299. }
  300. if (selector.children) {
  301. selector.children.forEach(selector => computeSpecificity(selector, specificity));
  302. }
  303. return specificity;
  304. }
  305. function compareSpecificity(specificity1, specificity2) {
  306. if (specificity1.a > specificity2.a) {
  307. return -1;
  308. } else if (specificity1.a < specificity2.a) {
  309. return 1;
  310. } else if (specificity1.b > specificity2.b) {
  311. return -1;
  312. } else if (specificity1.b < specificity2.b) {
  313. return 1;
  314. } else if (specificity1.c > specificity2.c) {
  315. return -1;
  316. } else if (specificity1.c < specificity2.c) {
  317. return 1;
  318. } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
  319. return -1;
  320. } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
  321. return 1;
  322. } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
  323. return -1;
  324. } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
  325. return 1;
  326. } else {
  327. return -1;
  328. }
  329. }
  330. function log(...args) {
  331. console.log("S-File <css-mat>", ...args); // eslint-disable-line no-console
  332. }
  333. })();