Open source CapCut alternative.
TypeScript
feat(site): load Cut fonts on demand [rebuild]
David Le55fb2ef58943
diff --git a/docs/guides/performance.md b/docs/guides/performance.mdindex 048b3cdd..7b6ba864 100644--- a/docs/guides/performance.md+++ b/docs/guides/performance.md@@ -27,7 +27,7 @@ The code that stalls is rarely slow on its own. It is whatever happens to be holthread when a frame was due. So the questions to ask of any change are the same two: howlong does this hold the thread at once, and how often.-The model for this section, and for the split, batch, defer and move techniques below, is+The model for this section and the techniques below is[The Expensive Main Thread](https://kciter.so/posts/the-expensive-main-thread/en/).## Techniques@@ -86,6 +86,9 @@ the box—the preview stays in sync with the source.reader cache. Sound, filmstrip and preview all join that same open file.7. **Measure before you ship.** A change to the preview, the timeline, or the frame loopruns the perf evals, and the summary says what moved.+8. **Load weight on demand.** A new font is one entry in `site/src/cut/lib/fonts.json`+ plus its @fontsource package; its CSS is never imported. Heavy effect code loads by+ `import()` behind an awaited prepare step, as `packages/effects-kit/src/lottie.ts` does.## Memory@@ -132,11 +135,4 @@ A nightly run gates the scrub cases on a CI machine profile.Every editor session also meters its own main thread. A frame over a second, or a halfminute mostly blocked, marks the session as trouble and the frames leading up to it aresent to analytics with the script that held the thread and the control that was pressed.-A small random share of sessions send regardless, as the baseline trouble is measured-against.--## Where it lives--The frame loop and decoders live in the preview's frame source and playback hook, the-memory budget in its own module beside them, the trace and meter in the perf trace and-perf log modules, and the evals in the site's scripts folder.+A small random share of sessions send regardless, as a baseline.diff --git a/site/next.config.ts b/site/next.config.tsindex 19f9a21c..3ddedf3e 100644--- a/site/next.config.ts+++ b/site/next.config.ts@@ -74,6 +74,15 @@ const nextConfig: NextConfig = {source: "/_next/static/:path*",headers: [{ key: "X-Robots-Tag", value: "noindex" }],},+ {+ // The editor's font faces (scripts/stage-cut-fonts.mjs). Their names+ // carry no hash, so they cache for a day.+ source: "/cut-fonts/:path*",+ headers: [+ { key: "Cache-Control", value: "public, max-age=86400" },+ { key: "X-Robots-Tag", value: "noindex" },+ ],+ },],// Cut is local-only: /api/cut/* 404s on a hosted deploy and never runs the// engine. But Turbopack's file tracer still follows the route's import of thediff --git a/site/scripts/stage-cut-fonts.mjs b/site/scripts/stage-cut-fonts.mjsindex 4449a93f..621148ce 100644--- a/site/scripts/stage-cut-fonts.mjs+++ b/site/scripts/stage-cut-fonts.mjs@@ -1,17 +1,18 @@-// Stage the Cut font files into public/ so a headless render draws text with-// the same faces the editor shows. The page declares these families from the-// @fontsource stylesheets (googleFonts.ts); a render worker hands skia a file-// path instead, so the latin face of each weight is copied here from the same-// packages under stable names, with a manifest the headless bootstrap reads.+// Stage the Cut font files into public/ for the page and a headless render.+// The families are listed once, in src/cut/lib/fonts.json. Every subset of+// each weight is copied here from its @fontsource package, and the manifest+// records each face's subset and unicode-range: the page adds one lazy+// FontFace per face (googleFonts.ts), and a render worker hands skia the latin+// files (lib/headless/nodeFonts.ts).//-// The alias-only families at the bottom cover the base system set (SF Pro,-// New York, Impact…). Those live on a Mac and nowhere else, so a Linux-// container would draw tofu for the default font; the aliases register a-// close stand-in under each name the CSS stacks ask for.+// The alias-only families cover the base system set (SF Pro, New York,+// Impact…). Those live on a Mac and nowhere else, so a Linux container would+// draw tofu for the default font; the aliases register a close stand-in under+// each name the CSS stacks ask for.//// Runs from postinstall and reads only node_modules, so it needs no network.// A missing face fails the install: the package versions pin the files.-import { copyFileSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import { copyFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { createRequire } from "node:module";import path from "node:path";import { fileURLToPath } from "node:url";@@ -19,116 +20,67 @@ import { fileURLToPath } from "node:url";const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));const dest = path.join(root, "public", "cut-fonts");const require = createRequire(import.meta.url);+const FAMILIES = JSON.parse(readFileSync(path.join(root, "src", "cut", "lib", "fonts.json"), "utf8"));-/** Keep in step with googleFonts.ts, which declares the same families for- * the page. An id here is a Cut font id; a family with no id is a stand-in. */-const FAMILIES = [- { id: "inter", label: "Inter", family: "Inter", weights: [400, 500, 600, 700] },- { id: "montserrat", label: "Montserrat", family: "Montserrat", weights: [400, 500, 600, 700, 800, 900] },- { id: "poppins", label: "Poppins", family: "Poppins", weights: [400, 500, 600, 700, 800, 900] },- { id: "oswald", label: "Oswald", family: "Oswald", weights: [400, 500, 600, 700] },- { id: "space-grotesk", label: "Space Grotesk", family: "Space Grotesk", weights: [400, 500, 600, 700] },- {- id: "playfair",- label: "Playfair Display",- family: "Playfair Display",- weights: [400, 500, 600, 700, 900],- italics: [400, 700, 900],- },- { id: "caveat", label: "Caveat", family: "Caveat", weights: [400, 500, 600, 700] },- { id: "bebas", label: "Bebas Neue", family: "Bebas Neue", weights: [400] },- {- id: "anton",- label: "Anton",- family: "Anton",- weights: [400],- aliases: ["Impact", "Arial Black"],- },- { id: "archivo-black", label: "Archivo Black", family: "Archivo Black", weights: [400] },- { id: "bangers", label: "Bangers", family: "Bangers", weights: [400] },- { id: "lobster", label: "Lobster", family: "Lobster", weights: [400] },- { id: "pacifico", label: "Pacifico", family: "Pacifico", weights: [400] },- { id: "permanent-marker", label: "Permanent Marker", family: "Permanent Marker", weights: [400] },- { id: "dm-serif", label: "DM Serif Display", family: "DM Serif Display", weights: [400] },- { id: "amatic", label: "Amatic SC", family: "Amatic SC", weights: [400, 700] },- // Light and Bold only: font matching draws a 400 title in the Light face,- // the thin LCD look, and 700–900 in Bold.- {- id: "dseg14",- label: "DSEG14 Classic",- family: "DSEG14 Classic",- weights: [300, 700],- italics: [300, 700],- },- { id: "outfit", label: "Outfit", family: "Outfit", weights: [400, 500, 600, 700] },- { id: "cinzel", label: "Cinzel", family: "Cinzel", weights: [400, 700] },- { id: "freckle-face", label: "Freckle Face", family: "Freckle Face", weights: [400] },- { id: "orbitron", label: "Orbitron", family: "Orbitron", weights: [400, 900] },- { id: "chewy", label: "Chewy", family: "Chewy", weights: [400] },- { id: "great-vibes", label: "Great Vibes", family: "Great Vibes", weights: [400] },- { id: "rubik-dirt", label: "Rubik Dirt", family: "Rubik Dirt", weights: [400] },- { id: "fredoka", label: "Fredoka", family: "Fredoka", weights: [500, 600, 700] },- { id: "oranienbaum", label: "Oranienbaum", family: "Oranienbaum", weights: [400] },- { id: "kaushan", label: "Kaushan Script", family: "Kaushan Script", weights: [400] },- { id: "rubik", label: "Rubik", family: "Rubik", weights: [400, 500, 700, 900] },- { id: "jost", label: "Jost", family: "Jost", weights: [400, 500, 600, 700] },- { id: "gloria-hallelujah", label: "Gloria Hallelujah", family: "Gloria Hallelujah", weights: [400] },- { id: "prompt", label: "Prompt", family: "Prompt", weights: [900] },- {- family: "Roboto",- weights: [400, 500, 600, 700],- aliases: [- "-apple-system",- "system-ui",- "SF Pro Display",- "SF Pro Text",- "Helvetica Neue",- "Helvetica",- "Arial",- "sans-serif",- ],- },- {- family: "Noto Serif",- weights: [400, 500, 600, 700],- aliases: ["New York", "ui-serif", "Georgia", "Times New Roman", "serif"],- },- {- family: "Nunito",- weights: [400, 500, 600, 700],- aliases: ["ui-rounded", "SF Pro Rounded", "Arial Rounded MT Bold"],- },- {- family: "Roboto Mono",- weights: [400, 500, 600, 700],- aliases: ["ui-monospace", "SF Mono", "Menlo", "Courier New", "monospace"],- },-];+/** The subset skia draws from; the others only serve the page. */+const SKIA_SUBSET = "latin";const slug = (family) => family.toLowerCase().replace(/[^a-z0-9]+/g, "-");+/** The faces one @fontsource stylesheet declares, one per subset:+ * "inter-cyrillic-400-normal" → { file, subset: "cyrillic", range }. A+ * single-subset family declares no unicode-range, so its face covers all. */+function readFaces(pkgDir, pkg, weight, style) {+ const css = readFileSync(path.join(pkgDir, `${weight}${style === "italic" ? "-italic" : ""}.css`), "utf8");+ const faces = [];+ for (const [, body] of css.matchAll(/@font-face\s*{([^}]*)}/g)) {+ const file = body.match(/url\(\.\/files\/([^)]+\.woff2)\)/)?.[1];+ if (!file) {+ throw new Error(`${pkg} ${weight} ${style}: a face with no woff2`);+ }+ const subset = file.slice(pkg.length + 1, -`-${weight}-${style}.woff2`.length);+ const range = body.match(/unicode-range:\s*([^;]+);/)?.[1].trim();+ faces.push({ file, subset, ...(range ? { range } : {}) });+ }+ if (!faces.some((f) => f.subset === SKIA_SUBSET)) {+ throw new Error(`${pkg} ${weight} ${style}: no ${SKIA_SUBSET} face`);+ }+ return faces;+}+rmSync(dest, { recursive: true, force: true });mkdirSync(dest, { recursive: true });const manifest = [];for (const entry of FAMILIES) {const pkg = slug(entry.family);- const files = path.join(path.dirname(require.resolve(`@fontsource/${pkg}/package.json`)), "files");- const staged = entry.weights.map((weight) => {- const name = `${pkg}-${weight}.woff2`;- copyFileSync(path.join(files, `${pkg}-latin-${weight}-normal.woff2`), path.join(dest, name));- return name;- });- // Italic faces join the same family; skia reads the slant off the file.- for (const weight of entry.italics ?? []) {- const name = `${pkg}-${weight}-italic.woff2`;- copyFileSync(path.join(files, `${pkg}-latin-${weight}-italic.woff2`), path.join(dest, name));- staged.push(name);+ const pkgDir = path.dirname(require.resolve(`@fontsource/${pkg}/package.json`));+ const styled = [+ ...entry.weights.map((weight) => ({ weight, style: "normal" })),+ ...(entry.italics ?? []).map((weight) => ({ weight, style: "italic" })),+ ];++ // Copy every subset's file; a subset's range is the same at every weight,+ // so the manifest keeps it once per family.+ const faces = [];+ const ranges = {};+ for (const { weight, style } of styled) {+ for (const { file, subset, range } of readFaces(pkgDir, pkg, weight, style)) {+ copyFileSync(path.join(pkgDir, "files", file), path.join(dest, file));+ faces.push({ file, weight, style, subset });+ if (range) {+ ranges[subset] = range;+ }+ }}+manifest.push({- ...(entry.id ? { id: entry.id, label: entry.label } : {}),+ ...(entry.id ? { id: entry.id } : {}),family: entry.family,...(entry.aliases ? { aliases: entry.aliases } : {}),- files: staged,+ // Skia reads weight and slant off each file.+ files: faces.filter((f) => f.subset === SKIA_SUBSET).map((f) => f.file),+ faces,+ ranges,});}-writeFileSync(path.join(dest, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);+writeFileSync(path.join(dest, "manifest.json"), `${JSON.stringify(manifest)}\n`);diff --git a/site/src/cut/lib/fontCatalog.test.ts b/site/src/cut/lib/fontCatalog.test.tsindex 8a97e408..c0c6d8ae 100644--- a/site/src/cut/lib/fontCatalog.test.ts+++ b/site/src/cut/lib/fontCatalog.test.ts@@ -1,22 +1,20 @@import { expect, test } from "bun:test";-import { readFileSync } from "node:fs";+import manifest from "../../../public/cut-fonts/manifest.json";import { GOOGLE_FONTS } from "./fontCatalog";-// The catalog's weights are the faces googleFonts.ts declares for the page, so-// a font suggestion never offers a weight the page would draw synthesized.+// The catalog's weights are the faces staged for the page, so a font+// suggestion never offers a weight the page would draw synthesized.-const declared = readFileSync(new URL("./googleFonts.ts", import.meta.url), "utf8");const faces = (style: "normal" | "italic") =>new Set(- [...declared.matchAll(/@fontsource\/([a-z0-9-]+)\/(\d+)(-italic)?\.css/g)]- .filter((m) => (style === "italic") === Boolean(m[3]))- .map((m) => `${m[1]}/${m[2]}`)+ manifest.flatMap((entry) =>+ entry.id ? entry.faces.filter((f) => f.style === style).map((f) => `${entry.id}/${f.weight}`) : []+ ));-const pkg = (label: string) => label.toLowerCase().replace(/[^a-z0-9]+/g, "-");test("every bundled family lists the weights the page declares", () => {- const listed = new Set(GOOGLE_FONTS.flatMap((f) => f.weights.map((w) => `${pkg(f.label)}/${w}`)));+ const listed = new Set(GOOGLE_FONTS.flatMap((f) => f.weights.map((w) => `${f.id}/${w}`)));expect(listed).toEqual(faces("normal"));- const italics = new Set(GOOGLE_FONTS.flatMap((f) => (f.italics ?? []).map((w) => `${pkg(f.label)}/${w}`)));+ const italics = new Set(GOOGLE_FONTS.flatMap((f) => (f.italics ?? []).map((w) => `${f.id}/${w}`)));expect(italics).toEqual(faces("italic"));});diff --git a/site/src/cut/lib/fontCatalog.ts b/site/src/cut/lib/fontCatalog.tsindex 5fbf21f6..698f364f 100644--- a/site/src/cut/lib/fontCatalog.ts+++ b/site/src/cut/lib/fontCatalog.ts@@ -1,55 +1,28 @@/**- * The bundled font families, named once.+ * The bundled font families, named once in fonts.json.** `googleFonts.ts` registers this list for the page, and the assistant's* catalog builds its font sentence from it, so the menu the user sees and the* ids the model is taught can't drift apart. A label is the family's own name,- * the one its stylesheet and the headless renderer declare it under. The+ * the one the page and the headless renderer declare it under. The* weights are the faces bundled, so a font suggestion only offers those.* Framework-free on purpose: the server imports it too.*/+import fonts from "./fonts.json";+export interface BundledFont {id: string;label: string;- /** The upright weights bundled, as googleFonts.ts declares them. */+ /** The upright weights bundled. */weights: number[];/** The weights bundled in italic too. */italics?: number[];}-export const GOOGLE_FONTS: BundledFont[] = [- { id: "inter", label: "Inter", weights: [400, 500, 600, 700] },- { id: "montserrat", label: "Montserrat", weights: [400, 500, 600, 700, 800, 900] },- { id: "poppins", label: "Poppins", weights: [400, 500, 600, 700, 800, 900] },- { id: "oswald", label: "Oswald", weights: [400, 500, 600, 700] },- { id: "space-grotesk", label: "Space Grotesk", weights: [400, 500, 600, 700] },- { id: "playfair", label: "Playfair Display", weights: [400, 500, 600, 700, 900], italics: [400, 700, 900] },- { id: "caveat", label: "Caveat", weights: [400, 500, 600, 700] },- { id: "bebas", label: "Bebas Neue", weights: [400] },- { id: "anton", label: "Anton", weights: [400] },- { id: "archivo-black", label: "Archivo Black", weights: [400] },- { id: "bangers", label: "Bangers", weights: [400] },- { id: "lobster", label: "Lobster", weights: [400] },- { id: "pacifico", label: "Pacifico", weights: [400] },- { id: "permanent-marker", label: "Permanent Marker", weights: [400] },- { id: "dm-serif", label: "DM Serif Display", weights: [400] },- { id: "amatic", label: "Amatic SC", weights: [400, 700] },- { id: "dseg14", label: "DSEG14 Classic", weights: [300, 700], italics: [300, 700] },- { id: "outfit", label: "Outfit", weights: [400, 500, 600, 700] },- { id: "cinzel", label: "Cinzel", weights: [400, 700] },- { id: "freckle-face", label: "Freckle Face", weights: [400] },- { id: "orbitron", label: "Orbitron", weights: [400, 900] },- { id: "chewy", label: "Chewy", weights: [400] },- { id: "great-vibes", label: "Great Vibes", weights: [400] },- { id: "rubik-dirt", label: "Rubik Dirt", weights: [400] },- { id: "fredoka", label: "Fredoka", weights: [500, 600, 700] },- { id: "oranienbaum", label: "Oranienbaum", weights: [400] },- { id: "kaushan", label: "Kaushan Script", weights: [400] },- { id: "rubik", label: "Rubik", weights: [400, 500, 700, 900] },- { id: "jost", label: "Jost", weights: [400, 500, 600, 700] },- { id: "gloria-hallelujah", label: "Gloria Hallelujah", weights: [400] },- { id: "prompt", label: "Prompt", weights: [900] },-];+export const GOOGLE_FONTS: BundledFont[] = fonts.flatMap((f) =>+ // A family with no id is a headless stand-in, off the menu.+ f.id ? [{ id: f.id, label: f.family, weights: f.weights, ...(f.italics ? { italics: f.italics } : {}) }] : []+);export const GOOGLE_FONT_IDS = GOOGLE_FONTS.map((f) => f.id);diff --git a/site/src/cut/lib/fonts.json b/site/src/cut/lib/fonts.jsonnew file mode 100644index 00000000..3b5728a4--- /dev/null+++ b/site/src/cut/lib/fonts.json@@ -0,0 +1,79 @@+[+ { "id": "inter", "family": "Inter", "weights": [400, 500, 600, 700] },+ { "id": "montserrat", "family": "Montserrat", "weights": [400, 500, 600, 700, 800, 900] },+ { "id": "poppins", "family": "Poppins", "weights": [400, 500, 600, 700, 800, 900] },+ { "id": "oswald", "family": "Oswald", "weights": [400, 500, 600, 700] },+ { "id": "space-grotesk", "family": "Space Grotesk", "weights": [400, 500, 600, 700] },+ {+ "id": "playfair",+ "family": "Playfair Display",+ "weights": [400, 500, 600, 700, 900],+ "italics": [400, 700, 900],+ "note": "The italics are the caption emphasis default's face (subtitles.ts)."+ },+ { "id": "caveat", "family": "Caveat", "weights": [400, 500, 600, 700] },+ { "id": "bebas", "family": "Bebas Neue", "weights": [400] },+ { "id": "anton", "family": "Anton", "weights": [400], "aliases": ["Impact", "Arial Black"] },+ { "id": "archivo-black", "family": "Archivo Black", "weights": [400] },+ { "id": "bangers", "family": "Bangers", "weights": [400] },+ { "id": "lobster", "family": "Lobster", "weights": [400] },+ { "id": "pacifico", "family": "Pacifico", "weights": [400] },+ { "id": "permanent-marker", "family": "Permanent Marker", "weights": [400] },+ { "id": "dm-serif", "family": "DM Serif Display", "weights": [400] },+ { "id": "amatic", "family": "Amatic SC", "weights": [400, 700] },+ {+ "id": "dseg14",+ "family": "DSEG14 Classic",+ "weights": [300, 700],+ "italics": [300, 700],+ "note": "Light and Bold only: font matching draws a 400 title in the thin Light LCD face, and 700-900 in Bold."+ },+ { "id": "outfit", "family": "Outfit", "weights": [400, 500, 600, 700] },+ { "id": "cinzel", "family": "Cinzel", "weights": [400, 700] },+ { "id": "freckle-face", "family": "Freckle Face", "weights": [400] },+ { "id": "orbitron", "family": "Orbitron", "weights": [400, 900] },+ { "id": "chewy", "family": "Chewy", "weights": [400] },+ { "id": "great-vibes", "family": "Great Vibes", "weights": [400] },+ { "id": "rubik-dirt", "family": "Rubik Dirt", "weights": [400] },+ { "id": "fredoka", "family": "Fredoka", "weights": [500, 600, 700] },+ { "id": "oranienbaum", "family": "Oranienbaum", "weights": [400] },+ { "id": "kaushan", "family": "Kaushan Script", "weights": [400] },+ { "id": "rubik", "family": "Rubik", "weights": [400, 500, 700, 900] },+ { "id": "jost", "family": "Jost", "weights": [400, 500, 600, 700] },+ { "id": "gloria-hallelujah", "family": "Gloria Hallelujah", "weights": [400] },+ {+ "id": "prompt",+ "family": "Prompt",+ "weights": [900],+ "note": "Black only: the heavy geometric face of a reference's font cycle."+ },+ {+ "family": "Roboto",+ "weights": [400, 500, 600, 700],+ "aliases": [+ "-apple-system",+ "system-ui",+ "SF Pro Display",+ "SF Pro Text",+ "Helvetica Neue",+ "Helvetica",+ "Arial",+ "sans-serif"+ ]+ },+ {+ "family": "Noto Serif",+ "weights": [400, 500, 600, 700],+ "aliases": ["New York", "ui-serif", "Georgia", "Times New Roman", "serif"]+ },+ {+ "family": "Nunito",+ "weights": [400, 500, 600, 700],+ "aliases": ["ui-rounded", "SF Pro Rounded", "Arial Rounded MT Bold"]+ },+ {+ "family": "Roboto Mono",+ "weights": [400, 500, 600, 700],+ "aliases": ["ui-monospace", "SF Mono", "Menlo", "Courier New", "monospace"]+ }+]diff --git a/site/src/cut/lib/googleFonts.test.ts b/site/src/cut/lib/googleFonts.test.tsnew file mode 100644index 00000000..0bea66a5--- /dev/null+++ b/site/src/cut/lib/googleFonts.test.ts@@ -0,0 +1,66 @@+import { afterAll, beforeAll, expect, test } from "bun:test";+import { readFileSync } from "node:fs";++// The page declares every bundled face as an unloaded FontFace, one per+// unicode subset, so a family costs the bundle nothing until text in it draws.++interface AddedFace {+ family: string;+ source: string;+ descriptors: FontFaceDescriptors;+ loaded: boolean;+}++const added: AddedFace[] = [];+const saved = { FontFace: globalThis.FontFace, document: globalThis.document };++/** A FontFace that records its arguments and whether anyone loaded it. */+class RecordingFace {+ face: AddedFace;+ constructor(family: string, source: string, descriptors: FontFaceDescriptors) {+ this.face = { family, source, descriptors, loaded: false };+ }+ load() {+ this.face.loaded = true;+ return Promise.resolve(this);+ }+}++beforeAll(async () => {+ Object.assign(globalThis, {+ FontFace: RecordingFace,+ document: { fonts: { add: (f: RecordingFace) => added.push(f.face) } },+ });+ await import("./googleFonts");+});+afterAll(() => {+ Object.assign(globalThis, saved);+});++/** Each subset's unicode-range in a @fontsource stylesheet, by file. */+function rangesIn(css: string): Map<string, string> {+ const ranges = new Map<string, string>();+ for (const [, body] of css.matchAll(/@font-face\s*{([^}]*)}/g)) {+ const file = body.match(/url\(\.\/files\/([^)]+\.woff2)\)/)![1];+ ranges.set(file, body.match(/unicode-range:\s*([^;]+);/)![1].trim());+ }+ return ranges;+}++test("a listed family gets a lazy FontFace per subset with its unicode range", () => {+ const css = readFileSync(new URL("../../../node_modules/@fontsource/inter/400.css", import.meta.url), "utf8");+ const expected = rangesIn(css);+ const inter400 = added.filter((f) => f.family === "Inter" && f.descriptors.weight === "400");++ expect(expected.size).toBeGreaterThan(1);+ expect(inter400.length).toBe(expected.size);+ for (const [file, range] of expected) {+ const face = inter400.find((f) => f.source.includes(`/cut-fonts/${file}`));+ expect(face?.descriptors).toMatchObject({ style: "normal", unicodeRange: range });+ }+ expect(added.some((f) => f.loaded)).toBe(false);+});++test("the stand-in families stay off the page", () => {+ expect(added.some((f) => f.family === "Roboto")).toBe(false);+});diff --git a/site/src/cut/lib/googleFonts.ts b/site/src/cut/lib/googleFonts.tsindex 921076a6..17299e95 100644--- a/site/src/cut/lib/googleFonts.ts+++ b/site/src/cut/lib/googleFonts.ts@@ -2,95 +2,59 @@/*** The bundled Google font families, self-hosted from the @fontsource packages.- * Their stylesheets declare one face per unicode subset, served from our- * origin, so nothing fetches Google at build or run time and a rasterize is- * deterministic offline. Each family is declared under its own name, the name- * the catalog labels it with and the headless renderer loads it under.- * Importing this module (the editor root does) registers every family into the- * shared font registry.+ * scripts/stage-cut-fonts.mjs copies every face of each family in fonts.json+ * into /cut-fonts, one file per unicode subset, so nothing fetches Google at+ * build or run time and a rasterize is deterministic offline. Each family is+ * declared under its own name, the name the catalog labels it with and the+ * headless renderer loads it under. Importing this module (the editor root+ * does) declares every face and registers every family into the shared font+ * registry.*/-import "@fontsource/inter/400.css";-import "@fontsource/inter/500.css";-import "@fontsource/inter/600.css";-import "@fontsource/inter/700.css";-import "@fontsource/montserrat/400.css";-import "@fontsource/montserrat/500.css";-import "@fontsource/montserrat/600.css";-import "@fontsource/montserrat/700.css";-import "@fontsource/montserrat/800.css";-import "@fontsource/montserrat/900.css";-import "@fontsource/poppins/400.css";-import "@fontsource/poppins/500.css";-import "@fontsource/poppins/600.css";-import "@fontsource/poppins/700.css";-import "@fontsource/poppins/800.css";-import "@fontsource/poppins/900.css";-import "@fontsource/oswald/400.css";-import "@fontsource/oswald/500.css";-import "@fontsource/oswald/600.css";-import "@fontsource/oswald/700.css";-import "@fontsource/space-grotesk/400.css";-import "@fontsource/space-grotesk/500.css";-import "@fontsource/space-grotesk/600.css";-import "@fontsource/space-grotesk/700.css";-import "@fontsource/playfair-display/400.css";-import "@fontsource/playfair-display/500.css";-import "@fontsource/playfair-display/600.css";-import "@fontsource/playfair-display/700.css";-import "@fontsource/playfair-display/900.css";-// The italics are the caption emphasis default's face (subtitles.ts).-import "@fontsource/playfair-display/400-italic.css";-import "@fontsource/playfair-display/700-italic.css";-import "@fontsource/playfair-display/900-italic.css";-import "@fontsource/caveat/400.css";-import "@fontsource/caveat/500.css";-import "@fontsource/caveat/600.css";-import "@fontsource/caveat/700.css";-import "@fontsource/bebas-neue/400.css";-import "@fontsource/anton/400.css";-import "@fontsource/archivo-black/400.css";-import "@fontsource/bangers/400.css";-import "@fontsource/lobster/400.css";-import "@fontsource/pacifico/400.css";-import "@fontsource/permanent-marker/400.css";-import "@fontsource/dm-serif-display/400.css";-import "@fontsource/amatic-sc/400.css";-import "@fontsource/amatic-sc/700.css";-// Light and Bold only, so a 400 title matches the thin Light LCD face.-import "@fontsource/dseg14-classic/300.css";-import "@fontsource/dseg14-classic/300-italic.css";-import "@fontsource/dseg14-classic/700.css";-import "@fontsource/dseg14-classic/700-italic.css";-import "@fontsource/outfit/400.css";-import "@fontsource/outfit/500.css";-import "@fontsource/outfit/600.css";-import "@fontsource/outfit/700.css";-import "@fontsource/cinzel/400.css";-import "@fontsource/cinzel/700.css";-import "@fontsource/freckle-face/400.css";-import "@fontsource/orbitron/400.css";-import "@fontsource/orbitron/900.css";-import "@fontsource/chewy/400.css";-import "@fontsource/great-vibes/400.css";-import "@fontsource/rubik-dirt/400.css";-import "@fontsource/fredoka/500.css";-import "@fontsource/fredoka/600.css";-import "@fontsource/fredoka/700.css";-import "@fontsource/oranienbaum/400.css";-import "@fontsource/kaushan-script/400.css";-import "@fontsource/rubik/400.css";-import "@fontsource/rubik/500.css";-import "@fontsource/rubik/700.css";-import "@fontsource/rubik/900.css";-import "@fontsource/jost/400.css";-import "@fontsource/jost/500.css";-import "@fontsource/jost/600.css";-import "@fontsource/jost/700.css";-import "@fontsource/gloria-hallelujah/400.css";-// Black only: the heavy geometric face of a reference's font cycle.-import "@fontsource/prompt/900.css";+import manifest from "../../../public/cut-fonts/manifest.json";import { GOOGLE_FONTS } from "./fontCatalog";import { registerFonts } from "./types";+/** One staged family as the manifest lists it. */+interface StagedFamily {+ /** Absent on the headless stand-ins, which the page never draws. */+ id?: string;+ family: string;+ faces: { file: string; weight: number; style: string; subset: string }[];+ /** Each subset's unicode-range; a single-subset family has none. */+ ranges: Partial<Record<string, string>>;+}++/** Where the staged files are served. */+const FONT_DIR = "/cut-fonts/";++/** Declare one FontFace per staged face, unloaded. The browser fetches a+ * face's file the first time text in its unicode range is drawn or+ * `document.fonts.load` asks for it, as it does for a CSS @font-face rule,+ * so a family nobody uses costs nothing. */+function declareFaces(): void {+ // Server rendering has no document; the browser's import declares them.+ if (typeof document === "undefined") {+ return;+ }++ for (const entry of manifest as StagedFamily[]) {+ if (!entry.id) {+ continue;+ }++ for (const face of entry.faces) {+ const range = entry.ranges[face.subset];+ const font = new FontFace(entry.family, `url(${FONT_DIR}${face.file}) format("woff2")`, {+ weight: String(face.weight),+ style: face.style,+ display: "swap",+ ...(range ? { unicodeRange: range } : {}),+ });+ document.fonts.add(font);+ }+ }+}++declareFaces();registerFonts(GOOGLE_FONTS.map((f) => ({ id: f.id, label: f.label, stack: `"${f.label}"` })));diff --git a/site/src/cut/lib/headless/nodeFonts.ts b/site/src/cut/lib/headless/nodeFonts.tsindex 1585a6da..e80df8f0 100644--- a/site/src/cut/lib/headless/nodeFonts.ts+++ b/site/src/cut/lib/headless/nodeFonts.ts@@ -5,9 +5,8 @@ import { registerFonts } from "../types";/*** Fonts for a headless render.*- * A page gets its faces from the @fontsource stylesheets, which serve them to- * the browser. Nothing in that reaches a render worker, so the same faces are- * staged as files by scripts/stage-cut-fonts.mjs and loaded into skia here,+ * scripts/stage-cut-fonts.mjs stages the faces the page declares as files, and+ * their latin subset loads into skia here,* under both their own names and the names the base system stacks ask for* ("SF Pro Display", "Impact", "New York"). After this* runs, `fontStack` resolves every Cut font id to a family skia can draw, and@@ -22,9 +21,9 @@ interface FontManifestEntry {/** The Cut font id, for the families the font menu offers. Absent on the* stand-ins, which only answer to their aliases. */id?: string;- label?: string;family: string;aliases?: string[];+ /** The latin face of each weight and slant. */files: string[];}@@ -65,7 +64,7 @@ export async function installHeadlessFonts(): Promise<number> {}if (entry.id)registerFonts([- { id: entry.id, label: entry.label ?? entry.family, stack: `"${entry.family}"` },+ { id: entry.id, label: entry.family, stack: `"${entry.family}"` },]);loaded++;}