This repository has been archived by the owner on Oct 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 76
/
critical.js
278 lines (226 loc) · 7.32 KB
/
critical.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/*global require:true*/
/*global console:true*/
/*global __dirname:true*/
/* eslint esnext: true */
(function( exports ){
"use strict";
var execFile = require("child_process").execFile;
var path = require( "path" );
var fs = require( "fs" );
var os = require( "os" );
var postcss = require( "postcss" );
var css = require("css");
var _ = require("lodash");
const atf = require("./lib/atf.js");
const rules = require("./lib/rules.js");
// add finally to build in Promise, will no-op when added to node
require("promise.prototype.finally").shim();
exports.getRules = function( cssfile, opts, cb ){
var defaultCb = function( err, output ){
if( err ){
throw new Error( err );
}
};
if( typeof cssfile !== "string" ){
throw new TypeError( "The CSS filename must be a string" );
}
if( !fs.existsSync( cssfile ) ){
throw new Error( "CSS file must exist" );
}
if( typeof opts === "undefined" && typeof cb === "undefined" ){
opts = {};
cb = defaultCb;
}
if( typeof opts === "function" ){
cb = opts;
opts = {};
}
cb = cb || defaultCb;
return rules(cssfile)
.then((rules) => { cb(null, rules); return rules; })
.catch((err) => cb(err, null));
};
exports.findCritical = function( url, opts, cb ){
var defaultCb = function( err, output ){
if( err ){
throw new Error( err );
}
};
if( typeof url !== "string" ){
throw new TypeError( "URL must be a string" );
}
if( typeof opts === "undefined" && typeof cb === "undefined" ){
opts = {};
cb = defaultCb;
}
if( typeof opts === "function" ){
cb = opts;
opts = {};
}
cb = cb || defaultCb;
var width = opts.width || 1200;
var height = opts.height || 900;
var forceInclude = opts.forceInclude || [];
var rules = opts.rules || [];
var usepostcss = opts.postcss;
var tmpfile;
if( !Array.isArray( forceInclude ) ){
throw new Error( "forceInclude must be an array of selectors" );
}
var rulesString = JSON.stringify( rules );
// TODO use "tmp" file library instead of date time
tmpfile = path.join( os.tmpdir(), "criticalcss-findcritical-rules" + (new Date()).getTime());
try {
fs.writeFileSync( tmpfile, rulesString );
} catch( e ){
throw e;
}
// TODO switch tmpfile to js object
return atf(url, width, height, forceInclude, tmpfile)
.then((critCSS) => {
if( usepostcss ){
return postcss([ require('postcss-initial') ])
.process(critCSS)
.then(function (result) {
cb(null, result.css);
return result.css;
});
}
cb( null, critCSS);
return critCSS;
})
.catch((err) => cb(err, null))
.finally(() => {
if( fs.existsSync(tmpfile) ){
fs.unlinkSync(tmpfile);
}
});
};
// create a function that can be passed to `map` for a collection of critical
// css rules. The function will match original rules against the selector of
// the critical css declarations, concatenate them together, and then keep
// only the unique ones
function replaceDecls(originalRules, criticalRule){
// find all the rules in the original CSS that have the same selectors and
// then create an array of all the associated declarations. Note that this
// works with mutiple duplicate selectors on the original CSS
var originalDecls = _.flatten(
originalRules
.filter(function(rule){
return _.isEqual(rule.selectors, criticalRule.selectors);
})
.map(function(rule){
return rule.declarations;
})
);
// take all the declarations that were found from the original CSS and use
// them here, make sure that we de-dup any declarations from the original CSS
criticalRule.declarations =
_.uniqBy(criticalRule.declarations.concat(originalDecls), function(decl){
return decl.property + ":" + decl.value;
});
return criticalRule;
}
function replace(originalRules){
return function (critical){
if( nested.indexOf(critical.type) == -1 && critical.type === "rule"){
return replaceDecls(originalRules, critical);
}
var type = critical.type;
// find all the rules that apply for the current nested rule
var originalNestedRules;
// get all of the rules inside nested stuff that match the critical
// nested selector text
originalNestedRules = _.flatten(
originalRules
.filter(function(rule){
return rule[type] == critical[type];
})
.map(function(nested){
return nested.rules;
})
);
// replace the declarations in each of the rules for this media query
// with the declarations in the original css for the same media query
critical.rules = critical
.rules
.map(replace(originalNestedRules));
return critical;
};
}
var nested = ["media", "supports", "document"];
exports.restoreOriginalDefs = function(originalCSS, criticalCSS, stringifyOpts){
// parse both the original CSS and the critical CSS so we can deal with the
// ASTs directly
var originalAST = css.parse(originalCSS);
var criticalAST = css.parse(criticalCSS);
var newRules;
// map our replace over all the rules in the critical AST
criticalAST.stylesheet.rules = criticalAST
.stylesheet
.rules
.map(replace(originalAST.stylesheet.rules));
// return the CSS as a string
return css.stringify(criticalAST, stringifyOpts);
};
function collectFontFamilies(rule){
return rule.declarations.reduce(function(acc, decl){
if(decl.property === "font-family"){
acc.push(decl.value);
}
return acc;
}, []);
}
exports.restoreFontFaces = function(originalCSS, criticalCSS, stringifyOpts){
// parse both the original CSS and the critical CSS so we can deal with the
// ASTs directly
var originalAST = css.parse(originalCSS);
var criticalAST = css.parse(criticalCSS);
var fontFaceRules, requiredFontFamilies, requiredFontFaces;
fontFaceRules = originalAST
.stylesheet
.rules
.filter(function(rule){
return rule.type === "font-face";
});
requiredFontFamilies = criticalAST
.stylesheet
.rules
.reduce(function(acc, rule){
var type = rule.type;
if(type === "rule") {
return acc.concat(collectFontFamilies(rule));
} else if (nested.indexOf(type) > -1){
return acc.concat(_.flatten(rule.rules.map(function(nestedRule){
return collectFontFamilies(nestedRule);
})));
} else {
return acc;
}
}, []);
requiredFontFaces = requiredFontFamilies.reduce(function(acc, requiredFamily){
return acc.concat(fontFaceRules.filter(function(fontFace){
var familyNameDecls, familyName;
familyNameDecls = fontFace
.declarations
.filter(function(decl){
return decl.property == "font-family";
});
// choose the value of the last of many possibly family name declarations
familyName = familyNameDecls[familyNameDecls.length - 1]
.value
.replace(/'|"/g, "");
// if the required family matches the family name of the rule
// then we want to keep this font face
return requiredFamily.indexOf(familyName) > -1;
}));
}, []);
// the above reduce will include each font face for every appearence
// in a `font-family` declaration, here we remove duplicates
requiredFontFaces = _.uniq(requiredFontFaces);
// prepend the font faces to the critical css output
criticalAST.stylesheet.rules =
requiredFontFaces.concat(criticalAST.stylesheet.rules);
return css.stringify(criticalAST, stringifyOpts);
};
}(typeof exports === "object" && exports || this));