css-matched-rules.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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.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. selectorInfo.ruleInfo.mediaInfo.pseudoSelectors.add(selectorInfo.ruleInfo.cssRule);
  134. matchedElements.forEach(element => addPseudoRule(element, selectorInfo));
  135. }
  136. }
  137. }
  138. }
  139. function getFilteredSelector(selector) {
  140. const removedSelectors = [];
  141. filterPseudoClasses(selector);
  142. if (removedSelectors.length) {
  143. removedSelectors.forEach(({ parentSelector, selector }) => {
  144. if (parentSelector.data.children.getSize() == 0 || !selector.prev || selector.prev.data.type == "Combinator") {
  145. parentSelector.data.children.replace(selector, cssTree.parse("*", { context: "selector" }).children.head);
  146. } else {
  147. parentSelector.data.children.remove(selector);
  148. }
  149. });
  150. }
  151. const selectorText = cssTree.generate(selector.data).trim();
  152. return selectorText;
  153. function filterPseudoClasses(selector, parentSelector) {
  154. if (selector.data.children) {
  155. for (let childSelector = selector.data.children.head; childSelector; childSelector = childSelector.next) {
  156. filterPseudoClasses(childSelector, selector);
  157. }
  158. }
  159. if ((selector.data.type == "PseudoClassSelector") ||
  160. (selector.data.type == "PseudoElementSelector" && (testVendorPseudo(selector) || IGNORED_PSEUDO_ELEMENTS.includes(selector.data.name)))) {
  161. removedSelectors.push({ parentSelector, selector });
  162. }
  163. }
  164. function testVendorPseudo(selector) {
  165. const name = selector.data.name;
  166. return name.startsWith("-") || name.startsWith("\\-");
  167. }
  168. }
  169. function addRule(element, selectorInfo, styles) {
  170. const mediaInfo = selectorInfo.ruleInfo.mediaInfo;
  171. const elementStyle = styles.get(element);
  172. let elementInfo = mediaInfo.elements.get(element);
  173. if (!elementInfo) {
  174. elementInfo = [];
  175. if (elementStyle) {
  176. elementInfo.push({ styleInfo: { cssStyle: elementStyle, style: new Map() } });
  177. }
  178. mediaInfo.elements.set(element, elementInfo);
  179. }
  180. const specificity = computeSpecificity(selectorInfo.selector.data);
  181. specificity.ruleIndex = selectorInfo.ruleInfo.ruleIndex;
  182. specificity.sheetIndex = selectorInfo.ruleInfo.sheetIndex;
  183. selectorInfo.specificity = specificity;
  184. elementInfo.push(selectorInfo);
  185. }
  186. function addPseudoRule(element, selectorInfo) {
  187. let elementInfo = selectorInfo.ruleInfo.mediaInfo.pseudos.get(element);
  188. if (!elementInfo) {
  189. elementInfo = [];
  190. selectorInfo.ruleInfo.mediaInfo.pseudos.set(element, elementInfo);
  191. }
  192. elementInfo.push(selectorInfo);
  193. }
  194. function computeCascade(mediaInfo, parentMediaInfos, mediaAllInfo) {
  195. mediaInfo.elements.forEach((elementInfo) => getStylesInfo(elementInfo).forEach((elementStyleInfo, styleName) => {
  196. if (elementStyleInfo.selectorInfo.ruleInfo || mediaInfo == mediaAllInfo) {
  197. let info;
  198. if (elementStyleInfo.selectorInfo.ruleInfo) {
  199. info = elementStyleInfo.selectorInfo.ruleInfo;
  200. const cssRule = info.cssRule;
  201. const ascendantMedia = [mediaInfo, ...parentMediaInfos].find(media => media.rules.get(cssRule)) || mediaInfo;
  202. ascendantMedia.rules.set(cssRule, info);
  203. if (cssRule) {
  204. info.matchedSelectors.add(elementStyleInfo.selectorInfo.selectorText);
  205. }
  206. } else {
  207. info = elementStyleInfo.selectorInfo.styleInfo;
  208. const cssStyle = info.cssStyle;
  209. const matchedStyleInfo = mediaAllInfo.matchedStyles.get(cssStyle);
  210. if (!matchedStyleInfo) {
  211. mediaAllInfo.matchedStyles.set(cssStyle, info);
  212. }
  213. }
  214. const styleValue = info.style.get(styleName);
  215. if (!styleValue) {
  216. info.style.set(styleName, elementStyleInfo.styleValue);
  217. }
  218. }
  219. }));
  220. delete mediaInfo.elements;
  221. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfos], mediaAllInfo));
  222. }
  223. function getStylesInfo(elementInfo) {
  224. const elementStylesInfo = new Map();
  225. elementInfo.forEach(selectorInfo => {
  226. if (selectorInfo.styleInfo) {
  227. const cssStyle = selectorInfo.styleInfo.cssStyle;
  228. cssStyle.children.forEach(declaration => {
  229. const styleValue = cssTree.generate(declaration);
  230. elementStylesInfo.set(declaration.property, { selectorInfo, styleValue, important: declaration.important });
  231. });
  232. } else {
  233. selectorInfo.ruleInfo.cssRule.block.children.forEach(declaration => {
  234. if (declaration.type == "Declaration") {
  235. const styleValue = cssTree.generate(declaration.value);
  236. const elementStyleInfo = elementStylesInfo.get(declaration.property);
  237. if (styleValue.trim() && (!elementStyleInfo || (declaration.important && !elementStyleInfo.important))) {
  238. elementStylesInfo.set(declaration.property, { selectorInfo, styleValue, important: declaration.important });
  239. }
  240. }
  241. });
  242. }
  243. });
  244. return elementStylesInfo;
  245. }
  246. function sortRules(media) {
  247. media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
  248. ruleInfo1.styleInfo && !ruleInfo2.styleInfo ? -1 :
  249. !ruleInfo1.styleInfo && ruleInfo2.styleInfo ? 1 :
  250. compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
  251. media.medias.forEach(sortRules);
  252. }
  253. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  254. if (selector.type == "IdSelector") {
  255. specificity.a++;
  256. }
  257. if (selector.type == "ClassSelector" || selector.type == "AttributeSelector" || (selector.type == "PseudoClassSelector" && selector.name != "not")) {
  258. specificity.b++;
  259. }
  260. if ((selector.type == "TypeSelector" && selector.name != "*") || selector.type == "PseudoElementSelector") {
  261. specificity.c++;
  262. }
  263. if (selector.children) {
  264. selector.children.forEach(selector => computeSpecificity(selector, specificity));
  265. }
  266. return specificity;
  267. }
  268. function compareSpecificity(specificity1, specificity2) {
  269. if (specificity1.a > specificity2.a) {
  270. return -1;
  271. } else if (specificity1.a < specificity2.a) {
  272. return 1;
  273. } else if (specificity1.b > specificity2.b) {
  274. return -1;
  275. } else if (specificity1.b < specificity2.b) {
  276. return 1;
  277. } else if (specificity1.c > specificity2.c) {
  278. return -1;
  279. } else if (specificity1.c < specificity2.c) {
  280. return 1;
  281. } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
  282. return -1;
  283. } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
  284. return 1;
  285. } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
  286. return -1;
  287. } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
  288. return 1;
  289. } else {
  290. return -1;
  291. }
  292. }
  293. function log(...args) {
  294. console.log("S-File <css-mat>", ...args); // eslint-disable-line no-console
  295. }
  296. })();