Skip to content

Commit b94b5bd

Browse files
authored
fix(core): bound timing compiler opening tag scans (#3719)
* fix(core): bound timing compiler opening tag scans * fix(core): bound ID-targeted duration tag scans
1 parent 3610d94 commit b94b5bd

2 files changed

Lines changed: 145 additions & 18 deletions

File tree

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

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,88 @@ describe("inert region scanning", () => {
9595
});
9696
});
9797

98+
describe("opening tag scanning", () => {
99+
it.each([injectDurations, clampDurations])(
100+
"keeps long unclosed ID-targeted tags unchanged in %p",
101+
(write) => {
102+
const html = '<video id="target" '.repeat(100_000);
103+
expect(write(html, [{ id: "target", duration: 3 }])).toBe(html);
104+
},
105+
);
106+
107+
it.each(["target", "a>b", "a<b", "a.b[0]"])(
108+
"preserves substring-ID matches and delimiter characters for %j",
109+
(id) => {
110+
const html = `<video data-id="${id}" data-start="1" data-duration="bad" data-end="4">`;
111+
expect(injectDurations(html, [{ id, duration: 3 }])).toBe(
112+
`<video data-id="${id}" data-start="1" data-duration="3" data-end="4">`,
113+
);
114+
expect(clampDurations(html, [{ id, duration: 3 }])).toBe(
115+
`<video data-id="${id}" data-start="1" data-duration="3" data-end="4">`,
116+
);
117+
},
118+
);
119+
120+
it("leaves similar IDs alone and applies repeated resolutions in order", () => {
121+
const html = '<video id="a.b" data-start="1" data-duration="bad"><video id="axb">';
122+
const resolutions = [
123+
{ id: "a.b", duration: 3 },
124+
{ id: "a.b", duration: 5 },
125+
];
126+
expect(injectDurations(html, resolutions)).toBe(
127+
'<video id="a.b" data-start="1" data-duration="3" data-end="4"><video id="axb">',
128+
);
129+
expect(clampDurations(html, resolutions)).toBe(
130+
'<video id="a.b" data-start="1" data-duration="5"><video id="axb">',
131+
);
132+
});
133+
134+
it.each(["<video", "<audio", "<div", "<section", "<video<audio<div<section"])(
135+
"preserves an unclosed %j suffix after compiling complete media",
136+
(prefix) => {
137+
const media = '<video id="v" data-start="1" data-duration="2">';
138+
const suffix = prefix.repeat(100_000);
139+
expect(compileTimingAttrs(media + suffix)).toEqual({
140+
html: compileTimingAttrs(media).html + suffix,
141+
unresolved: [],
142+
});
143+
expect(extractResolvedMedia(media + suffix).map((el) => el.id)).toEqual(["v"]);
144+
},
145+
);
146+
147+
it("keeps separate media ID counters and video/audio/composition resolution order", () => {
148+
const html = '<audio><VIDEO><section id="scene" data-start="0"><audio>';
149+
const result = compileTimingAttrs(html);
150+
expect(result.unresolved.map((el) => el.id)).toEqual([
151+
"hf-video-0",
152+
"hf-audio-0",
153+
"hf-audio-1",
154+
"scene",
155+
]);
156+
expect(result.html.indexOf('id="hf-audio-0"')).toBeLessThan(
157+
result.html.indexOf('id="hf-video-0"'),
158+
);
159+
});
160+
161+
it("extracts mixed-case media in source order", () => {
162+
const html = '<AUDIO id="a" data-duration="2"><video id="v" data-duration="3">';
163+
expect(extractResolvedMedia(html).map((el) => [el.id, el.tagName, el.duration])).toEqual([
164+
["a", "audio", 2],
165+
["v", "video", 3],
166+
]);
167+
});
168+
169+
it("retains the existing first-greater-than boundary even inside a quoted value", () => {
170+
const html = '<video title="a>b" data-duration="2">';
171+
const result = compileTimingAttrs(html);
172+
expect(result.html).toBe(
173+
'<video title="a id="hf-video-0" data-start="0" data-hf-auto-start="" data-has-audio="true">b" data-duration="2">',
174+
);
175+
expect(result.unresolved.map((el) => el.id)).toEqual(["hf-video-0"]);
176+
expect(extractResolvedMedia(html)).toEqual([]);
177+
});
178+
});
179+
98180
describe("compileTimingAttrs", () => {
99181
it.each(["", " ", "0s", "0abc", "0px", "-1s", "Infinity", "NaN"])(
100182
"does not partially parse invalid literal data-duration=%j",

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

Lines changed: 63 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,60 @@ function maskInertRegions(html: string): { masked: string; restore: (s: string)
154154

155155
// ── Core compilation ─────────────────────────────────────────────────────
156156

157+
function* iterateOpeningTags(html: string, prefix: RegExp) {
158+
let match: RegExpExecArray | null;
159+
while ((match = prefix.exec(html)) !== null) {
160+
const closing = html.indexOf(">", prefix.lastIndex);
161+
// Without a closer, no later prefix can form a complete tag either.
162+
if (closing < 0) break;
163+
const end = closing + 1;
164+
yield { tag: html.slice(match.index, end), index: match.index, end };
165+
prefix.lastIndex = end;
166+
}
167+
}
168+
169+
function replaceOpeningTags(
170+
html: string,
171+
prefix: RegExp,
172+
replace: (tag: string) => string,
173+
): string {
174+
const parts: string[] = [];
175+
let cursor = 0;
176+
for (const { tag, index, end } of iterateOpeningTags(html, prefix)) {
177+
parts.push(html.slice(cursor, index), replace(tag));
178+
cursor = end;
179+
}
180+
parts.push(html.slice(cursor));
181+
return parts.join("");
182+
}
183+
184+
function replaceIdTags(html: string, id: string, replace: (tag: string) => string): string {
185+
const idPattern = new RegExp(`id=["']${escapeRegex(id)}["']`, "gi");
186+
const lastClosing = html.lastIndexOf(">");
187+
const parts: string[] = [];
188+
let cursor = 0;
189+
let candidate = idPattern.exec(html);
190+
for (const { index, end } of iterateOpeningTags(html, /</g)) {
191+
if (index < cursor) continue;
192+
let targetEnd = -1;
193+
while (candidate && candidate.index < end) {
194+
const candidateEnd = candidate.index + candidate[0].length;
195+
if (candidate.index > index && candidateEnd <= lastClosing) targetEnd = candidateEnd;
196+
// Preserve the old greedy prefix's last matching ID, including overlaps.
197+
idPattern.lastIndex = candidate.index + 1;
198+
candidate = idPattern.exec(html);
199+
}
200+
if (targetEnd < 0) continue;
201+
// An authored ID can itself contain '>', so its closer may follow the
202+
// initial span. The lastClosing check guarantees a closing delimiter.
203+
const closing = html.indexOf(">", targetEnd) + 1;
204+
parts.push(html.slice(cursor, index), replace(html.slice(index, closing)));
205+
cursor = closing;
206+
}
207+
parts.push(html.slice(cursor));
208+
return parts.join("");
209+
}
210+
157211
function compileTag(
158212
tag: string,
159213
isVideo: boolean,
@@ -228,24 +282,24 @@ export function compileTimingAttrs(html: string): CompilationResult {
228282
html = masked;
229283

230284
// Process <video ...> tags
231-
html = html.replace(/<video[^>]*>/gi, (match) => {
285+
html = replaceOpeningTags(html, /<video/gi, (match) => {
232286
const { tag, unresolved: u } = compileTag(match, true, () => nextVideoId++);
233287
if (u) unresolved.push(u);
234288
return tag;
235289
});
236290

237291
// Process <audio ...> tags
238-
html = html.replace(/<audio[^>]*>/gi, (match) => {
292+
html = replaceOpeningTags(html, /<audio/gi, (match) => {
239293
const { tag, unresolved: u } = compileTag(match, false, () => nextAudioId++);
240294
if (u) unresolved.push(u);
241295
return tag;
242296
});
243297

244298
// Identify unresolved timed elements (divs with data-start but no data-end/data-duration)
245299
// These are typically compositions whose duration depends on GSAP timelines
246-
html.replace(/<(?:div|section)[^>]*>/gi, (match) => {
247-
if (!hasAttr(match, "data-start")) return match;
248-
if (hasAttr(match, "data-end") || hasAttr(match, "data-duration")) return match;
300+
for (const { tag: match } of iterateOpeningTags(html, /<(?:div|section)/gi)) {
301+
if (!hasAttr(match, "data-start")) continue;
302+
if (hasAttr(match, "data-end") || hasAttr(match, "data-duration")) continue;
249303

250304
const id = getAttr(match, "id");
251305
const compositionSrc = getAttr(match, "data-composition-src");
@@ -260,9 +314,7 @@ export function compileTimingAttrs(html: string): CompilationResult {
260314
compositionSrc: compositionSrc ?? undefined,
261315
});
262316
}
263-
264-
return match;
265-
});
317+
}
266318

267319
return { html: restore(html), unresolved };
268320
}
@@ -277,9 +329,7 @@ export function compileTimingAttrs(html: string): CompilationResult {
277329
export function injectDurations(html: string, resolutions: ResolvedDuration[]): string {
278330
for (const { id, duration } of resolutions) {
279331
// Match the element's opening tag by id
280-
const idPattern = new RegExp(`(<[^>]*id=["']${escapeRegex(id)}["'][^>]*>)`, "gi");
281-
282-
html = html.replace(idPattern, (tag) => {
332+
html = replaceIdTags(html, id, (tag) => {
283333
let result = tag;
284334

285335
// Add data-duration if missing
@@ -314,10 +364,7 @@ export function extractResolvedMedia(html: string): ResolvedMediaElement[] {
314364
const resolved: ResolvedMediaElement[] = [];
315365

316366
html = maskInertRegions(html).masked;
317-
const mediaRegex = /<(?:video|audio)[^>]*>/gi;
318-
let match: RegExpExecArray | null;
319-
while ((match = mediaRegex.exec(html)) !== null) {
320-
const tag = match[0];
367+
for (const { tag } of iterateOpeningTags(html, /<(?:video|audio)/gi)) {
321368
const id = getAttr(tag, "id");
322369
const durationStr = getAttr(tag, "data-duration");
323370
if (!id || durationStr === null) continue;
@@ -351,9 +398,7 @@ export function extractResolvedMedia(html: string): ResolvedMediaElement[] {
351398
*/
352399
export function clampDurations(html: string, clamps: ResolvedDuration[]): string {
353400
for (const { id, duration } of clamps) {
354-
const idPattern = new RegExp(`(<[^>]*id=["']${escapeRegex(id)}["'][^>]*>)`, "gi");
355-
356-
html = html.replace(idPattern, (tag) => {
401+
html = replaceIdTags(html, id, (tag) => {
357402
// Replace data-duration value
358403
tag = tag.replace(/data-duration=["'][^"']*["']/, `data-duration="${duration}"`);
359404

0 commit comments

Comments
 (0)