css-rules-matcher.js 11 KB

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