Skip to content

Write HTML. Render video. Built for agents.

fix(parsers): moving a clip on the timeline moves its inner animations too (#4761)

Miguel Ángelf1c1f1d69cfe
diff --git a/packages/parsers/src/clipTweens.ts b/packages/parsers/src/clipTweens.ts
new file mode 100644
index 0000000000..525a8810b5
--- /dev/null
+++ b/packages/parsers/src/clipTweens.ts
@@ -0,0 +1,48 @@
+import type { GsapAnimation } from "./gsapSerialize.js";
+
+type TweenTarget = Pick<GsapAnimation, "targetSelector" | "hasPartialSelector">;
+type TweenTime = Pick<GsapAnimation, "position" | "implicitPosition">;
+
+// Tweens a timeline move or retime of a clip carries: an own selector, plus (given a DOM) a fully known target
+// set that is the clip or sits inside it with no nearer `data-start` clip. A tween also aiming outside stays put.
+export function clipTweenMatcher(
+ clipSelectors: string | readonly string[],
+ root?: ParentNode,
+): (tween: TweenTarget) => boolean {
+ const own = typeof clipSelectors === "string" ? [clipSelectors] : clipSelectors;
+ const clips = root ? own.flatMap((selector) => queryAll(root, selector)) : [];
+ return ({ targetSelector, hasPartialSelector }) => {
+ if (hasPartialSelector) return false;
+ if (own.includes(targetSelector)) return true;
+ if (!root || clips.length === 0) return false;
+ const targets = queryAll(root, targetSelector);
+ return (
+ targets.length > 0 &&
+ targets.every((target) => {
+ const owner = target.closest("[data-start]");
+ return clips.includes(target) || (owner !== null && clips.includes(owner));
+ })
+ );
+ };
+}
+
+/** Where a GSAP script's clips live: linkedom keeps a `<template>`'s children under it, out of document queries. */
+export function clipQueryRoot(script: Element): ParentNode {
+ return script.closest("template") ?? script.ownerDocument;
+}
+
+/** A written position; an implicit one follows the tween before it and must stay unwritten. */
+export function hasExplicitTime<T extends TweenTime>(
+ animation: T,
+): animation is T & { position: number } {
+ return typeof animation.position === "number" && !animation.implicitPosition;
+}
+
+function queryAll(root: ParentNode, selector: string): Element[] {
+ try {
+ return Array.from(root.querySelectorAll(selector));
+ } catch {
+ // Pseudo-selectors such as a proxy or dwell label never match the DOM.
+ return [];
+ }
+}
diff --git a/packages/parsers/src/gsapParser.ts b/packages/parsers/src/gsapParser.ts
index 777a2d712a..0e83cdbb5d 100644
--- a/packages/parsers/src/gsapParser.ts
+++ b/packages/parsers/src/gsapParser.ts
@@ -51,6 +51,7 @@ export {
} from "./gsapConstants";
import { classifyPropertyGroup, classifyTweenPropertyGroup } from "./gsapConstants";
import type { PropertyGroupName } from "./gsapConstants";
+import { clipTweenMatcher, hasExplicitTime } from "./clipTweens";
import {
findObjectArrayKeyframeIndex,
getCompatibleObjectArrayKeyframeTiming,
@@ -402,6 +403,23 @@ function lookupBinding(name: string, path: AstPath, bindings: TargetBindings): s
return null;
}
+function hasUnresolvedArrayPart(
+ node: AstNode,
+ path: AstPath,
+ scope: ScopeBindings,
+ bindings: TargetBindings,
+ helpers: TargetHelpers,
+): boolean {
+ return (
+ node?.type === "ArrayExpression" &&
+ node.elements.some(
+ (el: AstNode) =>
+ !resolveTargetSelector(el, path, scope, bindings, helpers) ||
+ hasUnresolvedArrayPart(el, path, scope, bindings, helpers),
+ )
+ );
+}
+
/**
* Resolve a tween's first argument to a CSS selector. Handles inline string
* literals, element variables (lexically scoped), arrays of elements (joined
@@ -585,6 +603,7 @@ interface TweenCallInfo {
node: AstNode;
method: GsapMethod;
selector: string;
+ selectorPartial?: boolean;
varsArg: AstNode;
fromArg?: AstNode;
positionArg?: AstNode;
@@ -649,6 +668,9 @@ function findAllTweenCalls(
const selectorValue =
resolveTargetSelector(args[0], path, scope, targetBindings, targetHelpers) ??
"__unresolved__";
+ const partial = hasUnresolvedArrayPart(args[0], path, scope, targetBindings, targetHelpers)
+ ? { selectorPartial: true }
+ : {};
if (method === "fromTo") {
results.push({
@@ -656,6 +678,7 @@ function findAllTweenCalls(
node,
method: "fromTo",
selector: selectorValue,
+ ...partial,
fromArg: args[1],
varsArg: args[2],
positionArg: args[3],
@@ -666,6 +689,7 @@ function findAllTweenCalls(
node,
method: method as GsapMethod,
selector: selectorValue,
+ ...partial,
varsArg: args[1],
positionArg: args[2],
...(isGlobalSet ? { global: true } : {}),
@@ -1134,6 +1158,7 @@ function tweenCallToAnimation(
if (motionPathResult) anim.arcPath = motionPathResult.arcPath;
if (hasUnresolvedKeyframes) anim.hasUnresolvedKeyframes = true;
if (call.selector === "__unresolved__") anim.hasUnresolvedSelector = true;
+ if (call.selectorPartial) anim.hasPartialSelector = true;
return anim;
}
@@ -1543,7 +1568,9 @@ export function shiftPositionsInScript(
script: string,
targetSelector: string,
delta: number,
+ root?: ParentNode,
): string {
+ const carries = clipTweenMatcher(targetSelector, root);
let parsed: ParsedGsapAst;
try {
parsed = parseGsapAst(script);
@@ -1553,8 +1580,7 @@ export function shiftPositionsInScript(
}
let changed = false;
for (const entry of parsed.located) {
- if (entry.animation.targetSelector !== targetSelector) continue;
- if (typeof entry.animation.position !== "number") continue;
+ if (!carries(entry.animation) || !hasExplicitTime(entry.animation)) continue;
const newPos = Math.max(0, Math.round((entry.animation.position + delta) * 1000) / 1000);
applyUpdatesToCall(entry.call, { position: newPos });
changed = true;
@@ -1569,9 +1595,11 @@ export function scalePositionsInScript(
oldDuration: number,
newStart: number,
newDuration: number,
+ root?: ParentNode,
): string {
if (oldDuration <= 0 || newDuration <= 0) return script;
const ratio = newDuration / oldDuration;
+ const carries = clipTweenMatcher(targetSelector, root);
let parsed: ParsedGsapAst;
try {
parsed = parseGsapAst(script);
@@ -1581,13 +1609,14 @@ export function scalePositionsInScript(
}
let changed = false;
for (const entry of parsed.located) {
- if (entry.animation.targetSelector !== targetSelector) continue;
- if (typeof entry.animation.position !== "number") continue;
- const newPos = Math.max(
- 0,
- Math.round((newStart + (entry.animation.position - oldStart) * ratio) * 1000) / 1000,
- );
- const updates: Partial<GsapAnimation> = { position: newPos };
+ if (!carries(entry.animation) || typeof entry.animation.position !== "number") continue;
+ const updates: Partial<GsapAnimation> = {};
+ if (hasExplicitTime(entry.animation)) {
+ updates.position = Math.max(
+ 0,
+ Math.round((newStart + (entry.animation.position - oldStart) * ratio) * 1000) / 1000,
+ );
+ }
if (typeof entry.animation.duration === "number" && entry.animation.duration > 0) {
updates.duration = Math.max(
0.001,
diff --git a/packages/parsers/src/gsapParserAcorn.ts b/packages/parsers/src/gsapParserAcorn.ts
index 675788b4d1..f4d1f3956c 100644
--- a/packages/parsers/src/gsapParserAcorn.ts
+++ b/packages/parsers/src/gsapParserAcorn.ts
@@ -583,6 +583,22 @@ function resolveTargetSelector(
return null;
}
+function hasUnresolvedArrayPart(
+ node: any,
+ ancestors: any[],
+ scope: ScopeBindings,
+ bindings: TargetBindings,
+): boolean {
+ return (
+ node?.type === "ArrayExpression" &&
+ node.elements.some(
+ (el: any) =>
+ !resolveTargetSelector(el, ancestors, scope, bindings) ||
+ hasUnresolvedArrayPart(el, ancestors, scope, bindings),
+ )
+ );
+}
+
/**
* Classify an otherwise-unresolved tween target that is a plain object literal
* (`tl.to({}, …)`) or a proxy object (`tl.to(s, {onUpdate})`). Returns a
@@ -864,6 +880,7 @@ export interface TweenCallInfo {
ancestors: any[];
method: GsapMethod;
selector: string;
+ selectorPartial?: boolean;
varsArg: any;
fromArg?: any;
positionArg?: any;
@@ -929,6 +946,9 @@ function findAllTweenCalls(
? (resolveTargetSelector(args[0], nodeAncestors, scope, targetBindings) ??
"__unresolved__")
: "__unresolved__";
+ const partial = hasUnresolvedArrayPart(args[0], nodeAncestors, scope, targetBindings)
+ ? { selectorPartial: true }
+ : {};
if (method === "fromTo" && args.length >= 3) {
results.push({
@@ -936,6 +956,7 @@ function findAllTweenCalls(
ancestors: nodeAncestors,
method: "fromTo",
selector: selectorValue,
+ ...partial,
fromArg: args[1],
varsArg: args[2],
positionArg: args[3],
@@ -946,6 +967,7 @@ function findAllTweenCalls(
ancestors: nodeAncestors,
method: method as GsapMethod,
selector: selectorValue,
+ ...partial,
varsArg: args[1],
positionArg: args[2],
...(isGlobalSet ? { global: true } : {}),
@@ -1403,6 +1425,7 @@ function tweenCallToAnimation(
if (hasUnresolvedKeyframes) anim.hasUnresolvedKeyframes = true;
if (durationUnresolved) anim.durationUnresolved = true;
if (selector === "__unresolved__") anim.hasUnresolvedSelector = true;
+ if (call.selectorPartial) anim.hasPartialSelector = true;
if (provenance) anim.provenance = provenance;
return anim;
}
@@ -1903,6 +1926,18 @@ const parseMemo = new Map<string, ParsedGsap>();
* Browser-safe equivalent of `parseGsapScript` (gsapParser.ts).
* Uses acorn + acorn-walk instead of recast + @babel/parser.
*/
+/** The script that holds a file's timeline: the first to declare one, else the first with tween calls. */
+export function findTimelineScript<T extends { textContent: string | null }>(
+ scripts: readonly T[],
+): T | null {
+ const text = (script: T) => script.textContent ?? "";
+ return (
+ scripts.find((script) => text(script).includes("gsap.timeline")) ??
+ scripts.find((script) => /\.(set|to)\(/.test(text(script))) ??
+ null
+ );
+}
+
export function parseGsapScriptAcorn(script: string): ParsedGsap {
const parsed = parseMemo.get(script) ?? parseGsapScriptAcornUncached(script);
parseMemo.delete(script);
diff --git a/packages/parsers/src/gsapSerialize.ts b/packages/parsers/src/gsapSerialize.ts
index 227b188f97..d2651f8d6d 100644
--- a/packages/parsers/src/gsapSerialize.ts
+++ b/packages/parsers/src/gsapSerialize.ts
@@ -70,6 +70,7 @@ export interface GsapAnimation {
hasUnresolvedKeyframes?: boolean;
/** True when the tween's target selector couldn't be statically resolved (dynamic). */
hasUnresolvedSelector?: boolean;
+ hasPartialSelector?: boolean;
/** Absolute start time computed by walking the timeline chain (handles +=, -=, <, >, labels). */
resolvedStart?: number;
/** True when no position arg was authored — the tween is sequentially placed by GSAP. */
diff --git a/packages/parsers/src/gsapWriter.parity.test.ts b/packages/parsers/src/gsapWriter.parity.test.ts
index 9e0add6c8d..a5be3e89c7 100644
--- a/packages/parsers/src/gsapWriter.parity.test.ts
+++ b/packages/parsers/src/gsapWriter.parity.test.ts
@@ -7,10 +7,10 @@
* This is the safety net for porting WS-3 ops one at a time: each ported op
* gets a fixture row here proving it matches the battle-tested original.
*
- * The server switches between writers via STUDIO_SDK_CUTOVER_ENABLED (WS-3.F).
- * Recast remains the default; acorn runs only when the flag is enabled.
+ * The server picks the writer from HYPERFRAMES_GSAP_WRITER; acorn is the default.
*/
import { describe, expect, it } from "vitest";
+import { parseHTML } from "linkedom";
import {
parseGsapScript,
removeAllKeyframesFromScript as removeAllRecast,
@@ -1973,3 +1973,93 @@ tl.to("#el", { y: 50, duration: 1 }, "+=0.5");`;
expect(scaleAcorn(POSITIONS_MULTI, "#hero", 0, 1, 2, 0)).toBe(POSITIONS_MULTI);
});
});
+
+describe("shift/scalePositionsInScript carry the clip's inner tweens", () => {
+ const { document } = parseHTML(`<html><body>
+<div id="scene" data-start="1" data-duration="4">
+ <h1 class="title">Hi</h1>
+ <p id="child" class="inner">Kid</p>
+ <div id="nested" data-start="2" data-duration="1"><span id="deep">x</span></div>
+</div>
+<div id="sibling" class="title">Out</div>
+</body></html>`);
+ const script = `const tl = gsap.timeline({ paused: true });
+tl.from("#scene", { opacity: 0, duration: 1 }, 1);
+tl.from("#scene h1", { y: 20, duration: 1 }, 1.5);
+tl.to("#child", { rotation: 90, duration: 1 });
+tl.to("#sibling", { y: 5, duration: 0.5 });
+tl.to("#child", { x: 10, duration: 1 }, 2);
+tl.to(["#child", "#scene h1"], { opacity: 0.5, duration: 1 }, 3);
+tl.to(".inner", { scale: 2, duration: 1 }, 3.5);
+tl.to("#sibling", { x: 5, duration: 1 }, 2);
+tl.to(".title", { color: "red", duration: 1 }, 2.5);
+tl.to("#deep", { y: 5, duration: 0.5 }, 2);
+tl.to(["#scene h1", window.logo], { x: 1, duration: 1 }, 2);
+tl.to(["#scene", window.logo], { x: 2, duration: 1 }, 2);`;
+ const timings = (out: string) =>
+ parseGsapScriptAcorn(out).animations.map((a) => [
+ a.targetSelector,
+ a.implicitPosition ? "chained" : a.position,
+ a.duration,
+ ]);
+ const writers = [
+ ["acorn", shiftAcorn, scaleAcorn],
+ ["recast", shiftRecast, scaleRecast],
+ ] as const;
+
+ const bare = parseHTML(
+ `<html><body><div id="bare" class="card"><p>x</p></div></body></html>`,
+ ).document;
+ const bareScript = `const tl = gsap.timeline({ paused: true });
+tl.to(".card", { x: 1, duration: 1 }, 1);`;
+
+ for (const [name, shift, scale] of writers) {
+ it(`${name}: a tween whose target is the clip moves with it, even without data-start`, () => {
+ expect(timings(shift(bareScript, "#bare", 1, bare))).toEqual([[".card", 2, 1]]);
+ });
+
+ it(`${name}: known limit, an outside tween chained after moved content moves with it`, () => {
+ const sibling = (out: string) => parseGsapScriptAcorn(out).animations[3]!;
+ expect(sibling(script)).toMatchObject({ targetSelector: "#sibling", resolvedStart: 3.5 });
+ expect(sibling(shift(script, "#scene", 2, document))).toMatchObject({
+ targetSelector: "#sibling",
+ implicitPosition: true,
+ resolvedStart: 5.5,
+ });
+ });
+
+ it(`${name}: a shift moves the clip and its descendants, never outside or nested clips`, () => {
+ expect(timings(shift(script, "#scene", 2, document))).toEqual([
+ ["#scene", 3, 1],
+ ["#scene h1", 3.5, 1],
+ ["#child", "chained", 1],
+ ["#sibling", "chained", 0.5],
+ ["#child", 4, 1],
+ ["#child, #scene h1", 5, 1],
+ [".inner", 5.5, 1],
+ ["#sibling", 2, 1],
+ [".title", 2.5, 1],
+ ["#deep", 2, 0.5],
+ ["#scene h1", 2, 1],
+ ["#scene", 2, 1],
+ ]);
+ });
+
+ it(`${name}: a scale retimes the clip and its descendants, never outside or nested clips`, () => {
+ expect(timings(scale(script, "#scene", 1, 4, 1, 8, document))).toEqual([
+ ["#scene", 1, 2],
+ ["#scene h1", 2, 2],
+ ["#child", "chained", 2],
+ ["#sibling", "chained", 0.5],
+ ["#child", 3, 2],
+ ["#child, #scene h1", 5, 2],
+ [".inner", 6, 2],
+ ["#sibling", 2, 1],
+ [".title", 2.5, 1],
+ ["#deep", 2, 0.5],
+ ["#scene h1", 2, 1],
+ ["#scene", 2, 1],
+ ]);
+ });
+ }
+});
diff --git a/packages/parsers/src/gsapWriterAcorn.ts b/packages/parsers/src/gsapWriterAcorn.ts
index b1dd333919..ed5f294e0a 100644
--- a/packages/parsers/src/gsapWriterAcorn.ts
+++ b/packages/parsers/src/gsapWriterAcorn.ts
@@ -32,6 +32,9 @@ import {
} from "./gsapObjectArrayTiming.js";
import type { SplitAnimationsOptions, SplitAnimationsResult } from "./gsapSerialize.js";
import * as acornWalk from "acorn-walk";
+import { clipQueryRoot, clipTweenMatcher, hasExplicitTime } from "./clipTweens.js";
+
+export { clipQueryRoot, clipTweenMatcher, hasExplicitTime };
// acorn ESTree nodes are structurally untyped here; mirror gsapParserAcorn.ts /
// gsapInline.ts rather than re-deriving the full ESTree union for every access.
@@ -445,7 +448,7 @@ function overwritePosition(ms: MagicString, call: TweenCallInfo, position: numbe
}
/**
- * Shift every tween targeting `targetSelector` by `delta` seconds (clamped ≥0),
+ * Shift every tween the clip at `targetSelector` carries by `delta` seconds (clamped ≥0),
* rewriting each call's position argument. Mirrors recast's shiftPositionsInScript
* (used by timeline clip-move to keep GSAP positions in sync with the clip start).
*/
@@ -453,14 +456,15 @@ export function shiftPositionsInScript(
script: string,
targetSelector: string,
delta: number,
+ root?: ParentNode,
): string {
const parsed = parseGsapScriptAcornForWrite(script);
if (!parsed) return script;
+ const carries = clipTweenMatcher(targetSelector, root);
const ms = new MagicString(script);
let changed = false;
for (const entry of parsed.located) {
- if (entry.animation.targetSelector !== targetSelector) continue;
- if (typeof entry.animation.position !== "number") continue;
+ if (!carries(entry.animation) || !hasExplicitTime(entry.animation)) continue;
overwritePosition(ms, entry.call, shiftedPosition(entry.animation.position, delta));
changed = true;
}
@@ -564,7 +568,7 @@ function isLoopOrForEach(node: Node): boolean {
}
/**
- * Linearly remap every tween targeting `targetSelector` from the old clip
+ * Linearly remap every tween the clip at `targetSelector` carries from the old clip
* [oldStart, oldDuration] onto the new [newStart, newDuration] (position and,
* when present, duration scaled by the duration ratio). Mirrors recast's
* scalePositionsInScript (used by timeline clip-resize).
@@ -576,21 +580,24 @@ export function scalePositionsInScript(
oldDuration: number,
newStart: number,
newDuration: number,
+ root?: ParentNode,
): string {
if (oldDuration <= 0 || newDuration <= 0) return script;
const ratio = newDuration / oldDuration;
const parsed = parseGsapScriptAcornForWrite(script);
if (!parsed) return script;
+ const carries = clipTweenMatcher(targetSelector, root);
const ms = new MagicString(script);
let changed = false;
for (const entry of parsed.located) {
- if (entry.animation.targetSelector !== targetSelector) continue;
- if (typeof entry.animation.position !== "number") continue;
- const newPos = Math.max(
- 0,
- Math.round((newStart + (entry.animation.position - oldStart) * ratio) * 1000) / 1000,
- );
- overwritePosition(ms, entry.call, newPos);
+ if (!carries(entry.animation) || typeof entry.animation.position !== "number") continue;
+ if (hasExplicitTime(entry.animation)) {
+ const newPos = Math.max(
+ 0,
+ Math.round((newStart + (entry.animation.position - oldStart) * ratio) * 1000) / 1000,
+ );
+ overwritePosition(ms, entry.call, newPos);
+ }
if (typeof entry.animation.duration === "number" && entry.animation.duration > 0) {
const newDur = Math.max(0.001, Math.round(entry.animation.duration * ratio * 1000) / 1000);
upsertProp(ms, entry.call.varsArg, "duration", newDur);
diff --git a/packages/sdk/src/engine/model.ts b/packages/sdk/src/engine/model.ts
index 3eb4c1aea2..16515de1db 100644
--- a/packages/sdk/src/engine/model.ts
+++ b/packages/sdk/src/engine/model.ts
@@ -6,6 +6,7 @@
*/
import { parseHTML } from "linkedom";
+import { findTimelineScript } from "@hyperframes/core/gsap-parser-acorn";
import { findVariableDeclaration } from "./variableModel.js";
import {
ensureHfIds,
@@ -474,12 +475,13 @@ export function getGsapScripts(document: Document): string[] {
.filter(isGsapScriptText);
}
-function findGsapScriptElement(document: Document): Element | null {
- for (const script of findScriptElementsDeep(document)) {
- const text = script.textContent ?? "";
- if (isGsapScriptText(text)) return script;
- }
- return null;
+export function findGsapScriptElement(document: Document): Element | null {
+ const scripts = findScriptElementsDeep(document);
+ return (
+ findTimelineScript(scripts) ??
+ scripts.find((s) => isGsapScriptText(s.textContent ?? "")) ??
+ null
+ );
}
export function getGsapScript(document: Document): string | null {
diff --git a/packages/sdk/src/engine/mutate.gsap.test.ts b/packages/sdk/src/engine/mutate.gsap.test.ts
index 5083ae1c2b..11a1e70c31 100644
--- a/packages/sdk/src/engine/mutate.gsap.test.ts
+++ b/packages/sdk/src/engine/mutate.gsap.test.ts
@@ -1081,6 +1081,60 @@ describe("handleSetTiming GSAP sync (CF2 #15/#16)", () => {
expect(script).not.toMatch(/tl\.to\("#box",[^)]*\}, \d/);
});
+ it("moving a scene carries its children's tweens, not chained, partly known or outside ones", () => {
+ const parsed =
+ parseMutable(`<div data-hf-id="hf-stage" data-hf-root style="width: 1280px; height: 720px">
+ <div id="scene" data-hf-id="hf-scene" data-start="1" data-duration="3"><h1 data-hf-id="hf-title">Hi</h1></div>
+ <div id="side" data-hf-id="hf-side" data-start="0" data-duration="5"></div>
+ <script>var tl = gsap.timeline({ paused: true });
+tl.from("#scene h1", { y: 20, duration: 1 }, 1);
+tl.to("#scene h1", { x: 5, duration: 1 });
+tl.to("#side", { y: 1, duration: 0.5 });
+tl.to(["#scene h1", window.logo], { x: 1, duration: 1 }, 2);
+tl.to("#side", { x: 5, duration: 1 }, 1);
+window.__timelines["t"] = tl;</script>
+</div>`);
+ applyOp(parsed, { type: "setTiming", target: "hf-scene", start: 3 });
+ const script = getScript(parsed);
+ expect(script).toContain('tl.from("#scene h1", { y: 20, duration: 1 }, 3);');
+ expect(script).toContain('tl.to("#scene h1", { x: 5, duration: 1 });');
+ expect(script).toContain('tl.to(["#scene h1", window.logo], { x: 1, duration: 1 }, 2);');
+ expect(script).toContain('tl.to("#side", { x: 5, duration: 1 }, 1);');
+ // Known limit: the chained outside tween stays unwritten, so it follows the moved content.
+ expect(script).toContain('tl.to("#side", { y: 1, duration: 0.5 });');
+ });
+
+ it("moving a clip syncs the timeline script even when a config script comes first", () => {
+ const parsed =
+ parseMutable(`<div data-hf-id="hf-stage" data-hf-root style="width: 1280px; height: 720px">
+ <div id="scene" data-hf-id="hf-scene" data-start="1" data-duration="3"><h1 data-hf-id="hf-title">Hi</h1></div>
+ <script>gsap.config({ nullTargetWarn: false });</script>
+ <script>var tl = gsap.timeline({ paused: true });
+tl.from("#scene h1", { y: 20, duration: 1 }, 1.5);
+window.__timelines["t"] = tl;</script>
+</div>`);
+ applyOp(parsed, { type: "setTiming", target: "hf-scene", start: 3 });
+ const html = serializeDocument(parsed);
+ expect(html).toContain("gsap.config({ nullTargetWarn: false });");
+ expect(html).toContain('tl.from("#scene h1", { y: 20, duration: 1 }, 3.5);');
+ });
+
+ it("moving a clip in a template-wrapped composition carries its tweens", () => {
+ const parsed = parseMutable(`<template id="card-template">
+ <div data-composition-id="card-comp" data-hf-id="hf-comp" data-width="1280" data-height="720">
+ <div id="card" data-hf-id="hf-card" data-start="1" data-duration="2"><h1 data-hf-id="hf-t">Hi</h1></div>
+ <script>var tl = gsap.timeline({ paused: true });
+tl.to("[data-hf-id=\\"hf-card\\"]", { x: 1, duration: 1 }, 1);
+tl.from("#card h1", { y: 20, duration: 1 }, 1.5);
+window.__timelines["card-comp"] = tl;</script>
+ </div>
+</template>`);
+ applyOp(parsed, { type: "setTiming", target: "hf-card", start: 3 });
+ const script = getScript(parsed);
+ expect(script).toContain("{ x: 1, duration: 1 }, 3);");
+ expect(script).toContain('tl.from("#card h1", { y: 20, duration: 1 }, 3.5);');
+ });
+
it("canonicalizes a clip carrying both authored duration and derived end", () => {
const parsed = timingDoc(
`data-start="1" data-duration="2" data-end="3"`,
diff --git a/packages/sdk/src/engine/mutate.ts b/packages/sdk/src/engine/mutate.ts
index 8498ba9445..8b18eb5b32 100644
--- a/packages/sdk/src/engine/mutate.ts
+++ b/packages/sdk/src/engine/mutate.ts
@@ -29,6 +29,7 @@ import {
setOwnText,
getSiblingIndex,
getGsapScript,
+ findGsapScriptElement,
setGsapScript,
getStyleSheet,
setStyleSheet,
@@ -77,6 +78,9 @@ import {
updateArcSegmentInScript,
removeArcPathFromScript,
unrollDynamicAnimations,
+ clipQueryRoot,
+ clipTweenMatcher,
+ hasExplicitTime,
} from "@hyperframes/core/gsap-writer-acorn";
import { deriveKeyframeBackfillDefaults } from "./keyframeBackfill.js";
import {
@@ -457,6 +461,8 @@ function handleSetTiming(
// we avoid re-fetching the script element on every iteration.
const origScript = getGsapScript(parsed.document);
const parsedGsap = origScript ? parseGsapScriptAcornForWrite(origScript) : null;
+ const scriptElement = findGsapScriptElement(parsed.document);
+ const clipRoot = scriptElement ? clipQueryRoot(scriptElement) : parsed.document;
let currentScript = origScript;
for (const id of ids) {
@@ -541,12 +547,17 @@ function handleSetTiming(
// Sync GSAP tween positions: the GSAP script is the source of truth at play time —
// the timeline rebuilds from it on every seek. Without this, DOM attribute edits
// have zero playback effect; the script's position/duration silently overrides them.
- // Match against BOTH the element's data-hf-id (the canonical form) AND its DOM
- // id: the Studio GSAP panel / ensureElementAddressable author tweens as
- // `#domId`, which selectorMatchesId(hfId) never matched — so moving/resizing
- // those clips left their tweens unsynced.
- const matchHfId = el.getAttribute("data-hf-id") ?? id;
- const matchDomId = el.getAttribute("id");
+ const hfId = el.getAttribute("data-hf-id") ?? id;
+ const domId = el.getAttribute("id");
+ const carries = clipTweenMatcher(
+ [
+ `[data-hf-id="${hfId}"]`,
+ `[data-hf-id='${hfId}']`,
+ `#${hfId}`,
+ ...(domId ? [`#${domId}`] : []),
+ ],
+ clipRoot,
+ );
if (parsedGsap && currentScript) {
// A missing data-start means an implicit start of 0 (matching the server
// shiftGsapPositions path); a malformed attr parses to NaN. Sanitize to a
@@ -566,10 +577,7 @@ function handleSetTiming(
: 1;
const remapStart = startChanged && newStart !== null ? newStart : oldStartNum;
for (const { id: animId, animation } of parsedGsap.located) {
- const matches =
- selectorMatchesId(animation.targetSelector, matchHfId) ||
- (matchDomId !== null && selectorMatchesId(animation.targetSelector, matchDomId));
- if (!matches) continue;
+ if (!carries(animation)) continue;
// Skip tweens whose position is a label or relative string ("+=0.5",
// "<", ">"): relative positions already track their neighbours, and a
// string position can't be safely shifted by the clip delta here.
@@ -581,7 +589,7 @@ function handleSetTiming(
// explicit position arg → parsed as implicitPosition): the writer would
// APPEND a position arg, collapsing the stagger onto one point. Duration
// still scales below.
- if ((startChanged || durChanged) && animation.implicitPosition !== true) {
+ if ((startChanged || durChanged) && hasExplicitTime(animation)) {
const shifted = remapStart + (animation.position - oldStartNum) * ratio;
updates.position = Math.max(0, Math.round(shifted * 1000) / 1000);
}
diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.ts
index 26f98d6679..bb018acb12 100644
--- a/packages/studio-server/src/routes/files.test.ts
+++ b/packages/studio-server/src/routes/files.test.ts
@@ -2510,6 +2510,60 @@ tl.to("#b", { duration: 1, x: 200 }, 2);
expect(result.mutated).toBe(false);
});
+ it("moving or stretching a clip retimes the tweens inside it and leaves outside ones alone", async () => {
+ const comp = `<template id="scene-template">
+ <div data-composition-id="scene" data-width="1920" data-height="1080">
+ <div id="card" class="clip" data-start="1" data-duration="2"><h1>Hi</h1><p id="line">Kid</p>
+ <div id="pip" class="clip" data-start="1.5" data-duration="1"><i id="dot"></i></div>
+ </div>
+ <div id="side" class="clip" data-start="0" data-duration="3"></div>
+ </div>
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ tl.from("#card h1", { y: 20, duration: 1 }, 1);
+ tl.to("#line", { x: 10, duration: 1 }, 1.5);
+ tl.to("#side", { x: 5, duration: 1 }, 1);
+ tl.to("#dot", { x: 1, duration: 1 }, 1.5);
+ window.__timelines["scene"] = tl;
+ </script>
+</template>`;
+ const projectDir = createProjectDir();
+ writeComp(projectDir, "scene.html", comp);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+ const mutate = async (body: object) => {
+ const res = await app.request(
+ "http://localhost/projects/demo/gsap-mutations/compositions/scene.html",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ },
+ );
+ expect(res.status).toBe(200);
+ return ((await res.json()) as { after: string }).after;
+ };
+
+ const moved = await mutate({ type: "shift-positions", targetSelector: "#card", delta: 2 });
+ expect(moved).toContain('tl.from("#card h1", { y: 20, duration: 1 }, 3);');
+ expect(moved).toContain('tl.to("#line", { x: 10, duration: 1 }, 3.5);');
+ expect(moved).toContain('tl.to("#side", { x: 5, duration: 1 }, 1);');
+ expect(moved).toContain('tl.to("#dot", { x: 1, duration: 1 }, 1.5);');
+
+ const stretched = await mutate({
+ type: "scale-positions",
+ targetSelector: "#card",
+ oldStart: 3,
+ oldDuration: 2,
+ newStart: 3,
+ newDuration: 4,
+ });
+ expect(stretched).toContain('tl.from("#card h1", { y: 20, duration: 2 }, 3);');
+ expect(stretched).toContain('tl.to("#line", { x: 10, duration: 2 }, 4);');
+ expect(stretched).toContain('tl.to("#side", { x: 5, duration: 1 }, 1);');
+ expect(stretched).toContain('tl.to("#dot", { x: 1, duration: 1 }, 1.5);');
+ });
+
it("rejects a shift-positions-batch with a missing/non-array `shifts` field (400)", async () => {
const projectDir = createProjectDir();
writeHtml(
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts
index 90f63ed379..d710117fac 100644
--- a/packages/studio-server/src/routes/files.ts
+++ b/packages/studio-server/src/routes/files.ts
@@ -46,7 +46,7 @@ import {
} from "../helpers/finiteMutation.js";
import type { GsapAnimation } from "@hyperframes/parsers";
import { classifyPropertyGroup } from "@hyperframes/parsers/gsap-constants";
-import { parseGsapScriptAcorn } from "@hyperframes/parsers/gsap-parser-acorn";
+import { findTimelineScript, parseGsapScriptAcorn } from "@hyperframes/parsers/gsap-parser-acorn";
import { unrollComputedTimeline } from "@hyperframes/parsers";
import {
updateAnimationInScript,
@@ -75,6 +75,7 @@ import {
scalePositionsInScript,
dedupePositionWritesInScript,
syncPositionHoldsBeforeKeyframes,
+ clipQueryRoot,
} from "@hyperframes/parsers/gsap-writer-acorn";
import {
removeElementFromHtml,
@@ -674,6 +675,7 @@ function updateReferences(projectDir: string, oldPath: string, newPath: string):
function extractGsapScriptBlock(html: string): {
scriptText: string;
document: Document;
+ root: ParentNode;
replaceScript: (newText: string) => string;
} | null {
const { document } = parseHTML(ensureHfIds(html));
@@ -683,24 +685,17 @@ function extractGsapScriptBlock(html: string): {
Array.from(tmpl.querySelectorAll("script:not([src])")),
),
];
- for (const script of scripts) {
- const content = script.textContent || "";
- if (
- content.includes("gsap.timeline") ||
- content.includes(".set(") ||
- content.includes(".to(")
- ) {
- return {
- scriptText: content,
- document,
- replaceScript(newText: string): string {
- script.textContent = newText;
- return document.toString();
- },
- };
- }
- }
- return null;
+ const script = findTimelineScript(scripts);
+ if (!script) return null;
+ return {
+ scriptText: script.textContent || "",
+ document,
+ root: clipQueryRoot(script),
+ replaceScript(newText: string): string {
+ script.textContent = newText;
+ return document.toString();
+ },
+ };
}
/**
@@ -1705,13 +1700,13 @@ function executeGsapMutationAcorn(
case "shift-positions": {
const { targetSelector, delta } = body;
if (!targetSelector || !Number.isFinite(delta) || delta === 0) return block.scriptText;
- return shiftPositionsInScript(block.scriptText, targetSelector, delta);
+ return shiftPositionsInScript(block.scriptText, targetSelector, delta, block.root);
}
case "shift-positions-batch": {
let script = block.scriptText;
for (const s of body.shifts) {
if (!s.targetSelector || !Number.isFinite(s.delta) || s.delta === 0) continue;
- script = shiftPositionsInScript(script, s.targetSelector, s.delta);
+ script = shiftPositionsInScript(script, s.targetSelector, s.delta, block.root);
}
return script;
}
@@ -1735,6 +1730,7 @@ function executeGsapMutationAcorn(
oldDuration,
newStart,
newDuration,
+ block.root,
);
}
default:
@@ -2077,14 +2073,14 @@ async function executeGsapMutationRecast(
const { targetSelector, delta } = body;
if (!targetSelector || !Number.isFinite(delta) || delta === 0) return block.scriptText;
const { shiftPositionsInScript } = parser;
- return shiftPositionsInScript(block.scriptText, targetSelector, delta);
+ return shiftPositionsInScript(block.scriptText, targetSelector, delta, block.root);
}
case "shift-positions-batch": {
const { shiftPositionsInScript } = parser;
let script = block.scriptText;
for (const s of body.shifts) {
if (!s.targetSelector || !Number.isFinite(s.delta) || s.delta === 0) continue;
- script = shiftPositionsInScript(script, s.targetSelector, s.delta);
+ script = shiftPositionsInScript(script, s.targetSelector, s.delta, block.root);
}
return script;
}
@@ -2109,6 +2105,7 @@ async function executeGsapMutationRecast(
oldDuration,
newStart,
newDuration,
+ block.root,
);
}
default:
diff --git a/packages/studio/src/hooks/timelineTimingSync.ts b/packages/studio/src/hooks/timelineTimingSync.ts
index e66ff3bc84..484061a586 100644
--- a/packages/studio/src/hooks/timelineTimingSync.ts
+++ b/packages/studio/src/hooks/timelineTimingSync.ts
@@ -3,7 +3,11 @@
// edit's undo history, and swapping the rewritten script into the live preview
// without a full iframe reload when possible.
import { type TimelineElement, usePlayerStore } from "../player/store/playerStore";
-import { applySoftReload, applySoftReloadFinalization } from "../utils/gsapSoftReload";
+import {
+ applySoftReload,
+ applySoftReloadFinalization,
+ extractGsapScriptText,
+} from "../utils/gsapSoftReload";
import { furthestClipEndFromDocument } from "../player/lib/timelineElementHelpers";
import type { RecordEditInput } from "../utils/studioFileHistory";
import { patchDocumentRootDuration } from "./timelineEditingGsap";
@@ -15,6 +19,9 @@ import {
rollbackOwnedMutation,
type GsapMutationStatus,
} from "./gsapMutationClient";
+import type { CutoverResult } from "../utils/sdkEditTransaction";
+import { findTimelineScript } from "@hyperframes/core/gsap-parser-acorn";
+import { walkCompositionDescendants } from "@hyperframes/parsers/hf-ids";
import {
serializeStudioFileMutations,
type StudioProjectFileWriter,
@@ -365,6 +372,21 @@ export async function scaleGsapPositions(
);
}
+/** The GSAP sync a committed SDK timing write made, or null when its timeline script is unchanged. */
+export function sdkTimingGsapSync(
+ result: Extract<CutoverResult, { status: "committed" }>,
+): GsapMutationStatus | null {
+ const timelineText = (html: string) => {
+ const scripts: Element[] = [];
+ walkCompositionDescendants(new DOMParser().parseFromString(html, "text/html"), (el) => {
+ if (el.tagName.toLowerCase() === "script") scripts.push(el);
+ });
+ return findTimelineScript(scripts)?.textContent ?? null;
+ };
+ if (timelineText(result.before) === timelineText(result.after)) return null;
+ return { mutated: true, scriptText: extractGsapScriptText(result.after) };
+}
+
/** Timing delta a single-clip edit applies to its GSAP tweens. */
export type SingleClipGsapEdit =
| { kind: "shift"; delta: number }
@@ -395,8 +417,9 @@ export function finishClipTimingFallback(input: {
recordEdit: (edit: RecordEditInput) => Promise<void>;
writeProjectFile: StudioProjectFileWriter;
edit: SingleClipGsapEdit;
+ sdkGsap?: GsapMutationStatus | null;
}): Promise<void> {
- const { projectId, targetPath, domId, edit } = input;
+ const { projectId, targetPath, domId, edit, sdkGsap } = input;
const timingChanged =
edit.kind === "shift"
? edit.delta !== 0
@@ -418,8 +441,9 @@ export function finishClipTimingFallback(input: {
return finishTimelineTimingFallback({
iframe: input.iframe,
reloadPreview: input.reloadPreview,
- gsapMutation:
- timingChanged && domId && projectId
+ gsapMutation: sdkGsap
+ ? () => Promise.resolve(sdkGsap)
+ : timingChanged && domId && projectId
? () =>
foldGsapMutationIntoHistory({
writeFile: input.writeProjectFile,
@@ -463,12 +487,24 @@ export async function finishGroupTimingGsapFallback<C extends { element: Timelin
resolveChangePath: (element: TimelineElement) => string;
/** Per-change GSAP mutation; return null to skip a change with no timing delta. */
mutateChange: (change: C, changePath: string) => Promise<GsapMutationStatus> | null;
+ sdkGsap?: GsapMutationStatus | null;
}): Promise<void> {
const activePath = input.activeCompPath || "index.html";
const otherFileChanged = input.changes.some(
(change) => input.resolveChangePath(change.element) !== activePath,
);
const onGsapError = (err: unknown) => console.error(`[Timeline] ${input.errorLabel}`, err);
+ const { sdkGsap } = input;
+ if (sdkGsap) {
+ await finishTimelineTimingFallback({
+ iframe: input.iframe,
+ reloadPreview: input.reloadPreview,
+ gsapMutation: () => Promise.resolve(sdkGsap),
+ onGsapError,
+ rebindWhenUnmutated: !otherFileChanged,
+ });
+ return;
+ }
await finishTimelineTimingFallback({
iframe: input.iframe,
reloadPreview: input.reloadPreview,
diff --git a/packages/studio/src/hooks/useDomEditCommits.test.tsx b/packages/studio/src/hooks/useDomEditCommits.test.tsx
index 60b5b554b0..8761f2903f 100644
--- a/packages/studio/src/hooks/useDomEditCommits.test.tsx
+++ b/packages/studio/src/hooks/useDomEditCommits.test.tsx
@@ -1204,7 +1204,12 @@ describe("useDomEditCommits style persist handling", () => {
const fetchMock = stubPatchFetch({ ok: true, changed: true, matched: true });
const { iframe, element } = createPreviewElement();
const rendered = renderDomEditCommits(createSelection(element), iframe, {
- onTrySdkPersist: async () => ({ status: "committed", version: "sdk-version-2" }),
+ onTrySdkPersist: async () => ({
+ status: "committed",
+ version: "sdk-version-2",
+ before: "",
+ after: "",
+ }),
});
try {
diff --git a/packages/studio/src/hooks/useElementLifecycleOps.multiDelete.test.tsx b/packages/studio/src/hooks/useElementLifecycleOps.multiDelete.test.tsx
index 93d1a90403..3a316bd617 100644
--- a/packages/studio/src/hooks/useElementLifecycleOps.multiDelete.test.tsx
+++ b/packages/studio/src/hooks/useElementLifecycleOps.multiDelete.test.tsx
@@ -92,7 +92,9 @@ describe("useElementLifecycleOps — deleting a canvas multi-selection", () => {
it("reports a successful SDK delete as landed", async () => {
const ops = mountDeleteOps({
projectIdRef: { current: "p1" },
- onTrySdkDelete: vi.fn(async () => ({ status: "committed", version: "v1" }) as const),
+ onTrySdkDelete: vi.fn(
+ async () => ({ status: "committed", version: "v1", before: "", after: "" }) as const,
+ ),
});
const target = { ...selectionFor("a"), hfId: "hf-a" };
diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx
index fc7b07f7c4..d6c933d547 100644
--- a/packages/studio/src/hooks/useTimelineEditing.test.tsx
+++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx
@@ -21,6 +21,10 @@ import {
resolveTimelineGroupResizeChanges,
} from "../player/components/timelineGroupEditing";
import { createRuntimeStartTimeResolver } from "@hyperframes/core/runtime/start-resolver";
+import {
+ scalePositionsInScript,
+ shiftPositionsInScript,
+} from "@hyperframes/core/gsap-writer-acorn";
vi.mock("../components/editor/manualEditingAvailability", async (importOriginal) => {
const actual =
@@ -134,6 +138,7 @@ function renderTimelineEditingHook(input: {
invalidateGsapCache?: () => void;
showToast?: (message: string, kind?: string) => void;
canEdit?: NonNullable<Parameters<typeof useTimelineEditing>[0]["canEdit"]>;
+ activeCompPath?: string;
}): {
move: ReturnType<typeof useTimelineEditing>["handleTimelineElementMove"];
resize: ReturnType<typeof useTimelineEditing>["handleTimelineElementResize"];
@@ -166,7 +171,7 @@ function renderTimelineEditingHook(input: {
commitRef.current = input.onZIndexCommit;
const hook = useTimelineEditing({
projectId: input.projectId ?? null,
- activeCompPath: "index.html",
+ activeCompPath: input.activeCompPath ?? "index.html",
timelineElements: input.timelineElements,
showToast: input.showToast ?? vi.fn(),
writeProjectFile: input.writeProjectFile ?? vi.fn(),
@@ -372,39 +377,6 @@ function setupSingleClipHarness(options?: {
};
}
-const SDK_KEYFRAMED_SOURCE = [
- `<div data-hf-id="hf-stage" data-hf-root data-composition-id="main" data-duration="10">`,
- ` <div id="clip" data-hf-id="hf-clip" data-start="1" data-duration="2"></div>`,
- `</div>`,
- `<script>`,
- `const tl = gsap.timeline({ paused: true });`,
- `tl.to("#clip", { keyframes: [{ x: 0 }, { x: 100 }], duration: 2 }, 1);`,
- `window.__timelines = [tl];`,
- `</script>`,
-].join("\n");
-
-async function setupSdkKeyframedClipHarness() {
- const iframe = createPreviewIframe([{ id: "clip", track: 0 }]);
- const clip = timelineElement({ id: "clip", track: 0, zIndex: 0, start: 1 });
- const sdkSession = await openComposition(SDK_KEYFRAMED_SOURCE);
- const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
- const invalidateGsapCache = vi.fn();
- const fetchMock = stubProjectFetch(SDK_KEYFRAMED_SOURCE);
- usePlayerStore.getState().setDuration(10);
- const hook = renderTimelineEditingHook({
- timelineElements: [clip],
- iframe,
- onZIndexCommit: vi.fn().mockResolvedValue(undefined),
- projectId: "p1",
- writeProjectFile,
- recordEdit: vi.fn(async () => {}),
- sdkSession,
- publishSdkSession: vi.fn<TimelinePublishSdkSession>(() => "published"),
- invalidateGsapCache,
- });
- return { clip, fetchMock, hook, invalidateGsapCache, writeProjectFile };
-}
-
/** Assert a lane write landed in both the live iframe DOM and the persisted file. */
function expectLanePersisted(
iframe: HTMLIFrameElement,
@@ -830,58 +802,6 @@ describe("useTimelineEditing timeline z-index reorder", () => {
h.unmount();
});
- it("shifts authored GSAP positions after an SDK-backed clip move commits", async () => {
- const { clip, fetchMock, hook, invalidateGsapCache, writeProjectFile } =
- await setupSdkKeyframedClipHarness();
-
- await act(async () => {
- await hook.move(clip, { start: 2.25, track: clip.track });
- });
-
- expect(writeProjectFile.mock.calls[0]?.[1]).toContain('data-start="2.25"');
- const mutationCall = fetchMock.mock.calls.find((call) =>
- requestUrl(call[0]).includes("/gsap-mutations/"),
- );
- expect(mutationCall).toBeDefined();
- const init = mutationCall?.[1] as RequestInit | undefined;
- expect(JSON.parse(String(init?.body))).toEqual({
- type: "shift-positions",
- targetSelector: "#clip",
- delta: 1.25,
- });
- expect(invalidateGsapCache).toHaveBeenCalledTimes(1);
-
- hook.unmount();
- });
-
- it("scales authored GSAP positions after an SDK-backed clip resize commits", async () => {
- const { clip, fetchMock, hook, invalidateGsapCache, writeProjectFile } =
- await setupSdkKeyframedClipHarness();
-
- await act(async () => {
- await hook.resize(clip, { start: 2, duration: 4, playbackStart: undefined });
- });
-
- expect(writeProjectFile.mock.calls[0]?.[1]).toContain('data-start="2"');
- expect(writeProjectFile.mock.calls[0]?.[1]).toContain('data-duration="4"');
- const mutationCall = fetchMock.mock.calls.find((call) =>
- requestUrl(call[0]).includes("/gsap-mutations/"),
- );
- expect(mutationCall).toBeDefined();
- const init = mutationCall?.[1] as RequestInit | undefined;
- expect(JSON.parse(String(init?.body))).toEqual({
- type: "scale-positions",
- targetSelector: "#clip",
- oldStart: 1,
- oldDuration: 2,
- newStart: 2,
- newDuration: 4,
- });
- expect(invalidateGsapCache).toHaveBeenCalledTimes(1);
-
- hook.unmount();
- });
-
it("persists a vertical-only lane move (start unchanged) through the single-element fallback", async () => {
// Regression: `if (!startChanged) return` ran BEFORE the file persist, so a
// pure lane change routed through onMoveElement (no onMoveElements wired)
@@ -993,55 +913,6 @@ describe("useTimelineEditing timeline z-index reorder", () => {
unmount();
});
- it("shifts every keyed clip and invalidates the cache after an SDK-backed group move", async () => {
- const source = [
- `<div data-hf-id="hf-stage" data-hf-root data-duration="10">`,
- ` <div id="a" data-hf-id="hf-a" data-start="0" data-duration="1"></div>`,
- ` <div id="b" data-hf-id="hf-b" data-start="1" data-duration="1"></div>`,
- `</div>`,
- `<script>`,
- `const tl = gsap.timeline({ paused: true });`,
- `tl.to("#a", { keyframes: [{ x: 0 }, { x: 100 }], duration: 1 }, 0);`,
- `tl.to("#b", { keyframes: [{ x: 0 }, { x: 100 }], duration: 1 }, 1);`,
- `window.__timelines = [tl];`,
- `</script>`,
- ].join("\n");
- const { iframe, a, b } = makeTwoClipPair();
- const sdkSession = await openComposition(source);
- const fetchMock = stubProjectFetch(source);
- const invalidateGsapCache = vi.fn();
- usePlayerStore.getState().setDuration(10);
- const hook = renderTimelineEditingHook({
- timelineElements: [a, b],
- iframe,
- onZIndexCommit: vi.fn().mockResolvedValue(undefined),
- projectId: "p1",
- writeProjectFile: vi.fn<(...args: unknown[]) => Promise<void>>(async () => {}),
- recordEdit: vi.fn(async () => {}),
- sdkSession,
- publishSdkSession: vi.fn<TimelinePublishSdkSession>(() => "published"),
- invalidateGsapCache,
- });
-
- await act(async () => {
- await hook.groupMove([
- { element: a, start: 1 },
- { element: b, start: 2 },
- ]);
- });
-
- const mutations = fetchMock.mock.calls
- .filter((call) => requestUrl(call[0]).includes("/gsap-mutations/"))
- .map((call) => JSON.parse(String((call[1] as RequestInit | undefined)?.body)));
- expect(mutations).toEqual([
- { type: "shift-positions", targetSelector: "#a", delta: 1 },
- { type: "shift-positions", targetSelector: "#b", delta: 1 },
- ]);
- expect(invalidateGsapCache).toHaveBeenCalledTimes(1);
-
- hook.unmount();
- });
-
it("partitions a group move by source file while keeping one undo entry", async () => {
const files: Record<string, string> = {
"index.html": '<div id="a" data-start="0" data-duration="1"></div>',
@@ -2353,3 +2224,187 @@ describe("useTimelineEditing: nested rows write composition-local starts", () =>
hook.unmount();
});
});
+
+describe("clip timing edits sync GSAP exactly once", () => {
+ const SCENE_PATH = "compositions/scene.html";
+ const SCENE_SOURCE = [
+ `<div data-hf-id="hf-stage" data-hf-root data-composition-id="scene" data-duration="10">`,
+ ` <div id="scene" data-hf-id="hf-scene" data-start="1" data-duration="4"><h1 data-hf-id="hf-title">Hi</h1></div>`,
+ ` <div id="side" data-hf-id="hf-side" data-start="0" data-duration="8"></div>`,
+ `</div>`,
+ `<script>`,
+ `const tl = gsap.timeline({ paused: true });`,
+ `tl.to("#scene", { x: 1, duration: 1 }, 1);`,
+ `tl.from("#scene h1", { y: 20, duration: 1 }, 1.5);`,
+ `tl.to("#side", { x: 5, duration: 1 }, 2);`,
+ `window.__timelines = [tl];`,
+ `</script>`,
+ ].join("\n");
+
+ // A project whose files live in memory, with the GSAP route running the real server writer on them.
+ function stubProjectFiles(initial: Record<string, string>) {
+ const files = { ...initial };
+ const pathAfter = (url: string, marker: string) => decodeURIComponent(url.split(marker)[1]!);
+ const applyServerMutation = (path: string, body: Record<string, unknown>) => {
+ const before = files[path]!;
+ const doc = new DOMParser().parseFromString(before, "text/html");
+ const root = doc.querySelector("template")?.content ?? doc;
+ const old = [...root.querySelectorAll("script")]
+ .map((script) => script.textContent ?? "")
+ .find((text) => text.includes("gsap.timeline"))!;
+ const next =
+ body.type === "shift-positions"
+ ? shiftPositionsInScript(old, String(body.targetSelector), Number(body.delta), root)
+ : scalePositionsInScript(
+ old,
+ String(body.targetSelector),
+ Number(body.oldStart),
+ Number(body.oldDuration),
+ Number(body.newStart),
+ Number(body.newDuration),
+ root,
+ );
+ const after = before.replace(old, next);
+ files[path] = after;
+ return {
+ ok: true,
+ mutated: after !== before,
+ changed: after !== before,
+ scriptText: next,
+ before,
+ after,
+ };
+ };
+ const fetchMock = vi.fn(
+ async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
+ const url = requestUrl(input);
+ if (url.includes("/gsap-mutation-capabilities"))
+ return jsonResponse({ atomicOwnershipPairs: true });
+ if (url.includes("/gsap-mutations/")) {
+ return jsonResponse(
+ applyServerMutation(pathAfter(url, "/gsap-mutations/"), JSON.parse(String(init?.body))),
+ );
+ }
+ if (url.includes("/files/"))
+ return jsonResponse({ content: files[pathAfter(url, "/files/")] });
+ throw new Error(`Unexpected fetch: ${url}`);
+ },
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const writeProjectFile = vi.fn(async (path: string, content: string) => {
+ files[path] = content;
+ });
+ return { files, fetchMock, writeProjectFile };
+ }
+
+ async function setupScene(withSdk: boolean, source = SCENE_SOURCE) {
+ const project = stubProjectFiles({ [SCENE_PATH]: source });
+ const iframe = createPreviewIframe([
+ { id: "scene", track: 0 },
+ { id: "side", track: 1 },
+ ]);
+ const scene = timelineElement({
+ id: "scene",
+ track: 0,
+ zIndex: 0,
+ start: 1,
+ duration: 4,
+ sourceFile: SCENE_PATH,
+ });
+ const side = timelineElement({
+ id: "side",
+ track: 1,
+ zIndex: 0,
+ start: 0,
+ duration: 8,
+ sourceFile: SCENE_PATH,
+ });
+ usePlayerStore.getState().setDuration(10);
+ const hook = renderTimelineEditingHook({
+ timelineElements: [scene, side],
+ iframe,
+ onZIndexCommit: vi.fn().mockResolvedValue(undefined),
+ projectId: "p1",
+ activeCompPath: SCENE_PATH,
+ writeProjectFile: project.writeProjectFile,
+ recordEdit: vi.fn(async () => {}),
+ sdkSession: withSdk ? await openComposition(source) : undefined,
+ publishSdkSession: vi.fn<TimelinePublishSdkSession>(() => "published"),
+ });
+ const tweens = () =>
+ project.files[SCENE_PATH]!.split("\n").filter((line) => line.startsWith("tl."));
+ return { ...project, hook, scene, side, tweens };
+ }
+
+ it("a move then a stretch through the SDK sync once in a template file with a config script first", async () => {
+ const withConfig = `<template id="scene-template">\n${SCENE_SOURCE.replace(
+ "<script>",
+ "<script>gsap.config({ nullTargetWarn: false });</script>\n<script>",
+ )}\n</template>`;
+ const h = await setupScene(true, withConfig);
+ await act(async () => {
+ await h.hook.move(h.scene, { start: 3, track: h.scene.track });
+ await flushAsyncWork();
+ });
+ const moved = { ...h.scene, start: 3 };
+ await act(async () => {
+ await h.hook.resize(moved, { start: 3, duration: 6, playbackStart: undefined });
+ await flushAsyncWork();
+ });
+ expect(h.tweens()).toEqual([
+ `tl.to("#scene", { x: 1, duration: 1.5 }, 3);`,
+ `tl.from("#scene h1", { y: 20, duration: 1.5 }, 3.75);`,
+ `tl.to("#side", { x: 5, duration: 1 }, 2);`,
+ ]);
+ h.hook.unmount();
+ });
+
+ for (const withSdk of [true, false]) {
+ const via = withSdk ? "through the SDK" : "through the server (no SDK session)";
+
+ it(`a move ${via} lands each tween once`, async () => {
+ const h = await setupScene(withSdk);
+ await act(async () => {
+ await h.hook.move(h.scene, { start: 3, track: h.scene.track });
+ await flushAsyncWork();
+ });
+ expect(h.tweens()).toEqual([
+ `tl.to("#scene", { x: 1, duration: 1 }, 3);`,
+ `tl.from("#scene h1", { y: 20, duration: 1 }, 3.5);`,
+ `tl.to("#side", { x: 5, duration: 1 }, 2);`,
+ ]);
+ h.hook.unmount();
+ });
+
+ it(`a resize ${via} scales each tween once`, async () => {
+ const h = await setupScene(withSdk);
+ await act(async () => {
+ await h.hook.resize(h.scene, { start: 1, duration: 8, playbackStart: undefined });
+ await flushAsyncWork();
+ });
+ expect(h.tweens()).toEqual([
+ `tl.to("#scene", { x: 1, duration: 2 }, 1);`,
+ `tl.from("#scene h1", { y: 20, duration: 2 }, 2);`,
+ `tl.to("#side", { x: 5, duration: 1 }, 2);`,
+ ]);
+ h.hook.unmount();
+ });
+
+ it(`a group move ${via} lands each tween once`, async () => {
+ const h = await setupScene(withSdk);
+ await act(async () => {
+ await h.hook.groupMove([
+ { element: h.scene, start: 3 },
+ { element: h.side, start: 1 },
+ ]);
+ await flushAsyncWork();
+ });
+ expect(h.tweens()).toEqual([
+ `tl.to("#scene", { x: 1, duration: 1 }, 3);`,
+ `tl.from("#scene h1", { y: 20, duration: 1 }, 3.5);`,
+ `tl.to("#side", { x: 5, duration: 1 }, 3);`,
+ ]);
+ h.hook.unmount();
+ });
+ }
+});
diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts
index 3f7d11eac7..929e22048b 100644
--- a/packages/studio/src/hooks/useTimelineEditing.ts
+++ b/packages/studio/src/hooks/useTimelineEditing.ts
@@ -19,6 +19,7 @@ import { playbackStartAttributeForElement } from "../player/lib/timelineElementH
import {
captureDurationRollback,
finishClipTimingFallback,
+ sdkTimingGsapSync,
readFileContent,
syncPreviewContentDuration,
} from "./timelineTimingSync";
@@ -229,10 +230,8 @@ export function useTimelineEditing({
);
};
const coalesceKey = `timeline-move:${element.hfId ?? element.id}`;
- const finishMoveGsapSync = () =>
- // Every timing writer converges the same GSAP positions after its
- // durable clip-start commit. The SDK owns the attribute write; this
- // sync owns only the dependent animation rewrite and preview refresh.
+ const finishMoveGsapSync = (sdkGsap?: ReturnType<typeof sdkTimingGsapSync>) =>
+ // One GSAP sync per edit: the SDK commit's own (sdkGsap), else the server rewrite here.
finishClipTimingFallback({
iframe: previewIframeRef.current,
reloadPreview,
@@ -244,15 +243,15 @@ export function useTimelineEditing({
recordEdit,
writeProjectFile,
edit: { kind: "shift", delta: updates.start - element.start },
+ sdkGsap,
}).finally(() => invalidateGsapCache?.());
const moveFallback = () =>
- enqueueEdit(element, "Move timeline clip", buildMovePatches, coalesceKey).then(
- finishMoveGsapSync,
+ enqueueEdit(element, "Move timeline clip", buildMovePatches, coalesceKey).then(() =>
+ finishMoveGsapSync(),
);
return reorderDone
.then(() => {
- // The SDK setTiming path writes start only — a lane change must take
- // the fallback, whose patch builder writes data-track-index too.
+ // SDK setTiming writes start only; a lane change needs the fallback's track patch.
if (sdkSession && element.hfId && !needsExtension && !trackChanged) {
return sdkTimingPersist(
element.hfId,
@@ -272,7 +271,7 @@ export function useTimelineEditing({
{ label: "Move timeline clip", coalesceKey, skipRefresh: true },
).then((result) => {
if (!cutoverCommittedOrThrow(result)) return moveFallback();
- return finishMoveGsapSync();
+ return finishMoveGsapSync(sdkTimingGsapSync(result));
});
}
return moveFallback();
@@ -337,7 +336,7 @@ export function useTimelineEditing({
// script (timing-only resize) — same no-flash path as move; full reload is
// the fallback.
const coalesceKey = `timeline-resize:${element.hfId ?? element.id}`;
- const finishResizeGsapSync = () =>
+ const finishResizeGsapSync = (sdkGsap?: ReturnType<typeof sdkTimingGsapSync>) =>
finishClipTimingFallback({
iframe: previewIframeRef.current,
reloadPreview,
@@ -353,10 +352,11 @@ export function useTimelineEditing({
from: { start: toCompositionTime(element, element.start), duration: element.duration },
to: { start: toCompositionTime(element, updates.start), duration: updates.duration },
},
+ sdkGsap,
}).finally(() => invalidateGsapCache?.());
const resizeFallback = () =>
- enqueueEdit(element, "Resize timeline clip", buildResizePatches, coalesceKey).then(
- finishResizeGsapSync,
+ enqueueEdit(element, "Resize timeline clip", buildResizePatches, coalesceKey).then(() =>
+ finishResizeGsapSync(),
);
const persistDone =
sdkSession && element.hfId && !hasPbsAdjustment && !needsExtension
@@ -378,7 +378,7 @@ export function useTimelineEditing({
{ label: "Resize timeline clip", coalesceKey, skipRefresh: true },
).then((result) => {
if (!cutoverCommittedOrThrow(result)) return resizeFallback();
- return finishResizeGsapSync();
+ return finishResizeGsapSync(sdkTimingGsapSync(result));
})
: resizeFallback();
return persistDone.catch((error) => {
diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts
index 4963cee7b2..03cb03bc6b 100644
--- a/packages/studio/src/hooks/useTimelineGroupEditing.ts
+++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts
@@ -24,11 +24,13 @@ import { playbackStartAttributeForElement } from "../player/lib/timelineElementH
import {
captureDurationRollback,
finishGroupTimingGsapFallback,
+ sdkTimingGsapSync,
readFileContent,
scaleGsapPositions,
shiftGsapPositions,
syncPreviewContentDuration,
} from "./timelineTimingSync";
+import type { GsapMutationStatus } from "./gsapMutationClient";
import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics";
export interface TimelineGroupMoveChange {
@@ -186,8 +188,8 @@ export function useTimelineGroupEditing({
// Shared SDK fast path for group move/resize: eligible when nothing needs the
// server (no root-duration growth, one shared file, every change SDK-addressable
- // and `eligible` per the caller's own gate). Returns whether the SDK handled it;
- // false → caller falls through to the server batch persist.
+ // and `eligible` per the caller's own gate). Returns the SDK's GSAP sync (null: the
+ // server syncs) when it handled the edit; null → caller falls through to the server.
const trySdkBatchPersist = useCallback(
async (input: {
changes: readonly { element: TimelineElement }[];
@@ -200,14 +202,14 @@ export function useTimelineGroupEditing({
label: string;
coalesceKey: string;
coalesceMs?: number;
- }): Promise<boolean> => {
+ }): Promise<{ sdkGsap: GsapMutationStatus | null } | null> => {
const sharedPath = allChangesSharePath(input.changes, activeCompPath);
const canUseSdk =
!input.needsExtension &&
sharedPath !== null &&
input.eligible &&
input.sdkChanges.every((change) => change !== null);
- if (!canUseSdk) return false;
+ if (!canUseSdk) return null;
const result = await sdkTimingBatchPersist(
input.sdkChanges.filter((change): change is NonNullable<typeof change> => change !== null),
sharedPath,
@@ -227,7 +229,7 @@ export function useTimelineGroupEditing({
skipRefresh: true,
},
);
- return cutoverCommittedOrThrow(result);
+ return cutoverCommittedOrThrow(result) ? { sdkGsap: sdkTimingGsapSync(result) } : null;
},
[
activeCompPath,
@@ -289,7 +291,7 @@ export function useTimelineGroupEditing({
const label = options?.label ?? "Move timeline clips";
return enqueueGroupOperation(label, async (projectId) => {
await options?.beforeTiming;
- const handledBySdk = await trySdkBatchPersist({
+ const sdk = await trySdkBatchPersist({
changes,
sdkChanges: toSdkTimingChanges(changes, (change) => ({
start: toAuthoredStart(change.element, change.start),
@@ -300,7 +302,7 @@ export function useTimelineGroupEditing({
coalesceKey,
coalesceMs,
});
- if (!handledBySdk) {
+ if (!sdk) {
await persistServerBatch(
projectId,
label,
@@ -339,6 +341,7 @@ export function useTimelineGroupEditing({
writeProjectFile,
activeCompPath,
changes,
+ sdkGsap: sdk?.sdkGsap,
resolveChangePath: (element) => targetPathFor(element, activeCompPath),
mutateChange: (change, changePath) => {
const delta = change.start - change.element.start;
@@ -408,7 +411,7 @@ export function useTimelineGroupEditing({
const coalesceMs = options?.coalesceMs;
return enqueueGroupOperation("Resize timeline clips", async (projectId) => {
await options?.beforeTiming;
- const handledBySdk = await trySdkBatchPersist({
+ const sdk = await trySdkBatchPersist({
changes,
sdkChanges: toSdkTimingChanges(changes, (change) => ({
start: toAuthoredStart(change.element, change.start),
@@ -420,7 +423,7 @@ export function useTimelineGroupEditing({
coalesceKey,
coalesceMs,
});
- if (!handledBySdk) {
+ if (!sdk) {
await persistServerBatch(
projectId,
"Resize timeline clips",
@@ -451,6 +454,7 @@ export function useTimelineGroupEditing({
writeProjectFile,
activeCompPath,
changes,
+ sdkGsap: sdk?.sdkGsap,
resolveChangePath: (element) => targetPathFor(element, activeCompPath),
mutateChange: (change, changePath) => {
const domId = change.element.domId;
diff --git a/packages/studio/src/utils/sdkEditTransaction.ts b/packages/studio/src/utils/sdkEditTransaction.ts
index 10dad8f9de..7479ac4c61 100644
--- a/packages/studio/src/utils/sdkEditTransaction.ts
+++ b/packages/studio/src/utils/sdkEditTransaction.ts
@@ -11,7 +11,7 @@ import {
export type CutoverResult =
| { status: "declined"; reason: string }
- | { status: "committed"; version: string }
+ | { status: "committed"; version: string; before: string; after: string }
| { status: "failed"; error: Error };
export interface SdkSessionPublication {
@@ -143,7 +143,9 @@ export function failedCutover(
}
/** Only an explicit decline may enter the legacy mutation backend. */
-export function cutoverCommittedOrThrow(result: CutoverResult): boolean {
+export function cutoverCommittedOrThrow(
+ result: CutoverResult,
+): result is Extract<CutoverResult, { status: "committed" }> {
if (result.status === "failed") throw result.error;
return result.status === "committed";
}
@@ -300,7 +302,12 @@ async function commitCandidateEdit(
});
}
if (refreshTarget) refreshCommittedEdit(edit.after, deps, options);
- return { status: "committed", version: hashContent(edit.after) };
+ return {
+ status: "committed",
+ version: hashContent(edit.after),
+ before: originalContent,
+ after: edit.after,
+ };
}
export async function persistSdkCandidateMutation(