Skip to content

Commit a29a0c6

Browse files
feat(sdk,core): ws-3 — splitAnimationsInScript acorn port + SDK op
- acorn: updateAnimationSelectorInScript, insertInheritedStateSetInScript helpers - acorn: splitAnimationsInScript exported (parity with recast version) - parity: 4 new fixtures (3 cases + no-op) — 23 total parity tests - SDK types: splitAnimations EditOp variant - mutate.ts: handleSplitAnimations + can() gate - mutate.gsap.test.ts: 3 new tests (56 total passing) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Co-authored-by: Miguel Ángel <[email protected]>
1 parent dc60436 commit a29a0c6

5 files changed

Lines changed: 344 additions & 0 deletions

File tree

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

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,16 @@ import {
1414
convertToKeyframesInScript as convertRecast,
1515
materializeKeyframesInScript as materializeRecast,
1616
splitIntoPropertyGroups as splitGroupsRecast,
17+
splitAnimationsInScript as splitAnimsRecast,
18+
type SplitAnimationsOptions,
1719
} from "./gsapParser.js";
1820
import { parseGsapScriptAcornForWrite, type ParsedGsapAcornForWrite } from "./gsapParserAcorn.js";
1921
import {
2022
removeAllKeyframesFromScript as removeAllAcorn,
2123
convertToKeyframesFromScript as convertAcorn,
2224
materializeKeyframesFromScript as materializeAcorn,
2325
splitIntoPropertyGroupsFromScript as splitGroupsAcorn,
26+
splitAnimationsInScript as splitAnimsAcorn,
2427
} from "./gsapWriterAcorn.js";
2528

2629
function acornId(script: string): string {
@@ -301,3 +304,89 @@ describe("parity: splitIntoPropertyGroupsFromScript (recast vs acorn)", () => {
301304
expect(out).toBe(script);
302305
});
303306
});
307+
308+
// ── splitAnimationsInScript parity ────────────────────────────────────────────
309+
310+
function animShapesOf(script: string) {
311+
return parseGsapScript(script).animations.map((a) => ({
312+
method: a.method,
313+
selector: a.targetSelector,
314+
properties: a.properties,
315+
fromProperties: a.fromProperties,
316+
duration: a.duration,
317+
position: a.position,
318+
}));
319+
}
320+
321+
const SPLIT_ANIM_CASES: Array<{ name: string; script: string; opts: SplitAnimationsOptions }> = [
322+
{
323+
name: "all tweens before split — retargets none",
324+
script: `
325+
const tl = gsap.timeline({ paused: true });
326+
tl.to("#hero", { x: 100, duration: 1 }, 0);
327+
`,
328+
opts: {
329+
originalId: "hero",
330+
newId: "hero-2",
331+
splitTime: 2,
332+
elementStart: 0,
333+
elementDuration: 4,
334+
},
335+
},
336+
{
337+
name: "tween entirely after split — retargeted to newId",
338+
script: `
339+
const tl = gsap.timeline({ paused: true });
340+
tl.to("#hero", { opacity: 0, duration: 0.5 }, 3);
341+
`,
342+
opts: {
343+
originalId: "hero",
344+
newId: "hero-2",
345+
splitTime: 2,
346+
elementStart: 0,
347+
elementDuration: 4,
348+
},
349+
},
350+
{
351+
name: "tween spanning split — truncated first half + fromTo second half",
352+
script: `
353+
const tl = gsap.timeline({ paused: true });
354+
tl.to("#hero", { x: 200, duration: 4 }, 0);
355+
`,
356+
opts: {
357+
originalId: "hero",
358+
newId: "hero-2",
359+
splitTime: 2,
360+
elementStart: 0,
361+
elementDuration: 4,
362+
},
363+
},
364+
];
365+
366+
describe("parity: splitAnimationsInScript (recast vs acorn)", () => {
367+
for (const { name, script, opts } of SPLIT_ANIM_CASES) {
368+
it(name, () => {
369+
const { script: recastOut } = splitAnimsRecast(script, opts);
370+
const { script: acornOut } = splitAnimsAcorn(script, opts);
371+
const sortByPos = (arr: ReturnType<typeof animShapesOf>) =>
372+
arr.slice().sort((a, b) => {
373+
const pa = typeof a.position === "number" ? a.position : 0;
374+
const pb = typeof b.position === "number" ? b.position : 0;
375+
return pa - pb || (a.selector ?? "").localeCompare(b.selector ?? "");
376+
});
377+
expect(sortByPos(animShapesOf(acornOut))).toEqual(sortByPos(animShapesOf(recastOut)));
378+
});
379+
}
380+
381+
it("no-op when originalId not found in script", () => {
382+
const script = SPLIT_ANIM_CASES[0]!.script;
383+
const opts: SplitAnimationsOptions = {
384+
originalId: "nonexistent",
385+
newId: "x",
386+
splitTime: 2,
387+
elementStart: 0,
388+
elementDuration: 4,
389+
};
390+
expect(splitAnimsAcorn(script, opts).script).toBe(script);
391+
});
392+
});

