Skip to content

Write HTML. Render video. Built for agents.

fix(core): bundling and rendering keep print-only, titled and non-CSS styles conditional (#4664)

Miguel Ángelc5a69727ffdd
diff --git a/packages/core/src/compiler/htmlBundler.test.ts b/packages/core/src/compiler/htmlBundler.test.ts
index 6eb1f059d2..5d3e9d28e0 100644
--- a/packages/core/src/compiler/htmlBundler.test.ts
+++ b/packages/core/src/compiler/htmlBundler.test.ts
@@ -1356,6 +1356,336 @@ describe("bundleToSingleHtml", () => {
expect(styleText(bundled)).not.toContain("@import");
});
+ describe("head style coalescing", () => {
+ async function bundledHeadStyles(head: string, files: Record<string, string> = {}) {
+ const dir = makeTempProject({
+ ...files,
+ "index.html": `<!doctype html>
+<html><head>${head}</head><body>
+ <div data-composition-id="root" data-width="320" data-height="180"></div>
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
+</body></html>`,
+ });
+ const { document } = parseHTML(await bundleToSingleHtml(dir));
+ return [
+ ...document.querySelectorAll("head style:not([data-hyperframes-text-rendering])"),
+ ].map((el) => ({
+ media: el.getAttribute("media"),
+ type: el.getAttribute("type"),
+ css: el.textContent,
+ ...(el.hasAttribute("title") && { title: el.getAttribute("title") }),
+ }));
+ }
+
+ it("does not merge a non-CSS style into CSS", async () => {
+ expect(
+ await bundledHeadStyles(
+ `<style>p{color:red}</style><style type="text/x-tpl">{{ a }}</style>`,
+ ),
+ ).toEqual([
+ { media: null, type: null, css: "p{color:red}" },
+ { media: null, type: "text/x-tpl", css: "{{ a }}" },
+ ]);
+ });
+
+ it("still merges styles the browser applies under the same condition", async () => {
+ expect(
+ await bundledHeadStyles(
+ `<style>a{color:red}</style><style type="text/css">b{color:red}</style>` +
+ `<style media="all">i{color:red}</style><style type="TEXT/CSS">u{color:red}</style>` +
+ `<style media=" ALL ">s{color:red}</style>` +
+ `<style media="print">a{color:blue}</style><style media="print">b{color:blue}</style>`,
+ ),
+ ).toEqual([
+ {
+ media: null,
+ type: null,
+ css: "a{color:red}\n\nb{color:red}\n\ni{color:red}\n\nu{color:red}\n\ns{color:red}",
+ },
+ { media: "print", type: null, css: "a{color:blue}\n\nb{color:blue}" },
+ ]);
+ });
+
+ it("inlines each linked sheet at its link's place with the link's media", async () => {
+ expect(
+ await bundledHeadStyles(
+ `<style>p{color:red}</style><link rel="stylesheet" href="print.css" media="print">` +
+ `<style>p{color:green}</style><link rel="stylesheet" href="late.css">`,
+ { "print.css": "p{color:blue}", "late.css": "p{color:black}" },
+ ),
+ ).toEqual([
+ { media: null, type: null, css: "p{color:red}" },
+ { media: "print", type: null, css: "p{color:blue}" },
+ { media: null, type: null, css: "p{color:green}\n\np{color:black}" },
+ ]);
+ });
+
+ it("does not inline a linked sheet of a non-CSS type as CSS", async () => {
+ expect(
+ await bundledHeadStyles(`<link rel="stylesheet" type="text/x-scss" href="a.scss">`, {
+ "a.scss": "p{color:blue}",
+ }),
+ ).toEqual([]);
+ });
+
+ it("does not inline a disabled linked sheet", async () => {
+ expect(
+ await bundledHeadStyles(`<link rel="stylesheet" href="a.css" disabled>`, {
+ "a.css": "p{color:blue}",
+ }),
+ ).toEqual([]);
+ });
+
+ it("merges a titled style only with styles of the same title", async () => {
+ expect(
+ await bundledHeadStyles(
+ `<style>a{color:red}</style><style title="t">b{color:red}</style><style title="t">i{color:red}</style>` +
+ `<style title="T">u{color:red}</style><style title="">s{color:red}</style><style>q{color:red}</style>` +
+ `<link rel="stylesheet" href="alt.css" title="u">`,
+ { "alt.css": "p{color:blue}" },
+ ),
+ ).toEqual([
+ { media: null, type: null, css: "a{color:red}" },
+ { media: null, type: null, css: "b{color:red}\n\ni{color:red}", title: "t" },
+ { media: null, type: null, css: "u{color:red}", title: "T" },
+ { media: null, type: null, css: "s{color:red}\n\nq{color:red}", title: "" },
+ { media: null, type: null, css: "p{color:blue}", title: "u" },
+ ]);
+ });
+
+ it("keeps a composition's print style print-only and its non-CSS style out of CSS", async () => {
+ const comp = (
+ id: string,
+ ) => `<div data-composition-id="${id}" data-width="320" data-height="180">
+ <style media="print">.${id}-p{color:blue}</style><style type="text/x-tpl">.${id}-t{color:red}</style>
+ <p class="${id}-p">x</p></div>`;
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><head></head><body>
+ <div data-composition-id="root" data-width="320" data-height="180">
+ <div data-composition-id="file" data-composition-src="file.html"></div>
+ <div data-composition-id="inline"></div>
+ </div>
+ <template id="inline-template">${comp("inline")}</template>
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
+</body></html>`,
+ "file.html": `<template id="file-template">${comp("file")}</template>`,
+ });
+ const { document } = parseHTML(await bundleToSingleHtml(dir));
+ const css = (selector: string) =>
+ [...document.querySelectorAll(selector)].map((el) => el.textContent).join("\n");
+ for (const id of ["file", "inline"]) {
+ expect(css('style[media="print"]')).toContain(`.${id}-p{color:blue}`);
+ expect(css("style:not([media]):not([type])")).not.toContain(`.${id}-p{`);
+ expect(css("style:not([type])")).not.toContain(`.${id}-t{`);
+ }
+ });
+
+ it("keeps rule order across a conditional style", async () => {
+ expect(
+ await bundledHeadStyles(
+ `<style>p{color:red}</style><style media="print">p{color:blue}</style><style>p{color:green}</style>`,
+ ),
+ ).toEqual([
+ { media: null, type: null, css: "p{color:red}" },
+ { media: "print", type: null, css: "p{color:blue}" },
+ { media: null, type: null, css: "p{color:green}" },
+ ]);
+ });
+
+ it("inlines a linked sheet whose type carries a charset, but not a style with that type", async () => {
+ expect(
+ await bundledHeadStyles(
+ `<link rel="stylesheet" type="text/css; charset=utf-8" href="a.css">` +
+ `<style type="text/css; charset=utf-8">p{color:red}</style>`,
+ { "a.css": "p{color:blue}" },
+ ),
+ ).toEqual([
+ { media: null, type: null, css: "p{color:blue}" },
+ { media: null, type: "text/css; charset=utf-8", css: "p{color:red}" },
+ ]);
+ });
+
+ it("keeps the untitled copy of a @font-face that a later alternate style repeats", async () => {
+ const face = `@font-face{font-family:"PF";src:url(https://cdn.example/f.woff2)}`;
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><head><style>${face}.t{font-family:"PF"}</style><style title="main">.x{}</style>
+<style title="alt">${face}</style></head><body>
+ <div data-composition-id="root" data-width="320" data-height="180"></div>
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
+</body></html>`,
+ });
+ const { document } = parseHTML(await bundleToSingleHtml(dir));
+ const untitled = [...document.querySelectorAll("head style:not([title])")];
+ expect(untitled.map((el) => el.textContent).join("")).toContain("@font-face");
+ });
+
+ it("keeps a root-less template's non-CSS style out of CSS", async () => {
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><head></head><body>
+ <div data-composition-id="root" data-width="320" data-height="180">
+ <div data-composition-id="bare"></div>
+ </div>
+ <template id="bare-template"><style type="text/x-tpl">.bare-t{color:red}</style><p>x</p></template>
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
+</body></html>`,
+ });
+ const { document } = parseHTML(await bundleToSingleHtml(dir));
+ const css = [...document.querySelectorAll("style:not([type])")].map((el) => el.textContent);
+ expect(css.join("\n")).not.toContain(".bare-t{");
+ });
+ });
+
+ describe("composition links to the same file", () => {
+ async function sharedLinks(aLink: string, bLink: string, rootHead = "", rootBody = "") {
+ const comp = (id: string, link: string) =>
+ `<template id="${id}-template"><div data-composition-id="${id}" data-width="320" data-height="180">${link}<p class="${id}">x</p></div></template>`;
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><head>${rootHead}</head><body>${rootBody}
+ <div data-composition-id="root" data-width="320" data-height="180">
+ <div data-composition-id="a" data-composition-src="a.html"></div>
+ <div data-composition-id="b" data-composition-src="b.html"></div>
+ </div>
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
+</body></html>`,
+ "a.html": comp("a", aLink.replace("HREF", "shared.css")),
+ "b.html": comp("b", bLink.replace("HREF", "shared.css")),
+ "shared.css": ".a,.b{color:green}",
+ });
+ const { document } = parseHTML(await bundleToSingleHtml(dir));
+ return [...document.querySelectorAll("link[href]")].map((el) =>
+ Object.fromEntries([...el.attributes].map((attr) => [attr.name, attr.value])),
+ );
+ }
+ const link = (attrs = "") => `<link rel="stylesheet" href="HREF"${attrs}>`;
+ const plain = { href: "shared.css", rel: "stylesheet" };
+ const print = { ...plain, media: "print" };
+
+ it.each([
+ ["a plain link after a print one", link(' media="print"'), link(), [print, plain]],
+ [
+ "a plain link after a titled one",
+ link(' title="alt"'),
+ link(),
+ [{ ...plain, title: "alt" }, plain],
+ ],
+ ["a print link after a plain one", link(), link(' media="print"'), [plain, print]],
+ [
+ "a screen link after a print one",
+ link(' media="print"'),
+ link(' media="screen"'),
+ [print, { ...plain, media: "screen" }],
+ ],
+ ["two print links", link(' media="print"'), link(' media="print"'), [print]],
+ ["two plain links", link(), link(), [plain]],
+ [
+ "a plain link after a disabled one",
+ link(" disabled"),
+ link(),
+ [{ ...plain, disabled: "" }, plain],
+ ],
+ [
+ "a stylesheet after a preload of the same file",
+ '<link rel="preload" as="style" href="HREF">',
+ link(),
+ [plain, { href: "shared.css", rel: "preload", as: "style" }],
+ ],
+ [
+ "two links of different non-CSS types",
+ link(' type="text/x-scss"'),
+ link(' type="text/x-less"'),
+ [
+ { ...plain, type: "text/x-scss" },
+ { ...plain, type: "text/x-less" },
+ ],
+ ],
+ [
+ "a plain link after a CORS one, as one link",
+ link(" crossorigin"),
+ link(),
+ [{ ...plain, crossorigin: "" }],
+ ],
+ [
+ "two CORS links spelled differently, as one link",
+ link(' crossorigin=""'),
+ link(' crossorigin="anonymous"'),
+ [{ ...plain, crossorigin: "" }],
+ ],
+ ])("keeps %s under its own condition", async (_, aLink, bLink, expected) => {
+ expect(await sharedLinks(aLink, bLink)).toEqual(expected);
+ });
+
+ it("keeps a plain link after an alternate one", async () => {
+ const links = await sharedLinks(
+ `<link rel="alternate stylesheet" title="alt" href="HREF">`,
+ link(),
+ );
+ expect(links).toContainEqual(plain);
+ });
+
+ it("keeps a composition's plain link when the root links the same URL for print", async () => {
+ const url = "https://cdn.example/shared.css";
+ const links = await sharedLinks(
+ link().replace("HREF", url),
+ link(),
+ `<link rel="stylesheet" href="${url}" media="print">`,
+ );
+ expect(links).toEqual([{ ...print, href: url }, { ...plain, href: url }, plain]);
+ });
+
+ it("lets the root's link stand for a composition's that differs only in fetch attributes", async () => {
+ const url = "https://cdn.example/shared.css";
+ const snippet = ' integrity="sha512-x" crossorigin="anonymous" referrerpolicy="no-referrer"';
+ for (const [rootAttrs, compAttrs] of [
+ [' integrity="sha384-x"', ""],
+ [' referrerpolicy="no-referrer"', ""],
+ [" crossorigin", ""],
+ [snippet, snippet],
+ ]) {
+ const rootLink = link(rootAttrs).replace("HREF", url);
+ const links = await sharedLinks(link(compAttrs).replace("HREF", url), "", rootLink);
+ expect(links).toHaveLength(1);
+ }
+ });
+
+ it("keeps a composition's link when the root's same link is in a noscript", async () => {
+ const url = "https://cdn.example/shared.css";
+ expect(
+ await sharedLinks(
+ link().replace("HREF", url),
+ "",
+ "",
+ `<noscript>${link().replace("HREF", url)}</noscript>`,
+ ),
+ ).toEqual([
+ { ...plain, href: url },
+ { ...plain, href: url },
+ ]);
+ });
+
+ it("carries a composition link's type and disabled state", async () => {
+ const dir = makeTempProject({
+ "index.html": `<!doctype html>
+<html><head></head><body>
+ <div data-composition-id="root" data-width="320" data-height="180">
+ <div data-composition-id="a" data-composition-src="a.html"></div>
+ </div>
+ <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>
+</body></html>`,
+ "a.html": `<template id="a-template"><div data-composition-id="a" data-width="320" data-height="180">
+<link rel="stylesheet" href="x.scss" type="text/x-scss"><link rel="stylesheet" href="off.css" disabled><p>x</p></div></template>`,
+ });
+ const { document } = parseHTML(await bundleToSingleHtml(dir));
+ expect(document.querySelector('link[href="x.scss"]')?.getAttribute("type")).toBe(
+ "text/x-scss",
+ );
+ expect(document.querySelector('link[href="off.css"]')?.hasAttribute("disabled")).toBe(true);
+ });
+ });
+
it("preserves @import for absolute URLs", async () => {
const dir = makeTempProject({
"index.html": `<!doctype html>
diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts
index 2fbfa235c9..999577830a 100644
--- a/packages/core/src/compiler/htmlBundler.ts
+++ b/packages/core/src/compiler/htmlBundler.ts
@@ -1,4 +1,12 @@
-import { inlineScriptRuns } from "./scriptRuns";
+import {
+ compositionStyle,
+ cssStyleMergeKey,
+ UNCONDITIONAL_CSS_KEY,
+ headStyleRuns,
+ inlineScriptRuns,
+ styleElementsFor,
+ type CompositionStyle,
+} from "./scriptRuns";
import { SCENE_PART_ATTR } from "../sceneParts";
import {
ensureExternalScriptTag,
@@ -34,7 +42,11 @@ import {
import { validateHyperframeHtmlContract } from "./staticGuard";
import { getHyperframeRuntimeScript } from "../generated/runtime-inline";
import { readDeclaredDefaults } from "../runtime/getVariables";
-import { inlineSubCompositions, refuseSwapsReachedByRootScripts } from "./inlineSubCompositions";
+import {
+ ensureExternalLinkTag,
+ inlineSubCompositions,
+ refuseSwapsReachedByRootScripts,
+} from "./inlineSubCompositions";
import { queryByAttr } from "../utils/cssSelector";
import { isSafePath, resolveWithinProject } from "../safePath.js";
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
@@ -704,12 +716,7 @@ function placeSceneStylesLikeRender(document: Document): void {
}
function isAlwaysAppliedStyle(el: Element): boolean {
- const type = el.getAttribute("type")?.trim().toLowerCase();
- return (
- !el.hasAttribute("media") &&
- (!type || type === "text/css") &&
- !el.closest("template, noscript, svg")
- );
+ return cssStyleMergeKey(el) === UNCONDITIONAL_CSS_KEY && !el.closest("template, noscript, svg");
}
type PartRun<T> = { scene?: string; chunks: T[] };
@@ -722,18 +729,14 @@ function pushRun<T>(runs: PartRun<T>[], scene: string | undefined, chunk: T): vo
function coalesceHeadStylesAndBodyScripts(document: Document): void {
const allHeadStyles = [...document.querySelectorAll("head style")];
- const untaggedRuns: Element[][] = [[]];
- for (const el of allHeadStyles) {
- if (el.hasAttribute(SCENE_PART_ATTR)) untaggedRuns.push([]);
- else untaggedRuns.at(-1)!.push(el);
- }
- for (const run of allHeadStyles.length > 1 ? untaggedRuns : []) {
+ const isScenePart = (el: Element) => el.hasAttribute(SCENE_PART_ATTR);
+ for (const run of allHeadStyles.length > 1 ? headStyleRuns(allHeadStyles, isScenePart) : []) {
const merged = joinCssHoistingImports(run.map((el) => el.textContent || ""));
if (!merged) continue;
run[0]!.textContent = merged;
for (const el of run.slice(1)) el.remove();
}
- if (untaggedRuns.length > 1) placeSceneStylesLikeRender(document);
+ if (allHeadStyles.some(isScenePart)) placeSceneStylesLikeRender(document);
const isPinned = (el: Element) =>
el.hasAttribute(RUNTIME_BOOTSTRAP_ATTR) || el.hasAttribute(SCENE_PART_ATTR);
@@ -996,36 +999,21 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
rebaseEntryAuthoredAssetPaths(document, sourceDir, projectDir);
}
- // Inline local CSS
- const localCssChunks: string[] = [];
- let cssAnchorPlaced = false;
for (const el of [...document.querySelectorAll('link[rel="stylesheet"]')]) {
const href = el.getAttribute("href");
- if (!href || !isRelativeUrl(href)) continue;
+ if (!href || !isRelativeUrl(href) || cssStyleMergeKey(el) === undefined) continue;
+ if (el.hasAttribute("disabled")) continue;
const cssPath = resolveEntryPath(href);
if (!cssPath) continue;
const css = safeReadFile(cssPath);
if (css == null) continue;
- localCssChunks.push(inlineCssFile(css, dirname(cssPath), projectDir));
- if (!cssAnchorPlaced) {
- const anchor = document.createElement("style");
- anchor.setAttribute("data-hf-bundled-local-css", "1");
- el.replaceWith(anchor);
- cssAnchorPlaced = true;
- } else {
- el.remove();
- }
- }
- if (localCssChunks.length > 0) {
- const anchor = document.querySelector('style[data-hf-bundled-local-css="1"]');
- if (anchor) {
- anchor.removeAttribute("data-hf-bundled-local-css");
- anchor.textContent = localCssChunks.join("\n\n");
- } else {
- const style = document.createElement("style");
- style.textContent = localCssChunks.join("\n\n");
- document.head.appendChild(style);
+ const style = document.createElement("style");
+ for (const name of ["media", "title"]) {
+ const value = el.getAttribute(name);
+ if (value !== null) style.setAttribute(name, value);
}
+ style.textContent = inlineCssFile(css, dirname(cssPath), projectDir);
+ el.replaceWith(style);
}
// Read before sub-compositions add theirs: only the root's own scripts can reach into scenes.
@@ -1079,10 +1067,12 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
},
});
refuseSwapsReachedByRootScripts(document, rootScripts);
- const styleRuns: PartRun<string>[] = [];
- subCompResult.styles.forEach((css, i) => pushRun(styleRuns, subCompResult.styleScenes[i], css));
+ const styleRuns: PartRun<CompositionStyle>[] = [];
+ subCompResult.styles.forEach((style, i) =>
+ pushRun(styleRuns, subCompResult.styleScenes[i], style),
+ );
const scriptRuns: PartRun<DeferredScriptChunk>[] = [];
- const compStyleChunks: string[] = [];
+ const compStyleChunks: CompositionStyle[] = [];
const compScriptChunks: DeferredScriptChunk[] = [];
const compExternalLinks = [...subCompResult.externalLinks];
const compVariablesByComp: Record<string, Record<string, unknown>> = {
@@ -1167,13 +1157,17 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
if (innerRoot) {
// Hoist styles into the collected style chunks
for (const styleEl of [...innerRoot.querySelectorAll("style")]) {
+ if (cssStyleMergeKey(styleEl) === undefined) continue;
const css = styleEl.textContent || "";
compStyleChunks.push(
- compId
- ? scopeCssToComposition(css, compId, runtimeScope, authoredRootId, {
- scopeRootSelectors: true,
- })
- : css,
+ compositionStyle(
+ styleEl,
+ compId
+ ? scopeCssToComposition(css, compId, runtimeScope, authoredRootId, {
+ scopeRootSelectors: true,
+ })
+ : css,
+ ),
);
styleEl.remove();
}
@@ -1198,13 +1192,17 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
} else {
// No matching inner root — inject all template content directly
for (const styleEl of [...innerDoc.querySelectorAll("style")]) {
+ if (cssStyleMergeKey(styleEl) === undefined) continue;
const css = styleEl.textContent || "";
compStyleChunks.push(
- compId
- ? scopeCssToComposition(css, compId, runtimeScope, undefined, {
- scopeRootSelectors: true,
- })
- : css,
+ compositionStyle(
+ styleEl,
+ compId
+ ? scopeCssToComposition(css, compId, runtimeScope, undefined, {
+ scopeRootSelectors: true,
+ })
+ : css,
+ ),
);
styleEl.remove();
}
@@ -1264,18 +1262,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
}
}
- // Inject external scripts from sub-compositions (e.g., Lottie CDN)
- // that aren't already present in the main document.
- for (const link of compExternalLinks) {
- const escapedHref = link.href.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
- if (!document.querySelector(`link[href="${escapedHref}"]`)) {
- const linkEl = document.createElement("link");
- linkEl.setAttribute("rel", link.rel);
- linkEl.setAttribute("href", link.href);
- if (link.crossorigin != null) linkEl.setAttribute("crossorigin", link.crossorigin);
- document.head.appendChild(linkEl);
- }
- }
+ for (const link of compExternalLinks) ensureExternalLinkTag(document, link);
for (const css of compStyleChunks) pushRun(styleRuns, undefined, css);
for (const chunk of compScriptChunks) pushRun(scriptRuns, undefined, chunk);
@@ -1285,10 +1272,11 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
else scriptRuns.unshift({ chunks: [variablesByCompScript] });
}
for (const { scene, chunks } of styleRuns) {
- const style = document.createElement("style");
- if (scene) style.setAttribute(SCENE_PART_ATTR, scene);
- style.textContent = scene ? joinCssHoistingImports(chunks) : chunks.join("\n\n");
- document.head.appendChild(style);
+ const join = scene ? joinCssHoistingImports : (css: string[]) => css.join("\n\n");
+ for (const style of styleElementsFor(document, chunks, join)) {
+ if (scene) style.setAttribute(SCENE_PART_ATTR, scene);
+ document.head.appendChild(style);
+ }
}
for (const { scene, chunks } of scriptRuns) {
const script = document.createElement("script");
@@ -1553,7 +1541,7 @@ function pushSubCompVariableStyles(
innerRoot: Element | null,
mergedVariables: Record<string, unknown>,
runtimeScope: string,
- compStyleChunks: string[],
+ compStyleChunks: CompositionStyle[],
): void {
if (!runtimeScope) return;
const declaredForCss = readDeclaredDefaults(innerDoc.documentElement);
@@ -1563,5 +1551,5 @@ function pushSubCompVariableStyles(
{ ...declaredForCss, ...mergedVariables },
runtimeScope,
);
- if (cssVars) compStyleChunks.push(cssVars);
+ if (cssVars) compStyleChunks.push({ css: cssVars, media: null, title: null });
}
diff --git a/packages/core/src/compiler/index.ts b/packages/core/src/compiler/index.ts
index c40df78d04..5affe4f181 100644
--- a/packages/core/src/compiler/index.ts
+++ b/packages/core/src/compiler/index.ts
@@ -60,7 +60,15 @@ export {
export { addScenePartsManifest } from "./scenePartsManifest";
// Script ordering shared by the bundler and the producer coalescers
-export { inlineScriptRuns, type InlineScriptRun } from "./scriptRuns";
+export {
+ compositionStyle,
+ cssStyleMergeKey,
+ headStyleRuns,
+ inlineScriptRuns,
+ styleElementsFor,
+ type CompositionStyle,
+ type InlineScriptRun,
+} from "./scriptRuns";
// Static guard
export {
@@ -78,6 +86,7 @@ export {
// Sub-composition inlining (shared between bundler and producer)
export {
+ ensureExternalLinkTag,
inlineSubCompositions,
type InlineSubCompositionsOptions,
type InlineSubCompositionsResult,
diff --git a/packages/core/src/compiler/inlineSubCompositions.test.ts b/packages/core/src/compiler/inlineSubCompositions.test.ts
index e89d0dee88..55100ac4f0 100644
--- a/packages/core/src/compiler/inlineSubCompositions.test.ts
+++ b/packages/core/src/compiler/inlineSubCompositions.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { parseHTML } from "linkedom";
-import { inlineSubCompositions } from "./inlineSubCompositions";
+import { ensureExternalLinkTag, inlineSubCompositions } from "./inlineSubCompositions";
import { readDeclaredDefaults, parseHostVariableValues } from "../runtime/getVariables";
// Fixtures reference GSAP CDN but are never loaded in a real browser — resolveHtml is mocked.
@@ -124,7 +124,7 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
// CSS was scoped: #intro selectors should be rewritten to use
// data-hf-authored-id attribute selector so they still resolve.
- const scopedCss = result.styles.join("\n");
+ const scopedCss = result.styles.map((style) => style.css).join("\n");
expect(scopedCss).toContain('[data-hf-authored-id="intro"]');
expect(scopedCss).not.toContain("#intro");
});
@@ -140,7 +140,7 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
// The CSS scoper rewrites `#intro` to `[data-hf-authored-id="intro"]`
// so that the selector resolves against the flattened structure.
- const scopedCss = result.styles.join("\n");
+ const scopedCss = result.styles.map((style) => style.css).join("\n");
expect(scopedCss).toContain('[data-hf-authored-id="intro"]');
expect(scopedCss).toContain('[data-hf-authored-id="intro"] .title');
});
@@ -182,7 +182,9 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
expect(host.getAttribute("data-composition-id")).toBe("captions-comp");
expect(host.querySelector('[data-composition-id="captions"]')).not.toBeNull();
- expect(result.styles.join("\n")).toContain('[data-composition-id="captions-comp"]');
+ expect(result.styles.map((style) => style.css).join("\n")).toContain(
+ '[data-composition-id="captions-comp"]',
+ );
const wrappedScript = result.scripts.join("\n");
expect(wrappedScript).toContain('var __hfCompId = "captions"');
expect(wrappedScript).toContain('var __hfTimelineCompId = "captions-comp"');
@@ -218,7 +220,7 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
expect(authoredRoot).not.toBeNull();
// CSS is still rewritten to use the attribute selector.
- const scopedCss = result.styles.join("\n");
+ const scopedCss = result.styles.map((style) => style.css).join("\n");
expect(scopedCss).toContain('[data-hf-authored-id="intro"]');
});
@@ -264,7 +266,7 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
const wrapper = host.querySelector("[data-hf-inner-root]");
expect(wrapper?.getAttribute("data-composition-id")).toBe("scoped-text");
- const scopedCss = result.styles.join("\n");
+ const scopedCss = result.styles.map((style) => style.css).join("\n");
expect(scopedCss).toContain("display: flex");
});
@@ -361,7 +363,7 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
]);
});
- it("deduplicates link hrefs across multiple sub-compositions", () => {
+ it("emits one link for the same link in two sub-compositions", () => {
const subComp = `<!doctype html>
<html><head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@800">
@@ -383,10 +385,10 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
parseHtml: (html) => parseHTML(html).document,
});
- expect(result.externalLinks).toHaveLength(1);
- expect(result.externalLinks[0]!.href).toBe(
- "https://fonts.googleapis.com/css2?family=Montserrat:wght@800",
- );
+ for (const link of result.externalLinks) ensureExternalLinkTag(document, link);
+ expect(
+ [...document.head.querySelectorAll("link")].map((el) => el.getAttribute("href")),
+ ).toEqual(["https://fonts.googleapis.com/css2?family=Montserrat:wght@800"]);
});
it("propagates data-timeline-locked from inner root to host element", () => {
@@ -445,7 +447,7 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
expect(host.getAttribute("data-composition-id")).toBe("intro");
expect(host.getAttribute("data-hf-authored-id")).toBe("intro");
- const scopedCss = result.styles.join("\n");
+ const scopedCss = result.styles.map((style) => style.css).join("\n");
// Root-only selector: must be compound
expect(scopedCss).toMatch(/\[data-composition-id="intro"\]\[data-hf-authored-id="intro"\]/);
@@ -690,7 +692,9 @@ describe("inlineSubCompositions – sub-composition asset paths", () => {
it("rewrites sibling refs in markup, hoisted CSS, and inline styles", () => {
const { document, result } = inlineFrame();
expect(document.querySelector("img")?.getAttribute("src")).toBe("design/styleframes/frame.png");
- expect(result.styles.join("\n")).toContain("design/styleframes/frame.png");
+ expect(result.styles.map((style) => style.css).join("\n")).toContain(
+ "design/styleframes/frame.png",
+ );
expect(document.querySelector("[style]")?.getAttribute("style")).toContain(
"design/styleframes/frame.png",
);
diff --git a/packages/core/src/compiler/inlineSubCompositions.ts b/packages/core/src/compiler/inlineSubCompositions.ts
index 3551c324db..9581116f3c 100644
--- a/packages/core/src/compiler/inlineSubCompositions.ts
+++ b/packages/core/src/compiler/inlineSubCompositions.ts
@@ -1,5 +1,11 @@
import { readExternalScriptAttributes, type ExternalScriptAttributes } from "./externalScripts";
import { parseImportMap, type ImportMap } from "./importMaps";
+import {
+ compositionStyle,
+ cssStyleMergeKey,
+ hasSameLink,
+ type CompositionStyle,
+} from "./scriptRuns";
/**
* Shared sub-composition inlining logic.
*
@@ -229,8 +235,31 @@ export interface InlineSubCompositionsOptions {
tagScenes?: boolean;
}
+export interface ExternalLink {
+ href: string;
+ rel: string;
+ crossorigin?: string;
+ media?: string;
+ title?: string;
+ type?: string;
+ disabled?: true;
+}
+
+/** Appends a hoisted link unless the document already has a live one it would duplicate. */
+export function ensureExternalLinkTag(doc: Document, link: ExternalLink): void {
+ const el = doc.createElement("link");
+ el.setAttribute("rel", link.rel);
+ el.setAttribute("href", link.href);
+ for (const name of ["crossorigin", "media", "title", "type"] as const) {
+ const value = link[name];
+ if (value != null) el.setAttribute(name, value);
+ }
+ if (link.disabled) el.setAttribute("disabled", "");
+ if (!hasSameLink(doc, el)) doc.head.appendChild(el);
+}
+
export interface InlineSubCompositionsResult {
- styles: string[];
+ styles: CompositionStyle[];
/** With `tagScenes`: the scene each entry of `styles` belongs to. */
styleScenes: string[];
scripts: string[];
@@ -239,7 +268,8 @@ export interface InlineSubCompositionsResult {
| { kind: "inline"; content: string; scene?: string }
| ({ kind: "external"; src: string; scene?: string } & ExternalScriptAttributes)
>;
- externalLinks: { href: string; rel: string; crossorigin?: string }[];
+ /** May list one link more than once; `ensureExternalLinkTag` dedupes. */
+ externalLinks: ExternalLink[];
variablesByComp: Record<string, Record<string, unknown>>;
/** Mounted files' import maps, addresses rebased; emit with `emitMountedModuleScripts`. */
importMaps: ImportMap[];
@@ -297,15 +327,14 @@ export function inlineSubCompositions(
tagScenes = false,
} = options;
- const styles: string[] = [];
+ const styles: CompositionStyle[] = [];
const styleScenes: string[] = [];
const scripts: string[] = [];
const externalScriptSrcs: string[] = [];
const scriptItems: InlineSubCompositionsResult["scriptItems"] = [];
const importMaps: ImportMap[] = [];
const moduleScripts: string[] = [];
- const externalLinks: { href: string; rel: string; crossorigin?: string }[] = [];
- const seenLinkHrefs = new Set<string>();
+ const externalLinks: ExternalLink[] = [];
const variablesByComp: Record<string, Record<string, unknown>> = {};
const sceneHosts = new Map<string, Element>();
@@ -441,13 +470,16 @@ export function inlineSubCompositions(
// composition's font from the render while preview kept it.
for (const link of plan.linkSources) {
const href = resolveSubAssetPath(link.getAttribute("href"));
- if (href && !seenLinkHrefs.has(href)) {
- seenLinkHrefs.add(href);
+ if (href) {
const rel = (link.getAttribute("rel") || "").trim();
const crossorigin = link.hasAttribute("crossorigin")
? link.getAttribute("crossorigin") || ""
: undefined;
- externalLinks.push({ href, rel, crossorigin });
+ const media = link.getAttribute("media") ?? undefined;
+ const title = link.getAttribute("title") ?? undefined;
+ const type = link.getAttribute("type") ?? undefined;
+ const disabled = link.hasAttribute("disabled") ? true : undefined;
+ externalLinks.push({ href, rel, crossorigin, media, title, type, disabled });
}
}
@@ -455,7 +487,8 @@ export function inlineSubCompositions(
// carries its backgrounds, positioning and fonts, and a <head> library tag
// (GSAP from a CDN) has to run before the content scripts calling into it.
for (const styleEl of plan.styleSources) {
- styles.push(scopeSubStyle(styleEl.textContent || ""));
+ if (cssStyleMergeKey(styleEl) === undefined) continue;
+ styles.push(compositionStyle(styleEl, scopeSubStyle(styleEl.textContent || "")));
if (scene) styleScenes.push(scene);
styleEl.remove();
}
diff --git a/packages/core/src/compiler/scriptRuns.ts b/packages/core/src/compiler/scriptRuns.ts
index 7ea577ad4d..367a133cb7 100644
--- a/packages/core/src/compiler/scriptRuns.ts
+++ b/packages/core/src/compiler/scriptRuns.ts
@@ -37,3 +37,77 @@ export function inlineScriptRuns(
if (members.length > 0) runs.push({ members, anchor: null });
return runs;
}
+
+/** Undefined for a type the browser never applies as CSS; `media="all"` and an empty title count as none. */
+export function cssStyleMergeKey(el: Element): string | undefined {
+ const rawType = el.getAttribute("type") ?? "";
+ // Chrome reads a link's type as a MIME type, so parameters are allowed; a style's must match exactly.
+ const type = el.tagName.toLowerCase() === "link" ? rawType.split(";")[0]!.trim() : rawType;
+ if (type !== "" && type.toLowerCase() !== "text/css") return undefined;
+ const media = (el.getAttribute("media") ?? "").trim().toLowerCase();
+ return JSON.stringify([media === "all" ? "" : media, el.getAttribute("title") ?? ""]);
+}
+
+export const UNCONDITIONAL_CSS_KEY = JSON.stringify(["", ""]);
+
+/** A link's identity and condition; fetch attributes (crossorigin, integrity, referrerpolicy) are not compared. */
+function linkDedupeKey(el: Element): string {
+ return JSON.stringify([
+ el.getAttribute("href"),
+ (el.getAttribute("rel") ?? "").trim().toLowerCase(),
+ cssStyleMergeKey(el) ?? el.getAttribute("type"),
+ el.hasAttribute("disabled"),
+ ]);
+}
+
+export function hasSameLink(scope: ParentNode, link: Element): boolean {
+ const key = linkDedupeKey(link);
+ return [...scope.querySelectorAll("link[href]")].some(
+ (other) => !other.closest("noscript") && linkDedupeKey(other) === key,
+ );
+}
+
+/** Groups head styles into runs of adjacent styles with one merge key, so merging a run never reorders rules. */
+export function headStyleRuns(
+ styles: readonly Element[],
+ isPinned: (el: Element) => boolean = () => false,
+): Element[][] {
+ const runs: Element[][] = [];
+ let previousKey: string | undefined;
+ for (const el of styles) {
+ const key = isPinned(el) ? undefined : cssStyleMergeKey(el);
+ if (key !== undefined && key === previousKey) runs.at(-1)!.push(el);
+ else if (key !== undefined) runs.push([el]);
+ previousKey = key;
+ }
+ return runs;
+}
+
+export interface CompositionStyle {
+ css: string;
+ media: string | null;
+ title: string | null;
+}
+
+export function compositionStyle(el: Element, css: string): CompositionStyle {
+ return { css, media: el.getAttribute("media"), title: el.getAttribute("title") };
+}
+
+/** One `<style>` per adjacent run of same-condition sheets, keeping each run's media and title. */
+export function styleElementsFor(
+ document: Document,
+ sheets: readonly CompositionStyle[],
+ join: (css: string[]) => string,
+): Element[] {
+ const elements = sheets.map(({ css, media, title }) => {
+ const el = document.createElement("style");
+ if (media !== null) el.setAttribute("media", media);
+ if (title !== null) el.setAttribute("title", title);
+ el.textContent = css;
+ return el;
+ });
+ return headStyleRuns(elements).map((run) => {
+ run[0]!.textContent = join(run.map((el) => el.textContent || ""));
+ return run[0]!;
+ });
+}
diff --git a/packages/core/src/runtime/compositionLoader.ts b/packages/core/src/runtime/compositionLoader.ts
index 45acf163db..443199e715 100644
--- a/packages/core/src/runtime/compositionLoader.ts
+++ b/packages/core/src/runtime/compositionLoader.ts
@@ -8,6 +8,7 @@ import {
wrapScopedCompositionScript,
} from "../compiler/compositionScoping";
import { parseImportMap } from "../compiler/importMaps";
+import { hasSameLink } from "../compiler/scriptRuns";
import { parseLayoutDimension } from "./compositionDimension";
import { markFlattenedInnerRoot } from "./flattenedRoot";
import {
@@ -457,10 +458,10 @@ async function mountCompositionContent(params: {
if (!rawHref) continue;
const href = params.compositionUrl ? new URL(rawHref, params.compositionUrl).href : rawHref;
if (params.compositionUrl && isSameDocumentUrl(href, params.compositionUrl)) continue;
- if (document.head.querySelector(`link[href="${CSS.escape(href)}"]`)) continue;
const clonedLink = link.cloneNode(true);
if (!isLinkElement(clonedLink)) continue;
clonedLink.href = href;
+ if (hasSameLink(document.head, clonedLink)) continue;
document.head.appendChild(clonedLink);
params.injectedLinks.push(clonedLink);
}
diff --git a/packages/producer/src/services/htmlCompiler.parity.test.ts b/packages/producer/src/services/htmlCompiler.parity.test.ts
index 16d7e0a06b..4d2cb5c995 100644
--- a/packages/producer/src/services/htmlCompiler.parity.test.ts
+++ b/packages/producer/src/services/htmlCompiler.parity.test.ts
@@ -119,6 +119,158 @@ describe("preview/render semantic compilation parity", () => {
expect(result.render).toEqual(result.preview);
});
+ it("keeps conditional head styles apart the same way in preview and render", async () => {
+ const dir = project({
+ "index.html": shell(
+ `<main data-composition-id="main" data-start="0" data-width="320" data-height="180" data-duration="1"></main>`,
+ `<style>p{color:red}</style><style media="print">p{color:blue}</style>` +
+ `<style type="text/x-tpl">{{ a }}</style><style title="alt">p{color:green}</style>` +
+ `<style>h1{color:black}</style><style>h2{color:black}</style>`,
+ ),
+ });
+ const headStyles = (html: string) =>
+ [...new DOMParser().parseFromString(html, "text/html").head.querySelectorAll("style")]
+ .filter((el) => !el.hasAttribute("data-hyperframes-text-rendering"))
+ .map((el) => [
+ el.getAttribute("media"),
+ el.getAttribute("type"),
+ el.getAttribute("title"),
+ el.textContent,
+ ]);
+ const preview = headStyles(await bundleToSingleHtml(dir));
+ const render = headStyles(
+ (
+ await compileForRender(dir, join(dir, "index.html"), join(dir, ".downloads"), {
+ allowSystemFontCapture: false,
+ })
+ ).html,
+ );
+ expect(preview).toEqual([
+ [null, null, null, "p{color:red}"],
+ ["print", null, null, "p{color:blue}"],
+ [null, "text/x-tpl", null, "{{ a }}"],
+ [null, null, "alt", "p{color:green}"],
+ [null, null, null, "h1{color:black}\n\nh2{color:black}"],
+ ]);
+ expect(render).toEqual(preview);
+ });
+
+ it("keeps a composition's print style print-only in preview and render", async () => {
+ const dir = project({
+ "index.html": shell(
+ `<main data-composition-id="main" data-start="0" data-width="320" data-height="180" data-duration="1">
+ <section data-composition-id="card" data-composition-src="card.html" data-start="0" data-duration="1"></section>
+ </main>`,
+ ),
+ "card.html": `<template id="card-template"><article data-composition-id="card" data-width="320" data-height="180">
+ <style media="print">.card-p{color:blue}</style><p class="card-p">x</p></article></template>`,
+ });
+ const printCss = (html: string) =>
+ [
+ ...new DOMParser()
+ .parseFromString(html, "text/html")
+ .querySelectorAll('style[media="print"]'),
+ ]
+ .map((el) => el.textContent)
+ .join("\n");
+ expect(printCss(await bundleToSingleHtml(dir))).toMatch(/\.card-p\{color:blue\}/);
+ const render = await compileForRender(dir, join(dir, "index.html"), join(dir, ".downloads"), {
+ allowSystemFontCapture: false,
+ });
+ expect(printCss(render.html)).toMatch(/\.card-p\{color:blue\}/);
+ });
+
+ it("emits conditional composition styles and links as their own elements in preview and render", async () => {
+ const host = (id: string) =>
+ `<section data-composition-id="${id}" data-composition-src="${id}.html" data-start="0" data-duration="1"></section>`;
+ const comp = (id: string, inner: string) =>
+ `<template id="${id}-template"><article data-composition-id="${id}" data-width="320" data-height="180">${inner}<p class="p${id}">x</p></article></template>`;
+ const dir = project({
+ "index.html": shell(
+ `<main data-composition-id="main" data-start="0" data-width="320" data-height="180" data-duration="1">
+ ${["a", "b", "c", "d"].map(host).join("")}</main>`,
+ ),
+ "a.html": comp("a", `<style media="(max-width: 10px">.pa{color:blue}</style>`),
+ "b.html": comp("b", `<style>.pb{color:green}</style>`),
+ "c.html": comp("c", `<style media="screen">@import "local.css"; .pc{color:red}</style>`),
+ "d.html": comp(
+ "d",
+ `<style title="alt">.pd{color:black}</style><link rel="stylesheet" href="d.css" media="print" title="alt">`,
+ ),
+ "local.css": ".q{color:green}",
+ "d.css": ".pd{color:white}",
+ });
+ const head = (html: string) => {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ const styles = [...doc.head.querySelectorAll("style")]
+ .filter((el) => /\.p[a-d]\b/.test(el.textContent ?? ""))
+ .map((el) => ({
+ media: el.getAttribute("media"),
+ title: el.getAttribute("title"),
+ css: (el.textContent ?? "").trim(),
+ }));
+ const links = [...doc.head.querySelectorAll('link[rel="stylesheet"]')].map((el) => ({
+ media: el.getAttribute("media"),
+ title: el.getAttribute("title"),
+ }));
+ return { styles, links };
+ };
+ const preview = head(await bundleToSingleHtml(dir));
+ const render = head(
+ (
+ await compileForRender(dir, join(dir, "index.html"), join(dir, ".downloads"), {
+ allowSystemFontCapture: false,
+ })
+ ).html,
+ );
+ const find = (id: string) => preview.styles.find((style) => style.css.includes(`.p${id}{`));
+ expect(find("a")?.media).toBe("(max-width: 10px");
+ expect(find("a")?.css).not.toContain(".pb{");
+ expect(find("b")).toMatchObject({ media: null, title: null });
+ expect(find("c")?.media).toBe("screen");
+ expect(find("c")?.css.startsWith('@import "local.css"')).toBe(true);
+ expect(find("d")).toMatchObject({ media: null, title: "alt" });
+ expect(preview.links).toEqual([{ media: "print", title: "alt" }]);
+ expect(render).toEqual(preview);
+ });
+
+ it("keeps each composition's link to a shared file under its own condition in preview, render and mount", async () => {
+ const url = "https://cdn.example/shared.css";
+ const host = (id: string) =>
+ `<section data-composition-id="${id}" data-composition-src="${id}.html" data-start="0" data-duration="1"></section>`;
+ const comp = (id: string, attrs: string) =>
+ `<template id="${id}-template"><article data-composition-id="${id}" data-width="320" data-height="180"><link rel="stylesheet" href="${url}"${attrs}><p>x</p></article></template>`;
+ const files = {
+ "index.html": shell(
+ `<main data-composition-id="main" data-start="0" data-width="320" data-height="180" data-duration="1">
+ ${["a", "b", "c"].map(host).join("")}</main>`,
+ `<link rel="stylesheet" href="${url}" title="alt">`,
+ ),
+ "a.html": comp("a", ' media="print"'),
+ "b.html": comp("b", ""),
+ "c.html": comp("c", ' media="print"'),
+ };
+ const dir = project(files);
+ const links = (head: ParentNode) =>
+ [...head.querySelectorAll(`link[href="${url}"]`)].map((el) => ({
+ media: el.getAttribute("media"),
+ title: el.getAttribute("title"),
+ }));
+ const parsedHead = (html: string) => new DOMParser().parseFromString(html, "text/html").head;
+ const expected = [
+ { media: null, title: "alt" },
+ { media: "print", title: null },
+ { media: null, title: null },
+ ];
+ expect(links(parsedHead(await bundleToSingleHtml(dir)))).toEqual(expected);
+ const render = await compileForRender(dir, join(dir, "index.html"), join(dir, ".downloads"), {
+ allowSystemFontCapture: false,
+ });
+ expect(links(parsedHead(render.html))).toEqual(expected);
+ await mountContract(dir, files["index.html"]);
+ expect(links(document.head)).toEqual(expected);
+ });
+
it("keeps legacy end/layer timing semantically identical", async () => {
const result = await contracts({
"index.html":
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
index 0053a3cfb5..b255192eaa 100644
--- a/packages/producer/src/services/htmlCompiler.ts
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -40,13 +40,16 @@ import {
type BundledHostCompositionIdentity,
buildVariablesByCompScript,
inlineSubCompositions as inlineSubCompositionsShared,
+ ensureExternalLinkTag,
ensureExternalScriptTag,
emitMountedModuleScripts,
prepareFlattenedInnerRoot,
emitRootCompositionVariableStyles,
readDeclaredDefaults,
parseHostVariableValues,
+ headStyleRuns,
inlineScriptRuns,
+ styleElementsFor,
insertBeforeCloseTag,
} from "@hyperframes/core/compiler";
import {
@@ -854,8 +857,8 @@ class ProducerHostIdentityMap extends Map<Element, BundledHostCompositionIdentit
}
/**
- * Merge all `<head>` `<style>` blocks into a single tag with `@import` rules
- * at the top, and merge each run of adjacent inline `<body>` `<script>` blocks
+ * Merge each run of adjacent same-condition `<head>` `<style>` blocks into one, `@import`
+ * rules at its top, and merge each run of adjacent inline `<body>` `<script>` blocks
* into one, without moving any of them past a `<script src>` or module script.
*
* Mirrors the bundler's `coalesceHeadStylesAndBodyScripts` to guarantee
@@ -870,13 +873,13 @@ function coalesceHeadStylesAndBodyScripts(html: string): string {
if (!head) return html;
const styleEls = Array.from(head.querySelectorAll("style"));
- if (styleEls.length > 1) {
- const importRe = /@import\s+url\([^)]*\)\s*;|@import\s+["'][^"']+["']\s*;/gi;
+ const importRe = /@import\s+url\([^)]*\)\s*;|@import\s+["'][^"']+["']\s*;/gi;
+ for (const run of styleEls.length > 1 ? headStyleRuns(styleEls) : []) {
const imports: string[] = [];
const cssParts: string[] = [];
const seenImports = new Set<string>();
- for (const el of styleEls) {
+ for (const el of run) {
const raw = (el.textContent || "").trim();
if (!raw) continue;
const nonImportCss = raw.replace(importRe, (match) => {
@@ -892,14 +895,9 @@ function coalesceHeadStylesAndBodyScripts(html: string): string {
}
const mergedCss = [...imports, ...cssParts].join("\n\n").trim();
- if (mergedCss) {
- const firstStyleEl = styleEls[0];
- if (firstStyleEl) firstStyleEl.textContent = mergedCss;
- for (let i = 1; i < styleEls.length; i++) {
- const el = styleEls[i];
- if (el) el.remove();
- }
- }
+ if (!mergedCss) continue;
+ run[0]!.textContent = mergedCss;
+ for (const el of run.slice(1)) el.remove();
}
if (body) {
@@ -1037,23 +1035,13 @@ function inlineSubCompositions(
}
}
- if (result.externalLinks.length && head) {
- for (const link of result.externalLinks) {
- const escapedHref = link.href.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
- if (document.querySelector(`link[href="${escapedHref}"]`)) continue;
- const el = document.createElement("link");
- el.setAttribute("rel", link.rel);
- el.setAttribute("href", link.href);
- if (link.crossorigin != null) el.setAttribute("crossorigin", link.crossorigin);
- head.appendChild(el);
- }
- }
+ if (head) for (const link of result.externalLinks) ensureExternalLinkTag(document, link);
// Append collected styles to <head>
- if (result.styles.length && head) {
- const styleEl = document.createElement("style");
- styleEl.textContent = result.styles.join("\n\n");
- head.appendChild(styleEl);
+ if (head) {
+ for (const style of styleElementsFor(document, result.styles, (css) => css.join("\n\n"))) {
+ head.appendChild(style);
+ }
}
// CDN and integrity-pinned scripts go first so plugins (e.g. TextPlugin,