css-rules-matcher.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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.mediaText, 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);
  102. } catch (error) {
  103. /* ignored */
  104. }
  105. if (selectors) {
  106. const selectorsText = selectors.map(selector => cssWhat.stringify([selector]));
  107. selectors.forEach((selector, selectorIndex) => {
  108. const selectorText = selectorsText[selectorIndex];
  109. getMatchedElementsSelector(doc,
  110. { cssRule, mediaInfo, ruleIndex, sheetIndex, selectors, selectorsText, selector, selectorText },
  111. 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, ruleData, matchedElementsCache) {
  122. let selectorText;
  123. const selectorContainsPseudo = containsPseudo(ruleData.selectorText);
  124. if (selectorContainsPseudo) {
  125. selectorText = getFilteredSelector(ruleData.selectorText);
  126. } else {
  127. selectorText = ruleData.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 (selectorContainsPseudo) {
  136. ruleData.mediaInfo.pseudoSelectors.add(ruleData.cssRule.selectorText);
  137. matchedElements.forEach(element => addPseudoRule(element, ruleData));
  138. } else {
  139. matchedElements.forEach(element => addRule(element, ruleData));
  140. }
  141. }
  142. }
  143. function addRule(element, ruleData) {
  144. let elementInfo = ruleData.mediaInfo.elements.get(element);
  145. if (!elementInfo) {
  146. elementInfo = [];
  147. const elementStyle = element.style;
  148. if (elementStyle && elementStyle.length) {
  149. elementInfo.push({ cssStyle: elementStyle });
  150. }
  151. ruleData.mediaInfo.elements.set(element, elementInfo);
  152. }
  153. const specificity = computeSpecificity(ruleData.selector);
  154. specificity.ruleIndex = ruleData.ruleIndex;
  155. specificity.sheetIndex = ruleData.sheetIndex;
  156. ruleData.specificity = specificity;
  157. elementInfo.push(ruleData);
  158. }
  159. function addPseudoRule(element, ruleData) {
  160. let elementInfo = ruleData.mediaInfo.pseudos.get(element);
  161. if (!elementInfo) {
  162. elementInfo = [];
  163. ruleData.mediaInfo.pseudos.set(element, elementInfo);
  164. }
  165. elementInfo.push(ruleData);
  166. }
  167. function computeCascade(mediaInfo, parentMediaInfos, mediaAllInfo) {
  168. mediaInfo.elements.forEach(elementInfo => getStylesInfo(elementInfo).forEach((elementStyleInfo, styleName) => {
  169. let ruleInfo, ascendantMedia;
  170. if (elementStyleInfo.cssRule) {
  171. ascendantMedia = [mediaInfo, ...parentMediaInfos].find(media => media.rules.get(elementStyleInfo.cssRule)) || mediaInfo;
  172. ruleInfo = ascendantMedia.rules.get(elementStyleInfo.cssRule);
  173. } else if (mediaInfo == mediaAllInfo) {
  174. ruleInfo = mediaAllInfo.styles.get(elementStyleInfo.cssStyle);
  175. }
  176. if (!ruleInfo) {
  177. ruleInfo = { style: new Map(), matchedSelectors: new Set(), selectorsText: elementStyleInfo.selectorsText };
  178. }
  179. if (elementStyleInfo.cssRule) {
  180. ascendantMedia.rules.set(elementStyleInfo.cssRule, ruleInfo);
  181. } else if (mediaInfo == mediaAllInfo) {
  182. mediaAllInfo.styles.set(elementStyleInfo.cssStyle, ruleInfo);
  183. }
  184. if (elementStyleInfo.selectorText) {
  185. ruleInfo.matchedSelectors.add(elementStyleInfo.selectorText);
  186. }
  187. const styleValue = ruleInfo.style.get(styleName);
  188. if (!styleValue) {
  189. ruleInfo.style.set(styleName, elementStyleInfo.styleValue);
  190. }
  191. }));
  192. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfos]));
  193. }
  194. function getStylesInfo(elementInfo) {
  195. const elementStylesInfo = new Map();
  196. elementInfo.forEach(ruleInfo => {
  197. if (ruleInfo.cssStyle) {
  198. const cssStyle = ruleInfo.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, { styleValue, cssStyle, important });
  204. });
  205. } else {
  206. const cssRule = ruleInfo.cssRule;
  207. const cssStyle = cssRule.style;
  208. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  209. stylesInfo.forEach(styleInfo => {
  210. const important = cssStyle.getPropertyPriority(styleInfo.name);
  211. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important && "!" + important);
  212. let elementStyleInfo = elementStylesInfo.get(styleInfo.name);
  213. if (!elementStyleInfo || (important && !elementStyleInfo.important)) {
  214. elementStylesInfo.set(styleInfo.name, { styleValue, cssRule, selectorText: ruleInfo.selectorText, selectorsText: ruleInfo.selectorsText, important });
  215. }
  216. });
  217. }
  218. });
  219. return elementStylesInfo;
  220. }
  221. function createMediaInfo(media) {
  222. const mediaInfo = { media: media, elements: new Map(), pseudos: new Map(), medias: new Map(), rules: new Map(), pseudoSelectors: new Set() };
  223. if (media == MEDIA_ALL) {
  224. mediaInfo.styles = new Map();
  225. }
  226. return mediaInfo;
  227. }
  228. function sortRules(media) {
  229. media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
  230. ruleInfo1.cssStyle && !ruleInfo2.cssStyle ? -1 :
  231. !ruleInfo1.cssStyle && ruleInfo2.cssStyle ? 1 :
  232. compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
  233. media.medias.forEach(sortRules);
  234. }
  235. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  236. selector.forEach(token => {
  237. if (token.expandedSelector && token.type == SELECTOR_TOKEN_TYPE_ATTRIBUTE && token.name == SELECTOR_TOKEN_NAME_ID && token.action == SELECTOR_TOKEN_ACTION_EQUALS) {
  238. specificity.a++;
  239. }
  240. if ((!token.expandedSelector && token.type == SELECTOR_TOKEN_TYPE_ATTRIBUTE) ||
  241. (token.expandedSelector && token.type == SELECTOR_TOKEN_TYPE_ATTRIBUTE && token.name == SELECTOR_TOKEN_NAME_CLASS && token.action == SELECTOR_TOKEN_ACTION_ELEMENT) ||
  242. (token.type == SELECTOR_TOKEN_TYPE_PSEUDO && token.name != SELECTOR_TOKEN_NAME_NOT)) {
  243. specificity.b++;
  244. }
  245. if ((token.type == SELECTOR_TOKEN_TYPE_TAG && token.value != SELECTOR_TOKEN_VALUE_STAR) || (token.type == SELECTOR_TOKEN_TYPE_PSEUDO_ELEMENT)) {
  246. specificity.c++;
  247. }
  248. if (token.data) {
  249. if (Array.isArray(token.data)) {
  250. token.data.forEach(selector => computeSpecificity(selector, specificity));
  251. }
  252. }
  253. });
  254. return specificity;
  255. }
  256. function compareSpecificity(specificity1, specificity2) {
  257. if (specificity1.a > specificity2.a) {
  258. return -1;
  259. } else if (specificity1.a < specificity2.a) {
  260. return 1;
  261. } else if (specificity1.b > specificity2.b) {
  262. return -1;
  263. } else if (specificity1.b < specificity2.b) {
  264. return 1;
  265. } else if (specificity1.c > specificity2.c) {
  266. return -1;
  267. } else if (specificity1.c < specificity2.c) {
  268. return 1;
  269. } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
  270. return -1;
  271. } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
  272. return 1;
  273. } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
  274. return -1;
  275. } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
  276. return 1;
  277. } else {
  278. return -1;
  279. }
  280. }
  281. function getFilteredSelector(selector) {
  282. const selectors = cssWhat.parse(selector);
  283. return cssWhat.stringify(selectors.map(selector => filterPseudoClasses(selector)));
  284. function filterPseudoClasses(selector) {
  285. const tokens = selector.filter(token => {
  286. if (token.data) {
  287. if (Array.isArray(token.data)) {
  288. token.data = token.data.map(selector => filterPseudoClasses(selector));
  289. }
  290. }
  291. const test = ((token.type != "pseudo" || !PSEUDOS_CLASSES.includes(":" + token.name))
  292. && (token.type != "pseudo-element"));
  293. return test;
  294. });
  295. let insertedTokens = 0;
  296. tokens.forEach((token, index) => {
  297. if (SEPARATOR_TYPES.includes(token.type)) {
  298. if (!tokens[index - 1] || SEPARATOR_TYPES.includes(tokens[index - 1].type)) {
  299. tokens.splice(index + insertedTokens, 0, { type: "universal" });
  300. insertedTokens++;
  301. }
  302. }
  303. });
  304. if (!tokens.length || SEPARATOR_TYPES.includes(tokens[tokens.length - 1].type)) {
  305. tokens.push({ type: "universal" });
  306. }
  307. return tokens;
  308. }
  309. }
  310. function containsPseudo(selectorText) {
  311. let ignoredPseudo;
  312. if (selectorText.includes("::")) {
  313. ignoredPseudo = true;
  314. } else {
  315. let pseudoIndex = 0;
  316. while (pseudoIndex < PSEUDOS_CLASSES.length && !ignoredPseudo) {
  317. ignoredPseudo = selectorText.includes(PSEUDOS_CLASSES[pseudoIndex]);
  318. if (!ignoredPseudo) {
  319. pseudoIndex++;
  320. }
  321. }
  322. }
  323. return ignoredPseudo;
  324. }
  325. function log(...args) {
  326. console.log("S-File <css-mat>", ...args); // eslint-disable-line no-console
  327. }
  328. })();