single-file-core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,350 @@
1
+ /*
2
+ * Copyright 2010-2020 Gildas Lormeau
3
+ * contact : gildas.lormeau <at> gmail.com
4
+ *
5
+ * This file is part of SingleFile.
6
+ *
7
+ * The code in this file is free software: you can redistribute it and/or
8
+ * modify it under the terms of the GNU Affero General Public License
9
+ * (GNU AGPL) as published by the Free Software Foundation, either version 3
10
+ * of the License, or (at your option) any later version.
11
+ *
12
+ * The code in this file 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 GNU Affero
15
+ * General Public License for more details.
16
+ *
17
+ * As additional permission under GNU AGPL version 3 section 7, you may
18
+ * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
19
+ * AGPL normally required by section 4, provided you include this license
20
+ * notice and a URL through which recipients can access the Corresponding
21
+ * Source.
22
+ */
23
+
24
+ import * as cssTree from "./../vendor/css-tree.js";
25
+
26
+ const MEDIA_ALL = "all";
27
+ const IGNORED_PSEUDO_ELEMENTS = ["after", "before", "first-letter", "first-line", "placeholder", "selection", "part", "marker"];
28
+ const SINGLE_FILE_HIDDEN_CLASS_NAME = "sf-hidden";
29
+ const DISPLAY_STYLE = "display";
30
+ const REGEXP_VENDOR_IDENTIFIER = /-(ms|webkit|moz|o)-/;
31
+ const DEBUG = false;
32
+
33
+ class MatchedRules {
34
+ constructor(doc, stylesheets, styles) {
35
+ this.doc = doc;
36
+ this.mediaAllInfo = createMediaInfo(MEDIA_ALL);
37
+ const matchedElementsCache = new Map();
38
+ let sheetIndex = 0;
39
+ const workStyleElement = doc.createElement("style");
40
+ doc.body.appendChild(workStyleElement);
41
+ stylesheets.forEach(stylesheetInfo => {
42
+ if (!stylesheetInfo.scoped) {
43
+ const cssRules = stylesheetInfo.stylesheet.children;
44
+ if (cssRules) {
45
+ if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
46
+ const mediaInfo = createMediaInfo(stylesheetInfo.mediaText);
47
+ this.mediaAllInfo.medias.set("style-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaInfo);
48
+ getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, styles, matchedElementsCache, workStyleElement);
49
+ } else {
50
+ getMatchedElementsRules(doc, cssRules, this.mediaAllInfo, sheetIndex, styles, matchedElementsCache, workStyleElement);
51
+ }
52
+ }
53
+ }
54
+ sheetIndex++;
55
+ });
56
+ let startTime;
57
+ if (DEBUG) {
58
+ startTime = Date.now();
59
+ log(" -- STARTED sortRules");
60
+ }
61
+ sortRules(this.mediaAllInfo);
62
+ if (DEBUG) {
63
+ log(" -- ENDED sortRules", Date.now() - startTime);
64
+ startTime = Date.now();
65
+ log(" -- STARTED computeCascade");
66
+ }
67
+ computeCascade(this.mediaAllInfo, [], this.mediaAllInfo, workStyleElement);
68
+ workStyleElement.remove();
69
+ if (DEBUG) {
70
+ log(" -- ENDED computeCascade", Date.now() - startTime);
71
+ }
72
+ }
73
+
74
+ getMediaAllInfo() {
75
+ return this.mediaAllInfo;
76
+ }
77
+ }
78
+
79
+ export {
80
+ getMediaAllInfo
81
+ };
82
+
83
+ function getMediaAllInfo(doc, stylesheets, styles) {
84
+ return new MatchedRules(doc, stylesheets, styles).getMediaAllInfo();
85
+ }
86
+
87
+ function createMediaInfo(media) {
88
+ const mediaInfo = { media: media, elements: new Map(), medias: new Map(), rules: new Map(), pseudoRules: new Map() };
89
+ if (media == MEDIA_ALL) {
90
+ mediaInfo.matchedStyles = new Map();
91
+ }
92
+ return mediaInfo;
93
+ }
94
+
95
+ function getMatchedElementsRules(doc, cssRules, mediaInfo, sheetIndex, styles, matchedElementsCache, workStylesheet) {
96
+ let mediaIndex = 0;
97
+ let ruleIndex = 0;
98
+ let startTime;
99
+ if (DEBUG && cssRules.length > 1) {
100
+ startTime = Date.now();
101
+ log(" -- STARTED getMatchedElementsRules", " index =", sheetIndex, "rules.length =", cssRules.length);
102
+ }
103
+ cssRules.forEach(ruleData => {
104
+ if (ruleData.block && ruleData.block.children && ruleData.prelude && ruleData.prelude.children) {
105
+ if (ruleData.type == "Atrule" && ruleData.name == "media") {
106
+ const mediaText = cssTree.generate(ruleData.prelude);
107
+ const ruleMediaInfo = createMediaInfo(mediaText);
108
+ mediaInfo.medias.set("rule-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, ruleMediaInfo);
109
+ mediaIndex++;
110
+ getMatchedElementsRules(doc, ruleData.block.children, ruleMediaInfo, sheetIndex, styles, matchedElementsCache, workStylesheet);
111
+ } else if (ruleData.type == "Rule") {
112
+ const selectors = ruleData.prelude.children.toArray();
113
+ const selectorsText = ruleData.prelude.children.toArray().map(selector => cssTree.generate(selector));
114
+ const ruleInfo = { ruleData, mediaInfo, ruleIndex, sheetIndex, matchedSelectors: new Set(), declarations: new Set(), selectors, selectorsText };
115
+ if (!invalidSelector(selectorsText.join(","), workStylesheet)) {
116
+ for (let selector = ruleData.prelude.children.head, selectorIndex = 0; selector; selector = selector.next, selectorIndex++) {
117
+ const selectorText = selectorsText[selectorIndex];
118
+ const selectorInfo = { selector, selectorText, ruleInfo };
119
+ getMatchedElementsSelector(doc, selectorInfo, styles, matchedElementsCache);
120
+ }
121
+ }
122
+ ruleIndex++;
123
+ }
124
+ }
125
+ });
126
+ if (DEBUG && cssRules.length > 1) {
127
+ log(" -- ENDED getMatchedElementsRules", "delay =", Date.now() - startTime);
128
+ }
129
+ }
130
+
131
+ function invalidSelector(selectorText, workStylesheet) {
132
+ workStylesheet.textContent = selectorText + "{}";
133
+ return workStylesheet.sheet ? !workStylesheet.sheet.cssRules.length : workStylesheet.sheet;
134
+ }
135
+
136
+ function getMatchedElementsSelector(doc, selectorInfo, styles, matchedElementsCache) {
137
+ const filteredSelectorText = getFilteredSelector(selectorInfo.selector, selectorInfo.selectorText);
138
+ const selectorText = filteredSelectorText != selectorInfo.selectorText ? filteredSelectorText : selectorInfo.selectorText;
139
+ const cachedMatchedElements = matchedElementsCache.get(selectorText);
140
+ let matchedElements = cachedMatchedElements;
141
+ if (!matchedElements) {
142
+ try {
143
+ matchedElements = doc.querySelectorAll(selectorText);
144
+ if (selectorText != "." + SINGLE_FILE_HIDDEN_CLASS_NAME) {
145
+ matchedElements = Array.from(doc.querySelectorAll(selectorText)).filter(matchedElement =>
146
+ !matchedElement.classList.contains(SINGLE_FILE_HIDDEN_CLASS_NAME) &&
147
+ (matchedElement.style.getPropertyValue(DISPLAY_STYLE) != "none" || matchedElement.style.getPropertyPriority("display") != "important")
148
+ );
149
+ }
150
+ } catch (error) {
151
+ // ignored
152
+ }
153
+ }
154
+ if (matchedElements) {
155
+ if (!cachedMatchedElements) {
156
+ matchedElementsCache.set(selectorText, matchedElements);
157
+ }
158
+ if (matchedElements.length) {
159
+ if (filteredSelectorText == selectorInfo.selectorText) {
160
+ matchedElements.forEach(element => addRule(element, selectorInfo, styles));
161
+ } else {
162
+ let pseudoSelectors = selectorInfo.ruleInfo.mediaInfo.pseudoRules.get(selectorInfo.ruleInfo.ruleData);
163
+ if (!pseudoSelectors) {
164
+ pseudoSelectors = new Set();
165
+ selectorInfo.ruleInfo.mediaInfo.pseudoRules.set(selectorInfo.ruleInfo.ruleData, pseudoSelectors);
166
+ }
167
+ pseudoSelectors.add(selectorInfo.selectorText);
168
+ }
169
+ }
170
+ }
171
+ }
172
+
173
+ function getFilteredSelector(selector, selectorText) {
174
+ const removedSelectors = [];
175
+ selector = { data: cssTree.parse(cssTree.generate(selector.data), { context: "selector" }) };
176
+ filterPseudoClasses(selector);
177
+ if (removedSelectors.length) {
178
+ removedSelectors.forEach(({ parentSelector, selector }) => {
179
+ if (parentSelector.data.children.size == 0 || !selector.prev || selector.prev.data.type == "Combinator" || selector.prev.data.type == "WhiteSpace") {
180
+ parentSelector.data.children.replace(selector, cssTree.parse("*", { context: "selector" }).children.head);
181
+ } else {
182
+ parentSelector.data.children.remove(selector);
183
+ }
184
+ });
185
+ selectorText = cssTree.generate(selector.data).trim();
186
+ }
187
+ return selectorText;
188
+
189
+ function filterPseudoClasses(selector, parentSelector) {
190
+ if (selector.data.children) {
191
+ for (let childSelector = selector.data.children.head; childSelector; childSelector = childSelector.next) {
192
+ filterPseudoClasses(childSelector, selector);
193
+ }
194
+ }
195
+ if ((selector.data.type == "PseudoClassSelector") ||
196
+ (selector.data.type == "PseudoElementSelector" && (testVendorPseudo(selector) || IGNORED_PSEUDO_ELEMENTS.includes(selector.data.name)))) {
197
+ removedSelectors.push({ parentSelector, selector });
198
+ }
199
+ }
200
+
201
+ function testVendorPseudo(selector) {
202
+ const name = selector.data.name;
203
+ return name.startsWith("-") || name.startsWith("\\-");
204
+ }
205
+ }
206
+
207
+ function addRule(element, selectorInfo, styles) {
208
+ const mediaInfo = selectorInfo.ruleInfo.mediaInfo;
209
+ const elementStyle = styles.get(element);
210
+ let elementInfo = mediaInfo.elements.get(element);
211
+ if (!elementInfo) {
212
+ elementInfo = [];
213
+ if (elementStyle) {
214
+ elementInfo.push({ styleInfo: { styleData: elementStyle, declarations: new Set() } });
215
+ }
216
+ mediaInfo.elements.set(element, elementInfo);
217
+ }
218
+ const specificity = computeSpecificity(selectorInfo.selector.data);
219
+ specificity.ruleIndex = selectorInfo.ruleInfo.ruleIndex;
220
+ specificity.sheetIndex = selectorInfo.ruleInfo.sheetIndex;
221
+ selectorInfo.specificity = specificity;
222
+ elementInfo.push(selectorInfo);
223
+ }
224
+
225
+ function computeCascade(mediaInfo, parentMediaInfo, mediaAllInfo, workStylesheet) {
226
+ mediaInfo.elements.forEach((elementInfo/*, element*/) =>
227
+ getDeclarationsInfo(elementInfo, workStylesheet/*, element*/).forEach((declarationsInfo, property) => {
228
+ if (declarationsInfo.selectorInfo.ruleInfo || mediaInfo == mediaAllInfo) {
229
+ let info;
230
+ if (declarationsInfo.selectorInfo.ruleInfo) {
231
+ info = declarationsInfo.selectorInfo.ruleInfo;
232
+ const ruleData = info.ruleData;
233
+ const ascendantMedia = [mediaInfo, ...parentMediaInfo].find(media => media.rules.get(ruleData)) || mediaInfo;
234
+ ascendantMedia.rules.set(ruleData, info);
235
+ if (ruleData) {
236
+ info.matchedSelectors.add(declarationsInfo.selectorInfo.selectorText);
237
+ }
238
+ } else {
239
+ info = declarationsInfo.selectorInfo.styleInfo;
240
+ const styleData = info.styleData;
241
+ const matchedStyleInfo = mediaAllInfo.matchedStyles.get(styleData);
242
+ if (!matchedStyleInfo) {
243
+ mediaAllInfo.matchedStyles.set(styleData, info);
244
+ }
245
+ }
246
+ if (!info.declarations.has(property)) {
247
+ info.declarations.add(property);
248
+ }
249
+ }
250
+ }));
251
+ delete mediaInfo.elements;
252
+ mediaInfo.medias.forEach(childMediaInfo => computeCascade(childMediaInfo, [mediaInfo, ...parentMediaInfo], mediaAllInfo, workStylesheet));
253
+ }
254
+
255
+ function getDeclarationsInfo(elementInfo, workStylesheet/*, element*/) {
256
+ const declarationsInfo = new Map();
257
+ const processedProperties = new Set();
258
+ elementInfo.forEach(selectorInfo => {
259
+ let declarations;
260
+ if (selectorInfo.styleInfo) {
261
+ declarations = selectorInfo.styleInfo.styleData.children;
262
+ } else {
263
+ declarations = selectorInfo.ruleInfo.ruleData.block.children;
264
+ }
265
+ processDeclarations(declarationsInfo, declarations, selectorInfo, processedProperties, workStylesheet);
266
+ });
267
+ return declarationsInfo;
268
+ }
269
+
270
+ function processDeclarations(declarationsInfo, declarations, selectorInfo, processedProperties, workStylesheet) {
271
+ for (let declaration = declarations.tail; declaration; declaration = declaration.prev) {
272
+ const declarationData = declaration.data;
273
+ const declarationText = cssTree.generate(declarationData);
274
+ if (declarationData.type == "Declaration" &&
275
+ (declarationText.match(REGEXP_VENDOR_IDENTIFIER) || !processedProperties.has(declarationData.property) || declarationData.important) && !invalidDeclaration(declarationText, workStylesheet)) {
276
+ const declarationInfo = declarationsInfo.get(declarationData);
277
+ if (!declarationInfo || (declarationData.important && !declarationInfo.important)) {
278
+ declarationsInfo.set(declarationData, { selectorInfo, important: declarationData.important });
279
+ if (!declarationText.match(REGEXP_VENDOR_IDENTIFIER)) {
280
+ processedProperties.add(declarationData.property);
281
+ }
282
+ }
283
+ }
284
+ }
285
+ }
286
+
287
+ function invalidDeclaration(declarationText, workStylesheet) {
288
+ let invalidDeclaration;
289
+ workStylesheet.textContent = "single-file-declaration { " + declarationText + "}";
290
+ if (workStylesheet.sheet && !workStylesheet.sheet.cssRules[0].style.length) {
291
+ if (!declarationText.match(REGEXP_VENDOR_IDENTIFIER)) {
292
+ invalidDeclaration = true;
293
+ }
294
+ }
295
+ return invalidDeclaration;
296
+ }
297
+
298
+ function sortRules(media) {
299
+ media.elements.forEach(elementRules => elementRules.sort((ruleInfo1, ruleInfo2) =>
300
+ ruleInfo1.styleInfo && !ruleInfo2.styleInfo ? -1 :
301
+ !ruleInfo1.styleInfo && ruleInfo2.styleInfo ? 1 :
302
+ compareSpecificity(ruleInfo1.specificity, ruleInfo2.specificity)));
303
+ media.medias.forEach(sortRules);
304
+ }
305
+
306
+ function computeSpecificity(selector, specificity = { a: 0, b: 0, c: 0 }) {
307
+ if (selector.type == "IdSelector") {
308
+ specificity.a++;
309
+ }
310
+ if (selector.type == "ClassSelector" || selector.type == "AttributeSelector" || (selector.type == "PseudoClassSelector" && selector.name != "not")) {
311
+ specificity.b++;
312
+ }
313
+ if ((selector.type == "TypeSelector" && selector.name != "*") || selector.type == "PseudoElementSelector") {
314
+ specificity.c++;
315
+ }
316
+ if (selector.children) {
317
+ selector.children.forEach(selector => computeSpecificity(selector, specificity));
318
+ }
319
+ return specificity;
320
+ }
321
+
322
+ function compareSpecificity(specificity1, specificity2) {
323
+ if (specificity1.a > specificity2.a) {
324
+ return -1;
325
+ } else if (specificity1.a < specificity2.a) {
326
+ return 1;
327
+ } else if (specificity1.b > specificity2.b) {
328
+ return -1;
329
+ } else if (specificity1.b < specificity2.b) {
330
+ return 1;
331
+ } else if (specificity1.c > specificity2.c) {
332
+ return -1;
333
+ } else if (specificity1.c < specificity2.c) {
334
+ return 1;
335
+ } else if (specificity1.sheetIndex > specificity2.sheetIndex) {
336
+ return -1;
337
+ } else if (specificity1.sheetIndex < specificity2.sheetIndex) {
338
+ return 1;
339
+ } else if (specificity1.ruleIndex > specificity2.ruleIndex) {
340
+ return -1;
341
+ } else if (specificity1.ruleIndex < specificity2.ruleIndex) {
342
+ return 1;
343
+ } else {
344
+ return -1;
345
+ }
346
+ }
347
+
348
+ function log(...args) {
349
+ console.log("S-File <css-mat>", ...args); // eslint-disable-line no-console
350
+ }
@@ -0,0 +1,91 @@
1
+ /*
2
+ * Copyright 2010-2020 Gildas Lormeau
3
+ * contact : gildas.lormeau <at> gmail.com
4
+ *
5
+ * This file is part of SingleFile.
6
+ *
7
+ * The code in this file is free software: you can redistribute it and/or
8
+ * modify it under the terms of the GNU Affero General Public License
9
+ * (GNU AGPL) as published by the Free Software Foundation, either version 3
10
+ * of the License, or (at your option) any later version.
11
+ *
12
+ * The code in this file 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 GNU Affero
15
+ * General Public License for more details.
16
+ *
17
+ * As additional permission under GNU AGPL version 3 section 7, you may
18
+ * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
19
+ * AGPL normally required by section 4, provided you include this license
20
+ * notice and a URL through which recipients can access the Corresponding
21
+ * Source.
22
+ */
23
+
24
+ import * as cssTree from "./../vendor/css-tree.js";
25
+ import * as mediaQueryParser from "./../vendor/css-media-query-parser.js";
26
+ import { flatten } from "./../single-file-helper.js";
27
+
28
+ const helper = {
29
+ flatten
30
+ };
31
+
32
+ const MEDIA_ALL = "all";
33
+ const MEDIA_SCREEN = "screen";
34
+
35
+ export {
36
+ process
37
+ };
38
+
39
+ function process(stylesheets) {
40
+ const stats = { processed: 0, discarded: 0 };
41
+ stylesheets.forEach((stylesheetInfo, element) => {
42
+ if (matchesMediaType(stylesheetInfo.mediaText || MEDIA_ALL, MEDIA_SCREEN) && stylesheetInfo.stylesheet.children) {
43
+ const removedRules = processRules(stylesheetInfo.stylesheet.children, stats);
44
+ removedRules.forEach(({ cssRules, cssRule }) => cssRules.remove(cssRule));
45
+ } else {
46
+ stylesheets.delete(element);
47
+ }
48
+ });
49
+ return stats;
50
+ }
51
+
52
+ function processRules(cssRules, stats, removedRules = []) {
53
+ for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
54
+ const ruleData = cssRule.data;
55
+ if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude && ruleData.prelude.children) {
56
+ stats.processed++;
57
+ if (matchesMediaType(cssTree.generate(ruleData.prelude), MEDIA_SCREEN)) {
58
+ processRules(ruleData.block.children, stats, removedRules);
59
+ } else {
60
+ removedRules.push({ cssRules, cssRule });
61
+ stats.discarded++;
62
+ }
63
+ }
64
+ }
65
+ return removedRules;
66
+ }
67
+
68
+ function matchesMediaType(mediaText, mediaType) {
69
+ const foundMediaTypes = helper.flatten(mediaQueryParser.parseMediaList(mediaText).map(node => getMediaTypes(node, mediaType)));
70
+ return foundMediaTypes.find(mediaTypeInfo => (!mediaTypeInfo.not && (mediaTypeInfo.value == mediaType || mediaTypeInfo.value == MEDIA_ALL))
71
+ || (mediaTypeInfo.not && (mediaTypeInfo.value == MEDIA_ALL || mediaTypeInfo.value != mediaType)));
72
+ }
73
+
74
+ function getMediaTypes(parentNode, mediaType, mediaTypes = []) {
75
+ parentNode.nodes.map((node, indexNode) => {
76
+ if (node.type == "media-query") {
77
+ return getMediaTypes(node, mediaType, mediaTypes);
78
+ } else {
79
+ if (node.type == "media-type") {
80
+ const nodeMediaType = { not: Boolean(indexNode && parentNode.nodes[0].type == "keyword" && parentNode.nodes[0].value == "not"), value: node.value };
81
+ if (!mediaTypes.find(mediaType => nodeMediaType.not == mediaType.not && nodeMediaType.value == mediaType.value)) {
82
+ mediaTypes.push(nodeMediaType);
83
+ }
84
+ }
85
+ }
86
+ });
87
+ if (!mediaTypes.length) {
88
+ mediaTypes.push({ not: false, value: MEDIA_ALL });
89
+ }
90
+ return mediaTypes;
91
+ }
@@ -0,0 +1,146 @@
1
+ /*
2
+ * Copyright 2010-2020 Gildas Lormeau
3
+ * contact : gildas.lormeau <at> gmail.com
4
+ *
5
+ * This file is part of SingleFile.
6
+ *
7
+ * The code in this file is free software: you can redistribute it and/or
8
+ * modify it under the terms of the GNU Affero General Public License
9
+ * (GNU AGPL) as published by the Free Software Foundation, either version 3
10
+ * of the License, or (at your option) any later version.
11
+ *
12
+ * The code in this file 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 GNU Affero
15
+ * General Public License for more details.
16
+ *
17
+ * As additional permission under GNU AGPL version 3 section 7, you may
18
+ * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
19
+ * AGPL normally required by section 4, provided you include this license
20
+ * notice and a URL through which recipients can access the Corresponding
21
+ * Source.
22
+ */
23
+
24
+ import * as cssTree from "./../vendor/css-tree.js";
25
+
26
+ const DEBUG = false;
27
+
28
+ export {
29
+ process
30
+ };
31
+
32
+ function process(stylesheets, styles, mediaAllInfo) {
33
+ const stats = { processed: 0, discarded: 0 };
34
+ let sheetIndex = 0;
35
+ stylesheets.forEach(stylesheetInfo => {
36
+ if (!stylesheetInfo.scoped) {
37
+ const cssRules = stylesheetInfo.stylesheet.children;
38
+ if (cssRules) {
39
+ stats.processed += cssRules.size;
40
+ stats.discarded += cssRules.size;
41
+ let mediaInfo;
42
+ if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != "all") {
43
+ mediaInfo = mediaAllInfo.medias.get("style-" + sheetIndex + "-" + stylesheetInfo.mediaText);
44
+ } else {
45
+ mediaInfo = mediaAllInfo;
46
+ }
47
+ processRules(cssRules, sheetIndex, mediaInfo);
48
+ stats.discarded -= cssRules.size;
49
+ }
50
+ }
51
+ sheetIndex++;
52
+ });
53
+ let startTime;
54
+ if (DEBUG) {
55
+ startTime = Date.now();
56
+ log(" -- STARTED processStyleAttribute");
57
+ }
58
+ styles.forEach(style => processStyleAttribute(style, mediaAllInfo));
59
+ if (DEBUG) {
60
+ log(" -- ENDED processStyleAttribute delay =", Date.now() - startTime);
61
+ }
62
+ return stats;
63
+ }
64
+
65
+ function processRules(cssRules, sheetIndex, mediaInfo) {
66
+ let mediaRuleIndex = 0, startTime;
67
+ if (DEBUG && cssRules.size > 1) {
68
+ startTime = Date.now();
69
+ log(" -- STARTED processRules", "rules.length =", cssRules.size);
70
+ }
71
+ const removedCssRules = [];
72
+ for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
73
+ const ruleData = cssRule.data;
74
+ if (ruleData.block && ruleData.block.children && ruleData.prelude && ruleData.prelude.children) {
75
+ if (ruleData.type == "Atrule" && ruleData.name == "media") {
76
+ const mediaText = cssTree.generate(ruleData.prelude);
77
+ processRules(ruleData.block.children, sheetIndex, mediaInfo.medias.get("rule-" + sheetIndex + "-" + mediaRuleIndex + "-" + mediaText));
78
+ if (!ruleData.prelude.children.size || !ruleData.block.children.size) {
79
+ removedCssRules.push(cssRule);
80
+ }
81
+ mediaRuleIndex++;
82
+ } else if (ruleData.type == "Rule") {
83
+ const ruleInfo = mediaInfo.rules.get(ruleData);
84
+ const pseudoSelectors = mediaInfo.pseudoRules.get(ruleData);
85
+ if (!ruleInfo && !pseudoSelectors) {
86
+ removedCssRules.push(cssRule);
87
+ } else if (ruleInfo) {
88
+ processRuleInfo(ruleData, ruleInfo, pseudoSelectors);
89
+ if (!ruleData.prelude.children.size || !ruleData.block.children.size) {
90
+ removedCssRules.push(cssRule);
91
+ }
92
+ }
93
+ }
94
+ } else {
95
+ if (!ruleData || ruleData.type == "Raw" || (ruleData.type == "Rule" && (!ruleData.prelude || ruleData.prelude.type == "Raw"))) {
96
+ removedCssRules.push(cssRule);
97
+ }
98
+ }
99
+ }
100
+ removedCssRules.forEach(cssRule => cssRules.remove(cssRule));
101
+ if (DEBUG && cssRules.size > 1) {
102
+ log(" -- ENDED processRules delay =", Date.now() - startTime);
103
+ }
104
+ }
105
+
106
+ function processRuleInfo(ruleData, ruleInfo, pseudoSelectors) {
107
+ const removedDeclarations = [];
108
+ const removedSelectors = [];
109
+ let pseudoSelectorFound;
110
+ for (let selector = ruleData.prelude.children.head; selector; selector = selector.next) {
111
+ const selectorText = cssTree.generate(selector.data);
112
+ if (pseudoSelectors && pseudoSelectors.has(selectorText)) {
113
+ pseudoSelectorFound = true;
114
+ }
115
+ if (!ruleInfo.matchedSelectors.has(selectorText) && (!pseudoSelectors || !pseudoSelectors.has(selectorText))) {
116
+ removedSelectors.push(selector);
117
+ }
118
+ }
119
+ if (!pseudoSelectorFound) {
120
+ for (let declaration = ruleData.block.children.tail; declaration; declaration = declaration.prev) {
121
+ if (!ruleInfo.declarations.has(declaration.data)) {
122
+ removedDeclarations.push(declaration);
123
+ }
124
+ }
125
+ }
126
+ removedDeclarations.forEach(declaration => ruleData.block.children.remove(declaration));
127
+ removedSelectors.forEach(selector => ruleData.prelude.children.remove(selector));
128
+ }
129
+
130
+ function processStyleAttribute(styleData, mediaAllInfo) {
131
+ const removedDeclarations = [];
132
+ const styleInfo = mediaAllInfo.matchedStyles.get(styleData);
133
+ if (styleInfo) {
134
+ let propertyFound;
135
+ for (let declaration = styleData.children.head; declaration && !propertyFound; declaration = declaration.next) {
136
+ if (!styleInfo.declarations.has(declaration.data)) {
137
+ removedDeclarations.push(declaration);
138
+ }
139
+ }
140
+ removedDeclarations.forEach(declaration => styleData.children.remove(declaration));
141
+ }
142
+ }
143
+
144
+ function log(...args) {
145
+ console.log("S-File <css-min>", ...args); // eslint-disable-line no-console
146
+ }
@@ -0,0 +1,109 @@
1
+ /*
2
+ * Copyright 2010-2020 Gildas Lormeau
3
+ * contact : gildas.lormeau <at> gmail.com
4
+ *
5
+ * This file is part of SingleFile.
6
+ *
7
+ * The code in this file is free software: you can redistribute it and/or
8
+ * modify it under the terms of the GNU Affero General Public License
9
+ * (GNU AGPL) as published by the Free Software Foundation, either version 3
10
+ * of the License, or (at your option) any later version.
11
+ *
12
+ * The code in this file 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 GNU Affero
15
+ * General Public License for more details.
16
+ *
17
+ * As additional permission under GNU AGPL version 3 section 7, you may
18
+ * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
19
+ * AGPL normally required by section 4, provided you include this license
20
+ * notice and a URL through which recipients can access the Corresponding
21
+ * Source.
22
+ */
23
+
24
+ import * as srcsetParser from "./../vendor/html-srcset-parser.js";
25
+
26
+ const EMPTY_RESOURCE = "data:,";
27
+
28
+ export {
29
+ process
30
+ };
31
+
32
+ function process(doc) {
33
+ doc.querySelectorAll("picture").forEach(pictureElement => {
34
+ const imgElement = pictureElement.querySelector("img");
35
+ if (imgElement) {
36
+ let { src, srcset } = getImgSrcData(imgElement);
37
+ if (!src) {
38
+ const data = getSourceSrcData(Array.from(pictureElement.querySelectorAll("source")).reverse());
39
+ src = data.src;
40
+ if (!srcset) {
41
+ srcset = data.srcset;
42
+ }
43
+ }
44
+ setSrc({ src, srcset }, imgElement, pictureElement);
45
+ }
46
+ });
47
+ doc.querySelectorAll(":not(picture) > img[srcset]").forEach(imgElement => setSrc(getImgSrcData(imgElement), imgElement));
48
+ }
49
+
50
+ function getImgSrcData(imgElement) {
51
+ let src = imgElement.getAttribute("src");
52
+ if (src == EMPTY_RESOURCE) {
53
+ src = null;
54
+ }
55
+ let srcset = getSourceSrc(imgElement.getAttribute("srcset"));
56
+ if (srcset == EMPTY_RESOURCE) {
57
+ srcset = null;
58
+ }
59
+ return { src, srcset };
60
+ }
61
+
62
+ function getSourceSrcData(sources) {
63
+ let source = sources.find(source => source.src);
64
+ let src = source && source.src;
65
+ let srcset = source && source.srcset;
66
+ if (!src) {
67
+ source = sources.find(source => getSourceSrc(source.src));
68
+ src = source && source.src;
69
+ if (src == EMPTY_RESOURCE) {
70
+ src = null;
71
+ }
72
+ }
73
+ if (!srcset) {
74
+ source = sources.find(source => getSourceSrc(source.srcset));
75
+ srcset = source && source.srcset;
76
+ if (srcset == EMPTY_RESOURCE) {
77
+ srcset = null;
78
+ }
79
+ }
80
+ return { src, srcset };
81
+ }
82
+
83
+ function setSrc(srcData, imgElement, pictureElement) {
84
+ if (srcData.src) {
85
+ imgElement.setAttribute("src", srcData.src);
86
+ imgElement.setAttribute("srcset", "");
87
+ imgElement.setAttribute("sizes", "");
88
+ } else {
89
+ imgElement.setAttribute("src", EMPTY_RESOURCE);
90
+ if (srcData.srcset) {
91
+ imgElement.setAttribute("srcset", srcData.srcset);
92
+ } else {
93
+ imgElement.setAttribute("srcset", "");
94
+ imgElement.setAttribute("sizes", "");
95
+ }
96
+ }
97
+ if (pictureElement) {
98
+ pictureElement.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
99
+ }
100
+ }
101
+
102
+ function getSourceSrc(sourceSrcSet) {
103
+ if (sourceSrcSet) {
104
+ const srcset = srcsetParser.process(sourceSrcSet);
105
+ if (srcset.length) {
106
+ return (srcset.find(srcset => srcset.url)).url;
107
+ }
108
+ }
109
+ }