Skip to content

Commit 5df0bea

Browse files
perf(core): a bundled film inlines each shared font once instead of once per composition (#4643)
* perf(core): a bundled film inlines each font once instead of once per composition * fix(core): font dedupe keeps the last copy, so the rule the browser uses never changes * fix(core): font dedupe merges only exact copies, from styles that always apply A style postcss cannot parse ships as authored instead of failing the bundle. The key keeps !important and whitespace inside quoted family names. Styles behind a media query, a non-CSS type, <noscript> or <svg> neither lose a copy nor keep one. * perf(core): font dedupe runs before inlining, so bundling is no slower Deduping after inlining made postcss parse every inlined font: a three-scene fixture went from about 40 ms to about 450 ms. The same url text inlines to the same bytes, so deduping first gives the same output. * fix(core): a scene-part bundle keeps each scene's own font copy, so a scene still swaps alone * chore(core): shorten the font dedupe comment * chore(core): trim the font dedupe comments to keep the file's comment share
1 parent 4aa6b16 commit 5df0bea

4 files changed

Lines changed: 237 additions & 0 deletions

File tree

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
22
import { parseHTML } from "linkedom";
33
import {
44
buildVariablesByCompScript,
5+
dedupeFontFaceRules,
56
scopeCssToComposition,
67
wrapInlineScriptWithErrorBoundary,
78
scopedModulePrelude,
@@ -1181,3 +1182,44 @@ describe("wrapInlineScriptWithErrorBoundary — <script> breakout", () => {
11811182
expect(result).toBe("");
11821183
});
11831184
});
1185+
1186+
describe("dedupeFontFaceRules", () => {
1187+
const face = (display: string) =>
1188+
`@font-face { font-family: "Brand"; src: url(data:font/woff2;base64,AA); font-display: ${display}; }`;
1189+
1190+
it("keeps the last copy, so a different rule declared in between never takes over", () => {
1191+
const [first, middle, last] = dedupeFontFaceRules([face("swap"), face("block"), face("swap")]);
1192+
expect(first).not.toContain("@font-face");
1193+
expect(middle).toContain("font-display: block");
1194+
expect(last).toContain("font-display: swap");
1195+
});
1196+
1197+
it("keeps two rules whose repeated src lines come in a different order", () => {
1198+
const a = `@font-face { font-family: "Brand"; src: url(a.woff); src: url(b.woff2); }`;
1199+
const b = `@font-face { font-family: "Brand"; src: url(b.woff2); src: url(a.woff); }`;
1200+
expect(dedupeFontFaceRules([a, b])).toEqual([a, b]);
1201+
});
1202+
1203+
it("leaves unparseable style text as authored and never keeps a copy from it", () => {
1204+
const broken = `${face("swap")} a { color: red`;
1205+
expect(dedupeFontFaceRules([face("swap"), broken])).toEqual([face("swap"), broken]);
1206+
});
1207+
1208+
it("keeps an !important src apart from a plain one", () => {
1209+
const a = `@font-face { font-family: "Brand"; src: url(a.woff2) !important; }`;
1210+
const b = `@font-face { font-family: "Brand"; src: url(a.woff2); }`;
1211+
expect(dedupeFontFaceRules([a, b])).toEqual([a, b]);
1212+
});
1213+
1214+
it("keeps quoted family names that differ only in inner spaces", () => {
1215+
const a = `@font-face { font-family: "Brand Sans"; src: url(a.woff2); }`;
1216+
const b = `@font-face { font-family: "Brand Sans"; src: url(a.woff2); }`;
1217+
expect(dedupeFontFaceRules([a, b])).toEqual([a, b]);
1218+
});
1219+
1220+
it("treats a src list wrapped over lines as the same rule", () => {
1221+
const a = `@font-face { font-family: "Brand"; src: url(a.woff2),\n url(b.woff); }`;
1222+
const b = `@font-face { font-family: "Brand"; src: url(a.woff2), url(b.woff); }`;
1223+
expect(dedupeFontFaceRules([a, b])[0]).not.toContain("@font-face");
1224+
});
1225+
});

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

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,55 @@ export function scopeCssToComposition(
256256
return root.toResult({ map: false }).css;
257257
}
258258

