-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathutils.js
More file actions
94 lines (84 loc) · 2.78 KB
/
utils.js
File metadata and controls
94 lines (84 loc) · 2.78 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
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import svgImageFlatten from 'fontello-batch-cli/svgflatten';
import SVGPath from 'svgpath';
export const FILE_COMPONENTS_REGEX = /^(_)?(.+)[|_](.+)\.svg$/;
const parseSVGIconFileName = (fileName, filePath) => {
if (typeof fileName != 'string' || path.extname(fileName) !== '.svg') {
return null;
}
const fileComponents = fileName.match(FILE_COMPONENTS_REGEX);
if (!fileComponents || !fileComponents.length || fileComponents.length < 3) {
return null;
}
return {
fileName,
enabled: !!fileComponents[1] ? false : true,
name: fileComponents[2],
code: fileComponents[3],
filePath: path.join(filePath, fileName),
};
};
export const getFileData = (filePath = './svgs', parse = parseSVGIconFileName) => {
const files = fs.readdirSync(filePath, 'utf-8');
if (!files) {
throw new Error(`No files found in ${filePath}`);
}
return files
.map((fileName) => {
return parse(fileName, filePath);
})
.filter((file) => !!file);
};
const loadFileContents = (filePath) => fs.readFileSync(filePath, 'utf-8');
const generateUIDFromString = (string) => crypto.createHash('md5').update(string).digest('hex');
const convertHexStringToDec = (string) => parseInt(string, 16);
export const generateGlyphs = (fileData) => {
return fileData.map((file) => {
if (!file) {
return;
}
const data = loadFileContents(file.filePath);
const flattenedData = svgImageFlatten(data);
const path = new SVGPath(flattenedData.d)
.translate(-flattenedData.x, -flattenedData.y)
.scale(1000 / flattenedData.height)
.abs()
.round(1)
.toString();
return {
uid: generateUIDFromString(file.fileName),
css: file.name,
code: convertHexStringToDec(file.code),
src: 'custom_icons',
selected: file.enabled,
svg: {
path,
width: 1000,
},
search: [file.name],
};
});
};
export const writeJSONToDisk = (fileName = 'config.json', fileData = {}) => {
writeToDisk(fileName, JSON.stringify(fileData, null, 4));
};
export const writeToDisk = (fileName, fileData) => {
const fileNameComponents = fileName.split('/');
if (fileNameComponents.length > 2) {
const folderPath = fileNameComponents.slice(0, -1).join('/');
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath);
}
}
try {
fs.unlinkSync(fileName);
} catch (error) {
// ignore
}
fs.writeFileSync(fileName, fileData, {
encoding: 'utf-8',
flag: 'w',
});
};