Skip to content

Commit 8066772

Browse files
perf(core): a preview loads each web font once, not once per scene (#5806)
* perf(core): a preview loads each web font once, not once per scene * test(core): count the bundle's font rules in its styles, not in the inlined runtime
1 parent 7735338 commit 8066772

8 files changed

Lines changed: 116 additions & 17 deletions

File tree

‎packages/core/src/compiler/compositionScoping.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,14 @@ function fontFaceKey(atRule: AtRule): string {
219219

220220
/** Drops repeats of an identical `@font-face` across the given style texts, keeping the last copy:
221221
* the last matching rule is the one the browser uses, so a rule in between never gains precedence. */
222-
export function dedupeFontFaceRules(styleTexts: string[]): string[] {
222+
export const dedupeFontFaceRules = (styleTexts: string[]): string[] => dropFontFaces(styleTexts);
223+
224+
export function hoistFontFaceRules(styleTexts: string[]): { styles: string[]; faces: string[] } {
225+
const faces: string[] = [];
226+
return { styles: dropFontFaces(styleTexts, faces), faces };
227+
}
228+
229+
function dropFontFaces(styleTexts: string[], hoisted?: string[]): string[] {
223230
const seen = new Set<string>();
224231
return [...styleTexts]
225232
.reverse()
@@ -235,12 +242,13 @@ export function dedupeFontFaceRules(styleTexts: string[]): string[] {
235242
for (const node of [...(root.nodes ?? [])].reverse()) {
236243
if (!isFontFaceAtRule(node)) continue;
237244
const key = fontFaceKey(node);
238-
if (seen.has(key)) {
239-
node.remove();
240-
changed = true;
241-
} else {
245+
if (!seen.has(key)) {
242246
seen.add(key);
247+
if (!hoisted) continue;
248+
hoisted.unshift(node.toString());
243249
}
250+
node.remove();
251+
changed = true;
244252
}
245253
return changed ? root.toResult({ map: false }).css : css;
246254
})

‎packages/core/src/compiler/htmlBundler.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3182,7 +3182,7 @@ describe("bundleToSingleHtml sceneParts", () => {
31823182
const partsOf = (doc: Document, scene: string) =>
31833183
[...doc.querySelectorAll(`[data-hf-scene="${scene}"]`)].map((el) => el.tagName.toLowerCase());
31843184

3185-
it("keeps each scene's own copy of a shared @font-face, so one scene still swaps alone", async () => {
3185+
it("puts a @font-face two scenes share in one style outside the scenes, once", async () => {
31863186
const face = `@font-face { font-family: "Brand"; src: url('assets/fonts/brand.woff2'); }`;
31873187
const dir = makeTempProject({
31883188
"index.html": `<!doctype html>
@@ -3202,8 +3202,14 @@ describe("bundleToSingleHtml sceneParts", () => {
32023202
const css = [...doc.querySelectorAll(`style[data-hf-scene="${scene}"]`)]
32033203
.map((el) => el.textContent ?? "")
32043204
.join("\n");
3205-
expect(css).toContain("@font-face");
3205+
expect(css).not.toContain("@font-face");
32063206
}
3207+
const fonts = doc.querySelector("style[data-hf-scene-fonts]");
3208+
expect(fonts?.hasAttribute("data-hf-scene")).toBe(false);
3209+
const faces = (css: string) => css.match(/@font-face/g)?.length ?? 0;
3210+
expect(faces(fonts?.textContent ?? "")).toBe(1);
3211+
const allCss = [...doc.querySelectorAll("style")].map((el) => el.textContent ?? "").join("\n");
3212+
expect(faces(allCss)).toBe(1);
32073213
});
32083214

32093215
it("tags each top-level scene's host, styles and scripts, with nested scenes in their parent's parts", async () => {

‎packages/core/src/compiler/htmlBundler.ts‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616
isJavaScriptType,
1717
planCompositionAssembly,
1818
} from "./compositionAssembly";
19-
import { SCENE_PART_ATTR } from "../sceneParts";
19+
import { SCENE_FONTS_ATTR, SCENE_PART_ATTR } from "../sceneParts";
2020
import {
2121
ensureExternalScriptTag,
2222
readExternalScriptAttributes,
@@ -54,6 +54,7 @@ import {
5454
import {
5555
buildVariablesByCompScript,
5656
dedupeFontFaceRules,
57+
hoistFontFaceRules,
5758
scopeCssToComposition,
5859
wrapInlineScriptWithErrorBoundary,
5960
scopedModulePrelude,
@@ -1406,13 +1407,20 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
14061407
if (srcset)
14071408
el.setAttribute("srcset", rewriteSrcsetWithInlinedAssets(srcset, projectDir, inlineAssets));
14081409
}
1409-
// Before inlining, so postcss reads paths not font bytes; scene parts keep copies to swap alone.
1410-
if (!options?.sceneParts) {
1411-
const liveStyles = [...document.querySelectorAll("style")].filter(isAlwaysAppliedStyle);
1412-
const dedupedStyles = dedupeFontFaceRules(liveStyles.map((el) => el.textContent || ""));
1413-
liveStyles.forEach((el, i) => {
1414-
el.textContent = dedupedStyles[i] ?? "";
1415-
});
1410+
// Before inlining, so postcss reads paths not font bytes.
1411+
const liveStyles = [...document.querySelectorAll("style")].filter(isAlwaysAppliedStyle);
1412+
const liveCss = liveStyles.map((el) => el.textContent || "");
1413+
const { styles, faces } = options?.sceneParts
1414+
? hoistFontFaceRules(liveCss)
1415+
: { styles: dedupeFontFaceRules(liveCss), faces: [] };
1416+
liveStyles.forEach((el, i) => {
1417+
el.textContent = styles[i] ?? "";
1418+
});
1419+
if (faces.length > 0) {
1420+
const holder = document.createElement("style");
1421+
holder.setAttribute(SCENE_FONTS_ATTR, "");
1422+
holder.textContent = faces.join("\n");
1423+
document.head.prepend(holder);
14161424
}
14171425
for (const styleEl of document.querySelectorAll("style")) {
14181426
styleEl.textContent = rewriteCssUrlsWithInlinedAssets(

‎packages/core/src/compiler/scenePartsManifest.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,4 +87,23 @@ describe("addScenePartsManifest", () => {
8787
expect(ba.scenes).toEqual(ab.scenes);
8888
expect(ba.shared).not.toBe(ab.shared);
8989
});
90+
91+
it("leaves the shared fonts style out of the shared hash, so a scene that brings a font still swaps", () => {
92+
const withFonts = (faces: string) =>
93+
doc("one", "<h1>t</h1>").replace(
94+
"<head>",
95+
`<head><style data-hf-scene-fonts>${faces}</style>`,
96+
);
97+
const one = manifestOf(
98+
addScenePartsManifest(withFonts('@font-face{font-family:"A";src:url(a.woff2)}')),
99+
);
100+
const two = manifestOf(
101+
addScenePartsManifest(
102+
withFonts(
103+
'@font-face{font-family:"A";src:url(a.woff2)}\n@font-face{font-family:"B";src:url(b.woff2)}',
104+
),
105+
),
106+
);
107+
expect(two.shared).toBe(one.shared);
108+
});
90109
});

‎packages/core/src/compiler/scenePartsManifest.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { createHash } from "node:crypto";
2-
import { SCENE_PART_ATTR, SCENE_PARTS_META, type SceneParts } from "../sceneParts";
2+
import {
3+
SCENE_FONTS_ATTR,
4+
SCENE_PART_ATTR,
5+
SCENE_PARTS_META,
6+
type SceneParts,
7+
} from "../sceneParts";
38
import { injectTagsAtHeadStart, parseHTMLContent } from "./htmlDocument";
49

510
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[] =
2025
// A marker keeps each part's place in `shared`, so moving or reordering a scene changes it.
2126
for (const el of parts)
2227
el.replaceWith(doc.createComment(`hf-scene:${el.getAttribute(SCENE_PART_ATTR)}`));
23-
for (const el of ignore.flatMap((sel) => [...doc.querySelectorAll(sel)])) el.remove();
28+
for (const el of [...ignore, `style[${SCENE_FONTS_ATTR}]`].flatMap((sel) => [
29+
...doc.querySelectorAll(sel),
30+
]))
31+
el.remove();
2432
const manifest: SceneParts = {
2533
shared: hash(doc.toString()),
2634
scenes: Object.fromEntries([...byScene].map(([scene, html]) => [scene, hash(html.join("\n"))])),

‎packages/core/src/runtime/init.swapScenes.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,30 @@ describe("__hfSwapScenes", () => {
244244
expect(JSON.parse(meta).scenes.a).toBe("ha2");
245245
});
246246

247+
it("adds only the fonts a swapped scene brings, leaving the loaded ones' style as it was", async () => {
248+
const faceA = '@font-face{font-family:"A";src:url(a.woff2)}';
249+
const faceB = '@font-face{font-family:"B";src:url(b.woff2)}';
250+
boot(
251+
[A1, B],
252+
trackingRoot().root,
253+
(head) => `<style data-hf-scene-fonts>${faceA}</style>${head}`,
254+
);
255+
await tick();
256+
const loaded = document.querySelector("style[data-hf-scene-fonts]")!;
257+
258+
const next = preview([A2, B]).html.replace(
259+
"<head>",
260+
`<head><style data-hf-scene-fonts>${faceA}\n${faceB}</style>`,
261+
);
262+
await window.__hfSwapScenes!(next);
263+
264+
expect(sceneHost("a").textContent).toBe("A two");
265+
const holders = [...document.querySelectorAll("style[data-hf-scene-fonts]")];
266+
expect(holders[0]).toBe(loaded);
267+
expect(loaded.textContent).toBe(faceA);
268+
expect(holders.map((el) => el.textContent)).toEqual([faceA, faceB]);
269+
});
270+
247271
it("runs the swapped scene's script only once web fonts are ready", async () => {
248272
const { root } = trackingRoot();
249273
boot([A1, B], root);

‎packages/core/src/runtime/init.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,11 @@ import {
103103
fetchCaptionOverrides,
104104
} from "./captionOverrides";
105105
import {
106+
SCENE_FONTS_ATTR,
106107
SCENE_NO_SWAP_ATTR,
107108
SCENE_PART_ATTR,
108109
SCENE_PARTS_META,
110+
fontFaceBlocks,
109111
type SceneParts,
110112
} from "../sceneParts";
111113
import {
@@ -3717,6 +3719,24 @@ export function initSandboxRuntimeModular(): void {
37173719
}
37183720
}
37193721
};
3722+
// Only the rules not here yet: rewriting a loaded rule's style would load its font again.
3723+
const addNewFontFaces = (next: Document) => {
3724+
const holders = (doc: Document) =>
3725+
Array.from(doc.querySelectorAll(`style[${SCENE_FONTS_ATTR}]`));
3726+
const live = holders(document);
3727+
const have = new Set(live.flatMap((el) => fontFaceBlocks(el.textContent ?? "")));
3728+
const added = new Set(
3729+
holders(next)
3730+
.flatMap((el) => fontFaceBlocks(el.textContent ?? ""))
3731+
.filter((face) => !have.has(face)),
3732+
);
3733+
if (added.size === 0) return;
3734+
const style = document.createElement("style");
3735+
style.setAttribute(SCENE_FONTS_ATTR, "");
3736+
style.textContent = [...added].join("\n");
3737+
if (live.length > 0) live.at(-1)!.after(style);
3738+
else document.head.prepend(style);
3739+
};
37203740
// Swap edited scenes in place from a rebuilt preview document. Refuses before changing anything unless
37213741
// the documents differ only inside existing scenes; a later failure is left to the caller's reload.
37223742
const swapScenes = async (html: string, signal?: AbortSignal): Promise<void> => {
@@ -3883,6 +3903,7 @@ export function initSandboxRuntimeModular(): void {
38833903
swappedHosts.push(host);
38843904
if (host.querySelector(".caption-group")) captionHosts.push(host);
38853905
}
3906+
addNewFontFaces(next);
38863907
// Run once every host is replaced, so no new script binds to a scene still to be swapped.
38873908
refreshSvgSelectorAliases();
38883909
const sceneScripts = swaps.flatMap(({ newParts }) =>

‎packages/core/src/sceneParts.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@ export const SCENE_PART_ATTR = "data-hf-scene";
22

33
export const SCENE_PARTS_META = "hf-scene-parts";
44

5+
export const SCENE_FONTS_ATTR = "data-hf-scene-fonts";
6+
7+
export const fontFaceBlocks = (css: string): string[] =>
8+
css.match(/@font-face\s*\{[^}]*\}/gi) ?? [];
9+
510
/** On a scene's top-level host: why the scene cannot be swapped in place, so edits to it reload. */
611
export const SCENE_NO_SWAP_ATTR = "data-hf-scene-no-swap";
712

0 commit comments

Comments
 (0)