Files
hyperframes/packages/core/src/runtime/applyVariableBindings.test.ts
T
Miguel Ángel cb8e7995a2 perf(runtime): swap edited scenes into the running preview from a rebuilt document (#4502)
* perf(runtime): swap edited scenes in place from a rebuilt preview document

window.__hfSwapScenes(html) compares the preview manifests. When the rebuilt document differs
only inside existing scenes, it replaces each changed scene's host, styles and scripts, drops
the old scene timelines (nested ones included), reruns the passes boot runs on scene DOM,
releases the old media, rebinds and keeps the playhead. Anything else rejects before touching
the film, so the caller does its full reload.

* fix(runtime): refuse unsafe scene swaps and redraw the swapped scene like a seek

The swap now refuses scenes marked unswappable or with more than one
host, keeps the style order, lets adapters find the new scene, redraws
through the transport seek and rejects when torn down mid-swap.

* fix(runtime): scope swap caption overrides to the swapped scene and swap only manifest pages

Other scenes kept re-dimmed caption words after a swap, and pages without
a scene manifest offered a swap that could only be refused.

* fix(runtime): repaint caption colours that were overridden after their tween rendered

A swapped scene, or a film reloaded mid-way, rendered its caption tweens
before the overrides rewrote their colours, so words kept the old colour.

* fix(runtime): repaint caption colours of a swapped scene the playhead has passed

* refactor(core): cut scene swap comments to what names and types do not say

* fix(runtime): a scene swap keeps other media loaded and waits for new media by reloading

* fix(runtime): a scene swap resolves bound and proxied media before refusing

The new-media check compared the new scene raw src against the live DOM, which variable
bindings and the media proxy have already rewritten. A scene with a customised data-var-src
logo, or a proxied video, was refused on every edit. Both sides now resolve src the same way:
the bound variable value, else the src attribute before any proxy swap, which the proxy now
records where it rewrites the src.

* fix(runtime): a scene swap binds variables only in the swapped scene, before media setup

The swap re-ran variable bindings over the whole document after binding media, so a proxied
video in any scene got its original, undecodable src back and a bound text in an untouched
scene was rewritten. Bindings now run only inside the swapped hosts and before media binding,
as boot does, and the src guard compares against the src the element had before its proxy.

* fix(runtime): a scene swap keeps unchanged video and audio playing

A text edit beside a video rebuilt the video from scratch, so it went blank until it loaded
again. A video or audio in the edited scene whose src matches one in the old scene (same src,
same order among those) is now the old element, moved into the new scene and given the new
element attributes and children, except src and the runtime-owned preload.

* fix(runtime): a scene swap refuses more new-media forms and names the scene

The new-media check missed uppercase URL(), image-set() and @import strings, SVG image href
and xlink:href, and object data, so a new asset could pop in after the swap. Its refusal now
says the media is new to this scene, which is what it checks. The existing inline style url(),
poster and srcset checks get tests of their own.

* fix(runtime): a scene swap loads caption overrides before changing the page

The swap wrote the new scene first and only then fetched caption-overrides.json, so a stalled
request left the preview half swapped when the caller gave up and reloaded. The overrides are
now fetched before the first write and applied from the fetched data. A swap that another swap
finished first while it waited now refuses, since its document is the older one.

* refactor(runtime): keep the proxy src record within the comment share

* fix(runtime): a scene swap keeps media only when the edit left it as written and ungraded

Keeping a live video or audio and copying the new attributes onto it was not the same as a
fresh load: muted only sets the initial state, and a graded video left its grading canvas in
the discarded scene, so it went black. The swap now keeps an element only when its authored
markup, captured before the runtime writes to it, equals the new one, and the grading runtime
says it is not graded. Anything else is rebuilt fresh; the attribute copy is gone.

* fix(runtime): a waiting scene swap refuses after any other swap changed the page

The check compared the scene manifest, which misses a scene changed and changed back while a
captioned swap waited for its overrides; that swap then went on with stale elements and wrote a
wrong manifest. A generation count the swap owns now moves on every page change by a swap, so
any intervening swap makes the waiting one refuse.

* fix(runtime): a scene swap warns about a non-media data-var-src once, as a load does

The new-media scan resolved every bound src through the warning path, so each swap logged the
ignored data-var-src again for the old and the new element. The scan now resolves silently and
only the bindings pass warns, once for the new element.

* refactor(runtime): keep the grading query within the comment share

* fix(runtime): a scene swap replaces each of a scene's styles in its own place

The bundle can now give one scene several style runs separated by another scene's, when its
nested scene comes later in source order. The swap put all new styles before the first old one,
so a later same-named @keyframes moved ahead of the other scene's and the cascade differed from a
fresh load and the render. Each new style now replaces its old counterpart in place, and a scene
whose style count differs is refused before any write.

* test(core): check the bundled stylesheets, not the inlined runtime, for a leftover @import

* fix(runtime): a video kept through a scene swap starts its new tweens from its authored values

* fix(runtime): a from() caption colour tween with an override still lights its word up

* fix(runtime): a scene swap reverts the old timelines, so a kept video shows the edited CSS

* fix(runtime): a caption word with a dim-colour override still lights up when spoken

* fix(runtime): a word whose colour override lands late still looks dim before it is spoken

* fix(runtime): a caption override keeps class highlights and resolves var() colours per word
2026-09-26 13:18:17 +00:00

190 lines
8.0 KiB
TypeScript

/**
* @vitest-environment jsdom
*/
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { applyVariableBindings } from "./applyVariableBindings";
import { getVariables } from "./getVariables";
type TestWindow = Window & {
__hfVariables?: unknown;
__hfVariablesByComp?: Record<string, Record<string, unknown>>;
__hyperframes?: { getVariables?: () => Record<string, unknown> };
};
const win = window as TestWindow;
beforeEach(() => {
win.__hyperframes = { getVariables };
});
afterEach(() => {
delete win.__hfVariables;
delete win.__hfVariablesByComp;
delete win.__hyperframes;
document.documentElement.removeAttribute("data-composition-variables");
document.body.innerHTML = "";
});
function setDeclared(decls: unknown[]): void {
document.documentElement.setAttribute("data-composition-variables", JSON.stringify(decls));
}
describe("applyVariableBindings", () => {
it("sets src from a string variable via data-var-src", () => {
setDeclared([{ id: "hero", type: "image", label: "Hero", default: "default.jpg" }]);
document.body.innerHTML = `
<div data-hf-root data-composition-id="c1">
<img id="img" data-var-src="hero" src="fallback.jpg" />
</div>`;
applyVariableBindings(document);
expect(document.getElementById("img")?.getAttribute("src")).toBe("default.jpg");
});
it("render-time overrides win, and {url} image values resolve", () => {
setDeclared([{ id: "hero", type: "image", label: "Hero", default: "default.jpg" }]);
win.__hfVariables = { hero: { url: "https://cdn/override.png" } };
document.body.innerHTML = `
<div data-hf-root><video data-var-src="hero" src="fallback.mp4"></video></div>`;
applyVariableBindings(document);
expect(document.querySelector("video")?.getAttribute("src")).toBe("https://cdn/override.png");
});
it("keeps the authored src when the variable resolves to nothing", () => {
document.body.innerHTML = `<div data-hf-root><img data-var-src="ghost" src="keep.jpg" /></div>`;
applyVariableBindings(document);
expect(document.querySelector("img")?.getAttribute("src")).toBe("keep.jpg");
});
it("sets text content from a scalar via data-var-text", () => {
setDeclared([{ id: "title", type: "string", label: "Title", default: "Hello" }]);
win.__hfVariables = { title: "Overridden" };
document.body.innerHTML = `<div data-hf-root><h1 data-var-text="title">Authored</h1></div>`;
applyVariableBindings(document);
expect(document.querySelector("h1")?.textContent).toBe("Overridden");
});
it("applies scalar variables as --{id} custom props on the root", () => {
setDeclared([
{ id: "accent", type: "color", label: "Accent", default: "#00C3FF" },
{ id: "count", type: "number", label: "Count", default: 3 },
]);
win.__hfVariables = { accent: "#ff0000" };
document.body.innerHTML = `<div id="root" data-hf-root></div>`;
applyVariableBindings(document);
const root = document.getElementById("root");
expect(root?.style.getPropertyValue("--accent")).toBe("#ff0000");
expect(root?.style.getPropertyValue("--count")).toBe("3");
});
it("applies a font value's family name, and skips other objects", () => {
win.__hfVariables = {
brandFont: { name: "Inter", source: "https://fonts" },
img: { url: "x" },
};
document.body.innerHTML = `<div id="root" data-hf-root></div>`;
applyVariableBindings(document);
const root = document.getElementById("root");
expect(root?.style.getPropertyValue("--brandFont")).toBe("Inter");
expect(root?.style.getPropertyValue("--img")).toBe("");
});
it("preserves element children when binding text on a container", () => {
win.__hfVariables = { title: "Replaced" };
document.body.innerHTML = `
<div data-hf-root>
<h1 data-var-text="title">Hello <em id="kid" class="clip">world</em></h1>
</div>`;
applyVariableBindings(document);
const h1 = document.querySelector("h1");
expect(document.getElementById("kid")?.textContent).toBe("world");
expect(h1?.childNodes[0]?.nodeValue).toBe("Replaced");
});
it("is idempotent across re-application (loader re-apply path)", () => {
win.__hfVariables = { title: "Once" };
document.body.innerHTML = `<div data-hf-root><h1 data-var-text="title">t</h1></div>`;
applyVariableBindings(document);
applyVariableBindings(document);
expect(document.querySelector("h1")?.textContent).toBe("Once");
});
it("resolves sub-composition elements against their scoped values", () => {
win.__hfVariablesByComp = { sub: { label: "Scoped" } };
win.__hfVariables = { label: "TopLevel" };
document.body.innerHTML = `
<div data-hf-root data-composition-id="main">
<p id="top" data-var-text="label">t</p>
<div data-composition-id="sub"><p id="inner" data-var-text="label">s</p></div>
</div>`;
applyVariableBindings(document);
expect(document.getElementById("inner")?.textContent).toBe("Scoped");
expect(document.getElementById("top")?.textContent).toBe("TopLevel");
});
describe("security", () => {
it("refuses data-var-src on a non-media tag (XSS sink)", () => {
win.__hfVariables = { evil: "javascript:alert(document.cookie)" };
document.body.innerHTML = `<div data-hf-root><iframe id="f" data-var-src="evil"></iframe></div>`;
applyVariableBindings(document);
// No src written — the iframe can't be turned into a javascript: executor.
expect(document.getElementById("f")?.hasAttribute("src")).toBe(false);
});
it("refuses an unsafe URL protocol even on an allowed media tag", () => {
win.__hfVariables = {
evil: "javascript:alert(1)",
data: "data:text/html,<script>x</script>",
};
document.body.innerHTML = `
<div data-hf-root>
<img id="a" data-var-src="evil" src="keep.jpg" />
<video id="b" data-var-src="data" src="keep.mp4"></video>
</div>`;
applyVariableBindings(document);
// Authored src preserved; the unsafe value is not applied.
expect(document.getElementById("a")?.getAttribute("src")).toBe("keep.jpg");
expect(document.getElementById("b")?.getAttribute("src")).toBe("keep.mp4");
});
it("allows https, blob, relative, and image data: URLs on media tags", () => {
win.__hfVariables = {
https: "https://cdn/x.png",
rel: "./local.png",
img: "data:image/png;base64,AAAA",
};
document.body.innerHTML = `
<div data-hf-root>
<img id="h" data-var-src="https" src="f.png" />
<img id="r" data-var-src="rel" src="f.png" />
<img id="d" data-var-src="img" src="f.png" />
</div>`;
applyVariableBindings(document);
expect(document.getElementById("h")?.getAttribute("src")).toBe("https://cdn/x.png");
expect(document.getElementById("r")?.getAttribute("src")).toBe("./local.png");
expect(document.getElementById("d")?.getAttribute("src")).toBe("data:image/png;base64,AAAA");
});
it("strips declaration-smuggling characters from a CSS custom property value", () => {
setDeclared([{ id: "accent", type: "string", label: "Accent", default: "red" }]);
win.__hfVariables = { accent: "red; background: url(//evil?data=secret)" };
document.body.innerHTML = `<div id="root" data-hf-root></div>`;
applyVariableBindings(document);
const css = document.getElementById("root")?.style.getPropertyValue("--accent") ?? "";
expect(css).not.toContain(";");
expect(css).not.toContain("{");
expect(css).not.toContain("<");
});
});
});
describe("applyVariableBindings media src", () => {
it("leaves an unchanged src alone, since rewriting it restarts the media's load", () => {
setDeclared([{ id: "clip", type: "string", label: "Clip", default: "clip.mp4" }]);
document.body.innerHTML = '<video data-var-src="clip" src="clip.mp4"></video>';
const video = document.querySelector("video")!;
const writes = vi.spyOn(video, "setAttribute");
applyVariableBindings(document);
expect(writes).not.toHaveBeenCalledWith("src", expect.anything());
});
});