css-matched-rules.js 13 KB

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