-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
111 lines (84 loc) · 3.19 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
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
import fs from "fs-extra";
import puppeteer from "puppeteer";
import path from "path";
export async function fit(srcs, dests, options = { silent: false }){
if(typeof srcs !== 'string' && !Array.isArray(srcs)){
throw new Error('src must be an array or a string.');
}
if(typeof dests !== 'string' && !Array.isArray(dests)){
throw new Error('dest must be an array or a string.');
}
let opts = Object.assign({
puppeteer: {
args: ['--headless', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']
}
}, options);
srcs = Array.isArray(srcs) ? srcs : [srcs];
dests = Array.isArray(dests) ? dests : [dests];
if(srcs.length !== dests.length && dests.find(d => path.extname(d) === '.svg')){
throw new Error('uneven number of src and dest files.');
}
let inputs;
try{
inputs = srcs.reduce((concat, src, i) => {
let arr = [];
if(fs.existsSync(src)){
if(fs.lstatSync(src).isDirectory()){
arr = fs.readdirSync(src).map(d => ({src: `${src}/${d}`}));
} else {
arr = [{src}];
}
}
let dest = dests[i % dests.length];
let destIsFile = path.extname(dest) !== '';
let destPath = destIsFile ? path.dirname(dest) : dest;
fs.mkdirpSync(destPath);
arr = arr.map(input => {
return {
src: input.src,
dest: destIsFile ? dest : `${destPath}/${path.basename(input.src)}`
};
});
return concat.concat(arr);
}, []);
} catch(e){console.log(e);}
inputs.forEach(d => {
if(path.extname(d.src) !== '.svg'){
throw new Error('some srcs are non svg files.');
}
if(path.extname(d.dest) !== '.svg'){
throw new Error('some dest files have a non svg extension.');
}
});
const browser = await puppeteer.launch({
executablePath: opts.puppeteer.executablePath,
args: opts.puppeteer.args,
});
try{
const page = await browser.newPage();
for(let i = inputs.length; i--;){
let input = inputs[i];
let svg = fs.readFileSync(input.src, {encoding: 'utf8'});
await page.setContent(svg);
const result = await (await page.waitForSelector("svg")).evaluate((el) => {
let { x, y, width, height } = el.getBBox();
el.setAttribute('viewBox', `${x} ${y} ${width} ${height}`);
if(el.hasAttribute('width')){
el.setAttribute('width', width);
}
if(el.hasAttribute('height')){
el.setAttribute('height', height);
}
return el.outerHTML;
});
fs.writeFileSync(`${input.dest}`, result);
if(!opts.silent){
console.log(`\x1b[32m%s\x1b[0m`, `✔`, `${input.src} fitted.`);
}
}
} catch(e){console.log(e);}
await browser.close();
}
export default {
fit
};