css-rules-matcher.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 CSSRule, cssWhat, parseCss */
  21. this.RulesMatcher = this.RulesMatcher || (() => {
  22. const MEDIA_ALL = "all";
  23. const PRIORITY_IMPORTANT = "important";
  24. const IGNORED_PSEUDO_CLASSES = [":focus", ":focus-within", ":hover", ":link", ":visited", ":active"];
  25. class RulesMatcher {
  26. constructor(doc) {
  27. this.doc = doc;
  28. this.mediaAllInfo = createMediaInfo(MEDIA_ALL);
  29. const matchedElementsCache = {};
  30. const unmatchedSelectorsCache = [];
  31. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  32. if (styleElement.sheet) {
  33. if (styleElement.media && styleElement.media != MEDIA_ALL) {
  34. const mediaInfo = createMediaInfo(styleElement.media);
  35. this.mediaAllInfo.medias.set(styleIndex + "-" + styleElement.media, mediaInfo);
  36. getMatchedElementsRules(doc, styleElement.sheet.cssRules, mediaInfo, styleIndex, matchedElementsCache, unmatchedSelectorsCache);
  37. } else {
  38. getMatchedElementsRules(doc, styleElement.sheet.cssRules, this.mediaAllInfo, styleIndex, matchedElementsCache, unmatchedSelectorsCache);
  39. }
  40. }
  41. });
  42. sortRules(this.mediaAllInfo);
  43. computeCascade(this.mediaAllInfo, [], this.mediaAllInfo);
  44. }
  45. getAllMatchedRules() {
  46. return this.mediaAllInfo;
  47. }
  48. getMatchedRules(element) {
  49. this.mediaAllInfo.elements.get(element);
  50. }
  51. }
  52. return {
  53. create(doc) {
  54. return new RulesMatcher(doc);
  55. }
  56. };
  57. function getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, matchedElementsCache, unmatchedSelectorsCache) {
  58. Array.from(cssRules).forEach((cssRule, ruleIndex) => {
  59. if (cssRule.type == CSSRule.MEDIA_RULE) {
  60. const ruleMediaInfo = createMediaInfo(cssRule.media);
  61. mediaInfo.medias.set(cssRule.media, ruleMediaInfo);
  62. getMatchedElementsRules(doc, cssRule.cssRules, ruleMediaInfo, sheetIndex, matchedElementsCache, unmatchedSelectorsCache);
  63. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  64. if (cssRule.selectorText) {
  65. let selectors;
  66. try {
  67. selectors = cssWhat.parse(cssRule.selectorText);
  68. } catch (error) {
  69. /* ignored */
  70. }
  71. if (selectors) {
  72. const selectorsText = selectors.map(selector => cssWhat.stringify([selector]));
  73. selectors.forEach((selector, selectorIndex) => getMatchedElementsSelector(doc, cssRule, selector, selectorsText[selectorIndex], selectorsText, mediaInfo, ruleIndex, sheetIndex, matchedElementsCache, unmatchedSelectorsCache));
  74. }
  75. }
  76. }
  77. });
  78. }
  79. function getMatchedElementsSelector(doc, cssRule, selector, selectorText, selectorsText, mediaInfo, ruleIndex, sheetIndex, matchedElementsCache, unmatchedSelectorsCache) {
  80. let matchedElements = matchedElementsCache[selectorText];
  81. if (!matchedElements) {
  82. let selectorIndex = 0, selectorsLength = unmatchedSelectorsCache.length, unmatchedSelector;
  83. while (selectorIndex < selectorsLength && !(unmatchedSelector = selectorText.startsWith(unmatchedSelectorsCache[selectorIndex]))) {
  84. selectorIndex++;
  85. }
  86. if (selectorIndex < selectorsLength && unmatchedSelector) {
  87. matchedElements = [];
  88. } else {
  89. matchedElements = doc.querySelectorAll(selectorText);
  90. if (!matchedElements.length) {
  91. unmatchedSelectorsCache.push(selectorText + " ");
  92. }
  93. }
  94. matchedElementsCache[selectorText] = matchedElements;
  95. }
  96. if (matchedElements.length) {
  97. matchedElements.forEach(element => addRule(element, cssRule, selector, selectorText, selectorsText, mediaInfo, ruleIndex, sheetIndex));
  98. }
  99. }
  100. function addRule(element, cssRule, selector, selectorText, selectorsText, mediaInfo, ruleIndex, sheetIndex) {
  101. const info = getInfo(element, cssRule, selector, mediaInfo, ruleIndex, sheetIndex);
  102. const { elementInfo, ruleInfo, specificity } = info;
  103. if (ruleInfo) {
  104. if (compareSpecificity(ruleInfo.specificity, specificity) == 1) {
  105. let pseudoClassIndex = 0, pseudoClassesLength = IGNORED_PSEUDO_CLASSES.length, ignoredPseudoClass;
  106. while (pseudoClassIndex < pseudoClassesLength && !(ignoredPseudoClass = selectorText.includes(IGNORED_PSEUDO_CLASSES[pseudoClassIndex]))) {
  107. pseudoClassIndex++;
  108. }
  109. if (pseudoClassIndex < pseudoClassesLength && ignoredPseudoClass) {
  110. ruleInfo.specificity = specificity;
  111. ruleInfo.selectorText = selectorText;
  112. }
  113. }
  114. } else {
  115. elementInfo.push({ cssRule, specificity, selectorText, selectorsText });
  116. }
  117. }
  118. function getInfo(element, cssRule, selector, mediaInfo, ruleIndex, sheetIndex) {
  119. let elementInfo;
  120. if (mediaInfo.elements.has(element)) {
  121. elementInfo = mediaInfo.elements.get(element);
  122. } else {
  123. elementInfo = [];
  124. const elementStyle = element.getAttribute("style");
  125. if (elementStyle) {
  126. elementInfo.push({ cssStyle: element.style });
  127. }
  128. mediaInfo.elements.set(element, elementInfo);
  129. }
  130. const specificity = computeSpecificity(selector);
  131. specificity.ruleIndex = ruleIndex;
  132. specificity.sheetIndex = sheetIndex;
  133. let ruleInfo;
  134. if (elementInfo.length) {
  135. let elementRuleIndex = 0, elementRulesLength = elementInfo.length, cssRuleFound;
  136. while (elementRuleIndex < elementRulesLength && !(cssRuleFound = elementInfo[elementRuleIndex].cssRule == cssRule)) {
  137. elementRuleIndex++;
  138. }
  139. if (elementRuleIndex < elementRulesLength && cssRuleFound) {
  140. ruleInfo = elementInfo[elementRuleIndex];
  141. }
  142. }
  143. return { elementInfo, ruleInfo, specificity };
  144. }
  145. function computeCascade(mediaInfo, parentMediaInfos, mediaAllInfo) {
  146. mediaInfo.elements.forEach(elementInfo => getStylesInfo(elementInfo).forEach((elementStyleInfo, styleName) => {
  147. let ruleInfo, ascendantMedia;
  148. if (elementStyleInfo.cssRule) {
  149. ascendantMedia = [mediaInfo, ...parentMediaInfos].find(media => media.rules.get(elementStyleInfo.cssRule)) || mediaInfo;
  150. ruleInfo = ascendantMedia.rules.get(elementStyleInfo.cssRule);
  151. } else if (mediaInfo == mediaAllInfo) {
  152. ruleInfo = mediaAllInfo.styles.get(elementStyleInfo.cssStyle);
  153. }
  154. if (!ruleInfo) {
  155. ruleInfo = { style: new Map(), matchedSelectors: new Set(), selectorsText: elementStyleInfo.selectorsText };
  156. }
  157. if (elementStyleInfo.cssRule) {
  158. ascendantMedia.rules.set(elementStyleInfo.cssRule, ruleInfo);
  159. } else if (mediaInfo == mediaAllInfo) {
  160. mediaAllInfo.styles.set(elementStyleInfo.cssStyle, ruleInfo);
  161. }
  162. if (elementStyleInfo.selectorText) {
  163. ruleInfo.matchedSelectors.add(elementStyleInfo.selectorText);
  164. }
  165. const styleValue = ruleInfo.style.get(styleName);
  166. if (!styleValue) {
  167. ruleInfo.style.set(styleName, elementStyleInfo.styleValue);
  168. }
  169. }));
  170. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfos]));
  171. }
  172. function getStylesInfo(elementInfo) {
  173. const elementStylesInfo = new Map();
  174. elementInfo.forEach(ruleInfo => {
  175. if (ruleInfo.cssStyle) {
  176. const cssStyle = ruleInfo.cssStyle;
  177. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  178. stylesInfo.forEach(styleInfo => {
  179. const important = cssStyle.getPropertyPriority(styleInfo.name) == PRIORITY_IMPORTANT;
  180. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important ? "!" + PRIORITY_IMPORTANT : "");
  181. elementStylesInfo.set(styleInfo.name, { styleValue, cssStyle: ruleInfo.cssStyle, important });
  182. });
  183. } else {
  184. const cssStyle = ruleInfo.cssRule.style;
  185. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  186. stylesInfo.forEach(styleInfo => {
  187. const important = cssStyle.getPropertyPriority(styleInfo.name) == PRIORITY_IMPORTANT;
  188. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important ? "!" + PRIORITY_IMPORTANT : "");
  189. let elementStyleInfo = elementStylesInfo.get(styleInfo.name);
  190. if (!elementStyleInfo || (important && !elementStyleInfo.important)) {
  191. elementStylesInfo.set(styleInfo.name, { styleValue, cssRule: ruleInfo.cssRule, selectorText: ruleInfo.selectorText, selectorsText: ruleInfo.selectorsText, important });
  192. }
  193. });
  194. }
  195. });
  196. return elementStylesInfo;
  197. }
  198. function createMediaInfo(media) {
  199. const mediaInfo = { media: media, elements: new Map(), medias: new Map(), rules: new Map() };
  200. if (media == MEDIA_ALL) {
  201. mediaInfo.styles = new Map();
  202. }
  203. return mediaInfo;
  204. }
  205. function sortRules(media) {
  206. media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
  207. ruleInfo1.cssStyle && !ruleInfo2.cssStyle ? -1 :
  208. !ruleInfo1.cssStyle && ruleInfo2.cssStyle ? 1 :
  209. compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
  210. media.medias.forEach(sortRules);
  211. }
  212. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  213. selector.forEach(token => {
  214. if (token.expandedSelector && token.type == "attribute" && token.name === "id" && token.action === "equals") {
  215. specificity.a++;
  216. }
  217. if ((!token.expandedSelector && token.type == "attribute") ||
  218. (token.expandedSelector && token.type == "attribute" && token.name === "class" && token.action === "element") ||
  219. (token.type == "pseudo" && token.name != "not")) {
  220. specificity.b++;
  221. }
  222. if ((token.type == "tag" && token.value != "*") || (token.type == "pseudo-element")) {
  223. specificity.c++;
  224. }
  225. if (token.data) {
  226. if (Array.isArray(token.data)) {
  227. token.data.forEach(selector => computeSpecificity(selector, specificity));
  228. }
  229. }
  230. });
  231. return specificity;
  232. }
  233. function compareSpecificity(specificity1, specificity2) {
  234. if (specificity1.a > specificity2.a) {
  235. return -1;
  236. } else if (specificity1.a < specificity2.a) {
  237. return 1;
  238. } else if (specificity1.b > specificity2.b) {
  239. return -1;
  240. } else if (specificity1.b < specificity2.b) {
  241. return 1;
  242. } else if (specificity1.c > specificity2.c) {
  243. return -1;
  244. } else if (specificity1.c < specificity2.c) {
  245. return 1;
  246. } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
  247. return -1;
  248. } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
  249. return 1;
  250. } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
  251. return -1;
  252. } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
  253. return 1;
  254. } else {
  255. return -1;
  256. }
  257. }
  258. })();