diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json index 0213ad312a..b22dac1060 100644 --- a/packages/core/package-subpaths.json +++ b/packages/core/package-subpaths.json @@ -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", diff --git a/packages/core/package.json b/packages/core/package.json index a9dc03ce24..27c515161f 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -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" diff --git a/packages/core/src/runtime/editing/patchTween.ts b/packages/core/src/runtime/editing/patchTween.ts index bfec4f0263..7097b2e4fc 100644 --- a/packages/core/src/runtime/editing/patchTween.ts +++ b/packages/core/src/runtime/editing/patchTween.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; } diff --git a/packages/core/src/runtime/editing/softReload.test.ts b/packages/core/src/runtime/editing/softReload.test.ts new file mode 100644 index 0000000000..d83272239e --- /dev/null +++ b/packages/core/src/runtime/editing/softReload.test.ts @@ -0,0 +1,178 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { parseSoftReload, softReload, type SoftReloadParams } from "./softReload"; + +type TestWindow = Window & Record; +const win = window as TestWindow; +const SCRIPT = `var __timelines = {}; __timelines["main"] = 1;`; +const params = (over: Partial = {}): SoftReloadParams => ({ + script: SCRIPT, + time: 1.5, + sets: [], + authored: [], + timing: [], + ...over, +}); + +const killed = vi.fn(); +function preview(markup: string) { + document.body.innerHTML = `${markup}`; + const seeks: number[] = []; + win.gsap = { + timeline: () => ({}), + set: (targets: HTMLElement[], vars: Record) => { + 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 = (node: T): T => { + if ((node as Node).nodeName === "SCRIPT") (win.__timelines as Record).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).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( + `
`, + ); + 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(`
`); + 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( + `
`, + ); + 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(`
`); + 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 = `
`; + + 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> = []; + 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( + `
` + + `
` + + `
`, + ); + + 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(); + }); +}); diff --git a/packages/core/src/runtime/editing/softReload.ts b/packages/core/src/runtime/editing/softReload.ts new file mode 100644 index 0000000000..c90552004f --- /dev/null +++ b/packages/core/src/runtime/editing/softReload.ts @@ -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; + getChildren?: (deep: boolean) => TweenLike[]; +}; + +export type SoftReloadWindow = Window & { + __timelines?: Record; + __player?: { + getTime?: () => number; + seek?: (t: number) => void; + isPlaying?: () => boolean; + play?: () => void; + }; + __hfForceTimelineRebind?: () => void; + __hfSuppressSceneMutations?: (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) => 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; rewritten: Set }; + +/** 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(); + // The preview rewrites an inlined composition's own root, so the file's timing is not its own. + const rewritten = new Set(); + 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): 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>, el: Element, props: Iterable): void { + const seen = targets.get(el) ?? new Set(); + 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 }, + doc: Document, + targetKeys: string[], + sets: readonly StandaloneSet[] = [], +): Map> { + const targets = new Map>(); + const timelines = (win.__timelines ?? {}) as Record; + const others = new Set( + 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): Set { + const els = new Set(); + 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, + targets: Map>, +): void { + const elsewhere = tweenTargetsIn(others); + const roots = new Set(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>>(); + +export function recordLiveSet(el: Element, vars: Record): void { + const byElement = liveSets.get(el.ownerDocument) ?? new Map>(); + liveSets.set(el.ownerDocument, byElement); + addProps(byElement, el, tweenedProps(vars)); +} + +function addLiveSetTargets( + doc: Document, + targetKeys: string[], + targets: Map>, +): void { + const roots = new Set(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): 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("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, +): 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( + `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 | 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>, + authored: Map, +): 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>, + input: SoftReloadInput, + ownFile: string | null, +): Map | null { + const authored = new Map(); + 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 { + 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 | 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((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:` or `#`, 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 => + 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 }; +} diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts index cbe8f89358..2db4cd7245 100644 --- a/packages/core/src/runtime/editingAgent.test.ts +++ b/packages/core/src/runtime/editingAgent.test.ts @@ -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 = `
`; + const frame = window as unknown as Record; + 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 = `

Hi

diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts index 2dd0135009..96395dae6d 100644 --- a/packages/core/src/runtime/editingAgent.ts +++ b/packages/core/src/runtime/editingAgent.ts @@ -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 { diff --git a/packages/core/src/runtime/editingPort.test.ts b/packages/core/src/runtime/editingPort.test.ts index c4fd50b17c..218d386751 100644 --- a/packages/core/src/runtime/editingPort.test.ts +++ b/packages/core/src/runtime/editingPort.test.ts @@ -105,6 +105,7 @@ describe("createEditingPortClient", () => { "edit-element", "gsap-set", "patch-tweens", + "soft-reload", ], }); } finally { diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index 4fadd4c62a..6123a34f97 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -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 = EditingRequests[K]["params"]; export type EditingResult = 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. */ diff --git a/packages/studio/src/hooks/gsapRuntimePatch.ts b/packages/studio/src/hooks/gsapRuntimePatch.ts index ceef342aee..b2436492ff 100644 --- a/packages/studio/src/hooks/gsapRuntimePatch.ts +++ b/packages/studio/src/hooks/gsapRuntimePatch.ts @@ -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; } diff --git a/packages/studio/src/hooks/timelineTimingSync.sealed.test.ts b/packages/studio/src/hooks/timelineTimingSync.sealed.test.ts new file mode 100644 index 0000000000..01082541b6 --- /dev/null +++ b/packages/studio/src/hooks/timelineTimingSync.sealed.test.ts @@ -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()), + 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) => + `
`; + +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(); +}); diff --git a/packages/studio/src/hooks/timelineTimingSync.ts b/packages/studio/src/hooks/timelineTimingSync.ts index 7b067f56c2..232bc912e9 100644 --- a/packages/studio/src/hooks/timelineTimingSync.ts +++ b/packages/studio/src/hooks/timelineTimingSync.ts @@ -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(); diff --git a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx index 4b0cc0124a..a7da353013 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx +++ b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx @@ -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(); }); diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.ts index 2204747757..16952e9603 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.ts +++ b/packages/studio/src/hooks/useGsapScriptCommits.ts @@ -221,6 +221,7 @@ function softReloadOrEscalate( origin: "preview_sync" | "sdk_refresh", authoredHtml?: string, nestedFiles?: Map | 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(); diff --git a/packages/studio/src/utils/authoredSource.ts b/packages/studio/src/utils/authoredSource.ts index b6d1553521..1518bbbed0 100644 --- a/packages/studio/src/utils/authoredSource.ts +++ b/packages/studio/src/utils/authoredSource.ts @@ -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(); + 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; } diff --git a/packages/studio/src/utils/elementGsap.ts b/packages/studio/src/utils/elementGsap.ts index 489404c9c4..021cb836ef 100644 --- a/packages/studio/src/utils/elementGsap.ts +++ b/packages/studio/src/utils/elementGsap.ts @@ -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"; diff --git a/packages/studio/src/utils/gsapSoftReload.sealed.test.ts b/packages/studio/src/utils/gsapSoftReload.sealed.test.ts new file mode 100644 index 0000000000..c81df0177b --- /dev/null +++ b/packages/studio/src/utils/gsapSoftReload.sealed.test.ts @@ -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()), + 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) => + `
`; +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(); +}); diff --git a/packages/studio/src/utils/gsapSoftReload.test.ts b/packages/studio/src/utils/gsapSoftReload.test.ts index 5f25816cdf..9628dabace 100644 --- a/packages/studio/src/utils/gsapSoftReload.test.ts +++ b/packages/studio/src/utils/gsapSoftReload.test.ts @@ -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); diff --git a/packages/studio/src/utils/gsapSoftReload.ts b/packages/studio/src/utils/gsapSoftReload.ts index af7f715808..8934940b82 100644 --- a/packages/studio/src/utils/gsapSoftReload.ts +++ b/packages/studio/src/utils/gsapSoftReload.ts @@ -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 void; pause?: () => void }>; - __player?: { - getTime?: () => number; - seek?: (t: number) => void; - isPlaying?: () => boolean; - play?: () => void; - }; - __hfForceTimelineRebind?: () => void; - __hfSuppressSceneMutations?: (fn: () => T) => T; - __hfStudioManualEditsApply?: () => void; - // Set while a MotionPathPlugin