Skip to content

Commit 1aa31f5

Browse files
feat(sdk,core): ws-3 — unrollDynamicAnimations acorn port + SDK op
Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Co-authored-by: Miguel Ángel <[email protected]>
1 parent 262854c commit 1aa31f5

4 files changed

Lines changed: 172 additions & 1 deletion

File tree

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

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
setArcPathInScript as setArcAcorn,
2828
updateArcSegmentInScript as updateArcSegmentAcorn,
2929
removeArcPathFromScript as removeArcAcorn,
30+
unrollDynamicAnimations as unrollAcorn,
3031
} from "./gsapWriterAcorn.js";
3132
function acornId(script: string): string {
3233
const parsed = parseGsapScriptAcornForWrite(script) as ParsedGsapAcornForWrite;
@@ -460,3 +461,71 @@ describe("removeArcPathFromScript: acorn output correctness", () => {
460461
expect(arcShapeOf(removeArcAcorn(enabled, id)).arcPath).toBeUndefined();
461462
});
462463
});
464+
465+
// ─── unrollDynamicAnimations correctness ──────────────────────────────────────
466+
467+
const UNROLL_LOOP_SCRIPT = `
468+
const tl = gsap.timeline({ paused: true });
469+
const items = ["#a", "#b"];
470+
for (let i = 0; i < items.length; i++) {
471+
tl.to(items[i], { opacity: 1, duration: 1 }, 0);
472+
}
473+
`;
474+
475+
const UNROLL_FOREACH_SCRIPT = `
476+
const tl = gsap.timeline({ paused: true });
477+
["#a", "#b"].forEach(function(sel) {
478+
tl.to(sel, { opacity: 1, duration: 2 }, 1);
479+
});
480+
`;
481+
482+
const UNROLL_ELEMENTS = [
483+
{
484+
selector: "#hero",
485+
keyframes: [
486+
{ percentage: 0, properties: { opacity: 0 } },
487+
{ percentage: 100, properties: { opacity: 1 } },
488+
],
489+
},
490+
{
491+
selector: "#sub",
492+
keyframes: [
493+
{ percentage: 0, properties: { x: 0 } },
494+
{ percentage: 100, properties: { x: 200 } },
495+
],
496+
},
497+
];
498+
499+
function unrollId(script: string): string {
500+
const p = acornId(script);
501+
return p;
502+
}
503+
504+
describe("unrollDynamicAnimations: acorn output correctness", () => {
505+
it("for-loop: loop replaced with individual tl.to() calls", () => {
506+
const id = unrollId(UNROLL_LOOP_SCRIPT);
507+
const out = unrollAcorn(UNROLL_LOOP_SCRIPT, id, UNROLL_ELEMENTS);
508+
expect(out).not.toBe(UNROLL_LOOP_SCRIPT);
509+
expect(out).toContain('tl.to("#hero"');
510+
expect(out).toContain('tl.to("#sub"');
511+
expect(out).not.toContain("for (");
512+
});
513+
514+
it("forEach: loop replaced with individual tl.to() calls", () => {
515+
const id = unrollId(UNROLL_FOREACH_SCRIPT);
516+
const out = unrollAcorn(UNROLL_FOREACH_SCRIPT, id, UNROLL_ELEMENTS);
517+
expect(out).toContain('tl.to("#hero"');
518+
expect(out).not.toContain("forEach");
519+
});
520+
521+
it("preserves duration and position from original tween", () => {
522+
const id = unrollId(UNROLL_LOOP_SCRIPT);
523+
const out = unrollAcorn(UNROLL_LOOP_SCRIPT, id, UNROLL_ELEMENTS);
524+
expect(out).toContain("duration: 1");
525+
expect(out).toContain("}, 0)");
526+
});
527+
528+
it("no-op when animationId not found", () => {
529+
expect(unrollAcorn(UNROLL_LOOP_SCRIPT, "nope", UNROLL_ELEMENTS)).toBe(UNROLL_LOOP_SCRIPT);
530+
});
531+
});

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

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1632,3 +1632,88 @@ export function splitAnimationsInScript(
16321632

16331633
return { script: result, skippedSelectors };
16341634
}
1635+
1636+
// ── Unroll dynamic animations ────────────────────────────────────────────────
1637+
1638+
function isLoopNode(node: any): boolean {
1639+
const t = node?.type;
1640+
return (
1641+
t === "ForStatement" ||
1642+
t === "ForInStatement" ||
1643+
t === "ForOfStatement" ||
1644+
t === "WhileStatement"
1645+
);
1646+
}
1647+
1648+
function isForEachStatement(node: any): boolean {
1649+
return (
1650+
node?.type === "ExpressionStatement" &&
1651+
node.expression?.type === "CallExpression" &&
1652+
node.expression.callee?.property?.name === "forEach"
1653+
);
1654+
}
1655+
1656+
function findEnclosingLoop(ancestors: any[]): { start: number; end: number } | null {
1657+
for (let i = ancestors.length - 2; i >= 0; i--) {
1658+
const node = ancestors[i];
1659+
if (isLoopNode(node) || isForEachStatement(node)) {
1660+
return { start: node.start as number, end: node.end as number };
1661+
}
1662+
}
1663+
return null;
1664+
}
1665+
1666+
function buildUnrollReplacement(
1667+
timelineVar: string,
1668+
animation: GsapAnimation,
1669+
elements: Array<{
1670+
selector: string;
1671+
keyframes: Array<{ percentage: number; properties: Record<string, number | string> }>;
1672+
easeEach?: string;
1673+
}>,
1674+
): string {
1675+
const duration = typeof animation.duration === "number" ? animation.duration : 8;
1676+
const ease = typeof animation.ease === "string" ? animation.ease : "none";
1677+
const pos = animation.position ?? 0;
1678+
const posCode = typeof pos === "number" ? String(pos) : JSON.stringify(pos);
1679+
const calls = elements.map((el) => {
1680+
const sorted = [...el.keyframes].sort((a, b) => a.percentage - b.percentage);
1681+
const kfCode = buildKeyframeObjectCode(sorted, el.easeEach);
1682+
return `${timelineVar}.to(${JSON.stringify(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${JSON.stringify(ease)} }, ${posCode});`;
1683+
});
1684+
return calls.join("\n ");
1685+
}
1686+
1687+
export type UnrollElement = {
1688+
selector: string;
1689+
keyframes: Array<{ percentage: number; properties: Record<string, number | string> }>;
1690+
easeEach?: string;
1691+
};
1692+
1693+
/**
1694+
* Replace a dynamic loop that generates multiple tween calls with individual
1695+
* static `tl.to()` calls — one per element. Finds the loop containing the
1696+
* animation and replaces the entire loop body with unrolled static calls.
1697+
*/
1698+
export function unrollDynamicAnimations(
1699+
script: string,
1700+
animationId: string,
1701+
elements: UnrollElement[],
1702+
): string {
1703+
const parsed = parseGsapScriptAcornForWrite(script);
1704+
if (!parsed) return script;
1705+
const target = parsed.located.find((l) => l.id === animationId);
1706+
if (!target) return script;
1707+
1708+
const replacement = buildUnrollReplacement(parsed.timelineVar, target.animation, elements);
1709+
const ms = new MagicString(script);
1710+
const loop = findEnclosingLoop(target.call.ancestors);
1711+
if (loop) {
1712+
ms.overwrite(loop.start, loop.end, replacement);
1713+
} else {
1714+
const stmt = findEnclosingExpressionStatement(target.call.ancestors);
1715+
if (!stmt) return script;
1716+
ms.overwrite(stmt.start as number, stmt.end as number, replacement);
1717+
}
1718+
return ms.toString();
1719+
}

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ import {
6161
setArcPathInScript,
6262
updateArcSegmentInScript,
6363
removeArcPathFromScript,
64+
unrollDynamicAnimations,
6465
} from "@hyperframes/core/gsap-writer-acorn";
6566
import { deriveKeyframeBackfillDefaults } from "./keyframeBackfill.js";
6667

