-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathcomponents-build-screenshots.js
180 lines (162 loc) · 7.11 KB
/
components-build-screenshots.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
const _ = require('lodash');
const chalk = require('chalk');
const co = require('co');
const express = require('express');
const filesize = require('filesize');
const fs = require('fs');
const imagemin = require('imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const Jimp = require('jimp');
const Nightmare = require('nightmare');
const path = require('path');
const prettyHrtime = require('pretty-hrtime');
const tmp = require('tmp');
const defaults = require('./components-build-defaults');
const startServer = options => new Promise((resolve) => {
const app = express();
app.set('port', options.serverPort);
app.use(express.static(path.join(__dirname, '..')));
const server = app.listen(app.get('port'), () => {
console.log('- Started static HTML server on port:', server.address().port);
resolve(server);
});
});
const initNightmare = () => Nightmare({ // eslint-disable-line
show: false,
frame: false,
useContentSize: true,
switches: {
// Unfortunately .viewport() sets the viewport size in *CSS pixels*.
// Let's force device pixel ratio to 1 otherwise screenshots will vary in size
// depending on the machine running this script (double for Retina Macbook Pro)
// https://github.com/segmentio/nightmare/issues/498#issuecomment-265948400
'force-device-scale-factor': '1',
},
});
const formatFromSizeToSize = (from, to) => `(${filesize(from)} => ${filesize(to)})`;
module.exports = _options => new Promise((resolve, reject) => {
const options = _.merge({}, defaults, _options);
const startTime = process.hrtime();
console.log(chalk.magenta('Working on components screenshots...'));
if (options.components.tempListPath === undefined ||
!fs.existsSync(options.components.tempListPath)) {
reject('Can not find components list (JSON)');
return;
}
if (!options.components.build.screenshots) {
console.log(chalk.dim('Skipped by request.'));
resolve();
return;
}
const components = JSON.parse(fs.readFileSync(options.components.tempListPath, 'utf8'));
const nightmare = initNightmare();
let tmpTotalFileSize = 0;
let screenshotTotalFileSize = 0;
const renderPromise = co(function* generator() {
// Setup a quick static HTML server so that CSS is loaded correctly.
const server = yield startServer(options);
// Unfortunately, can't use forEach() in generators, so let's for()...
for (let comp_idx = 0; comp_idx < components.length; comp_idx += 1) {
const component = components[comp_idx];
const frontMatter = _.merge({}, options.components.frontMatter, component.frontMatter);
// Grab the size of the component enclosing rectangle
// https://github.com/segmentio/nightmare/issues/498#issuecomment-189156529
const componentRect = yield nightmare
.viewport(options.screenshot.viewport.width, options.screenshot.viewport.height)
// .wait(1000)
.goto(`http://localhost:${options.serverPort}${component.page.href}`)
.wait(frontMatter.screenshot.selector)
.evaluate((_selector) => {
// Hide scrollbar that could pop up due to .scrollTo
const styleEl = document.createElement('style');
document.head.appendChild(styleEl);
styleEl.sheet.insertRule('::-webkit-scrollbar { display:none; }', 0);
const element = document.querySelector(_selector);
if (element) {
const rect = element.getBoundingClientRect();
return {
x: Math.round(rect.left),
y: Math.round(rect.top),
width: Math.round(rect.width),
height: Math.round(rect.height),
};
}
return false;
}, frontMatter.screenshot.selector);
// Capture the component
if (componentRect === false) {
console.log(chalk.red(' * FAILED to create screenshot:'), component.screenshot.path);
continue; // eslint-disable-line
}
const screenshotDir = path.dirname(component.screenshot.path);
const tmpPngObj = tmp.fileSync({ dir: screenshotDir });
componentRect.height = Math.min(componentRect.height, options.screenshot.viewport.height);
yield nightmare
// we can not use .screenshot() with componentRect, so constrain the viewport instead
.viewport(
componentRect.width || options.screenshot.viewport.width,
componentRect.height || options.screenshot.viewport.height
).scrollTo(componentRect.y, componentRect.x)
// .wait(1000)
.screenshot(tmpPngObj.name); // do *not* use componentRect here or risk distortions
// Resize and convert to JPEG, and optimize
const tmpJpegDirObj = tmp.dirSync({ dir: screenshotDir, unsafeCleanup: true });
const tmpJpegPath = path.join(tmpJpegDirObj.name, path.basename(component.screenshot.path));
const screenshot = yield Jimp.read(tmpPngObj.name);
yield new Promise((write_resolve, write_reject) => {
if (frontMatter.screenshot.autocrop) {
screenshot.autocrop(false);
}
// Allow shrinking, up to a point
const scaleHeight = screenshot.bitmap.height <= options.screenshot.target.minHeight
? 0.0 : options.screenshot.target.minHeight / screenshot.bitmap.height;
const scaleWidth = screenshot.bitmap.width <= options.screenshot.target.minWidth
? 0.0 : options.screenshot.target.minWidth / screenshot.bitmap.width;
const scale = Math.max(scaleHeight, scaleWidth);
screenshot
.scale(scale > 0 ? scale : 1.0)
// Do not use .quality() here, default max quality helps optimizers below
.write(tmpJpegPath, (jimp_err) => {
if (jimp_err) {
write_reject(jimp_err);
}
// Optimize
imagemin([tmpJpegPath], screenshotDir, {
plugins: [
imageminMozjpeg({ quality: options.screenshot.mozjpegQuality }),
// imageminJpegRecompress(), // this guy is useless
// imageminJpegtran(), // this guy is useless
],
}).then(() => {
write_resolve();
}).catch((imagemin_err) => {
write_reject(imagemin_err);
});
});
});
const tmpFileSize = fs.statSync(tmpPngObj.name).size;
tmpTotalFileSize += tmpFileSize;
const screenshotFileSize = fs.statSync(component.screenshot.path).size;
screenshotTotalFileSize += screenshotFileSize;
// Cleanup
tmpPngObj.removeCallback();
fs.unlinkSync(tmpJpegPath);
tmpJpegDirObj.removeCallback();
console.log(
' * Created screenshot:',
component.screenshot.path,
chalk.dim(formatFromSizeToSize(tmpFileSize, screenshotFileSize))
);
} // Loop over components
yield nightmare.end();
server.close();
console.log('- Closed static HTML server');
const elapsed = process.hrtime(startTime);
console.log(
chalk.magenta('Done with components screenshots!'),
chalk.dim(formatFromSizeToSize(tmpTotalFileSize, screenshotTotalFileSize)),
chalk.dim(prettyHrtime(elapsed))
);
});
resolve(renderPromise);
}); // return promise