‎packages/core/src/parsers/gsapWriterAcorn.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
} from "./gsapParserAcorn.js";
1717
import { classifyPropertyGroup } from "./gsapConstants.js";
1818
import type { PropertyGroupName } from "./gsapConstants.js";
19+
import type { SplitAnimationsOptions, SplitAnimationsResult } from "./gsapParser.js";
1920
import * as acornWalk from "acorn-walk";
2021

2122
// ── Code generation helpers ──────────────────────────────────────────────────
@@ -1302,3 +1303,169 @@ export function removeLabelFromScript(script: string, name: string): string {
13021303
}
13031304
return ms.toString();
13041305
}
1306+
1307+
// ── splitAnimationsInScript helpers ──────────────────────────────────────────
1308+
1309+
/** Overwrite the selector (first arg) of a tween call. */
1310+
function updateAnimationSelectorInScript(
1311+
script: string,
1312+
animationId: string,
1313+
newSelector: string,
1314+
): string {
1315+
const parsed = parseGsapScriptAcornForWrite(script);
1316+
if (!parsed) return script;
1317+
const target = parsed.located.find((l) => l.id === animationId);
1318+
if (!target) return script;
1319+
const selectorArg = target.call.node.arguments?.[0];
1320+
if (!selectorArg) return script;
1321+
const ms = new MagicString(script);
1322+
ms.overwrite(selectorArg.start, selectorArg.end, JSON.stringify(newSelector));
1323+
return ms.toString();
1324+
}
1325+
1326+
/**
1327+
* Insert a `tl.set()` call immediately after the timeline declaration
1328+
* (before existing tweens) to establish inherited state on a new element.
1329+
*/
1330+
function insertInheritedStateSetInScript(
1331+
script: string,
1332+
selector: string,
1333+
position: number,
1334+
properties: Record<string, number | string>,
1335+
): string {
1336+
const parsed = parseGsapScriptAcornForWrite(script);
1337+
if (!parsed) return script;
1338+
const props = Object.entries(properties)
1339+
.map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`)
1340+
.join(", ");
1341+
const code = `${parsed.timelineVar}.set(${JSON.stringify(selector)}, { ${props} }, ${position});`;
1342+
const ms = new MagicString(script);
1343+
const tlDecl = findTimelineDeclarationStatement(parsed.ast, parsed.timelineVar);
1344+
if (tlDecl) {
1345+
ms.appendLeft(tlDecl.end, "\n" + code);
1346+
} else if (parsed.located.length > 0) {
1347+
const firstCall = parsed.located[0]!.call;
1348+
const exprStmt = findEnclosingExpressionStatement(firstCall.ancestors);
1349+
const insertAt = exprStmt?.start ?? firstCall.node.start;
1350+
ms.prependLeft(insertAt, code + "\n");
1351+
} else {
1352+
ms.append("\n" + code);
1353+
}
1354+
return ms.toString();
1355+
}
1356+
1357+
// fallow-ignore-next-line complexity
1358+
export function splitAnimationsInScript(
1359+
script: string,
1360+
opts: SplitAnimationsOptions,
1361+
): SplitAnimationsResult {
1362+
const parsed = parseGsapScriptAcornForWrite(script);
1363+
if (!parsed) return { script, skippedSelectors: [] };
1364+
1365+
const originalSelector = `#${opts.originalId}`;
1366+
const newSelector = `#${opts.newId}`;
1367+
1368+
const animations = parsed.located.map((l) => l.animation);
1369+
const skippedSelectors: string[] = [];
1370+
1371+
for (const a of animations) {
1372+
if (a.targetSelector !== originalSelector && a.targetSelector.includes(opts.originalId)) {
1373+
skippedSelectors.push(a.targetSelector);
1374+
}
1375+
}
1376+
1377+
const matching = animations.filter((a) => a.targetSelector === originalSelector);
1378+
if (matching.length === 0) return { script, skippedSelectors };
1379+
1380+
let result = script;
1381+
const newElementStart = opts.splitTime;
1382+
const inheritedProps: Record<string, number | string> = {};
1383+
1384+
// Reverse iteration: updateAnimationSelectorInScript mutates selectors which
1385+
// can shift count-based ID suffixes for later animations.
1386+
for (let i = matching.length - 1; i >= 0; i--) {
1387+
const anim = matching[i]!;
1388+
const pos = typeof anim.position === "number" ? anim.position : 0;
1389+
const dur = anim.duration ?? 0;
1390+
const animEnd = pos + dur;
1391+
1392+
if (anim.keyframes) {
1393+
if (pos >= opts.splitTime) {
1394+
result = updateAnimationSelectorInScript(result, anim.id, newSelector);
1395+
} else if (animEnd > opts.splitTime) {
1396+
skippedSelectors.push(`${originalSelector} (keyframes spanning split)`);
1397+
const kfs = anim.keyframes.keyframes;
1398+
for (const kf of kfs) {
1399+
const kfTime = pos + (kf.percentage / 100) * dur;
1400+
if (kfTime <= opts.splitTime) {
1401+
for (const [k, v] of Object.entries(kf.properties)) {
1402+
inheritedProps[k] = v;
1403+
}
1404+
}
1405+
}
1406+
} else {
1407+
const kfs = anim.keyframes.keyframes;
1408+
if (kfs.length > 0) {
1409+
for (const [k, v] of Object.entries(kfs[kfs.length - 1]!.properties)) {
1410+
inheritedProps[k] = v;
1411+
}
1412+
}
1413+
}
1414+
continue;
1415+
}
1416+
1417+
if (animEnd <= opts.splitTime) {
1418+
for (const [k, v] of Object.entries(anim.properties)) {
1419+
inheritedProps[k] = v;
1420+
}
1421+
continue;
1422+
}
1423+
1424+
if (pos >= opts.splitTime) {
1425+
result = updateAnimationSelectorInScript(result, anim.id, newSelector);
1426+
continue;
1427+
}
1428+
1429+
// Spans the split — linear interpolation to compute mid-values.
1430+
const progress = dur > 0 ? (opts.splitTime - pos) / dur : 0;
1431+
const fromSource = anim.fromProperties ?? inheritedProps;
1432+
const midProps: Record<string, number | string> = {};
1433+
for (const [k, v] of Object.entries(anim.properties)) {
1434+
if (typeof v !== "number") {
1435+
midProps[k] = v;
1436+
continue;
1437+
}
1438+
const fromVal = typeof fromSource[k] === "number" ? (fromSource[k] as number) : 0;
1439+
midProps[k] = fromVal + (v - fromVal) * progress;
1440+
}
1441+
1442+
const firstHalfDuration = opts.splitTime - pos;
1443+
result = updateAnimationInScript(result, anim.id, {
1444+
duration: firstHalfDuration,
1445+
properties: midProps,
1446+
});
1447+
1448+
const secondHalfDuration = animEnd - opts.splitTime;
1449+
const addResult = addAnimationToScript(result, {
1450+
targetSelector: newSelector,
1451+
method: "fromTo",
1452+
position: newElementStart,
1453+
duration: secondHalfDuration,
1454+
properties: { ...anim.properties },
1455+
fromProperties: { ...midProps },
1456+
ease: anim.ease,
1457+
extras: anim.extras,
1458+
});
1459+
result = addResult.script;
1460+
1461+
for (const [k, v] of Object.entries(midProps)) {
1462+
inheritedProps[k] = v;
1463+
}
1464+
}
1465+
1466+
if (Object.keys(inheritedProps).length > 0) {
1467+
result = insertInheritedStateSetInScript(result, newSelector, newElementStart, inheritedProps);
1468+
}
1469+
1470+
return { script: result, skippedSelectors };
1471+
}

