css-rules-matcher.js 11 KB

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