Skip to content

Commit f1c1f1d

Browse files
fix(parsers): moving a clip on the timeline moves its inner animations too (#4761)
* fix(parsers): moving a clip on the timeline moves its inner animations too * fix(parsers): a timeline move keeps chained and partly known tweens where they belong * fix(parsers): moving a clip leaves chained outside tweens and template aliases in place * fix(studio): a clip timing edit syncs its animations once, not twice * fix(studio): a timing edit falls back to the server when the SDK wrote no animation change * fix(studio): the SDK sync check reads scripts inside a template too * fix(studio): the SDK sync check finds template scripts through the DOM walker * fix(core): a clip retime writes only its own timed tweens, never outside ones * style(core): format the clip tween import
1 parent 567525a commit f1c1f1d

18 files changed

Lines changed: 662 additions & 228 deletions

‎packages/parsers/src/clipTweens.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import type { GsapAnimation } from "./gsapSerialize.js";
2+
3+
type TweenTarget = Pick<GsapAnimation, "targetSelector" | "hasPartialSelector">;
4+
type TweenTime = Pick<GsapAnimation, "position" | "implicitPosition">;
5+
6+
// Tweens a timeline move or retime of a clip carries: an own selector, plus (given a DOM) a fully known target
7+
// set that is the clip or sits inside it with no nearer `data-start` clip. A tween also aiming outside stays put.
8+
export function clipTweenMatcher(
9+
clipSelectors: string | readonly string[],
10+
root?: ParentNode,
11+
): (tween: TweenTarget) => boolean {
12+
const own = typeof clipSelectors === "string" ? [clipSelectors] : clipSelectors;
13+
const clips = root ? own.flatMap((selector) => queryAll(root, selector)) : [];
14+
return ({ targetSelector, hasPartialSelector }) => {
15+
if (hasPartialSelector) return false;
16+
if (own.includes(targetSelector)) return true;
17+
if (!root || clips.length === 0) return false;
18+
const targets = queryAll(root, targetSelector);
19+
return (
20+
targets.length > 0 &&
21+
targets.every((target) => {
22+
const owner = target.closest("[data-start]");
23+
return clips.includes(target) || (owner !== null && clips.includes(owner));
24+
})
25+
);
26+
};
27+
}
28+
29+
/** Where a GSAP script's clips live: linkedom keeps a `<template>`'s children under it, out of document queries. */
30+
export function clipQueryRoot(script: Element): ParentNode {
31+
return script.closest("template") ?? script.ownerDocument;
32+
}
33+
34+
/** A written position; an implicit one follows the tween before it and must stay unwritten. */
35+
export function hasExplicitTime<T extends TweenTime>(
36+
animation: T,
37+
): animation is T & { position: number } {
38+
return typeof animation.position === "number" && !animation.implicitPosition;
39+
}
40+
41+
function queryAll(root: ParentNode, selector: string): Element[] {
42+
try {
43+
return Array.from(root.querySelectorAll(selector));
44+
} catch {
45+
// Pseudo-selectors such as a proxy or dwell label never match the DOM.
46+
return [];
47+
}
48+
}

‎packages/parsers/src/gsapParser.ts‎

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ export {
5151
} from "./gsapConstants";
5252
import { classifyPropertyGroup, classifyTweenPropertyGroup } from "./gsapConstants";
5353
import type { PropertyGroupName } from "./gsapConstants";
54+
import { clipTweenMatcher, hasExplicitTime } from "./clipTweens";
5455
import {
5556
findObjectArrayKeyframeIndex,
5657
getCompatibleObjectArrayKeyframeTiming,
@@ -402,6 +403,23 @@ function lookupBinding(name: string, path: AstPath, bindings: TargetBindings): s
402403
return null;
403404
}
404405

406+
function hasUnresolvedArrayPart(
407+
node: AstNode,
408+
path: AstPath,
409+
scope: ScopeBindings,
410+
bindings: TargetBindings,
411+
helpers: TargetHelpers,
412+
): boolean {
413+
return (
414+
node?.type === "ArrayExpression" &&
415+
node.elements.some(
416+
(el: AstNode) =>
417+
!resolveTargetSelector(el, path, scope, bindings, helpers) ||
418+
hasUnresolvedArrayPart(el, path, scope, bindings, helpers),
419+
)
420+
);
421+
}
422+
405423
/**
406424
* Resolve a tween's first argument to a CSS selector. Handles inline string
407425
* literals, element variables (lexically scoped), arrays of elements (joined
@@ -585,6 +603,7 @@ interface TweenCallInfo {
585603
node: AstNode;
586604
method: GsapMethod;
587605
selector: string;
606+
selectorPartial?: boolean;
588607
varsArg: AstNode;
589608
fromArg?: AstNode;
590609
positionArg?: AstNode;
@@ -649,13 +668,17 @@ function findAllTweenCalls(
649668
const selectorValue =
650669
resolveTargetSelector(args[0], path, scope, targetBindings, targetHelpers) ??
651670
"__unresolved__";
671+
const partial = hasUnresolvedArrayPart(args[0], path, scope, targetBindings, targetHelpers)
672+
? { selectorPartial: true }
673+
: {};
652674

653675
if (method === "fromTo") {
654676
results.push({
655677
path,
656678
node,
657679
method: "fromTo",
658680
selector: selectorValue,
681+
...partial,
659682
fromArg: args[1],
660683
varsArg: args[2],
661684
positionArg: args[3],
@@ -666,6 +689,7 @@ function findAllTweenCalls(
666689
node,
667690
method: method as GsapMethod,
668691
selector: selectorValue,
692+
...partial,
669693
varsArg: args[1],
670694
positionArg: args[2],
671695
...(isGlobalSet ? { global: true } : {}),
@@ -1134,6 +1158,7 @@ function tweenCallToAnimation(
11341158
if (motionPathResult) anim.arcPath = motionPathResult.arcPath;
11351159
if (hasUnresolvedKeyframes) anim.hasUnresolvedKeyframes = true;
11361160
if (call.selector === "__unresolved__") anim.hasUnresolvedSelector = true;
1161+
if (call.selectorPartial) anim.hasPartialSelector = true;
11371162
return anim;
11381163
}
11391164

@@ -1543,7 +1568,9 @@ export function shiftPositionsInScript(
15431568
script: string,
15441569
targetSelector: string,
15451570
delta: number,
1571+
root?: ParentNode,
15461572
): string {
1573+
const carries = clipTweenMatcher(targetSelector, root);
15471574
let parsed: ParsedGsapAst;
15481575
try {
15491576
parsed = parseGsapAst(script);
@@ -1553,8 +1580,7 @@ export function shiftPositionsInScript(
15531580
}
15541581
let changed = false;
15551582
for (const entry of parsed.located) {
1556-
if (entry.animation.targetSelector !== targetSelector) continue;
1557-
if (typeof entry.animation.position !== "number") continue;
1583+
if (!carries(entry.animation) || !hasExplicitTime(entry.animation)) continue;
15581584
const newPos = Math.max(0, Math.round((entry.animation.position + delta) * 1000) / 1000);
15591585
applyUpdatesToCall(entry.call, { position: newPos });
15601586
changed = true;
@@ -1569,9 +1595,11 @@ export function scalePositionsInScript(
15691595
oldDuration: number,
15701596
newStart: number,
15711597
newDuration: number,
1598+
root?: ParentNode,
15721599
): string {
15731600
if (oldDuration <= 0 || newDuration <= 0) return script;
15741601
const ratio = newDuration / oldDuration;
1602+
const carries = clipTweenMatcher(targetSelector, root);
15751603
let parsed: ParsedGsapAst;
15761604
try {
15771605
parsed = parseGsapAst(script);
@@ -1581,13 +1609,14 @@ export function scalePositionsInScript(
15811609
}
15821610
let changed = false;
15831611
for (const entry of parsed.located) {
1584-
if (entry.animation.targetSelector !== targetSelector) continue;
1585-
if (typeof entry.animation.position !== "number") continue;
1586-
const newPos = Math.max(
1587-
0,
1588-
Math.round((newStart + (entry.animation.position - oldStart) * ratio) * 1000) / 1000,
1589-
);
1590-
const updates: Partial<GsapAnimation> = { position: newPos };
1612+
if (!carries(entry.animation) || typeof entry.animation.position !== "number") continue;
1613+
const updates: Partial<GsapAnimation> = {};
1614+
if (hasExplicitTime(entry.animation)) {
1615+
updates.position = Math.max(
1616+
0,
1617+
Math.round((newStart + (entry.animation.position - oldStart) * ratio) * 1000) / 1000,
1618+
);
1619+
}
15911620
if (typeof entry.animation.duration === "number" && entry.animation.duration > 0) {
15921621
updates.duration = Math.max(
15931622
0.001,

‎packages/parsers/src/gsapParserAcorn.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,22 @@ function resolveTargetSelector(
583583
return null;
584584
}
585585

586+
function hasUnresolvedArrayPart(
587+
node: any,
588+
ancestors: any[],
589+
scope: ScopeBindings,
590+
bindings: TargetBindings,
591+
): boolean {
592+
return (
593+
node?.type === "ArrayExpression" &&
594+
node.elements.some(
595+
(el: any) =>
596+
!resolveTargetSelector(el, ancestors, scope, bindings) ||
597+
hasUnresolvedArrayPart(el, ancestors, scope, bindings),
598+
)
599+
);
600+
}
601+
586602
/**
587603
* Classify an otherwise-unresolved tween target that is a plain object literal
588604
* (`tl.to({}, …)`) or a proxy object (`tl.to(s, {onUpdate})`). Returns a
@@ -864,6 +880,7 @@ export interface TweenCallInfo {
864880
ancestors: any[];
865881
method: GsapMethod;
866882
selector: string;
883+
selectorPartial?: boolean;
867884
varsArg: any;
868885
fromArg?: any;
869886
positionArg?: any;
@@ -929,13 +946,17 @@ function findAllTweenCalls(
929946
? (resolveTargetSelector(args[0], nodeAncestors, scope, targetBindings) ??
930947
"__unresolved__")
931948
: "__unresolved__";
949+
const partial = hasUnresolvedArrayPart(args[0], nodeAncestors, scope, targetBindings)
950+
? { selectorPartial: true }
951+
: {};
932952

933953
if (method === "fromTo" && args.length >= 3) {
934954
results.push({
935955
node,
936956
ancestors: nodeAncestors,
937957
method: "fromTo",
938958
selector: selectorValue,
959+
...partial,
939960
fromArg: args[1],
940961
varsArg: args[2],
941962
positionArg: args[3],
@@ -946,6 +967,7 @@ function findAllTweenCalls(
946967
ancestors: nodeAncestors,
947968
method: method as GsapMethod,
948969
selector: selectorValue,
970+
...partial,
949971
varsArg: args[1],
950972
positionArg: args[2],
951973
...(isGlobalSet ? { global: true } : {}),
@@ -1403,6 +1425,7 @@ function tweenCallToAnimation(
14031425
if (hasUnresolvedKeyframes) anim.hasUnresolvedKeyframes = true;
14041426
if (durationUnresolved) anim.durationUnresolved = true;
14051427
if (selector === "__unresolved__") anim.hasUnresolvedSelector = true;
1428+
if (call.selectorPartial) anim.hasPartialSelector = true;
14061429
if (provenance) anim.provenance = provenance;
14071430
return anim;
14081431
}
@@ -1903,6 +1926,18 @@ const parseMemo = new Map<string, ParsedGsap>();
19031926
* Browser-safe equivalent of `parseGsapScript` (gsapParser.ts).
19041927
* Uses acorn + acorn-walk instead of recast + @babel/parser.
19051928
*/
1929+
/** The script that holds a file's timeline: the first to declare one, else the first with tween calls. */
1930+
export function findTimelineScript<T extends { textContent: string | null }>(
1931+
scripts: readonly T[],
1932+
): T | null {
1933+
const text = (script: T) => script.textContent ?? "";
1934+
return (
1935+
scripts.find((script) => text(script).includes("gsap.timeline")) ??
1936+
scripts.find((script) => /\.(set|to)\(/.test(text(script))) ??
1937+
null
1938+
);
1939+
}
1940+
19061941
export function parseGsapScriptAcorn(script: string): ParsedGsap {
19071942
const parsed = parseMemo.get(script) ?? parseGsapScriptAcornUncached(script);
19081943
parseMemo.delete(script);

‎packages/parsers/src/gsapSerialize.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ export interface GsapAnimation {
7070
hasUnresolvedKeyframes?: boolean;
7171
/** True when the tween's target selector couldn't be statically resolved (dynamic). */
7272
hasUnresolvedSelector?: boolean;
73+
hasPartialSelector?: boolean;
7374
/** Absolute start time computed by walking the timeline chain (handles +=, -=, <, >, labels). */
7475
resolvedStart?: number;
7576
/** True when no position arg was authored — the tween is sequentially placed by GSAP. */

‎packages/parsers/src/gsapWriter.parity.test.ts‎

Lines changed: 92 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77
* This is the safety net for porting WS-3 ops one at a time: each ported op
88
* gets a fixture row here proving it matches the battle-tested original.
99
*
10-
* The server switches between writers via STUDIO_SDK_CUTOVER_ENABLED (WS-3.F).
11-
* Recast remains the default; acorn runs only when the flag is enabled.
10+
* The server picks the writer from HYPERFRAMES_GSAP_WRITER; acorn is the default.
1211
*/
1312
import { describe, expect, it } from "vitest";
13+
import { parseHTML } from "linkedom";
1414
import {
1515
parseGsapScript,
1616
removeAllKeyframesFromScript as removeAllRecast,
@@ -1973,3 +1973,93 @@ tl.to("#el", { y: 50, duration: 1 }, "+=0.5");`;
19731973
expect(scaleAcorn(POSITIONS_MULTI, "#hero", 0, 1, 2, 0)).toBe(POSITIONS_MULTI);
19741974
});
19751975
});
1976+
1977+
describe("shift/scalePositionsInScript carry the clip's inner tweens", () => {
1978+
const { document } = parseHTML(`<html><body>
1979+
<div id="scene" data-start="1" data-duration="4">
1980+
<h1 class="title">Hi</h1>
1981+
<p id="child" class="inner">Kid</p>
1982+
<div id="nested" data-start="2" data-duration="1"><span id="deep">x</span></div>
1983+
</div>
1984+
<div id="sibling" class="title">Out</div>
1985+
</body></html>`);
1986+
const script = `const tl = gsap.timeline({ paused: true });
1987+
tl.from("#scene", { opacity: 0, duration: 1 }, 1);
1988+
tl.from("#scene h1", { y: 20, duration: 1 }, 1.5);
1989+
tl.to("#child", { rotation: 90, duration: 1 });
1990+
tl.to("#sibling", { y: 5, duration: 0.5 });
1991+
tl.to("#child", { x: 10, duration: 1 }, 2);
1992+
tl.to(["#child", "#scene h1"], { opacity: 0.5, duration: 1 }, 3);
1993+
tl.to(".inner", { scale: 2, duration: 1 }, 3.5);
1994+
tl.to("#sibling", { x: 5, duration: 1 }, 2);
1995+
tl.to(".title", { color: "red", duration: 1 }, 2.5);
1996+
tl.to("#deep", { y: 5, duration: 0.5 }, 2);
1997+
tl.to(["#scene h1", window.logo], { x: 1, duration: 1 }, 2);
1998+
tl.to(["#scene", window.logo], { x: 2, duration: 1 }, 2);`;
1999+
const timings = (out: string) =>
2000+
parseGsapScriptAcorn(out).animations.map((a) => [
2001+
a.targetSelector,
2002+
a.implicitPosition ? "chained" : a.position,
2003+
a.duration,
2004+
]);
2005+
const writers = [
2006+
["acorn", shiftAcorn, scaleAcorn],
2007+
["recast", shiftRecast, scaleRecast],
2008+
] as const;
2009+
2010+
const bare = parseHTML(
2011+
`<html><body><div id="bare" class="card"><p>x</p></div></body></html>`,
2012+
).document;
2013+
const bareScript = `const tl = gsap.timeline({ paused: true });
2014+
tl.to(".card", { x: 1, duration: 1 }, 1);`;
2015+
2016+
for (const [name, shift, scale] of writers) {
2017+
it(`${name}: a tween whose target is the clip moves with it, even without data-start`, () => {
2018+
expect(timings(shift(bareScript, "#bare", 1, bare))).toEqual([[".card", 2, 1]]);
2019+
});
2020+
2021+
it(`${name}: known limit, an outside tween chained after moved content moves with it`, () => {
2022+
const sibling = (out: string) => parseGsapScriptAcorn(out).animations[3]!;
2023+
expect(sibling(script)).toMatchObject({ targetSelector: "#sibling", resolvedStart: 3.5 });
2024+
expect(sibling(shift(script, "#scene", 2, document))).toMatchObject({
2025+
targetSelector: "#sibling",
2026+
implicitPosition: true,
2027+
resolvedStart: 5.5,
2028+
});
2029+
});
2030+
2031+
it(`${name}: a shift moves the clip and its descendants, never outside or nested clips`, () => {
2032+
expect(timings(shift(script, "#scene", 2, document))).toEqual([
2033+
["#scene", 3, 1],
2034+
["#scene h1", 3.5, 1],
2035+
["#child", "chained", 1],
2036+
["#sibling", "chained", 0.5],
2037+
["#child", 4, 1],
2038+
["#child, #scene h1", 5, 1],
2039+
[".inner", 5.5, 1],
2040+
["#sibling", 2, 1],
2041+
[".title", 2.5, 1],
2042+
["#deep", 2, 0.5],
2043+
["#scene h1", 2, 1],
2044+
["#scene", 2, 1],
2045+
]);
2046+
});
2047+
2048+
it(`${name}: a scale retimes the clip and its descendants, never outside or nested clips`, () => {
2049+
expect(timings(scale(script, "#scene", 1, 4, 1, 8, document))).toEqual([
2050+
["#scene", 1, 2],
2051+
["#scene h1", 2, 2],
2052+
["#child", "chained", 2],
2053+
["#sibling", "chained", 0.5],
2054+
["#child", 3, 2],
2055+
["#child, #scene h1", 5, 2],
2056+
[".inner", 6, 2],
2057+
["#sibling", 2, 1],
2058+
[".title", 2.5, 1],
2059+
["#deep", 2, 0.5],
2060+
["#scene h1", 2, 1],
2061+
["#scene", 2, 1],
2062+
]);
2063+
});
2064+
}
2065+
});

0 commit comments

Comments
 (0)