Skip to content

Write HTML. Render video. Built for agents.

fix(core): a sub-composition follows its host clip when the host moves without a reload (#5058)

Miguel Ángel5d19e23cb435
diff --git a/packages/core/src/runtime/init.subCompositionPlacement.test.ts b/packages/core/src/runtime/init.subCompositionPlacement.test.ts
new file mode 100644
index 0000000000..aa5b569f1f
--- /dev/null
+++ b/packages/core/src/runtime/init.subCompositionPlacement.test.ts
@@ -0,0 +1,74 @@
+import gsap from "gsap";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { initSandboxRuntimeModular } from "./init";
+import type { RuntimeTimelineLike } from "./types";
+import { resetRuntimeFixtureDom } from "./runtimeSeekFixture.test-helpers";
+
+// Pins where a running runtime places a sub-composition's timeline, against what a fresh load does.
+describe("runtime sub-composition placement", () => {
+ beforeEach(() => {
+ resetRuntimeFixtureDom();
+ window.gsap = gsap as unknown as typeof window.gsap;
+ });
+
+ afterEach(() => {
+ window.__hfRuntimeTeardown?.();
+ vi.restoreAllMocks();
+ delete window.__player;
+ delete window.__playerReady;
+ delete window.__hf;
+ });
+
+ /** A root with one scene clip at `hostStart`, whose timeline slides `#s` from 0 to 100 over 2 s. */
+ function load(hostStart: number | string) {
+ document.body.innerHTML =
+ `<div data-composition-id="main" data-root="true" data-duration="10">` +
+ `<div id="host" class="clip" data-composition-id="scene" data-start="${hostStart}" data-duration="3">` +
+ `<div id="s"></div></div></div>`;
+ const scene = gsap
+ .timeline({ paused: true })
+ .to("#s", { x: 100, duration: 2, ease: "none" }, 0);
+ const root = gsap.timeline({ paused: true }).to({}, { duration: 1 }, 0);
+ window.__timelines = { main: root, scene } as unknown as Record<string, RuntimeTimelineLike>;
+ initSandboxRuntimeModular();
+ return { scene, root };
+ }
+
+ const shownX = () => Number(gsap.getProperty("#s", "x"));
+
+ it("places the scene at its host's new start when a rebind follows a host move, as a fresh load does", () => {
+ const { scene } = load(1);
+ window.__player?.seek(5);
+ expect(shownX()).toBe(100);
+
+ document.getElementById("host")!.setAttribute("data-start", "4");
+ window.__hfForceTimelineRebind?.();
+
+ expect(scene.startTime()).toBe(4);
+ expect(shownX()).toBe(50);
+ window.__player?.seek(4.5);
+ expect(shownX()).toBe(25);
+ });
+
+ it("leaves a scene where the root script places it after a re-run, as a fresh load does", () => {
+ const { scene } = load(1);
+ const root = gsap.timeline({ paused: true }).to({}, { duration: 1 }, 0).add(scene, 2);
+ window.__timelines = { main: root, scene } as unknown as Record<string, RuntimeTimelineLike>;
+ window.__hfForceTimelineRebind?.();
+ expect(scene.startTime()).toBe(2);
+
+ document.getElementById("host")!.setAttribute("data-start", "4");
+ window.__hfForceTimelineRebind?.();
+
+ expect(scene.startTime()).toBe(2);
+ });
+
+ it("leaves an unmoved scene in place on a rebind, whatever its start rounds to", () => {
+ const { root, scene } = load("0.33333333");
+ const remove = vi.spyOn(root, "remove");
+
+ window.__hfForceTimelineRebind?.();
+
+ expect(remove).not.toHaveBeenCalledWith(scene);
+ });
+});
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index 46158b4eae..de3a670aed 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -1372,8 +1372,8 @@ export function initSandboxRuntimeModular(): void {
return seconds;
};
- // Sub-composition timelines the runtime nested into the root, by host composition id.
- const autoNestedHostIds = new WeakMap<object, string>();
+ // Sub-composition timelines the runtime nested into the root: the host composition id, and where.
+ const autoNested = new WeakMap<object, { hostId: string; parent: unknown; at: number }>();
const resolveRootTimelineFromDocument = (): TimelineResolution => {
const timelines = (window.__timelines ?? {}) as Record<string, RuntimeTimelineLike | undefined>;
@@ -1425,8 +1425,22 @@ export function initSandboxRuntimeModular(): void {
parent: RuntimeTimelineLike,
candidate: { compositionId: string; timeline: RuntimeTimelineLike },
): void => {
- parent.add(candidate.timeline, resolveCompositionStartSeconds(candidate.compositionId));
- autoNestedHostIds.set(candidate.timeline, candidate.compositionId);
+ const at = resolveCompositionStartSeconds(candidate.compositionId);
+ parent.add(candidate.timeline, at);
+ autoNested.set(candidate.timeline, { hostId: candidate.compositionId, parent, at });
+ };
+ const followHostStart = (
+ root: RuntimeTimelineLike,
+ candidate: { compositionId: string; timeline: RuntimeTimelineLike },
+ ): void => {
+ const nested = candidate.timeline as RuntimeTimelineLike & RuntimeTimelineChildLike;
+ const placed = autoNested.get(nested);
+ // Under another root, a re-run script placed it, and owns that place as on a fresh load.
+ if (!placed || placed.parent !== root || nested.parent !== (root as unknown)) return;
+ if (Math.abs(placed.at - resolveCompositionStartSeconds(candidate.compositionId)) < 1e-6)
+ return;
+ // GSAP takes a child out of its parent before adding it; the rebind's unpause aligns it to the root.
+ nestAtHostStart(root, candidate);
};
const createCompositeTimelineFromCandidates = (
candidates: Array<{
@@ -1505,8 +1519,10 @@ export function initSandboxRuntimeModular(): void {
if (!Array.isArray(existingChildren)) return none;
const addedIds: string[] = [];
for (const candidate of candidates) {
- const alreadyIncluded = existingChildren.some((child) => child === candidate.timeline);
- if (alreadyIncluded) continue;
+ if (existingChildren.includes(candidate.timeline)) {
+ followHostStart(rootTimeline, candidate);
+ continue;
+ }
try {
nestAtHostStart(rootTimeline, candidate);
addedIds.push(candidate.compositionId);
@@ -2980,7 +2996,7 @@ export function initSandboxRuntimeModular(): void {
};
// A sub-composition is hidden after its host clip, so its animation counts only until then.
const autoNestedHostEndSeconds = (child: RuntimeTimelineChildLike): number => {
- const hostId = autoNestedHostIds.get(child);
+ const hostId = autoNested.get(child)?.hostId;
const host = hostId
? document.querySelector(`[data-composition-id="${CSS.escape(hostId)}"]`)
: null;
diff --git a/packages/parsers/src/gsapParserAcorn.ts b/packages/parsers/src/gsapParserAcorn.ts
index 2371d597cc..4f88013de6 100644
--- a/packages/parsers/src/gsapParserAcorn.ts
+++ b/packages/parsers/src/gsapParserAcorn.ts
@@ -32,6 +32,7 @@ import { getObjectArrayKeyframeTiming } from "./gsapObjectArrayTiming.js";
// Browser-safe re-exports so studio code can build arc config without importing
// the recast parser (this acorn module is the browser-safe gsap subpath).
export { buildArcPath, editabilityForProvenance } from "./gsapSerialize.js";
+export { scriptShape } from "./scriptShape.js";
export type {
ArcPathConfig,
ArcPathSegment,
diff --git a/packages/parsers/src/scriptShape.test.ts b/packages/parsers/src/scriptShape.test.ts
new file mode 100644
index 0000000000..1ffaab2186
--- /dev/null
+++ b/packages/parsers/src/scriptShape.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+import { scriptShape } from "./scriptShape";
+
+const same = (a: string, b: string, maskNumbers = false) =>
+ scriptShape(a, maskNumbers) === scriptShape(b, maskNumbers);
+
+describe("scriptShape", () => {
+ it("matches a script to esbuild's re-print of it", () => {
+ const written = `// cards
+const tl = gsap.timeline({ paused: true, })
+const each = i => tl.to('#c' + i, { x: 1.0, y: (10), }, i * .5) /* in */
+if (a) { each(1) }
+const w = { x: window.innerWidth - 40 }
+`;
+ // Verbatim output of esbuild transformSync (loader js, legalComments none), as the preview bundler prints it.
+ const printed =
+ 'const tl = gsap.timeline({ paused: true });\nconst each = (i) => tl.to("#c" + i, { x: 1, y: 10 }, i * 0.5);\nif (a) {\n each(1);\n}\nconst w = { x: window.innerWidth - 40 };';
+ expect(same(written, printed)).toBe(true);
+ });
+
+ it("matches an untagged template to the line break esbuild prints for its escape", () => {
+ expect(same("const s = `a\\nb`", "const s = `a\nb`")).toBe(true);
+ });
+
+ it.each([
+ ["an operator", `x = w - 40`, `x = w + 40`],
+ ["a comparison", `a === b`, `a !== b`],
+ ["a compound assignment", `a += 1`, `a -= 1`],
+ ["a unary operator", `f(!a)`, `f(~a)`],
+ ["a regular expression", `s.replace(/a/g, "")`, `s.replace(/b/i, "")`],
+ ["a private name", `class A { #p = 1 }`, `class A { #q = 1 }`],
+ ["an array hole", `f([1, , 2])`, `f([1, 2])`],
+ ["a comma that joins two calls", `if (c) f(), g()`, `if (c) f(); g()`],
+ ["a semicolon that splits a call", `a;\n(b)`, `a\n(b)`],
+ ["a tagged template's raw text", "String.raw`p\\nq`", "String.raw`p\nq`"],
+ ["a prototype written as a key", `({ __proto__: __proto__ })`, `({ __proto__ })`],
+ ])("tells scripts apart that differ only in %s", (_name, a, b) => {
+ expect(same(a, b)).toBe(false);
+ });
+
+ it("hides numbers only when asked", () => {
+ expect(same(`tl.to("#a", {}, 1)`, `tl.to("#a", {}, 2)`)).toBe(false);
+ expect(same(`tl.to("#a", {}, 1)`, `tl.to("#a", {}, 2)`, true)).toBe(true);
+ });
+
+ it("is null for a script that does not parse", () => {
+ expect(scriptShape("tl.to(")).toBeNull();
+ });
+});
diff --git a/packages/parsers/src/scriptShape.ts b/packages/parsers/src/scriptShape.ts
new file mode 100644
index 0000000000..df9df13329
--- /dev/null
+++ b/packages/parsers/src/scriptShape.ts
@@ -0,0 +1,42 @@
+import * as acorn from "acorn";
+
+type Shape = { type?: unknown; key?: { name?: unknown } };
+
+type TaggedTemplate = { type: "TaggedTemplateExpression"; quasi: { quasis: { value: object }[] } };
+
+const isTaggedTemplate = (value: unknown): value is TaggedTemplate =>
+ (value as { type?: unknown } | null)?.type === "TaggedTemplateExpression";
+
+/** What a re-print changes without changing behaviour; only a tag reads a template's raw text. */
+const printOnly = (tagged: WeakSet<object>) =>
+ new Map<string, (holder: Shape) => boolean>([
+ ["start", () => true],
+ ["end", () => true],
+ ["raw", (holder) => !tagged.has(holder)],
+ ["shorthand", (holder) => holder.key?.name !== "__proto__"],
+ ]);
+
+const isNumberLiteral = (holder: Shape, key: string, value: unknown) =>
+ key === "value" && typeof value === "number" && holder.type === "Literal";
+
+/**
+ * A script's syntax tree as one string, or null when it does not parse. Comments, layout, quote
+ * style, parentheses and semicolons drop out; `maskNumbers` also hides every number literal.
+ */
+export function scriptShape(code: string, maskNumbers = false): string | null {
+ let tree: acorn.Node;
+ try {
+ tree = acorn.parse(code, { ecmaVersion: "latest", allowHashBang: true });
+ } catch {
+ return null;
+ }
+ const tagged = new WeakSet<object>();
+ const dropped = printOnly(tagged);
+ return JSON.stringify(tree, function (this: Shape, key: string, value: unknown) {
+ if (dropped.get(key)?.(this)) return undefined;
+ if (isTaggedTemplate(value)) for (const quasi of value.quasi.quasis) tagged.add(quasi.value);
+ if (typeof value === "bigint") return `${value}n`;
+ if (maskNumbers && isNumberLiteral(this, key, value)) return "num";
+ return value;
+ });
+}
diff --git a/packages/studio/src/utils/gsapLiveRetime.cache.test.ts b/packages/studio/src/utils/gsapLiveRetime.cache.test.ts
new file mode 100644
index 0000000000..e5d212a3f9
--- /dev/null
+++ b/packages/studio/src/utils/gsapLiveRetime.cache.test.ts
@@ -0,0 +1,39 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const reads = vi.hoisted(() => ({ shape: [] as string[] }));
+
+vi.mock("@hyperframes/parsers/gsap-parser-acorn", async (importOriginal) => {
+ const real = await importOriginal<typeof import("@hyperframes/parsers/gsap-parser-acorn")>();
+ return {
+ ...real,
+ scriptShape: (code: string, mask?: boolean) => (
+ reads.shape.push(code), real.scriptShape(code, mask)
+ ),
+ };
+});
+
+const { planLiveRetime } = await import("./gsapLiveRetime");
+
+const at = (start: number) =>
+ `var tl = gsap.timeline({ paused: true });\ntl.to("#a", { x: 1, duration: 1 }, ${start});\nwindow.__timelines["t"] = tl;`;
+
+describe("planLiveRetime", () => {
+ beforeEach(() => {
+ reads.shape.length = 0;
+ });
+
+ it("reads each script's shape once across two drags in a row", () => {
+ expect(planLiveRetime(at(0), at(1)).kind).toBe("retime");
+ expect(planLiveRetime(at(1), at(2)).kind).toBe("retime");
+
+ expect(reads.shape).toEqual([at(0), at(1), at(2)]);
+ });
+
+ it("keeps the live script's shape while saves land before the preview catches up", () => {
+ planLiveRetime(at(10), at(11));
+ planLiveRetime(at(10), at(12));
+ planLiveRetime(at(10), at(13));
+
+ expect(reads.shape).toEqual([at(10), at(11), at(12), at(13)]);
+ });
+});
diff --git a/packages/studio/src/utils/gsapLiveRetime.realGsap.test.ts b/packages/studio/src/utils/gsapLiveRetime.realGsap.test.ts
index 06001a3921..bdd05c50a9 100644
--- a/packages/studio/src/utils/gsapLiveRetime.realGsap.test.ts
+++ b/packages/studio/src/utils/gsapLiveRetime.realGsap.test.ts
@@ -17,9 +17,11 @@ const BEFORE = [
const SAMPLES = Array.from({ length: 25 }, (_, i) => i * 0.25);
/** Runs a composition script and binds its timeline at `at`, as the preview's runtime does. */
-function play(script: string, at = 0, nested = "") {
+function play(script: string, at = 0, nested = "", registered = "") {
const win = { __timelines: {} as Record<string, gsap.core.Timeline> };
new Function("gsap", "window", script)(gsap, win);
+ // Another composition's script, which registers its own timeline beside this one.
+ new Function("gsap", "window", registered)(gsap, win);
const timeline = win.__timelines.t!;
// The runtime nests each sub-composition's timeline into its host's; the script does not know them...
const sub = gsap.timeline().to({}, { duration: 6.7 });
@@ -52,12 +54,12 @@ const shownNow = () =>
);
/** A preview iframe whose live script is `script`, built and bound. */
-function preview(script: string, nested = "") {
+function preview(script: string, nested = "", registered = "") {
const tag = document.createElement("script");
tag.type = "text/plain"; // the runtime already ran it; happy-dom must not run it again
tag.textContent = script;
document.body.appendChild(tag);
- const { win, timeline } = play(script, 0, nested);
+ const { win, timeline } = play(script, 0, nested, registered);
const rebind = vi.fn();
// The runtime hooks a rebind needs; a soft reload would also need `gsap`, which this preview lacks.
Object.assign(win, { __hfForceTimelineRebind: rebind, __player: { seek: vi.fn() } });
@@ -245,6 +247,14 @@ it.each([
after: script('tl.to("#a", { x: 100, duration: 1 }, 3);'),
nested: 'sub.to("#a", { x: 50, duration: 1 }, 2);',
},
+ {
+ name: "another composition's timeline on the moved tween's element",
+ path: "rerun",
+ before: script('tl.to("#a", { x: 100, duration: 1 }, 0);'),
+ after: script('tl.to("#a", { x: 100, duration: 1 }, 3);'),
+ registered:
+ 'window.__timelines.scene = gsap.timeline({ paused: true }).to("#a", { x: 50, duration: 1 }, 2);',
+ },
{
name: "a delayed tween that GSAP orders after the moved one",
path: "rerun",
@@ -300,7 +310,7 @@ it.each([
},
{
name: "a move of a sub-composition's host",
- path: "rerun",
+ path: "retime",
before: script('tl.to("#a", { y: 40, duration: 1 }, 0);'),
after: script('tl.to("#a", { y: 40, duration: 1 }, 2);'),
setup: () => {
@@ -311,17 +321,10 @@ it.each([
},
{
name: "a tween on an element inside a sub-composition's host",
- path: "rerun",
- before: script('tl.to("#a", { y: 40, duration: 1 }, 0);'),
- after: script('tl.to("#a", { y: 40, duration: 1 }, 2);'),
- setup: () => inComposition("t", inComposition("scene", document.getElementById("a")!)),
- },
- {
- name: "a tween on an element of the timeline's own composition",
path: "retime",
before: script('tl.to("#a", { y: 40, duration: 1 }, 0);'),
after: script('tl.to("#a", { y: 40, duration: 1 }, 2);'),
- setup: () => inComposition("t", document.getElementById("a")!),
+ setup: () => inComposition("t", inComposition("scene", document.getElementById("a")!)),
},
{
name: "a set and a tween on one element that round to the same start",
@@ -358,10 +361,10 @@ it.each([
},
])(
"after a drop over $name, the live preview equals a fresh load or the script re-runs",
- async ({ before, after, nested = "", at = 0, path, setup, unplayed }) => {
+ async ({ before, after, nested = "", registered = "", at = 0, path, setup, unplayed }) => {
setup?.();
const error = vi.spyOn(console, "error");
- const live = preview(before, nested);
+ const live = preview(before, nested, registered);
// Played through once, then parked: every tween has recorded its start values.
if (!unplayed) live.timeline.totalTime(live.timeline.duration(), false);
live.timeline.totalTime(at, false);
@@ -371,7 +374,7 @@ it.each([
const shown = shownNow();
const got = observe(live.timeline);
live.timeline.revert();
- const fresh = play(after, at, nested).timeline;
+ const fresh = play(after, at, nested, registered).timeline;
expect(shown).toEqual(shownNow());
expect(got).toEqual(observe(fresh));
}
@@ -433,6 +436,12 @@ it("reloads the preview, and says so, when moving the live tweens throws", async
expect(error).toHaveBeenCalledTimes(1);
});
+it("re-runs the script when the edit also flips an operator in a tween's value", () => {
+ const before = script('tl.to("#a", { x: window.innerWidth - 40, duration: 1 }, 0);');
+ const after = script('tl.to("#a", { x: window.innerWidth + 40, duration: 1 }, 1);');
+ expect(planLiveRetime(before, after).kind).toBe("rerun");
+});
+
it("re-runs the script when the edit also joins two words of code", () => {
const before = script('tl.to("#a", { x: 1, duration: 1 }, 0);', "var b = typeof a;");
const after = script('tl.to("#a", { x: 1, duration: 1 }, 1);', "var b = typeofa;");
@@ -514,6 +523,15 @@ it("syncs a timeline move by moving the live tweens and rebinding, without re-ru
expect(document.querySelectorAll("script")).toHaveLength(1);
});
+it("moves the live tweens when the preview runs the saved script re-printed without its comments", async () => {
+ const live = preview(BEFORE);
+ const saved = `// Seams between sections.\n${moveA().replaceAll('"', "'")}\n/* end */`;
+
+ const reloadPreview = await dropInto(live.iframe, saved);
+
+ expect(reloadPreview).not.toHaveBeenCalled();
+});
+
it("moves the live tweens when the preview runs a reformatted copy of the saved script", async () => {
const live = preview(BEFORE);
live.tag.textContent = reformatted(BEFORE);
diff --git a/packages/studio/src/utils/gsapLiveRetime.ts b/packages/studio/src/utils/gsapLiveRetime.ts
index 0075211edf..045a04f63e 100644
--- a/packages/studio/src/utils/gsapLiveRetime.ts
+++ b/packages/studio/src/utils/gsapLiveRetime.ts
@@ -1,5 +1,5 @@
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
-import { parseGsapScriptAcorn } from "@hyperframes/core/gsap-parser-acorn";
+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 {
@@ -30,19 +30,14 @@ export type LiveRetimePlan =
const RERUN = { kind: "rerun" } as const;
-/** The preview runs a reformatted copy of the script: compare code, not its layout. */
-const withoutLayout = (code: string) =>
- code
- .replace(/\s+/g, " ")
- .replace(/ ?([^\w$ ]) ?/g, "$1")
- .trim();
-
function untimedShape(animation: GsapAnimation): string {
const { id: _id, position: _p, resolvedStart: _s, duration: _d, ...rest } = animation;
// An offset into the text, which moves when the preview reformats its copy of the script.
const provenance = rest.provenance && { ...rest.provenance, sourceRange: undefined };
return JSON.stringify({ ...rest, provenance }, (_key, value) =>
- typeof value === "string" && value.startsWith("__raw:") ? withoutLayout(value) : value,
+ typeof value === "string" && value.startsWith("__raw:")
+ ? (scriptShape(`(${value.slice(6)}\n)`) ?? value)
+ : value,
);
}
@@ -55,13 +50,22 @@ const placedAlone = (animation: GsapAnimation) =>
const lengthOf = (animation: GsapAnimation) =>
animation.method === "set" ? 0 : animation.durationUnresolved ? undefined : animation.duration;
-/** A timing edit rewrites numbers only; anything else may be code the parser does not read. */
-const withoutNumbers = (script: string) =>
- withoutLayout(script.replace(/(?<![\w$#.])\d*\.?\d+/g, "0"));
+/** The last two script shapes, by text: a repeat drag starts from the script the last one saved. */
+const shapes = new Map<string, string | null>();
+
+function shapeOf(code: string): string | null {
+ const shape = shapes.has(code) ? (shapes.get(code) as string | null) : scriptShape(code, true);
+ shapes.delete(code);
+ shapes.set(code, shape);
+ if (shapes.size > 2) shapes.delete(shapes.keys().next().value!);
+ return shape;
+}
/** Decides, from the two scripts alone, whether a saved edit moved tweens and nothing else. */
export function planLiveRetime(before: string, after: string): LiveRetimePlan {
- if (withoutNumbers(before) !== withoutNumbers(after)) return RERUN;
+ // The preview runs the script re-printed by the bundler; a timing edit rewrites numbers only.
+ const shape = shapeOf(before);
+ if (shape === null || shape !== shapeOf(after)) return RERUN;
const keys = timelineKeys(after);
if (keys.length !== 1 || timelineKeys(before).join() !== keys.join()) return RERUN;
const was = parseGsapScriptAcorn(before).animations.filter(onTimeline);
@@ -180,16 +184,6 @@ function sharesOneStretch(tweens: TweenTiming[]): boolean {
return stretch > 0 && fits;
}
-/** The runtime places a sub-composition's timeline at its host's start once; moving the host leaves it there. */
-function inOrHostsSubComposition(target: unknown, ownId: string): boolean {
- const element = target as Element;
- const owner = element.closest?.("[data-composition-id]");
- return (
- (owner != null && owner.getAttribute("data-composition-id") !== ownId) ||
- element.querySelector?.("[data-composition-id]") != null
- );
-}
-
/** Tweens on one element still start in the order they did, an equal start in script order. */
const keepsOrder = (tweens: TweenTiming[]) =>
tweens.every(
@@ -204,6 +198,7 @@ function movesKeepEachElementsHistory(
timeline: LiveTimeline,
plan: LiveRetime,
children: LiveTween[],
+ registry: unknown[],
): boolean {
const byElement = new Map<unknown, number[]>();
children.forEach((child, i) => {
@@ -216,7 +211,6 @@ function movesKeepEachElementsHistory(
const moved = new Set<unknown>();
for (const [target, indexes] of byElement) {
if (!indexes.some((i) => plan.tweens[i]!.moved)) continue;
- if (inOrHostsSubComposition(target, plan.key)) return false;
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);
@@ -224,13 +218,26 @@ function movesKeepEachElementsHistory(
if (!keepsOrder(tweens) || !sharesOneStretch(tweens) || !(shifted || undelayed)) return false;
moved.add(target);
}
- return !timeline
- .getChildren(false, false, true)
- .some((sub) =>
- sub
- .getChildren(true, true, false)
- .some((tween) => tween.targets?.().some((t) => moved.has(t))),
+ 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);
}
/**
@@ -245,7 +252,8 @@ export function applyLiveRetime(iframe: HTMLIFrameElement | null, plan: LiveReti
const children = pairedLiveTweens(timeline, plan);
if (!children) return false;
if (plan.tweens.some((t) => t.moved)) {
- if (!movesKeepEachElementsHistory(timeline, plan, children)) return false;
+ 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]! }))