forked from gskinner/regexr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.babel.js
361 lines (328 loc) · 9.58 KB
/
gulpfile.babel.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// imports
const gulp = require("gulp");
const inject = require("gulp-inject");
const rename = require("gulp-rename");
const template = require("gulp-template");
const sass = require("gulp-sass");
const cleanCSS = require("gulp-clean-css");
const htmlmin = require("gulp-htmlmin");
const svgstore = require("gulp-svgstore");
const svgmin = require("gulp-svgmin");
const autoprefixer = require("gulp-autoprefixer");
const rollup = require("rollup");
const babel = require("rollup-plugin-babel");
const uglify = require("rollup-plugin-uglify").uglify;
const replace = require("rollup-plugin-replace");
const browser = require("browser-sync").create();
const Vinyl = require("vinyl");
const Buffer = require("buffer").Buffer;
const del = require("del");
const Readable = require("stream").Readable;
const createHash = require("crypto").createHash;
const fs = require("fs");
const basename = require("path").basename;
// constants
const isProduction = () => process.env.NODE_ENV === "production";
const pkg = require("./package.json");
const babelPlugin = babel({
presets: [["@babel/env", {modules: false}]],
babelrc: false
});
const replacePlugin = replace({
delimiters: ["<%= ", " %>"],
"build_version": pkg.version,
"build_date": getDateString()
});
const uglifyPlugin = uglify();
let bundleCache;
const serverCopyAndWatchGlob = [
"index.php", "server/**",
"!server/**/composer.*",
"!server/**/*.sql",
"!server/**/*.md",
"!server/gulpfile.js",
"!server/Config*.php",
"!server/**/*package*.json",
"!server/{.git*,.git/**}",
"!server/node_modules/",
"!server/node_modules/**",
];
// tasks
gulp.task("serve", () => {
browser.init({
server: {baseDir: "./"},
options: {ignored: "./dev/**/*"}
});
});
gulp.task("watch", () => {
gulp.watch("./dev/src/**/*.js", gulp.series("js", "browserreload"));
gulp.watch("./index.html", gulp.series("browserreload"));
gulp.watch("./dev/icons/*.svg", gulp.series("icons"));
gulp.watch("./dev/inject/*", gulp.series("inject", "browserreload"));
// sass watch ignores colors_* files (themes)
gulp.watch(["./dev/sass/**/*.scss", "!**/colors_*.scss"], gulp.series("sass"));
// set up chokidar watcher to re-render themes
gulp.watch("./dev/sass/colors_*.scss").on("change", renderTheme);
});
gulp.task("browserreload", (done) => {
browser.reload();
done();
});
gulp.task("watch-server", () => {
return gulp.watch(serverCopyAndWatchGlob, gulp.series("copy-server"));
});
gulp.task("js", () => {
const plugins = [babelPlugin, replacePlugin];
if (isProduction()) { plugins.push(uglifyPlugin); }
return rollup.rollup({
input: "./dev/src/app.js",
cache: bundleCache,
moduleContext: {
"./dev/lib/codemirror.js": "window",
"./dev/lib/clipboard.js": "window",
"./dev/lib/native.js": "window"
},
plugins,
onwarn: (warning, warn) => {
// ignore circular dependency warnings
if (warning.code === "CIRCULAR_DEPENDENCY") { return; }
warn(warning);
}
}).then(bundle => {
bundleCache = bundle.cache;
return bundle.write({
format: "iife",
file: "./deploy/regexr.js",
name: "regexr",
sourcemap: !isProduction()
})
});
});
gulp.task("sass", () => {
const str = buildSass("default")
.pipe(rename("regexr.css"))
.pipe(gulp.dest("deploy"));
return isProduction()
? str
: str.pipe(browser.stream());
});
// create tasks for all themes
fs.readdirSync("./dev/sass").filter(f => /colors_\w+\.scss/.test(f)).forEach(f => {
const theme = getThemeFromPath(f);
gulp.task(`sass-${theme}`, () => {
return diffTheme(theme).then(() => {
return gulp.src(`./assets/themes/${theme}.css`)
.pipe(browser.stream());
})
});
});
// manually render a theme via task, called from the chokidar listener in the watch task
const renderTheme = filename => {
const theme = getThemeFromPath(basename(filename));
// wrapped in series() so it shows in the console
gulp.series(gulp.task(`sass-${theme}`))();
};
gulp.task("html", () => {
return gulp.src("./index.html")
.pipe(template({
js_version: createFileHash("deploy/regexr.js"),
css_version: createFileHash("deploy/regexr.css")
}))
.pipe(htmlmin({
collapseWhitespace: true,
conservativeCollapse: true,
removeComments: true
}))
.pipe(gulp.dest("build"));
});
gulp.task("icons", () => {
return gulp.src("dev/icons/*.svg")
// strip fill attributes and style tags to facilitate CSS styling:
.pipe(svgmin({
plugins: [
{removeAttrs: {attrs: "fill"}},
{removeStyleElement: true}
]}
))
.pipe(svgstore({inlineSvg: true}))
.pipe(gulp.dest("dev/inject"));
});
gulp.task("inject", () => {
return gulp.src("index.html")
.pipe(inject(gulp.src("dev/inject/*"), {
transform: (path, file) => {
const tag = /\.css$/ig.test(path) ? "style" : "";
return (tag ? `<${tag}>` : "") + file.contents.toString() + (tag ? `</${tag}>` : "");
}
}))
.pipe(gulp.dest("."));
});
gulp.task("clean", () => {
return del([
"build/**",
"!build",
"!build/sitemap.txt",
"!build/{.git*,.git/**}",
"!build/v1/**"
]);
});
gulp.task("copy", () => {
// index.html is copied in by the html task
return gulp.src([
"deploy/**", "assets/**", "!deploy/*.map", ...serverCopyAndWatchGlob
], {base: "./"})
.pipe(gulp.dest("./build/"));
});
gulp.task("copy-server", () => {
// index.html is copied in by the html task
return gulp.src(serverCopyAndWatchGlob, {base: "./"})
.pipe(gulp.dest("./build/"));
});
gulp.task("build", gulp.parallel("js", "sass"));
gulp.task("server", gulp.series("copy-server", "watch-server"));
gulp.task("default",
gulp.series("build",
gulp.parallel("serve", "watch")
)
);
gulp.task("deploy",
gulp.series(
cb => (process.env.NODE_ENV = "production") && cb(),
"clean", "build", "html", "copy"
)
);
// helpers
function createFileHash(filename) {
const hash = createHash("sha256");
const fileContents = fs.readFileSync(filename, "utf-8");
hash.update(fileContents);
return hash.digest("hex").slice(0, 9);
}
function getDateString() {
const now = new Date();
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return `${months[now.getMonth()]} ${now.getDate()}, ${now.getFullYear()}`;
}
// theme "default", "light", "dark"
function buildSass(theme) {
// read (s)css dependencies for the temp file
const libs = fs.readdirSync("./dev/lib").filter(file => /\.s?css$/.test(file));
const base = "./dev/sass/";
// sass file that is piped into the stream from memory
const tmpSass = `
${libs.map(f => `@import "../lib/${basename(f)}";`).join("\n")}
@import "./colors${theme === "default" ? "" : "_" + theme}.scss";
@import "./regexr.scss";
`;
const tmpFile = new Vinyl({
cwd: "/",
base,
path: `${base + theme}.scss`,
contents: Buffer.from(tmpSass)
});
// open an object stream and read the vinyl file in, piping thru the sass compilation
const src = Readable({ objectMode: true });
src._read = () => {
src.push(tmpFile);
src.push(null); // required for gulp to close properly
};
return src
.pipe(sass().on("error", sass.logError))
.pipe(autoprefixer({remove: false}))
.pipe(cleanCSS());
}
function diffTheme(theme) {
const css = {};
return Promise.all(
// render both the default styles and the theme styles, saving the results
["default", theme].map(type => new Promise((resolve, reject) => {
buildSass(type).on("data", file => {
css[type] = file.contents.toString();
resolve();
});
}))
).then(() => new Promise((resolve, reject) => {
// diff the results, writing the results as the theme to override defaults
const diff = (new CSSDiff()).diff(css.default, css[theme]);
fs.writeFile(`./assets/themes/${theme}.css`, diff, resolve);
}));
}
function getThemeFromPath(filename) {
return filename.match(/_(\w+)\.scss/)[1];
}
class CSSDiff {
diff(base, targ, pretty = false) {
let diff = this.compare(this.parse(base), this.parse(targ));
return this._writeDiff(diff, pretty);
}
parse(s, o = {}) {
this._parse(s, /([^\n\r\{\}]+?)\s*\{\s*/g, /\}/g, o);
for (let n in o) {
if (n === " keys") { continue; }
o[n] = this.parseBlock(o[n]);
}
return o;
}
parseBlock(s, o = {}) {
return this._parse(s, /([^\s:]+)\s*:/g, /(?:;|$)/g, o);
}
compare(o0, o1, o = {}) {
let keys = o1[" keys"], l=keys.length, arr=[];
for (let i=0; i<l; i++) {
let n = keys[i];
if (!o0[n]) { o[n] = o1[n]; arr.push(n); continue; }
let diff = this._compareBlock(o0[n], o1[n]);
if (diff) { o[n] = diff; arr.push(n); }
}
o[" keys"] = arr;
return o;
}
_compareBlock(o0, o1) {
let keys = o1[" keys"], l=keys.length, arr=[], o;
for (let i=0; i<l; i++) {
let n = keys[i];
if (o0[n] === o1[n]) { continue; }
if (!o) { o = {}; }
o[n] = o1[n];
arr.push(n);
}
if (o) { o[" keys"] = arr; }
return o;
}
_parse(s, keyRE, closeRE, o) {
let i, match, arr=[];
while (match = keyRE.exec(s)) {
let key = match[1];
i = closeRE.lastIndex = keyRE.lastIndex;
if (!(match = closeRE.exec(s))) { console.log("couldn't find close", key); break; }
o[key] = s.substring(i, closeRE.lastIndex-match[0].length).trim();
i = keyRE.lastIndex = closeRE.lastIndex;
arr.push(key);
}
o[" keys"] = arr;
return o;
}
_writeDiff(o, pretty = false) {
let diff = "", ln="\n", s=" ";
if (!pretty) { ln = s = ""; }
let keys = o[" keys"], l=keys.length;
for (let i=0; i<l; i++) {
let n = keys[i];
if (diff) { diff += ln + ln; }
diff += n + s + "{" + ln;
diff += this._writeBlock(o[n], pretty);
diff += "}";
}
return diff;
}
_writeBlock(o, pretty = false) {
let diff = "", ln="\n", t="\t", s=" ";
if (!pretty) { ln = t = s = ""; }
let keys = o[" keys"], l=keys.length;
for (let i=0; i<l; i++) {
let n = keys[i];
diff += t + n + ":" + s + o[n] + ";" + ln;
}
return diff;
}
}