css-rules-matcher.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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_PSEUDOS = [":focus", ":focus-within", ":hover", ":link", ":visited", ":active", "::after", "::before", "::first-line", "::first-letter", "::placeholder", "::selection", "::marker", "::cue"];
  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. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  41. if (styleElement.sheet) {
  42. let cssRules = styleElement.sheet.cssRules;
  43. if (styleElement.media && styleElement.media != MEDIA_ALL) {
  44. const mediaInfo = createMediaInfo(styleElement.media);
  45. this.mediaAllInfo.medias.set(styleIndex + "-" + styleElement.media, mediaInfo);
  46. getMatchedElementsRules(doc, cssRules, mediaInfo, styleIndex, matchedElementsCache);
  47. } else {
  48. getMatchedElementsRules(doc, cssRules, this.mediaAllInfo, styleIndex, matchedElementsCache);
  49. }
  50. }
  51. });
  52. let startTime;
  53. if (DEBUG) {
  54. startTime = Date.now();
  55. log(" -- STARTED sortRules");
  56. }
  57. sortRules(this.mediaAllInfo);
  58. if (DEBUG) {
  59. log(" -- ENDED sortRules", Date.now() - startTime);
  60. startTime = Date.now();
  61. log(" -- STARTED computeCascade");
  62. }
  63. computeCascade(this.mediaAllInfo, [], this.mediaAllInfo);
  64. if (DEBUG) {
  65. log(" -- ENDED computeCascade", Date.now() - startTime);
  66. }
  67. }
  68. getAllMatchedRules() {
  69. return this.mediaAllInfo;
  70. }
  71. getMatchedRules(element) {
  72. this.mediaAllInfo.elements.get(element);
  73. }
  74. }
  75. return {
  76. create(doc) {
  77. return new RulesMatcher(doc);
  78. }
  79. };
  80. function getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, matchedElementsCache) {
  81. let startTime;
  82. if (DEBUG && cssRules.length > 1) {
  83. startTime = Date.now();
  84. log(" -- STARTED getMatchedElementsRules", " index =", sheetIndex, "rules.length =", cssRules.length);
  85. }
  86. Array.from(cssRules).forEach((cssRule, ruleIndex) => {
  87. const cssRuleType = cssRule.type;
  88. if (cssRuleType == CSSRule.MEDIA_RULE) {
  89. const cssRuleMedia = cssRule.media;
  90. const ruleMediaInfo = createMediaInfo(cssRuleMedia);
  91. mediaInfo.medias.set(cssRuleMedia, ruleMediaInfo);
  92. getMatchedElementsRules(doc, cssRule.cssRules, ruleMediaInfo, sheetIndex, matchedElementsCache);
  93. } else if (cssRuleType == CSSRule.STYLE_RULE) {
  94. const selectorText = cssRule.selectorText;
  95. if (selectorText) {
  96. let selectors;
  97. try {
  98. selectors = cssWhat.parse(selectorText);
  99. } catch (error) {
  100. /* ignored */
  101. }
  102. if (selectors) {
  103. const selectorsText = selectors.map(selector => cssWhat.stringify([selector]));
  104. selectors.forEach((selector, selectorIndex) => getMatchedElementsSelector(doc, cssRule, selector, selectorsText[selectorIndex], selectorsText, mediaInfo, ruleIndex, sheetIndex, matchedElementsCache));
  105. }
  106. }
  107. }
  108. });
  109. if (DEBUG && cssRules.length > 1) {
  110. log(" -- ENDED getMatchedElementsRules", "delay =", Date.now() - startTime);
  111. }
  112. }
  113. function getMatchedElementsSelector(doc, cssRule, selector, selectorText, selectorsText, mediaInfo, ruleIndex, sheetIndex, matchedElementsCache) {
  114. const cachedMatchedElements = matchedElementsCache.get(selectorText);
  115. const matchedElements = cachedMatchedElements || doc.querySelectorAll(selectorText);
  116. if (!cachedMatchedElements) {
  117. matchedElementsCache.set(selectorText, matchedElements);
  118. }
  119. if (matchedElements.length) {
  120. matchedElements.forEach(element => addRule(element, cssRule, selector, selectorText, selectorsText, mediaInfo, ruleIndex, sheetIndex));
  121. }
  122. }
  123. function addRule(element, cssRule, selector, selectorText, selectorsText, mediaInfo, ruleIndex, sheetIndex) {
  124. const info = getInfo(element, cssRule, selector, mediaInfo, ruleIndex, sheetIndex);
  125. const { elementInfo, ruleInfo, specificity } = info;
  126. if (ruleInfo) {
  127. if (compareSpecificity(ruleInfo.specificity, specificity) == 1) {
  128. let pseudoIndex = 0, pseudoLength = IGNORED_PSEUDOS.length, ignoredPseudo;
  129. while (pseudoIndex < pseudoLength && !(ignoredPseudo = selectorText.includes(IGNORED_PSEUDOS[pseudoIndex]))) {
  130. pseudoIndex++;
  131. }
  132. if (!ignoredPseudo || pseudoIndex < pseudoLength) {
  133. ruleInfo.specificity = specificity;
  134. ruleInfo.selectorText = selectorText;
  135. }
  136. }
  137. } else {
  138. elementInfo.push({ cssRule, specificity, selectorText, selectorsText });
  139. }
  140. }
  141. function getInfo(element, cssRule, selector, mediaInfo, ruleIndex, sheetIndex) {
  142. let elementInfo = mediaInfo.elements.get(element);
  143. if (!elementInfo) {
  144. elementInfo = [];
  145. const elementStyle = element.style;
  146. if (elementStyle && elementStyle.length) {
  147. elementInfo.push({ cssStyle: elementStyle });
  148. }
  149. mediaInfo.elements.set(element, elementInfo);
  150. }
  151. const specificity = computeSpecificity(selector);
  152. specificity.ruleIndex = ruleIndex;
  153. specificity.sheetIndex = sheetIndex;
  154. let ruleInfo;
  155. if (elementInfo.length) {
  156. let elementRuleIndex = 0, elementRulesLength = elementInfo.length, cssRuleFound;
  157. while (elementRuleIndex < elementRulesLength && !(cssRuleFound = elementInfo[elementRuleIndex].cssRule == cssRule)) {
  158. elementRuleIndex++;
  159. }
  160. if (elementRuleIndex < elementRulesLength && cssRuleFound) {
  161. ruleInfo = elementInfo[elementRuleIndex];
  162. }
  163. }
  164. return { elementInfo, ruleInfo, specificity };
  165. }
  166. function computeCascade(mediaInfo, parentMediaInfos, mediaAllInfo) {
  167. mediaInfo.elements.forEach(elementInfo => getStylesInfo(elementInfo).forEach((elementStyleInfo, styleName) => {
  168. let ruleInfo, ascendantMedia;
  169. if (elementStyleInfo.cssRule) {
  170. ascendantMedia = [mediaInfo, ...parentMediaInfos].find(media => media.rules.get(elementStyleInfo.cssRule)) || mediaInfo;
  171. ruleInfo = ascendantMedia.rules.get(elementStyleInfo.cssRule);
  172. } else if (mediaInfo == mediaAllInfo) {
  173. ruleInfo = mediaAllInfo.styles.get(elementStyleInfo.cssStyle);
  174. }
  175. if (!ruleInfo) {
  176. ruleInfo = { style: new Map(), matchedSelectors: new Set(), selectorsText: elementStyleInfo.selectorsText };
  177. }
  178. if (elementStyleInfo.cssRule) {
  179. ascendantMedia.rules.set(elementStyleInfo.cssRule, ruleInfo);
  180. } else if (mediaInfo == mediaAllInfo) {
  181. mediaAllInfo.styles.set(elementStyleInfo.cssStyle, ruleInfo);
  182. }
  183. if (elementStyleInfo.selectorText) {
  184. ruleInfo.matchedSelectors.add(elementStyleInfo.selectorText);
  185. }
  186. const styleValue = ruleInfo.style.get(styleName);
  187. if (!styleValue) {
  188. ruleInfo.style.set(styleName, elementStyleInfo.styleValue);
  189. }
  190. }));
  191. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfos]));
  192. }
  193. function getStylesInfo(elementInfo) {
  194. const elementStylesInfo = new Map();
  195. elementInfo.forEach(ruleInfo => {
  196. if (ruleInfo.cssStyle) {
  197. const cssStyle = ruleInfo.cssStyle;
  198. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  199. stylesInfo.forEach(styleInfo => {
  200. const important = cssStyle.getPropertyPriority(styleInfo.name);
  201. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important && "!" + important);
  202. elementStylesInfo.set(styleInfo.name, { styleValue, cssStyle, important });
  203. });
  204. } else {
  205. const cssRule = ruleInfo.cssRule;
  206. const cssStyle = 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, { styleValue, cssRule, selectorText: ruleInfo.selectorText, selectorsText: ruleInfo.selectorsText, important });
  214. }
  215. });
  216. }
  217. });
  218. return elementStylesInfo;
  219. }
  220. function createMediaInfo(media) {
  221. const mediaInfo = { media: media, elements: new Map(), medias: new Map(), rules: new Map() };
  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.cssStyle && !ruleInfo2.cssStyle ? -1 :
  230. !ruleInfo1.cssStyle && ruleInfo2.cssStyle ? 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 log(...args) {
  281. console.log("S-File <css-mat>", ...args); // eslint-disable-line no-console
  282. }
  283. })();