perf(producer): compile time stays linear on pages with thousands of clips or style rules (#8528)

* perf(producer): compile time stays linear on pages with thousands of clips or style rules

* perf(producer): each background rule's selector matches in bounded time, :has() included

* fix(producer): a wrapper's escaped class selector still finds its background
This commit is contained in:
Miguel Ángel
2026-11-22 21:14:59 +00:00
committed by GitHub
parent 2e1cd03237
commit 60c0f9e279
4 changed files with 256 additions and 48 deletions
@@ -396,6 +396,16 @@ describe("compileTimingAttrs", () => {
});
});
// 5,000 clips: main rescanned the page once per clip, about a minute for this page.
const CLIPS = 5_000;
const manyClips = (attrs: string) =>
Array.from(
{ length: CLIPS },
(_, i) => `<audio id="a${i}" src="a.mp3" data-start="1"${attrs}>`,
).join("");
const eachClip = (duration: number) =>
Array.from({ length: CLIPS }, (_, i) => ({ id: `a${i}`, duration }));
describe("injectDurations", () => {
it("adds data-duration and data-end for resolved elements", () => {
const html = '<video id="v1" src="a.mp4" data-start="2">';
@@ -414,6 +424,24 @@ describe("injectDurations", () => {
expect(result).toContain('data-end="5"');
});
it("writes 5,000 clips' durations in one scan of the page", () => {
const started = performance.now();
const result = injectDurations(manyClips(""), eachClip(4));
expect(performance.now() - started).toBeLessThan(1000);
expect(result.match(/data-duration="4" data-end="5"/g)).toHaveLength(CLIPS);
});
it("keeps the first duration when a clip is listed twice, and fills every tag with that id", () => {
const html = '<video id="v1" data-start="1"><audio id="v1" data-start="2">';
const result = injectDurations(html, [
{ id: "v1", duration: 4 },
{ id: "v1", duration: 9 },
]);
expect(result).toBe(
'<video id="v1" data-start="1" data-duration="4" data-end="5"><audio id="v1" data-start="2" data-duration="4" data-end="6">',
);
});
it("does not overwrite existing data-duration", () => {
const html = '<video id="v1" src="a.mp4" data-start="0" data-duration="3">';
const result = injectDurations(html, [{ id: "v1", duration: 10 }]);
@@ -482,6 +510,14 @@ describe("clampDurations", () => {
expect(result).toContain('data-duration="5"');
expect(result).toContain('data-end="7"');
});
it("clamps 5,000 clips in one scan of the page, the last clamp for a clip winning", () => {
const clamps = [...eachClip(3), ...eachClip(2)];
const started = performance.now();
const result = clampDurations(manyClips(' data-duration="10" data-end="11"'), clamps);
expect(performance.now() - started).toBeLessThan(1000);
expect(result.match(/data-duration="2" data-end="3"/g)).toHaveLength(CLIPS);
});
});
describe("shouldClampResolvedMediaDuration", () => {
+43 -37
View File
@@ -141,15 +141,30 @@ function replaceOpeningTags(
return parts.join("");
}
function replaceIdTags(html: string, id: string, replace: (tag: string) => string): string {
/** Applies each tag's durations, in the order given, in one scan of the page however many there are. */
function applyDurationsById(
html: string,
resolutions: readonly ResolvedDuration[],
apply: (tag: string, duration: number) => string,
): string {
const durationsById = new Map<string, number[]>();
for (const { id, duration } of resolutions) {
const durations = durationsById.get(id);
if (durations) durations.push(duration);
else durationsById.set(id, [duration]);
}
const parts: string[] = [];
let cursor = 0;
for (const span of scanHtmlOpeningTags(html)) {
if (!span.closed) continue;
const tag = html.slice(span.start, span.end);
const attr = span.attributes.find((attr) => attr.name === "id");
if (attr?.kind !== "value" || decodeAuthoredAttribute(attr.value) !== id) continue;
parts.push(html.slice(cursor, span.start), replace(tag));
if (attr?.kind !== "value") continue;
const durations = durationsById.get(decodeAuthoredAttribute(attr.value));
if (!durations) continue;
parts.push(
html.slice(cursor, span.start),
durations.reduce(apply, html.slice(span.start, span.end)),
);
cursor = span.end;
}
parts.push(html.slice(cursor));
@@ -278,29 +293,24 @@ export function compileTimingAttrs(html: string): CompilationResult {
* GSAP timeline queries.
*/
export function injectDurations(html: string, resolutions: ResolvedDuration[]): string {
for (const { id, duration } of resolutions) {
// Match the element's opening tag by id
html = replaceIdTags(html, id, (tag) => {
let result = tag;
return applyDurationsById(html, resolutions, (tag, duration) => {
let result = tag;
// Add data-duration if missing
if (parseStrictFiniteTimingNumber(getAttr(result, "data-duration")) == null) {
result = setAttr(result, "data-duration", String(duration));
// Add data-duration if missing
if (parseStrictFiniteTimingNumber(getAttr(result, "data-duration")) == null) {
result = setAttr(result, "data-duration", String(duration));
}
// Add data-end if missing. Skip relative id-refs.
if (!hasAttr(result, "data-end")) {
const start = parseNumeric(getAttr(result, "data-start"));
if (start != null) {
result = injectAttr(result, "data-end", String(start + duration));
}
}
// Add data-end if missing. Skip relative id-refs.
if (!hasAttr(result, "data-end")) {
const start = parseNumeric(getAttr(result, "data-start"));
if (start != null) {
result = injectAttr(result, "data-end", String(start + duration));
}
}
return result;
});
}
return html;
return result;
});
}
/**
@@ -343,19 +353,15 @@ export function extractResolvedMedia(html: string): ResolvedMediaElement[] {
* and recomputes data-end accordingly.
*/
export function clampDurations(html: string, clamps: ResolvedDuration[]): string {
for (const { id, duration } of clamps) {
html = replaceIdTags(html, id, (tag) => {
// Replace data-duration value
if (hasAttr(tag, "data-duration")) tag = setAttr(tag, "data-duration", String(duration));
return applyDurationsById(html, clamps, (tag, duration) => {
// Replace data-duration value
if (hasAttr(tag, "data-duration")) tag = setAttr(tag, "data-duration", String(duration));
const start = parseNumeric(getAttr(tag, "data-start"));
if (start != null && hasAttr(tag, "data-end")) {
tag = setAttr(tag, "data-end", String(start + duration));
}
const start = parseNumeric(getAttr(tag, "data-start"));
if (start != null && hasAttr(tag, "data-end")) {
tag = setAttr(tag, "data-end", String(start + duration));
}
return tag;
});
}
return html;
return tag;
});
}
@@ -1433,6 +1433,71 @@ describe("detectAncestorBackgroundImage", () => {
expect(detectAncestorBackgroundImage(wrap("html, body { background: #0d1117; }"))).toBe(false);
});
it("checks 5,000 background rules against a 50,000-element page in one pass", () => {
// Main matched each selector against the whole page: about 9 s for this one.
const css = Array.from(
{ length: 5_000 },
(_, i) => `.c${i} div { background-image: url(x.png); }`,
).join("\n");
const page = wrap(css, "", "<div></div>".repeat(50_000));
const started = performance.now();
expect(detectAncestorBackgroundImage(page)).toBe(false);
expect(performance.now() - started).toBeLessThan(1000);
});
it("answers yes for a root nested deeper than any real page, without matching", () => {
const deep = `${"<div>".repeat(300)}<div data-composition-id="main"></div>${"</div>".repeat(300)}`;
const html = `<html><head><style>.x { background-image: url(x.png); }</style></head><body>${deep}</body></html>`;
expect(detectAncestorBackgroundImage(html)).toBe(true);
});
it("answers yes once background rules would take over 100,000 selector checks", () => {
// 3 ancestors (wrapper, body, html): 40,000 selectors is 120,000 checks.
const css = Array.from({ length: 40_000 }, (_, i) => `.c${i}`).join(",");
const html =
`<html><head><style>${css} { background-image: url(x.png); }</style></head>` +
'<body><div><div data-composition-id="main"></div></div></body></html>';
expect(detectAncestorBackgroundImage(html)).toBe(true);
const fewer = html.replace(css, Array.from({ length: 30_000 }, (_, i) => `.c${i}`).join(","));
expect(detectAncestorBackgroundImage(fewer)).toBe(false);
});
it("decides :has() rules without letting one match scan the page", () => {
// Main ran each :has() over the whole 50,000-element page per ancestor; stripped, it widens to a yes.
const css = Array.from(
{ length: 1_000 },
(_, i) => `:has(.n${i}) { background-image: url(x.png); }`,
);
const page = wrap(css.join("\n"), "", "<i></i>".repeat(50_000));
const started = performance.now();
expect(detectAncestorBackgroundImage(page)).toBe(true);
expect(performance.now() - started).toBeLessThan(1000);
});
it("still reads combinators exactly and pseudo parts only widening", () => {
const page = (css: string) =>
`<html><head><style>${css} { background-image: url(x.png); }</style></head><body>` +
'<div class="page"><div class="mid"><div class="wrap">' +
'<div data-composition-id="main"><div class="tile card"></div></div></div></div></div></body></html>';
expect(detectAncestorBackgroundImage(page(".page .wrap"))).toBe(true);
expect(detectAncestorBackgroundImage(page(".mid > .wrap"))).toBe(true);
expect(detectAncestorBackgroundImage(page(".page > .wrap"))).toBe(false);
expect(detectAncestorBackgroundImage(page(".tile::before, .card:hover"))).toBe(false);
expect(detectAncestorBackgroundImage(page(":is(.a, .b) .tile"))).toBe(false);
expect(detectAncestorBackgroundImage(page(".other ~ .wrap"))).toBe(true);
expect(detectAncestorBackgroundImage(page('.page[data-x="a]b"] .wrap:not(.z)'))).toBe(false);
expect(detectAncestorBackgroundImage(page(".page:not(.z"))).toBe(true);
});
it("reads CSS escapes in a wrapper's selector, hex escapes with their closing space included", () => {
const page = (css: string, cls: string) =>
`<html><head><style>${css} { background-image: url(x.png); }</style></head><body>` +
`<div class="${cls}"><div data-composition-id="main"></div></div></body></html>`;
expect(detectAncestorBackgroundImage(page(".\\31 23", "123"))).toBe(true);
expect(detectAncestorBackgroundImage(page(".md\\:bg", "md:bg"))).toBe(true);
expect(detectAncestorBackgroundImage(page(".\\31 23 .x", "123"))).toBe(false);
});
it("returns false without a composition root", () => {
expect(
detectAncestorBackgroundImage(
+112 -11
View File
@@ -564,6 +564,106 @@ export function detectThreeDTransformUsage(html: string): boolean {
return THREE_D_CONTEXT_PATTERN.test(html);
}
type AncestorStep = { compound: string; child: boolean };
const CSS_ESCAPE = /\\(?:[0-9a-fA-F]{1,6}[ \t\n\r\f]?|[^])?/y;
/**
* Each selector of a list as plain compounds, pseudo-classes, pseudo-elements and sibling steps dropped:
* each drop only widens the match, and a plain compound matches in bounded time. null when unbalanced.
*/
function ancestorSelectorSteps(list: string): AncestorStep[][] | null {
const selectors: AncestorStep[][] = [];
let steps: AncestorStep[] = [];
let combinators: (string | null)[] = [];
let compound = "";
let open = false;
let combinator: string | null = null;
const skipGroup = (at: number, close: string): number => {
let depth = 0;
for (let i = at; i < list.length; i++) {
const ch = list[i]!;
if (ch === "\\") i++;
else if (ch === '"' || ch === "'") {
const end = list.indexOf(ch, i + 1);
if (end < 0) return -1;
i = end;
} else if (ch === list[at]) depth++;
else if (ch === close && --depth === 0) return i;
}
return -1;
};
const flush = () => {
if (!open) return;
if ((combinator === "+" || combinator === "~") && steps.length > 0) {
steps.pop();
combinator = combinators.pop() ?? null;
}
steps.push({ compound: compound || "*", child: combinator === ">" });
combinators.push(combinator);
compound = "";
open = false;
combinator = null;
};
for (let i = 0; i <= list.length; i++) {
const ch = list[i];
if (ch === undefined || ch === ",") {
flush();
if (steps.length) selectors.push(steps);
steps = [];
combinators = [];
combinator = null;
} else if (ch === "\\") {
CSS_ESCAPE.lastIndex = i;
const escape = CSS_ESCAPE.exec(list)![0];
compound += escape;
i += escape.length - 1;
open = true;
} else if (ch === "[") {
const end = skipGroup(i, "]");
if (end < 0) return null;
compound += list.slice(i, end + 1);
open = true;
i = end;
} else if (ch === ":") {
while (/[:\w-]/.test(list[i + 1] ?? "")) i++;
if (list[i + 1] === "(") i = skipGroup(i + 1, ")");
if (i < 0) return null;
open = true;
} else if (/\s/.test(ch)) {
flush();
if (steps.length) combinator ??= " ";
} else if (ch === ">" || ch === "+" || ch === "~") {
flush();
combinator = ch;
} else if (ch === "(" || ch === ")" || ch === "]") {
return null;
} else {
compound += ch;
open = true;
}
}
return selectors;
}
/** Whether the steps select one of `ancestors` (nearest first), at most steps x ancestors plain matches. */
function matchesAnAncestor(steps: AncestorStep[], ancestors: Element[]): boolean {
let reach = ancestors.map((el) => el.matches(steps[0]!.compound));
for (const step of steps.slice(1)) {
let above = false;
const next = ancestors.map(() => false);
for (let j = ancestors.length - 1; j >= 0; j--) {
const placed = step.child ? reach[j + 1] === true : above;
next[j] = placed && ancestors[j]!.matches(step.compound);
above ||= reach[j]!;
}
reach = next;
}
return reach.includes(true);
}
const MAX_ROOT_ANCESTORS = 256;
const MAX_ANCESTOR_SELECTOR_CHECKS = 100_000;
/**
* Background-image signals on ancestors of the composition root.
* drawElementImage only paints the captured subtree; drawElementService's
@@ -587,28 +687,29 @@ export function detectAncestorBackgroundImage(html: string): boolean {
if (document.documentElement && !ancestors.includes(document.documentElement)) {
ancestors.push(document.documentElement);
}
// Past these bounds the answer is "yes": the baseline capture route paints any background.
if (ancestors.length > MAX_ROOT_ANCESTORS) return true;
let selectorChecks = 0;
// Inline styles on the ancestor chain.
for (const el of ancestors) {
const style = el.getAttribute("style");
if (style && hasBackgroundImageDeclaration(`{${style}}`)) return true;
}
// <style> rules: any rule carrying an image-painting background declaration
// whose selector resolves to an ancestor of the root. Selector matching goes
// through querySelectorAll so class/id/compound selectors on wrappers are
// covered, not just literal `body`/`html`.
// <style> rules whose image background selects an ancestor of the root, by
// Element.matches, so class/id/compound selectors on wrappers count too.
for (const styleEl of document.querySelectorAll("style")) {
const css = styleEl.textContent ?? "";
for (const { parts: rule } of cssRuleMatches(css)) {
const [, selectorList, declarations] = rule;
if (!hasBackgroundImageDeclaration(`{${declarations}}`)) continue;
for (const selector of selectorList.split(",")) {
const sel = selector.trim();
if (!sel || sel.startsWith("@")) continue;
if (/^(?:html|:root)$/i.test(sel)) return true;
if (selectorList.trim().startsWith("@")) continue;
const selectors = ancestorSelectorSteps(selectorList);
if (!selectors) return true;
for (const steps of selectors) {
selectorChecks += steps.length * ancestors.length;
if (selectorChecks > MAX_ANCESTOR_SELECTOR_CHECKS) return true;
try {
for (const matched of document.querySelectorAll(sel)) {
if (ancestors.includes(matched)) return true;
}
if (matchesAnAncestor(steps, ancestors)) return true;
} catch {
// Selector syntax linkedom can't parse (e.g. vendor pseudo) — skip.
}