This repository was archived by the owner on Jul 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (78 loc) · 2.31 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
73
74
75
76
77
78
79
80
81
const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');
class CrossMailWarrior{
constructor(opts) {
if (opts.cloneToAttrs) {
this.setToAttrs = opts.cloneToAttrs
} else {
this.setToAttrs = ['data-lang']
}
if (opts.valuePrefix) {
this.valuePrefix = opts.valuePrefix
} else {
this.valuePrefix = ''
}
if (opts.setImportants !== undefined) {
this.setImportants = opts.setImportants
} else {
this.setImportants = true;
}
if (!opts.paths) {
this.srcDir = path.join(__dirname, 'source');
this.destDir = path.join(__dirname, 'dest');
} else {
this.srcDir = opts.paths.source ? opts.paths.source : path.join(__dirname, 'source');
this.destDir = opts.paths.dest ? opts.paths.dest : path.join(__dirname, 'dest');
}
this.srcFiles = fs.readdirSync(this.srcDir, 'utf-8');
for (let file of this.srcFiles) {
this._replace(file);
}
}
_replace(file) {
const $ = cheerio.load(fs.readFileSync(path.join(this.srcDir, file)))
for (let element of $('body *').toArray()) {
if (element.attribs.class) {
for (let attr of this.setToAttrs) {
$(element).attr(attr, this.valuePrefix + element.attribs.class);
}
}
}
let str = $('style').html();
if (this.setImportants) {
str = str.replace(/[\;]\n/g, ' !important;\n');
}
const regex = /\.([^>,:\s{.]+)/gm;
let m,
matches = [];
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
matches.push(m[0])
};
let uniqMatches = [...new Set(matches)];
uniqMatches.reverse().forEach(match => {
str = this._replaceStyleString(str, match)
});
$('style').html(str);
fs.writeFileSync(path.join(this.destDir, file), $.html(), 'utf-8');
}
_replaceStyleString(styles, match) {
console.log("start replacing =================")
console.log(styles, match)
const currentClass = match;
let strToReplace = '';
for (let attr of this.setToAttrs) {
if (Number(strToReplace.length) === 0) {
strToReplace = `[${attr}=${this.valuePrefix}${currentClass.replace('.', '')}] `;
} else {
strToReplace += `, [${attr}=${this.valuePrefix}${currentClass.replace('.', '')}] `;
}
}
let replaced = styles.replace(new RegExp('\\'+currentClass+'[^_:-]', 'g'), strToReplace);
return replaced;
}
}
module.exports = CrossMailWarrior