|
| 1 | +import * as fs from "fs"; |
| 2 | +import * as path from "path"; |
| 3 | +import { fileURLToPath } from "url"; |
| 4 | +import Fonts from "../static/fonts/_list.json" assert { type: "json" }; |
| 5 | +import subsetFont from "subset-font"; |
| 6 | + |
| 7 | +const __filename = fileURLToPath(import.meta.url); |
| 8 | +const __dirname = path.dirname(__filename); |
| 9 | + |
| 10 | +export async function generatePreviewFonts(debug) { |
| 11 | + const srcDir = __dirname + "/../static/webfonts"; |
| 12 | + const targetDir = __dirname + "/../static/webfonts-preview"; |
| 13 | + fs.mkdirSync(targetDir, { recursive: true }); |
| 14 | + |
| 15 | + const srcFiles = fs.readdirSync(srcDir); |
| 16 | + |
| 17 | + for (const font of Fonts) { |
| 18 | + if (font.systemFont) continue; |
| 19 | + |
| 20 | + const display = font.display || font.name; |
| 21 | + |
| 22 | + const fileNames = srcFiles.filter((it) => |
| 23 | + it.startsWith(font.name.replaceAll(" ", "") + "-") |
| 24 | + ); |
| 25 | + |
| 26 | + if (fileNames.length !== 1) |
| 27 | + throw new Error( |
| 28 | + `cannot find font file for ${font.name}. Candidates: ${fileNames}` |
| 29 | + ); |
| 30 | + const fileName = fileNames[0]; |
| 31 | + |
| 32 | + generateSubset( |
| 33 | + srcDir + "/" + fileName, |
| 34 | + targetDir + "/" + fileName, |
| 35 | + display |
| 36 | + ); |
| 37 | + if (debug) { |
| 38 | + console.log( |
| 39 | + `Processing ${font.name} with file ${fileName} to display "${display}".` |
| 40 | + ); |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +async function generateSubset(source, target, name, debug) { |
| 46 | + const font = fs.readFileSync(source); |
| 47 | + const subset = await subsetFont(font, name, { |
| 48 | + targetFormat: "woff2", |
| 49 | + }); |
| 50 | + fs.writeFileSync(target, subset); |
| 51 | +} |
| 52 | +//detect if we run this as a main |
| 53 | +if (import.meta.url.endsWith(process.argv[1])) { |
| 54 | + generatePreviewFonts(true); |
| 55 | +} |
0 commit comments