@@ -208,6 +209,12 @@ function applyArcPathOp(parsed: ParsedDocument, op: EditOp): MutationResult | un
208209
);
209210
case "removeArcPath":
210211
return handleArcPathScript(parsed, s, removeArcPathFromScript(s, op.animationId));
212+
case "unrollDynamicAnimations":
213+
return handleArcPathScript(
214+
parsed,
215+
s,
216+
unrollDynamicAnimations(s, op.animationId, op.elements),
217+
);
211218
default:
212219
return undefined;
213220
}
@@ -1107,6 +1114,7 @@ export function validateOp(parsed: ParsedDocument, op: EditOp): CanResult {
11071114
case "setArcPath":
11081115
case "updateArcSegment":
11091116
case "removeArcPath":
1117+
case "unrollDynamicAnimations":
11101118
case "deleteAllForSelector":
11111119
case "removeLabel":
11121120
if (getGsapScript(parsed.document) === null)

‎packages/sdk/src/types.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,16 @@ export type EditOp =
157157
cp2?: { x: number; y: number };
158158
};
159159
}
160-
| { type: "removeArcPath"; animationId: string };
160+
| { type: "removeArcPath"; animationId: string }
161+
| {
162+
type: "unrollDynamicAnimations";
163+
animationId: string;
164+
elements: Array<{
165+
selector: string;
166+
keyframes: Array<{ percentage: number; properties: Record<string, number | string> }>;
167+
easeEach?: string;
168+
}>;
169+
};
161170

162171
export interface ElasticHold {
163172
start: number;

0 commit comments

Comments
 (0)