fix(studio): a timing drag moves the animation in place in a sealed preview (#8163)

* fix(studio): a scene edit swaps in place and a far scene mounts for selection in a sealed preview

* test(studio): a sealed undo that reloads marks its scenes stale first

* fix(studio): a timing drag moves the animation in place in a sealed preview

* fix(studio): a sealed timing drag moves the clip's window and the film length with its tweens

* test(studio): the sealed retime test checks both requests were sent before comparing them

* refactor(studio): the sealed live retime code passes the quality audit

* style(core): format the sealed live retime parser
This commit is contained in:
Miguel Ángel
2026-11-20 18:49:29 +00:00
committed by GitHub
parent be3d218074
commit 6cf81c6689
12 changed files with 560 additions and 170 deletions
+6
View File
@@ -482,6 +482,12 @@
"types": "./dist/runtime/editing/scenes.d.ts",
"environments": ["browser", "bun", "node"]
},
"./runtime/live-retime": {
"source": "./src/runtime/editing/liveRetime.ts",
"runtime": "./dist/runtime/editing/liveRetime.js",
"types": "./dist/runtime/editing/liveRetime.d.ts",
"environments": ["browser", "bun", "node"]
},
"./runtime/clip-window": {
"source": "./src/runtime/clipWindow.ts",
"runtime": "./dist/runtime/clipWindow.js",
+10
View File
@@ -489,6 +489,12 @@
"import": "./src/runtime/editing/scenes.ts",
"types": "./src/runtime/editing/scenes.ts"
},
"./runtime/live-retime": {
"bun": "./src/runtime/editing/liveRetime.ts",
"node": "./dist/runtime/editing/liveRetime.js",
"import": "./src/runtime/editing/liveRetime.ts",
"types": "./src/runtime/editing/liveRetime.ts"
},
"./runtime/clip-window": {
"bun": "./src/runtime/clipWindow.ts",
"node": "./dist/runtime/clipWindow.js",
@@ -1013,6 +1019,10 @@
"import": "./dist/runtime/editing/scenes.js",
"types": "./dist/runtime/editing/scenes.d.ts"
},
"./runtime/live-retime": {
"import": "./dist/runtime/editing/liveRetime.js",
"types": "./dist/runtime/editing/liveRetime.d.ts"
},
"./runtime/clip-window": {
"import": "./dist/runtime/clipWindow.js",
"types": "./dist/runtime/clipWindow.d.ts"
@@ -0,0 +1,112 @@
import { gsap } from "gsap";
import { afterEach, describe, expect, it, vi } from "vitest";
import { liveRetime, parseLiveRetime, type LiveRetimeParams } from "./liveRetime";
type TestWindow = Window & Record<string, unknown>;
const win = window as TestWindow;
const script = (start: number) =>
`var tl = gsap.timeline({ paused: true }); tl.to("#a", { x: 100, duration: 1 }, ${start}); window.__timelines["t"] = tl;`;
const MOVE = {
selector: "#a",
start: 1.5,
duration: 1,
wasStart: 0.5,
wasDuration: 1,
moved: true,
};
const params = (over: Partial<LiveRetimeParams> = {}): LiveRetimeParams => ({
key: "t",
after: script(1.5),
time: 2,
tweens: [{ ...MOVE, source: 0 }],
timing: [],
...over,
});
function preview() {
document.body.innerHTML = `<div data-composition-id="t" data-duration="3"><div id="a" data-start="0.5" data-duration="1"></div></div><script type="text/plain">${script(0.5)}</script>`;
win.__timelines = {};
new Function("gsap", "window", script(0.5))(gsap, win);
win.__hfForceTimelineRebind = vi.fn();
win.__player = { seek: vi.fn() };
const timeline = (win.__timelines as Record<string, gsap.core.Timeline>).t!;
const start = () => timeline.getChildren(false, true, false)[0]!.startTime();
return { start, text: () => document.querySelector("script")!.textContent };
}
afterEach(() => {
document.body.innerHTML = "";
for (const key of ["__timelines", "__hfForceTimelineRebind", "__player"]) delete win[key];
});
describe("live-retime", () => {
it("moves the live tween to the planned start, records the saved script, and re-seeks", () => {
const live = preview();
expect(liveRetime(params())).toEqual({ result: "moved" });
expect(live.start()).toBe(1.5);
expect(live.text()).toBe(script(1.5));
expect(win.__hfForceTimelineRebind).toHaveBeenCalledOnce();
expect((win.__player as { seek: ReturnType<typeof vi.fn> }).seek).toHaveBeenCalledWith(2);
});
it("moves nothing when the live timeline is not where the plan says it was", () => {
const live = preview();
const stale = params({ tweens: [{ ...MOVE, wasStart: 0.7, source: 0 }] });
expect(liveRetime(stale)).toEqual({ result: "unchanged" });
expect(live.start()).toBe(0.5);
expect(live.text()).toBe(script(0.5));
expect(win.__hfForceTimelineRebind).not.toHaveBeenCalled();
});
});
describe("live-retime of a timing edit", () => {
const timing: LiveRetimeParams["timing"] = [["#a", [["data-start", "1.5"]]]];
it("puts the saved clip timing on the live element before the rebind derives its window", () => {
preview();
const clip = document.getElementById("a")!;
const seen: Array<string | null> = [];
win.__hfForceTimelineRebind = () => seen.push(clip.getAttribute("data-start"));
expect(liveRetime(params({ timing }))).toEqual({ result: "moved" });
expect(seen).toEqual(["1.5"]);
});
it("leaves the clip's timing to the re-run when its tweens cannot move", () => {
preview();
const stale = params({ timing, tweens: [{ ...MOVE, wasStart: 0.7, source: 0 }] });
expect(liveRetime(stale)).toEqual({ result: "unchanged" });
expect(document.getElementById("a")!.getAttribute("data-start")).toBe("0.5");
});
it("moves nothing and asks for a reload when a timed element of the saved file is not in the preview", () => {
const live = preview();
expect(liveRetime(params({ timing: [["#gone", [["data-start", "1"]]]] }))).toEqual({
result: "failed",
});
expect(live.start()).toBe(0.5);
});
});
describe("parseLiveRetime", () => {
it("accepts a bounded plan", () => {
expect(parseLiveRetime(params())).toEqual(params());
});
it.each([
["an extra field", { ...params(), script: "x" }],
["a tween with an extra field", params({ tweens: [{ ...MOVE, source: 0, x: 1 } as never] })],
["a non-finite start", params({ tweens: [{ ...MOVE, start: Infinity, source: 0 }] })],
["a negative length", params({ tweens: [{ ...MOVE, duration: -1, source: 0 }] })],
["a fractional source", params({ tweens: [{ ...MOVE, source: 0.5 }] })],
["no tweens", params({ tweens: [] })],
["a negative time", params({ time: -1 })],
["a timing attribute that is not timing", params({ timing: [["#a", [["class", "x"]]]] })],
])("refuses %s", (_label, request) => {
expect(parseLiveRetime(request)).toBeNull();
});
});
@@ -0,0 +1,263 @@
// A saved timing edit that only moved tweens moves the live ones instead of re-running the script.
// Studio plans the move from the saved scripts; the frame checks its timeline matches the plan first.
import { RUNTIME_FILLER } from "../protocol";
import {
applyTimingPlan,
compositionFile,
finalizeSoftReload,
findGsapScriptElements,
parseSavedTiming,
planSavedTiming,
scriptsRegistering,
type SavedTiming,
type SoftReloadWindow,
} from "./softReload";
export interface TweenTiming {
selector: string;
start: number;
duration: number;
wasStart: number;
wasDuration: number;
moved: boolean;
/** Its place in the script, which is the order a fresh run adds it to the timeline. */
source: number;
}
/** A move planned from the saved scripts: `tweens` in the live timeline's child order. */
export type RetimePlan = { key: string; after: string; tweens: TweenTiming[] };
interface LiveTween {
duration: (value?: number) => number;
startTime: () => number;
delay: () => number;
repeatDelay?: () => number;
data?: unknown;
targets?: () => unknown[];
}
interface LiveTimeline {
getChildren(nested: boolean, tweens: true, timelines: false): LiveTween[];
getChildren(nested: false, tweens: false, timelines: true): LiveTimeline[];
remove: (child: LiveTween) => unknown;
add: (child: LiveTween, position: number) => unknown;
time: () => number;
progress: (value: number, suppressEvents: boolean) => unknown;
totalTime: (time: number, suppressEvents: boolean) => unknown;
}
const same = (a: number, b: number) => Math.abs(a - b) < 1e-6;
const targetsMatch = (tween: LiveTween, selector: string) => {
const targets = tween.targets?.() ?? [];
try {
return targets.length > 0 && targets.every((t) => (t as Element).matches?.(selector) === true);
} catch {
return false;
}
};
/** The live tweens, one per planned tween, when each sits exactly where the parser says it did. */
function pairedLiveTweens(timeline: LiveTimeline, plan: RetimePlan): LiveTween[] | null {
// The script's tweens only: the runtime also nests sub-composition timelines and adds filler tweens here.
const children = timeline
.getChildren(false, true, false)
.filter((tween) => tween.data !== RUNTIME_FILLER);
if (children.length !== plan.tweens.length) return null;
const paired = plan.tweens.every((t, i) => {
const live = children[i]!;
return (
targetsMatch(live, t.selector) &&
same(live.startTime() - live.delay(), t.wasStart) &&
same(live.duration(), t.wasDuration)
);
});
return paired ? children : null;
}
/** The writer rounds every time it writes to 3 decimals. */
const near = (a: number, b: number) => Math.abs(a - b) <= 2e-3;
/** One stretch for every tween (start = shift + stretch × old start, length = stretch × old length), in old order. */
function sharesOneStretch(tweens: TweenTiming[]): boolean {
const first = tweens[0]!;
const last = tweens.at(-1)!;
const longest = tweens.reduce((x, y) => (y.wasDuration > x.wasDuration ? y : x));
const spread = last.wasStart - first.wasStart;
// Taken over the widest span, so the writer's rounding cannot push it past `near`.
const stretch =
spread > longest.wasDuration
? (last.start - first.start) / spread
: longest.wasDuration > 0
? longest.duration / longest.wasDuration
: 1;
const fits = tweens.every(
(t) =>
near(t.start, first.start + stretch * (t.wasStart - first.wasStart)) &&
near(t.duration, stretch * t.wasDuration),
);
return stretch > 0 && fits;
}
/** Tweens on one element still start in the order they did, an equal start in script order. */
const keepsOrder = (tweens: TweenTiming[]) =>
tweens.every(
(t, k) => k === 0 || (tweens[k - 1]!.start - t.start || tweens[k - 1]!.source - t.source) < 0,
);
/**
* A tween keeps the start values it recorded when it first played, so every element a move touches
* must keep its tweens' spacing, and no timeline the script does not own may animate it.
*/
function movesKeepEachElementsHistory(
timeline: LiveTimeline,
plan: RetimePlan,
children: LiveTween[],
registry: unknown[],
): boolean {
const byElement = new Map<unknown, number[]>();
children.forEach((child, i) => {
for (const target of child.targets?.() ?? []) {
const indexes = byElement.get(target);
if (indexes) indexes.push(i);
else byElement.set(target, [i]);
}
});
const moved = new Set<unknown>();
for (const [target, indexes] of byElement) {
if (!indexes.some((i) => plan.tweens[i]!.moved)) continue;
const tweens = indexes.map((i) => plan.tweens[i]!);
// GSAP adds delays to the schedule unstretched; a shift keeps every length.
const shifted = tweens.every((t) => t.duration === t.wasDuration);
const undelayed = indexes.every((i) => !children[i]!.delay() && !children[i]!.repeatDelay?.());
if (!keepsOrder(tweens) || !sharesOneStretch(tweens) || !(shifted || undelayed)) return false;
moved.add(target);
}
return !animatedElsewhere(timeline, registry, moved);
}
/** Whether a timeline other than `own` (nested in it, or another registered one) animates any of `targets`. */
function animatedElsewhere(own: LiveTimeline, registry: unknown[], targets: Set<unknown>): boolean {
const seen = new Set<unknown>([own]);
const visit = (timeline: LiveTimeline): boolean => {
if (seen.has(timeline)) return false;
seen.add(timeline);
return (
timeline
.getChildren(false, true, false)
.some((tween) => tween.targets?.().some((target) => targets.has(target))) ||
timeline.getChildren(false, false, true).some(visit)
);
};
const timelines = registry.filter(
(entry): entry is LiveTimeline => typeof (entry as LiveTimeline)?.getChildren === "function",
);
return own.getChildren(false, false, true).some(visit) || timelines.some(visit);
}
/**
* Moves the live tweens `plan` names and records the saved script as `script`'s text.
* False, with nothing changed, when the live timeline is not exactly what the plan read.
*/
export function retimeLiveTweens(
win: { __timelines?: Record<string, unknown> } | null,
script: HTMLScriptElement,
plan: RetimePlan,
): boolean {
const timeline = win?.__timelines?.[plan.key] as LiveTimeline | undefined;
if (typeof timeline?.getChildren !== "function") return false;
// Paired before anything moves: moving a tween re-sorts the timeline's children.
const children = pairedLiveTweens(timeline, plan);
if (!children) return false;
if (plan.tweens.some((t) => t.moved)) {
const registry = Object.values(win?.__timelines ?? {});
if (!movesKeepEachElementsHistory(timeline, plan, children, registry)) return false;
// Re-added in script order: GSAP orders equal starts by when they were added, as a fresh run does.
const bySource = plan.tweens
.map((t, i) => ({ ...t, tween: children[i]! }))
.sort((a, b) => a.source - b.source);
for (const { tween } of bySource) timeline.remove(tween);
for (const { tween, start, duration } of bySource) {
if (tween.duration() !== duration) tween.duration(duration);
timeline.add(tween, start);
}
// Replayed to the playhead as the runtime binds a fresh load, callbacks included.
const at = timeline.time();
timeline.progress(0.0001, true);
timeline.totalTime(at, false);
}
// A script element runs once, so this only keeps the next comparison honest; nothing re-executes.
script.textContent = plan.after;
return true;
}
/** `timing`: the saved file's clip and film timing, which no commit could patch into a sealed frame. */
export type LiveRetimeParams = RetimePlan & { time: number; timing: SavedTiming };
/** "unchanged": nothing moved, so only a re-run syncs it; "failed": the preview may be half-moved. */
export type LiveRetimeResult = "moved" | "unchanged" | "failed";
const MAX_TWEENS = 1_000;
const MAX_KEY = 512;
const MAX_SELECTOR = 2_000;
const MAX_SCRIPT = 1_000_000;
const TIMING_FIELDS = "duration,moved,selector,source,start,wasDuration,wasStart";
const isRecord = (value: unknown): value is Record<string, unknown> =>
Object.prototype.toString.call(value) === "[object Object]";
const finite = (value: unknown): value is number =>
typeof value === "number" && Number.isFinite(value);
const okSelector = (selector: unknown): boolean =>
typeof selector === "string" && selector.length > 0 && selector.length <= MAX_SELECTOR;
const okSource = (source: unknown): boolean => Number.isInteger(source) && (source as number) >= 0;
function okTimes({ start, duration, wasStart, wasDuration }: Record<string, unknown>): boolean {
if (![start, duration, wasStart, wasDuration].every(finite)) return false;
return (duration as number) >= 0 && (wasDuration as number) >= 0;
}
function parseTiming(value: unknown): TweenTiming | null {
if (!isRecord(value) || Object.keys(value).sort().join() !== TIMING_FIELDS) return null;
const ok =
okSelector(value.selector) &&
okTimes(value) &&
okSource(value.source) &&
typeof value.moved === "boolean";
return ok ? (value as unknown as TweenTiming) : null;
}
export function parseLiveRetime(params: unknown): LiveRetimeParams | null {
if (!isRecord(params) || Object.keys(params).sort().join() !== "after,key,time,timing,tweens")
return null;
const { key, after, time, tweens } = params;
if (typeof key !== "string" || key.length === 0 || key.length > MAX_KEY) return null;
if (typeof after !== "string" || after.length === 0 || after.length > MAX_SCRIPT) return null;
if (!finite(time) || time < 0) return null;
if (!Array.isArray(tweens) || tweens.length === 0 || tweens.length > MAX_TWEENS) return null;
const parsed = tweens.map(parseTiming);
const timing = parseSavedTiming(params.timing);
if (!timing || !parsed.every(Boolean)) return null;
return { key, after, time, tweens: parsed as TweenTiming[], timing };
}
/** The frame moving its own tweens to the plan Studio made from the saved scripts, then re-seeking. */
export function liveRetime(params: LiveRetimeParams): { result: LiveRetimeResult } {
const win = window as SoftReloadWindow;
const [script, ...extra] = scriptsRegistering(findGsapScriptElements(document), [params.key]);
if (!script || extra.length > 0) return { result: "unchanged" };
const timing = planSavedTiming(document, compositionFile(document, [params.key]), params.timing);
if (!timing) return { result: "failed" };
try {
if (!retimeLiveTweens(win, script, params)) return { result: "unchanged" };
if (!win.__hfForceTimelineRebind) return { result: "failed" };
const finalize = () => {
applyTimingPlan(timing);
finalizeSoftReload(win, params.time);
};
if (win.__hfSuppressSceneMutations) win.__hfSuppressSceneMutations(finalize);
else finalize();
return { result: "moved" };
} catch (error) {
console.error("[hyperframes] Moving the live tweens threw; a full reload follows", error);
return { result: "failed" };
}
}
@@ -207,6 +207,7 @@ describe("installEditingAgent", () => {
"hold-scenes",
"mark-scenes-stale",
"swap-scenes",
"live-retime",
"assets-unloaded",
],
},
@@ -598,6 +599,23 @@ describe("installEditingAgent", () => {
delete window.__hfSwapScenes;
});
it("answers a live retime through the port, and refuses one carrying anything extra", async () => {
const port = connectedPort();
const tween = { selector: "#a", start: 1, duration: 1, wasStart: 0, wasDuration: 1 };
const tweens = [{ ...tween, moved: true, source: 0 }];
const plan = { key: "t", after: "x", time: 0, tweens, timing: [] };
const extra = { ...plan, script: "x" };
expect(await ask(port, { v: 1, id: 1, kind: "live-retime", params: extra })).toMatchObject({
ok: false,
});
// No live script registers the timeline, so nothing can move.
expect(await ask(port, { v: 1, id: 2, kind: "live-retime", params: plan })).toMatchObject({
ok: true,
result: { result: "unchanged" },
});
});
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>
@@ -44,6 +44,7 @@ import { gsapSet } from "./editing/gsapSet";
import { patchTweens } from "./editing/patchTween";
import { softReload } from "./editing/softReload";
import { holdScenes, markScenesStale, swapScenes } from "./editing/scenes";
import { liveRetime } from "./editing/liveRetime";
import { previewAssetsUnloaded } from "../lottieReadiness";
import {
getLogicalOpacity,
@@ -233,6 +234,7 @@ const HANDLERS: Handlers = {
"hold-scenes": holdScenes,
"mark-scenes-stale": markScenesStale,
"swap-scenes": swapScenes,
"live-retime": liveRetime,
"assets-unloaded": () => ({ unloaded: previewAssetsUnloaded(document, window.__hfLottie) }),
};
@@ -110,6 +110,7 @@ describe("createEditingPortClient", () => {
"hold-scenes",
"mark-scenes-stale",
"swap-scenes",
"live-retime",
"assets-unloaded",
],
});
+8
View File
@@ -45,6 +45,11 @@ import {
type SwapScenesParams,
type SwapScenesResult,
} from "./editing/scenes";
import {
parseLiveRetime,
type LiveRetimeParams,
type LiveRetimeResult,
} from "./editing/liveRetime";
import type { RuntimeTimelineMessage } from "./types";
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
import { parseCombo } from "../keyCombo";
@@ -205,6 +210,7 @@ export const EDITING_REQUEST_KINDS = [
"hold-scenes",
"mark-scenes-stale",
"swap-scenes",
"live-retime",
"assets-unloaded",
] as const;
export type EditingRequestKind = (typeof EDITING_REQUEST_KINDS)[number];
@@ -354,6 +360,7 @@ export interface EditingRequests {
"hold-scenes": { params: HoldScenesParams; result: { held: boolean } };
"mark-scenes-stale": { params: MarkScenesStaleParams; result: { marked: true } };
"swap-scenes": { params: SwapScenesParams; result: SwapScenesResult };
"live-retime": { params: LiveRetimeParams; result: { result: LiveRetimeResult } };
"assets-unloaded": { params: NoParams; result: { unloaded: boolean } };
}
export type EditingParams<K extends EditingRequestKind> = EditingRequests[K]["params"];
@@ -587,6 +594,7 @@ const PARAM_PARSERS: {
"hold-scenes": parseHoldScenes,
"mark-scenes-stale": parseMarkScenesStale,
"swap-scenes": parseSwapScenes,
"live-retime": parseLiveRetime,
"assets-unloaded": noParams,
};
@@ -37,8 +37,12 @@ it("takes a sealed timing edit's saved clip and film timing to the frame with th
});
await new Promise((resolve) => setTimeout(resolve, 0));
const retime = previewRequest.mock.calls.find(([, kind]) => kind === "live-retime");
const softReload = previewRequest.mock.calls.find(([, kind]) => kind === "soft-reload");
if (!softReload) throw new Error("no soft-reload request was sent");
if (!retime || !softReload) throw new Error("the live retime and soft reload were not both sent");
expect((retime[2] as { timing: unknown }).timing).toEqual(
(softReload[2] as { timing: unknown }).timing,
);
const timing = (softReload[2] as { timing: Array<[string, string[][]]> }).timing;
expect(timing.map(([, attributes]) => attributes)).toEqual([
[["data-duration", "6"]],
@@ -137,7 +137,7 @@ async function syncTimingEditPreview(
reloadPreview();
return;
}
if (moveLiveTweens(iframe, scriptText, currentTime(), reloadPreview)) return;
if (await moveLiveTweens(iframe, scriptText, currentTime(), reloadPreview, outcome)) return;
const nestedFiles = await settleNestedReads(
projectId
? readNestedFiles(iframe, scriptText, (path) => readFileContent(projectId, path))
@@ -0,0 +1,70 @@
// @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 { moveLiveTweens } from "./gsapLiveRetime";
const iframe = document.createElement("iframe");
const script = (start: number) =>
[
"var tl = gsap.timeline({ paused: true });",
`tl.to("#a", { x: 100, duration: 1 }, ${start});`,
'window.__timelines["t"] = tl;',
].join("\n");
const file = (text: string) => `<div id="a"></div><script>${text}</script>`;
const files = {
before: file(script(0.5)),
after: file(script(1.5)).replace('id="a"', 'id="a" data-start="1.5"'),
};
beforeEach(() => previewRequest.mockReset());
it("sends a sealed preview the move planned from the saved file before and after the edit", async () => {
previewRequest.mockResolvedValue({ result: "moved" });
const reload = vi.fn();
expect(await moveLiveTweens(iframe, script(1.5), 2, reload, files)).toBe(true);
expect(previewRequest).toHaveBeenCalledExactlyOnceWith(iframe, "live-retime", {
key: "t",
after: script(1.5),
tweens: [
{
selector: "#a",
start: 1.5,
duration: 1,
wasStart: 0.5,
wasDuration: 1,
moved: true,
source: 0,
},
],
time: 2,
timing: [[expect.any(String), [["data-start", "1.5"]]]],
});
expect(reload).not.toHaveBeenCalled();
});
it.each([
["moved nothing", { result: "unchanged" }, false, 0],
["failed halfway", { result: "failed" }, true, 1],
["does not answer", null, true, 1],
["answers with an extra field", { result: "moved", after: "x()" }, true, 1],
])("when the frame %s it re-runs or reloads instead", async (_l, reply, handled, reloads) => {
previewRequest.mockResolvedValue(reply);
const reload = vi.fn();
expect(await moveLiveTweens(iframe, script(1.5), 0, reload, files)).toBe(handled);
expect(reload).toHaveBeenCalledTimes(reloads);
});
it("leaves it to a re-run, sending nothing, when the file before the edit is not known", async () => {
expect(await moveLiveTweens(iframe, script(1.5), 0, vi.fn(), { after: files.after })).toBe(false);
expect(previewRequest).not.toHaveBeenCalled();
});
+64 -168
View File
@@ -1,24 +1,19 @@
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import { parseGsapScriptAcorn, scriptShape } from "@hyperframes/parsers/gsap-parser-acorn";
import { hasExplicitTime } from "@hyperframes/parsers/gsap-writer-acorn";
import { RUNTIME_FILLER } from "@hyperframes/core/runtime/protocol";
import {
retimeLiveTweens,
type LiveRetimeResult,
type TweenTiming,
} from "@hyperframes/core/runtime/live-retime";
import {
applySoftReloadFinalization,
findGsapScriptElements,
scriptsRegistering,
timelineKeys,
} from "./gsapSoftReload";
interface TweenTiming {
selector: string;
start: number;
duration: number;
wasStart: number;
wasDuration: number;
moved: boolean;
/** Its place in the script, which is the order a fresh run adds it to the timeline. */
source: number;
}
import { previewFrameOpaque, previewRequest } from "../player/lib/previewChannel";
import { savedTiming } from "./authoredSource";
/**
* How a saved script differs from the live one: `retime` when only tween starts and lengths moved
@@ -113,163 +108,61 @@ export function planLiveRetimeFromPreview(
return plan.kind === "retime" ? { ...plan, script } : RERUN;
}
interface LiveTween {
duration: (value?: number) => number;
startTime: () => number;
delay: () => number;
repeatDelay?: () => number;
data?: unknown;
targets?: () => unknown[];
}
interface LiveTimeline {
getChildren(nested: boolean, tweens: true, timelines: false): LiveTween[];
getChildren(nested: false, tweens: false, timelines: true): LiveTimeline[];
remove: (child: LiveTween) => unknown;
add: (child: LiveTween, position: number) => unknown;
time: () => number;
progress: (value: number, suppressEvents: boolean) => unknown;
totalTime: (time: number, suppressEvents: boolean) => unknown;
}
const same = (a: number, b: number) => Math.abs(a - b) < 1e-6;
const targetsMatch = (tween: LiveTween, selector: string) => {
const targets = tween.targets?.() ?? [];
try {
return targets.length > 0 && targets.every((t) => (t as Element).matches?.(selector) === true);
} catch {
return false;
}
};
/** The live tweens, one per planned tween, when each sits exactly where the parser says it did. */
function pairedLiveTweens(timeline: LiveTimeline, plan: LiveRetime): LiveTween[] | null {
// The script's tweens only: the runtime also nests sub-composition timelines and adds filler tweens here.
const children = timeline
.getChildren(false, true, false)
.filter((tween) => tween.data !== RUNTIME_FILLER);
if (children.length !== plan.tweens.length) return null;
const paired = plan.tweens.every((t, i) => {
const live = children[i]!;
return (
targetsMatch(live, t.selector) &&
same(live.startTime() - live.delay(), t.wasStart) &&
same(live.duration(), t.wasDuration)
);
});
return paired ? children : null;
}
/** The writer rounds every time it writes to 3 decimals. */
const near = (a: number, b: number) => Math.abs(a - b) <= 2e-3;
/** One stretch for every tween (start = shift + stretch × old start, length = stretch × old length), in old order. */
function sharesOneStretch(tweens: TweenTiming[]): boolean {
const first = tweens[0]!;
const last = tweens.at(-1)!;
const longest = tweens.reduce((x, y) => (y.wasDuration > x.wasDuration ? y : x));
const spread = last.wasStart - first.wasStart;
// Taken over the widest span, so the writer's rounding cannot push it past `near`.
const stretch =
spread > longest.wasDuration
? (last.start - first.start) / spread
: longest.wasDuration > 0
? longest.duration / longest.wasDuration
: 1;
const fits = tweens.every(
(t) =>
near(t.start, first.start + stretch * (t.wasStart - first.wasStart)) &&
near(t.duration, stretch * t.wasDuration),
);
return stretch > 0 && fits;
}
/** Tweens on one element still start in the order they did, an equal start in script order. */
const keepsOrder = (tweens: TweenTiming[]) =>
tweens.every(
(t, k) => k === 0 || (tweens[k - 1]!.start - t.start || tweens[k - 1]!.source - t.source) < 0,
);
/**
* A tween keeps the start values it recorded when it first played, so every element a move touches
* must keep its tweens' spacing, and no timeline the script does not own may animate it.
*/
function movesKeepEachElementsHistory(
timeline: LiveTimeline,
plan: LiveRetime,
children: LiveTween[],
registry: unknown[],
): boolean {
const byElement = new Map<unknown, number[]>();
children.forEach((child, i) => {
for (const target of child.targets?.() ?? []) {
const indexes = byElement.get(target);
if (indexes) indexes.push(i);
else byElement.set(target, [i]);
}
});
const moved = new Set<unknown>();
for (const [target, indexes] of byElement) {
if (!indexes.some((i) => plan.tweens[i]!.moved)) continue;
const tweens = indexes.map((i) => plan.tweens[i]!);
// GSAP adds delays to the schedule unstretched; a shift keeps every length.
const shifted = tweens.every((t) => t.duration === t.wasDuration);
const undelayed = indexes.every((i) => !children[i]!.delay() && !children[i]!.repeatDelay?.());
if (!keepsOrder(tweens) || !sharesOneStretch(tweens) || !(shifted || undelayed)) return false;
moved.add(target);
}
return !animatedElsewhere(timeline, registry, moved);
}
/** Whether a timeline other than `own` (nested in it, or another registered one) animates any of `targets`. */
function animatedElsewhere(own: LiveTimeline, registry: unknown[], targets: Set<unknown>): boolean {
const seen = new Set<unknown>([own]);
const visit = (timeline: LiveTimeline): boolean => {
if (seen.has(timeline)) return false;
seen.add(timeline);
return (
timeline
.getChildren(false, true, false)
.some((tween) => tween.targets?.().some((target) => targets.has(target))) ||
timeline.getChildren(false, false, true).some(visit)
);
};
const timelines = registry.filter(
(entry): entry is LiveTimeline => typeof (entry as LiveTimeline)?.getChildren === "function",
);
return own.getChildren(false, false, true).some(visit) || timelines.some(visit);
}
/**
* Moves the live tweens a `retime` plan names and records the saved script as the live one.
* False, with nothing changed, when the live timeline is not exactly what the parser read.
*/
/** Moves the live tweens a `retime` plan names; false, with nothing changed, when the timeline differs. */
export function applyLiveRetime(iframe: HTMLIFrameElement | null, plan: LiveRetime): boolean {
const win = iframe?.contentWindow as { __timelines?: Record<string, unknown> } | null;
const timeline = win?.__timelines?.[plan.key] as LiveTimeline | undefined;
if (typeof timeline?.getChildren !== "function") return false;
// Paired before anything moves: moving a tween re-sorts the timeline's children.
const children = pairedLiveTweens(timeline, plan);
if (!children) return false;
if (plan.tweens.some((t) => t.moved)) {
const registry = Object.values(win?.__timelines ?? {});
if (!movesKeepEachElementsHistory(timeline, plan, children, registry)) return false;
// Re-added in script order: GSAP orders equal starts by when they were added, as a fresh run does.
const bySource = plan.tweens
.map((t, i) => ({ ...t, tween: children[i]! }))
.sort((a, b) => a.source - b.source);
for (const { tween } of bySource) timeline.remove(tween);
for (const { tween, start, duration } of bySource) {
if (tween.duration() !== duration) tween.duration(duration);
timeline.add(tween, start);
}
// Replayed to the playhead as the runtime binds a fresh load, callbacks included.
const at = timeline.time();
timeline.progress(0.0001, true);
timeline.totalTime(at, false);
}
// A script element runs once, so this only keeps the next comparison honest; nothing re-executes.
plan.script.textContent = plan.after;
return retimeLiveTweens(win, plan.script, plan);
}
const RETIME_RESULTS = new Set<unknown>(["moved", "unchanged", "failed"]);
/** The frame's reply is data: anything but exactly `{ result }` with a known result counts as a failure. */
function sealedRetimeResult(reply: unknown): LiveRetimeResult {
if (typeof reply !== "object" || reply === null || Object.keys(reply).length !== 1)
return "failed";
const { result } = reply as { result?: unknown };
return RETIME_RESULTS.has(result) ? (result as LiveRetimeResult) : "failed";
}
/** The edited file as saved before and after the edit. */
type SavedFiles = { before?: string; after?: string };
/** A `retime` plan from the file as saved before the edit; null when no single script there owns the timeline. */
function planFromSavedFile(
scriptText: string,
savedBefore: string,
): Extract<LiveRetimePlan, { kind: "retime" }> | null {
const [key] = timelineKeys(scriptText);
if (!key) return null;
const previous = new DOMParser().parseFromString(savedBefore, "text/html");
const [before, ...extra] = scriptsRegistering(findGsapScriptElements(previous), [key]);
if (!before || extra.length > 0) return null;
const plan = planLiveRetime(before.textContent ?? "", scriptText);
return plan.kind === "retime" ? plan : null;
}
// Planned from the saved files alone; the frame checks its timeline matches the plan before moving anything.
async function moveSealedLiveTweens(
iframe: HTMLIFrameElement,
scriptText: string,
currentTime: number,
reloadPreview: () => void,
files: SavedFiles,
): Promise<boolean> {
if (files.before === undefined || files.after === undefined) return false;
const plan = planFromSavedFile(scriptText, files.before);
if (!plan) return false;
const { key: planKey, after, tweens } = plan;
const reply = await previewRequest(iframe, "live-retime", {
key: planKey,
after,
tweens,
time: currentTime,
timing: savedTiming(files.after),
});
const result = sealedRetimeResult(reply);
if (result === "unchanged") return false;
if (result === "failed") reloadPreview();
return true;
}
@@ -279,7 +172,10 @@ export function moveLiveTweens(
scriptText: string,
currentTime: number,
reloadPreview: () => void,
): boolean {
files: SavedFiles = {},
): boolean | Promise<boolean> {
if (previewFrameOpaque(iframe))
return moveSealedLiveTweens(iframe, scriptText, currentTime, reloadPreview, files);
const plan = planLiveRetimeFromPreview(iframe, scriptText);
if (plan.kind !== "retime") return false;
try {