‎packages/sdk/src/engine/mutate.gsap.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,64 @@ window.__timelines["t"] = tl;`;
666666
});
667667
});
668668

669+
// ─── splitAnimations ──────────────────────────────────────────────────────────
670+
671+
describe("splitAnimations", () => {
672+
const SPLIT_SCRIPT = `var tl = gsap.timeline({ paused: true });
673+
tl.to("#hero", { x: 200, duration: 4 }, 0);
674+
window.__timelines["t"] = tl;`;
675+
676+
function freshSplit() {
677+
return parseMutable(`<div data-hf-id="hf-stage" data-hf-root style="width:1280px;height:720px">
678+
<div data-hf-id="hf-hero"></div>
679+
<script>${SPLIT_SCRIPT}</script>
680+
</div>`);
681+
}
682+
683+
it("retargets post-split tween to newId", () => {
684+
const parsed = freshSplit();
685+
const result = applyOp(parsed, {
686+
type: "splitAnimations",
687+
originalId: "hero",
688+
newId: "hero-2",
689+
splitTime: 3,
690+
elementStart: 0,
691+
elementDuration: 4,
692+
});
693+
expect(result.forward).toHaveLength(1);
694+
const newScript = String(result.forward[0]?.value ?? "");
695+
expect(newScript).toContain("#hero-2");
696+
});
697+
698+
it("spanning tween produces fromTo on new element", () => {
699+
const parsed = freshSplit();
700+
const result = applyOp(parsed, {
701+
type: "splitAnimations",
702+
originalId: "hero",
703+
newId: "hero-2",
704+
splitTime: 2,
705+
elementStart: 0,
706+
elementDuration: 4,
707+
});
708+
const newScript = String(result.forward[0]?.value ?? "");
709+
expect(newScript).toContain(".fromTo(");
710+
expect(newScript).toContain("#hero-2");
711+
});
712+
713+
it("no-op when originalId not found", () => {
714+
const parsed = freshSplit();
715+
const result = applyOp(parsed, {
716+
type: "splitAnimations",
717+
originalId: "nonexistent",
718+
newId: "x",
719+
splitTime: 2,
720+
elementStart: 0,
721+
elementDuration: 4,
722+
});
723+
expect(result.forward).toHaveLength(0);
724+
});
725+
});
726+
669727
// ─── Label ops ────────────────────────────────────────────────────────────────
670728

671729
describe("addLabel", () => {

‎packages/sdk/src/engine/mutate.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import {
5454
convertToKeyframesFromScript,
5555
materializeKeyframesFromScript,
5656
splitIntoPropertyGroupsFromScript,
57+
splitAnimationsInScript,
5758
updateKeyframeInScript,
5859
addLabelToScript,
5960
removeLabelFromScript,
@@ -179,6 +180,8 @@ function applyGsapKeyframeOp(parsed: ParsedDocument, op: EditOp): MutationResult
179180
);
180181
case "splitIntoPropertyGroups":
181182
return handleSplitIntoPropertyGroups(parsed, op.animationId);
183+
case "splitAnimations":
184+
return handleSplitAnimations(parsed, op);
182185
default:
183186
return undefined;
184187
}
@@ -823,6 +826,24 @@ function handleSplitIntoPropertyGroups(
823826
return gsapScriptChange(script, newScript);
824827
}
825828

829+
function handleSplitAnimations(
830+
parsed: ParsedDocument,
831+
op: Extract<EditOp, { type: "splitAnimations" }>,
832+
): MutationResult {
833+
const script = getGsapScript(parsed.document);
834+
if (!script) return EMPTY;
835+
const { script: newScript } = splitAnimationsInScript(script, {
836+
originalId: op.originalId,
837+
newId: op.newId,
838+
splitTime: op.splitTime,
839+
elementStart: op.elementStart,
840+
elementDuration: op.elementDuration,
841+
});
842+
if (newScript === script) return EMPTY;
843+
setGsapScript(parsed.document, newScript);
844+
return gsapScriptChange(script, newScript);
845+
}
846+
826847
function handleDeleteAllForSelector(parsed: ParsedDocument, selector: string): MutationResult {
827848
const script = getGsapScript(parsed.document);
828849
if (!script) return EMPTY;
@@ -1044,6 +1065,7 @@ export function validateOp(parsed: ParsedDocument, op: EditOp): CanResult {
10441065
case "convertToKeyframes":
10451066
case "materializeKeyframes":
10461067
case "splitIntoPropertyGroups":
1068+
case "splitAnimations":
10471069
case "deleteAllForSelector":
10481070
case "removeLabel":
10491071
if (getGsapScript(parsed.document) === null)

0 commit comments

Comments
 (0)