css-matched-rules.js 12 KB

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