css-rules-matcher.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 SEPARATOR_TYPES = ["descendant", "child", "sibling", "adjacent"];
  24. const PSEUDOS_CLASSES = [":focus", ":focus-within", ":hover", ":link", ":visited", ":active"];
  25. const SELECTOR_TOKEN_TYPE_TAG = "tag";
  26. const SELECTOR_TOKEN_TYPE_ATTRIBUTE = "attribute";
  27. const SELECTOR_TOKEN_TYPE_PSEUDO = "pseudo";
  28. const SELECTOR_TOKEN_TYPE_PSEUDO_ELEMENT = "pseudo-element";
  29. const SELECTOR_TOKEN_NAME_ID = "id";
  30. const SELECTOR_TOKEN_NAME_CLASS = "class";
  31. const SELECTOR_TOKEN_NAME_NOT = "not";
  32. const SELECTOR_TOKEN_ACTION_EQUALS = "equals";
  33. const SELECTOR_TOKEN_ACTION_ELEMENT = "element";
  34. const SELECTOR_TOKEN_VALUE_STAR = "*";
  35. const DEBUG = false;
  36. class RulesMatcher {
  37. constructor(doc) {
  38. this.doc = doc;
  39. this.mediaAllInfo = createMediaInfo(MEDIA_ALL);
  40. const matchedElementsCache = new Map();
  41. doc.querySelectorAll("style").forEach((styleElement, sheetIndex) => {
  42. if (styleElement.sheet) {
  43. const cssRules = styleElement.sheet.cssRules;
  44. if (styleElement.media && styleElement.media != MEDIA_ALL) {
  45. const mediaInfo = createMediaInfo(styleElement.media);
  46. this.mediaAllInfo.medias.set("style-" + sheetIndex + "-" + styleElement.media, mediaInfo);
  47. getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, matchedElementsCache);
  48. } else {
  49. getMatchedElementsRules(doc, cssRules, this.mediaAllInfo, sheetIndex, matchedElementsCache);
  50. }
  51. }
  52. });
  53. let startTime;
  54. if (DEBUG) {
  55. startTime = Date.now();
  56. log(" -- STARTED sortRules");
  57. }
  58. sortRules(this.mediaAllInfo);
  59. if (DEBUG) {
  60. log(" -- ENDED sortRules", Date.now() - startTime);
  61. startTime = Date.now();
  62. log(" -- STARTED computeCascade");
  63. }
  64. computeCascade(this.mediaAllInfo, [], this.mediaAllInfo);
  65. if (DEBUG) {
  66. log(" -- ENDED computeCascade", Date.now() - startTime);
  67. }
  68. }
  69. getMediaAllInfo() {
  70. return this.mediaAllInfo;
  71. }
  72. getMatchedRules(element) {
  73. this.mediaAllInfo.elements.get(element);
  74. }
  75. }
  76. return {
  77. create(doc) {
  78. return new RulesMatcher(doc);
  79. }
  80. };
  81. function getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, matchedElementsCache) {
  82. let mediaIndex = 0;
  83. let startTime;
  84. if (DEBUG && cssRules.length > 1) {
  85. startTime = Date.now();
  86. log(" -- STARTED getMatchedElementsRules", " index =", sheetIndex, "rules.length =", cssRules.length);
  87. }
  88. Array.from(cssRules).forEach((cssRule, ruleIndex) => {
  89. const cssRuleType = cssRule.type;
  90. if (cssRuleType == CSSRule.MEDIA_RULE) {
  91. const cssRuleMedia = cssRule.media;
  92. const ruleMediaInfo = createMediaInfo(cssRuleMedia);
  93. mediaInfo.medias.set("rule-" + sheetIndex + "-" + mediaIndex + "-" + cssRuleMedia.mediaText, ruleMediaInfo);
  94. mediaIndex++;
  95. getMatchedElementsRules(doc, cssRule.cssRules, ruleMediaInfo, sheetIndex, matchedElementsCache);
  96. } else if (cssRuleType == CSSRule.STYLE_RULE) {
  97. const selectorText = cssRule.selectorText;
  98. if (selectorText) {
  99. let selectors;
  100. try {
  101. selectors = cssWhat.parse(selectorText.trim());
  102. } catch (error) {
  103. /* ignored */
  104. }
  105. if (selectors) {
  106. const selectorsText = selectors.map(selector => cssWhat.stringify([selector]));
  107. const ruleInfo = { cssRule, mediaInfo, ruleIndex, sheetIndex, matchedSelectors: new Set(), style: new Map(), selectors, selectorsText };
  108. selectors.forEach((selector, selectorIndex) => {
  109. const selectorText = selectorsText[selectorIndex];
  110. const selectorInfo = { selector, selectorText, ruleInfo };
  111. getMatchedElementsSelector(doc, selectorInfo, matchedElementsCache);
  112. });
  113. }
  114. }
  115. }
  116. });
  117. if (DEBUG && cssRules.length > 1) {
  118. log(" -- ENDED getMatchedElementsRules", "delay =", Date.now() - startTime);
  119. }
  120. }
  121. function getMatchedElementsSelector(doc, selectorInfo, matchedElementsCache) {
  122. let selectorText;
  123. const filteredSelectorText = getFilteredSelector(selectorInfo.selectorText);
  124. if (filteredSelectorText != selectorInfo.selectorText) {
  125. selectorText = filteredSelectorText;
  126. } else {
  127. selectorText = selectorInfo.selectorText;
  128. }
  129. const cachedMatchedElements = matchedElementsCache.get(selectorText);
  130. const matchedElements = cachedMatchedElements || doc.querySelectorAll(selectorText);
  131. if (!cachedMatchedElements) {
  132. matchedElementsCache.set(selectorText, matchedElements);
  133. }
  134. if (matchedElements.length) {
  135. if (filteredSelectorText != selectorInfo.selectorText) {
  136. selectorInfo.ruleInfo.mediaInfo.pseudoSelectors.add(selectorInfo.ruleInfo.cssRule.selectorText);
  137. matchedElements.forEach(element => addPseudoRule(element, selectorInfo));
  138. } else {
  139. matchedElements.forEach(element => addRule(element, selectorInfo));
  140. }
  141. }
  142. }
  143. function addRule(element, selectorInfo) {
  144. const mediaInfo = selectorInfo.ruleInfo.mediaInfo;
  145. let elementInfo = mediaInfo.elements.get(element);
  146. if (!elementInfo) {
  147. elementInfo = [];
  148. const elementStyle = element.style;
  149. if (elementStyle && elementStyle.length) {
  150. elementInfo.push({ styleInfo: { cssStyle: elementStyle, style: new Map() } });
  151. }
  152. mediaInfo.elements.set(element, elementInfo);
  153. }
  154. const specificity = computeSpecificity(selectorInfo.selector);
  155. specificity.ruleIndex = selectorInfo.ruleInfo.ruleIndex;
  156. specificity.sheetIndex = selectorInfo.ruleInfo.sheetIndex;
  157. selectorInfo.specificity = specificity;
  158. elementInfo.push(selectorInfo);
  159. }
  160. function addPseudoRule(element, selectorInfo) {
  161. let elementInfo = selectorInfo.ruleInfo.mediaInfo.pseudos.get(element);
  162. if (!elementInfo) {
  163. elementInfo = [];
  164. selectorInfo.ruleInfo.mediaInfo.pseudos.set(element, elementInfo);
  165. }
  166. elementInfo.push(selectorInfo);
  167. }
  168. function computeCascade(mediaInfo, parentMediaInfos, mediaAllInfo) {
  169. mediaInfo.elements.forEach(elementInfo => getStylesInfo(elementInfo).forEach((elementStyleInfo, styleName) => {
  170. if (elementStyleInfo.selectorInfo.ruleInfo) {
  171. const ruleInfo = elementStyleInfo.selectorInfo.ruleInfo;
  172. const cssRule = ruleInfo.cssRule;
  173. const ascendantMedia = [mediaInfo, ...parentMediaInfos].find(media => media.rules.get(cssRule)) || mediaInfo;
  174. ascendantMedia.rules.set(cssRule, ruleInfo);
  175. if (cssRule) {
  176. ruleInfo.matchedSelectors.add(elementStyleInfo.selectorInfo.selectorText);
  177. }
  178. const styleValue = ruleInfo.style.get(styleName);
  179. if (!styleValue) {
  180. ruleInfo.style.set(styleName, elementStyleInfo.styleValue);
  181. }
  182. } else {
  183. const styleInfo = elementStyleInfo.selectorInfo.styleInfo;
  184. const cssStyle = styleInfo.cssStyle;
  185. const matchedStyleInfo = mediaAllInfo.matchedStyles.get(cssStyle);
  186. if (!matchedStyleInfo) {
  187. mediaAllInfo.matchedStyles.set(cssStyle, styleInfo);
  188. }
  189. const styleValue = styleInfo.style.get(styleName);
  190. if (!styleValue) {
  191. styleInfo.style.set(styleName, elementStyleInfo.styleValue);
  192. }
  193. }
  194. }));
  195. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfos], mediaAllInfo));
  196. }
  197. function getStylesInfo(elementInfo) {
  198. const elementStylesInfo = new Map();
  199. elementInfo.forEach(selectorInfo => {
  200. if (selectorInfo.styleInfo) {
  201. const cssStyle = selectorInfo.styleInfo.cssStyle;
  202. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  203. stylesInfo.forEach(styleInfo => {
  204. const important = cssStyle.getPropertyPriority(styleInfo.name);
  205. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important && "!" + important);
  206. elementStylesInfo.set(styleInfo.name, { selectorInfo, styleValue, important });
  207. });
  208. } else {
  209. const cssStyle = selectorInfo.ruleInfo.cssRule.style;
  210. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  211. stylesInfo.forEach(styleInfo => {
  212. const important = cssStyle.getPropertyPriority(styleInfo.name);
  213. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important && "!" + important);
  214. const elementStyleInfo = elementStylesInfo.get(styleInfo.name);
  215. if (!elementStyleInfo || (important && !elementStyleInfo.important)) {
  216. elementStylesInfo.set(styleInfo.name, { selectorInfo, styleValue, important });
  217. }
  218. });
  219. }
  220. });
  221. return elementStylesInfo;
  222. }
  223. function createMediaInfo(media) {
  224. const mediaInfo = { media: media, elements: new Map(), pseudos: new Map(), medias: new Map(), rules: new Map(), pseudoSelectors: new Set() };
  225. if (media == MEDIA_ALL) {
  226. mediaInfo.matchedStyles = new Map();
  227. }
  228. return mediaInfo;
  229. }
  230. function sortRules(media) {
  231. media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
  232. ruleInfo1.styleInfo && !ruleInfo2.styleInfo ? -1 :
  233. !ruleInfo1.styleInfo && ruleInfo2.styleInfo ? 1 :
  234. compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
  235. media.medias.forEach(sortRules);
  236. }
  237. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  238. selector.forEach(token => {
  239. if (token.expandedSelector && token.type == SELECTOR_TOKEN_TYPE_ATTRIBUTE && token.name == SELECTOR_TOKEN_NAME_ID && token.action == SELECTOR_TOKEN_ACTION_EQUALS) {
  240. specificity.a++;
  241. }
  242. if ((!token.expandedSelector && token.type == SELECTOR_TOKEN_TYPE_ATTRIBUTE) ||
  243. (token.expandedSelector && token.type == SELECTOR_TOKEN_TYPE_ATTRIBUTE && token.name == SELECTOR_TOKEN_NAME_CLASS && token.action == SELECTOR_TOKEN_ACTION_ELEMENT) ||
  244. (token.type == SELECTOR_TOKEN_TYPE_PSEUDO && token.name != SELECTOR_TOKEN_NAME_NOT)) {
  245. specificity.b++;
  246. }
  247. if ((token.type == SELECTOR_TOKEN_TYPE_TAG && token.value != SELECTOR_TOKEN_VALUE_STAR) || (token.type == SELECTOR_TOKEN_TYPE_PSEUDO_ELEMENT)) {
  248. specificity.c++;
  249. }
  250. if (token.data) {
  251. if (Array.isArray(token.data)) {
  252. token.data.forEach(selector => computeSpecificity(selector, specificity));
  253. }
  254. }
  255. });
  256. return specificity;
  257. }
  258. function compareSpecificity(specificity1, specificity2) {
  259. if (specificity1.a > specificity2.a) {
  260. return -1;
  261. } else if (specificity1.a < specificity2.a) {
  262. return 1;
  263. } else if (specificity1.b > specificity2.b) {
  264. return -1;
  265. } else if (specificity1.b < specificity2.b) {
  266. return 1;
  267. } else if (specificity1.c > specificity2.c) {
  268. return -1;
  269. } else if (specificity1.c < specificity2.c) {
  270. return 1;
  271. } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
  272. return -1;
  273. } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
  274. return 1;
  275. } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
  276. return -1;
  277. } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
  278. return 1;
  279. } else {
  280. return -1;
  281. }
  282. }
  283. function getFilteredSelector(selector) {
  284. let selectors;
  285. try {
  286. selectors = cssWhat.parse(selector.trim());
  287. } catch (error) {
  288. return selector;
  289. }
  290. return cssWhat.stringify(selectors.map(selector => filterPseudoClasses(selector)));
  291. function filterPseudoClasses(selector, negatedData) {
  292. const tokens = selector.filter(token => {
  293. if (token.data) {
  294. if (Array.isArray(token.data)) {
  295. token.data = token.data.map(selector => filterPseudoClasses(selector, token.name == "not" && token.type == "pseudo"));
  296. }
  297. }
  298. return negatedData || ((token.type != "pseudo" || !PSEUDOS_CLASSES.includes(":" + token.name))
  299. && (token.type != "pseudo-element"));
  300. });
  301. let insertedTokens = 0;
  302. tokens.forEach((token, index) => {
  303. if (SEPARATOR_TYPES.includes(token.type)) {
  304. if (!tokens[index - 1] || SEPARATOR_TYPES.includes(tokens[index - 1].type)) {
  305. tokens.splice(index + insertedTokens, 0, { type: "universal" });
  306. insertedTokens++;
  307. }
  308. }
  309. });
  310. if (!tokens.length || SEPARATOR_TYPES.includes(tokens[tokens.length - 1].type)) {
  311. tokens.push({ type: "universal" });
  312. }
  313. return tokens;
  314. }
  315. }
  316. function log(...args) {
  317. console.log("S-File <css-mat>", ...args); // eslint-disable-line no-console
  318. }
  319. })();