css-matched-rules.js 12 KB

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