-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
364 lines (336 loc) · 13.9 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
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
362
363
364
"use strict";
const mkdirp = require("mkdirp");
const fs = require("fs");
const readRecursive = require("fs-readdir-recursive");
const path = require("path");
const getDirName = path.dirname;
const { Collection } = require("@iconify/json-tools");
const { version } = require("./package.json");
async function svelteiconifysvg(inputDirectoryArray, outputFilePath, options) {
//console.log(options); //for testing cli
if (logit("primary", options)) console.log("\r\nsvelteiconifysvg v" + version);
inputDirectoryArray = Array.isArray(inputDirectoryArray) ? inputDirectoryArray : [inputDirectoryArray];
let dirFilesObjArr = getFilesInDirectory(inputDirectoryArray, options);
let text = getContentsOfAllFiles(dirFilesObjArr, outputFilePath, options);
if (options && options.outputSVGfiles) {
let iconsList = getIconNamesFromTextUsingRegexV2(text, options);
await getFilesFromIconList(
iconsList,
async (code, filename) => {
let dash = outputFilePath.endsWith("/") ? "" : "/";
let fullpath = outputFilePath + dash + filename;
if (logit("secondary", options)) console.log("fullpath " + fullpath);
await saveCodeToFile(fullpath, code, iconsList.length, iconsList.length, options);
},
options
);
} else {
let iconsList = getIconNamesFromTextUsingRegex(text);
if ((options && !options.alwaysSave) || !options) {
//alwaysSave = false is default
let iconListHasChanged = await getWhetherIconListHasChanged(iconsList, outputFilePath, options);
if (iconListHasChanged) {
let { code, count } =
options && options.getCodeFromIconList
? await options.getCodeFromIconList(iconsList, options)
: getCodeFromIconList(iconsList, options);
await saveCodeToFile(outputFilePath, code, count, iconsList.length, options);
} else {
if (logit("primary", options))
console.log("- Skipped getting & saving icons - current list is already saved");
}
} else {
let { code, count } =
options && options.getCodeFromIconList
? await options.getCodeFromIconList(iconsList, options)
: getCodeFromIconList(iconsList, options);
await saveCodeToFile(outputFilePath, code, count, iconsList.length, options);
}
}
}
//----------------------------------------------------------------------------
async function getWhetherIconListHasChanged(iconsList, outputFilePath, options) {
// returning true represents needing the iconsList to be resaved
const actualpath = await path.resolve(outputFilePath);
// try to read current icons file
try {
const data = fs.readFileSync(actualpath, "utf8");
} catch (e) {
if (logit("secondary", options)) console.log("- alwaysSave: output path doesn't exist so saving anyway");
return true;
}
// try to get icons list from icons file
let contents = getContentsOfOneFile(actualpath, options);
let savedIconsList = getIconNamesFromTextUsingRegex(contents, { suppress_log: true, duplicates: true });
if (savedIconsList && Array.isArray(savedIconsList)) {
let sameLength = iconsList.length === savedIconsList.length;
let doesNotIncludeAllIcons =
savedIconsList.filter((icon_name) => iconsList.includes(icon_name)).length !== savedIconsList.length;
return !sameLength || doesNotIncludeAllIcons;
} else {
if (logit("secondary", options)) console.log("- alwaysSave: new icons found so saving anyway");
return true;
}
}
function getFilesInDirectory(dirsArr, options) {
let ret = [];
dirsArr.forEach((dir) => {
try {
if (options && options.recursive) {
// recursive = true (make this the default)
ret.push({ dir, files: readRecursive(dir) });
} else {
ret.push({ dir, files: fs.readdirSync(dir, "utf8") });
}
} catch (err) {
if (logit("primary", options)) console.log("- Error getting files in directory");
if (logit("secondary", options)) console.error(err);
}
});
if (logit("secondary", options)) console.log("- Found " + ret.length + " file" + (ret.length > 1 ? "s" : ""));
if (logit("secondary", options)) console.log(ret);
return ret;
}
function getContentsOfAllFiles(dirFilesObjArr, output, options) {
let html = "";
dirFilesObjArr.forEach((dirFilesObj) => {
dirFilesObj.files.map((fileName) => {
if (
(fileName.endsWith(".svelte") || fileName.endsWith(".js")) &&
dirFilesObj.dir + "/" + fileName !== output
) {
html += getContentsOfOneFile(dirFilesObj.dir + "/" + fileName, options);
}
});
});
return html;
}
function getContentsOfOneFile(file, options) {
try {
return fs.readFileSync(file, "utf8");
} catch (err) {
if (logit("secondary", options)) console.log("- Error getting contents of file " + file);
if (logit("secondary", options)) console.log(err);
return "";
}
}
function getIconNamesFromTextUsingRegex(str, options) {
//iconify icon names are in the format of alphanumeric:alphanumeric, where text can also contain dashes e.g.
//fa:random
//si-glyph:pin-location-2
//https://regex101.com
//(?<=") must start with, but don't capture "
//(?!(bind|on|svelte)) must not start with these words, they're not icons but follow the same format!
//[a-zA-Z0-9-]+ any characters for first part of icon name (alphanumeric or a dash)
//: colon between words
//[a-zA-Z0-9-]+ as above
//(?=") must end with, but don't capture "
const regexp = /(?<=("|'))(?!(bind|on|svelte))[a-zA-Z0-9-]+:[a-zA-Z0-9-]+(?=("|'))/g;
let arr = [...str.matchAll(regexp)]; //note requires node 12
let results = [];
arr.forEach((a) => {
if ((options && options.duplicates) || !results.includes(a[0])) results.push(a[0]);
});
if (!(options && options.suppress_log) && logit("secondary", options))
console.log("- Found the following icon references:", results.sort());
return results.sort();
}
function getIconNamesFromTextUsingRegexV2(str, options) {
//iconify icon names are in the format of alphanumeric:alphanumeric, where text can also contain dashes e.g.
//fa:random
//si-glyph:pin-location-2
//https://regex101.com
//(?<=") must start with, but don't capture "
//(?!(bind|on|svelte)) must not start with these words, they're not icons but follow the same format!
//[a-zA-Z0-9-]+ any characters for first part of icon name (alphanumeric or a dash)
//: colon between words
//[a-zA-Z0-9-]+ as above
//(?=") must end with, but don't capture "
const regexp = /(?<=iconify#)[a-zA-Z0-9-]+(?=#iconify)/g;
let arr = [...str.matchAll(regexp)]; //note requires node 12
let results = [];
arr.forEach((a) => {
if (!results.includes(a[0])) results.push(a[0]);
});
if (logit("secondary", options))
console.log("- Found " + results.length + " icon" + (results.length > 1 ? "s" : ""));
if (logit("secondary", options)) console.log(results.sort());
return results.sort();
}
function getFilesFromIconList(icons, callback, options) {
// Sort icons by collections: filtered[prefix][array of icons]
let filtered = {};
icons.forEach((origNameWithFirstDash) => {
let origName = origNameWithFirstDash.replace("-", ":");
if (logit("secondary", options)) console.log("- Generating SVG for: '" + origName + "'");
let icon = origName;
let parts = origName.split(":"),
prefix;
if (parts.length > 1) {
prefix = parts.shift();
icon = parts.join(":");
} else {
parts = icon.split("-");
prefix = parts.shift();
icon = parts.join("-");
}
if (filtered[prefix] === void 0) {
filtered[prefix] = [];
}
if (filtered[prefix].indexOf(icon) === -1) {
filtered[prefix].push({ name: icon, origName });
}
});
// Parse each collection
Object.keys(filtered).forEach((prefix) => {
let collection = new Collection();
if (!collection.loadIconifyCollection(prefix)) {
if (logit("secondary", options)) console.log("- Error loading collection");
if (logit("secondary", options)) console.log(prefix);
return;
}
filtered[prefix].map((iconObj) => {
let data = collection.getIconData(iconObj.name);
let code =
`<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">` +
getSVGHtmlFromData(data, options);
let filename = iconObj.origName.replace(":", "-") + ".svg";
callback(code, filename);
});
});
}
function getCodeFromIconList(icons, options) {
// Sort icons by collections: filtered[prefix][array of icons]
let filtered = {};
let exportText = options && options.commonJs ? "module.exports = " : "export default";
let count = 0;
let errors = "";
let code = `/*
This file was generated directly by 'https://github.com/Swiftaff/svelte-iconify-svg'
or via the rollup plugin 'https://github.com/Swiftaff/rollup-plugin-iconify-svg'.
*/
${exportText} {
`;
icons.forEach((origName) => {
let icon = origName;
let parts = origName.split(":"),
prefix;
if (parts.length > 1) {
prefix = parts.shift();
icon = parts.join(":");
} else {
parts = icon.split("-");
prefix = parts.shift();
icon = parts.join("-");
}
if (filtered[prefix] === void 0) {
filtered[prefix] = [];
}
if (filtered[prefix].indexOf(icon) === -1) {
filtered[prefix].push({ name: icon, origName });
}
});
// Parse each collection
Object.keys(filtered).forEach((prefix) => {
let collection = new Collection();
let loaded = collection.loadIconifyCollection(prefix);
if (!loaded) {
let this_error =
"x ERROR no such icon prefix '" +
prefix +
":' - in these icon names (" +
filtered[prefix].map((f) => "'" + f.origName + "'").join(",") +
")";
errors += this_error + "\r\n";
if (logit("secondary", options)) console.log(this_error);
} else {
filtered[prefix].map((iconObj) => {
let data = collection.getIconData(iconObj.name);
if (data) {
if (logit("secondary", options)) console.log("- Generating SVG for: '" + iconObj.origName + "'");
code +=
'"' +
iconObj.origName +
'": `' +
getSVGHtmlFromData(data, options) +
"`," +
`
`;
count++;
} else {
let this_error = "x ERROR no such icon name '" + iconObj.origName + "'";
errors += this_error + "\r\n";
if (logit("secondary", options)) console.log(this_error);
}
});
}
});
code += `}
`;
code = errors.length ? `/*\r\n${errors}*/\r\n\r\n${code}` : code;
return { code, count };
}
function getSVGHtmlFromData(d, options) {
let body = getBodyAndFlipIfNeeded(d, options);
return `<svg
width="100%"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
aria-hidden="true"
focusable="false"
style="-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg);
transform: rotate(360deg);"
preserveAspectRatio="xMidYMid meet"
viewBox="${d.left} ${d.top} ${d.width} ${d.height}">
${body}
<rect x="${d.left}" y="${d.top}" width="${d.width}" height="${d.height}" fill="rgba(0, 0, 0, 0)" />
</svg>`;
}
function getBodyAndFlipIfNeeded(d, options) {
let body = d.body;
if ((!options || (options && options.transform)) && (d.hFlip || d.vFlip)) {
let tw = d.hFlip ? d.width : 0;
let th = d.vFlip ? d.height : 0;
let sw = d.hFlip ? -1 : 1;
let sh = d.vFlip ? -1 : 1;
body = `<g transform="translate(${tw} ${th}) scale(${sw} ${sh})">${body}</g>`;
}
return body;
}
async function saveCodeToFile(output, code, iconCount, iconTotal, options) {
let dirname = getDirName(output);
const made = mkdirp.sync(dirname);
if (made) {
if (logit("secondary", options)) console.log("- mkdirp had to create some of these directories");
if (logit("secondary", options)) console.log(made);
}
fs.writeFileSync(output, code, "utf8");
if (logit("primary", options))
console.log(
"- Saved " + iconCount + " of " + iconTotal + " icons bundle to",
output,
" (" + code.length + " bytes)"
);
}
function logit(level, options) {
if (level === "primary") {
return (
options &&
(options.logging === "all" ||
options.logging === true ||
options.logging === "true" ||
typeof options.logging === "undefined" ||
options.logging === "some")
);
} else if (level === "secondary") {
return (
options &&
(options.logging === "all" ||
options.logging == true ||
options.logging == "true" ||
typeof options.logging === "undefined")
);
}
}
module.exports = svelteiconifysvg;