1
0

css-matched-rules.js 12 KB

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