// Builds the church fonts (WEBSITE-1.0-PLAN §3 "Font pairings", contracts FONT_PAIRINGS) into // packages/ui/fonts/: the woff2 files each pairing needs (Latin and Latin Extended only) copied // from the pinned @fontsource-variable packages, and fonts.css with // - an @font-face per file (unicode-range from Fontsource, so a page only downloads what it uses), // - a size-matched fallback face per font (Capsize metrics on Arial or Georgia), so the swap // from the fallback to the font doesn't move the layout, // - [data-cc-fonts=""] → --cc-font-heading / --cc-font-body / --cc-heading-variation (for // Fraunces's soft axis: apply it as font-variation-settings on headings), and // - [data-cc-corners=""] → --cc-radius (and --cc-radius-sm, --cc-radius-button). // // node scripts/fonts.mjs write fonts/ // node scripts/fonts.mjs --check fail if fonts/ is out of date (run by `npm test`) // // The output is committed, so the apps' builds don't depend on this script or Capsize. import fs from "node:fs"; import process from "node:process"; import { Buffer } from "node:buffer"; import console from "node:console"; import path from "node:path"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; import { createFontStack } from "@capsizecss/core"; import { CORNERS, FONT_PAIRINGS } from "@crosscode/contracts"; const require = createRequire(import.meta.url); const here = path.dirname(fileURLToPath(import.meta.url)); const OUT = path.join(here, "..", "fonts"); const SUBSETS = ["latin-ext", "latin"]; // Fontsource's order: the later block wins where ranges overlap. const BUDGET = 160 * 1024; // per pairing, for an English page (Latin): heading + body + body italic. const slug = (family) => family.toLowerCase().replace(/\s+/g, "-"); const camel = (family) => slug(family).replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase()); const cssName = (family) => `CC ${family}`; /** Fonts that use another Fontsource axis file than plain weight, and the setting that turns it on. */ const AXES = { Fraunces: { file: "soft", variation: '"SOFT" 100, "WONK" 0' } }; const metrics = (name) => require(`@capsizecss/metrics/${name}`).default ?? require(`@capsizecss/metrics/${name}`); /** family → { category, styles } from the pairings: body fonts need italic, headings don't. */ function families() { const out = new Map(); for (const p of Object.values(FONT_PAIRINGS)) { for (const [role, face] of [["heading", p.heading], ["body", p.body]]) { const f = out.get(face.family) ?? { category: face.category, styles: new Set(["normal"]) }; if (role === "body") f.styles.add("italic"); out.set(face.family, f); } } return out; } /** The @font-face blocks Fontsource has for a family's style, by subset. */ function fontsourceFaces(family, style) { const pkg = path.dirname(require.resolve(`@fontsource-variable/${slug(family)}/package.json`)); const axis = AXES[family]?.file ?? "wght"; const css = fs.readFileSync(path.join(pkg, style === "italic" ? `${axis}-italic.css` : `${axis}.css`), "utf8"); const faces = {}; for (const m of css.matchAll(/\/\* ([a-z0-9-]+) \*\/\s*@font-face \{([^}]*)\}/g)) { const subset = SUBSETS.find((s) => m[1] === `${slug(family)}-${s}-${axis}-${style}`); if (!subset) continue; const body = m[2]; faces[subset] = { weight: /font-weight:\s*([^;]+);/.exec(body)[1].trim(), range: /unicode-range:\s*([^;]+);/.exec(body)[1].trim(), file: path.join(pkg, "files", `${m[1]}.woff2`), }; } for (const s of SUBSETS) if (!faces[s]) throw new Error(`${family} ${style}: no ${s} face in Fontsource`); return faces; } const fallbackFor = (category) => (category === "serif" ? { name: "Georgia", metrics: metrics("georgia"), generic: "serif" } : { name: "Arial", metrics: metrics("arial"), generic: "sans-serif" }); export function build() { const files = new Map(); // name in fonts/files → source path const css = [ "/* Generated by packages/ui/scripts/fonts.mjs from @fontsource-variable (SIL Open Font License 1.1,", " see fonts/LICENSES.md) and Capsize metrics. Don't edit: run `npm run fonts -w packages/ui`. */", "", ]; const stacks = {}; const sizes = {}; for (const [family, f] of families()) { for (const style of f.styles) { for (const [subset, face] of Object.entries(fontsourceFaces(family, style))) { const name = path.basename(face.file); files.set(name, face.file); if (subset === "latin") sizes[`${family}/${style}`] = fs.statSync(face.file).size; css.push(`@font-face { font-family: '${cssName(family)}'; font-style: ${style}; font-display: swap; font-weight: ${face.weight}; src: url(./files/${name}) format('woff2-variations'), url(./files/${name}) format('woff2'); unicode-range: ${face.range}; }`); } } const fb = fallbackFor(f.category); const own = { ...metrics(camel(family)), familyName: cssName(family) }; const { fontFamily, fontFaces } = createFontStack([own, fb.metrics], { fontFaceFormat: "styleString" }); css.push(fontFaces.replace(/\s+/g, " ").replace(/\} ?@/g, "}\n@").trim()); stacks[family] = `${fontFamily}, ${fb.generic}`; } css.push(""); for (const [id, p] of Object.entries(FONT_PAIRINGS)) { css.push(`[data-cc-fonts="${id}"] { --cc-font-heading: ${stacks[p.heading.family]}; --cc-font-body: ${stacks[p.body.family]}; --cc-heading-variation: ${AXES[p.heading.family]?.variation ?? "normal"}; }`); const used = new Set([`${p.heading.family}/normal`, `${p.body.family}/normal`, `${p.body.family}/italic`]); const total = [...used].reduce((n, k) => n + sizes[k], 0); if (total > BUDGET) throw new Error(`${id} needs ${Math.round(total / 1024)} KB of fonts for an English page; the budget is ${BUDGET / 1024} KB`); } const RADII = { sharp: ["0", "0", "0"], soft: ["1rem", "0.5rem", "0.5rem"], round: ["1.25rem", "0.75rem", "9999px"] }; if (Object.keys(RADII).join() !== CORNERS.join()) throw new Error("A corner style without a radius"); for (const [id, [r, sm, button]] of Object.entries(RADII)) css.push(`[data-cc-corners="${id}"] { --cc-radius: ${r}; --cc-radius-sm: ${sm}; --cc-radius-button: ${button}; }`); return { css: css.join("\n") + "\n", files }; } const LICENCES = (families) => `# Font licences Every font in \`files/\` is from the [Fontsource](https://fontsource.org) packages pinned in \`packages/ui/package.json\` and is licensed under the **SIL Open Font License 1.1**: free to use, bundle and self-host, not to be sold on its own. Each package's \`LICENSE\` has the full text and the copyright holders. ${[...families].map((f) => `- ${f}: \`@fontsource-variable/${slug(f)}\``).join("\n")} `; const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); if (isMain) { const check = process.argv.includes("--check"); const { css, files } = build(); const want = new Map([["fonts.css", Buffer.from(css)], ["LICENSES.md", Buffer.from(LICENCES(families().keys()))]]); for (const [name, src] of files) want.set(`files/${name}`, fs.readFileSync(src)); const have = fs.existsSync(OUT) ? fs.readdirSync(OUT, { recursive: true }).map(String).map((p) => p.replace(/\\/g, "/")).filter((p) => fs.statSync(path.join(OUT, p)).isFile()) : []; const stale = [...want].filter(([p, buf]) => !fs.existsSync(path.join(OUT, p)) || !fs.readFileSync(path.join(OUT, p)).equals(buf)).map(([p]) => p); const extra = have.filter((p) => !want.has(p)); if (check) { if (stale.length || extra.length) { console.error(`fonts/ is out of date (${[...stale, ...extra].slice(0, 5).join(", ")}): run \`npm run fonts -w packages/ui\``); process.exit(1); } console.log(`fonts/ is up to date (${files.size} font files)`); } else { fs.mkdirSync(path.join(OUT, "files"), { recursive: true }); for (const p of extra) fs.rmSync(path.join(OUT, p)); for (const [p, buf] of want) fs.writeFileSync(path.join(OUT, p), buf); console.log(`Wrote fonts/ (${files.size} font files)`); } }