{{ message }}
Repository navigation
Expand file tree
/
Copy pathbuild.ts
More file actions
591 lines (497 loc) · 15.2 KB
/
Copy pathbuild.ts
File metadata and controls
591 lines (497 loc) · 15.2 KB
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
import fs from 'fs-extra';
import { join } from 'path';
import Svgo from 'svgo';
async function build(rootDir: string) {
try {
const pkgJsonPath = join(rootDir, 'package.json');
const srcDir = join(rootDir, 'src');
const srcSvgDir = join(srcDir, 'svg');
const iconDir = join(rootDir, 'icons');
const distDir = join(rootDir, 'dist');
const distIoniconsDir = join(distDir, 'ionicons');
const distSvgDir = join(distDir, 'svg');
await Promise.all([fs.emptyDir(iconDir), fs.emptyDir(distDir)]);
await fs.emptyDir(distSvgDir), await fs.emptyDir(distIoniconsDir);
const pkgData = await fs.readJson(pkgJsonPath);
const version = pkgData.version as string;
const srcSvgData = await getSvgs(srcSvgDir, distSvgDir, distIoniconsDir);
await optimizeSvgs(srcSvgData);
await Promise.all([
createDataJson(version, srcDir, distDir, srcSvgData),
createIconPackage(version, iconDir, srcSvgData),
]);
const svgSymbolsContent = await createSvgSymbols(version, distDir, srcSvgData);
await createCheatsheet(version, rootDir, distDir, svgSymbolsContent, srcSvgData);
await copyToTesting(rootDir, distDir, srcSvgData);
} catch (e) {
console.error(e);
process.exit(1);
}
}
async function optimizeSvgs(srcSvgData: SvgData[]) {
// https://github.com/svg/svgo
const optimizePass = new Svgo({});
const webComponentPass = new Svgo({
full: true,
plugins: [
{
addFillNoneCss: {
type: 'perItem',
fn: (item, params) => {
if (!Array.isArray(params.attrs)) {
params.attrs = [params.attrs];
}
if (item.isElem()) {
item.eachAttr((attr) => {
if (attr.name === 'fill') {
if (attr.value === 'none') {
item.class.add('ionicon-fill-none');
}
item.removeAttr('fill');
} else if (attr.name === 'stroke') {
item.removeAttr('stroke');
} else if (attr.name === 'stroke-width' && attr.value === '32') {
item.removeAttr('stroke-width');
item.class.add('ionicon-stroke-width');
}
});
}
},
},
} as any,
{
removeStyleElement: true,
},
{
removeScriptElement: true,
},
{
removeDimensions: true,
},
],
});
const sourcePass = new Svgo({
full: true,
plugins: [
{
addFillNoneCss: {
type: 'perItem',
fn: (item, params) => {
if (!Array.isArray(params.attrs)) {
params.attrs = [params.attrs];
}
if (item.isElem()) {
item.eachAttr((attr) => {
if (attr.name === 'stroke' || attr.name === 'fill') {
if (attr.value === '#000') {
item.addAttr({
name: attr.name,
value: 'currentColor',
prefix: '',
local: attr.name,
});
} else if (attr.value !== 'none') {
throw new Error(`invalid "${attr.name}" value: ${attr.value}`);
}
}
});
}
},
},
} as any,
{
removeStyleElement: true,
},
{
removeScriptElement: true,
},
{
removeDimensions: true,
},
],
});
const validatePass = new Svgo({
full: true,
plugins: [
{
addFillNoneCss: {
type: 'perItem',
fn: (item, params) => {
if (!Array.isArray(params.attrs)) {
params.attrs = [params.attrs];
}
if (item.isElem()) {
item.eachAttr((attr) => {
if (attr.name === 'style') {
throw new Error('Inline style attributed detected');
}
});
}
if (item.isElem('style')) {
throw new Error('Inline style element detected');
}
},
},
} as any,
],
});
await Promise.all(
srcSvgData.map(async (svgData) => {
return optimizeSvg(optimizePass, webComponentPass, sourcePass, validatePass, svgData);
}),
);
}
async function optimizeSvg(
optimizePass: Svgo,
webComponentPass: Svgo,
sourcePass: Svgo,
validatePass: Svgo,
svgData: SvgData,
) {
const srcSvgContent = await fs.readFile(svgData.srcFilePath, 'utf8');
const optimizedSvg = await optimizePass.optimize(srcSvgContent, { path: svgData.srcFilePath });
const optimizedCode = optimizedSvg.data.replace(
/<svg (.*?)>/,
`<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512"><title>${svgData.title}</title>`,
);
const webComponentSvg = await webComponentPass.optimize(optimizedCode, { path: svgData.srcFilePath });
const sourceSvg = await sourcePass.optimize(optimizedCode, { path: svgData.srcFilePath });
svgData.optimizedSvgContent = webComponentSvg.data;
try {
await validatePass.optimize(svgData.optimizedSvgContent, { path: svgData.srcFilePath });
} catch (e) {
console.error(`${e.message}: ${svgData.srcFilePath}`);
}
await fs.writeFile(svgData.optimizedFilePath, svgData.optimizedSvgContent);
await fs.writeFile(svgData.distSvgFilePath, sourceSvg.data);
}
async function copyToTesting(rootDir: string, distDir: string, srcSvgData: SvgData[]) {
const testDir = join(rootDir, 'www');
const testBuildDir = join(testDir, 'build');
const testSvgDir = join(testBuildDir, 'svg');
await fs.ensureDir(testSvgDir);
await Promise.all(
srcSvgData.map(async (svgData) => {
const testSvgFilePath = join(testSvgDir, svgData.fileName);
await fs.writeFile(testSvgFilePath, svgData.optimizedSvgContent);
}),
);
const distCheatsheetFilePath = join(distDir, 'cheatsheet.html');
const testCheatsheetFilePath = join(testDir, 'cheatsheet.html');
await fs.copyFile(distCheatsheetFilePath, testCheatsheetFilePath);
}
async function createSvgSymbols(version: string, distDir: string, srcSvgData: SvgData[]) {
srcSvgData = srcSvgData.sort((a, b) => {
if (a.iconName < b.iconName) return -1;
if (a.iconName > b.iconName) return 1;
return 0;
});
const symbolsSvgFilePath = join(distDir, 'ionicons.symbols.svg');
const lines = [
`<svg data-ionicons="${version}" style="display:none">`,
`<style>`,
`.ionicon {`,
` fill: currentColor;`,
` stroke: currentColor;`,
`}`,
`.ionicon-fill-none {`,
` fill: none;`,
`}`,
`.ionicon-stroke-width {`,
` stroke-width: 32px;`,
`}`,
`</style>`,
];
srcSvgData.forEach((svgData) => {
const svg = svgData.optimizedSvgContent
.replace(`<svg xmlns="http://www.w3.org/2000/svg"`, `<symbol id="${svgData.iconName}"`)
.replace(`</svg>`, `</symbol>`);
lines.push(svg);
});
lines.push(`</svg>`, ``);
const content = lines.join('\n');
await fs.writeFile(symbolsSvgFilePath, content);
return content;
}
async function createCheatsheet(
version: string,
rootDir: string,
distDir: string,
svgSymbolsContent: string,
srcSvgData: SvgData[],
) {
const CheatsheetTmpFilePath = join(rootDir, 'scripts', 'cheatsheet-template.html');
const distCheatsheetFilePath = join(distDir, 'cheatsheet.html');
const c = srcSvgData.map(
(svgData) => `<a href="./svg/${svgData.fileName}"><svg><use href="#${svgData.iconName}" xlink:href="#${svgData.iconName}"/></svg></a>`,
);
c.push(svgSymbolsContent);
const html = (await fs.readFile(CheatsheetTmpFilePath, 'utf8'))
.replace(/{{version}}/g, version)
.replace(/{{count}}/g, srcSvgData.length.toString())
.replace(/{{content}}/g, c.join('\n'));
await fs.writeFile(distCheatsheetFilePath, html);
}
async function getSvgs(srcSvgDir: string, distSvgDir: string, distIoniconsDir: string): Promise<SvgData[]> {
const optimizedSvgDir = join(distIoniconsDir, 'svg');
await fs.emptyDir(optimizedSvgDir);
const svgFiles = (await fs.readdir(srcSvgDir)).filter((fileName) => {
return !fileName.startsWith('.') && fileName.endsWith('.svg');
});
const svgData = await Promise.all(
svgFiles.map(async (fileName) => {
// fileName: airplane-outline.svg
if (fileName.toLowerCase() !== fileName) {
throw new Error(`svg filename "${fileName}" must be all lowercase`);
}
// srcFilePath: /src/svg/airplane-outline.svg
const srcFilePath = join(srcSvgDir, fileName);
// srcFilePath: /src/svg/airplane-outline.svg
const distSvgFilePath = join(distSvgDir, fileName);
// optimizedFilePath: /dist/ionicons/svg/airplane-outline.svg
const optimizedFilePath = join(optimizedSvgDir, fileName);
const dotSplit = fileName.split('.');
if (dotSplit.length > 2) {
throw new Error(`svg filename "${fileName}" cannot contain more than one period`);
}
// iconName: airplane-outline
const iconName = dotSplit[0];
if (reservedKeywords.has(iconName)) {
throw new Error(`svg icon name "${iconName}" is a reserved JavaScript keyword`);
}
// fileNameMjs: airplane-outline.mjs
const fileNameMjs = iconName + '.mjs';
// fileNameCjs: airplane-outline.mjs
const fileNameCjs = iconName + '.js';
// exportName: airplaneOutline
const exportName = camelize(iconName);
const title = toTitleCase(
fileName.replace('.svg', '').replace('-outline', '').replace('-sharp', '').replace(/-/g, ' '),
);
return {
fileName,
title,
srcFilePath,
distSvgFilePath,
srcSvgContent: await fs.readFile(srcFilePath, 'utf8'),
optimizedFilePath,
optimizedSvgContent: null,
iconName,
fileNameMjs,
fileNameCjs,
exportName,
};
}),
);
return svgData.sort((a, b) => {
if (a.exportName < b.exportName) return -1;
if (a.exportName > b.exportName) return 1;
return 0;
});
}
async function createIconPackage(version: string, iconDir: string, srcSvgData: SvgData[]) {
const iconPkgJsonFilePath = join(iconDir, 'package.json');
await Promise.all([
createEsmIcons(version, iconDir, srcSvgData),
createCjsIcons(version, iconDir, srcSvgData),
createDtsIcons(version, iconDir, srcSvgData),
]);
const iconPkgJson = {
name: 'ionicons/icons',
version,
module: 'index.mjs',
main: 'index.js',
typings: 'index.d.ts',
private: true,
};
const jsonStr = JSON.stringify(iconPkgJson, null, 2) + '\n';
await fs.writeFile(iconPkgJsonFilePath, jsonStr);
}
async function createEsmIcons(version: string, iconDir: string, srcSvgData: SvgData[]) {
const iconEsmFilePath = join(iconDir, 'index.mjs');
const o = [`/* Ionicons v${version}, ES Modules */`, ``];
srcSvgData.forEach((svgData) => {
o.push(`export const ${svgData.exportName} = ${getDataUrl(svgData)}`);
});
await fs.writeFile(iconEsmFilePath, o.join('\n') + '\n');
}
async function createCjsIcons(version: string, iconDir: string, srcSvgData: SvgData[]) {
const iconCjsFilePath = join(iconDir, 'index.js');
const o = [`/* Ionicons v${version}, CommonJS */`, ``];
srcSvgData.forEach((svgData) => {
o.push(`exports.${svgData.exportName} = ${getDataUrl(svgData)}`);
});
await fs.writeFile(iconCjsFilePath, o.join('\n') + '\n');
}
async function createDtsIcons(version: string, iconDir: string, srcSvgData: SvgData[]) {
const iconDtsFilePath = join(iconDir, 'index.d.ts');
const o = [`/* Ionicons v${version}, Types */`, ``];
srcSvgData.forEach((svgData) => {
o.push(`export declare var ${svgData.exportName}: string;`);
});
await fs.writeFile(iconDtsFilePath, o.join('\n') + '\n');
}
function getDataUrl(svgData: SvgData) {
let svg = svgData.optimizedSvgContent;
if (svg.includes(`'`)) {
throw new Error(`oh no! no single quotes allowed! ${svgData.fileName}`);
}
if (svg.includes(`\n`) || svg.includes(`\r`)) {
throw new Error(`oh no! no new lines allowed! ${svgData.fileName}`);
}
svg = svg.replace(/"/g, "'");
return `"data:image/svg+xml;utf8,${svg}"`;
}
async function createDataJson(version: string, srcDir: string, distDir: string, srcSvgData: SvgData[]) {
const srcDataJsonPath = join(srcDir, 'data.json');
const distDataJsonPath = join(distDir, 'ionicons.json');
let data: JsonData;
try {
data = await fs.readJson(srcDataJsonPath);
} catch (e) {
data = {} as any;
}
data.icons = data.icons || [];
// add new icons
srcSvgData.forEach((svgData) => {
if (!data.icons.some((i) => i.name === svgData.iconName)) {
data.icons.push({
name: svgData.iconName,
});
}
});
// remove dead icons
data.icons = data.icons.filter((dataIcon) => {
return srcSvgData.some((svgData) => dataIcon.name === svgData.iconName);
});
// sort
data.icons = data.icons.sort((a, b) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
data.icons.forEach((icon) => {
icon.tags = icon.tags || icon.name.split('-');
icon.tags = icon.tags.sort();
});
const srcJsonStr = JSON.stringify(data, null, 2) + '\n';
await fs.writeFile(srcDataJsonPath, srcJsonStr);
const distJsonData = {
name: 'ionicons',
version,
icons: data.icons,
};
const distJsonStr = JSON.stringify(distJsonData, null, 2) + '\n';
await fs.writeFile(distDataJsonPath, distJsonStr);
}
function camelize(text: string) {
let words = text.split(/[-_]/g); // ok one simple regexp.
return words[0].toLowerCase() + words.slice(1).map(upFirst).join('');
}
function upFirst(word: string) {
return word[0].toUpperCase() + word.toLowerCase().slice(1);
}
interface SvgData {
/**
* airplane-outline.svg
*/
fileName: string;
/**
* airplane
*/
title: string;
/**
* /src/svg/airplane-outline.svg
*/
srcFilePath: string;
/**
* /dist/ionicons/svg/airplane-outline.svg
*/
optimizedFilePath: string;
/**
* /dist/svg/airplane-outline.svg
*/
distSvgFilePath: string;
optimizedSvgContent: string;
/**
* airplane-outline
*/
iconName: string;
/**
* airplane-outline.mjs
*/
fileNameMjs: string;
/**
* airplane-outline.js
*/
fileNameCjs: string;
/**
* airplaneOutline
*/
exportName: string;
}
interface JsonData {
icons: { name: string; tags?: string[] }[];
version?: string;
}
function toTitleCase(str: string) {
const s = str.trim().toLowerCase().split(' ');
for (var i = 0; i < s.length; i++) {
s[i] = s[i].charAt(0).toUpperCase() + s[i].slice(1);
}
return s.join(' ');
}
// https://mathiasbynens.be/notes/reserved-keywords
const reservedKeywords = new Set([
'do',
'if',
'in',
'for',
'let',
'new',
'try',
'var',
'case',
'else',
'enum',
'eval',
'null',
'this',
'true',
'void',
'with',
'await',
'break',
'catch',
'class',
'const',
'false',
'super',
'throw',
'while',
'yield',
'delete',
'export',
'import',
'public',
'return',
'static',
'switch',
'typeof',
'default',
'extends',
'finally',
'package',
'private',
'continue',
'debugger',
'function',
'arguments',
'interface',
'protected',
'implements',
'instanceof',
'constructor',
]);
// let's do this
build(join(__dirname, '..'));
You can’t perform that action at this time.
