-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgftocss.js
77 lines (64 loc) · 1.89 KB
/
gftocss.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
/*
Download all font files and put them under ./fonts/[Font Name]
then execute node gftocss.js [Font Name]
*/
const fs = require('fs');
if (process.argv.length === 2) {
console.error(`Font foldernames not specified`);
process.exit(1);
}
const fontFolder = `fonts/${process.argv[2]}`;
if (!fs.existsSync(fontFolder)) {
console.error(
`${fontFolder}\nFolder with name ${process.argv[2]} does not exists\n`
);
process.exit(1);
}
const fontName = process.argv[2].replace(/_/g, ' ');
const fontFiles = fs
.readdirSync(fontFolder)
.filter((file) => /.*\.(woff|ttf)/.test(file));
let fonts = {};
fontFiles.forEach((fontFile) => {
const [fontType, extName] = fontFile.match(/(.*)\.(.*)/).slice(1);
if (fonts[fontType]) fonts[fontType] = fonts[fontType].concat(extName);
else fonts[fontType] = [].concat(extName);
});
const fontFaceTemplate = (fontName, font, weight, style, format) => {
return `@font-face{
font-family: '${fontName}';
font-weight: ${weight};
font-style: ${style};
src: ${format
.map((f, i) => {
return `url('./${font}.${f}') format('${f === 'ttf' ? 'truetype' : f}')${
i === format.length - 1 ? ';' : ','
}`;
})
.join('\n ')}
font-display: swap;
}\n\n`;
};
let constructedCSS = '';
Object.keys(fonts).forEach((font, i) => {
const [fontWeight, fontStyle] = (() => {
let match = font.match(/latin-(\d*)(\w*)/).slice(1);
return [
match[0] ? match[0] : '400',
match[1] === 'italic' ? match[1] : 'normal',
];
})();
const fontFormats = fonts[font].sort((a, b) => b.localeCompare(a));
console.log(
fontFaceTemplate(fontName, font, fontWeight, fontStyle, fontFormats)
);
constructedCSS += fontFaceTemplate(
fontName,
font,
fontWeight,
fontStyle,
fontFormats
);
});
const cssFileName = `${fontFolder}/${fontName.replace(/\ /g, '_')}.css`;
fs.writeFileSync(cssFileName, constructedCSS);