css-matched-rules.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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, 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.sheet);
  41. } else {
  42. getMatchedElementsRules(doc, cssRules, this.mediaAllInfo, sheetIndex, styles, matchedElementsCache, workStyleElement.sheet);
  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.sheet);
  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. getMediaAllInfo(doc, stylesheets, styles) {
  70. return new MatchedRules(doc, stylesheets, styles).getMediaAllInfo();
  71. }
  72. };
  73. function createMediaInfo(media) {
  74. const mediaInfo = { media: media, elements: new Map(), pseudos: new Map(), medias: new Map(), rules: new Map(), pseudoRules: new Map() };
  75. if (media == MEDIA_ALL) {
  76. mediaInfo.matchedStyles = new Map();
  77. }
  78. return mediaInfo;
  79. }
  80. function getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, styles, matchedElementsCache, workStylesheet) {
  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. let invalidSelector;
  117. try {
  118. workStylesheet.insertRule(selectorText + "{}");
  119. workStylesheet.deleteRule(0);
  120. } catch (error) {
  121. if (!selectorText.match(REGEXP_VENDOR_IDENTIFIER)) {
  122. invalidSelector = true;
  123. }
  124. }
  125. return invalidSelector;
  126. }
  127. function getMatchedElementsSelector(doc, selectorInfo, styles, matchedElementsCache) {
  128. let selectorText;
  129. const selectorData = cssTree.parse(cssTree.generate(selectorInfo.selector.data), { context: "selector" });
  130. const filteredSelectorText = getFilteredSelector({ data: selectorData });
  131. if (filteredSelectorText != selectorInfo.selectorText) {
  132. selectorText = filteredSelectorText;
  133. } else {
  134. selectorText = selectorInfo.selectorText;
  135. }
  136. const cachedMatchedElements = matchedElementsCache.get(selectorText);
  137. let matchedElements = cachedMatchedElements;
  138. if (!matchedElements) {
  139. try {
  140. matchedElements = doc.querySelectorAll(selectorText);
  141. } catch (error) {
  142. // ignored
  143. console.warn("(SingleFile) Invalid selector", selectorText); // eslint-disable-line no-console
  144. }
  145. }
  146. if (matchedElements) {
  147. if (!cachedMatchedElements) {
  148. matchedElementsCache.set(selectorText, matchedElements);
  149. }
  150. if (matchedElements.length) {
  151. if (filteredSelectorText == selectorInfo.selectorText) {
  152. matchedElements.forEach(element => addRule(element, selectorInfo, styles));
  153. } else {
  154. let pseudoSelectors = selectorInfo.ruleInfo.mediaInfo.pseudoRules.get(selectorInfo.ruleInfo.ruleData);
  155. if (!pseudoSelectors) {
  156. pseudoSelectors = new Set();
  157. selectorInfo.ruleInfo.mediaInfo.pseudoRules.set(selectorInfo.ruleInfo.ruleData, pseudoSelectors);
  158. }
  159. pseudoSelectors.add(selectorInfo.selectorText);
  160. matchedElements.forEach(element => addPseudoRule(element, selectorInfo));
  161. }
  162. }
  163. }
  164. }
  165. function getFilteredSelector(selector) {
  166. const removedSelectors = [];
  167. selector = { data: cssTree.parse(cssTree.generate(selector.data), { context: "selector" }) };
  168. filterPseudoClasses(selector);
  169. if (removedSelectors.length) {
  170. removedSelectors.forEach(({ parentSelector, selector }) => {
  171. if (parentSelector.data.children.getSize() == 0 || !selector.prev || selector.prev.data.type == "Combinator") {
  172. parentSelector.data.children.replace(selector, cssTree.parse("*", { context: "selector" }).children.head);
  173. } else {
  174. parentSelector.data.children.remove(selector);
  175. }
  176. });
  177. }
  178. const selectorText = cssTree.generate(selector.data).trim();
  179. return selectorText;
  180. function filterPseudoClasses(selector, parentSelector) {
  181. if (selector.data.children) {
  182. for (let childSelector = selector.data.children.head; childSelector; childSelector = childSelector.next) {
  183. filterPseudoClasses(childSelector, selector);
  184. }
  185. }
  186. if ((selector.data.type == "PseudoClassSelector") ||
  187. (selector.data.type == "PseudoElementSelector" && (testVendorPseudo(selector) || IGNORED_PSEUDO_ELEMENTS.includes(selector.data.name)))) {
  188. removedSelectors.push({ parentSelector, selector });
  189. }
  190. }
  191. function testVendorPseudo(selector) {
  192. const name = selector.data.name;
  193. return name.startsWith("-") || name.startsWith("\\-");
  194. }
  195. }
  196. function addRule(element, selectorInfo, styles) {
  197. const mediaInfo = selectorInfo.ruleInfo.mediaInfo;
  198. const elementStyle = styles.get(element);
  199. let elementInfo = mediaInfo.elements.get(element);
  200. if (!elementInfo) {
  201. elementInfo = [];
  202. if (elementStyle) {
  203. elementInfo.push({ styleInfo: { styleData: elementStyle, declarations: new Set() } });
  204. }
  205. mediaInfo.elements.set(element, elementInfo);
  206. }
  207. const specificity = computeSpecificity(selectorInfo.selector.data);
  208. specificity.ruleIndex = selectorInfo.ruleInfo.ruleIndex;
  209. specificity.sheetIndex = selectorInfo.ruleInfo.sheetIndex;
  210. selectorInfo.specificity = specificity;
  211. elementInfo.push(selectorInfo);
  212. }
  213. function addPseudoRule(element, selectorInfo) {
  214. let elementInfo = selectorInfo.ruleInfo.mediaInfo.pseudos.get(element);
  215. if (!elementInfo) {
  216. elementInfo = [];
  217. selectorInfo.ruleInfo.mediaInfo.pseudos.set(element, elementInfo);
  218. }
  219. elementInfo.push(selectorInfo);
  220. }
  221. function computeCascade(mediaInfo, parentMediaInfo, mediaAllInfo, workStylesheet) {
  222. mediaInfo.elements.forEach((elementInfo/*, element*/) =>
  223. getDeclarationsInfo(elementInfo, workStylesheet/*, element*/).forEach((declarationsInfo, property) => {
  224. if (declarationsInfo.selectorInfo.ruleInfo || mediaInfo == mediaAllInfo) {
  225. let info;
  226. if (declarationsInfo.selectorInfo.ruleInfo) {
  227. info = declarationsInfo.selectorInfo.ruleInfo;
  228. const ruleData = info.ruleData;
  229. const ascendantMedia = [mediaInfo, ...parentMediaInfo].find(media => media.rules.get(ruleData)) || mediaInfo;
  230. ascendantMedia.rules.set(ruleData, info);
  231. if (ruleData) {
  232. info.matchedSelectors.add(declarationsInfo.selectorInfo.selectorText);
  233. }
  234. } else {
  235. info = declarationsInfo.selectorInfo.styleInfo;
  236. const styleData = info.styleData;
  237. const matchedStyleInfo = mediaAllInfo.matchedStyles.get(styleData);
  238. if (!matchedStyleInfo) {
  239. mediaAllInfo.matchedStyles.set(styleData, info);
  240. }
  241. }
  242. if (!info.declarations.has(property)) {
  243. info.declarations.add(property);
  244. }
  245. }
  246. }));
  247. delete mediaInfo.elements;
  248. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfo], mediaAllInfo, workStylesheet));
  249. }
  250. function getDeclarationsInfo(elementInfo, workStylesheet/*, element*/) {
  251. const declarationsInfo = new Map();
  252. const processedProperties = new Set();
  253. elementInfo.forEach(selectorInfo => {
  254. let declarations;
  255. if (selectorInfo.styleInfo) {
  256. declarations = selectorInfo.styleInfo.styleData.children;
  257. } else {
  258. declarations = selectorInfo.ruleInfo.ruleData.block.children;
  259. }
  260. processDeclarations(declarationsInfo, declarations, selectorInfo, processedProperties, workStylesheet);
  261. });
  262. return declarationsInfo;
  263. }
  264. function processDeclarations(declarationsInfo, declarations, selectorInfo, processedProperties, workStylesheet) {
  265. for (let declaration = declarations.tail; declaration; declaration = declaration.prev) {
  266. const declarationData = declaration.data;
  267. const declarationText = cssTree.generate(declarationData);
  268. if (declarationData.type == "Declaration" &&
  269. (declarationText.match(REGEXP_VENDOR_IDENTIFIER) || !processedProperties.has(declarationData.property) || declarationData.important) && !invalidDeclaration(declarationText, workStylesheet)) {
  270. const declarationInfo = declarationsInfo.get(declarationData);
  271. if (!declarationInfo || (declarationData.important && !declarationInfo.important)) {
  272. declarationsInfo.set(declarationData, { selectorInfo, important: declarationData.important });
  273. if (!declarationText.match(REGEXP_VENDOR_IDENTIFIER)) {
  274. processedProperties.add(declarationData.property);
  275. }
  276. }
  277. }
  278. }
  279. }
  280. function invalidDeclaration(declarationText, workStylesheet) {
  281. let invalidDeclaration;
  282. workStylesheet.insertRule("single-file-declaration { " + declarationText + "}");
  283. if (!workStylesheet.cssRules[0].style.length) {
  284. if (!declarationText.match(REGEXP_VENDOR_IDENTIFIER)) {
  285. invalidDeclaration = true;
  286. }
  287. }
  288. workStylesheet.deleteRule(0);
  289. return invalidDeclaration;
  290. }
  291. function sortRules(media) {
  292. media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
  293. ruleInfo1.styleInfo && !ruleInfo2.styleInfo ? -1 :
  294. !ruleInfo1.styleInfo && ruleInfo2.styleInfo ? 1 :
  295. compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
  296. media.medias.forEach(sortRules);
  297. }
  298. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  299. if (selector.type == "IdSelector") {
  300. specificity.a++;
  301. }
  302. if (selector.type == "ClassSelector" || selector.type == "AttributeSelector" || (selector.type == "PseudoClassSelector" && selector.name != "not")) {
  303. specificity.b++;
  304. }
  305. if ((selector.type == "TypeSelector" && selector.name != "*") || selector.type == "PseudoElementSelector") {
  306. specificity.c++;
  307. }
  308. if (selector.children) {
  309. selector.children.forEach(selector => computeSpecificity(selector, specificity));
  310. }
  311. return specificity;
  312. }
  313. function compareSpecificity(specificity1, specificity2) {
  314. if (specificity1.a > specificity2.a) {
  315. return -1;
  316. } else if (specificity1.a < specificity2.a) {
  317. return 1;
  318. } else if (specificity1.b > specificity2.b) {
  319. return -1;
  320. } else if (specificity1.b < specificity2.b) {
  321. return 1;
  322. } else if (specificity1.c > specificity2.c) {
  323. return -1;
  324. } else if (specificity1.c < specificity2.c) {
  325. return 1;
  326. } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
  327. return -1;
  328. } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
  329. return 1;
  330. } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
  331. return -1;
  332. } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
  333. return 1;
  334. } else {
  335. return -1;
  336. }
  337. }
  338. function log(...args) {
  339. console.log("S-File <css-mat>", ...args); // eslint-disable-line no-console
  340. }
  341. })();