Skip to content

Commit 50e8d82

Browse files
committed
fix(core): register media ID exports and trim names in linear time
1 parent 4c31715 commit 50e8d82

6 files changed

Lines changed: 147 additions & 98 deletions

File tree

‎packages/core/package-subpaths.json‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,12 @@
517517
"runtime": "./schemas/registry-item.json",
518518
"types": null,
519519
"environments": ["browser", "bun", "node"]
520+
},
521+
"./timeline-asset-id": {
522+
"source": "./src/timelineAssetId.ts",
523+
"runtime": "./dist/timelineAssetId.js",
524+
"types": "./dist/timelineAssetId.d.ts",
525+
"environments": ["browser", "bun", "node"]
520526
}
521527
}
522528
}

‎packages/core/package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -519,9 +519,9 @@
519519
"./schemas/registry-item.json": "./schemas/registry-item.json",
520520
"./timeline-asset-id": {
521521
"bun": "./src/timelineAssetId.ts",
522+
"node": "./dist/timelineAssetId.js",
522523
"import": "./src/timelineAssetId.ts",
523-
"types": "./src/timelineAssetId.ts",
524-
"node": "./dist/timelineAssetId.js"
524+
"types": "./src/timelineAssetId.ts"
525525
}
526526
},
527527
"publishConfig": {

‎packages/core/src/runtime/timeline.test.ts‎

Lines changed: 0 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -640,59 +640,6 @@ describe("collectRuntimeTimelinePayload", () => {
640640
expect(result.clips[0].assetUrl).toBe("https://example.com/hero.jpg");
641641
});
642642

643-
it.each(["video", "audio", "img"])(
644-
"preserves an authored %s id after replacing its source",
645-
(tag) => {
646-
document.body.innerHTML = `<div data-composition-id="main" data-duration="10">
647-
<${tag} id="harbor" class="clip harbor" src="assets/harbor.mp4"
648-
data-start="0" data-duration="5"></${tag}>
649-
</div>`;
650-
expect(collectRuntimeTimelinePayload(defaultParams).clips[0].label).toBe("Harbor");
651-
document.getElementById("harbor")!.setAttribute("src", "assets/library.mp4");
652-
expect(collectRuntimeTimelinePayload(defaultParams).clips[0].label).toBe("Harbor");
653-
},
654-
);
655-
656-
it.each([
657-
["Harbor%20Sunset.mp4", "Harbor Sunset"],
658-
["%E6%B5%B7%E6%B8%AF.mp4", "海港"],
659-
["Harbor%.mp4?v=1.2", "Harbor%"],
660-
])("decodes the generated label from %s", (filename, label) => {
661-
document.body.innerHTML = `<div data-composition-id="main" data-duration="10">
662-
<video src="assets/${filename}" data-start="0" data-duration="5"></video>
663-
</div>`;
664-
expect(collectRuntimeTimelinePayload(defaultParams).clips[0].label).toBe(label);
665-
});
666-
667-
it("decodes a generated filename without a usable document base URL", () => {
668-
const base = document.createElement("base");
669-
base.href = "about:blank";
670-
document.head.appendChild(base);
671-
try {
672-
expect(document.baseURI).toBe("about:blank");
673-
document.body.innerHTML = `<div data-composition-id="main" data-duration="10">
674-
<video src="assets/Harbor%20Sunset.mp4?v=1.2"
675-
data-start="0" data-duration="5"></video>
676-
</div>`;
677-
expect(collectRuntimeTimelinePayload(defaultParams).clips[0].label).toBe("Harbor Sunset");
678-
} finally {
679-
base.remove();
680-
}
681-
});
682-
683-
it.each(["data-timeline-label", "data-label", "aria-label"])(
684-
"preserves an authored %s after replacing a media source",
685-
(attribute) => {
686-
document.body.innerHTML = `<div data-composition-id="main" data-duration="10">
687-
<video id="harbor" src="assets/harbor.mp4" data-start="0" data-duration="5"></video>
688-
</div>`;
689-
const clip = document.getElementById("harbor")!;
690-
clip.setAttribute(attribute, "Opening Shot");
691-
clip.setAttribute("src", "assets/library.mp4");
692-
expect(collectRuntimeTimelinePayload(defaultParams).clips[0].label).toBe("Opening Shot");
693-
},
694-
);
695-
696643
it("uses label from data-timeline-label", () => {
697644
const root = document.createElement("div");
698645
root.setAttribute("data-composition-id", "main");
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { describe, it, expect, afterEach } from "vitest";
2+
import { collectRuntimeTimelinePayload } from "./timeline";
3+
4+
describe("media timeline labels", () => {
5+
const defaultParams = { canonicalFps: 30 };
6+
afterEach(() => {
7+
document.body.innerHTML = "";
8+
});
9+
it.each(["video", "audio", "img"])(
10+
"preserves an authored %s id after replacing its source",
11+
(tag) => {
12+
document.body.innerHTML = `<div data-composition-id="main" data-duration="10">
13+
<${tag} id="harbor" class="clip harbor" src="assets/harbor.mp4"
14+
data-start="0" data-duration="5"></${tag}>
15+
</div>`;
16+
expect(collectRuntimeTimelinePayload(defaultParams).clips[0].label).toBe("Harbor");
17+
document.getElementById("harbor")!.setAttribute("src", "assets/library.mp4");
18+
expect(collectRuntimeTimelinePayload(defaultParams).clips[0].label).toBe("Harbor");
19+
},
20+
);
21+
22+
it.each([
23+
["Harbor%20Sunset.mp4", "Harbor Sunset"],
24+
["%E6%B5%B7%E6%B8%AF.mp4", "海港"],
25+
["Harbor%.mp4?v=1.2", "Harbor%"],
26+
])("decodes the generated label from %s", (filename, label) => {
27+
document.body.innerHTML = `<div data-composition-id="main" data-duration="10">
28+
<video src="assets/${filename}" data-start="0" data-duration="5"></video>
29+
</div>`;
30+
expect(collectRuntimeTimelinePayload(defaultParams).clips[0].label).toBe(label);
31+
});
32+
33+
it("decodes a generated filename without a usable document base URL", () => {
34+
const base = document.createElement("base");
35+
base.href = "about:blank";
36+
document.head.appendChild(base);
37+
try {
38+
expect(document.baseURI).toBe("about:blank");
39+
document.body.innerHTML = `<div data-composition-id="main" data-duration="10">
40+
<video src="assets/Harbor%20Sunset.mp4?v=1.2"
41+
data-start="0" data-duration="5"></video>
42+
</div>`;
43+
expect(collectRuntimeTimelinePayload(defaultParams).clips[0].label).toBe("Harbor Sunset");
44+
} finally {
45+
base.remove();
46+
}
47+
});
48+
49+
it.each(["data-timeline-label", "data-label", "aria-label"])(
50+
"preserves an authored %s after replacing a media source",
51+
(attribute) => {
52+
document.body.innerHTML = `<div data-composition-id="main" data-duration="10">
53+
<video id="harbor" src="assets/harbor.mp4" data-start="0" data-duration="5"></video>
54+
</div>`;
55+
const clip = document.getElementById("harbor")!;
56+
clip.setAttribute(attribute, "Opening Shot");
57+
clip.setAttribute("src", "assets/library.mp4");
58+
expect(collectRuntimeTimelinePayload(defaultParams).clips[0].label).toBe("Opening Shot");
59+
},
60+
);
61+
});
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { describe, expect, it } from "vitest";
2+
import { buildTimelineAssetId } from "./timelineAssetId";
3+
4+
describe("timeline asset ids", () => {
5+
it("trims a long underscore prefix and suffix", () => {
6+
const padding = "_".repeat(20000);
7+
expect(buildTimelineAssetId(`assets/${padding}harbor${padding}.mp4`, [])).toBe("harbor");
8+
});
9+
10+
it("mints the fallback when normalization leaves no name", () => {
11+
expect(buildTimelineAssetId("assets/____.mp4", ["asset", "asset_2"])).toBe("asset_3");
12+
});
13+
});

‎packages/core/src/timelineAssetId.ts‎

Lines changed: 65 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,37 @@
1+
function trimIdUnderscores(value: string): string {
2+
let start = 0;
3+
let end = value.length;
4+
while (value[start] === "_") start += 1;
5+
while (end > start && value[end - 1] === "_") end -= 1;
6+
return value.slice(start, end);
7+
}
8+
19
export function buildTimelineAssetId(assetPath: string, existingIds: Iterable<string>): string {
2-
const baseName = assetPath.split("/").pop() ?? "asset";
10+
const baseName = assetPath.slice(assetPath.lastIndexOf("/") + 1);
311
const normalized = baseName
412
.replace(/\.[^.]+$/, "")
513
.replace(/[^a-zA-Z0-9_-]+/g, "_")
6-
.replace(/^_+|_+$/g, "")
714
.toLowerCase();
8-
const baseId = normalized || "asset";
15+
const baseId = trimIdUnderscores(normalized) || "asset";
916
const ids = new Set(existingIds);
1017
if (!ids.has(baseId)) return baseId;
1118
let suffix = 2;
1219
while (ids.has(`${baseId}_${suffix}`)) suffix += 1;
1320
return `${baseId}_${suffix}`;
1421
}
1522

23+
function referenceChildren(element: Element): Iterable<Element> {
24+
if (element.children.length > 0) return element.children;
25+
if (element.tagName.toLowerCase() !== "template") return [];
26+
const content = (element as HTMLTemplateElement).content;
27+
return content ? content.children : [];
28+
}
29+
1630
function documentElements(document: Document): Element[] {
1731
const elements: Element[] = [];
1832
const visit = (element: Element): void => {
1933
elements.push(element);
20-
for (const child of Array.from(element.children)) visit(child);
21-
if (element.tagName.toLowerCase() === "template" && element.children.length === 0) {
22-
const content = (element as HTMLTemplateElement).content;
23-
if (content) for (const child of Array.from(content.children)) visit(child);
24-
}
34+
for (const child of referenceChildren(element)) visit(child);
2535
};
2636
if (document.documentElement) visit(document.documentElement);
2737
return elements;
@@ -43,47 +53,59 @@ function referencesId(value: string, id: string): boolean {
4353
return decoded.includes(id);
4454
}
4555

56+
function decodeFragment(value: string): string {
57+
const fragment = value.split("#").slice(1).join("#");
58+
try {
59+
return decodeURIComponent(fragment);
60+
} catch {
61+
return fragment;
62+
}
63+
}
64+
65+
function attributeReferencesId(attribute: Attr, id: string): boolean {
66+
if (["id", "data-hf-id"].includes(attribute.name)) return false;
67+
if (attribute.name === "src") return referencesId(decodeFragment(attribute.value), id);
68+
return referencesId(attribute.value, id);
69+
}
70+
71+
function elementReferencesId(element: Element, id: string): boolean {
72+
const code = ["script", "style"].includes(element.tagName.toLowerCase());
73+
if (code && referencesId(element.textContent ?? "", id)) return true;
74+
return Array.from(element.attributes).some((attribute) => attributeReferencesId(attribute, id));
75+
}
76+
77+
type MediaIdentity = { id: string; src: string };
78+
79+
function readMediaIdentity(element: Element): MediaIdentity | null {
80+
const media = ["video", "audio", "img"].includes(element.tagName.toLowerCase());
81+
const src = element.getAttribute("src");
82+
const id = element.getAttribute("id");
83+
if (!media || !src || !id) return null;
84+
return { id, src };
85+
}
86+
87+
function matchesGeneratedId({ id, src }: MediaIdentity): boolean {
88+
const base = buildTimelineAssetId(src, []);
89+
const suffix = id.slice(base.length);
90+
return id === base || (id.startsWith(base) && /^_(?:[2-9]\d*|1\d+)$/.test(suffix));
91+
}
92+
93+
function canRenameMedia(element: Element, identity: MediaIdentity, newSrc: string): boolean {
94+
const authored = ["data-timeline-label", "data-label", "aria-label"].some((name) =>
95+
element.getAttribute(name)?.trim(),
96+
);
97+
return !authored && identity.src !== newSrc && matchesGeneratedId(identity);
98+
}
99+
46100
export function replacementTimelineAssetId(
47101
document: Document,
48102
element: Element,
49103
newSrc: string,
50104
): string | null {
51-
if (!["video", "audio", "img"].includes(element.tagName.toLowerCase())) return null;
52-
const oldSrc = element.getAttribute("src");
53-
const id = element.getAttribute("id");
54-
if (!oldSrc || !id || oldSrc === newSrc) return null;
55-
if (
56-
["data-timeline-label", "data-label", "aria-label"].some((name) =>
57-
element.getAttribute(name)?.trim(),
58-
)
59-
)
60-
return null;
61-
const base = buildTimelineAssetId(oldSrc, []);
62-
const suffix = id.slice(base.length);
63-
if (id !== base && (!id.startsWith(base) || !/^_[2-9]\d*$|^_1\d+$/.test(suffix))) return null;
105+
const identity = readMediaIdentity(element);
106+
if (!identity || !canRenameMedia(element, identity, newSrc)) return null;
64107
const elements = documentElements(document);
65-
for (const other of elements) {
66-
if (
67-
["script", "style"].includes(other.tagName.toLowerCase()) &&
68-
referencesId(other.textContent ?? "", id)
69-
)
70-
return null;
71-
for (const attribute of Array.from(other.attributes)) {
72-
if (attribute.name === "id" || attribute.name === "data-hf-id") continue;
73-
if (attribute.name === "src") {
74-
const fragment = attribute.value.split("#").slice(1).join("#");
75-
let decodedFragment = fragment;
76-
try {
77-
decodedFragment = decodeURIComponent(fragment);
78-
} catch {
79-
decodedFragment = fragment;
80-
}
81-
if (referencesId(decodedFragment, id)) return null;
82-
continue;
83-
}
84-
if (referencesId(attribute.value, id)) return null;
85-
}
86-
}
108+
if (elements.some((other) => elementReferencesId(other, identity.id))) return null;
87109
const ids = elements
88110
.filter((other) => other !== element)
89111
.map((other) => other.getAttribute("id"))

0 commit comments

Comments
 (0)