Files
hyperframes/packages/core/src/runtime/captionOverrides.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

386 lines
14 KiB
TypeScript

// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
import { applyCaptionOverrides } from "./captionOverrides";
function installCaptionOverrideFetch(overrides: unknown) {
vi.stubGlobal("fetch", async () => ({
ok: true,
async json() {
return overrides;
},
}));
}
function installGsapMock() {
const setCalls: Array<{ target: Element; vars: Record<string, unknown> }> = [];
const gsap = {
set(target: Element, vars: Record<string, unknown>) {
setCalls.push({ target, vars });
for (const [key, value] of Object.entries(vars)) {
if (key === "fontSize" && typeof value === "string" && target instanceof HTMLElement) {
target.style.fontSize = value;
}
}
},
killTweensOf() {},
getTweensOf() {
return [];
},
};
Object.defineProperty(window, "gsap", {
configurable: true,
value: gsap,
});
return { setCalls };
}
/** A gsap mock whose `getTweensOf` returns the supplied colour tweens, so classification is testable. */
function installGsapMockWithTweens(tweens: Array<Record<string, unknown>>) {
const gsap = {
set(target: HTMLElement, vars: Record<string, unknown>) {
if (typeof vars.color === "string") target.style.color = vars.color;
},
killTweensOf() {},
getTweensOf() {
return tweens.map((vars, i) => ({ vars, startTime: () => i }));
},
};
Object.defineProperty(window, "gsap", { configurable: true, value: gsap });
return tweens;
}
async function flushCaptionOverrides() {
for (let i = 0; i < 4; i++) {
await Promise.resolve();
}
}
afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
vi.unstubAllGlobals();
document.head.innerHTML = "";
document.body.innerHTML = "";
Reflect.deleteProperty(window, "gsap");
});
describe("applyCaptionOverrides", () => {
it("treats a missing optional sidecar as a silent no-op", async () => {
installGsapMock();
const json = vi.fn();
vi.stubGlobal("fetch", async () => ({ ok: false, status: 404, json }));
const error = vi.spyOn(console, "error").mockImplementation(() => {});
document.body.innerHTML = `<div class="caption-group"><span>Hi</span></div>`;
applyCaptionOverrides();
await flushCaptionOverrides();
expect(json).not.toHaveBeenCalled();
expect(error).not.toHaveBeenCalled();
});
it.each([
["malformed JSON", () => Promise.reject(new SyntaxError("Unexpected token"))],
["a non-array root", () => Promise.resolve({ wordIndex: 0 })],
["a non-object entry", () => Promise.resolve([null])],
])("reports a present sidecar containing %s", async (_shape, json) => {
installGsapMock();
vi.stubGlobal("fetch", async () => ({ ok: true, status: 200, json }));
const error = vi.spyOn(console, "error").mockImplementation(() => {});
document.body.innerHTML = `<div class="caption-group"><span>Hi</span></div>`;
applyCaptionOverrides();
await flushCaptionOverrides();
expect(error).toHaveBeenCalledOnce();
expect(error.mock.calls[0]?.[0]).toContain("caption-overrides.json");
});
it("accepts an empty array as the explicit no-op payload", async () => {
installGsapMock();
installCaptionOverrideFetch([]);
const error = vi.spyOn(console, "error").mockImplementation(() => {});
document.body.innerHTML = `<div class="caption-group"><span>Hi</span></div>`;
applyCaptionOverrides();
await flushCaptionOverrides();
expect(error).not.toHaveBeenCalled();
});
it("reuses existing caption wrappers when overrides are applied more than once", async () => {
const { setCalls } = installGsapMock();
installCaptionOverrideFetch([{ wordIndex: 0, x: 12, y: -4, scale: 1.2 }]);
document.body.innerHTML = `
<div class="caption-group">
<span id="w0">Hello</span>
</div>
`;
applyCaptionOverrides();
await flushCaptionOverrides();
applyCaptionOverrides();
await flushCaptionOverrides();
const group = document.querySelector(".caption-group");
const word = document.getElementById("w0");
const wrappers = group?.querySelectorAll('[data-caption-wrapper="true"]');
const wrapper = wrappers?.item(0);
if (!group || !word || !wrapper) throw new Error("Expected wrapped caption word");
expect(wrappers).toHaveLength(1);
expect(wrapper.parentElement).toBe(group);
expect(word.parentElement).toBe(wrapper);
expect(setCalls.map((call) => call.target)).toEqual([wrapper, wrapper]);
});
it("treats a pre-wrapped word as the wordIndex target, not as another word", async () => {
installGsapMock();
installCaptionOverrideFetch([{ wordIndex: 0, fontSize: 72 }]);
document.body.innerHTML = `
<div class="caption-group">
<span data-caption-wrapper="true">
<span id="w0">Hello</span>
</span>
</div>
`;
applyCaptionOverrides();
await flushCaptionOverrides();
const word = document.getElementById("w0");
const wrapper = word?.parentElement;
if (!(word instanceof HTMLElement) || !wrapper) {
throw new Error("Expected pre-wrapped caption word");
}
expect(word.style.fontSize).toBe("72px");
expect(wrapper.getAttribute("style") ?? "").not.toContain("font-size");
});
it("resolves wordId overrides against the inner word of an existing wrapper", async () => {
const { setCalls } = installGsapMock();
installCaptionOverrideFetch([{ wordId: "w0", x: 16 }]);
document.body.innerHTML = `
<div class="caption-group">
<span data-caption-wrapper="true">
<span id="w0">Hello</span>
</span>
</div>
`;
applyCaptionOverrides();
await flushCaptionOverrides();
const word = document.getElementById("w0");
const wrapper = word?.parentElement;
if (!(word instanceof HTMLElement) || !wrapper) {
throw new Error("Expected pre-wrapped caption word");
}
expect(setCalls).toHaveLength(1);
expect(setCalls[0]?.target).toBe(wrapper);
expect(setCalls[0]?.vars).toEqual({ x: 16 });
});
});
/** Mounts one caption word whose stylesheet (rest) colour is `rest`. */
function mountWord(rest: string) {
document.head.innerHTML = `<style>#w0 { color: ${rest}; }</style>`;
document.body.innerHTML = `<div class="caption-group"><span id="w0">Hi</span></div>`;
}
const SHIPPED_REST = "rgba(255, 255, 255, 0.55)";
describe("caption colour classification", () => {
it.each([
[{ dimColor: "#888", activeColor: "#fff" }, "#fff"],
[{ dimColor: "#888" }, "#ffffff"],
])("lights up a word whose only tween leaves its rest colour, with %o", async (override, lit) => {
// The shape the shipped caption scripts emit: dim by CSS, one tween to white when spoken.
const tweens = installGsapMockWithTweens([{ color: "#ffffff" }]);
installCaptionOverrideFetch([{ wordIndex: 0, ...override }]);
mountWord(SHIPPED_REST);
applyCaptionOverrides();
await flushCaptionOverrides();
expect(tweens[0].color).toBe(lit);
});
it("classifies a return to the rest colour as dim, however the colour is spelled", async () => {
const tweens = installGsapMockWithTweens([
{ color: "white" },
{ color: "rgba(255,255,255,.55)" },
]);
installCaptionOverrideFetch([{ wordIndex: 0, dimColor: "#888", activeColor: "#0f0" }]);
mountWord(SHIPPED_REST);
applyCaptionOverrides();
await flushCaptionOverrides();
expect(tweens.map((tw) => tw.color)).toEqual(["#0f0", "#888"]);
});
it("lights up a fromTo() from a dim colour into the word's own stylesheet colour", async () => {
const tweens = installGsapMockWithTweens([{ color: "#fff", startAt: { color: "#444" } }]);
installCaptionOverrideFetch([{ wordIndex: 0, dimColor: "#888", activeColor: "#0f0" }]);
mountWord("#fff");
applyCaptionOverrides();
await flushCaptionOverrides();
expect(tweens[0].color).toBe("#0f0");
});
it("repaints a word the playhead already lit with its rest colour, so it is dim before it is spoken", async () => {
// Overrides can land after the word lit up; its invalidated tween re-reads its start from this.
const tweens = installGsapMockWithTweens([{ color: "#ffffff" }]);
installCaptionOverrideFetch([{ wordIndex: 0, activeColor: "#0f0" }]);
mountWord(SHIPPED_REST);
document.getElementById("w0")!.style.color = "#ffffff";
applyCaptionOverrides();
await flushCaptionOverrides();
expect(tweens[0].color).toBe("#0f0");
expect(document.getElementById("w0")!.style.color).toBe(SHIPPED_REST);
});
it("leaves the colour a from() tween has rendered on its word", async () => {
// The from() is mid-way (#a2a2a2) when the overrides land; its recorded start stays #444.
installGsapMockWithTweens([{ color: "#444", runBackwards: true }]);
installCaptionOverrideFetch([{ wordIndex: 0, activeColor: "#0f0" }]);
mountWord("#fff");
document.getElementById("w0")!.style.color = "#a2a2a2";
applyCaptionOverrides();
await flushCaptionOverrides();
expect(document.getElementById("w0")!.style.color).toBe("rgb(162, 162, 162)");
});
it("resolves each distinct tween colour once per apply, not once per word", async () => {
installGsapMockWithTweens([{ color: "#ffffff" }, { color: SHIPPED_REST }]);
// An override that leaves the colours as they are, so every word sees the same two.
installCaptionOverrideFetch(
[0, 1, 2].map((wordIndex) => ({ wordIndex, activeColor: "#ffffff" })),
);
document.head.innerHTML = `<style>span { color: ${SHIPPED_REST}; }</style>`;
document.body.innerHTML = `<div class="caption-group"><span></span><span></span><span></span></div>`;
const computed = vi.spyOn(window, "getComputedStyle");
applyCaptionOverrides();
await flushCaptionOverrides();
// One rest colour per word, plus the two tween colours.
expect(computed).toHaveBeenCalledTimes(3 + 2);
});
});
describe("caption state declaration", () => {
it("honours a declared state when dim and active colours are IDENTICAL", async () => {
// Without the declaration both tweens return the word to its rest colour, so both read as dim
// and `activeColor` is silently dropped.
const tweens = installGsapMockWithTweens([
{ color: "#888", data: { captionState: "dim" } },
{ color: "#888", data: { captionState: "active" } },
]);
installCaptionOverrideFetch([{ wordIndex: 0, dimColor: "#111", activeColor: "#eee" }]);
mountWord("#888");
applyCaptionOverrides();
await flushCaptionOverrides();
expect(tweens[0].color).toBe("#111");
expect(tweens[1].color).toBe("#eee");
});
it("invalidates every colour tween on the word, so each re-reads its start from the dimmed word", async () => {
const tween = (color: string, at: number) => ({
vars: { color },
startTime: () => at,
invalidate: vi.fn(),
});
const rendered = [tween("#fff", 0), tween("#222", 1)];
const gsap = { set() {}, killTweensOf() {}, getTweensOf: () => rendered };
Object.defineProperty(window, "gsap", { configurable: true, value: gsap });
installCaptionOverrideFetch([{ wordIndex: 0, dimColor: "#111" }]);
mountWord("#222");
applyCaptionOverrides();
await flushCaptionOverrides();
expect(rendered.map((tw) => [tw.vars.color, tw.invalidate.mock.calls.length])).toEqual([
["#fff", 1],
["#111", 1],
]);
});
it("leaves a from() colour tween as recorded, so it still lights the word up to its own colour", async () => {
const from = {
vars: { color: "#444", runBackwards: true },
startTime: () => 0,
invalidate: vi.fn(),
};
const gsap = { set() {}, killTweensOf() {}, getTweensOf: () => [from] };
Object.defineProperty(window, "gsap", { configurable: true, value: gsap });
installCaptionOverrideFetch([{ wordIndex: 0, dimColor: "#888" }]);
document.body.innerHTML = `<div class="caption-group"><span id="w0">Hi</span></div>`;
applyCaptionOverrides();
await flushCaptionOverrides();
expect(from.invalidate).not.toHaveBeenCalled();
});
it("leaves a word with no colour tween to its own classes under an active-only override", async () => {
const set = vi.fn((el: HTMLElement, vars: Record<string, unknown>) => {
if (vars.color) el.style.color = String(vars.color);
});
Object.defineProperty(window, "gsap", {
configurable: true,
value: { set, killTweensOf() {}, getTweensOf: () => [] },
});
installCaptionOverrideFetch([{ wordIndex: 0, activeColor: "#ff0" }]);
document.body.innerHTML = `<style>.w { color: #888; }</style><div class="caption-group"><span class="w">Hi</span></div>`;
applyCaptionOverrides();
await flushCaptionOverrides();
expect(document.querySelector<HTMLElement>(".w")?.style.color).toBe("");
});
it("prefers the declaration over the rest colour, per tween, when they disagree", async () => {
// The first two are the reverse of what the rest colour infers; the third is undeclared.
const tweens = installGsapMockWithTweens([
{ color: "#222", data: { captionState: "active" } },
{ color: "#fff", data: { captionState: "dim" } },
{ color: "#222" },
]);
installCaptionOverrideFetch([{ wordIndex: 0, dimColor: "#111", activeColor: "#eee" }]);
mountWord("#222");
applyCaptionOverrides();
await flushCaptionOverrides();
expect(tweens.map((tw) => tw.color)).toEqual(["#eee", "#111", "#111"]);
});
it("falls through to the rest colour for a malformed declaration", async () => {
// A typo, a primitive, or a null must never ship a broken composition — an unrecognised value
// is not a state, so classification continues as if nothing was declared.
for (const data of [{ captionState: "typo" }, { captionState: 42 }, null, "notAnObject"]) {
const tweens = installGsapMockWithTweens([{ color: "#222", data }, { color: "#fff" }]);
installCaptionOverrideFetch([{ wordIndex: 0, dimColor: "#dim", activeColor: "#active" }]);
mountWord("#222");
applyCaptionOverrides();
await flushCaptionOverrides();
expect(tweens[0].color).toBe("#dim");
expect(tweens[1].color).toBe("#active");
}
});
});