2024-07-10 03:23:28 +08:00
|
|
|
import * as fs from "fs";
|
|
|
|
import * as path from "path";
|
|
|
|
import { fileURLToPath } from "url";
|
2024-07-15 18:17:31 +08:00
|
|
|
import Fonts from "../static/fonts/_list.json";
|
2024-07-10 03:23:28 +08:00
|
|
|
import subsetFont from "subset-font";
|
|
|
|
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
|
2024-07-15 18:17:31 +08:00
|
|
|
export async function generatePreviewFonts(
|
|
|
|
debug: boolean = false
|
|
|
|
): Promise<void> {
|
2024-07-10 03:23:28 +08:00
|
|
|
const srcDir = __dirname + "/../static/webfonts";
|
|
|
|
const targetDir = __dirname + "/../static/webfonts-preview";
|
|
|
|
fs.mkdirSync(targetDir, { recursive: true });
|
|
|
|
|
|
|
|
const srcFiles = fs.readdirSync(srcDir);
|
|
|
|
|
|
|
|
for (const font of Fonts) {
|
|
|
|
if (font.systemFont) continue;
|
|
|
|
|
2024-07-15 18:17:31 +08:00
|
|
|
const display = (font.display ?? font.name) + "Fontfamily";
|
2024-07-10 03:23:28 +08:00
|
|
|
|
|
|
|
const fileNames = srcFiles.filter((it) =>
|
|
|
|
it.startsWith(font.name.replaceAll(" ", "") + "-")
|
|
|
|
);
|
|
|
|
|
|
|
|
if (fileNames.length !== 1)
|
|
|
|
throw new Error(
|
|
|
|
`cannot find font file for ${font.name}. Candidates: ${fileNames}`
|
|
|
|
);
|
|
|
|
const fileName = fileNames[0];
|
|
|
|
|
2024-07-15 18:17:31 +08:00
|
|
|
await generateSubset(
|
2024-07-10 03:23:28 +08:00
|
|
|
srcDir + "/" + fileName,
|
|
|
|
targetDir + "/" + fileName,
|
|
|
|
display
|
|
|
|
);
|
|
|
|
if (debug) {
|
|
|
|
console.log(
|
|
|
|
`Processing ${font.name} with file ${fileName} to display "${display}".`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-22 21:08:11 +08:00
|
|
|
async function generateSubset(
|
|
|
|
source: string,
|
|
|
|
target: string,
|
|
|
|
name: string
|
|
|
|
): Promise<void> {
|
2024-07-10 03:23:28 +08:00
|
|
|
const font = fs.readFileSync(source);
|
|
|
|
const subset = await subsetFont(font, name, {
|
|
|
|
targetFormat: "woff2",
|
|
|
|
});
|
|
|
|
fs.writeFileSync(target, subset);
|
|
|
|
}
|
|
|
|
//detect if we run this as a main
|
2024-07-22 21:08:11 +08:00
|
|
|
if (import.meta.url.endsWith(process.argv[1] as string)) {
|
|
|
|
void generatePreviewFonts(true);
|
2024-07-10 03:23:28 +08:00
|
|
|
}
|