-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (57 loc) · 1.88 KB
/
index.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
"use strict";
const PLUGIN_NAME = 'gulp-feather';
const PluginError = require('plugin-error');
const through = require('through2');
const { JSDOM } = require('jsdom');
const { replace } = require('feather-icons');
function emulateBrowser(dom, execFunc) {
const savedVariables = new Map();
// override document and DOMParser
if (typeof global.document !== 'undefined') {
savedVariables.set('document', global.document);
}
global.document = dom.window.document;
if (typeof global.DOMParser !== 'undefined') {
savedVariables.set('DOMParser', global.DOMParser);
}
global.DOMParser = dom.window.DOMParser;
execFunc();
// restore overrided variables
if (savedVariables.has('document')) {
global.document = savedVariables.get('document');
}
if (savedVariables.has('DOMParser')) {
global.DOMParser = savedVariables.get('DOMParser');
}
}
module.exports = (attrs = {}) => through.obj(function (file, encoding, cb) {
if (file.isNull()) {
// nothing to do
return cb(null, file);
}
if (file.isStream()) {
// might support stream in the future
const err = new PluginError(PLUGIN_NAME, 'Streams not supported!');
this.emit('error', err);
return cb(err);
}
if (file.isBuffer()) {
// create dom from html file
const dom = new JSDOM(file.contents, { runScripts: 'outside-only' });
// replace feathericons in an emulated browser environment
emulateBrowser(dom, ()=>replace(attrs));
// output to file contents
const HTMLResult = dom.serialize();
if (file.contents.length < HTMLResult.length) {
const buf = Buffer.from(HTMLResult, encoding);
file.contents = buf;
} else {
file.contents.write(HTMLResult, encoding);
}
return cb(null, file);
}
// this should be unreachable
const err = new PluginError(PLUGIN_NAME, 'Unexpected type of input');
this.emit('error', err);
return cb(err);
});