1
0

css-rules-matcher.js 12 KB

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