259+
function isFontFaceAtRule(node: { type: string; name?: string }): node is AtRule {
260+
return node.type === "atrule" && (node as AtRule).name.toLowerCase() === "font-face";
261+
}
262+
263+
function fontFaceKey(atRule: AtRule): string {
264+
const decls: string[] = [];
265+
atRule.walkDecls((decl) => {
266+
// Collapse whitespace outside quoted strings only: "A B" and "A B" name different families.
267+
const value = decl.value.replace(
268+
/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|\s+/g,
269+
(_m, str) => str ?? " ",
270+
);
271+
decls.push(
272+
`${decl.prop.trim().toLowerCase()}:${value.trim()}${decl.important ? "!important" : ""}`,
273+
);
274+
});
275+
return decls.join(";");
276+
}
277+
278+
/** Drops repeats of an identical `@font-face` across the given style texts, keeping the last copy:
279+
* the last matching rule is the one the browser uses, so a rule in between never gains precedence. */
280+
export function dedupeFontFaceRules(styleTexts: string[]): string[] {
281+
const seen = new Set<string>();
282+
return [...styleTexts]
283+
.reverse()
284+
.map((css) => {
285+
if (!css || !/@font-face/i.test(css)) return css;
286+
let root: postcss.Root;
287+
try {
288+
root = postcss.parse(css);
289+
} catch {
290+
return css; // unparseable text ships as authored and takes no part
291+
}
292+
let changed = false;
293+
for (const node of [...(root.nodes ?? [])].reverse()) {
294+
if (!isFontFaceAtRule(node)) continue;
295+
const key = fontFaceKey(node);
296+
if (seen.has(key)) {
297+
node.remove();
298+
changed = true;
299+
} else {
300+
seen.add(key);
301+
}
302+
}
303+
return changed ? root.toResult({ map: false }).css : css;
304+
})
305+
.reverse();
306+
}
307+
259308
/**
260309
* Serialize a value as a JS literal safe to emit inside a `<script>` element.
261310
*

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

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1545,6 +1545,110 @@ describe("bundleToSingleHtml", () => {
15451545
expect(bundled).not.toContain("data:font/woff2");
15461546
});
15471547

1548+
it("inlines a font shared by two compositions once, keeping a rule that differs in weight", async () => {
1549+
const dir = makeTempProject({
1550+
"index.html": `<!doctype html>
1551+
<html><head></head><body>
1552+
<div id="root" data-composition-id="main" data-width="1920" data-height="1080">
1553+
<div
1554+
data-composition-id="hero"
1555+
data-composition-src="compositions/hero.html"
1556+
data-start="0"
1557+
data-duration="2"></div>
1558+
<div
1559+
data-composition-id="outro"
1560+
data-composition-src="compositions/outro.html"
1561+
data-start="2"
1562+
data-duration="2"></div>
1563+
<div
1564+
data-composition-id="bold"
1565+
data-composition-src="compositions/bold.html"
1566+
data-start="4"
1567+
data-duration="2"></div>
1568+
</div>
1569+
<script>window.__timelines={};</script>
1570+
</body></html>`,
1571+
"compositions/hero.html": `<template id="hero-template">
1572+
<div data-composition-id="hero" data-width="1920" data-height="1080">
1573+
<style>
1574+
@font-face {
1575+
font-family: "Brand Sans";
1576+
font-weight: 400;
1577+
font-style: normal;
1578+
src: url("../fonts/brand.woff2") format("woff2");
1579+
}
1580+
</style>
1581+
<p>Hero</p>
1582+
</div>
1583+
</template>`,
1584+
// A separate composition declaring the byte-identical @font-face rule:
1585+
// its bytes must ship once, not once per composition that repeats it.
1586+
"compositions/outro.html": `<template id="outro-template">
1587+
<div data-composition-id="outro" data-width="1920" data-height="1080">
1588+
<style>
1589+
@font-face {
1590+
font-family: "Brand Sans";
1591+
font-weight: 400;
1592+
font-style: normal;
1593+
src: url("../fonts/brand.woff2") format("woff2");
1594+
}
1595+
</style>
1596+
<p>Outro</p>
1597+
</div>
1598+
</template>`,
1599+
// Same family and src, but a different font-weight: a genuinely
1600+
// different rule that must survive dedupe untouched.
1601+
"compositions/bold.html": `<template id="bold-template">
1602+
<div data-composition-id="bold" data-width="1920" data-height="1080">
1603+
<style>
1604+
@font-face {
1605+
font-family: "Brand Sans";
1606+
font-weight: 700;
1607+
font-style: normal;
1608+
src: url("../fonts/brand.woff2") format("woff2");
1609+
}
1610+
</style>
1611+
<p>Bold</p>
1612+
</div>
1613+
</template>`,
1614+
"fonts/brand.woff2": "brand-font-bytes",
1615+
});
1616+
1617+
const bundled = await bundleToSingleHtml(dir);
1618+
const fontFaceRules = bundled.match(/@font-face\s*{[^}]*}/g) ?? [];
1619+
const rulesByWeight = (weight: string) =>
1620+
fontFaceRules.filter((rule) => rule.includes(`font-weight: ${weight};`));
1621+
1622+
expect(fontFaceRules).toHaveLength(2);
1623+
expect(rulesByWeight("400")).toHaveLength(1);
1624+
expect(rulesByWeight("700")).toHaveLength(1);
1625+
expect(bundled.split(inlinedAs("font/woff2", "brand-font-bytes")).length - 1).toBe(2);
1626+
});
1627+
1628+
it.each([
1629+
["a media query", `<style media="print">FACE</style>`],
1630+
["a non-CSS type", `<style type="text/x-template">FACE</style>`],
1631+
["<noscript>", `<noscript><style>FACE</style></noscript>`],
1632+
["<svg>", `<svg><style>FACE</style></svg>`],
1633+
])("keeps a font's always-applied copy when the later copy sits behind %s", async (_, later) => {
1634+
const face = `@font-face { font-family: "Brand"; src: url("fonts/brand.woff2") format("woff2"); }`;
1635+
const dir = makeTempProject({
1636+
"index.html": `<!doctype html>
1637+
<html><head><style>${face}</style></head><body>
1638+
<div id="root" data-composition-id="main" data-width="1920" data-height="1080">
1639+
${later.replace("FACE", face)}
1640+
<p>Hi</p>
1641+
</div>
1642+
<script>window.__timelines={};</script>
1643+
</body></html>`,
1644+
"fonts/brand.woff2": "brand-font-bytes",
1645+
});
1646+
1647+
const { document } = parseHTML(await bundleToSingleHtml(dir));
1648+
const headCss = [...document.querySelectorAll("head style")].map((s) => s.textContent).join("");
1649+
expect(headCss).toContain("@font-face");
1650+
});
1651+
15481652
it("leaves an oversized asset relative and warns rather than inlining it", async () => {
15491653
const dir = makeTempProject({
15501654
"index.html": `<!doctype html>
@@ -2094,6 +2198,30 @@ describe("bundleToSingleHtml sceneParts", () => {
20942198
const partsOf = (doc: Document, scene: string) =>
20952199
[...doc.querySelectorAll(`[data-hf-scene="${scene}"]`)].map((el) => el.tagName.toLowerCase());
20962200

2201+
it("keeps each scene's own copy of a shared @font-face, so one scene still swaps alone", async () => {
2202+
const face = `@font-face { font-family: "Brand"; src: url('assets/fonts/brand.woff2'); }`;
2203+
const dir = makeTempProject({
2204+
"index.html": `<!doctype html>
2205+
<html><head></head><body>
2206+
<div id="root" data-composition-id="main" data-width="1920" data-height="1080" data-duration="4">
2207+
<div data-composition-id="a" data-composition-src="compositions/a.html" data-start="0" data-duration="2"></div>
2208+
<div data-composition-id="b" data-composition-src="compositions/b.html" data-start="2" data-duration="2"></div>
2209+
</div>
2210+
</body></html>`,
2211+
"compositions/a.html": `<template id="a-template"><div data-composition-id="a"><style>${face}</style><p>A</p></div></template>`,
2212+
"compositions/b.html": `<template id="b-template"><div data-composition-id="b"><style>${face}</style><p>B</p></div></template>`,
2213+
});
2214+
const doc = parseHTML(
2215+
await bundleToSingleHtml(dir, { sceneParts: true, inlineAssets: false }),
2216+
).document;
2217+
for (const scene of ["a", "b"]) {
2218+
const css = [...doc.querySelectorAll(`style[data-hf-scene="${scene}"]`)]
2219+
.map((el) => el.textContent ?? "")
2220+
.join("\n");
2221+
expect(css).toContain("@font-face");
2222+
}
2223+
});
2224+
20972225
it("tags each top-level scene's host, styles and scripts, with nested scenes in their parent's parts", async () => {
20982226
const doc = parseHTML(await bundleToSingleHtml(film(), { sceneParts: true })).document;
20992227
// The nested scene is reached after b, so a's parts come in two runs around b's.

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
// rewriteSubCompPaths functions are used by inlineSubCompositions (shared module)
2727
import {
2828
buildVariablesByCompScript,
29+
dedupeFontFaceRules,
2930
scopeCssToComposition,
3031
wrapInlineScriptWithErrorBoundary,
3132
wrapScopedCompositionScript,
@@ -702,6 +703,15 @@ function placeSceneStylesLikeRender(document: Document): void {
702703
first.before(holder);
703704
}
704705

706+
function isAlwaysAppliedStyle(el: Element): boolean {
707+
const type = el.getAttribute("type")?.trim().toLowerCase();
708+
return (
709+
!el.hasAttribute("media") &&
710+
(!type || type === "text/css") &&
711+
!el.closest("template, noscript, svg")
712+
);
713+
}
714+
705715
type PartRun<T> = { scene?: string; chunks: T[] };
706716

707717
function pushRun<T>(runs: PartRun<T>[], scene: string | undefined, chunk: T): void {
@@ -1317,6 +1327,14 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
13171327
if (srcset)
13181328
el.setAttribute("srcset", rewriteSrcsetWithInlinedAssets(srcset, projectDir, inlineAssets));
13191329
}
1330+
// Before inlining, so postcss reads paths not font bytes; scene parts keep copies to swap alone.
1331+
if (!options?.sceneParts) {
1332+
const liveStyles = [...document.querySelectorAll("style")].filter(isAlwaysAppliedStyle);
1333+
const dedupedStyles = dedupeFontFaceRules(liveStyles.map((el) => el.textContent || ""));
1334+
liveStyles.forEach((el, i) => {
1335+
el.textContent = dedupedStyles[i] ?? "";
1336+
});
1337+
}
13201338
for (const styleEl of document.querySelectorAll("style")) {
13211339
styleEl.textContent = rewriteCssUrlsWithInlinedAssets(
13221340
styleEl.textContent || "",

0 commit comments

Comments
 (0)