/** * Writes starters/blog/src/styles/font-fallbacks.css: one metric-matched fallback face per web * font of the type pairings (RFC-0023 §2). Each is a local system font (Arial, Times New Roman, * Courier New) scaled and given the web font's ascent, descent and line gap, so the text set in * it while the web font loads takes the same room, and `font-display: swap` moves almost nothing * (no layout shift). The technique and the formulas are Next.js's and Fontaine's; the metrics are * read from our own font files with Capsize. * * node scripts/font-fallbacks.ts # rewrite the file * node scripts/font-fallbacks.ts --check # fail if it is stale (CI) */ import { readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { fromBuffer } from "@capsizecss/unpack"; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const STARTER = path.join(ROOT, "starters/blog"); const OUT = path.join(STARTER, "src/styles/font-fallbacks.css"); interface Metrics { ascent: number; descent: number; lineGap: number; unitsPerEm: number; xWidthAvg: number; } /** * The local fonts the fallbacks stand on. Their metrics are constants (read with Capsize from the * macOS copies; Windows ships the same fonts), so this script runs anywhere. */ const SYSTEM = { sans: { local: ["Arial", "ArialMT"], metrics: { ascent: 1854, descent: -434, lineGap: 67, unitsPerEm: 2048, xWidthAvg: 913 }, }, serif: { local: ["Times New Roman", "TimesNewRomanPSMT"], metrics: { ascent: 1825, descent: -443, lineGap: 87, unitsPerEm: 2048, xWidthAvg: 832 }, }, mono: { local: ["Courier New", "CourierNewPSMT"], metrics: { ascent: 1705, descent: -615, lineGap: 0, unitsPerEm: 2048, xWidthAvg: 1229 }, }, } as const satisfies Record; /** * The web fonts of the pairings (fonts.css) and the kind of local font each falls back to. * `widthScale` corrects the average width Capsize reads from a variable font's default instance * when that is not what text is drawn in: Source Sans 3's default is ExtraLight, Fraunces' has * other optical-size and softness settings than body text at 16–18px. Measured in Chrome by * setting a 640px paragraph in the font and in its fallback (line widths within ~1%). */ export const WEB_FONTS: readonly { family: string; file: string; kind: keyof typeof SYSTEM; widthScale?: number; }[] = [ { family: "Fraunces Variable", file: "fraunces-latin-wght-normal.woff2", kind: "serif", widthScale: 0.8945, }, { family: "Inter Variable", file: "inter-latin-wght-normal.woff2", kind: "sans" }, { family: "Space Grotesk Variable", file: "space-grotesk-latin-wght-normal.woff2", kind: "sans" }, { family: "Source Sans 3 Variable", file: "source-sans-3-latin-wght-normal.woff2", kind: "sans", widthScale: 1.0352, }, { family: "Source Serif 4 Variable", file: "source-serif-4-latin-wght-normal.woff2", kind: "serif", }, { family: "JetBrains Mono Variable", file: "jetbrains-mono-latin-wght-normal.woff2", kind: "mono", }, ]; const pct = (n: number) => `${(n * 100).toFixed(2)}%`; /** The @font-face for `family`'s fallback: size-adjust and the three overrides (Fontaine's maths). */ export function fallbackFace( family: string, web: Metrics, opts: { kind: keyof typeof SYSTEM; widthScale?: number }, ): string { const sys = SYSTEM[opts.kind]; const sizeAdjust = ((web.xWidthAvg / web.unitsPerEm) * (opts.widthScale ?? 1)) / (sys.metrics.xWidthAvg / sys.metrics.unitsPerEm); const em = web.unitsPerEm * sizeAdjust; return [ "@font-face {", ` font-family: "${family} Fallback";`, ` src: ${sys.local.map((n) => `local("${n}")`).join(", ")};`, ` size-adjust: ${pct(sizeAdjust)};`, ` ascent-override: ${pct(web.ascent / em)};`, ` descent-override: ${pct(Math.abs(web.descent) / em)};`, ` line-gap-override: ${pct(web.lineGap / em)};`, "}", ].join("\n"); } async function render(): Promise { const faces: string[] = []; for (const font of WEB_FONTS) { const m = await fromBuffer(await readFile(path.join(STARTER, "public/fonts/v1", font.file))); faces.push(fallbackFace(font.family, m, font)); } return [ "/*", " * Generated by scripts/font-fallbacks.ts: do not edit. Metric-matched fallback faces for the", " * pairings' web fonts (tokens.css lists each right after its web font), so the swap to the web", " * font does not move the text.", " */", ...faces, "", ].join("\n"); } if (import.meta.url === `file://${process.argv[1]}`) { const css = await render(); if (process.argv.includes("--check")) { const current = await readFile(OUT, "utf8").catch(() => ""); if (current !== css) { console.error(`${path.relative(ROOT, OUT)} is stale: run node scripts/font-fallbacks.ts`); process.exit(1); } } else { await writeFile(OUT, css); console.log(`wrote ${path.relative(ROOT, OUT)}`); } }