css-rules-matcher.js 9.2 KB

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