css-rules-matcher.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. let 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. let styleInfos = mediaAllInfo.matchedStyles.get(cssStyle);
  186. if (!styleInfos) {
  187. styleInfos = [];
  188. mediaAllInfo.matchedStyles.set(cssStyle, styleInfos);
  189. }
  190. styleInfos.push(styleInfo);
  191. const styleValue = styleInfo.style.get(styleName);
  192. if (!styleValue) {
  193. styleInfo.style.set(styleName, elementStyleInfo.styleValue);
  194. }
  195. }
  196. }));
  197. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfos], mediaAllInfo));
  198. }
  199. function getStylesInfo(elementInfo) {
  200. const elementStylesInfo = new Map();
  201. elementInfo.forEach(selectorInfo => {
  202. if (selectorInfo.styleInfo) {
  203. const cssStyle = selectorInfo.styleInfo.cssStyle;
  204. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  205. stylesInfo.forEach(styleInfo => {
  206. const important = cssStyle.getPropertyPriority(styleInfo.name);
  207. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important && "!" + important);
  208. elementStylesInfo.set(styleInfo.name, { selectorInfo, styleValue, important });
  209. });
  210. } else {
  211. const cssStyle = selectorInfo.ruleInfo.cssRule.style;
  212. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  213. stylesInfo.forEach(styleInfo => {
  214. const important = cssStyle.getPropertyPriority(styleInfo.name);
  215. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important && "!" + important);
  216. let elementStyleInfo = elementStylesInfo.get(styleInfo.name);
  217. if (!elementStyleInfo || (important && !elementStyleInfo.important)) {
  218. elementStylesInfo.set(styleInfo.name, { selectorInfo, styleValue, important });
  219. }
  220. });
  221. }
  222. });
  223. return elementStylesInfo;
  224. }
  225. function createMediaInfo(media) {
  226. const mediaInfo = { media: media, elements: new Map(), pseudos: new Map(), medias: new Map(), rules: new Map(), pseudoSelectors: new Set() };
  227. if (media == MEDIA_ALL) {
  228. mediaInfo.matchedStyles = new Map();
  229. }
  230. return mediaInfo;
  231. }
  232. function sortRules(media) {
  233. media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
  234. ruleInfo1.styleInfo && !ruleInfo2.styleInfo ? -1 :
  235. !ruleInfo1.styleInfo && ruleInfo2.styleInfo ? 1 :
  236. compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
  237. media.medias.forEach(sortRules);
  238. }
  239. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  240. selector.forEach(token => {
  241. if (token.expandedSelector && token.type == SELECTOR_TOKEN_TYPE_ATTRIBUTE && token.name == SELECTOR_TOKEN_NAME_ID && token.action == SELECTOR_TOKEN_ACTION_EQUALS) {
  242. specificity.a++;
  243. }
  244. if ((!token.expandedSelector && token.type == SELECTOR_TOKEN_TYPE_ATTRIBUTE) ||
  245. (token.expandedSelector && token.type == SELECTOR_TOKEN_TYPE_ATTRIBUTE && token.name == SELECTOR_TOKEN_NAME_CLASS && token.action == SELECTOR_TOKEN_ACTION_ELEMENT) ||
  246. (token.type == SELECTOR_TOKEN_TYPE_PSEUDO && token.name != SELECTOR_TOKEN_NAME_NOT)) {
  247. specificity.b++;
  248. }
  249. if ((token.type == SELECTOR_TOKEN_TYPE_TAG && token.value != SELECTOR_TOKEN_VALUE_STAR) || (token.type == SELECTOR_TOKEN_TYPE_PSEUDO_ELEMENT)) {
  250. specificity.c++;
  251. }
  252. if (token.data) {
  253. if (Array.isArray(token.data)) {
  254. token.data.forEach(selector => computeSpecificity(selector, specificity));
  255. }
  256. }
  257. });
  258. return specificity;
  259. }
  260. function compareSpecificity(specificity1, specificity2) {
  261. if (specificity1.a > specificity2.a) {
  262. return -1;
  263. } else if (specificity1.a < specificity2.a) {
  264. return 1;
  265. } else if (specificity1.b > specificity2.b) {
  266. return -1;
  267. } else if (specificity1.b < specificity2.b) {
  268. return 1;
  269. } else if (specificity1.c > specificity2.c) {
  270. return -1;
  271. } else if (specificity1.c < specificity2.c) {
  272. return 1;
  273. } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
  274. return -1;
  275. } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
  276. return 1;
  277. } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
  278. return -1;
  279. } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
  280. return 1;
  281. } else {
  282. return -1;
  283. }
  284. }
  285. function getFilteredSelector(selector) {
  286. let selectors;
  287. try {
  288. selectors = cssWhat.parse(selector.trim());
  289. } catch (error) {
  290. return selector;
  291. }
  292. return cssWhat.stringify(selectors.map(selector => filterPseudoClasses(selector)));
  293. function filterPseudoClasses(selector, negatedData) {
  294. const tokens = selector.filter(token => {
  295. if (token.data) {
  296. if (Array.isArray(token.data)) {
  297. token.data = token.data.map(selector => filterPseudoClasses(selector, token.name == "not" && token.type == "pseudo"));
  298. }
  299. }
  300. return negatedData || ((token.type != "pseudo" || !PSEUDOS_CLASSES.includes(":" + token.name))
  301. && (token.type != "pseudo-element"));
  302. });
  303. let insertedTokens = 0;
  304. tokens.forEach((token, index) => {
  305. if (SEPARATOR_TYPES.includes(token.type)) {
  306. if (!tokens[index - 1] || SEPARATOR_TYPES.includes(tokens[index - 1].type)) {
  307. tokens.splice(index + insertedTokens, 0, { type: "universal" });
  308. insertedTokens++;
  309. }
  310. }
  311. });
  312. if (!tokens.length || SEPARATOR_TYPES.includes(tokens[tokens.length - 1].type)) {
  313. tokens.push({ type: "universal" });
  314. }
  315. return tokens;
  316. }
  317. }
  318. function log(...args) {
  319. console.log("S-File <css-mat>", ...args); // eslint-disable-line no-console
  320. }
  321. })();