css-rules-matcher.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 PRIORITY_IMPORTANT = "important";
  24. const IGNORED_PSEUDO_CLASSES = [":focus", ":focus-within", ":hover", ":link", ":visited", ":active"]
  25. class RulesMatcher {
  26. constructor(doc) {
  27. this.doc = doc;
  28. this.mediaAllInfo = createMediaInfo(MEDIA_ALL);
  29. const matchedElementsCache = new Map();
  30. const unmatchedSelectorsCache = new Set();
  31. doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  32. if (styleElement.sheet) {
  33. if (styleElement.media && styleElement.media != MEDIA_ALL) {
  34. const mediaInfo = createMediaInfo(styleElement.media);
  35. this.mediaAllInfo.medias.set(styleIndex + "-" + styleElement.media, mediaInfo);
  36. getMatchedElementsRules(doc, styleElement.sheet.cssRules, mediaInfo, styleIndex, matchedElementsCache, unmatchedSelectorsCache);
  37. } else {
  38. getMatchedElementsRules(doc, styleElement.sheet.cssRules, this.mediaAllInfo, styleIndex, matchedElementsCache, unmatchedSelectorsCache);
  39. }
  40. }
  41. });
  42. sortRules(this.mediaAllInfo);
  43. computeCascade(this.mediaAllInfo, [], this.mediaAllInfo);
  44. }
  45. getAllMatchedRules() {
  46. return this.mediaAllInfo;
  47. }
  48. getMatchedRules(element) {
  49. this.mediaAllInfo.elements.get(element);
  50. }
  51. }
  52. return {
  53. create(doc) {
  54. return new RulesMatcher(doc);
  55. }
  56. };
  57. function getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, matchedElementsCache, unmatchedSelectorsCache) {
  58. Array.from(cssRules).forEach((cssRule, ruleIndex) => {
  59. if (cssRule.type == CSSRule.MEDIA_RULE) {
  60. const ruleMediaInfo = createMediaInfo(cssRule.media);
  61. mediaInfo.medias.set(cssRule.media, ruleMediaInfo);
  62. getMatchedElementsRules(doc, cssRule.cssRules, ruleMediaInfo, sheetIndex, matchedElementsCache, unmatchedSelectorsCache);
  63. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  64. if (cssRule.selectorText) {
  65. try {
  66. let selectors = cssWhat.parse(cssRule.selectorText);
  67. const selectorsText = selectors.map(selector => cssWhat.stringify([selector]));
  68. selectors.forEach(selector => getMatchedElementsSelector(doc, cssRule, selector, selectorsText, mediaInfo, ruleIndex, sheetIndex, matchedElementsCache, unmatchedSelectorsCache));
  69. } catch (error) {
  70. /* ignored */
  71. }
  72. }
  73. }
  74. });
  75. }
  76. function getMatchedElementsSelector(doc, cssRule, selector, selectorsText, mediaInfo, ruleIndex, sheetIndex, matchedElementsCache, unmatchedSelectorsCache) {
  77. const selectorText = cssWhat.stringify([selector]);
  78. let matchedElements = matchedElementsCache.get(selectorText);
  79. if (!matchedElements) {
  80. if (unmatchedSelectorsCache.has(selectorText)) {
  81. matchedElements = [];
  82. } else {
  83. matchedElements = doc.querySelectorAll(selectorText);
  84. if (!matchedElements.length) {
  85. unmatchedSelectorsCache.add(selectorText);
  86. }
  87. }
  88. matchedElementsCache.set(selectorText, matchedElements);
  89. }
  90. if (matchedElements.length) {
  91. matchedElements.forEach(element => {
  92. let elementInfo;
  93. if (mediaInfo.elements.has(element)) {
  94. elementInfo = mediaInfo.elements.get(element);
  95. } else {
  96. elementInfo = [];
  97. const elementStyle = element.getAttribute("style");
  98. if (elementStyle) {
  99. elementInfo.push({ cssStyle: element.style });
  100. }
  101. mediaInfo.elements.set(element, elementInfo);
  102. }
  103. const specificity = computeSpecificity(selector);
  104. specificity.ruleIndex = ruleIndex;
  105. specificity.sheetIndex = sheetIndex;
  106. let ruleInfo = elementInfo.find(ruleInfo => ruleInfo.cssRule == cssRule);
  107. if (ruleInfo) {
  108. if (!IGNORED_PSEUDO_CLASSES.find(pseudoClass => selectorText.find(pseudoClass)) && compareSpecificity(ruleInfo.specificity, specificity) == 1) {
  109. ruleInfo.specificity = specificity;
  110. ruleInfo.selectorText = selectorText;
  111. }
  112. } else {
  113. ruleInfo = { cssRule, specificity, selectorText, selectorsText };
  114. elementInfo.push(ruleInfo);
  115. }
  116. });
  117. }
  118. }
  119. function computeCascade(mediaInfo, parentMediaInfos, mediaAllInfo) {
  120. mediaInfo.elements.forEach(elementInfo => getStylesInfo(elementInfo).forEach((elementStyleInfo, styleName) => {
  121. let ruleInfo, ascendantMedia;
  122. if (elementStyleInfo.cssRule) {
  123. ascendantMedia = [mediaInfo, ...parentMediaInfos].find(media => media.rules.get(elementStyleInfo.cssRule)) || mediaInfo;
  124. ruleInfo = ascendantMedia.rules.get(elementStyleInfo.cssRule);
  125. } else if (mediaInfo == mediaAllInfo) {
  126. ruleInfo = mediaAllInfo.styles.get(elementStyleInfo.cssStyle);
  127. }
  128. if (!ruleInfo) {
  129. ruleInfo = { style: new Map(), matchedSelectors: new Set(), selectorsText: elementStyleInfo.selectorsText };
  130. }
  131. if (elementStyleInfo.cssRule) {
  132. ascendantMedia.rules.set(elementStyleInfo.cssRule, ruleInfo);
  133. } else if (mediaInfo == mediaAllInfo) {
  134. mediaAllInfo.styles.set(elementStyleInfo.cssStyle, ruleInfo);
  135. }
  136. if (elementStyleInfo.selectorText) {
  137. ruleInfo.matchedSelectors.add(elementStyleInfo.selectorText);
  138. }
  139. const styleValue = ruleInfo.style.get(styleName);
  140. if (!styleValue) {
  141. ruleInfo.style.set(styleName, elementStyleInfo.styleValue);
  142. }
  143. }));
  144. mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfos]));
  145. }
  146. function getStylesInfo(elementInfo) {
  147. const elementStylesInfo = new Map();
  148. elementInfo.forEach(ruleInfo => {
  149. if (ruleInfo.cssStyle) {
  150. const cssStyle = ruleInfo.cssStyle;
  151. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  152. stylesInfo.forEach(styleInfo => {
  153. const important = cssStyle.getPropertyPriority(styleInfo.name) == PRIORITY_IMPORTANT;
  154. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important ? "!" + PRIORITY_IMPORTANT : "");
  155. elementStylesInfo.set(styleInfo.name, { styleValue, cssStyle: ruleInfo.cssStyle, important });
  156. });
  157. } else {
  158. const cssStyle = ruleInfo.cssRule.style;
  159. const stylesInfo = parseCss.parseAListOfDeclarations(cssStyle.cssText);
  160. stylesInfo.forEach(styleInfo => {
  161. const important = cssStyle.getPropertyPriority(styleInfo.name) == PRIORITY_IMPORTANT;
  162. const styleValue = cssStyle.getPropertyValue(styleInfo.name) + (important ? "!" + PRIORITY_IMPORTANT : "");
  163. let elementStyleInfo = elementStylesInfo.get(styleInfo.name);
  164. if (!elementStyleInfo || (important && !elementStyleInfo.important)) {
  165. elementStylesInfo.set(styleInfo.name, { styleValue, cssRule: ruleInfo.cssRule, selectorText: ruleInfo.selectorText, selectorsText: ruleInfo.selectorsText, important });
  166. }
  167. });
  168. }
  169. });
  170. return elementStylesInfo;
  171. }
  172. function createMediaInfo(media) {
  173. const mediaInfo = { media: media, elements: new Map(), medias: new Map(), rules: new Map() };
  174. if (media == MEDIA_ALL) {
  175. mediaInfo.styles = new Map();
  176. }
  177. return mediaInfo;
  178. }
  179. function sortRules(media) {
  180. media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
  181. ruleInfo1.cssStyle && !ruleInfo2.cssStyle ? -1 :
  182. !ruleInfo1.cssStyle && ruleInfo2.cssStyle ? 1 :
  183. compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
  184. media.medias.forEach(sortRules);
  185. }
  186. function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
  187. selector.forEach(token => {
  188. if (token.expandedSelector && token.type == "attribute" && token.name === "id" && token.action === "equals") {
  189. specificity.a++;
  190. }
  191. if ((!token.expandedSelector && token.type == "attribute") ||
  192. (token.expandedSelector && token.type == "attribute" && token.name === "class" && token.action === "element") ||
  193. (token.type == "pseudo" && token.name != "not")) {
  194. specificity.b++;
  195. }
  196. if ((token.type == "tag" && token.value != "*") || (token.type == "pseudo-element")) {
  197. specificity.c++;
  198. }
  199. if (token.data) {
  200. if (Array.isArray(token.data)) {
  201. token.data.forEach(selector => computeSpecificity(selector, specificity));
  202. }
  203. }
  204. });
  205. return specificity;
  206. }
  207. function compareSpecificity(specificity1, specificity2) {
  208. if (specificity1.a > specificity2.a) {
  209. return -1;
  210. } else if (specificity1.a < specificity2.a) {
  211. return 1;
  212. } else if (specificity1.b > specificity2.b) {
  213. return -1;
  214. } else if (specificity1.b < specificity2.b) {
  215. return 1;
  216. } else if (specificity1.c > specificity2.c) {
  217. return -1;
  218. } else if (specificity1.c < specificity2.c) {
  219. return 1;
  220. } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
  221. return -1;
  222. } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
  223. return 1;
  224. } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
  225. return -1;
  226. } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
  227. return 1;
  228. } else {
  229. return -1;
  230. }
  231. }
  232. })();