Skip to content

Write HTML. Render video. Built for agents.

perf(core): a preview loads each web font once, not once per scene (#5806)

Miguel Ángel80667726e8a9
diff --git a/packages/core/src/compiler/compositionScoping.ts b/packages/core/src/compiler/compositionScoping.ts
index 27f868a0ae..c231115a43 100644
--- a/packages/core/src/compiler/compositionScoping.ts
+++ b/packages/core/src/compiler/compositionScoping.ts
@@ -219,7 +219,14 @@ function fontFaceKey(atRule: AtRule): string {
/** Drops repeats of an identical `@font-face` across the given style texts, keeping the last copy:
* the last matching rule is the one the browser uses, so a rule in between never gains precedence. */
-export function dedupeFontFaceRules(styleTexts: string[]): string[] {
+export const dedupeFontFaceRules = (styleTexts: string[]): string[] => dropFontFaces(styleTexts);
+
+export function hoistFontFaceRules(styleTexts: string[]): { styles: string[]; faces: string[] } {
+ const faces: string[] = [];
+ return { styles: dropFontFaces(styleTexts, faces), faces };
+}
+
+function dropFontFaces(styleTexts: string[], hoisted?: string[]): string[] {
const seen = new Set<string>();
return [...styleTexts]
.reverse()
@@ -235,12 +242,13 @@ export function dedupeFontFaceRules(styleTexts: string[]): string[] {
for (const node of [...(root.nodes ?? [])].reverse()) {
if (!isFontFaceAtRule(node)) continue;
const key = fontFaceKey(node);
- if (seen.has(key)) {
- node.remove();
- changed = true;
- } else {
+ if (!seen.has(key)) {
seen.add(key);
+ if (!hoisted) continue;
+ hoisted.unshift(node.toString());
}
+ node.remove();
+ changed = true;
}
return changed ? root.toResult({ map: false }).css : css;
})
diff --git a/packages/core/src/compiler/htmlBundler.test.ts b/packages/core/src/compiler/htmlBundler.test.ts
index a511cc885a..3366608623 100644
--- a/packages/core/src/compiler/htmlBundler.test.ts
+++ b/packages/core/src/compiler/htmlBundler.test.ts
@@ -3182,7 +3182,7 @@ describe("bundleToSingleHtml sceneParts", () => {
const partsOf = (doc: Document, scene: string) =>
[...doc.querySelectorAll(`[data-hf-scene="${scene}"]`)].map((el) => el.tagName.toLowerCase());
- it("keeps each scene's own copy of a shared @font-face, so one scene still swaps alone", async () => {
+ it("puts a @font-face two scenes share in one style outside the scenes, once", async () => {
const face = `@font-face { font-family: "Brand"; src: url('assets/fonts/brand.woff2'); }`;
const dir = makeTempProject({
"index.html": `<!doctype html>
@@ -3202,8 +3202,14 @@ describe("bundleToSingleHtml sceneParts", () => {
const css = [...doc.querySelectorAll(`style[data-hf-scene="${scene}"]`)]
.map((el) => el.textContent ?? "")
.join("\n");
- expect(css).toContain("@font-face");
+ expect(css).not.toContain("@font-face");
}
+ const fonts = doc.querySelector("style[data-hf-scene-fonts]");
+ expect(fonts?.hasAttribute("data-hf-scene")).toBe(false);
+ const faces = (css: string) => css.match(/@font-face/g)?.length ?? 0;
+ expect(faces(fonts?.textContent ?? "")).toBe(1);
+ const allCss = [...doc.querySelectorAll("style")].map((el) => el.textContent ?? "").join("\n");
+ expect(faces(allCss)).toBe(1);
});
it("tags each top-level scene's host, styles and scripts, with nested scenes in their parent's parts", async () => {
diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts
index 7f385202bc..0dd6c5fa3e 100644
--- a/packages/core/src/compiler/htmlBundler.ts
+++ b/packages/core/src/compiler/htmlBundler.ts
@@ -16,7 +16,7 @@ import {
isJavaScriptType,
planCompositionAssembly,
} from "./compositionAssembly";
-import { SCENE_PART_ATTR } from "../sceneParts";
+import { SCENE_FONTS_ATTR, SCENE_PART_ATTR } from "../sceneParts";
import {
ensureExternalScriptTag,
readExternalScriptAttributes,
@@ -54,6 +54,7 @@ import {
import {
buildVariablesByCompScript,
dedupeFontFaceRules,
+ hoistFontFaceRules,
scopeCssToComposition,
wrapInlineScriptWithErrorBoundary,
scopedModulePrelude,
@@ -1406,13 +1407,20 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
if (srcset)
el.setAttribute("srcset", rewriteSrcsetWithInlinedAssets(srcset, projectDir, inlineAssets));
}
- // Before inlining, so postcss reads paths not font bytes; scene parts keep copies to swap alone.
- if (!options?.sceneParts) {
- const liveStyles = [...document.querySelectorAll("style")].filter(isAlwaysAppliedStyle);
- const dedupedStyles = dedupeFontFaceRules(liveStyles.map((el) => el.textContent || ""));
- liveStyles.forEach((el, i) => {
- el.textContent = dedupedStyles[i] ?? "";
- });
+ // Before inlining, so postcss reads paths not font bytes.
+ const liveStyles = [...document.querySelectorAll("style")].filter(isAlwaysAppliedStyle);
+ const liveCss = liveStyles.map((el) => el.textContent || "");
+ const { styles, faces } = options?.sceneParts
+ ? hoistFontFaceRules(liveCss)
+ : { styles: dedupeFontFaceRules(liveCss), faces: [] };
+ liveStyles.forEach((el, i) => {
+ el.textContent = styles[i] ?? "";
+ });
+ if (faces.length > 0) {
+ const holder = document.createElement("style");
+ holder.setAttribute(SCENE_FONTS_ATTR, "");
+ holder.textContent = faces.join("\n");
+ document.head.prepend(holder);
}
for (const styleEl of document.querySelectorAll("style")) {
styleEl.textContent = rewriteCssUrlsWithInlinedAssets(
diff --git a/packages/core/src/compiler/scenePartsManifest.test.ts b/packages/core/src/compiler/scenePartsManifest.test.ts
index caa9f48d56..6828a067ae 100644
--- a/packages/core/src/compiler/scenePartsManifest.test.ts
+++ b/packages/core/src/compiler/scenePartsManifest.test.ts
@@ -87,4 +87,23 @@ describe("addScenePartsManifest", () => {
expect(ba.scenes).toEqual(ab.scenes);
expect(ba.shared).not.toBe(ab.shared);
});
+
+ it("leaves the shared fonts style out of the shared hash, so a scene that brings a font still swaps", () => {
+ const withFonts = (faces: string) =>
+ doc("one", "<h1>t</h1>").replace(
+ "<head>",
+ `<head><style data-hf-scene-fonts>${faces}</style>`,
+ );
+ const one = manifestOf(
+ addScenePartsManifest(withFonts('@font-face{font-family:"A";src:url(a.woff2)}')),
+ );
+ const two = manifestOf(
+ addScenePartsManifest(
+ withFonts(
+ '@font-face{font-family:"A";src:url(a.woff2)}\n@font-face{font-family:"B";src:url(b.woff2)}',
+ ),
+ ),
+ );
+ expect(two.shared).toBe(one.shared);
+ });
});
diff --git a/packages/core/src/compiler/scenePartsManifest.ts b/packages/core/src/compiler/scenePartsManifest.ts
index 52a9b818ad..4e94bfd1b1 100644
--- a/packages/core/src/compiler/scenePartsManifest.ts
+++ b/packages/core/src/compiler/scenePartsManifest.ts
@@ -1,5 +1,10 @@
import { createHash } from "node:crypto";
-import { SCENE_PART_ATTR, SCENE_PARTS_META, type SceneParts } from "../sceneParts";
+import {
+ SCENE_FONTS_ATTR,
+ SCENE_PART_ATTR,
+ SCENE_PARTS_META,
+ type SceneParts,
+} from "../sceneParts";
import { injectTagsAtHeadStart, parseHTMLContent } from "./htmlDocument";
const hash = (text: string) => createHash("sha1").update(text).digest("hex").slice(0, 16);
@@ -20,7 +25,10 @@ export function addScenePartsManifest(html: string, ignore: readonly string[] =
// A marker keeps each part's place in `shared`, so moving or reordering a scene changes it.
for (const el of parts)
el.replaceWith(doc.createComment(`hf-scene:${el.getAttribute(SCENE_PART_ATTR)}`));
- for (const el of ignore.flatMap((sel) => [...doc.querySelectorAll(sel)])) el.remove();
+ for (const el of [...ignore, `style[${SCENE_FONTS_ATTR}]`].flatMap((sel) => [
+ ...doc.querySelectorAll(sel),
+ ]))
+ el.remove();
const manifest: SceneParts = {
shared: hash(doc.toString()),
scenes: Object.fromEntries([...byScene].map(([scene, html]) => [scene, hash(html.join("\n"))])),
diff --git a/packages/core/src/runtime/init.swapScenes.test.ts b/packages/core/src/runtime/init.swapScenes.test.ts
index c8191865e7..804cd93f66 100644
--- a/packages/core/src/runtime/init.swapScenes.test.ts
+++ b/packages/core/src/runtime/init.swapScenes.test.ts
@@ -244,6 +244,30 @@ describe("__hfSwapScenes", () => {
expect(JSON.parse(meta).scenes.a).toBe("ha2");
});
+ it("adds only the fonts a swapped scene brings, leaving the loaded ones' style as it was", async () => {
+ const faceA = '@font-face{font-family:"A";src:url(a.woff2)}';
+ const faceB = '@font-face{font-family:"B";src:url(b.woff2)}';
+ boot(
+ [A1, B],
+ trackingRoot().root,
+ (head) => `<style data-hf-scene-fonts>${faceA}</style>${head}`,
+ );
+ await tick();
+ const loaded = document.querySelector("style[data-hf-scene-fonts]")!;
+
+ const next = preview([A2, B]).html.replace(
+ "<head>",
+ `<head><style data-hf-scene-fonts>${faceA}\n${faceB}</style>`,
+ );
+ await window.__hfSwapScenes!(next);
+
+ expect(sceneHost("a").textContent).toBe("A two");
+ const holders = [...document.querySelectorAll("style[data-hf-scene-fonts]")];
+ expect(holders[0]).toBe(loaded);
+ expect(loaded.textContent).toBe(faceA);
+ expect(holders.map((el) => el.textContent)).toEqual([faceA, faceB]);
+ });
+
it("runs the swapped scene's script only once web fonts are ready", async () => {
const { root } = trackingRoot();
boot([A1, B], root);
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index 2ad3ff3c62..c6c8d1a839 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -103,9 +103,11 @@ import {
fetchCaptionOverrides,
} from "./captionOverrides";
import {
+ SCENE_FONTS_ATTR,
SCENE_NO_SWAP_ATTR,
SCENE_PART_ATTR,
SCENE_PARTS_META,
+ fontFaceBlocks,
type SceneParts,
} from "../sceneParts";
import {
@@ -3717,6 +3719,24 @@ export function initSandboxRuntimeModular(): void {
}
}
};
+ // Only the rules not here yet: rewriting a loaded rule's style would load its font again.
+ const addNewFontFaces = (next: Document) => {
+ const holders = (doc: Document) =>
+ Array.from(doc.querySelectorAll(`style[${SCENE_FONTS_ATTR}]`));
+ const live = holders(document);
+ const have = new Set(live.flatMap((el) => fontFaceBlocks(el.textContent ?? "")));
+ const added = new Set(
+ holders(next)
+ .flatMap((el) => fontFaceBlocks(el.textContent ?? ""))
+ .filter((face) => !have.has(face)),
+ );
+ if (added.size === 0) return;
+ const style = document.createElement("style");
+ style.setAttribute(SCENE_FONTS_ATTR, "");
+ style.textContent = [...added].join("\n");
+ if (live.length > 0) live.at(-1)!.after(style);
+ else document.head.prepend(style);
+ };
// Swap edited scenes in place from a rebuilt preview document. Refuses before changing anything unless
// the documents differ only inside existing scenes; a later failure is left to the caller's reload.
const swapScenes = async (html: string, signal?: AbortSignal): Promise<void> => {
@@ -3883,6 +3903,7 @@ export function initSandboxRuntimeModular(): void {
swappedHosts.push(host);
if (host.querySelector(".caption-group")) captionHosts.push(host);
}
+ addNewFontFaces(next);
// Run once every host is replaced, so no new script binds to a scene still to be swapped.
refreshSvgSelectorAliases();
const sceneScripts = swaps.flatMap(({ newParts }) =>
diff --git a/packages/core/src/sceneParts.ts b/packages/core/src/sceneParts.ts
index a748bd651d..0ccadf23f4 100644
--- a/packages/core/src/sceneParts.ts
+++ b/packages/core/src/sceneParts.ts
@@ -2,6 +2,11 @@ export const SCENE_PART_ATTR = "data-hf-scene";
export const SCENE_PARTS_META = "hf-scene-parts";
+export const SCENE_FONTS_ATTR = "data-hf-scene-fonts";
+
+export const fontFaceBlocks = (css: string): string[] =>
+ css.match(/@font-face\s*\{[^}]*\}/gi) ?? [];
+
/** On a scene's top-level host: why the scene cannot be swapped in place, so edits to it reload. */
export const SCENE_NO_SWAP_ATTR = "data-hf-scene-no-swap";