css-rules-matcher.js 10 KB

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