Skip to content

Write HTML. Render video. Built for agents.

fix(studio): a resize after a drag writes its keyframe below the timeline it uses (#4638)

Miguel Ángele7a0b6be2c5b
diff --git a/packages/parsers/src/gsapParser.ts b/packages/parsers/src/gsapParser.ts
index 8ff6a1b568..777a2d712a 100644
--- a/packages/parsers/src/gsapParser.ts
+++ b/packages/parsers/src/gsapParser.ts
@@ -1463,9 +1463,10 @@ function findStatementPath(path: AstPath): AstPath | null {
function insertAfterAnchor(parsed: ParsedGsapAst, newStatement: AstNode): void {
const lastCall = parsed.located[parsed.located.length - 1]?.call;
- const anchorPath = lastCall
- ? findStatementPath(lastCall.path)
- : findTimelineDeclarationPath(parsed.ast, parsed.timelineVar);
+ const lastPath = lastCall ? findStatementPath(lastCall.path) : null;
+ const timeline = findTimelineDeclarationPath(parsed.ast, parsed.timelineVar);
+ const beforeTimeline = !!timeline && !!lastPath && lastPath.node.start < timeline.node.start;
+ const anchorPath = !lastCall || beforeTimeline ? timeline : lastPath;
if (anchorPath) {
anchorPath.insertAfter(newStatement);
} else {
diff --git a/packages/parsers/src/gsapWriter.timelineOrder.test.ts b/packages/parsers/src/gsapWriter.timelineOrder.test.ts
new file mode 100644
index 0000000000..9433de450a
--- /dev/null
+++ b/packages/parsers/src/gsapWriter.timelineOrder.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+import * as acorn from "./gsapWriterAcorn.js";
+import * as recast from "./gsapParser.js";
+
+const script = (tl: string) => `window.__timelines = window.__timelines || {};
+const ${tl} = gsap.timeline({ paused: true });
+window.__timelines["main"] = ${tl};`;
+
+const drag = { targetSelector: "#card", method: "set", position: 0, global: true } as const;
+const resize = { targetSelector: "#card", method: "set", position: 0 } as const;
+
+function dragThenResize(writer: typeof acorn | typeof recast, tl: string): string {
+ const dragged = writer.addAnimationToScript(script(tl), {
+ ...drag,
+ properties: { x: -217, y: -38 },
+ }).script;
+ return writer.addAnimationToScript(dragged, {
+ ...resize,
+ properties: { width: 751, height: 871 },
+ }).script;
+}
+
+describe.each([
+ ["acorn", acorn],
+ ["recast", recast],
+])("%s writer: statements on the timeline land below its declaration", (_name, writer) => {
+ it.each(["tl", "master"])("drag then resize with `const %s`", (tl) => {
+ const out = dragThenResize(writer, tl);
+ expect(out.indexOf(`${tl}.set("#card"`)).toBeGreaterThan(out.indexOf(`const ${tl} =`));
+ expect(out.indexOf(`gsap.set("#card"`)).toBeLessThan(out.indexOf(`const ${tl} =`));
+ });
+
+ it("drag then a keyframed tween", () => {
+ const dragged = writer.addAnimationToScript(script("tl"), {
+ ...drag,
+ properties: { x: 10, y: 20 },
+ }).script;
+ const out = writer.addAnimationWithKeyframesToScript(dragged, "#card", 0, 1, [
+ { percentage: 0, properties: { width: 500 } },
+ { percentage: 100, properties: { width: 700 } },
+ ]).script;
+ expect(out.indexOf(`tl.to("#card"`)).toBeGreaterThan(out.indexOf("const tl ="));
+ });
+});
+
+describe("acorn writer: a lone drag or resize keeps its output", () => {
+ it("resize alone", () => {
+ const out = acorn.addAnimationToScript(script("tl"), {
+ ...resize,
+ properties: { width: 751, height: 871 },
+ }).script;
+ expect(out).toBe(`window.__timelines = window.__timelines || {};
+const tl = gsap.timeline({ paused: true });
+tl.set("#card", { width: 751, height: 871 }, 0);
+window.__timelines["main"] = tl;`);
+ });
+
+ it("drag alone", () => {
+ const out = acorn.addAnimationToScript(script("tl"), {
+ ...drag,
+ properties: { x: -217, y: -38 },
+ }).script;
+ expect(out).toBe(`window.__timelines = window.__timelines || {};
+gsap.set("#card", { x: -217, y: -38 });
+const tl = gsap.timeline({ paused: true });
+window.__timelines["main"] = tl;`);
+ });
+});
diff --git a/packages/parsers/src/gsapWriterAcorn.ts b/packages/parsers/src/gsapWriterAcorn.ts
index f6d8e42151..484c9f95a7 100644
--- a/packages/parsers/src/gsapWriterAcorn.ts
+++ b/packages/parsers/src/gsapWriterAcorn.ts
@@ -302,19 +302,20 @@ function isTimelineRooted(node: Node, timelineVar: string, script: string): bool
}
/**
- * Find the byte offset after which to insert a new statement (tween or label).
+ * Byte offset to insert a new tween or label at: never above the timeline declaration.
* Returns null when no timeline declaration exists in the script — callers must
* not emit `tl.xxx()` calls in that case as `tl` would be undefined at render.
*/
function findInsertionPoint(parsed: ParsedGsapAcornForWrite): number | null {
+ const tlDecl = findTimelineDeclarationStatement(parsed.ast, parsed.timelineVar);
const lastLocated = parsed.located[parsed.located.length - 1];
if (lastLocated) {
const lastCall = lastLocated.call;
const exprStmt = findEnclosingExpressionStatement(lastCall.ancestors);
- return exprStmt?.end ?? lastCall.node.end;
+ const lastCallEnd = exprStmt?.end ?? lastCall.node.end;
+ return Math.max(lastCallEnd, tlDecl?.end ?? 0);
}
if (!parsed.hasTimeline) return null;
- const tlDecl = findTimelineDeclarationStatement(parsed.ast, parsed.timelineVar);
return tlDecl?.end ?? (parsed.ast.end as number);
}
diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.ts
index e1a0ef908e..6ee0e8e482 100644
--- a/packages/studio-server/src/routes/files.test.ts
+++ b/packages/studio-server/src/routes/files.test.ts
@@ -1649,6 +1649,34 @@ const tl = gsap.timeline({ paused: true });
expect(result.mutated).toBe(false);
});
+ it("a resize after a drag on a script-less file writes below the timeline it creates", async () => {
+ const projectDir = createProjectDir();
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+ writeHtml(projectDir, "index.html", '<html><body><div id="card"></div></body></html>');
+ const add = (properties: Record<string, number>, global?: boolean) =>
+ app.request("http://localhost/projects/demo/gsap-mutations/index.html", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ type: "add",
+ targetSelector: "#card",
+ method: "set",
+ position: 0,
+ properties,
+ global,
+ }),
+ });
+
+ expect((await add({ x: -217, y: -38 }, true)).status).toBe(200);
+ expect((await add({ width: 751, height: 871 })).status).toBe(200);
+
+ const html = readFileSync(join(projectDir, "index.html"), "utf-8");
+ const declaration = html.indexOf("const tl = gsap.timeline");
+ expect(html.indexOf('gsap.set("#card"')).toBeLessThan(declaration);
+ expect(html.indexOf('tl.set("#card"')).toBeGreaterThan(declaration);
+ });
+
it("consolidate-position-writes leaves exactly one position write per selector", async () => {
const projectDir = createProjectDir();
const CORRUPTED = `<!DOCTYPE html><html><body><script data-hyperframes-gsap>