Skip to content

Open source CapCut alternative.

TypeScript

feat(site): Cut installs its own font files

David Le227a15a8913a
diff --git a/site/.gitignore b/site/.gitignore
index 86e492c9..7fb60b04 100644
--- a/site/.gitignore
+++ b/site/.gitignore
@@ -58,3 +58,4 @@ next-env.d.ts
# MediaPipe wasm runtime, staged from node_modules by postinstall
/public/mediapipe/wasm/
+/public/cut-fonts/
diff --git a/site/scripts/fetch-cut-fonts.mjs b/site/scripts/fetch-cut-fonts.mjs
new file mode 100644
index 00000000..a896a773
--- /dev/null
+++ b/site/scripts/fetch-cut-fonts.mjs
@@ -0,0 +1,136 @@
+// Stage the Cut font files into public/ so a headless render draws text with
+// the same faces the editor shows. The page gets these families from
+// next/font/google, which downloads them during `next build` and serves them
+// under hashed names — fine for a browser, useless to a render worker that
+// needs a file path to hand skia. So the same faces are staged here under
+// stable names, with a manifest the headless bootstrap reads.
+//
+// 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.
+//
+// Files are fetched once and kept, so a re-install is free and an offline one
+// keeps working. Runs from postinstall; a failure warns and leaves whatever
+// is already staged.
+import { mkdirSync, readdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const dest = path.join(root, "public", "cut-fonts");
+
+/** Keep in step with googleFonts.ts, which registers 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, 700] },
+ { id: "montserrat", label: "Montserrat", family: "Montserrat", weights: [400, 700] },
+ { id: "poppins", label: "Poppins", family: "Poppins", weights: [400, 700] },
+ { id: "oswald", label: "Oswald", family: "Oswald", weights: [400, 700] },
+ { id: "space-grotesk", label: "Space Grotesk", family: "Space Grotesk", weights: [400, 700] },
+ { id: "playfair", label: "Playfair Display", family: "Playfair Display", weights: [400, 700] },
+ { id: "caveat", label: "Caveat", family: "Caveat", weights: [400, 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] },
+ {
+ family: "Roboto",
+ weights: [400, 700],
+ aliases: [
+ "-apple-system",
+ "system-ui",
+ "SF Pro Display",
+ "SF Pro Text",
+ "Helvetica Neue",
+ "Helvetica",
+ "Arial",
+ "sans-serif",
+ ],
+ },
+ {
+ family: "Noto Serif",
+ weights: [400, 700],
+ aliases: ["New York", "ui-serif", "Georgia", "Times New Roman", "serif"],
+ },
+ {
+ family: "Nunito",
+ weights: [400, 700],
+ aliases: ["ui-rounded", "SF Pro Rounded", "Arial Rounded MT Bold"],
+ },
+ {
+ family: "Roboto Mono",
+ weights: [400, 700],
+ aliases: ["ui-monospace", "SF Mono", "Menlo", "Courier New", "monospace"],
+ },
+];
+
+// A browser UA gets woff2 back; skia reads it, and it is a fraction of a ttf.
+const UA =
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36";
+
+const slug = (family) => family.toLowerCase().replace(/[^a-z0-9]+/g, "-");
+
+/** The latin-subset file URL for each weight of one family. Blocks arrive one
+ * per subset, each headed by its /* subset *\/ comment; latin carries the
+ * characters a title is written in. */
+async function faceUrls(family, weights) {
+ const spec = `${family.replace(/ /g, "+")}:wght@${weights.join(";")}`;
+ const res = await fetch(`https://fonts.googleapis.com/css2?family=${spec}&display=swap`, {
+ headers: { "User-Agent": UA },
+ });
+ if (!res.ok) throw new Error(`css2 answered ${res.status}`);
+ const css = await res.text();
+ const found = new Map();
+ for (const [, subset, body] of css.matchAll(/\/\*\s*([\w-]+)\s*\*\/\s*@font-face\s*\{([^}]*)\}/g)) {
+ if (subset !== "latin") continue;
+ const weight = Number(body.match(/font-weight:\s*(\d+)/)?.[1]);
+ const url = body.match(/src:\s*url\((https:[^)]+)\)/)?.[1];
+ if (weight && url && !found.has(weight)) found.set(weight, url);
+ }
+ return found;
+}
+
+mkdirSync(dest, { recursive: true });
+const staged = new Set(readdirSync(dest));
+const manifest = [];
+for (const entry of FAMILIES) {
+ const fileFor = (weight) => `${slug(entry.family)}-${weight}.woff2`;
+ const files = entry.weights.map(fileFor);
+ try {
+ if (files.some((f) => !staged.has(f))) {
+ const urls = await faceUrls(entry.family, entry.weights);
+ for (const weight of entry.weights) {
+ const name = fileFor(weight);
+ if (staged.has(name)) continue;
+ const url = urls.get(weight);
+ if (!url) throw new Error(`no latin face at weight ${weight}`);
+ const res = await fetch(url, { headers: { "User-Agent": UA } });
+ if (!res.ok) throw new Error(`weight ${weight} answered ${res.status}`);
+ writeFileSync(path.join(dest, name), Buffer.from(await res.arrayBuffer()));
+ staged.add(name);
+ }
+ }
+ manifest.push({
+ ...(entry.id ? { id: entry.id, label: entry.label } : {}),
+ family: entry.family,
+ ...(entry.aliases ? { aliases: entry.aliases } : {}),
+ files,
+ });
+ } catch (err) {
+ // One family that will not come down is one font a headless render falls
+ // back for; the rest still stage.
+ console.warn(`fetch-cut-fonts: ${entry.family}: ${err instanceof Error ? err.message : err}`);
+ }
+}
+writeFileSync(path.join(dest, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 31e1b8e8..038ea082 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -129,7 +129,7 @@ export function Editor({
// Uploaded fonts become live FontFaces the moment their assets exist (and
// drop out when deleted), so titles set in them never measure a fallback.
const assetsForFonts = useEditor((s) => s.assets);
- useEffect(() => syncFontAssets(assetsForFonts), [assetsForFonts]);
+ useEffect(() => void syncFontAssets(assetsForFonts), [assetsForFonts]);
const [conflictReloaded, setConflictReloaded] = useState(false);
const [shareGone, setShareGone] = useState(false);
// This project lives on this Mac and the Donkey app isn't answering. Nothing
diff --git a/site/src/cut/lib/fontAssets.ts b/site/src/cut/lib/fontAssets.ts
index a9a93207..1f96a264 100644
--- a/site/src/cut/lib/fontAssets.ts
+++ b/site/src/cut/lib/fontAssets.ts
@@ -16,9 +16,28 @@ import {
type MediaAsset,
} from "./types";
-/** Asset ids whose FontFace is loaded (or loading) in this page. */
+/** Asset ids whose face is loaded (or loading) in this process. */
const loaded = new Map<string, Promise<void>>();
+/**
+ * How a font's bytes become a family the painters can draw.
+ *
+ * The page adds a FontFace to the document. A process with no document
+ * installs its own — the server canvas's font library — so a title set in a
+ * project's uploaded font renders the same in a job as in the tab.
+ */
+export type FontInstaller = (family: string, bytes: ArrayBuffer) => Promise<void>;
+
+let installFace: FontInstaller = async (family, bytes) => {
+ const face = new FontFace(family, bytes);
+ await face.load();
+ document.fonts.add(face);
+};
+
+export function setFontInstaller(install: FontInstaller): void {
+ installFace = install;
+}
+
/** A display label from the uploaded file's name, extension dropped. */
const fontLabel = (name: string) => name.replace(/\.(ttf|otf|woff2?|TTF|OTF)$/, "") || "Custom font";
@@ -31,9 +50,7 @@ export function registerFontAsset(asset: MediaAsset): Promise<void> {
hit = (async () => {
const res = await fetch(asset.url);
if (!res.ok) throw new Error("font fetch failed");
- const face = new FontFace(family, await res.arrayBuffer());
- await face.load();
- document.fonts.add(face);
+ await installFace(family, await res.arrayBuffer());
registerFonts([
{ id: uploadedFontId(asset.id), label: fontLabel(asset.name), stack: `"${family}"` },
]);
@@ -46,14 +63,15 @@ export function registerFontAsset(asset: MediaAsset): Promise<void> {
}
/** Reconcile the registry with the project's font assets: register new ones,
- * unregister deleted ones. The editor calls this whenever assets change. */
-export function syncFontAssets(assets: MediaAsset[]): void {
+ * unregister deleted ones. The editor calls this whenever assets change; a
+ * headless run awaits it before drawing anything. */
+export function syncFontAssets(assets: MediaAsset[]): Promise<void> {
const fonts = assets.filter((a) => a.type === "font");
- for (const a of fonts) void registerFontAsset(a);
const live = new Set(fonts.map((a) => a.id));
const stale = [...loaded.keys()].filter((id) => !live.has(id));
if (stale.length) {
for (const id of stale) loaded.delete(id);
unregisterFonts(stale.map(uploadedFontId));
}
+ return Promise.all(fonts.map(registerFontAsset)).then(() => {});
}
diff --git a/site/src/cut/lib/headless/nodeFonts.ts b/site/src/cut/lib/headless/nodeFonts.ts
new file mode 100644
index 00000000..ac26f174
--- /dev/null
+++ b/site/src/cut/lib/headless/nodeFonts.ts
@@ -0,0 +1,75 @@
+import { setFontInstaller } from "../fontAssets";
+import { registerFonts } from "../types";
+
+/**
+ * Fonts for a headless render.
+ *
+ * A page gets its faces from next/font, which serves them to the browser and
+ * hands the painters a CSS stack. Nothing in that reaches a render worker, so
+ * the same faces are staged as files by scripts/fetch-cut-fonts.mjs and
+ * loaded 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
+ * a title rendered headless looks like the title in the tab.
+ *
+ * A project's own uploaded font files go the same way, through the installer
+ * the font-assets module hands its bytes to: skia reads faces from disk, so
+ * the bytes land in a scratch file first.
+ */
+
+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[];
+ files: string[];
+}
+
+/** Load the staged font files into skia. Returns how many families landed;
+ * 0 when the directory is missing, which leaves text to whatever faces the
+ * host itself has. */
+export async function installHeadlessFonts(): Promise<number> {
+ try {
+ const [skia, fs, path] = await Promise.all([
+ import("skia-canvas"),
+ import("node:fs/promises"),
+ import("node:path"),
+ ]);
+ // Registered before the staged files are read: a project's uploaded font
+ // is a separate capability, and it should survive an image built without
+ // the staging step.
+ setFontInstaller(async (family, bytes) => {
+ const os = await import("node:os");
+ const scratch = await fs.mkdtemp(path.join(os.tmpdir(), "cut-font-"));
+ const file = path.join(scratch, `${family}.font`);
+ await fs.writeFile(file, Buffer.from(bytes));
+ skia.FontLibrary.use(family, [file]);
+ });
+
+ const dir = path.join(process.cwd(), "public", "cut-fonts");
+ const manifest = JSON.parse(
+ await fs.readFile(path.join(dir, "manifest.json"), "utf8")
+ ) as FontManifestEntry[];
+
+ let loaded = 0;
+ for (const entry of manifest) {
+ const files = entry.files.map((f) => path.join(dir, f));
+ try {
+ skia.FontLibrary.use(entry.family, files);
+ for (const alias of entry.aliases ?? []) skia.FontLibrary.use(alias, files);
+ } catch {
+ continue; // one unreadable face costs that font alone
+ }
+ if (entry.id)
+ registerFonts([
+ { id: entry.id, label: entry.label ?? entry.family, stack: `"${entry.family}"` },
+ ]);
+ loaded++;
+ }
+ return loaded;
+ } catch {
+ return 0;
+ }
+}