fix(studio): a script edit re-runs in place in a sealed preview, without a reload (#8158)

* fix(studio): a script edit re-runs in place in a sealed preview, without a reload

* fix(studio): a sealed timing edit takes the saved clip and film timing along with its soft reload

* test(studio): the sealed timing test checks a soft reload was sent before reading it

* refactor(studio): the sealed soft reload code passes the quality audit without suppressions

* chore(core): core's size budget makes room for the sealed preview's frame-side editing code

Main already measured 1,841,737 bytes packed against a 1,830,000 budget; the sealed soft reload brings it to 1,855,277. Budgets follow SIZE_BUDGET_HEADROOM: ceil(1,855,277 x 1.05) packed, ceil(4,665,659 x 1.05) unpacked.

* fix(core): a sealed timing edit is not skipped when a nested file's root repeats a clip's id
This commit is contained in:
Miguel Ángel
2026-11-18 21:41:54 +00:00
committed by GitHub
parent 3ae9e7302d
commit b8bb8b3803
22 changed files with 1144 additions and 580 deletions
+6
View File
@@ -470,6 +470,12 @@
"types": "./dist/runtime/editing/patchTween.d.ts",
"environments": ["browser", "bun", "node"]
},
"./runtime/soft-reload": {
"source": "./src/runtime/editing/softReload.ts",
"runtime": "./dist/runtime/editing/softReload.js",
"types": "./dist/runtime/editing/softReload.d.ts",
"environments": ["browser", "bun", "node"]
},
"./runtime/clip-window": {
"source": "./src/runtime/clipWindow.ts",
"runtime": "./dist/runtime/clipWindow.js",
+10
View File
@@ -477,6 +477,12 @@
"import": "./src/runtime/editing/patchTween.ts",
"types": "./src/runtime/editing/patchTween.ts"
},
"./runtime/soft-reload": {
"bun": "./src/runtime/editing/softReload.ts",
"node": "./dist/runtime/editing/softReload.js",
"import": "./src/runtime/editing/softReload.ts",
"types": "./src/runtime/editing/softReload.ts"
},
"./runtime/clip-window": {
"bun": "./src/runtime/clipWindow.ts",
"node": "./dist/runtime/clipWindow.js",
@@ -993,6 +999,10 @@
"import": "./dist/runtime/editing/patchTween.js",
"types": "./dist/runtime/editing/patchTween.d.ts"
},
"./runtime/soft-reload": {
"import": "./dist/runtime/editing/softReload.js",
"types": "./dist/runtime/editing/softReload.d.ts"
},
"./runtime/clip-window": {
"import": "./dist/runtime/clipWindow.js",
"types": "./dist/runtime/clipWindow.d.ts"
@@ -2,6 +2,7 @@
// confidently returns false and the caller reloads. Studio runs it on a frame it can reach,
// a sealed frame on itself through the editing port.
import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading";
import { recordLiveSet } from "./softReload";
export interface SetPatchProps {
x?: number;
@@ -196,6 +197,7 @@ export function applyGlobalSet(
const numeric = finiteNumericProps(props);
if (typeof target.gsap?.set !== "function" || !el || !numeric) return null;
target.gsap.set(el, numeric);
recordLiveSet(el, numeric);
return el;
}
@@ -0,0 +1,178 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { parseSoftReload, softReload, type SoftReloadParams } from "./softReload";
type TestWindow = Window & Record<string, unknown>;
const win = window as TestWindow;
const SCRIPT = `var __timelines = {}; __timelines["main"] = 1;`;
const params = (over: Partial<SoftReloadParams> = {}): SoftReloadParams => ({
script: SCRIPT,
time: 1.5,
sets: [],
authored: [],
timing: [],
...over,
});
const killed = vi.fn();
function preview(markup: string) {
document.body.innerHTML = `${markup}<script>${SCRIPT}</script>`;
const seeks: number[] = [];
win.gsap = {
timeline: () => ({}),
set: (targets: HTMLElement[], vars: Record<string, unknown>) => {
if (vars.clearProps) for (const el of targets) el.removeAttribute("style");
},
};
win.__timelines = { main: { kill: killed, clear: () => {} } };
win.__hfForceTimelineRebind = () => {};
win.__player = { seek: (t: number) => seeks.push(t) };
// The sent script registers on a local: the stub registers what a real run would.
const append = document.body.appendChild.bind(document.body);
document.body.appendChild = <T extends Node>(node: T): T => {
if ((node as Node).nodeName === "SCRIPT") (win.__timelines as Record<string, object>).main = {};
return append(node);
};
return seeks;
}
afterEach(() => {
document.body.innerHTML = "";
for (const key of ["gsap", "__timelines", "__hfForceTimelineRebind", "__player"]) delete win[key];
delete (document.body as Partial<HTMLElement>).appendChild;
killed.mockReset();
});
describe("soft-reload", () => {
it("re-runs the sent script and gives a reset element the authored style Studio sent", async () => {
const seeks = preview(
`<div data-composition-id="main"><div id="a" data-hf-id="h1" style="opacity: 0.3; transform: translateX(50px)"></div></div>`,
);
const el = document.getElementById("a")!;
Object.assign(el, { _gsap: {} });
const reply = await softReload(params({ authored: [["hf:h1", "opacity: 0.8"]] }));
expect(reply).toEqual({ result: "applied" });
expect([el.style.opacity, el.style.transform]).toEqual(["0.8", ""]);
expect(killed).toHaveBeenCalledOnce();
const scripts = [...document.querySelectorAll("script")].map((s) => s.textContent);
expect(scripts).toEqual([`(function(){${SCRIPT}\n})();`]);
expect(seeks).toEqual([1.5]);
});
it("restores what a removed standalone set wrote, from the selector and names Studio sent", async () => {
preview(`<div data-composition-id="main"><div id="a" style="left: 10px"></div></div>`);
const el = document.getElementById("a")!;
el.style.backgroundColor = "red";
await softReload(
params({
sets: [{ selector: "#a", props: ["background-color"] }],
authored: [["#a", "left: 10px"]],
}),
);
expect([el.style.backgroundColor, el.style.left]).toEqual(["", "10px"]);
});
it("changes nothing and refuses when a reset element is written in a file Studio did not send", async () => {
preview(
`<div data-composition-id="main" data-composition-file="main.html"><div data-composition-file="card.html"><div id="b"></div></div></div>`,
);
const el = document.getElementById("b")!;
Object.assign(el, { _gsap: {} });
el.style.opacity = "0.3";
const reply = await softReload(params());
expect(reply).toEqual({ result: "cannot-soft-reload" });
expect(killed).not.toHaveBeenCalled();
expect(el.style.opacity).toBe("0.3");
expect(document.querySelector("script")?.textContent).toBe(SCRIPT);
});
it("refuses a script that registers no timeline key, before touching anything", async () => {
preview(`<div data-composition-id="main"></div>`);
expect(await softReload(params({ script: "gsap.to('#a', {x: 1})" }))).toEqual({
result: "cannot-soft-reload",
});
expect(killed).not.toHaveBeenCalled();
});
});
describe("soft-reload of a timing edit", () => {
const MARKUP = `<div data-composition-id="main" data-hf-id="root" data-duration="5"><div id="clip" data-start="1" data-duration="2" data-hf-autostamped></div></div>`;
it("puts the saved timing on the live clip and the film before the rebind derives its windows", async () => {
preview(MARKUP);
const clip = document.getElementById("clip")!;
const root = document.querySelector("[data-composition-id]")!;
const seen: Array<Array<string | null>> = [];
win.__hfForceTimelineRebind = () =>
seen.push([clip.getAttribute("data-start"), root.getAttribute("data-duration")]);
const timing: SoftReloadParams["timing"] = [
["hf:root", [["data-duration", "8"]]],
[
"#clip",
[
["data-start", "4"],
["data-duration", "2"],
],
],
];
expect(await softReload(params({ timing }))).toEqual({ result: "applied" });
expect(seen).toEqual([["4", "8"]]);
expect(clip.hasAttribute("data-hf-autostamped")).toBe(false);
});
it("changes nothing and refuses when a timed element of the saved file is not in the preview", async () => {
preview(MARKUP);
const clip = document.getElementById("clip")!;
const timing: SoftReloadParams["timing"] = [
["#clip", [["data-start", "4"]]],
["#gone", [["data-start", "1"]]],
];
expect(await softReload(params({ timing }))).toEqual({ result: "cannot-soft-reload" });
expect(clip.getAttribute("data-start")).toBe("1");
expect(killed).not.toHaveBeenCalled();
});
it("times the saved file's clip even when a nested file's root repeats its per-file id", async () => {
preview(
`<div data-composition-file="main.html"><div data-composition-id="main" data-hf-id="root">` +
`<div data-composition-file="card.html"><div data-composition-id="card" data-hf-inner-root data-hf-id="shared"></div></div>` +
`<div id="clip" data-hf-id="shared" data-start="1" data-duration="2"></div></div></div>`,
);
const timing: SoftReloadParams["timing"] = [["hf:shared", [["data-start", "4"]]]];
expect(await softReload(params({ timing }))).toEqual({ result: "applied" });
expect(document.getElementById("clip")!.getAttribute("data-start")).toBe("4");
});
});
describe("parseSoftReload", () => {
it("accepts a bounded request", () => {
const ok = params({ sets: [{ selector: "#a", props: ["width"] }], authored: [["hf:1", ""]] });
expect(parseSoftReload(ok)).toEqual(ok);
});
it.each([
["an extra field", { ...params(), keys: ["main"] }],
["an empty script", params({ script: "" })],
["an oversized script", params({ script: "x".repeat(1_000_001) })],
["a negative time", params({ time: -1 })],
["a non-finite time", params({ time: Number.NaN })],
["a set with an extra field", params({ sets: [{ selector: "#a", props: [], x: 1 } as never] })],
["an authored key of no known kind", params({ authored: [["a", ""]] })],
["an authored entry with three parts", params({ authored: [["#a", "", ""] as never] })],
["a timing attribute that is not timing", params({ timing: [["#a", [["style", "x"]]]] })],
["no timing field", { ...params(), timing: undefined }],
])("refuses %s", (_label, request) => {
expect(parseSoftReload(request)).toBeNull();
});
});
@@ -0,0 +1,605 @@
// A GSAP script edit re-runs the edited composition's script in the live preview, without a reload.
// Studio runs it on a frame it can reach; a sealed frame runs it on itself through the editing port,
// with the script Studio saved and the authored styles Studio read from that file.
import { GSAP_BASE_URL_META, motionPathPluginUrl } from "../../gsapCdn";
import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading";
import { escapeCssString } from "../editingElement";
import { applyAuthoredTiming } from "../../studioPreviewMark";
type TweenLike = {
targets?: () => unknown[];
vars?: Record<string, unknown>;
getChildren?: (deep: boolean) => TweenLike[];
};
export type SoftReloadWindow = Window & {
__timelines?: Record<string, unknown>;
__player?: {
getTime?: () => number;
seek?: (t: number) => void;
isPlaying?: () => boolean;
play?: () => void;
};
__hfForceTimelineRebind?: () => void;
__hfSuppressSceneMutations?: <T>(fn: () => T) => T;
__hfStudioManualEditsApply?: () => void;
// Set while a MotionPathPlugin script is fetched, so overlapping reloads queue no second one.
__hfMotionPathPluginLoading?: boolean;
gsap?: {
version?: string;
registerPlugin?: (...plugins: unknown[]) => unknown;
set?: (targets: Element | Element[], vars: Record<string, unknown>) => void;
};
MotionPathPlugin?: unknown;
};
/** What one standalone `gsap.set` in the outgoing script wrote: its selector and the CSS names. */
export type StandaloneSet = { selector: string; props: string[] };
// "applied": ran, or runs once the MotionPath plugin loads. "verify-failed": ran, its timeline keys
// read empty for now, the live state is right. "cannot-soft-reload": only a full reload fixes it.
export type SoftReloadResult = "applied" | "verify-failed" | "cannot-soft-reload";
export interface SoftReloadInput {
script: string;
/** The time to seek the rebuilt timeline to; the player's own time when absent. */
time?: number;
/** What the outgoing script's standalone sets wrote, which no timeline child records. */
sets: readonly StandaloneSet[];
/** An element's authored style text: null when unknown, undefined when its file is not at hand. */
authoredStyle: (
el: Element,
file: string | null,
ownFile: string | null,
) => string | null | undefined;
/** A sealed timing edit's saved timing, which a reachable preview's commit already patched live. */
timing?: SavedTiming;
}
/** The attributes the runtime derives clip windows and the film's length from. */
export const TIMING_ATTRIBUTES = new Set([
"data-start",
"data-end",
"data-duration",
"data-track-index",
"data-media-start",
"data-playback-start",
"data-playback-rate",
]);
/** `[key, attributes]` per element of the saved file, keyed as `authoredKey` keys a live one. */
export type SavedTiming = Array<[string, Array<[string, string]>]>;
type TimingPlan = Array<[Element, Array<[string, string]>]>;
type LiveTimed = { live: Map<string, Element>; rewritten: Set<string> };
/** The live elements of `ownFile` by key; null when two share a key. */
function liveTimedElements(doc: Document, ownFile: string | null): LiveTimed | null {
const live = new Map<string, Element>();
// The preview rewrites an inlined composition's own root, so the file's timing is not its own.
const rewritten = new Set<string>();
for (const el of doc.querySelectorAll("[data-hf-id], [id]")) {
const key = authoringFile(el) === ownFile ? authoredKey(el) : null;
if (key === null) continue;
if (el.hasAttribute("data-hf-inner-root")) rewritten.add(key);
if (rewritten.has(key)) continue;
if (live.has(key)) return null;
live.set(key, el);
}
return { live, rewritten };
}
/** Each live element of `ownFile` with the saved timing it lacks; null when one is missing or two share a key. */
export function planSavedTiming(
doc: Document,
ownFile: string | null,
timing: SavedTiming,
): TimingPlan | null {
const found = liveTimedElements(doc, ownFile);
if (!found) return null;
const { live, rewritten } = found;
const plan: TimingPlan = [];
for (const [key, attributes] of timing) {
const el = live.get(key);
if (!el && rewritten.has(key)) continue;
if (!el) return null;
const changed = attributes.filter(([name, value]) => el.getAttribute(name) !== value);
if (changed.length > 0) plan.push([el, changed]);
}
return plan;
}
export const applyTimingPlan = (plan: TimingPlan): void => {
for (const [el, attributes] of plan) applyAuthoredTiming(el, attributes);
};
const NESTED_VARS = new Set(["css", "startAt", "keyframes"]);
/** The CSS names a tween's vars write; GSAP's own keys (ease, duration) are not CSS and restore as no-ops. */
export function tweenedProps(vars: unknown): string[] {
if (!vars || typeof vars !== "object") return [];
return Object.entries(vars).flatMap(([key, value]) => [
key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`),
...(NESTED_VARS.has(key) || /^\d|%$/.test(key) ? tweenedProps(value) : []),
]);
}
export function elementTargets(tween: { targets?: () => unknown[] }): Element[] {
return (tween.targets?.() ?? []).filter((t): t is Element =>
Boolean((t as HTMLElement | null)?.style && (t as Node).nodeType),
);
}
// A nested composition's timeline sits inside the root one but only its own script rebuilds it.
function ownTweens(tl: TweenLike, nested: Set<unknown>): TweenLike[] {
return (tl.getChildren?.(false) ?? []).flatMap((child) => {
if (nested.has(child)) return [];
return child.getChildren ? ownTweens(child, nested) : [child];
});
}
// The preview marks each inlined composition's host with its file; the host itself is the parent's.
export function authoringFile(el: Element): string | null {
return (
el.parentElement?.closest("[data-composition-file]")?.getAttribute("data-composition-file") ??
null
);
}
function addProps(targets: Map<Element, Set<string>>, el: Element, props: Iterable<string>): void {
const seen = targets.get(el) ?? new Set<string>();
for (const prop of props) seen.add(prop);
targets.set(el, seen);
}
/** Each element the re-run rebuilds, with the CSS names its killed tweens wrote. */
export function collectResetTargets(
win: { __timelines?: Record<string, unknown> },
doc: Document,
targetKeys: string[],
sets: readonly StandaloneSet[] = [],
): Map<Element, Set<string>> {
const targets = new Map<Element, Set<string>>();
const timelines = (win.__timelines ?? {}) as Record<string, TweenLike | undefined>;
const others = new Set<unknown>(
Object.entries(timelines).flatMap(([key, tl]) => (targetKeys.includes(key) ? [] : [tl])),
);
for (const key of targetKeys) {
try {
for (const tween of ownTweens(timelines[key] ?? {}, others)) {
const props = tweenedProps(tween.vars);
for (const el of elementTargets(tween)) addProps(targets, el, props);
}
} catch {}
}
sweepHeldElements(doc, targetKeys, others, targets);
addLiveSetTargets(doc, targetKeys, targets);
for (const set of sets) {
try {
for (const el of doc.querySelectorAll(set.selector)) addProps(targets, el, set.props);
} catch {}
}
return targets;
}
function tweenTargetsIn(timelines: Set<unknown>): Set<Element> {
const els = new Set<Element>();
for (const tl of timelines) {
try {
for (const tween of (tl as TweenLike | undefined)?.getChildren?.(true) ?? []) {
for (const el of elementTargets(tween)) els.add(el);
}
} catch {}
}
return els;
}
function compositionRoot(doc: Document, key: string): Element | undefined {
return doc.querySelectorAll(`[data-composition-id="${escapeCssString(key)}"]`)[0];
}
export function compositionFile(doc: Document, targetKeys: string[]): string | null {
const root = targetKeys.map((key) => compositionRoot(doc, key)).find(Boolean);
return root?.closest("[data-composition-file]")?.getAttribute("data-composition-file") ?? null;
}
// A standalone gsap.set, or keyframes just removed, leaves GSAP state no timeline child shows.
// The nearest composition root says whose script set it; another timeline's targets stay its own.
function sweepHeldElements(
doc: Document,
targetKeys: string[],
others: Set<unknown>,
targets: Map<Element, Set<string>>,
): void {
const elsewhere = tweenTargetsIn(others);
const roots = new Set<Element | null | undefined>(targetKeys.map((k) => compositionRoot(doc, k)));
roots.delete(undefined);
for (const root of roots) {
for (const el of root ? [root, ...root.querySelectorAll("*")] : []) {
if (targets.has(el) || elsewhere.has(el) || !("_gsap" in el)) continue;
if (el === root || roots.has(el.parentElement?.closest("[data-composition-id]")))
targets.set(el, new Set());
}
}
}
// What a live patch set on each element since its last reload; no script in the preview ran it.
const liveSets = new WeakMap<Document, Map<Element, Set<string>>>();
export function recordLiveSet(el: Element, vars: Record<string, unknown>): void {
const byElement = liveSets.get(el.ownerDocument) ?? new Map<Element, Set<string>>();
liveSets.set(el.ownerDocument, byElement);
addProps(byElement, el, tweenedProps(vars));
}
function addLiveSetTargets(
doc: Document,
targetKeys: string[],
targets: Map<Element, Set<string>>,
): void {
const roots = new Set<Element | null | undefined>(targetKeys.map((k) => compositionRoot(doc, k)));
for (const [el, props] of liveSets.get(doc) ?? []) {
if (!roots.has(el) && !roots.has(el.parentElement?.closest("[data-composition-id]"))) continue;
addProps(targets, el, props);
}
}
function forgetLiveSets(reset: Map<Element, unknown>): void {
for (const el of reset.keys()) liveSets.get(el.ownerDocument)?.delete(el);
}
function isGsapScript(text: string): boolean {
return (
text.includes("gsap.timeline") ||
text.includes("__timelines") ||
text.includes(".to(") ||
text.includes(".set(")
);
}
export function findGsapScriptElements(doc: ParentNode): HTMLScriptElement[] {
const results: HTMLScriptElement[] = [];
for (const script of doc.querySelectorAll<HTMLScriptElement>("script:not([src])")) {
if (isGsapScript(script.textContent || "")) results.push(script);
}
return results;
}
export function timelineKeys(scriptText: string): string[] {
return [...scriptText.matchAll(/__timelines\s*\[\s*["'`]([^"'`]+)["'`]\s*\]/g)]
.map((m) => m[1]!)
.filter((key) => key !== "__proxied");
}
/** The script elements that register one of `keys` on `window.__timelines`. */
export function scriptsRegistering(
scripts: readonly HTMLScriptElement[],
keys: readonly string[],
): HTMLScriptElement[] {
return scripts.filter((script) => {
const text = script.textContent || "";
return keys.some(
(key) => text.includes(`__timelines["${key}"]`) || text.includes(`__timelines['${key}']`),
);
});
}
// The script's own keys, not "any key": a scoped re-run repopulates only its composition, and the
// global map can read empty for a moment right after it.
function verifyTimelinesPopulated(win: SoftReloadWindow, targetKeys: string[]): boolean {
const timelines = win.__timelines;
if (!timelines) return false;
return targetKeys.every((key) => timelines[key] != null);
}
// GSAP masks a folded CSS translate/rotate/scale with `none`, and a tween writes what it animates
// inline; a fresh load has only what the file authors. Opacity has its own restore.
export function restoreAuthoredStyle(
style: CSSStyleDeclaration,
authored: CSSStyleDeclaration | null,
tweened: Set<string>,
): void {
style.transform = authored?.transform ?? "";
if (!authored) return;
for (const prop of ["translate", "rotate", "scale", ...tweened]) {
if (prop === "opacity") continue;
style.setProperty(prop, authored.getPropertyValue(prop), authored.getPropertyPriority(prop));
}
}
// Seek before the rebind: the rebind renders the new timeline at the runtime's scrub position, and a
// seek after it can be a no-op. A seek pauses the player, so an edit made while playing resumes it.
export function finalizeSoftReload(win: SoftReloadWindow, currentTime: number): void {
const wasPlaying = win.__player?.isPlaying?.() === true;
win.__player?.seek?.(currentTime);
win.__hfForceTimelineRebind?.();
win.__hfStudioManualEditsApply?.();
if (wasPlaying) win.__player?.play?.();
}
export function previewMotionPathUrl(doc: Document, version?: string): string {
const baseUrl = doc.head.querySelector<HTMLMetaElement>(
`meta[name="${GSAP_BASE_URL_META}"]`,
)?.content;
return motionPathPluginUrl(version, baseUrl);
}
function runSuppressed(win: SoftReloadWindow, reload: () => void): boolean {
try {
if (win.__hfSuppressSceneMutations) win.__hfSuppressSceneMutations(reload);
else reload();
return true;
} catch (error) {
console.error("[hyperframes] GSAP soft reload threw; a full reload follows", error);
return false;
}
}
type TimelineHandle = TweenLike & { kill?: () => void; clear?: () => void };
function killTimelines(win: SoftReloadWindow, targetKeys: string[]): void {
const timelines = win.__timelines as Record<string, TimelineHandle> | undefined;
if (!timelines) return;
for (const key of targetKeys) {
const tl = timelines[key];
if (!tl) continue;
try {
// kill() keeps the children, and the finalize seek renders this timeline until the rebind swaps it.
tl.clear?.();
tl.kill?.();
} catch {}
delete timelines[key];
}
}
// clearProps flushes GSAP's transform cache, so from() tweens read no stale end values, but it
// also clears the element's own style: save, clear, restore, then put back what the file authors.
function resetTargetStyles(
win: SoftReloadWindow,
targets: Map<Element, Set<string>>,
authored: Map<Element, CSSStyleDeclaration | null>,
): void {
const allTargets = [...targets.keys()];
if (allTargets.length === 0 || !win.gsap?.set) return;
// Another realm's nodes fail instanceof HTMLElement, so style access is duck-typed.
const saved = allTargets.map(
(el) => [el as HTMLElement, (el as HTMLElement).style.cssText] as const,
);
win.gsap.set(allTargets, { clearProps: "all" });
for (const [el, css] of saved) {
const s = el.style;
s.cssText = css;
const source = authored.get(el) ?? null;
restoreAuthoredStyle(s, source, targets.get(el)!);
// The saved cssText holds a mid-tween opacity, which a re-initialized tween would keep as its bound.
const opacity = source ? source.opacity : readStampedAuthoredOpacity(el);
if (opacity !== null) applyAuthoredInlineOpacity(s, opacity);
}
}
// Runs `ready` once the MotionPath plugin is in the frame, or `failed` when it cannot load.
function whenMotionPathLoaded(
win: SoftReloadWindow,
doc: Document,
ready: () => void,
failed: () => void,
): void {
// A load already in flight is the one to wait for; a second plugin script re-flashes the frame.
if (win.__hfMotionPathPluginLoading) {
const started = Date.now();
const poll = win.setInterval(() => {
if (win.MotionPathPlugin) {
win.clearInterval(poll);
ready();
} else if (!win.__hfMotionPathPluginLoading || Date.now() - started > 10000) {
win.clearInterval(poll);
failed();
}
}, 50);
return;
}
win.__hfMotionPathPluginLoading = true;
const pluginScript = doc.createElement("script");
pluginScript.src = previewMotionPathUrl(doc, win.gsap?.version);
pluginScript.onload = () => {
win.__hfMotionPathPluginLoading = false;
ready();
};
// Running the script without the plugin would leave a motionPath tween that cannot play.
pluginScript.onerror = () => {
win.__hfMotionPathPluginLoading = false;
failed();
};
doc.head.appendChild(pluginScript);
}
/** The timeline keys the script owns and the live scripts it replaces; null when which to replace is unclear. */
function reloadScope(
win: SoftReloadWindow,
doc: Document,
script: string,
): { targetKeys: string[]; staleScripts: HTMLScriptElement[] } | null {
if (!script || !win.gsap || !win.__hfForceTimelineRebind) return null;
// Each composition owns one timeline key; tearing down every timeline would revert the others.
const targetKeys = timelineKeys(script);
if (targetKeys.length === 0) return null;
const gsapScripts = findGsapScriptElements(doc);
if (gsapScripts.length === 0) return null;
const staleScripts = scriptsRegistering(gsapScripts, targetKeys);
// Several scripts and none registers these keys: which element to replace is ambiguous.
if (gsapScripts.length > 1 && staleScripts.length === 0) return null;
return { targetKeys, staleScripts };
}
/** Each reset element's authored style; null when one's file is not at hand. */
function readAuthoredStyles(
doc: Document,
targets: Map<Element, Set<string>>,
input: SoftReloadInput,
ownFile: string | null,
): Map<Element, CSSStyleDeclaration | null> | null {
const authored = new Map<Element, CSSStyleDeclaration | null>();
for (const el of targets.keys()) {
const text = input.authoredStyle(el, authoringFile(el), ownFile);
if (text === undefined) return null;
const probe = text === null ? null : doc.createElement("div");
probe?.setAttribute("style", text!);
authored.set(el, probe?.style ?? null);
}
return authored;
}
// Re-runs the script in place of the live one registering the same `__timelines` keys, tearing down
// only those timelines. A promise only while it waits for the MotionPath plugin.
export function softReloadFrame(
win: SoftReloadWindow,
doc: Document,
input: SoftReloadInput,
): SoftReloadResult | Promise<SoftReloadResult> {
const { script } = input;
const scope = reloadScope(win, doc, script);
if (!scope) return "cannot-soft-reload";
const { targetKeys, staleScripts } = scope;
const currentTime = input.time ?? win.__player?.getTime?.() ?? 0;
const targets = collectResetTargets(win, doc, targetKeys, input.sets);
const ownFile = compositionFile(doc, targetKeys);
const authored = readAuthoredStyles(doc, targets, input, ownFile);
if (!authored) return "cannot-soft-reload";
const timing = input.timing ? planSavedTiming(doc, ownFile, input.timing) : [];
if (timing === null) return "cannot-soft-reload";
let deferred: ((result: SoftReloadResult) => void) | null = null;
let pending: Promise<SoftReloadResult> | null = null;
let builtDom = false;
const executeScript = () => {
if (win.MotionPathPlugin && win.gsap?.registerPlugin)
win.gsap.registerPlugin(win.MotionPathPlugin);
const s = doc.createElement("script");
s.textContent = `(function(){${script}\n})();`;
const before = doc.body.querySelectorAll("*").length + 1;
doc.body.appendChild(s);
// A script that builds DOM builds it again on every run; only a full load starts from the file.
// Not seen: text-only writes, nodes put in the head or a shadow root, and nodes added later.
builtDom = doc.body.querySelectorAll("*").length > before;
finalizeSoftReload(win, currentTime);
deferred?.(builtDom ? "cannot-soft-reload" : "applied");
};
const doReload = () => {
applyTimingPlan(timing);
killTimelines(win, targetKeys);
resetTargetStyles(win, targets, authored);
forgetLiveSets(targets);
for (const stale of staleScripts) stale.remove();
const needsMotionPath = /motionPath\s*[:{]/.test(script);
if (!needsMotionPath || win.MotionPathPlugin || !win.gsap) return executeScript();
pending = new Promise<SoftReloadResult>((resolve) => (deferred = resolve));
whenMotionPathLoaded(win, doc, executeScript, () => deferred?.("cannot-soft-reload"));
};
if (!runSuppressed(win, doReload) || builtDom) return "cannot-soft-reload";
if (pending) return pending;
return verifyTimelinesPopulated(win, targetKeys) ? "applied" : "verify-failed";
}
export const MAX_SOFT_RELOAD_SCRIPT = 1_000_000;
const MAX_SETS = 1_000;
const MAX_SET_PROPS = 64;
const MAX_SELECTOR_LENGTH = 2_000;
const MAX_AUTHORED = 10_000;
const MAX_AUTHORED_KEY = 512;
const MAX_AUTHORED_STYLE = 16_384;
const MAX_TIMED = 10_000;
const MAX_TIMING_VALUE = 64;
export type SoftReloadParams = {
script: string;
time: number;
sets: StandaloneSet[];
/** `[key, style]`: key `hf:<data-hf-id>` or `#<id>`, style the element's authored style text. */
authored: Array<[string, string]>;
/** Empty unless a timing edit: the saved file's timing, applied before the re-run's rebind. */
timing: SavedTiming;
};
const isRecord = (value: unknown): value is Record<string, unknown> =>
Object.prototype.toString.call(value) === "[object Object]";
const boundedString = (value: unknown, max: number): value is string =>
typeof value === "string" && value.length <= max;
function parseSet(value: unknown): StandaloneSet | null {
if (!isRecord(value) || Object.keys(value).sort().join() !== "props,selector") return null;
const { selector, props } = value;
if (!boundedString(selector, MAX_SELECTOR_LENGTH) || selector.length === 0) return null;
if (!Array.isArray(props) || props.length > MAX_SET_PROPS) return null;
return props.every((p) => boundedString(p, 64)) ? { selector, props: props as string[] } : null;
}
const isAuthoredEntry = (entry: unknown): entry is [string, string] =>
Array.isArray(entry) &&
entry.length === 2 &&
boundedString(entry[0], MAX_AUTHORED_KEY) &&
/^(hf:|#)./.test(entry[0]) &&
boundedString(entry[1], MAX_AUTHORED_STYLE);
const isTimingAttribute = (value: unknown): value is [string, string] =>
Array.isArray(value) &&
value.length === 2 &&
TIMING_ATTRIBUTES.has(value[0]) &&
boundedString(value[1], MAX_TIMING_VALUE);
const isTimedEntry = (entry: unknown): entry is SavedTiming[number] =>
Array.isArray(entry) &&
entry.length === 2 &&
boundedString(entry[0], MAX_AUTHORED_KEY) &&
/^(hf:|#)./.test(entry[0]) &&
Array.isArray(entry[1]) &&
entry[1].length <= TIMING_ATTRIBUTES.size &&
entry[1].every(isTimingAttribute);
export function parseSavedTiming(value: unknown): SavedTiming | null {
const ok = Array.isArray(value) && value.length <= MAX_TIMED && value.every(isTimedEntry);
return ok ? (value as SavedTiming) : null;
}
export function parseSoftReload(params: unknown): SoftReloadParams | null {
const fields = "authored,script,sets,time,timing";
if (!isRecord(params) || Object.keys(params).sort().join() !== fields) return null;
const { script, time, sets, authored } = params;
const timing = parseSavedTiming(params.timing);
if (!timing) return null;
if (!boundedString(script, MAX_SOFT_RELOAD_SCRIPT) || script.length === 0) return null;
if (typeof time !== "number" || !Number.isFinite(time) || time < 0) return null;
if (!Array.isArray(sets) || sets.length > MAX_SETS) return null;
if (!Array.isArray(authored) || authored.length > MAX_AUTHORED) return null;
const parsedSets = sets.map(parseSet);
if (!parsedSets.every(Boolean) || !authored.every(isAuthoredEntry)) return null;
return { script, time, sets: parsedSets as StandaloneSet[], authored, timing };
}
/** The key Studio files an element's authored style under: its hf-id, else its id. */
export function authoredKey(el: Element): string | null {
const hfId = el.getAttribute("data-hf-id");
if (hfId) return `hf:${hfId}`;
return el.id ? `#${el.id}` : null;
}
/** The frame re-running its own script: only elements of the saved file have authored styles to use. */
export async function softReload(params: SoftReloadParams): Promise<{ result: SoftReloadResult }> {
const styles = new Map(params.authored);
const result = await softReloadFrame(window as SoftReloadWindow, document, {
script: params.script,
time: params.time,
sets: params.sets,
timing: params.timing,
authoredStyle: (el, file, ownFile) => {
if (file !== ownFile) return undefined;
const key = authoredKey(el);
return key === null ? null : (styles.get(key) ?? null);
},
});
return { result };
}
@@ -202,6 +202,7 @@ describe("installEditingAgent", () => {
"edit-element",
"gsap-set",
"patch-tweens",
"soft-reload",
],
},
});
@@ -527,6 +528,31 @@ describe("installEditingAgent", () => {
});
});
it("re-runs a sent script through the port, and refuses a request carrying anything extra", async () => {
const script = `var __timelines = {}; __timelines["main"] = 1;`;
document.body.innerHTML = `<div data-composition-id="main"></div><script>${script}</script>`;
const frame = window as unknown as Record<string, unknown>;
Object.assign(frame, { gsap: { set: () => {} }, __timelines: { main: {} } });
frame.__hfForceTimelineRebind = () => {};
const port = connectedPort();
const params = { script, time: 0, sets: [], authored: [], timing: [] };
const extra = { ...params, keys: ["main"] };
expect(await ask(port, { v: 1, id: 1, kind: "soft-reload", params: extra })).toMatchObject({
id: 1,
ok: false,
});
expect(document.querySelector("script")?.textContent).toBe(script);
// The sent script registers on a local, so the frame reads its timeline empty for now.
expect(await ask(port, { v: 1, id: 2, kind: "soft-reload", params })).toMatchObject({
id: 2,
ok: true,
result: { result: "verify-failed" },
});
expect(document.querySelector("script")?.textContent).toBe(`(function(){${script}\n})();`);
for (const key of ["gsap", "__timelines", "__hfForceTimelineRebind"]) delete frame[key];
});
it("answers computed styles for the element a selector names", async () => {
document.body.innerHTML = `<p id="title" style="color: rgb(1, 2, 3); opacity: 0.5">Hi</p>
<canvas data-hf-preview-video-canvas style="opacity: 0.25"></canvas>
@@ -41,6 +41,7 @@ import { motionPathHome } from "./editing/motionPathHome";
import { cropLift } from "./editing/cropLift";
import { gsapSet } from "./editing/gsapSet";
import { patchTweens } from "./editing/patchTween";
import { softReload } from "./editing/softReload";
import {
getLogicalOpacity,
markedForStudio,
@@ -224,6 +225,7 @@ const HANDLERS: Handlers = {
"edit-element": editElement,
"gsap-set": gsapSet,
"patch-tweens": patchTweens,
"soft-reload": softReload,
};
function serve(port: MessagePort): void {
@@ -105,6 +105,7 @@ describe("createEditingPortClient", () => {
"edit-element",
"gsap-set",
"patch-tweens",
"soft-reload",
],
});
} finally {
+8
View File
@@ -30,6 +30,11 @@ import type { GsapSnapshot } from "./editing/gsapSnapshot";
import type { MotionPathFrameHome } from "./editing/motionPathHome";
import { parseGsapSet, type GsapSetParams } from "./editing/gsapSet";
import { parsePatchTweens, type PatchTweensParams } from "./editing/patchTween";
import {
parseSoftReload,
type SoftReloadParams,
type SoftReloadResult,
} from "./editing/softReload";
import type { EditingLayer } from "./editingLayers";
import type { RuntimeTimelineMessage } from "./types";
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
@@ -180,6 +185,7 @@ export const EDITING_REQUEST_KINDS = [
"edit-element",
"gsap-set",
"patch-tweens",
"soft-reload",
] as const;
export type EditingRequestKind = (typeof EDITING_REQUEST_KINDS)[number];
@@ -316,6 +322,7 @@ export interface EditingRequests {
"edit-element": { params: EditElementParams; result: EditElementResult };
"gsap-set": { params: GsapSetParams; result: { applied: boolean } };
"patch-tweens": { params: PatchTweensParams; result: { patched: boolean } };
"soft-reload": { params: SoftReloadParams; result: { result: SoftReloadResult } };
}
export type EditingParams<K extends EditingRequestKind> = EditingRequests[K]["params"];
export type EditingResult<K extends EditingRequestKind> = EditingRequests[K]["result"];
@@ -526,6 +533,7 @@ const PARAM_PARSERS: {
"edit-element": parseEditElement,
"gsap-set": parseGsapSet,
"patch-tweens": parsePatchTweens,
"soft-reload": parseSoftReload,
};
/** Validates one request off the wire. Never throws: anything unusable becomes a typed error. */
@@ -10,7 +10,6 @@ import {
type PatchTarget,
type RuntimeTweenChange,
} from "@hyperframes/core/runtime/patch-tween";
import { recordLiveSet } from "../utils/softReloadTargets";
export type { RuntimeTweenChange, SetPatchProps } from "@hyperframes/core/runtime/patch-tween";
@@ -46,9 +45,7 @@ export function patchRuntimeTweenInPlace(
const target = reachablePreview(iframe);
if (change.kind !== "global-set")
return patchTween(target, selector, change, compositionId, deferSeek);
const el = applyGlobalSet(target, selector, change.props);
if (el) recordLiveSet(el, { ...change.props });
return el !== null;
return applyGlobalSet(target, selector, change.props) !== null;
} catch {
return false;
}
@@ -0,0 +1,51 @@
// @vitest-environment happy-dom
import { expect, it, vi } from "vitest";
const { previewRequest } = vi.hoisted(() => ({ previewRequest: vi.fn() }));
vi.mock("../player/lib/previewChannel", async (importOriginal) => ({
...(await importOriginal<typeof import("../player/lib/previewChannel")>()),
previewFrameOpaque: () => true,
previewRequest,
}));
import { finishTimelineTimingFallback } from "./timelineTimingSync";
const script = (at: number) =>
`var tl = gsap.timeline({ paused: true }); tl.to("#clip", { x: 100, duration: 1 }, ${at}); window.__timelines["main"] = tl;`;
// The move's attribute write landed first, so the GSAP rewrite's own pair differs only in its script.
const file = (at: number) =>
`<div data-composition-id="main" data-duration="6"><div id="clip" data-start="3" data-duration="2"></div></div><script>${script(at)}</script>`;
it("takes a sealed timing edit's saved clip and film timing to the frame with the in-place sync", async () => {
previewRequest.mockImplementation(async (_iframe: unknown, kind: string) =>
kind === "soft-reload" ? { result: "applied" } : { result: "unchanged" },
);
const reloadPreview = vi.fn();
await finishTimelineTimingFallback({
iframe: document.createElement("iframe"),
projectId: null,
reloadPreview,
gsapMutation: async () => ({
mutated: true,
scriptText: script(3),
before: file(1),
after: file(3),
}),
onGsapError: vi.fn(),
rebindWhenUnmutated: true,
});
await new Promise((resolve) => setTimeout(resolve, 0));
const softReload = previewRequest.mock.calls.find(([, kind]) => kind === "soft-reload");
if (!softReload) throw new Error("no soft-reload request was sent");
const timing = (softReload[2] as { timing: Array<[string, string[][]]> }).timing;
expect(timing.map(([, attributes]) => attributes)).toEqual([
[["data-duration", "6"]],
[
["data-start", "3"],
["data-duration", "2"],
],
]);
expect(reloadPreview).not.toHaveBeenCalled();
});
@@ -147,6 +147,8 @@ async function syncTimingEditPreview(
onAsyncFailure: reloadPreview,
currentTimeOverride: currentTime(),
authoredHtml: outcome.after,
previousHtml: outcome.before,
timingEdit: true,
nestedFiles,
});
if (result === "cannot-soft-reload") reloadPreview();
@@ -66,11 +66,16 @@ function syncDragPreview(res: MutationResult, reloadPreview: () => void) {
applyPreviewSync(FAKE_IFRAME, res, dragOptions(), reloadPreview);
}
function expectSoftReloadedWith(onAsyncFailure: unknown, authoredHtml: string | undefined) {
function expectSoftReloadedWith(
onAsyncFailure: unknown,
authoredHtml: string | undefined,
previousHtml?: string,
) {
expect(applySoftReload).toHaveBeenCalledWith(FAKE_IFRAME, "SCRIPT", {
onAsyncFailure,
currentTimeOverride: 0,
authoredHtml,
previousHtml,
});
}
@@ -707,7 +712,7 @@ describe("runCommit — instantPatch wiring", () => {
);
});
expectSoftReloadedWith(deps.reloadPreview, "AFTER");
expectSoftReloadedWith(deps.reloadPreview, "AFTER", "BEFORE");
expect(deps.reloadPreview).not.toHaveBeenCalled();
});
@@ -902,7 +907,7 @@ describe("runCommit — instantPatch wiring", () => {
});
expect(fetch).toHaveBeenCalledTimes(1);
expectSoftReloadedWith(deps.reloadPreview, "AFTER");
expectSoftReloadedWith(deps.reloadPreview, "AFTER", "BEFORE");
expect(deps.reloadPreview).not.toHaveBeenCalled();
expect(deps.onCacheInvalidate).toHaveBeenCalledTimes(1);
});
@@ -917,7 +922,7 @@ describe("runCommit — instantPatch wiring", () => {
});
expect(patchRuntimeTweenInPlace).not.toHaveBeenCalled();
expectSoftReloadedWith(deps.reloadPreview, "AFTER");
expectSoftReloadedWith(deps.reloadPreview, "AFTER", "BEFORE");
expect(deps.reloadPreview).not.toHaveBeenCalled();
});
@@ -221,6 +221,7 @@ function softReloadOrEscalate(
origin: "preview_sync" | "sdk_refresh",
authoredHtml?: string,
nestedFiles?: Map<string, string> | null,
previousHtml?: string,
): void {
// Seek the rebuilt timeline to the studio's own authoritative scrub position,
// not the iframe's raw `__player.getTime()` — see the comment in
@@ -230,6 +231,7 @@ function softReloadOrEscalate(
onAsyncFailure: reloadPreview,
currentTimeOverride: currentTime,
authoredHtml,
previousHtml,
nestedFiles,
});
if (result === "applied") return;
@@ -286,6 +288,7 @@ export function applyPreviewSync(
"preview_sync",
result.after ?? undefined,
nestedFiles,
result.before,
);
} else {
reloadPreview();
@@ -1,4 +1,9 @@
import { ensureHfIds, isCompositionTemplate } from "@hyperframes/parsers/hf-ids";
import {
authoredKey,
TIMING_ATTRIBUTES,
type SavedTiming,
} from "@hyperframes/core/runtime/soft-reload";
import {
PREVIEW_ONLY_ATTRS,
PREVIEW_VIDEO_CANVAS_ATTR,
@@ -35,6 +40,38 @@ export function findAuthoredElement(doc: Document, live: Element): Element | nul
return live.id ? findByAttribute(doc, "id", live.id) : null;
}
// Both keys an element's style is filed under: its hf-id and its id.
function styleKeys(el: Element): string[] {
const hfId = el.getAttribute("data-hf-id");
return [hfId ? `hf:${hfId}` : "", el.id ? `#${el.id}` : ""].filter(Boolean);
}
export function authoredStyles(html: string): Array<[string, string]> {
const styles = new Map<string, string>();
const elements = searchRoots(parseSavedSource(html)).flatMap((root) => [
...root.querySelectorAll("[data-hf-id], [id]"),
]);
for (const el of elements) {
for (const key of styleKeys(el)) {
if (!styles.has(key)) styles.set(key, el.getAttribute("style") ?? "");
}
}
return [...styles];
}
export function savedTiming(html: string): SavedTiming {
const timing: SavedTiming = [];
for (const el of parseSavedSource(html).querySelectorAll("[data-hf-id], [id]")) {
const key = authoredKey(el);
const attributes = [...TIMING_ATTRIBUTES].flatMap((name): Array<[string, string]> => {
const value = el.getAttribute(name);
return value === null ? [] : [[name, value]];
});
if (key && attributes.length > 0) timing.push([key, attributes]);
}
return timing;
}
export function findAuthoredElementById(doc: Document, live: Element): Element | null {
return live.id ? findByAttribute(doc, "id", live.id) : null;
}
+1 -5
View File
@@ -46,8 +46,4 @@ export function setElementGsapSize(element: HTMLElement, width: number, height:
}
/** The targets CSSPlugin styles: not plain objects (the runtime's filler) or XML-namespace elements. */
export function elementTargets(tween: { targets?: () => unknown[] }): Element[] {
return (tween.targets?.() ?? []).filter((t): t is Element =>
Boolean((t as HTMLElement | null)?.style && (t as Node).nodeType),
);
}
export { elementTargets } from "@hyperframes/core/runtime/soft-reload";
@@ -0,0 +1,89 @@
// @vitest-environment happy-dom
import { beforeEach, expect, it, vi } from "vitest";
const { previewRequest } = vi.hoisted(() => ({ previewRequest: vi.fn() }));
vi.mock("../player/lib/previewChannel", async (importOriginal) => ({
...(await importOriginal<typeof import("../player/lib/previewChannel")>()),
previewFrameOpaque: () => true,
previewRequest,
}));
import { applySoftReload } from "./gsapSoftReload";
const iframe = document.createElement("iframe");
const SAVED = `window.__timelines["main"] = gsap.timeline(); gsap.set("#b", { x: 5 });`;
const file = (script: string) =>
`<div data-composition-id="main"><div id="a" style="opacity: 0.5"></div><div id="b"></div></div><script>${script}</script>`;
const PREVIOUS = file(
`window.__timelines["main"] = gsap.timeline(); gsap.set("#a", { width: 300 });`,
);
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
beforeEach(() => {
previewRequest.mockReset();
delete (window as { __ran?: boolean }).__ran;
});
it("sends one request built only from the saved files: the saved script, its authored styles, what the old one set", () => {
previewRequest.mockResolvedValue({ result: "applied" });
const result = applySoftReload(iframe, SAVED, {
authoredHtml: file(SAVED),
previousHtml: PREVIOUS,
currentTimeOverride: 2,
onAsyncFailure: vi.fn(),
});
expect(result).toBe("applied");
expect(previewRequest).toHaveBeenCalledOnce();
const [, kind, params] = previewRequest.mock.calls[0]!;
expect(kind).toBe("soft-reload");
expect(params.script).toBe(SAVED);
expect(params.time).toBe(2);
expect(params.sets).toEqual([{ selector: "#a", props: ["width"] }]);
expect(params.authored).toEqual(
expect.arrayContaining([
["#a", "opacity: 0.5"],
["#b", ""],
]),
);
expect(Object.keys(params).sort()).toEqual(["authored", "script", "sets", "time", "timing"]);
expect(params.timing).toEqual([]);
});
it.each([
["refuses", { result: "cannot-soft-reload" }, 1],
["does not answer", null, 1],
["answers with a script to run", { result: "applied", script: "window.__ran = true" }, 1],
["answers with an unknown result", { result: "window.__ran = true" }, 1],
["applied it", { result: "applied" }, 0],
["reads its timelines empty for now", { result: "verify-failed" }, 0],
])(
"reloads the preview only when the frame did not apply it: the frame %s",
async (_l, reply, reloads) => {
previewRequest.mockResolvedValue(reply);
const reload = vi.fn();
applySoftReload(iframe, SAVED, {
authoredHtml: file(SAVED),
previousHtml: PREVIOUS,
currentTimeOverride: 0,
onAsyncFailure: reload,
});
await settle();
expect(reload).toHaveBeenCalledTimes(reloads);
expect((window as { __ran?: boolean }).__ran).toBeUndefined();
},
);
it("asks for a full reload without sending anything when the file before the write is not known", () => {
const result = applySoftReload(iframe, SAVED, {
authoredHtml: file(SAVED),
currentTimeOverride: 0,
});
expect(result).toBe("cannot-soft-reload");
expect(previewRequest).not.toHaveBeenCalled();
});
@@ -284,7 +284,7 @@ window.__timelines["root"] = tl;`;
expect(contentWindow.__timelines.root).toBeDefined();
});
it("falls back to the async plugin load when MotionPathPlugin is genuinely absent", () => {
it("falls back to the async plugin load when MotionPathPlugin is genuinely absent", async () => {
const head = document.createElement("div");
const appendedScripts: HTMLScriptElement[] = [];
const realHeadAppend = head.appendChild.bind(head);
@@ -313,12 +313,13 @@ window.__timelines["root"] = tl;`;
// it escalates via onAsyncFailure so the caller can full-reload to recover,
// and clears the in-flight loading flag.
appendedScripts[0]!.onerror?.(new Event("error"));
await Promise.resolve();
expect(onAsyncFailure).toHaveBeenCalledTimes(1);
expect(contentWindow.__hfForceTimelineRebind).not.toHaveBeenCalled();
expect(contentWindow.__hfMotionPathPluginLoading).toBe(false);
});
it("loads a missing soft-reload plugin from the iframe mirror and reports its failure", () => {
it("loads a missing soft-reload plugin from the iframe mirror and reports its failure", async () => {
const { iframe, contentWindow } = buildMockIframe({
gsap: { timeline: vi.fn(), registerPlugin: vi.fn(), version: "3.14.2" },
});
@@ -334,6 +335,7 @@ window.__timelines["root"] = tl;`;
"http://localhost:8080/vendor/npm/gsap@3.14.2/dist/MotionPathPlugin.min.js",
);
plugin?.onerror?.(new Event("error"));
await Promise.resolve();
expect(onAsyncFailure).toHaveBeenCalledTimes(1);
expect(contentWindow.__hfForceTimelineRebind).not.toHaveBeenCalled();
expect(contentWindow.__hfMotionPathPluginLoading).toBe(false);
+96 -405
View File
@@ -1,70 +1,39 @@
import { parseGsapScript } from "@hyperframes/parsers/gsap-parser";
import { GSAP_BASE_URL_META, motionPathPluginUrl } from "@hyperframes/core/gsap-cdn";
import { findAuthoredElement } from "./authoredSource";
import {
applyAuthoredInlineOpacity,
readStampedAuthoredOpacity,
} from "@hyperframes/core/color-grading";
import {
authoringFile,
collectResetTargets,
compositionFile,
fileDocs,
forgetLiveSets,
} from "./softReloadTargets";
finalizeSoftReload,
findGsapScriptElements,
previewMotionPathUrl,
restoreAuthoredStyle,
scriptsRegistering,
softReloadFrame,
timelineKeys,
type SoftReloadResult,
type SoftReloadWindow,
} from "@hyperframes/core/runtime/soft-reload";
import { authoredStyles, findAuthoredElement, savedTiming } from "./authoredSource";
import { fileDocs, standaloneSets } from "./softReloadTargets";
import { previewFrameOpaque, previewRequest } from "../player/lib/previewChannel";
type IframeWindow = Window & {
__timelines?: Record<string, { kill?: () => void; pause?: () => void }>;
__player?: {
getTime?: () => number;
seek?: (t: number) => void;
isPlaying?: () => boolean;
play?: () => void;
};
__hfForceTimelineRebind?: () => void;
__hfSuppressSceneMutations?: <T>(fn: () => T) => T;
__hfStudioManualEditsApply?: () => void;
// Set while a MotionPathPlugin <script> is being fetched, so overlapping soft
// reloads (each needing the plugin) don't queue duplicate plugin scripts that
// re-flash the iframe. Cleared once the plugin loads or errors.
__hfMotionPathPluginLoading?: boolean;
__playerReady?: boolean;
gsap?: {
version?: string;
timeline?: (...args: unknown[]) => unknown;
registerPlugin?: (...plugins: unknown[]) => unknown;
set?: (targets: Element | Element[], vars: Record<string, unknown>) => void;
globalTimeline?: { getChildren?: (deep: boolean) => Array<{ kill?: () => void }> };
};
MotionPathPlugin?: unknown;
};
export {
findGsapScriptElements,
scriptsRegistering,
timelineKeys,
type SoftReloadResult,
} from "@hyperframes/core/runtime/soft-reload";
type IframeWindow = SoftReloadWindow & { __playerReady?: boolean };
/**
* Pre-load + register MotionPathPlugin ONCE in the preview iframe so
* `win.MotionPathPlugin` is reliably set before any studio edit. Called from the
* preview bootstrap (NLELayout's onIframeLoad) on every iframe load.
*
* Why: when a user ADDS a motion path to a composition that never used one, the
* plugin isn't loaded, so the first soft reload takes the async `<script src>`
* load path — the timeline is killed/cleared while the CDN load is pending,
* producing a visible flash. Loading it eagerly here means the soft reload runs
* synchronously and `needsMotionPath && !win.MotionPathPlugin` never fires for
* studio edits.
*
* Idempotent (no-ops once the plugin is present or already loading) and
* defensive: without gsap it waits for the runtime's ready, and it tolerates a CDN failure
* (the soft-reload async fallback in applySoftReload still covers that case).
* Pre-load and register MotionPathPlugin once per preview load (NLELayout's onIframeLoad), so
* adding the first motion path does not wait for the CDN mid-reload and flash. Idempotent; without
* gsap it waits for the runtime's ready, and a CDN failure is left to the soft reload's own load.
*/
// At most one preview waits for its runtime; a newer load replaces it, so a frame that never boots is not kept alive.
let pendingReadyRetry: ((event: MessageEvent) => void) | null = null;
function previewMotionPathUrl(doc: Document, version?: string): string {
const baseUrl = doc.head.querySelector<HTMLMetaElement>(
`meta[name="${GSAP_BASE_URL_META}"]`,
)?.content;
return motionPathPluginUrl(version, baseUrl);
}
export function ensureMotionPathPluginLoaded(iframe: HTMLIFrameElement | null): void {
if (pendingReadyRetry) window.removeEventListener("message", pendingReadyRetry);
pendingReadyRetry = null;
@@ -118,30 +87,10 @@ export function ensureMotionPathPluginLoaded(iframe: HTMLIFrameElement | null):
}
}
function isGsapScript(text: string): boolean {
return (
text.includes("gsap.timeline") ||
text.includes("__timelines") ||
text.includes(".to(") ||
text.includes(".set(")
);
}
export function findGsapScriptElements(doc: ParentNode): HTMLScriptElement[] {
const results: HTMLScriptElement[] = [];
const scripts = doc.querySelectorAll<HTMLScriptElement>("script:not([src])");
for (const script of scripts) {
if (isGsapScript(script.textContent || "")) results.push(script);
}
return results;
}
/**
* Extract the GSAP timeline script text from a serialized HTML document, for
* feeding into applySoftReload. Returns null when zero or multiple GSAP scripts
* are present (ambiguous — a serialized snapshot can't say WHICH script a
* single rewritten text corresponds to; caller should fall back to a full
* reload), matching applySoftReload's own single-script requirement.
* are present: a snapshot cannot say which script one rewritten text replaces.
*/
export function extractGsapScriptText(html: string): string | null {
const doc = new DOMParser().parseFromString(html, "text/html");
@@ -150,144 +99,31 @@ export function extractGsapScriptText(html: string): string | null {
return scripts[0].textContent || null;
}
/**
* Confirm the re-run repopulated the timeline(s) this script owns. We check the
* EXPECTED keys (the ones the script re-registers), not merely "any key": a
* scoped soft reload only re-runs ONE composition, so the right success signal is
* "my target keys are back", not "the global map is non-empty". Checking the
* exact keys avoids the transient false where the global map momentarily looks
* empty right after the re-run — the spurious trigger of the full-remount fallback.
*/
function verifyTimelinesPopulated(win: IframeWindow, targetKeys: string[]): boolean {
const timelines = win.__timelines;
if (!timelines) return false;
if (targetKeys.length > 0) {
return targetKeys.every((key) => timelines[key] != null);
}
return Object.keys(timelines).filter((k) => k !== "__proxied").length > 0;
}
// GSAP masks a folded CSS translate/rotate/scale with `none`, and a tween writes what it animates
// inline; a fresh load has only what the file authors. Opacity has its own restore.
function restoreAuthoredStyle(
style: CSSStyleDeclaration,
authored: CSSStyleDeclaration | null,
tweened: Set<string>,
) {
style.transform = authored?.transform ?? "";
if (!authored) return;
for (const prop of ["translate", "rotate", "scale", ...tweened]) {
if (prop === "opacity") continue;
style.setProperty(prop, authored.getPropertyValue(prop), authored.getPropertyPriority(prop));
}
}
function runSuppressed(win: IframeWindow, reload: () => void): boolean {
try {
if (win.__hfSuppressSceneMutations) win.__hfSuppressSceneMutations(reload);
else reload();
return true;
} catch (error) {
console.error("[Studio] GSAP soft reload threw; falling back to a full reload", error);
return false;
}
}
/**
* Outcome of a soft-reload attempt. Callers must distinguish PERMANENT failures
* (the preview genuinely can't be soft-updated — escalate to a full reload) from
* the TRANSIENT post-run empty-timeline window (the live `gsap.set` already shows
* the correct value — do NOT escalate; a remount would re-flash the WebGL context
* and revert subcomposition keyframes):
*
* - `"applied"` — the script ran (or is deferred to the async plugin
* load and WILL run). The preview is/will be correct.
* - `"verify-failed"` — TRANSIENT: the re-run happened but `__timelines`
* momentarily read empty. Live state is correct → do
* NOT escalate. (Was a bare `false` before.)
* - `"cannot-soft-reload"` — PERMANENT/STRUCTURAL: no gsap runtime, no rebind
* hook, no scopable target key, or no script element
* to replace. The preview is stale/broken → escalate.
*
* The async MotionPath-plugin load failure is still surfaced via
* `onAsyncFailure` (it fires after this returned `"applied"` optimistically).
*/
export type SoftReloadResult = "applied" | "verify-failed" | "cannot-soft-reload";
/**
* Replace the GSAP script in the live iframe without reloading. This preserves
* the WebGL context and shader transition cache.
*
* Scoped to root-document GSAP scripts only — scripts inside `<template>`
* elements (sub-compositions) are not visible to `querySelectorAll` and will
* fall back to a full iframe reload.
*
* Returns `"cannot-soft-reload"` (caller should full-reload) when:
* - The iframe or GSAP runtime isn't available
* - The rebind hook isn't installed
* - The script registers no scopable `__timelines` key
* - No GSAP script element exists in the live DOM
* - The synchronous re-run threw
*
* Returns `"verify-failed"` when the re-run executed but the target timeline
* keys read empty in the transient post-run window (live state is still correct).
*
* `onAsyncFailure` is invoked when the soft reload was deferred to load the
* MotionPath plugin (so this returned `"applied"` optimistically) but the plugin
* `<script>` then failed to load — the iframe is left without the plugin and the
* caller should perform a full reload to recover. It never fires on the
* synchronous paths.
*/
export interface SoftReloadOptions {
/** Escalation for async plugin-load failures (e.g. MotionPath CDN error). */
/** Escalation for a failure found after this returned, such as a MotionPath CDN error. */
onAsyncFailure?: () => void;
/** Seek target for the rebuilt timeline; defaults to the iframe player time. */
currentTimeOverride?: number;
/** After-write file HTML — the primary source for the authored opacity and transform restore. */
/** After-write file HTML: the source of the authored opacity and transform restore. */
authoredHtml?: string;
/** The same file before the write; a sealed preview needs it for what the outgoing script set. */
previousHtml?: string;
/** A timing edit, whose saved timing a sealed preview takes along: no commit could patch it live. */
timingEdit?: boolean;
/** Other composition files a reset element is written in, by path; null when one could not be read. */
nestedFiles?: Map<string, string> | null;
}
/**
* The soft reload's finalization step, shared with the rebind-only preview sync
* below: seek → force timeline rebind → reapply studio manual edits.
*
* Seek BEFORE rebind: __hfForceTimelineRebind's own internal force-render
* (see init.ts) renders the freshly-created timeline at whatever the
* runtime's internal scrub position already is, not at whatever we pass
* here afterward — a redundant seek() call after rebind can be a GSAP
* no-op if the timeline already reports being at that time internally.
*/
function finalizeSoftReload(win: IframeWindow, currentTime: number): void {
// A seek pauses the player, so an edit made while playing resumes it once the timeline is rebuilt.
const wasPlaying = win.__player?.isPlaying?.() === true;
win.__player?.seek?.(currentTime);
win.__hfForceTimelineRebind?.();
win.__hfStudioManualEditsApply?.();
if (wasPlaying) win.__player?.play?.();
}
/**
* Run ONLY applySoftReload's finalization (seek → __hfForceTimelineRebind →
* manual-edits reapply) against the live iframe — executing NO scripts and
* touching NO script elements. `__hfForceTimelineRebind` makes the runtime
* re-derive every clip's visibility window from the live DOM's `data-start` /
* `data-duration` attributes (init.ts: bindRootTimelineIfAvailable +
* syncTimedElementVisibility), so this is the flashless sync for a timing edit
* whose attributes were already live-patched and whose GSAP scripts are
* unchanged (`window.__timelines` still valid). Works for compositions with
* zero GSAP scripts too — the rebind hook is installed unconditionally by the
* runtime, independent of any animation library.
*
* Returns false when the iframe/runtime hook is unavailable or the run threw —
* the caller should escalate to a full reload.
* Seek, force the timeline rebind and reapply the manual edits, running no script. The rebind
* re-derives every clip window from the live DOM's timing attributes, so this syncs a timing edit
* whose attributes are already live and whose scripts are unchanged. False when it cannot run.
*/
export function applySoftReloadFinalization(
iframe: HTMLIFrameElement | null,
currentTime: number,
): boolean {
const win = iframe?.contentWindow as IframeWindow | null;
const win = iframe?.contentWindow as SoftReloadWindow | null;
try {
if (!win?.__hfForceTimelineRebind) return false;
if (win.__hfSuppressSceneMutations) {
@@ -315,7 +151,7 @@ const animatedBy = (doc: Document, scriptText: string): Set<Element> => {
/** Authored style back on the elements the restored script stops animating, before a reload lands. */
export function repaintDroppedTweenStyle(
win: IframeWindow,
win: SoftReloadWindow,
doc: Document,
authored: Document,
targetKeys: string[],
@@ -335,224 +171,79 @@ export function repaintDroppedTweenStyle(
}
}
export function timelineKeys(scriptText: string): string[] {
return [...scriptText.matchAll(/__timelines\s*\[\s*["'`]([^"'`]+)["'`]\s*\]/g)]
.map((m) => m[1]!)
.filter((key) => key !== "__proxied");
const outgoingScripts = (doc: ParentNode, scriptText: string): string[] =>
scriptsRegistering(findGsapScriptElements(doc), timelineKeys(scriptText)).map(
(script) => script.textContent ?? "",
);
const SOFT_RELOAD_RESULTS = new Set<unknown>(["applied", "verify-failed", "cannot-soft-reload"]);
/** The frame's reply is data: anything but exactly `{ result }` with a known result counts as a refusal. */
function sealedSoftReloadResult(reply: unknown): SoftReloadResult {
if (typeof reply !== "object" || reply === null) return "cannot-soft-reload";
const keys = Object.keys(reply);
const { result } = reply as { result?: unknown };
if (keys.length !== 1 || !SOFT_RELOAD_RESULTS.has(result)) return "cannot-soft-reload";
return result as SoftReloadResult;
}
/** The live script elements that register one of `keys` on `window.__timelines`. */
export function scriptsRegistering(
scripts: readonly HTMLScriptElement[],
keys: readonly string[],
): HTMLScriptElement[] {
return scripts.filter((script) => {
const text = script.textContent || "";
return keys.some(
(key) => text.includes(`__timelines["${key}"]`) || text.includes(`__timelines['${key}']`),
);
// Everything sent comes from the files Studio saved, never from the frame; the reply only says whether it applied.
function softReloadSealed(
iframe: HTMLIFrameElement,
scriptText: string,
{
authoredHtml,
previousHtml,
currentTimeOverride,
onAsyncFailure,
timingEdit,
}: SoftReloadOptions,
): SoftReloadResult {
if (authoredHtml === undefined || previousHtml === undefined || currentTimeOverride === undefined)
return "cannot-soft-reload";
const previous = new DOMParser().parseFromString(previousHtml, "text/html");
void previewRequest(iframe, "soft-reload", {
script: scriptText,
time: currentTimeOverride,
sets: standaloneSets(outgoingScripts(previous, scriptText)),
authored: authoredStyles(authoredHtml),
timing: timingEdit ? savedTiming(authoredHtml) : [],
}).then((reply) => {
if (sealedSoftReloadResult(reply) === "cannot-soft-reload") onAsyncFailure?.();
});
return "applied";
}
// fallow-ignore-next-line complexity
// Swaps the GSAP script without a reload, keeping the WebGL context. "cannot-soft-reload" asks for a
// full reload; a failure found later (no MotionPath plugin, a sealed refusal) calls `onAsyncFailure`.
export function applySoftReload(
iframe: HTMLIFrameElement | null,
scriptText: string,
options: SoftReloadOptions = {},
): SoftReloadResult {
const { onAsyncFailure, currentTimeOverride, authoredHtml } = options;
if (!iframe || !scriptText) return "cannot-soft-reload";
const win = iframe.contentWindow as IframeWindow | null;
if (previewFrameOpaque(iframe)) return softReloadSealed(iframe, scriptText, options);
const win = iframe.contentWindow as SoftReloadWindow | null;
const doc = iframe.contentDocument;
if (!win || !doc) return "cannot-soft-reload";
if (!win.gsap || !win.__hfForceTimelineRebind) return "cannot-soft-reload";
// Without the file an element is written in, only a full load restores it.
if (options.nestedFiles === null) return "cannot-soft-reload";
// Which composition(s) does this script rebuild? A soft reload re-runs ONE
// composition's GSAP script, which re-registers its own window.__timelines[key].
// In a multi-composition preview (top-level + inlined subcompositions) each
// composition owns a separate timeline keyed by its id, and they're all children
// of the global timeline — so tearing down ALL of them (or the global timeline's
// children) and re-running a single script wipes every OTHER composition,
// reverting its edits. Scope the teardown to the keys THIS script re-registers.
const targetKeys = timelineKeys(scriptText);
if (targetKeys.length === 0) return "cannot-soft-reload"; // can't scope safely → full reload
const gsapScripts = findGsapScriptElements(doc);
if (gsapScripts.length === 0) return "cannot-soft-reload";
// Remove only the stale script element(s) that registered a target key; one we
// can't match in the doc is left alone (re-running appends a fresh element).
const staleScripts = scriptsRegistering(gsapScripts, targetKeys);
// Multiple GSAP scripts exist but none registers a key this script owns — we
// can't identify which element to replace (ambiguous, matching
// extractGsapScriptText's single-script requirement). Escalate to a full reload
// rather than killing the target timeline and appending an orphan script.
if (gsapScripts.length > 1 && staleScripts.length === 0) return "cannot-soft-reload";
// Prefer the caller-supplied scrub position (the studio's own authoritative
// currentTime, e.g. usePlayerStore) over the iframe's raw `__player.getTime()`:
// the two can desync (a keyframe-node drag parks the playhead via the store
// BEFORE this reload's async commit resolves, and the iframe's own GSAP clock
// doesn't reliably reflect that yet), which re-seeks the freshly rebuilt
// timeline to the wrong frame and leaves the element (and its overlay)
// rendered at a stale/unrelated position.
const currentTime = currentTimeOverride ?? win.__player?.getTime?.() ?? 0;
// Track whether the MotionPath async path was taken. When it is, the script
// executes inside pluginScript.onload — after applySoftReload has already
// returned. We optimistically return true because the script WILL execute
// once the plugin loads; the alternative (returning false) would trigger a
// full iframe reload that destroys the very WebGL context we're preserving.
let deferredToAsync = false;
let builtDom = false;
// Authored-opacity resolution for the restore loop below. Three-state:
// "0.98" — the element's authored inline opacity
// "" — resolved, and the element has NO authored inline opacity
// null — unknown (no authored HTML supplied, element not found in it,
// and no runtime parse-time stamp)
// The just-written file (`authoredHtml`) is the current truth; the runtime's
// parse-time stamp (data-hf-authored-opacity, installAuthoredOpacityCapture)
// covers elements the file lookup can't resolve. Parsed lazily, at most once.
const docFor = fileDocs(compositionFile(doc, targetKeys), authoredHtml, options.nestedFiles);
const findAuthoredStyle = (el: HTMLElement): CSSStyleDeclaration | null => {
const fileDoc = docFor(authoringFile(el));
const source = fileDoc ? findAuthoredElement(fileDoc, el) : null;
// The parsed file lives in this realm, so instanceof holds here, unlike for the iframe nodes below.
return source instanceof HTMLElement || source instanceof SVGElement ? source.style : null;
};
const readAuthoredOpacity = (el: HTMLElement): string | null =>
findAuthoredStyle(el)?.opacity ?? readStampedAuthoredOpacity(el);
// fallow-ignore-next-line complexity
const doReload = () => {
const timelines = win.__timelines;
const targets = collectResetTargets(
win,
doc,
targetKeys,
staleScripts.map((script) => script.textContent ?? ""),
);
// Kill ONLY the target composition's timeline(s) — leaving every other
// composition's timeline (and its children on the global timeline) intact.
if (timelines) {
for (const key of targetKeys) {
const tl = timelines[key] as { kill?: () => void; clear?: () => void } | undefined;
if (!tl) continue;
try {
// kill() keeps the children, and the finalize seek renders this timeline until the rebind swaps it.
tl.clear?.();
tl.kill?.();
} catch {}
delete timelines[key];
}
}
// Reset GSAP's internal transform cache so from() tweens don't read stale
// end values. `clearProps: "all"` is needed to flush the cache, but it also
// nukes the element's CSS base (position, width, height, etc.) from the
// HTML `style=""` attribute. Save → clear → restore → what GSAP wrote, from the file.
const allTargets = [...targets.keys()];
if (allTargets.length > 0 && win.gsap?.set) {
// Iframe-realm nodes: instanceof HTMLElement fails across realms, so style access is duck-typed.
const saved = allTargets.map(
(el) => [el as HTMLElement, (el as HTMLElement).style.cssText] as const,
);
win.gsap.set(allTargets, { clearProps: "all" });
for (const [el, css] of saved) {
const s = el.style;
s.cssText = css;
restoreAuthoredStyle(s, findAuthoredStyle(el), targets.get(el)!);
// The restored cssText carries RUNTIME opacity, not authored opacity:
// a mid-flight tween's interpolated value. The re-run script's tweens re-initialize
// against it — a from() captures it as its END, a to() as its START —
// turning the transient into the tween's permanent bound (dimmed or
// invisible elements). Put the AUTHORED inline opacity back; the seek
// below re-renders the correct animated value either way.
const authored = readAuthoredOpacity(el);
if (authored !== null) applyAuthoredInlineOpacity(s, authored);
}
}
forgetLiveSets(targets);
for (const script of staleScripts) script.remove();
const executeScript = () => {
if (win.MotionPathPlugin && win.gsap?.registerPlugin) {
win.gsap.registerPlugin(win.MotionPathPlugin);
}
const s = doc.createElement("script");
s.textContent = `(function(){${scriptText}\n})();`;
const ownScriptNode = 1;
const before = doc.body.querySelectorAll("*").length + ownScriptNode;
doc.body.appendChild(s);
// A script that builds DOM builds it again on every run; only a full load starts from the file.
// Not seen: text-only writes, nodes put in the head or a shadow root, nodes added
// later, and a builder that removes its old nodes first (which needs no full load).
builtDom = doc.body.querySelectorAll("*").length > before;
if (builtDom && deferredToAsync) onAsyncFailure?.();
finalizeSoftReload(win, currentTime);
};
const needsMotionPath = /motionPath\s*[:{]/.test(scriptText);
if (needsMotionPath && !win.MotionPathPlugin && win.gsap) {
deferredToAsync = true;
// A prior soft reload is already fetching the plugin — don't queue a second
// <script> (it re-flashes the iframe). Defer THIS script's execution until
// the in-flight load settles via a one-shot poll. The bootstrap guard is
// the single source of truth for "plugin fetch in progress".
if (win.__hfMotionPathPluginLoading) {
const started = Date.now();
const poll = win.setInterval(() => {
if (win.MotionPathPlugin) {
win.clearInterval(poll);
executeScript();
} else if (!win.__hfMotionPathPluginLoading || Date.now() - started > 10000) {
// The in-flight load finished without registering the plugin (errored)
// or we timed out — recover with a full reload instead of running a
// script that references a missing plugin.
win.clearInterval(poll);
onAsyncFailure?.();
}
}, 50);
return;
}
win.__hfMotionPathPluginLoading = true;
const pluginScript = doc.createElement("script");
pluginScript.src = previewMotionPathUrl(doc, win.gsap?.version);
pluginScript.onload = () => {
win.__hfMotionPathPluginLoading = false;
executeScript();
};
pluginScript.onerror = () => {
// The plugin failed to load. Running executeScript() now would leave the
// iframe with a motionPath tween referencing a missing plugin while the
// caller already thinks the soft reload succeeded. Signal failure so the
// caller can full-reload (which fetches the plugin fresh) instead.
win.__hfMotionPathPluginLoading = false;
onAsyncFailure?.();
};
doc.head.appendChild(pluginScript);
return;
}
executeScript();
};
const run = () => runSuppressed(win, doReload);
// The synchronous re-run threw or built DOM a second time: the preview is now
// genuinely broken (no timeline, or duplicated nodes). Escalate to a full reload.
if (!run() || builtDom) return "cannot-soft-reload";
// When MotionPath needs async loading, the script hasn't executed yet —
// skip the __timelines check and report success optimistically (the script
// WILL run on plugin load; onAsyncFailure covers the CDN-error case).
if (deferredToAsync) return "applied";
// The re-run executed. If the target keys read back, we're done; otherwise
// it's the TRANSIENT empty-timeline window (live state is correct) — surfaced
// as "verify-failed" so callers know NOT to escalate.
return verifyTimelinesPopulated(win, targetKeys) ? "applied" : "verify-failed";
if (!win || !doc || options.nestedFiles === null) return "cannot-soft-reload";
let docFor: ((file: string | null) => Document | null) | null = null;
const result = softReloadFrame(win, doc, {
script: scriptText,
time: options.currentTimeOverride,
sets: standaloneSets(outgoingScripts(doc, scriptText)),
authoredStyle: (el, file, ownFile) => {
docFor ??= fileDocs(ownFile, options.authoredHtml, options.nestedFiles);
const fileDoc = docFor(file);
const source = fileDoc ? findAuthoredElement(fileDoc, el) : null;
return source ? (source.getAttribute("style") ?? "") : null;
},
});
if (typeof result === "string") return result;
void result.then((settled) => {
if (settled !== "applied") options.onAsyncFailure?.();
});
return "applied";
}
/** Other composition files for a soft reload: undefined when none are needed, null when a read failed. */
@@ -19,7 +19,7 @@ import {
diffSoftReloadableRestore,
showRestoreInPlace,
} from "./gsapUndoRestore";
import { recordLiveSet } from "./softReloadTargets";
import { recordLiveSet } from "@hyperframes/core/runtime/soft-reload";
import { applyPatch } from "./sourcePatcher";
import { beginStudioManualEditGesture } from "../components/editor/manualEdits";
import { studioManualEditSavesIn } from "../components/editor/manualEditsDom";
+10 -157
View File
@@ -1,166 +1,19 @@
// Which elements a GSAP soft reload resets, what their tweens wrote, and which file writes each.
// What a GSAP soft reload needs from the saved files; the reset itself lives in core.
import { parseGsapScript } from "@hyperframes/parsers/gsap-parser";
import { tweenedProps, type StandaloneSet } from "@hyperframes/core/runtime/soft-reload";
import { parseSavedSource } from "./authoredSource";
import { elementTargets } from "./elementGsap";
type TweenLike = {
targets?: () => unknown[];
vars?: Record<string, unknown>;
getChildren?: (deep: boolean) => TweenLike[];
};
const NESTED_VARS = new Set(["css", "startAt", "keyframes"]);
// The CSS names a tween's vars write; GSAP's own keys (ease, duration) are not CSS and restore as no-ops.
function tweenedProps(vars: unknown): string[] {
if (!vars || typeof vars !== "object") return [];
return Object.entries(vars).flatMap(([key, value]) => [
key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`),
...(NESTED_VARS.has(key) || /^\d|%$/.test(key) ? tweenedProps(value) : []),
]);
}
// A nested composition's timeline sits inside the root one but only its own script rebuilds it.
function ownTweens(tl: TweenLike, nested: Set<unknown>): TweenLike[] {
return (tl.getChildren?.(false) ?? []).flatMap((child) => {
if (nested.has(child)) return [];
return child.getChildren ? ownTweens(child, nested) : [child];
});
}
// The preview marks each inlined composition's host with its file; the host itself is the parent's.
export function authoringFile(el: Element): string | null {
return (
el.parentElement?.closest("[data-composition-file]")?.getAttribute("data-composition-file") ??
null
/** What each standalone `gsap.set` in the outgoing scripts wrote, which no timeline child records. */
export function standaloneSets(outgoingScripts: readonly string[]): StandaloneSet[] {
return outgoingScripts.flatMap((script) =>
script.includes("gsap.set(")
? parseGsapScript(script)
.animations.filter((set) => set.method === "set" && set.global)
.map((set) => ({ selector: set.targetSelector, props: tweenedProps(set.properties) }))
: [],
);
}
function addTweenTargets(tween: TweenLike, targets: Map<Element, Set<string>>): void {
const props = tweenedProps(tween.vars);
for (const el of elementTargets(tween)) {
const seen = targets.get(el) ?? new Set<string>();
for (const prop of props) seen.add(prop);
targets.set(el, seen);
}
}
/** Each element the re-run rebuilds, with the CSS names its killed tweens wrote. */
export function collectResetTargets(
win: { __timelines?: Record<string, unknown> },
doc: Document,
targetKeys: string[],
outgoingScripts: readonly string[] = [],
): Map<Element, Set<string>> {
const targets = new Map<Element, Set<string>>();
const timelines = (win.__timelines ?? {}) as Record<string, TweenLike | undefined>;
const others = new Set<unknown>(
Object.entries(timelines).flatMap(([key, tl]) => (targetKeys.includes(key) ? [] : [tl])),
);
for (const key of targetKeys) {
try {
for (const tween of ownTweens(timelines[key] ?? {}, others)) addTweenTargets(tween, targets);
} catch {}
}
sweepHeldElements(doc, targetKeys, others, targets);
addLiveSetTargets(doc, targetKeys, targets);
for (const script of outgoingScripts) addStandaloneSetTargets(doc, script, targets);
return targets;
}
function tweenTargetsIn(timelines: Set<unknown>): Set<Element> {
const els = new Set<Element>();
for (const tl of timelines) {
try {
for (const tween of (tl as TweenLike | undefined)?.getChildren?.(true) ?? []) {
for (const el of elementTargets(tween)) els.add(el);
}
} catch {}
}
return els;
}
function compositionRoot(doc: Document, key: string): Element | undefined {
return doc.querySelectorAll(`[data-composition-id="${CSS.escape(key)}"]`)[0];
}
export function compositionFile(doc: Document, targetKeys: string[]): string | null {
const root = targetKeys.map((key) => compositionRoot(doc, key)).find(Boolean);
return root?.closest("[data-composition-file]")?.getAttribute("data-composition-file") ?? null;
}
// A standalone gsap.set, or keyframes just removed, leaves GSAP state no timeline child shows.
// The nearest composition root says whose script set it; another timeline's targets stay its own.
function sweepHeldElements(
doc: Document,
targetKeys: string[],
others: Set<unknown>,
targets: Map<Element, Set<string>>,
): void {
const elsewhere = tweenTargetsIn(others);
const roots = new Set<Element | null | undefined>(targetKeys.map((k) => compositionRoot(doc, k)));
roots.delete(undefined);
for (const root of roots) {
for (const el of root ? [root, ...root.querySelectorAll("*")] : []) {
if (targets.has(el) || elsewhere.has(el) || !("_gsap" in el)) continue;
if (el === root || roots.has(el.parentElement?.closest("[data-composition-id]")))
targets.set(el, new Set());
}
}
}
// What a live patch set on each element since its last reload; no script in the preview ran it.
const liveSets = new WeakMap<Document, Map<Element, Set<string>>>();
export function recordLiveSet(el: Element, vars: Record<string, unknown>): void {
const byElement = liveSets.get(el.ownerDocument) ?? new Map<Element, Set<string>>();
liveSets.set(el.ownerDocument, byElement);
const props = byElement.get(el) ?? new Set<string>();
for (const prop of tweenedProps(vars)) props.add(prop);
byElement.set(el, props);
}
function addLiveSetTargets(
doc: Document,
targetKeys: string[],
targets: Map<Element, Set<string>>,
): void {
const roots = new Set<Element | null | undefined>(targetKeys.map((k) => compositionRoot(doc, k)));
for (const [el, props] of liveSets.get(doc) ?? []) {
if (!roots.has(el) && !roots.has(el.parentElement?.closest("[data-composition-id]"))) continue;
const seen = targets.get(el) ?? new Set<string>();
for (const prop of props) seen.add(prop);
targets.set(el, seen);
}
}
export function forgetLiveSets(reset: Map<Element, unknown>): void {
for (const el of reset.keys()) liveSets.get(el.ownerDocument)?.delete(el);
}
/** Adds what each standalone `gsap.set` in the outgoing script wrote, which no timeline child records. */
function addStandaloneSetTargets(
doc: Document,
outgoingScript: string,
targets: Map<Element, Set<string>>,
): void {
if (!outgoingScript.includes("gsap.set(")) return;
for (const set of parseGsapScript(outgoingScript).animations) {
if (set.method !== "set" || !set.global) continue;
let els: Element[];
try {
els = [...doc.querySelectorAll(set.targetSelector)];
} catch {
continue;
}
for (const el of els) {
const seen = targets.get(el) ?? new Set<string>();
for (const prop of tweenedProps(set.properties)) seen.add(prop);
targets.set(el, seen);
}
}
}
// Each file a reset element may be written in, parsed at most once per reload: the reloaded
// composition's own file is the one just written, any other comes from the caller.
export function fileDocs(
+2 -2
View File
@@ -8,8 +8,8 @@
"unpacked": 25500000
},
"@hyperframes/core": {
"packed": 1830000,
"unpacked": 4639000
"packed": 1948041,
"unpacked": 4898942
},
"@hyperframes/engine": {
"packed": 510000,