-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·291 lines (261 loc) · 8.21 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
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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const program = require('commander');
const htmlClean = require('htmlclean');
const cheerio = require('cheerio');
require('colors');
const iconTemplate = require('./src/icon-template');
const iconFamilyMap = require('./src/icon-family-map');
let outputPath,
filePath,
fileName,
extension,
outputMap = {},
outputFileName = 'icon-symbols.js',
defaultOptions = {
family: 'material',
directory: '',
map: true,
prepend: false,
icons: []
};
// start read line
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.write('Building Icons...');
runProgram()
.then(getFile)
.then(constructData)
.then(buildIcons)
.then(buildFile)
.then(() => {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
console.log('Success!'.green);
rl.close();
})
.catch(err => {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
console.log(`[ico Error] ${err}`.red);
rl.close();
});
/**
* Run Program
* run commander and setup paths and things
* @return {Promise}
*/
function runProgram() {
return new Promise((resolve, reject) => {
program
.description(`Command line tool for quickly building icon sets`)
.arguments('<file> [path]')
.option(`-O, --output [output]`, `Set output path. Defaults to <file> location.`)
.action(function(file) {
// normalize file path (includes file name)
filePath = `/${path.relative('/', path.normalize(file))}`;
let filePathParsed = path.parse(filePath);
// extension
if (filePathParsed.ext === '.js' || filePathParsed.ext === '.json') {
extension = filePathParsed.ext;
} else {
reject(`<file> must be a JSON or JS file`);
return;
}
// file name
fileName = filePathParsed.name + filePathParsed.ext;
// output path
if (program.output) {
outputPath = `/${path.relative('/', path.normalize(program.output))}`;
} else {
outputPath = filePathParsed.dir;
}
})
.parse(process.argv);
if (!filePath) {
reject(`<file> is required`);
return;
}
resolve();
});
}
/**
* Get File
* get file depending on extension
* @return {Promise} resolves the file contents
*/
function getFile() {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
rl.write('Getting File...');
return new Promise((resolve, reject) => {
// read json file
if (extension === '.json') {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
reject(`Could not open "${filePath}".`, err);
} else {
resolve(JSON.parse(data));
}
});
}
// require module
else if (extension === '.js') {
resolve(require(filePath));
}
});
}
/**
* Construct Data
* build icon collection based on file config
* @param data {Object}
* @return {Promise}
*/
function constructData(data) {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
rl.write('Constructing Data...');
return new Promise((resolve, reject) => {
// data should be an object
if (typeof data !== 'object') {
reject('Icon configuration should be an "Object" or "Array" type.');
return;
}
// if set is a collection, make sure all configs have a prepend
if (data.length && data.filter(config => typeof config.prepend === 'string').length !== data.length) {
reject('A collection of icon configs requires option "prepend" to avoid naming collisions');
return;
}
/** single config **/
// put it in an array and handle it like a collection
if (data && data.icons) {
data = [data];
}
// validate family names
let invalidFamilyNames = data.filter(config => !iconFamilyMap[config.family] && !config.directory);
if (invalidFamilyNames.length) {
reject(`Invalid icon family [${invalidFamilyNames.map(config => config.family || '?').join(', ')}] - available sets: [${Object.keys(iconFamilyMap).join(', ')}]`);
return;
}
/** collection of configs **/
if (data && data.length) {
data = data.map(config => {
// tack on default options
let currentConfig = Object.assign({}, defaultOptions, config);
if (!currentConfig.directory) {
switch (currentConfig.family) {
case 'weather': // /weather-icons/svg
currentConfig.directory = path.resolve(__dirname, 'node_modules', 'weather-icons', 'svg');
break;
case 'material': // /mdi-svg/svg
currentConfig.directory = path.resolve(__dirname, 'node_modules', 'mdi-svg', 'svg');
break;
}
}
let iconSet;
if (currentConfig.icons && currentConfig.icons.length === 1 && currentConfig.icons[0] === '*') {
iconSet = fs.readdirSync(currentConfig.directory, {encoding: 'utf8'}, function (err, filenames) {
if (err) {
reject(err);
}
return filenames;
});
iconSet = iconSet.map(icon => {
return icon.replace('.svg', '');
});
currentConfig.icons = iconSet;
}
return currentConfig;
});
resolve(data);
} else {
reject(badDataError)
}
});
}
/**
* Build Icons
* @param data {Array}
* @return {Promise.<*[]>}
*/
function buildIcons(data) {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
rl.write('Building Icon Sets...');
return Promise.all(data.map(config => {
return new Promise((resolve, reject) => {
let iconMap = config.icons.map(icon => {
let file;
let retrieveIconName;
let iconName = icon;
// weather icons have a prepended 'wi-' on the file names
// need to add that to get the right file
if (config.family === 'weather') {
retrieveIconName = `wi-${iconName}`;
} else {
retrieveIconName = iconName;
}
file = fs.readFileSync(path.resolve(config.directory, `${retrieveIconName}.svg`), 'utf8');
// remove common svg nonsense
file = file.replace(/<\?xml(.*?)>|<!DOCTYPE(.*?)>|^ /g, '');
file = file.replace(/<style(.*?)>*<\/style>/g, '');
file = file.replace(/svg/g, 'symbol');
$ = cheerio.load(file, {
normalizeWhitespace: true,
decodeEntities: false
});
// remove all fills / styles
$('[fill]').removeAttr('fill');
$('[style]').removeAttr('style');
let symbol = $('symbol');
// remove all symbol attributes except viewBox
let viewBox = symbol[0].attribs.viewbox;
symbol[0].attribs = {};
if (viewBox) {
symbol[0].attribs.viewbox = viewBox;
}
if (config.prepend) {
iconName = `${config.prepend}-${iconName}`
}
if (config.map) {
outputMap[iconName] = { viewBox };
}
symbol.attr('id', iconName);
return $.html();
});
// wrap symbols in svg
let svg = `<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">${iconMap.join('')}</svg>`;
resolve(htmlClean(svg));
});
}));
}
/**
* Build File
* @param svg {String}
* @return {Promise}
*/
function buildFile(svg) {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
rl.write('Writing New File...');
return new Promise((resolve, reject) => {
// add the svg and iconMap into the template
let template = iconTemplate.replace(/__svgSymbols__/, svg.join(''));
if (Object.keys(outputMap).length > 0 && outputMap.constructor === Object) {
template = template.replace(/__iconMap__/, JSON.stringify(outputMap));
} else {
template = template.replace(/__iconMap__/, '{}');
}
fs.writeFile(`${outputPath}/${outputFileName}`, template, err => {
if (err) {
throw err
} else {
resolve();
}
});
});
}