Skip to content

Write HTML. Render video. Built for agents.

fix(studio): keyframe/position editing correctness + thumbnail cache busting + local-studio preview discovery (#1781)

Miguel Ángel0a9555a0f717
diff --git a/bun.lock b/bun.lock
index a4e2e1eed2..3ebd2e5935 100644
--- a/bun.lock
+++ b/bun.lock
@@ -22,7 +22,7 @@
},
"packages/aws-lambda": {
"name": "@hyperframes/aws-lambda",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@aws-sdk/client-s3": "^3.700.0",
"@aws-sdk/client-sfn": "^3.700.0",
@@ -54,7 +54,7 @@
},
"packages/cli": {
"name": "@hyperframes/cli",
- "version": "0.7.16",
+ "version": "0.7.17",
"bin": {
"hyperframes": "./dist/cli.js",
},
@@ -103,7 +103,7 @@
},
"packages/core": {
"name": "@hyperframes/core",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@chenglou/pretext": "^0.0.5",
"@hyperframes/lint": "workspace:*",
@@ -128,7 +128,7 @@
},
"packages/engine": {
"name": "@hyperframes/engine",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@hono/node-server": "^1.13.0",
"@hyperframes/core": "workspace:^",
@@ -146,7 +146,7 @@
},
"packages/gcp-cloud-run": {
"name": "@hyperframes/gcp-cloud-run",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@google-cloud/storage": "^7.14.0",
"@google-cloud/workflows": "^4.2.0",
@@ -166,7 +166,7 @@
},
"packages/lint": {
"name": "@hyperframes/lint",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@hyperframes/parsers": "workspace:*",
"postcss": "^8.5.8",
@@ -181,7 +181,7 @@
},
"packages/parsers": {
"name": "@hyperframes/parsers",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@babel/parser": "^7.27.0",
"acorn": "^8.17.0",
@@ -201,7 +201,7 @@
},
"packages/player": {
"name": "@hyperframes/player",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@hyperframes/core": "workspace:*",
},
@@ -216,7 +216,7 @@
},
"packages/producer": {
"name": "@hyperframes/producer",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@fontsource/archivo-black": "^5.2.8",
"@fontsource/eb-garamond": "^5.2.7",
@@ -259,7 +259,7 @@
},
"packages/sdk": {
"name": "@hyperframes/sdk",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@hyperframes/core": "workspace:*",
"@hyperframes/parsers": "workspace:*",
@@ -285,7 +285,7 @@
},
"packages/shader-transitions": {
"name": "@hyperframes/shader-transitions",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"html2canvas": "^1.4.1",
},
@@ -297,7 +297,7 @@
},
"packages/studio": {
"name": "@hyperframes/studio",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@codemirror/autocomplete": "^6.20.1",
"@codemirror/commands": "^6.10.3",
@@ -318,6 +318,7 @@
"@phosphor-icons/react": "^2.1.10",
"bpm-detective": "^2.0.5",
"dompurify": "^3.2.4",
+ "gsap": "^3.13.0",
"marked": "^14.1.4",
"mediabunny": "^1.45.3",
},
@@ -344,7 +345,7 @@
},
"packages/studio-server": {
"name": "@hyperframes/studio-server",
- "version": "0.7.16",
+ "version": "0.7.17",
"dependencies": {
"@hyperframes/core": "workspace:*",
"@hyperframes/parsers": "workspace:*",
diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts
index 2aa7c6c9c3..ce19734beb 100644
--- a/packages/cli/src/commands/preview.ts
+++ b/packages/cli/src/commands/preview.ts
@@ -283,13 +283,15 @@ export default defineCommand({
},
});
-function previewBaseUrl(port: number): string {
- return `http://127.0.0.1:${port}`;
+// `host` is the loopback the server actually bound (Vite binds `[::1]`, embedded
+// binds `127.0.0.1`); default to IPv4 for the embedded/legacy callers.
+function previewBaseUrl(port: number, host = "127.0.0.1"): string {
+ return `http://${host}:${port}`;
}
-function absolutePreviewUrl(port: number, path: string): string {
+function absolutePreviewUrl(port: number, path: string, host = "127.0.0.1"): string {
if (/^https?:\/\//.test(path)) return path;
- return `${previewBaseUrl(port)}${path.startsWith("/") ? path : `/${path}`}`;
+ return `${previewBaseUrl(port, host)}${path.startsWith("/") ? path : `/${path}`}`;
}
function hasExplicitPreviewPort(argv: string[]): boolean {
@@ -309,7 +311,12 @@ function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
-function previewServerPayload(server: { port: number; projectName: string; projectDir: string }): {
+function previewServerPayload(server: {
+ port: number;
+ host?: string;
+ projectName: string;
+ projectDir: string;
+}): {
port: number;
projectName: string;
projectDir: string;
@@ -319,7 +326,7 @@ function previewServerPayload(server: { port: number; projectName: string; proje
port: server.port,
projectName: server.projectName,
projectDir: server.projectDir,
- url: previewBaseUrl(server.port),
+ url: previewBaseUrl(server.port, server.host),
};
}
@@ -415,7 +422,7 @@ async function printCurrentSelection(
const selection = {
...response.selection,
- thumbnailUrl: absolutePreviewUrl(server.port, response.selection.thumbnailUrl),
+ thumbnailUrl: absolutePreviewUrl(server.port, response.selection.thumbnailUrl, server.host),
};
if (json) {
@@ -597,7 +604,7 @@ async function printCurrentContext(
console.log(`${c.success("◇")} Studio context`);
if (contextIncludes(fields, "server")) {
console.log(` ${c.dim("Project")} ${server.projectName}`);
- console.log(` ${c.dim("Studio")} ${previewBaseUrl(server.port)}`);
+ console.log(` ${c.dim("Studio")} ${previewBaseUrl(server.port, server.host)}`);
}
if (contextIncludes(fields, "selection")) {
if (selection.ok) {
diff --git a/packages/cli/src/server/portUtils.ts b/packages/cli/src/server/portUtils.ts
index c72d7b7fef..92746a2f67 100644
--- a/packages/cli/src/server/portUtils.ts
+++ b/packages/cli/src/server/portUtils.ts
@@ -205,6 +205,13 @@ async function getProcessOnPort(port: number): Promise<string | null> {
export interface ActiveServer {
port: number;
+ /**
+ * Loopback host the server is reachable on, URL-ready (`127.0.0.1` or
+ * `[::1]`). Vite dev servers bind IPv6 (`::1`) while embedded servers bind
+ * IPv4; consumers must use this rather than assuming `127.0.0.1`. Defaults to
+ * `127.0.0.1` when unset (embedded scan path).
+ */
+ host?: string;
projectName: string;
projectDir: string;
version: string;
diff --git a/packages/cli/src/utils/studioSelectionClient.test.ts b/packages/cli/src/utils/studioSelectionClient.test.ts
index b178dc2bb6..6d62c0bcb6 100644
--- a/packages/cli/src/utils/studioSelectionClient.test.ts
+++ b/packages/cli/src/utils/studioSelectionClient.test.ts
@@ -112,6 +112,7 @@ describe("studioSelectionClient", () => {
expect(server).toEqual({
port: 5190,
+ host: "127.0.0.1",
projectName: "demo project",
projectDir: "/tmp/demo",
version: "studio-dev",
@@ -119,6 +120,35 @@ describe("studioSelectionClient", () => {
});
});
+ it("discovers a Vite Studio that only binds IPv6 loopback ([::1])", async () => {
+ const scan = vi.fn(async () => []);
+ // Vite binds ::1 only: the IPv4 probe is refused, the IPv6 probe succeeds.
+ const fetchImpl = vi.fn(async (url: string | URL | Request) => {
+ const u = String(url);
+ if (u === "http://127.0.0.1:5190/api/projects") throw new Error("ECONNREFUSED");
+ expect(u).toBe("http://[::1]:5190/api/projects");
+ return new Response(
+ JSON.stringify({ projects: [{ id: "demo project", dir: "/tmp/demo", title: "Demo" }] }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ );
+ }) as unknown as typeof fetch;
+
+ const server = await findPreviewServerForProject(resolve("/tmp/demo"), 3002, scan, fetchImpl);
+
+ expect(server).toEqual({
+ port: 5190,
+ host: "[::1]",
+ projectName: "demo project",
+ projectDir: "/tmp/demo",
+ version: "studio-dev",
+ pid: null,
+ });
+ // Follow-up API calls must target the IPv6 host the server was found on.
+ expect(studioSelectionUrl(server!)).toBe(
+ "http://[::1]:5190/api/projects/demo%20project/selection",
+ );
+ });
+
it("checks an explicit preferred port for Vite Studio discovery", async () => {
const scan = vi.fn(async () => []);
const fetchImpl = mockProjectsFetch(5191);
diff --git a/packages/cli/src/utils/studioSelectionClient.ts b/packages/cli/src/utils/studioSelectionClient.ts
index 441e7f980b..9a44eb351b 100644
--- a/packages/cli/src/utils/studioSelectionClient.ts
+++ b/packages/cli/src/utils/studioSelectionClient.ts
@@ -93,32 +93,41 @@ export function studioSelectionUrl(server: ActiveServer): string {
}
export function studioApiUrl(server: ActiveServer, route: string): string {
- return `http://127.0.0.1:${server.port}/api/projects/${encodeURIComponent(server.projectName)}/${route}`;
+ const host = server.host ?? "127.0.0.1";
+ return `http://${host}:${server.port}/api/projects/${encodeURIComponent(server.projectName)}/${route}`;
}
+// Vite dev servers bind IPv6 loopback (`::1`) by default while embedded servers
+// bind IPv4 (`127.0.0.1`), so probe both — a single family misses the other and
+// is exactly why `--selection`/`--context` failed against a local-studio preview.
+const LOOPBACK_HOSTS = ["127.0.0.1", "[::1]"] as const;
+
async function findViteStudioServerForProject(
normalizedProjectDir: string,
fetchImpl: typeof fetch,
ports: readonly number[] = VITE_STUDIO_DISCOVERY_PORTS,
): Promise<ActiveServer | null> {
for (const port of ports) {
- try {
- const response = await fetchImpl(`http://127.0.0.1:${port}/api/projects`);
- if (!response.ok) continue;
- const payload = (await response.json()) as StudioProjectsResponse;
- const project = payload.projects?.find(
- (candidate) => normalizePath(candidate.dir) === normalizedProjectDir,
- );
- if (!project) continue;
- return {
- port,
- projectName: project.id,
- projectDir: project.dir,
- version: "studio-dev",
- pid: null,
- };
- } catch {
- // Port is not a Vite-served Studio, or the dev server is not reachable.
+ for (const host of LOOPBACK_HOSTS) {
+ try {
+ const response = await fetchImpl(`http://${host}:${port}/api/projects`);
+ if (!response.ok) continue;
+ const payload = (await response.json()) as StudioProjectsResponse;
+ const project = payload.projects?.find(
+ (candidate) => normalizePath(candidate.dir) === normalizedProjectDir,
+ );
+ if (!project) continue;
+ return {
+ port,
+ host,
+ projectName: project.id,
+ projectDir: project.dir,
+ version: "studio-dev",
+ pid: null,
+ };
+ } catch {
+ // Not a Vite-served Studio on this host/port, or unreachable. Try next.
+ }
}
}
return null;
diff --git a/packages/parsers/src/gsapParser.test.ts b/packages/parsers/src/gsapParser.test.ts
index fc4a763b9a..4f287f9e43 100644
--- a/packages/parsers/src/gsapParser.test.ts
+++ b/packages/parsers/src/gsapParser.test.ts
@@ -20,6 +20,7 @@ import {
addMotionPathToScript,
convertToKeyframesInScript,
removeAllKeyframesFromScript,
+ dedupePositionWritesInScript,
addAnimationWithKeyframesToScript,
splitAnimationsInScript,
splitIntoPropertyGroups,
@@ -2192,6 +2193,10 @@ describe("keyframe mutations", () => {
expect(anim.keyframes).toBeUndefined();
expect(anim.properties.x).toBe(200);
expect(anim.properties.opacity).toBe(1);
+ // Removing all keyframes must HOLD statically (gsap.set equivalent): zero
+ // duration + immediateRender so the element does not re-animate.
+ expect(anim.duration).toBe(0);
+ expect(anim.extras?.immediateRender).toBe("__raw:true");
});
});
@@ -2925,3 +2930,79 @@ describe("base gsap.set (off-timeline global hold)", () => {
expect(sets).toHaveLength(0);
});
});
+
+describe("single position write per element (consolidation)", () => {
+ const posWritesFor = (script: string, selector: string) =>
+ parseGsapScript(script).animations.filter(
+ (a) => a.targetSelector === selector && a.propertyGroup === "position",
+ );
+
+ // The real corruption: a degenerate `tl.to(...,{duration:0,x,y})` AND a stray
+ // `gsap.set(...,{x,y})` for the same element. The later write overrides the
+ // earlier, so the element "can't move".
+ const CORRUPTED = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#box", { duration: 0, x: -766, y: 314, immediateRender: true }, 1.333);
+ gsap.set("#box", { x: -520, y: 170 });
+ gsap.set("#box", { rotation: 45 });
+ tl.to("#box", { opacity: 1, duration: 1 }, 0);
+ `;
+
+ it("dedupe collapses 2+ position writes to exactly one (keeping keepId)", () => {
+ expect(posWritesFor(CORRUPTED, "#box")).toHaveLength(2);
+ const keepId = posWritesFor(CORRUPTED, "#box").find((a) => a.method === "to")!.id;
+ const out = dedupePositionWritesInScript(CORRUPTED, "#box", keepId);
+ const kept = posWritesFor(out, "#box");
+ expect(kept).toHaveLength(1);
+ // Kept the tl.to; stray gsap.set position is gone.
+ expect(kept[0].method).toBe("to");
+ expect(out).not.toMatch(/gsap\.set\("#box",\s*\{\s*x:/);
+ });
+
+ it("dedupe leaves non-position writes for the selector untouched", () => {
+ const out = dedupePositionWritesInScript(CORRUPTED, "#box", undefined);
+ const anims = parseGsapScript(out).animations;
+ // rotation set + opacity tween survive (separate animations, not position).
+ expect(anims.some((a) => a.targetSelector === "#box" && "rotation" in a.properties)).toBe(true);
+ expect(anims.some((a) => a.targetSelector === "#box" && "opacity" in a.properties)).toBe(true);
+ expect(posWritesFor(out, "#box")).toHaveLength(1);
+ });
+
+ it("dedupe keeps the LAST position write when keepId is stale", () => {
+ const out = dedupePositionWritesInScript(CORRUPTED, "#box", "does-not-exist");
+ const kept = posWritesFor(out, "#box");
+ expect(kept).toHaveLength(1);
+ // Last in source order is the gsap.set(x:-520) — runtime-effective one.
+ expect(kept[0].method).toBe("set");
+ expect(kept[0].properties.x).toBe(-520);
+ });
+
+ it("dedupe + update yields exactly one position write with the NEW value", () => {
+ const keepId = posWritesFor(CORRUPTED, "#box").find((a) => a.method === "to")!.id;
+ let out = dedupePositionWritesInScript(CORRUPTED, "#box", keepId);
+ const surviving = posWritesFor(out, "#box")[0];
+ out = updateAnimationInScript(out, surviving.id, { properties: { x: 99, y: 42 } });
+ const kept = posWritesFor(out, "#box");
+ expect(kept).toHaveLength(1);
+ expect(kept[0].properties.x).toBe(99);
+ expect(kept[0].properties.y).toBe(42);
+ });
+
+ it("remove-all-keyframes strips position residue, leaving one held set", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#box", { keyframes: { "0%": { x: 0 }, "100%": { x: 200 } }, duration: 2 }, 0);
+ gsap.set("#box", { x: -520, y: 170 });
+ tl.to("#box", { opacity: 1, duration: 1 }, 0);
+ `;
+ const kfTween = posWritesFor(script, "#box").find((a) => a.keyframes)!;
+ const out = removeAllKeyframesFromScript(script, kfTween.id);
+ const kept = posWritesFor(out, "#box");
+ expect(kept).toHaveLength(1);
+ expect(kept[0].keyframes).toBeUndefined();
+ expect(kept[0].duration).toBe(0);
+ // The stray gsap.set position residue is gone; opacity tween survives.
+ expect(out).not.toMatch(/gsap\.set\("#box",\s*\{\s*x:/);
+ expect(parseGsapScript(out).animations.some((a) => "opacity" in a.properties)).toBe(true);
+ });
+});
diff --git a/packages/parsers/src/gsapParser.ts b/packages/parsers/src/gsapParser.ts
index 4702a0d4f7..e3e373ccb5 100644
--- a/packages/parsers/src/gsapParser.ts
+++ b/packages/parsers/src/gsapParser.ts
@@ -1267,13 +1267,13 @@ function isEditablePropertyKey(key: string): boolean {
return !BUILTIN_VAR_KEYS.has(key) && !DROPPED_VAR_KEYS.has(key) && !EXTRAS_KEYS.has(key);
}
-function makeObjectProperty(key: string, value: number | string): AstNode {
+function makeObjectProperty(key: string, value: number | string | boolean): AstNode {
const obj = parseExpr(`{ ${safeKey(key)}: ${valueToCode(value)} }`);
return obj.properties[0];
}
/** Set (or insert) a single key on an ObjectExpression, preserving sibling keys. */
-function setVarsKey(varsArg: AstNode, key: string, value: number | string): void {
+function setVarsKey(varsArg: AstNode, key: string, value: number | string | boolean): void {
if (varsArg?.type !== "ObjectExpression") return;
const existing = varsArg.properties.find(
(p: AstNode) => isObjectProperty(p) && propKeyName(p) === key,
@@ -1624,10 +1624,15 @@ export function removeAnimationFromScript(script: string, animationId: string):
target = parsed.located.find((l) => l.id === convertedId);
}
if (!target) return script;
- const node = target.call.node;
- const stmtPath = findStatementPath(target.call.path);
- if (!stmtPath) return script;
+ removeCallFromAst(target.call);
+ return recast.print(parsed.ast).code;
+}
+/** Remove a single located tween call from the AST (standalone stmt or chain link). */
+function removeCallFromAst(call: TweenCallInfo): void {
+ const node = call.node;
+ const stmtPath = findStatementPath(call.path);
+ if (!stmtPath) return;
const parentCall = findChainParentCall(stmtPath.node, node);
if (parentCall) {
// Inner link of a chain — splice it out by re-pointing the next link.
@@ -1639,6 +1644,36 @@ export function removeAnimationFromScript(script: string, animationId: string):
// Standalone tween — remove the whole statement.
stmtPath.prune();
}
+}
+
+/**
+ * Recast twin of {@link dedupePositionWritesInScript} (acorn). Enforce "exactly
+ * one position write per element": keep `keepId` (or the LAST position write in
+ * source order if stale), remove every OTHER pure-position write
+ * (`propertyGroup === "position"` — tl.to/from/fromTo flat-or-keyframed, tl.set,
+ * standalone gsap.set, incl. degenerate duration:0 tweens). Non-position writes
+ * for the selector are left untouched.
+ */
+export function dedupePositionWritesInScript(
+ script: string,
+ selector: string,
+ keepId?: string,
+): string {
+ let parsed: ParsedGsapAst;
+ try {
+ parsed = parseGsapAst(script);
+ } catch {
+ return script;
+ }
+ const posWrites = parsed.located.filter(
+ (l) => l.animation.targetSelector === selector && l.animation.propertyGroup === "position",
+ );
+ if (posWrites.length <= 1) return script;
+ const keeper = posWrites.find((l) => l.id === keepId) ?? posWrites[posWrites.length - 1]!;
+ for (const l of posWrites) {
+ if (l === keeper) continue;
+ removeCallFromAst(l.call);
+ }
return recast.print(parsed.ast).code;
}
@@ -2478,6 +2513,29 @@ export function removeAllKeyframesFromScript(script: string, animationId: string
const collapseEntry = method === "from" ? kfEntries[0]! : kfEntries[kfEntries.length - 1]!;
const record = objectExpressionToRecord(collapseEntry.prop.value, loc.parsed.scope);
collapseKeyframesToFlat(loc.target.call.varsArg, record);
+ // Removing ALL keyframes HOLDS the element statically — collapse to a
+ // zero-duration immediateRender tween (a `gsap.set` equivalent), dropping the
+ // original duration/ease so the element does not re-animate from its base
+ // toward the collapsed value (which moved it out from under the selection).
+ removeVarsKey(loc.target.call.varsArg, "ease");
+ setVarsKey(loc.target.call.varsArg, "duration", 0);
+ setVarsKey(loc.target.call.varsArg, "immediateRender", true);
+
+ // Removing all keyframes of a POSITION tween leaves exactly ONE held state:
+ // strip every sibling position write for the same selector (stray gsap.set or a
+ // second tl.to/tl.set) so the collapsed hold is the lone position source. Only
+ // position siblings are stripped; rotation/opacity/etc. for the selector remain.
+ if (loc.target.animation.propertyGroup === "position") {
+ for (const l of loc.parsed.located) {
+ if (l === loc.target) continue;
+ if (
+ l.animation.targetSelector === loc.target.animation.targetSelector &&
+ l.animation.propertyGroup === "position"
+ ) {
+ removeCallFromAst(l.call);
+ }
+ }
+ }
return recast.print(loc.parsed.ast).code;
}
diff --git a/packages/parsers/src/gsapWriter.parity.test.ts b/packages/parsers/src/gsapWriter.parity.test.ts
index 5b07b8fbbc..780c930666 100644
--- a/packages/parsers/src/gsapWriter.parity.test.ts
+++ b/packages/parsers/src/gsapWriter.parity.test.ts
@@ -28,6 +28,7 @@ import {
addAnimationWithKeyframesToScript as addWithKfRecast,
shiftPositionsInScript as shiftRecast,
scalePositionsInScript as scaleRecast,
+ dedupePositionWritesInScript as dedupePosRecast,
type SplitAnimationsOptions,
} from "./gsapParser.js";
import {
@@ -52,6 +53,7 @@ import {
removeAnimationFromScript as removeAnimAcorn,
shiftPositionsInScript as shiftAcorn,
scalePositionsInScript as scaleAcorn,
+ dedupePositionWritesInScript as dedupePosAcorn,
} from "./gsapWriterAcorn.js";
function acornId(script: string): string {
@@ -164,6 +166,44 @@ describe("parity: removeAllKeyframesFromScript (recast vs acorn)", () => {
});
});
+describe("parity: dedupePositionWritesInScript (recast vs acorn)", () => {
+ const DUP = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#box", { duration: 0, x: -766, y: 314, immediateRender: true }, 1.333);
+ gsap.set("#box", { x: -520, y: 170 });
+ gsap.set("#box", { rotation: 45 });
+ tl.to("#box", { opacity: 1, duration: 1 }, 0);
+ `;
+
+ it("keeps the same single position write in both writers (keep last)", () => {
+ const recastOut = dedupePosRecast(DUP, "#box");
+ const acornOut = dedupePosAcorn(DUP, "#box");
+ expect(modelOf(acornOut)).toEqual(modelOf(recastOut));
+ const posCount = modelOf(acornOut).filter(
+ (a) => "x" in a.properties || "y" in a.properties,
+ ).length;
+ expect(posCount).toBe(1);
+ });
+
+ it("keeps keepId (the tl.to) in both writers", () => {
+ const keepId = parseGsapScriptAcorn(DUP).animations.find(
+ (a) => a.method === "to" && a.propertyGroup === "position",
+ )!.id;
+ const recastOut = dedupePosRecast(DUP, "#box", keepId);
+ const acornOut = dedupePosAcorn(DUP, "#box", keepId);
+ expect(modelOf(acornOut)).toEqual(modelOf(recastOut));
+ });
+
+ it("no-op when 0 or 1 position writes — both writers", () => {
+ const single = `
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#box", { x: 10, duration: 1 }, 0);
+ `;
+ expect(dedupePosAcorn(single, "#box")).toBe(single);
+ expect(dedupePosRecast(single, "#box")).toBe(single);
+ });
+});
+
// Array-form keyframes (`keyframes: [{x,y}, …]`, no explicit %) used to no-op on
// removal in BOTH writers — the object-form path couldn't see the array, so the
// keyframe survived while downstream hold-sync stranded an `hf-hold`.
diff --git a/packages/parsers/src/gsapWriterAcorn.inline.test.ts b/packages/parsers/src/gsapWriterAcorn.inline.test.ts
index a193a23a0b..4eaa4ca22a 100644
--- a/packages/parsers/src/gsapWriterAcorn.inline.test.ts
+++ b/packages/parsers/src/gsapWriterAcorn.inline.test.ts
@@ -71,6 +71,11 @@ window.__timelines["scene"].to("#a", { keyframes: { "0%": { x: 0 }, "100%": { x:
const id = parseGsapScriptAcorn(kf).animations[0]!.id;
const out = removeAllKeyframesFromScript(kf, id);
expect(out).not.toContain("keyframes");
+ // Static hold (gsap.set equivalent): zero duration + immediateRender so the
+ // element does not re-animate after collapse.
+ const anim = parseGsapScriptAcorn(out).animations[0]!;
+ expect(anim.duration).toBe(0);
+ expect(anim.extras?.immediateRender).toBe("__raw:true");
});
it("adds the first tween to an empty inline timeline", () => {
diff --git a/packages/parsers/src/gsapWriterAcorn.ts b/packages/parsers/src/gsapWriterAcorn.ts
index 4927be9ae7..1c3f490ef2 100644
--- a/packages/parsers/src/gsapWriterAcorn.ts
+++ b/packages/parsers/src/gsapWriterAcorn.ts
@@ -155,7 +155,7 @@ function removeProp(ms: MagicString, propNode: Node, editableProps: Node[]): voi
}
/** Serialize a vars record to an object-literal source: `{ k: v, ... }`. */
-function buildVarsObjectCode(record: Record<string, number | string>): string {
+function buildVarsObjectCode(record: Record<string, number | string | boolean>): string {
const entries = Object.entries(record).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);
return entries.length > 0 ? `{ ${entries.join(", ")} }` : "{}";
}
@@ -468,16 +468,10 @@ export function addAnimationToScript(
return { script: result, id: newId };
}
-export function removeAnimationFromScript(script: string, animationId: string): string {
- const parsed = parseGsapScriptAcornForWrite(script);
- if (!parsed) return script;
- const target = parsed.located.find((l) => l.id === animationId);
- if (!target) return script;
-
- const ms = new MagicString(script);
- const N = target.call.node;
- const exprStmt = findEnclosingExpressionStatement(target.call.ancestors);
-
+/** Splice a single located tween call out of a MagicString (standalone stmt or chain link). */
+function removeCallFromMagicString(ms: MagicString, call: TweenCallInfo, script: string): void {
+ const N = call.node;
+ const exprStmt = findEnclosingExpressionStatement(call.ancestors);
if (N.callee?.object?.type !== "CallExpression" && exprStmt?.expression === N) {
// Standalone `tl.method(...)` — remove the whole ExpressionStatement
const end =
@@ -489,7 +483,50 @@ export function removeAnimationFromScript(script: string, animationId: string):
// Chain link — splice out `.method(args)` from N.callee.object.end to N.end
ms.remove(N.callee.object.end, N.end);
}
+}
+export function removeAnimationFromScript(script: string, animationId: string): string {
+ const parsed = parseGsapScriptAcornForWrite(script);
+ if (!parsed) return script;
+ const target = parsed.located.find((l) => l.id === animationId);
+ if (!target) return script;
+
+ const ms = new MagicString(script);
+ removeCallFromMagicString(ms, target.call, script);
+ return ms.toString();
+}
+
+/**
+ * Enforce "exactly one position write per element". Position commits (drag, add
+ * keyframe, static hold) must never leave the same selector with two conflicting
+ * position representations (e.g. a degenerate `tl.to("#box",{duration:0,x,y})`
+ * AND a `gsap.set("#box",{x,y})`) — the later one silently overrides the earlier,
+ * so the element "can't move" / snaps / leaves residue on delete.
+ *
+ * Keeps `keepId` (the write the commit just edited); falls back to the LAST
+ * position write in source order (the runtime-effective one) if `keepId` is stale.
+ * Removes every OTHER pure-position write (`propertyGroup === "position"`, which
+ * covers tl.to/from/fromTo flat-or-keyframed, tl.set, and standalone gsap.set,
+ * including degenerate duration:0 tweens). Non-position writes for the same
+ * selector (rotation / opacity / size / mixed) are left untouched.
+ */
+export function dedupePositionWritesInScript(
+ script: string,
+ selector: string,
+ keepId?: string,
+): string {
+ const parsed = parseGsapScriptAcornForWrite(script);
+ if (!parsed) return script;
+ const posWrites = parsed.located.filter(
+ (l) => l.animation.targetSelector === selector && l.animation.propertyGroup === "position",
+ );
+ if (posWrites.length <= 1) return script;
+ const keeper = posWrites.find((l) => l.id === keepId) ?? posWrites[posWrites.length - 1]!;
+ const ms = new MagicString(script);
+ for (const l of posWrites) {
+ if (l === keeper) continue;
+ removeCallFromMagicString(ms, l.call, script);
+ }
return ms.toString();
}
@@ -1180,6 +1217,7 @@ export function removePropertyFromAnimation(
* keyframe's properties: the first for `from()`, the last otherwise (the
* destination = the visible resting state).
*/
+// fallow-ignore-next-line complexity
export function removeAllKeyframesFromScript(script: string, animationId: string): string {
const parsed = parseGsapScriptAcornForWrite(script);
if (!parsed) return script;
@@ -1198,25 +1236,44 @@ export function removeAllKeyframesFromScript(script: string, animationId: string
target.call,
buildVarsObjectCode(buildCollapsedFlatVars(target.animation, collapse)),
);
+ // Removing all keyframes of a POSITION tween must leave exactly ONE held state:
+ // strip every sibling position write for the same selector (a stray gsap.set or
+ // a second tl.to/tl.set) so the collapsed hold is the lone position source. Only
+ // position siblings are stripped; rotation/opacity/etc. for the selector remain.
+ if (target.animation.propertyGroup === "position") {
+ for (const l of parsed.located) {
+ if (l === target) continue;
+ if (
+ l.animation.targetSelector === target.animation.targetSelector &&
+ l.animation.propertyGroup === "position"
+ ) {
+ removeCallFromMagicString(ms, l.call, script);
+ }
+ }
+ }
return ms.toString();
}
// Flat vars for a tween collapsing its keyframes onto one stop: existing
// top-level props, then the collapse keyframe's props (skip per-keyframe
-// `ease`), then duration/ease/extras. Drops keyframes + easeEach by omission.
+// `ease`), then extras. Removing all keyframes HOLDS the element statically —
+// collapse to a zero-duration immediateRender tween (a `gsap.set` equivalent),
+// dropping the original duration/ease so the element does not re-animate.
function buildCollapsedFlatVars(
animation: GsapAnimation,
collapse: { properties: Record<string, number | string> },
-): Record<string, number | string> {
- const flat: Record<string, number | string> = { ...animation.properties };
+): Record<string, number | string | boolean> {
+ const flat: Record<string, number | string | boolean> = { ...animation.properties };
for (const [k, v] of Object.entries(collapse.properties)) {
if (k !== "ease") flat[k] = v;
}
- if (animation.duration !== undefined) flat.duration = animation.duration;
- if (animation.ease) flat.ease = animation.ease;
for (const [k, v] of Object.entries(animation.extras ?? {})) {
if (typeof v === "number" || typeof v === "string") flat[k] = v;
}
+ // Static hold wins over any carried extras: zero duration + immediateRender,
+ // no ease.
+ flat.duration = 0;
+ flat.immediateRender = true;
return flat;
}
diff --git a/packages/player/src/controls.ts b/packages/player/src/controls.ts
index 9e2a410a4e..466bdd2138 100644
--- a/packages/player/src/controls.ts
+++ b/packages/player/src/controls.ts
@@ -73,7 +73,10 @@ export function createControls(
const playBtn = document.createElement("button");
playBtn.className = "hfp-play-btn";
playBtn.type = "button";
- playBtn.innerHTML = PLAY_ICON;
+ // Both glyphs stay in the DOM, stacked; toggling `hfp-playing` crossfade-morphs
+ // between them (see styles.ts) instead of swapping innerHTML, which would kill
+ // the transition.
+ playBtn.innerHTML = `<span class="hfp-ico hfp-ico-play">${PLAY_ICON}</span><span class="hfp-ico hfp-ico-pause">${PAUSE_ICON}</span>`;
playBtn.setAttribute("aria-label", "Play");
const scrubber = document.createElement("div");
@@ -350,7 +353,7 @@ export function createControls(
},
updatePlaying(playing: boolean) {
isPlaying = playing;
- playBtn.innerHTML = playing ? PAUSE_ICON : PLAY_ICON;
+ playBtn.classList.toggle("hfp-playing", playing);
playBtn.setAttribute("aria-label", playing ? "Pause" : "Play");
if (playing) startHideTimer();
else controls.classList.remove("hfp-hidden");
diff --git a/packages/player/src/styles.ts b/packages/player/src/styles.ts
index f5a65540be..5e9e712174 100644
--- a/packages/player/src/styles.ts
+++ b/packages/player/src/styles.ts
@@ -229,6 +229,7 @@ export const PLAYER_STYLES = /* css */ `
}
.hfp-play-btn {
+ position: relative;
background: none;
border: none;
color: var(--hfp-color, #fff);
@@ -247,6 +248,39 @@ export const PLAYER_STYLES = /* css */ `
opacity: 0.8;
}
+ /* Stacked play/pause glyphs that crossfade-morph on toggle (rotate + scale). */
+ .hfp-play-btn .hfp-ico {
+ position: absolute;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition:
+ opacity 200ms ease,
+ transform 220ms cubic-bezier(0.4, 0, 0.2, 1);
+ }
+ .hfp-play-btn .hfp-ico-play {
+ opacity: 1;
+ transform: rotate(0) scale(1);
+ }
+ .hfp-play-btn .hfp-ico-pause {
+ opacity: 0;
+ transform: rotate(-90deg) scale(0.4);
+ }
+ .hfp-play-btn.hfp-playing .hfp-ico-play {
+ opacity: 0;
+ transform: rotate(90deg) scale(0.4);
+ }
+ .hfp-play-btn.hfp-playing .hfp-ico-pause {
+ opacity: 1;
+ transform: rotate(0) scale(1);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .hfp-play-btn .hfp-ico {
+ transition-duration: 0ms;
+ transform: none;
+ }
+ }
+
.hfp-play-btn svg,
.hfp-play-btn svg * {
pointer-events: none;
@@ -424,7 +458,9 @@ export const PLAYER_STYLES = /* css */ `
}
`;
-export const PLAY_ICON = `<svg width="24" height="24" viewBox="0 0 18 18" fill="currentColor"><polygon points="4,2 16,9 4,16"/></svg>`;
+// Play glyph: the right-hand blade from the HyperFrames favicon, framed to its
+// bounding box so it fills the icon. Points right, like a play triangle.
+export const PLAY_ICON = `<svg width="24" height="24" viewBox="46 21 54 56" fill="currentColor"><path d="M87.5129 57.5141L56.9696 73.5433C52.8371 75.7098 48.7046 73.2553 49.6688 69.2104L58.9483 30.1391C59.9125 26.0942 65.2097 23.6397 68.3154 25.8062L91.2447 41.8354C96.4668 45.4796 94.4631 53.8699 87.5129 57.5141Z"/></svg>`;
export const PAUSE_ICON = `<svg width="24" height="24" viewBox="0 0 18 18" fill="currentColor"><rect x="3" y="2" width="4" height="14"/><rect x="11" y="2" width="4" height="14"/></svg>`;
export const VOLUME_HIGH_ICON = `<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/><path d="M14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/></svg>`;
export const VOLUME_LOW_ICON = `<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/></svg>`;
diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.ts
index c65238a089..2e2b58502e 100644
--- a/packages/studio-server/src/routes/files.test.ts
+++ b/packages/studio-server/src/routes/files.test.ts
@@ -239,6 +239,48 @@ tl.fromTo("#box", { opacity: 0, x: -50 }, { opacity: 1, x: 0, duration: 1.5, eas
expect(result.parsed.animations[0].fromProperties?.x).toBe(-50);
});
+ 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>
+const tl = gsap.timeline({ paused: true });
+tl.to("#box", { duration: 0, x: -766, y: 314, immediateRender: true }, 1.333);
+gsap.set("#box", { x: -520, y: 170 });
+gsap.set("#box", { rotation: 45 });
+</script></body></html>`;
+ writeHtml(projectDir, "dup.html", CORRUPTED);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const res = await app.request("http://localhost/projects/demo/gsap-mutations/dup.html", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ type: "consolidate-position-writes", targetSelector: "#box" }),
+ });
+ const result = (await res.json()) as {
+ ok: boolean;
+ parsed: {
+ animations: Array<{
+ targetSelector: string;
+ propertyGroup?: string;
+ properties: Record<string, unknown>;
+ }>;
+ };
+ };
+
+ expect(res.status).toBe(200);
+ expect(result.ok).toBe(true);
+ const posWrites = result.parsed.animations.filter(
+ (a) => a.targetSelector === "#box" && a.propertyGroup === "position",
+ );
+ expect(posWrites).toHaveLength(1);
+ // The non-position rotation set is untouched.
+ expect(
+ result.parsed.animations.some(
+ (a) => a.targetSelector === "#box" && "rotation" in a.properties,
+ ),
+ ).toBe(true);
+ });
+
it("rejects serialized non-finite mutation values before writing source", async () => {
const projectDir = createProjectDir();
writeHtml(projectDir, "comp.html", FROMTO_COMP);
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts
index bad65efb73..7d22d8ae9c 100644
--- a/packages/studio-server/src/routes/files.ts
+++ b/packages/studio-server/src/routes/files.ts
@@ -50,6 +50,7 @@ import {
splitIntoPropertyGroupsFromScript,
shiftPositionsInScript,
scalePositionsInScript,
+ dedupePositionWritesInScript,
} from "@hyperframes/parsers/gsap-writer-acorn";
import {
removeElementFromHtml,
@@ -736,6 +737,14 @@ type GsapMutationRequest =
type: "delete-all-for-selector";
targetSelector: string;
}
+ | {
+ // Enforce "exactly one position write per element": keep `keepAnimationId`
+ // (the write the commit is editing) and strip every other pure-position
+ // write for the selector. Self-heals files that already have duplicates.
+ type: "consolidate-position-writes";
+ targetSelector: string;
+ keepAnimationId?: string;
+ }
| {
// Rewrite all top-level helper/loop constructs into literal tweens so
// computed keyframes become directly editable (visual no-op).
@@ -897,6 +906,14 @@ function executeGsapMutationAcorn(
}
return script;
}
+ case "consolidate-position-writes": {
+ if (!body.targetSelector) return block.scriptText;
+ return dedupePositionWritesInScript(
+ block.scriptText,
+ body.targetSelector,
+ body.keepAnimationId,
+ );
+ }
case "remove-property": {
const r = requireAnimation(block.scriptText, body.animationId);
if ("err" in r) return r.err;
@@ -1101,6 +1118,7 @@ async function executeGsapMutationRecast(
addAnimationWithKeyframesToScript,
splitAnimationsInScript,
splitIntoPropertyGroups,
+ dedupePositionWritesInScript,
} = parser;
function requireAnimation(
@@ -1199,6 +1217,14 @@ async function executeGsapMutationRecast(
}
return script;
}
+ case "consolidate-position-writes": {
+ if (!body.targetSelector) return block.scriptText;
+ return dedupePositionWritesInScript(
+ block.scriptText,
+ body.targetSelector,
+ body.keepAnimationId,
+ );
+ }
case "remove-property": {
const r = requireAnimation(block.scriptText, body.animationId);
if ("err" in r) return r.err;
diff --git a/packages/studio-server/src/routes/thumbnail.test.ts b/packages/studio-server/src/routes/thumbnail.test.ts
index 1516b39506..7946e846ff 100644
--- a/packages/studio-server/src/routes/thumbnail.test.ts
+++ b/packages/studio-server/src/routes/thumbnail.test.ts
@@ -175,6 +175,28 @@ describe("registerThumbnailRoutes", () => {
expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);
});
+ it("regenerates when the composition HTML changes even with explicit w/h", async () => {
+ // Repro: the Studio requests thumbnails WITH explicit dimensions. The old
+ // code only read (and keyed on) the composition file when no w/h was given,
+ // so editing the HTML left the disk-cache key unchanged and served a stale
+ // thumbnail — even after a hard reload. The content hash must always be keyed.
+ const adapter = createAdapter();
+ const project = await adapter.resolveProject("demo");
+ if (!project) throw new Error("missing project");
+ const app = new Hono();
+ registerThumbnailRoutes(app, adapter);
+
+ const indexPath = join(project.dir, "index.html");
+ const url = "http://localhost/projects/demo/thumbnail/index.html?t=2&w=640&h=360&v=test";
+
+ writeFileSync(indexPath, `<div id="box">before</div>`);
+ await app.request(url);
+ writeFileSync(indexPath, `<div id="box">after</div>`);
+ await app.request(url);
+
+ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);
+ });
+
it("keeps changed studio motion separated in the disk cache", async () => {
const adapter = createAdapter();
const project = await adapter.resolveProject("demo");
diff --git a/packages/studio-server/src/routes/thumbnail.ts b/packages/studio-server/src/routes/thumbnail.ts
index 1b3316e471..ab18df5e91 100644
--- a/packages/studio-server/src/routes/thumbnail.ts
+++ b/packages/studio-server/src/routes/thumbnail.ts
@@ -39,11 +39,19 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
let compW = vpWidth || 1920;
let compH = vpHeight || 1080;
let sourceMtime = 0;
- if (!vpWidth) {
- const htmlFile = join(project.dir, compPath);
- if (existsSync(htmlFile)) {
- sourceMtime = Math.round(statSync(htmlFile).mtimeMs);
- const html = readFileSync(htmlFile, "utf-8");
+ // Content-hash the composition HTML into the cache key — ALWAYS, even when
+ // explicit w/h are supplied. The old code only read the file when `!vpWidth`,
+ // so Studio thumbnail requests (which pass dimensions) kept the source out of
+ // the key entirely (sourceMtime=0) and served a stale thumbnail after every
+ // edit, even on a hard reload. Keyed on content (like manualEdits/motion), not
+ // just mtime, so a restore/copy with a preserved mtime can't serve stale.
+ let sourceKey = "";
+ const htmlFile = join(project.dir, compPath);
+ if (existsSync(htmlFile)) {
+ const html = readFileSync(htmlFile, "utf-8");
+ sourceKey = `_${createHash("sha1").update(html).digest("hex").slice(0, 16)}`;
+ sourceMtime = Math.round(statSync(htmlFile).mtimeMs);
+ if (!vpWidth) {
const wMatch = html.match(/data-width=["'](\d+)["']/);
const hMatch = html.match(/data-height=["'](\d+)["']/);
if (wMatch?.[1]) compW = parseInt(wMatch[1]);
@@ -78,11 +86,11 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
const urlVersionKey = urlVersion
? `_${urlVersion.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 32)}`
: "";
- const cacheKey = `${THUMBNAIL_CACHE_VERSION}${urlVersionKey}${manualEditsKey}${motionKey}_${format}_${compPath.replace(/\//g, "_")}_${compW}x${compH}_${sourceMtime}_${seekTime.toFixed(2)}${selectorKey}.${format === "png" ? "png" : "jpg"}`;
+ const cacheKey = `${THUMBNAIL_CACHE_VERSION}${urlVersionKey}${manualEditsKey}${motionKey}${sourceKey}_${format}_${compPath.replace(/\//g, "_")}_${compW}x${compH}_${sourceMtime}_${seekTime.toFixed(2)}${selectorKey}.${format === "png" ? "png" : "jpg"}`;
const cachePath = join(cacheDir, cacheKey);
if (existsSync(cachePath)) {
return new Response(new Uint8Array(readFileSync(cachePath)), {
- headers: { "Content-Type": contentType, "Cache-Control": "public, max-age=60" },
+ headers: { "Content-Type": contentType, "Cache-Control": "no-cache" },
});
}
@@ -107,7 +115,7 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
if (!existsSync(cacheDir)) mkdirSync(cacheDir, { recursive: true });
writeFileSync(cachePath, buffer);
return new Response(new Uint8Array(buffer), {
- headers: { "Content-Type": contentType, "Cache-Control": "public, max-age=60" },
+ headers: { "Content-Type": contentType, "Cache-Control": "no-cache" },
});
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
diff --git a/packages/studio/package.json b/packages/studio/package.json
index 928be5241c..b462458457 100644
--- a/packages/studio/package.json
+++ b/packages/studio/package.json
@@ -62,6 +62,7 @@
"@phosphor-icons/react": "^2.1.10",
"bpm-detective": "^2.0.5",
"dompurify": "^3.2.4",
+ "gsap": "^3.13.0",
"marked": "^14.1.4",
"mediabunny": "^1.45.3"
},
diff --git a/packages/studio/src/components/StudioPreviewArea.tsx b/packages/studio/src/components/StudioPreviewArea.tsx
index be92a377a4..32d8a9d126 100644
--- a/packages/studio/src/components/StudioPreviewArea.tsx
+++ b/packages/studio/src/components/StudioPreviewArea.tsx
@@ -133,7 +133,7 @@ export function StudioPreviewArea({
handleGsapUpdateMeta,
handleGsapAddKeyframe,
handleGsapConvertToKeyframes,
- handleGsapDeleteAllForElement,
+ handleGsapRemoveAllKeyframes,
buildDomSelectionForTimelineElement,
applyMarqueeSelection,
} = useDomEditActionsContext();
@@ -158,9 +158,13 @@ export function StudioPreviewArea({
onSplitElement: handleTimelineElementSplit,
onRazorSplit: handleRazorSplit,
onRazorSplitAll: handleRazorSplitAll,
- onDeleteAllKeyframes: (elId: string) => {
- const rawId = elId.includes("#") ? (elId.split("#").pop() ?? elId) : elId;
- handleGsapDeleteAllForElement(`#${rawId}`);
+ onDeleteAllKeyframes: () => {
+ // Hold the element where it is (collapse keyframes to a static set) rather
+ // than deleting the whole animation — deleting strands a stale GSAP base
+ // that the next drag adds to, flinging the element off-screen.
+ const anim = selectedGsapAnimations.find((a) => a.keyframes);
+ if (!anim) return;
+ handleGsapRemoveAllKeyframes(anim.id);
},
// fallow-ignore-next-line complexity
onDeleteKeyframe: (_elId: string, pct: number) => {
@@ -208,7 +212,7 @@ export function StudioPreviewArea({
handleTimelineElementSplit,
handleRazorSplit,
handleRazorSplitAll,
- handleGsapDeleteAllForElement,
+ handleGsapRemoveAllKeyframes,
domEditSelection?.id,
selectedGsapAnimations,
handleGsapRemoveKeyframe,
diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsx
index 63af38fa52..68df0df321 100644
--- a/packages/studio/src/components/TimelineToolbar.tsx
+++ b/packages/studio/src/components/TimelineToolbar.tsx
@@ -5,6 +5,7 @@ import {
type EnableKeyframesSession,
} from "../hooks/useEnableKeyframes";
import { computeElementPercentage } from "../hooks/gsapShared";
+import { useKeyframeKeyboard } from "../hooks/useKeyframeKeyboard";
import {
getNextTimelineZoomPercent,
getTimelineZoomPercent,
@@ -89,6 +90,13 @@ export function TimelineToolbar({
onToggle: onToggleKeyframe,
} = useKeyframeToggle(domEditSession);
+ // Wire the "Add keyframe (K)" shortcut the toolbar advertises. Active only when
+ // there's a keyframeable selection; otherwise K stays JKL-pause in playback.
+ useKeyframeKeyboard({
+ enabled: STUDIO_KEYFRAMES_ENABLED && Boolean(onToggleKeyframe),
+ onAddKeyframe: onToggleKeyframe,
+ });
+
return (
<div className="border-b border-neutral-800/40 bg-neutral-950/96">
<div className="flex items-center justify-between px-3 py-2">
diff --git a/packages/studio/src/components/editor/MotionPathOverlay.tsx b/packages/studio/src/components/editor/MotionPathOverlay.tsx
index 038538717c..52e856a051 100644
--- a/packages/studio/src/components/editor/MotionPathOverlay.tsx
+++ b/packages/studio/src/components/editor/MotionPathOverlay.tsx
@@ -71,7 +71,7 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({
commitMutation,
selectedGsapAnimations,
handleGsapRemoveKeyframe,
- handleGsapDeleteAllForElement,
+ handleGsapRemoveAllKeyframes,
} = useDomEditContext();
const { rect, geometry, geometryResolved, visibleInPreview, home, pScale } = useMotionPathData(
iframeRef,
@@ -489,7 +489,7 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({
state={kfMenu}
onClose={() => setKfMenu(null)}
onDelete={(_elId, pct) => animId && handleGsapRemoveKeyframe(animId, pct)}
- onDeleteAll={(elId) => handleGsapDeleteAllForElement(`#${elId}`)}
+ onDeleteAll={() => animId && handleGsapRemoveAllKeyframes(animId)}
/>
)}
</>
diff --git a/packages/studio/src/hooks/gsapDragCommit.ts b/packages/studio/src/hooks/gsapDragCommit.ts
index 43260ae5e3..b2771accad 100644
--- a/packages/studio/src/hooks/gsapDragCommit.ts
+++ b/packages/studio/src/hooks/gsapDragCommit.ts
@@ -156,6 +156,33 @@ function findPositionSetAnimation(
);
}
+/**
+ * Find the EXISTING static position HOLD to update for a static-hold drag. Not
+ * just a `set`: a degenerate `tl.to("#el",{duration:0,x,y})` (what
+ * remove-all-keyframes leaves behind) is a held position too, and the next drag
+ * must UPDATE it in place rather than append a second `gsap.set` that fights it
+ * (the duplicate-position-write bug). Only zero-duration holds qualify — a
+ * live-duration `to`/`from` is NOT a static hold (and in the static path it's a
+ * stale/phantom parse: re-committing it would resurrect a just-deleted tween).
+ * Prefers a `set` (the canonical static channel) when both forms exist.
+ */
+function findExistingPositionWrite(
+ animations: GsapAnimation[],
+ selector: string,
+): GsapAnimation | null {
+ const set = findPositionSetAnimation(animations, selector);
+ if (set) return set;
+ return (
+ animations.find(
+ (a) =>
+ a.targetSelector === selector &&
+ a.propertyGroup === "position" &&
+ !a.keyframes &&
+ (a.duration ?? 0) === 0,
+ ) ?? null
+ );
+}
+
/**
* Commit a STATIC element drag as a `tl.set("#el",{x,y})` — the single-source
* position channel for elements with no position animation. Idempotent: a
@@ -235,7 +262,7 @@ export async function commitStaticGsapPosition(
);
}
-export { findPositionSetAnimation };
+export { findExistingPositionWrite };
function findRotationSetAnimation(
animations: GsapAnimation[],
diff --git a/packages/studio/src/hooks/gsapPositionDetection.ts b/packages/studio/src/hooks/gsapPositionDetection.ts
new file mode 100644
index 0000000000..f140930df9
--- /dev/null
+++ b/packages/studio/src/hooks/gsapPositionDetection.ts
@@ -0,0 +1,98 @@
+/**
+ * GSAP position-write detection helpers for the drag bridge: read the live
+ * runtime position from the preview iframe, and find/score the position
+ * animation for a selector (and pick the tween closest to the playhead).
+ *
+ * Extracted from gsapRuntimeBridge.ts to keep that file under the size cap.
+ */
+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
+import { usePlayerStore } from "../player/store/playerStore";
+import { getIframeGsap, queryIframeElement } from "./gsapShared";
+import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler";
+
+// fallow-ignore-next-line complexity
+export function readGsapPositionFromIframe(
+ iframe: HTMLIFrameElement | null,
+ elementSelector: string,
+): { x: number; y: number } | null {
+ const gsap = getIframeGsap(iframe);
+ if (!gsap) return null;
+
+ const element = queryIframeElement(iframe, elementSelector);
+ if (!element) return null;
+
+ const x = Number(gsap.getProperty(element, "x")) || 0;
+ const y = Number(gsap.getProperty(element, "y")) || 0;
+ return { x, y };
+}
+
+// fallow-ignore-next-line complexity
+function animHasPosition(anim: GsapAnimation): boolean {
+ if (anim.keyframes?.keyframes.some((kf) => "x" in kf.properties || "y" in kf.properties))
+ return true;
+ if (anim.method === "fromTo") {
+ const from = anim.fromProperties;
+ return (
+ "x" in anim.properties || "y" in anim.properties || !!(from && ("x" in from || "y" in from))
+ );
+ }
+ return "x" in anim.properties || "y" in anim.properties;
+}
+
+// fallow-ignore-next-line complexity
+export function findGsapPositionAnimation(
+ animations: GsapAnimation[],
+ selector?: string,
+): GsapAnimation | null {
+ if (animations.length === 0) return null;
+ const currentTime = usePlayerStore.getState().currentTime;
+
+ const scored = animations
+ .filter((a) => animHasPosition(a) || a.keyframes || animations.length === 1)
+ .map((a) => {
+ let score = 0;
+ if (animHasPosition(a)) score += 10;
+ if (a.keyframes) score += 5;
+ if (selector && a.targetSelector === selector) score += 8;
+ else if (a.targetSelector.includes(",")) score -= 5;
+ const pos = a.resolvedStart ?? (typeof a.position === "number" ? a.position : 0);
+ const dur = a.duration ?? 0;
+ if (currentTime >= pos - 0.05 && currentTime <= pos + dur + 0.05) score += 50;
+ else
+ score -= Math.round(
+ Math.min(Math.abs(currentTime - pos), Math.abs(currentTime - pos - dur)) * 5,
+ );
+ return { anim: a, score };
+ });
+ scored.sort((a, b) => b.score - a.score);
+ return scored[0]?.anim ?? animations[0];
+}
+
+/**
+ * From a set of candidate tweens, pick the one whose time range is closest to
+ * the current playhead. A tween that *contains* the playhead wins outright;
+ * otherwise the nearest endpoint wins. This ensures a drag at t=6s edits (or
+ * extends) the 4s tween, not the 1.5s one. Tie-break: most keyframes (so a
+ * gesture-recorded tween beats a stub when both are equidistant).
+ */
+// fallow-ignore-next-line complexity
+export function pickClosestToPlayhead(anims: GsapAnimation[]): GsapAnimation | null {
+ if (anims.length <= 1) return anims[0] ?? null;
+ const ct = usePlayerStore.getState().currentTime;
+ return anims.reduce((best, a) => {
+ const s = resolveTweenStart(a) ?? 0;
+ const e = s + resolveTweenDuration(a);
+ const dist = ct >= s && ct <= e ? 0 : Math.min(Math.abs(ct - s), Math.abs(ct - e));
+ const bestS = resolveTweenStart(best) ?? 0;
+ const bestE = bestS + resolveTweenDuration(best);
+ const bestDist =
+ ct >= bestS && ct <= bestE ? 0 : Math.min(Math.abs(ct - bestS), Math.abs(ct - bestE));
+ if (dist < bestDist) return a;
+ if (
+ dist === bestDist &&
+ (a.keyframes?.keyframes.length ?? 0) > (best.keyframes?.keyframes.length ?? 0)
+ )
+ return a;
+ return best;
+ });
+}
diff --git a/packages/studio/src/hooks/gsapRuntimeBridge.test.ts b/packages/studio/src/hooks/gsapRuntimeBridge.test.ts
index e96efea7c0..143fac9f92 100644
--- a/packages/studio/src/hooks/gsapRuntimeBridge.test.ts
+++ b/packages/studio/src/hooks/gsapRuntimeBridge.test.ts
@@ -127,6 +127,39 @@ describe("tryGsapDragIntercept — stale-parse guard (no resurrection after dele
});
});
+ it("updates a degenerate duration:0 hold-`to` in place instead of appending a gsap.set", async () => {
+ const commitMutation = vi.fn();
+ const iframe = fakeIframe("puck-b", []); // runtime empty → STATIC path
+ // What remove-all-keyframes leaves behind: a zero-duration immediateRender
+ // `tl.to` hold. A drag must UPDATE it, not append a 2nd (gsap.set) position
+ // write that silently overrides it (the duplicate-position-write bug).
+ const degenerateHold = {
+ id: "#puck-b-to-0-position",
+ targetSelector: "#puck-b",
+ method: "to",
+ propertyGroup: "position",
+ properties: { x: -766, y: 314 },
+ position: 1.333,
+ resolvedStart: 1.333,
+ duration: 0,
+ } as unknown as GsapAnimation;
+
+ const handled = await tryGsapDragIntercept(
+ selection,
+ { x: -50, y: 30 },
+ [degenerateHold],
+ iframe,
+ commitMutation,
+ );
+
+ expect(handled).toBe(true);
+ // In-place update (2 coalesced update-property), NOT an `add`/`add-keyframe`.
+ const types = commitMutation.mock.calls.map(([, m]) => m.type);
+ expect(types.every((t: string) => t === "update-property")).toBe(true);
+ expect(types).not.toContain("add");
+ expect(types).not.toContain("add-keyframe");
+ });
+
it("does not trip the stale-parse guard when the runtime still has the tween", async () => {
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
const liveTween = {
diff --git a/packages/studio/src/hooks/gsapRuntimeBridge.ts b/packages/studio/src/hooks/gsapRuntimeBridge.ts
index 55c2e50804..c442c4b97d 100644
--- a/packages/studio/src/hooks/gsapRuntimeBridge.ts
+++ b/packages/studio/src/hooks/gsapRuntimeBridge.ts
@@ -21,110 +21,24 @@ import {
commitKeyframedSizeFromResize,
commitWholePathOffset,
computeCurrentPercentage,
- findPositionSetAnimation,
+ findExistingPositionWrite,
findRotationSetAnimation,
findSizeSetAnimation,
materializeIfDynamic,
} from "./gsapDragCommit";
import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler";
import type { GsapDragCommitCallbacks } from "./gsapDragCommit";
-import { getIframeGsap, queryIframeElement, selectorFromSelection } from "./gsapShared";
+import { selectorFromSelection } from "./gsapShared";
+import {
+ findGsapPositionAnimation,
+ pickClosestToPlayhead,
+ readGsapPositionFromIframe,
+} from "./gsapPositionDetection";
import { hasNonHoldTweenForElement } from "./gsapRuntimeKeyframes";
import { roundTo3 } from "../utils/rounding";
-// ── Runtime reads ──────────────────────────────────────────────────────────
-
-// fallow-ignore-next-line complexity
-function readGsapPositionFromIframe(
- iframe: HTMLIFrameElement | null,
- elementSelector: string,
-): { x: number; y: number } | null {
- const gsap = getIframeGsap(iframe);
- if (!gsap) return null;
-
- const element = queryIframeElement(iframe, elementSelector);
- if (!element) return null;
-
- const x = Number(gsap.getProperty(element, "x")) || 0;
- const y = Number(gsap.getProperty(element, "y")) || 0;
- return { x, y };
-}
-
-// ── Animation matching ─────────────────────────────────────────────────────
-
-// fallow-ignore-next-line complexity
-function animHasPosition(anim: GsapAnimation): boolean {
- if (anim.keyframes?.keyframes.some((kf) => "x" in kf.properties || "y" in kf.properties))
- return true;
- if (anim.method === "fromTo") {
- const from = anim.fromProperties;
- return (
- "x" in anim.properties || "y" in anim.properties || !!(from && ("x" in from || "y" in from))
- );
- }
- return "x" in anim.properties || "y" in anim.properties;
-}
-
-function findGsapPositionAnimation(
- animations: GsapAnimation[],
- selector?: string,
-): GsapAnimation | null {
- if (animations.length === 0) return null;
- const currentTime = usePlayerStore.getState().currentTime;
-
- const scored = animations
- .filter((a) => animHasPosition(a) || a.keyframes || animations.length === 1)
- .map((a) => {
- let score = 0;
- if (animHasPosition(a)) score += 10;
- if (a.keyframes) score += 5;
- if (selector && a.targetSelector === selector) score += 8;
- else if (a.targetSelector.includes(",")) score -= 5;
- const pos = a.resolvedStart ?? (typeof a.position === "number" ? a.position : 0);
- const dur = a.duration ?? 0;
- if (currentTime >= pos - 0.05 && currentTime <= pos + dur + 0.05) score += 50;
- else
- score -= Math.round(
- Math.min(Math.abs(currentTime - pos), Math.abs(currentTime - pos - dur)) * 5,
- );
- return { anim: a, score };
- });
- scored.sort((a, b) => b.score - a.score);
- return scored[0]?.anim ?? animations[0];
-}
-
-// ── Selector resolution ────────────────────────────────────────────────────
-
// ── Property-group tween resolution ───────────────────────────────────────
-/**
- * From a set of candidate tweens, pick the one whose time range is closest to
- * the current playhead. A tween that *contains* the playhead wins outright;
- * otherwise the nearest endpoint wins. This ensures a drag at t=6s edits (or
- * extends) the 4s tween, not the 1.5s one. Tie-break: most keyframes (so a
- * gesture-recorded tween beats a stub when both are equidistant).
- */
-function pickClosestToPlayhead(anims: GsapAnimation[]): GsapAnimation | null {
- if (anims.length <= 1) return anims[0] ?? null;
- const ct = usePlayerStore.getState().currentTime;
- return anims.reduce((best, a) => {
- const s = resolveTweenStart(a) ?? 0;
- const e = s + resolveTweenDuration(a);
- const dist = ct >= s && ct <= e ? 0 : Math.min(Math.abs(ct - s), Math.abs(ct - e));
- const bestS = resolveTweenStart(best) ?? 0;
- const bestE = bestS + resolveTweenDuration(best);
- const bestDist =
- ct >= bestS && ct <= bestE ? 0 : Math.min(Math.abs(ct - bestS), Math.abs(ct - bestE));
- if (dist < bestDist) return a;
- if (
- dist === bestDist &&
- (a.keyframes?.keyframes.length ?? 0) > (best.keyframes?.keyframes.length ?? 0)
- )
- return a;
- return best;
- });
-}
-
/**
* Find the tween for a given property group, splitting a legacy mixed tween
* if necessary. Returns the resolved animation or null if none exists.
@@ -212,18 +126,48 @@ export async function tryGsapDragIntercept(
return false;
}
+ // Self-heal: enforce a single position write BEFORE committing. A corrupted
+ // file can carry 2+ conflicting position writes for one selector (e.g. a
+ // degenerate `tl.to(...,{duration:0,x,y})` AND a `gsap.set(...,{x,y})`) — the
+ // later one silently overrides the earlier, so the element "can't move". Keep
+ // the live keyframed/real tween if present (else any), strip the rest, so the
+ // commit below updates ONE write instead of fighting duplicates.
+ let workingAnimations = animations;
+ const isPosWrite = (a: GsapAnimation) =>
+ a.targetSelector === selector && a.propertyGroup === "position";
+ if (animations.filter(isPosWrite).length > 1 && fetchFallbackAnimations) {
+ const fresh = await fetchFallbackAnimations();
+ const dupes = fresh.filter(isPosWrite);
+ if (dupes.length > 1) {
+ const keeper =
+ dupes.find((a) => a.keyframes) ?? dupes.find((a) => (a.duration ?? 0) > 0) ?? dupes[0]!;
+ await commitMutation(
+ selection,
+ {
+ type: "consolidate-position-writes",
+ targetSelector: selector,
+ keepAnimationId: keeper.id,
+ },
+ { label: "Consolidate position writes", skipReload: true },
+ );
+ workingAnimations = await fetchFallbackAnimations();
+ } else {
+ workingAnimations = fresh;
+ }
+ }
+
const resolved = await resolveGroupTween(
"position",
- animations,
+ workingAnimations,
selection,
commitMutation,
fetchFallbackAnimations,
);
let posAnim = resolved?.anim ?? null;
- let resolvedAnimations = resolved?.animations ?? animations;
+ let resolvedAnimations = resolved?.animations ?? workingAnimations;
if (!posAnim) {
- posAnim = findGsapPositionAnimation(animations, selector);
+ posAnim = findGsapPositionAnimation(workingAnimations, selector);
if (!posAnim && fetchFallbackAnimations) {
const fresh = await fetchFallbackAnimations();
resolvedAnimations = fresh;
@@ -253,7 +197,7 @@ export async function tryGsapDragIntercept(
const existingSet =
posAnim && posAnim.method === "set" && posAnim.targetSelector === selector
? posAnim
- : findPositionSetAnimation(resolvedAnimations, selector);
+ : findExistingPositionWrite(resolvedAnimations, selector);
await commitStaticGsapPosition(selection, offset, gsapPos, selector, existingSet, {
commitMutation,
fetchAnimations: fetchFallbackAnimations,
diff --git a/packages/studio/src/hooks/useGsapKeyframeOps.ts b/packages/studio/src/hooks/useGsapKeyframeOps.ts
index bacb95a4b8..a40e109d6f 100644
--- a/packages/studio/src/hooks/useGsapKeyframeOps.ts
+++ b/packages/studio/src/hooks/useGsapKeyframeOps.ts
@@ -12,7 +12,11 @@ import {
} from "../utils/sdkCutover";
import type { KeyframeCacheEntry } from "../player/store/playerStore";
import { commitKeyframeAtTimeImpl } from "./gsapKeyframeCommit";
-import { readKeyframeSnapshot, writeKeyframeCache } from "./gsapKeyframeCacheHelpers";
+import {
+ clearKeyframeCacheForElement,
+ readKeyframeSnapshot,
+ writeKeyframeCache,
+} from "./gsapKeyframeCacheHelpers";
import type {
CommitMutation,
SafeGsapCommitMutation,
@@ -233,8 +237,13 @@ export function useGsapKeyframeOps({
const removeAllKeyframes = useCallback(
async (selection: DomEditSelection, animationId: string) => {
+ const targetPath = selection.sourceFile || activeCompPath || "index.html";
+ // remove-all-keyframes collapses the tween to a static hold and the commit
+ // path doesn't return parsed animations, so the keyframe cache is never
+ // refreshed — clear it here so the timeline diamonds disappear immediately.
+ const elementId = selection.id ?? selection.selector?.match(/^#([\w-]+)/)?.[1] ?? null;
+ if (elementId) clearKeyframeCacheForElement(targetPath, elementId);
if (sdkSession && sdkDeps) {
- const targetPath = selection.sourceFile || activeCompPath || "index.html";
const handled = await sdkGsapRemoveAllKeyframesPersist(
targetPath,
animationId,
diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.ts
index f49901a558..1de0045516 100644
--- a/packages/studio/src/hooks/useGsapTweenCache.ts
+++ b/packages/studio/src/hooks/useGsapTweenCache.ts
@@ -346,9 +346,16 @@ export function useGsapAnimationsForElement(
let ease: string | undefined;
let easeEach: string | undefined;
for (const anim of animations) {
+ // A static position hold (only x/y, no real motion) is a `set`, not a
+ // keyframe — don't synthesize a diamond for it. Covers both `tl.set(...)`
+ // and the `tl.to({ duration: 0, immediateRender: true })` hold that
+ // remove-all-keyframes collapses to (which is otherwise shown as a stray
+ // 0% keyframe).
if (
- anim.method === "set" &&
- Object.keys(anim.properties).every((k) => k === "x" || k === "y")
+ !anim.keyframes &&
+ Object.keys(anim.properties).length > 0 &&
+ Object.keys(anim.properties).every((k) => k === "x" || k === "y") &&
+ (anim.method === "set" || (anim.duration ?? 0) === 0)
)
continue;
const kf = anim.keyframes ?? synthesizeFlatTweenKeyframes(anim);
@@ -454,11 +461,13 @@ export function usePopulateKeyframeCacheForFile(
const mergedByElement = new Map<string, GsapKeyframesData>();
for (const anim of parsed.animations) {
if (anim.hasUnresolvedKeyframes) continue;
- // Position-only set tweens are static holds (created by drag), not
- // keyframed animations — skip them so they don't show timeline diamonds.
- if (anim.method === "set") {
+ // Position-only static holds are not keyframed animations — skip them so
+ // they don't draw a timeline diamond. Covers both a `tl.set(...)` and the
+ // `tl.to({ duration: 0, immediateRender: true })` that remove-all-keyframes
+ // collapses a keyframed tween to.
+ if (!anim.keyframes && (anim.method === "set" || (anim.duration ?? 0) === 0)) {
const propKeys = Object.keys(anim.properties).filter((k) => k !== "immediateRender");
- if (propKeys.every((k) => k === "x" || k === "y")) {
+ if (propKeys.length > 0 && propKeys.every((k) => k === "x" || k === "y")) {
continue;
}
}
diff --git a/packages/studio/src/hooks/useKeyframeKeyboard.ts b/packages/studio/src/hooks/useKeyframeKeyboard.ts
index 260c749f2b..22b3970f22 100644
--- a/packages/studio/src/hooks/useKeyframeKeyboard.ts
+++ b/packages/studio/src/hooks/useKeyframeKeyboard.ts
@@ -33,53 +33,48 @@ export function useKeyframeKeyboard({
(e: KeyboardEvent) => {
if (!enabled) return;
if (isTextInput(document.activeElement)) return;
+ if (e.metaKey || e.ctrlKey) return; // never shadow browser/system combos
const hasSelectedKeyframes = usePlayerStore.getState().selectedKeyframes.size > 0;
+ // Only consume a key we can actually act on. The fall-through matters:
+ // these keys (k/j/arrows) double as JKL playback shortcuts in
+ // usePlaybackKeyboard, so when a handler is absent we must let the event
+ // continue. When we DO act, stopImmediatePropagation prevents the playback
+ // handler from also firing (e.g. K pausing instead of adding a keyframe).
+ // The listener is registered in the capture phase so it runs first.
+ const consume = (run: () => void) => {
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ run();
+ };
+
switch (e.key.toLowerCase()) {
case "k":
- if (!e.metaKey && !e.ctrlKey) {
- e.preventDefault();
- onAddKeyframe?.();
- }
+ if (onAddKeyframe) consume(onAddKeyframe);
break;
case "delete":
case "backspace":
- if (hasSelectedKeyframes) {
- e.preventDefault();
- onDeleteKeyframe?.();
- }
+ if (onDeleteKeyframe && hasSelectedKeyframes) consume(onDeleteKeyframe);
break;
- case "j":
- if (!e.metaKey && !e.ctrlKey) {
- e.preventDefault();
- if (e.shiftKey) onNextKeyframe?.();
- else onPrevKeyframe?.();
- }
+ case "j": {
+ const nav = e.shiftKey ? onNextKeyframe : onPrevKeyframe;
+ if (nav) consume(nav);
break;
+ }
case "h":
- if (!e.metaKey && !e.ctrlKey && hasSelectedKeyframes) {
- e.preventDefault();
- onToggleHold?.();
- }
+ if (onToggleHold && hasSelectedKeyframes) consume(onToggleHold);
break;
case "u":
- if (!e.metaKey && !e.ctrlKey) {
- e.preventDefault();
- onToggleExpand?.();
- }
+ if (onToggleExpand) consume(onToggleExpand);
break;
case "arrowleft":
- if (hasSelectedKeyframes && !e.metaKey && !e.ctrlKey && !e.altKey) {
- e.preventDefault();
- onNudgeKeyframe?.(-1, e.shiftKey);
- }
+ if (onNudgeKeyframe && hasSelectedKeyframes && !e.altKey)
+ consume(() => onNudgeKeyframe(-1, e.shiftKey));
break;
case "arrowright":
- if (hasSelectedKeyframes && !e.metaKey && !e.ctrlKey && !e.altKey) {
- e.preventDefault();
- onNudgeKeyframe?.(1, e.shiftKey);
- }
+ if (onNudgeKeyframe && hasSelectedKeyframes && !e.altKey)
+ consume(() => onNudgeKeyframe(1, e.shiftKey));
break;
}
},
@@ -97,7 +92,9 @@ export function useKeyframeKeyboard({
useEffect(() => {
if (!enabled) return;
- window.addEventListener("keydown", handler);
- return () => window.removeEventListener("keydown", handler);
+ // Capture phase: run before usePlaybackKeyboard's (bubble-phase) JKL handler
+ // so an active keyframe shortcut can claim the key.
+ window.addEventListener("keydown", handler, { capture: true });
+ return () => window.removeEventListener("keydown", handler, { capture: true });
}, [enabled, handler]);
}
diff --git a/packages/studio/src/player/components/PlayerControls.tsx b/packages/studio/src/player/components/PlayerControls.tsx
index 488086800d..5df14ed537 100644
--- a/packages/studio/src/player/components/PlayerControls.tsx
+++ b/packages/studio/src/player/components/PlayerControls.tsx
@@ -1,4 +1,6 @@
import { useRef, useCallback, useEffect, memo } from "react";
+import gsap from "gsap";
+import { MorphSVGPlugin } from "gsap/MorphSVGPlugin";
import { formatFrameTime, formatTime, stepFrameTime } from "../lib/time";
import { shouldMutePreviewAudio } from "../lib/timelineIframeHelpers";
import { usePlayerStore } from "../store/playerStore";
@@ -14,20 +16,45 @@ type TimeDisplayMode = "time" | "frame";
/* ── Icon sub-components ─────────────────────────────────────────── */
-function PlayIcon() {
- return (
- <svg width="12" height="12" viewBox="0 0 24 24" fill="#FAFAFA" aria-hidden="true">
- <polygon points="6,3 20,12 6,21" />
- </svg>
- );
-}
+gsap.registerPlugin(MorphSVGPlugin);
-function PauseIcon() {
+// Play glyph: the right-hand blade from the HyperFrames favicon (points right).
+// Pause glyph: two bars centred in the same coordinate space so MorphSVG can
+// tween one `d` into the other. Both shapes live in the favicon's 0-100 space
+// and the svg viewBox frames the blade's bounding box.
+const PLAY_BLADE_D =
+ "M87.5129 57.5141L56.9696 73.5433C52.8371 75.7098 48.7046 73.2553 49.6688 69.2104L58.9483 30.1391C59.9125 26.0942 65.2097 23.6397 68.3154 25.8062L91.2447 41.8354C96.4668 45.4796 94.4631 53.8699 87.5129 57.5141Z";
+const PAUSE_BARS_D = "M56 28H67V71H56Z M73 28H84V71H73Z";
+
+// Morph the play blade <-> pause bars on toggle via GSAP MorphSVG. Both glyphs
+// are one path whose `d` tweens; the initial render matches `playing` with no
+// animation, and prefers-reduced-motion snaps instead of tweening.
+function PlayPauseMorphIcon({ playing }: { playing: boolean }) {
+ const pathRef = useRef<SVGPathElement>(null);
+ const isFirstRun = useRef(true);
+ useEffect(() => {
+ const el = pathRef.current;
+ if (!el) return;
+ const target = playing ? PAUSE_BARS_D : PLAY_BLADE_D;
+ const reduceMotion =
+ typeof window !== "undefined" &&
+ window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
+ if (isFirstRun.current || reduceMotion) {
+ isFirstRun.current = false;
+ gsap.set(el, { morphSVG: target });
+ return;
+ }
+ const tween = gsap.to(el, { duration: 0.28, ease: "power2.inOut", morphSVG: target });
+ return () => {
+ tween.kill();
+ };
+ }, [playing]);
return (
- <svg width="12" height="12" viewBox="0 0 24 24" fill="#FAFAFA" aria-hidden="true">
- <rect x="6" y="4" width="4" height="16" rx="1" />
- <rect x="14" y="4" width="4" height="16" rx="1" />
- </svg>
+ <span className="relative inline-flex h-3 w-3 items-center justify-center" aria-hidden="true">
+ <svg width="12" height="12" viewBox="46 21 54 56" fill="#FAFAFA">
+ <path ref={pathRef} d={playing ? PAUSE_BARS_D : PLAY_BLADE_D} />
+ </svg>
+ </span>
);
}
@@ -420,7 +447,7 @@ export const PlayerControls = memo(function PlayerControls({
className="flex-shrink-0 w-8 h-8 flex items-center justify-center rounded-lg disabled:opacity-30 disabled:pointer-events-none transition-colors"
style={{ background: "rgba(255,255,255,0.06)" }}
>
- {isPlaying ? <PauseIcon /> : <PlayIcon />}
+ <PlayPauseMorphIcon playing={isPlaying} />
</button>
</Tooltip>
diff --git a/packages/studio/src/utils/gsapSoftReload.test.ts b/packages/studio/src/utils/gsapSoftReload.test.ts
index 9552acf98e..34e168adcc 100644
--- a/packages/studio/src/utils/gsapSoftReload.test.ts
+++ b/packages/studio/src/utils/gsapSoftReload.test.ts
@@ -100,6 +100,35 @@ describe("applySoftReload", () => {
expect(contentWindow.__hfStudioManualEditsApply).toHaveBeenCalled();
});
+ it("strips a stale inline transform from an orphaned (non-timeline-child) element", () => {
+ // Repro: an element dragged via gsap.set whose keyframes were then removed is
+ // no longer a timeline child, so the timeline-children sweep misses it. Its
+ // stale inline transform must still be cleared so it snaps back to its source
+ // (overlay) position instead of rendering offset.
+ const orphan = document.createElement("div");
+ orphan.style.cssText = "left: 1240px; top: 200px; transform: translate(449px, 0px)";
+ Object.assign(orphan, { _gsap: {} }); // GSAP cache marker (set by gsap.set)
+
+ const scriptEl = document.createElement("script");
+ scriptEl.textContent = 'const tl = gsap.timeline({ paused: true }); tl.to("#x", { x: 1 });';
+ const container = document.createElement("div");
+ container.appendChild(scriptEl);
+
+ const { iframe } = buildMockIframe({ gsap: { timeline: vi.fn(), set: vi.fn() } });
+ (iframe as unknown as { contentDocument: unknown }).contentDocument = {
+ querySelectorAll: (sel: string) =>
+ sel === "script:not([src])" ? [scriptEl] : sel === "[style*='transform']" ? [orphan] : [],
+ createElement: (tag: string) => document.createElement(tag),
+ body: container,
+ head: document.createElement("div"),
+ };
+
+ applySoftReload(iframe, SCRIPT_TEXT);
+
+ expect(orphan.style.transform).toBe(""); // stale GSAP transform stripped
+ expect(orphan.style.left).toBe("1240px"); // authored CSS base preserved
+ });
+
it("wraps execution in __hfSuppressSceneMutations when available", () => {
let suppressionCalled = false;
const { iframe } = buildMockIframe({
diff --git a/packages/studio/src/utils/gsapSoftReload.ts b/packages/studio/src/utils/gsapSoftReload.ts
index 3b03c86749..a96de9703f 100644
--- a/packages/studio/src/utils/gsapSoftReload.ts
+++ b/packages/studio/src/utils/gsapSoftReload.ts
@@ -251,6 +251,25 @@ export function applySoftReload(
}
}
+ // Also reset elements carrying a GSAP-applied inline `transform` that the
+ // timeline-children sweep above missed — a dragged element whose position
+ // was a standalone `gsap.set` (never a timeline child), or one whose
+ // keyframes were just removed (no longer in any timeline). Their last
+ // `gsap.set` transform is otherwise orphaned: the re-run won't re-set it
+ // and the sweep above can't see it, so the element renders offset from its
+ // source position (matching the overlay) until a full reload. The clear
+ // below runs BEFORE the re-run, which re-applies the transform for any
+ // element the new script still animates.
+ const seenTargets = new Set<Element>(allTargets);
+ for (const el of doc.querySelectorAll<HTMLElement>("[style*='transform']")) {
+ // Gate on the GSAP cache (`_gsap`) so we only reset transforms GSAP owns —
+ // never strip an authored, non-GSAP inline transform.
+ if (el.style.transform && "_gsap" in el && !seenTargets.has(el)) {
+ seenTargets.add(el);
+ allTargets.push(el);
+ }
+ }
+
// Reset GSAP's internal transform cache so from() tweens don't read stale
// end values. `clearProps: "all"` is needed to flush the cache, but it also
// nukes the element's CSS base (position, width, height, etc.) from the