Skip to content

Write HTML. Render video. Built for agents.

feat(studio): draggable 3D-transform cube in the design panel (#1710)

Miguel Ángel37ac13804189
diff --git a/packages/core/src/parsers/gsapConstants.ts b/packages/core/src/parsers/gsapConstants.ts
index 5976e4b664..8bea681c7b 100644
--- a/packages/core/src/parsers/gsapConstants.ts
+++ b/packages/core/src/parsers/gsapConstants.ts
@@ -21,6 +21,7 @@ export const SUPPORTED_PROPS = [
"rotationY",
"rotationZ",
"perspective",
+ "transformPerspective",
"transformOrigin",
// Visibility
"opacity",
diff --git a/packages/core/src/parsers/gsapParser.test.ts b/packages/core/src/parsers/gsapParser.test.ts
index 71a5b38997..1be1712278 100644
--- a/packages/core/src/parsers/gsapParser.test.ts
+++ b/packages/core/src/parsers/gsapParser.test.ts
@@ -578,6 +578,47 @@ describe("stagger/yoyo/repeat round-trip", () => {
expect(updatedScript).toContain("opacity: 0.5");
});
+ it("converts a static set into a keyframed to() with a duration (keyframable 3D)", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ tl.set("#card", { rotationX: 50, rotationY: 20, immediateRender: true }, 0);
+ `;
+ const parsed = parseGsapScript(script);
+ const animId = parsed.animations[0].id;
+ const result = convertToKeyframesInScript(script, animId, undefined, 4);
+ // Flips set → to, drops the hold marker, gains a duration + keyframes.
+ expect(result).toContain('tl.to("#card"');
+ expect(result).not.toContain("immediateRender");
+ expect(result).toContain("duration: 4");
+ expect(result).toContain("keyframes:");
+ // Both endpoints start at the set's value (visual unchanged until edited).
+ const reparsed = parseGsapScript(result).animations[0];
+ expect(reparsed.keyframes).toBeTruthy();
+ expect(reparsed.keyframes!.keyframes[0]!.properties.rotationX).toBe(50);
+ expect(reparsed.keyframes!.keyframes.at(-1)!.properties.rotationX).toBe(50);
+ });
+
+ it("converts a GLOBAL gsap.set into a timeline-rooted to() (seekable, not gsap.to)", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ gsap.set("#card", { rotationX: 50, rotationY: 20 });
+ `;
+ const parsed = parseGsapScript(script);
+ const animId = parsed.animations[0].id;
+ expect(parsed.animations[0].global).toBe(true);
+ const result = convertToKeyframesInScript(script, animId, undefined, 4);
+ // Must re-root onto the master timeline (tl.to), NOT emit an off-timeline
+ // gsap.to that fires once at load and can't be seeked/rendered.
+ expect(result).toMatch(/tl\.to\(\s*"#card"/);
+ expect(result).not.toMatch(/gsap\.to\(/);
+ expect(result).toContain("duration: 4");
+ expect(result).toContain("keyframes:");
+ // Re-parsed tween is a real timeline keyframe tween, no longer global.
+ const reparsed = parseGsapScript(result).animations[0];
+ expect(reparsed.keyframes).toBeTruthy();
+ expect(reparsed.global).toBeFalsy();
+ });
+
it("apply-to-all (resetKeyframeEases) sets easeEach and strips every per-keyframe ease", () => {
const script = `
const tl = gsap.timeline({ paused: true });
@@ -2812,3 +2853,57 @@ tl.to("#el", { y: 50, duration: 1 }, "+=0.5");`;
expect(parsed.animations[1].position).toBe("+=0.5");
});
});
+
+describe("base gsap.set (off-timeline global hold)", () => {
+ const SCRIPT = `
+ const tl = gsap.timeline({ paused: true });
+ gsap.set("#box", { rotationX: 17, rotationY: 93 });
+ tl.to("#box", { x: 260, duration: 1 }, 0.3);
+ window.__timelines = { main: tl };
+ `;
+
+ it("parses a string-literal gsap.set as a global set animation", () => {
+ const anims = parseGsapScript(SCRIPT).animations.filter((a) => a.targetSelector === "#box");
+ const set = anims.find((a) => a.method === "set");
+ expect(set?.global).toBe(true);
+ expect(set?.properties).toEqual({ rotationX: 17, rotationY: 93 });
+ expect(anims.find((a) => a.method === "to")?.global).toBeUndefined();
+ });
+
+ it("creates a base gsap.set (not tl.set) when global is set", () => {
+ const base = `const tl = gsap.timeline({ paused: true });\ntl.to("#box", { x: 1, duration: 1 }, 0);\nwindow.__timelines = { main: tl };`;
+ const { script } = addAnimationToScript(base, {
+ targetSelector: "#box",
+ method: "set",
+ position: 0,
+ properties: { rotationX: 30 },
+ global: true,
+ });
+ expect(script).toContain('gsap.set("#box"');
+ expect(script).not.toContain('tl.set("#box"');
+ });
+
+ it("updates a global set in place, keeping it gsap.set", () => {
+ const set = parseGsapScript(SCRIPT).animations.find(
+ (a) => a.targetSelector === "#box" && a.method === "set",
+ )!;
+ const updated = updateAnimationInScript(SCRIPT, set.id, {
+ properties: { rotationX: 99, rotationY: 93 },
+ });
+ expect(updated).toContain('gsap.set("#box"');
+ expect(updated).toContain("99");
+ expect(updated).not.toContain('tl.set("#box"');
+ });
+
+ it("leaves a VARIABLE-target gsap.set as surrounding source (not parsed)", () => {
+ const script = `
+ const tl = gsap.timeline({ paused: true });
+ const el = document.querySelector("#box");
+ gsap.set(el, { rotationX: 5 });
+ tl.to("#box", { x: 10, duration: 1 }, 0);
+ window.__timelines = { main: tl };
+ `;
+ const sets = parseGsapScript(script).animations.filter((a) => a.method === "set");
+ expect(sets).toHaveLength(0);
+ });
+});
diff --git a/packages/core/src/parsers/gsapParser.ts b/packages/core/src/parsers/gsapParser.ts
index e6941f2f66..927f59e550 100644
--- a/packages/core/src/parsers/gsapParser.ts
+++ b/packages/core/src/parsers/gsapParser.ts
@@ -440,6 +440,8 @@ interface TweenCallInfo {
varsArg: AstNode;
fromArg?: AstNode;
positionArg?: AstNode;
+ /** True for a base `gsap.set(...)` (off-timeline) rather than `tl.set(...)`. */
+ global?: boolean;
}
/**
@@ -465,10 +467,24 @@ function findAllTweenCalls(
visitCallExpression(path: AstPath) {
const node = path.node;
const callee = node.callee;
+ // A base `gsap.set("#sel", props)` is an off-timeline static hold (no position,
+ // no keyframe marker). Treat it as an editable `set` animation so a static
+ // value (e.g. a 3D transform) round-trips and re-edits in place. Restricted to
+ // a STRING-LITERAL selector: variable-target `gsap.set(el, ...)` holds stay
+ // opaque surrounding source (editing them by selector would be ambiguous).
+ const gsapSetArg = node.arguments?.[0];
+ const isGlobalSet =
+ callee?.type === "MemberExpression" &&
+ callee.object?.type === "Identifier" &&
+ callee.object.name === "gsap" &&
+ callee.property?.type === "Identifier" &&
+ callee.property.name === "set" &&
+ (gsapSetArg?.type === "StringLiteral" ||
+ (gsapSetArg?.type === "Literal" && typeof gsapSetArg.value === "string"));
if (
callee?.type === "MemberExpression" &&
callee.property?.type === "Identifier" &&
- isTimelineRootedCall(node, timelineVar)
+ (isTimelineRootedCall(node, timelineVar) || isGlobalSet)
) {
const method = callee.property.name;
if (!GSAP_METHODS.has(method)) {
@@ -501,6 +517,7 @@ function findAllTweenCalls(
selector: selectorValue,
varsArg: args[1],
positionArg: args[2],
+ ...(isGlobalSet ? { global: true } : {}),
});
}
}
@@ -968,6 +985,7 @@ function tweenCallToAnimation(
group = classifyTweenPropertyGroup(kfProps);
}
if (group) anim.propertyGroup = group;
+ if (call.global) anim.global = true;
if (Object.keys(extras).length > 0) anim.extras = extras;
if (keyframesData) anim.keyframes = keyframesData;
if (motionPathResult) anim.arcPath = motionPathResult.arcPath;
@@ -1306,8 +1324,9 @@ function buildTweenStatementCode(timelineVar: string, anim: Omit<GsapAnimation,
const entries = Object.entries(props).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);
// immediateRender forces GSAP to apply the set when added to the timeline,
// not on the first seek — without it, tl.set at position 0 on a paused
- // timeline is invisible until the playhead moves past 0.
- if (anim.method === "set") entries.push("immediateRender: true");
+ // timeline is invisible until the playhead moves past 0. A base `gsap.set`
+ // already runs immediately, so it doesn't need (or get) the flag.
+ if (anim.method === "set" && !anim.global) entries.push("immediateRender: true");
if (anim.extras) {
for (const [k, v] of Object.entries(anim.extras)) {
entries.push(`${safeKey(k)}: ${valueToCode(v as number | string)}`);
@@ -1324,6 +1343,10 @@ function buildTweenStatementCode(timelineVar: string, anim: Omit<GsapAnimation,
const fromCode = `{ ${fromEntries.join(", ")} }`;
return `${timelineVar}.fromTo(${selector}, ${fromCode}, ${objCode}, ${posCode});`;
}
+ // A base `gsap.set` is off the timeline: no timeline var, no position arg.
+ if (anim.method === "set" && anim.global) {
+ return `gsap.set(${selector}, ${objCode});`;
+ }
return `${timelineVar}.${anim.method}(${selector}, ${objCode}, ${posCode});`;
}
@@ -2302,12 +2325,13 @@ export function convertToKeyframesInScript(
script: string,
animationId: string,
resolvedFromValues?: Record<string, number | string>,
+ setDuration = 1,
): string {
let loc = locateAnimationWithFallback(script, animationId);
if (!loc) return script;
const anim = loc.target.animation;
- if (anim.keyframes || anim.method === "set") return script;
+ if (anim.keyframes) return script;
const { fromProps, toProps } = resolveConversionProps(anim, resolvedFromValues);
const varsArg = loc.target.call.varsArg;
@@ -2326,6 +2350,27 @@ export function convertToKeyframesInScript(
if (anim.method === "fromTo") loc.target.call.node.arguments.splice(1, 1);
}
+ // A static `set` becomes an animatable `to`: flip the method, drop the
+ // immediateRender hold marker, and give it a real duration so the keyframes
+ // span time. This is what makes a static 3D transform keyframeable.
+ if (anim.method === "set") {
+ // A GLOBAL `gsap.set(...)` is off-timeline; flipping only the method would
+ // emit `gsap.to(...)`, which fires once at load and is NOT on the paused
+ // master timeline (the engine can't seek/render it). Re-root it onto the
+ // timeline var and add the position arg (a gsap.set has none) so the
+ // converted tween is seekable. A `tl.set` already has the right object.
+ const calleeObj = loc.target.call.node.callee.object;
+ if (anim.global && calleeObj?.type === "Identifier") {
+ calleeObj.name = loc.parsed.timelineVar;
+ if (loc.target.call.node.arguments.length < 3) {
+ loc.target.call.node.arguments.push(parseExpr("0"));
+ }
+ }
+ loc.target.call.node.callee.property.name = "to";
+ removeVarsKey(varsArg, "immediateRender");
+ setVarsKey(varsArg, "duration", Math.max(0.001, setDuration));
+ }
+
return recast.print(loc.parsed.ast).code;
}
diff --git a/packages/core/src/parsers/gsapParserAcorn.ts b/packages/core/src/parsers/gsapParserAcorn.ts
index 34dadaeb1e..7775d3763b 100644
--- a/packages/core/src/parsers/gsapParserAcorn.ts
+++ b/packages/core/src/parsers/gsapParserAcorn.ts
@@ -443,6 +443,8 @@ export interface TweenCallInfo {
varsArg: any;
fromArg?: any;
positionArg?: any;
+ /** True for a base `gsap.set(...)` (off-timeline) rather than `tl.set(...)`. */
+ global?: boolean;
}
/** True when callee chain is rooted at the timeline variable. */
@@ -477,10 +479,22 @@ function findAllTweenCalls(
// Fire BEFORE children (pre-order) so chained outer calls come first.
if (node.type === "CallExpression") {
const callee = node.callee;
+ // A base `gsap.set("#sel", props)` is an off-timeline static hold — parse it as
+ // an editable global `set` so a static value round-trips and re-edits in place.
+ // STRING-LITERAL selectors only: variable-target holds stay surrounding source.
+ const gsapSetArg = node.arguments?.[0];
+ const isGlobalSet =
+ callee?.type === "MemberExpression" &&
+ callee.object?.type === "Identifier" &&
+ callee.object.name === "gsap" &&
+ callee.property?.type === "Identifier" &&
+ callee.property.name === "set" &&
+ (gsapSetArg?.type === "StringLiteral" ||
+ (gsapSetArg?.type === "Literal" && typeof gsapSetArg.value === "string"));
if (
callee?.type === "MemberExpression" &&
callee.property?.type === "Identifier" &&
- isTimelineRootedCall(node, timelineVar) &&
+ (isTimelineRootedCall(node, timelineVar) || isGlobalSet) &&
GSAP_METHODS.has(callee.property.name)
) {
const method = callee.property.name;
@@ -509,6 +523,7 @@ function findAllTweenCalls(
selector: selectorValue,
varsArg: args[1],
positionArg: args[2],
+ ...(isGlobalSet ? { global: true } : {}),
});
}
}
@@ -923,6 +938,7 @@ function tweenCallToAnimation(
group = classifyTweenPropertyGroup(kfProps);
}
if (group) anim.propertyGroup = group;
+ if (call.global) anim.global = true;
if (Object.keys(extras).length > 0) anim.extras = extras;
if (keyframesData) anim.keyframes = keyframesData;
if (motionPathResult) anim.arcPath = motionPathResult.arcPath;
diff --git a/packages/core/src/parsers/gsapSerialize.ts b/packages/core/src/parsers/gsapSerialize.ts
index af11a1b817..c5832c7156 100644
--- a/packages/core/src/parsers/gsapSerialize.ts
+++ b/packages/core/src/parsers/gsapSerialize.ts
@@ -73,6 +73,11 @@ export interface GsapAnimation {
/** Which property group this tween belongs to (position, scale, size, rotation, visual, other).
* Undefined for legacy mixed tweens that bundle multiple groups. */
propertyGroup?: PropertyGroupName;
+ /** True for a base `gsap.set(...)` (a static hold that runs immediately, OFF the
+ * timeline) rather than `tl.set(...)`. Carries no timeline position and shows no
+ * keyframe marker — used to persist a static value (e.g. a 3D transform) without
+ * introducing a 0% keyframe. */
+ global?: boolean;
/** How this tween was constructed in source. Absent ⇒ literal. */
provenance?: GsapProvenance;
}
@@ -202,7 +207,10 @@ export function serializeGsapAnimations(
const posStr = typeof anim.position === "string" ? `"${anim.position}"` : anim.position;
switch (anim.method) {
case "set":
- return ` ${timelineVar}.set(${selector}, ${propsStr}, ${posStr});`;
+ // A global set is a base `gsap.set` — off the timeline, no position arg.
+ return anim.global
+ ? ` gsap.set(${selector}, ${propsStr});`
+ : ` ${timelineVar}.set(${selector}, ${propsStr}, ${posStr});`;
case "to":
return ` ${timelineVar}.to(${selector}, ${propsStr}, ${posStr});`;
case "from":
@@ -476,6 +484,12 @@ export function resolveConversionProps(
anim: GsapAnimation,
resolvedFromValues?: Record<string, number | string>,
): { fromProps: Record<string, number | string>; toProps: Record<string, number | string> } {
+ if (anim.method === "set") {
+ // A static hold becomes a keyframed `to` whose 0% and 100% both start at the
+ // set's value — the visual is unchanged until the user edits a keyframe to
+ // animate it. (The caller flips the call from `set` to `to` + adds a duration.)
+ return { fromProps: { ...anim.properties }, toProps: { ...anim.properties } };
+ }
if (anim.method === "to") {
const identity = buildIdentityMap(anim.properties);
const fromProps = resolvedFromValues ? { ...identity, ...resolvedFromValues } : identity;
diff --git a/packages/core/src/parsers/gsapWriter.acorn.test.ts b/packages/core/src/parsers/gsapWriter.acorn.test.ts
index c2b520e292..1c40a9364f 100644
--- a/packages/core/src/parsers/gsapWriter.acorn.test.ts
+++ b/packages/core/src/parsers/gsapWriter.acorn.test.ts
@@ -9,6 +9,7 @@ import { describe, expect, it } from "vitest";
import {
addAnimationToScript,
addKeyframeToScript,
+ convertToKeyframesFromScript,
removeAnimationFromScript,
removeKeyframeFromScript,
updateAnimationInScript,
@@ -347,3 +348,22 @@ describe("T6c — keyframe write ops", () => {
expect(result).toBe(SCRIPT_D);
});
});
+
+describe("T6c — convertToKeyframesFromScript: global gsap.set", () => {
+ const SCRIPT_GLOBAL_SET = `\
+var tl = gsap.timeline({ paused: true });
+gsap.set("#card", { rotationX: 50, rotationY: 20 });
+window.__timelines["t"] = tl;`;
+
+ it("re-roots a global gsap.set onto the timeline (tl.to + position), not gsap.to", () => {
+ const animId = parseGsapScript(SCRIPT_GLOBAL_SET).animations[0].id;
+ const result = convertToKeyframesFromScript(SCRIPT_GLOBAL_SET, animId, undefined, 4);
+ // Off-timeline gsap.to would fire once at load and be unseekable; must be tl.to.
+ expect(result).toMatch(/tl\.to\(\s*"#card"/);
+ expect(result).not.toMatch(/gsap\.to\(/);
+ expect(result).toContain("keyframes:");
+ const reparsed = parseGsapScript(result).animations[0];
+ expect(reparsed.keyframes).toBeTruthy();
+ expect(reparsed.global).toBeFalsy();
+ });
+});
diff --git a/packages/core/src/parsers/gsapWriterAcorn.ts b/packages/core/src/parsers/gsapWriterAcorn.ts
index 9a7245c382..3d9bf70027 100644
--- a/packages/core/src/parsers/gsapWriterAcorn.ts
+++ b/packages/core/src/parsers/gsapWriterAcorn.ts
@@ -72,6 +72,10 @@ function buildTweenStatementCode(timelineVar: string, anim: Omit<GsapAnimation,
);
return `${timelineVar}.fromTo(${selector}, { ${fromEntries.join(", ")} }, ${objCode}, ${posCode});`;
}
+ // A base `gsap.set` is off the timeline: no timeline var, no position arg.
+ if (anim.method === "set" && anim.global) {
+ return `gsap.set(${selector}, ${objCode});`;
+ }
return `${timelineVar}.${anim.method}(${selector}, ${objCode}, ${posCode});`;
}
@@ -1207,6 +1211,7 @@ function buildKeyframesVarsCode(
toProps: Record<string, number | string>,
varsNode: Node,
source: string,
+ setDuration?: number,
): string {
const fromEntries = Object.entries(fromProps).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);
const toEntries = Object.entries(toProps).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);
@@ -1215,7 +1220,14 @@ function buildKeyframesVarsCode(
// Preserve every non-editable key (duration/delay/callbacks/stagger/yoyo/…)
// verbatim from source — rebuilding from the animation object alone dropped
// `delay` (not a GsapAnimation field), shifting the tween's start time.
- const parts: string[] = [`keyframes: ${kfCode}`, ...preservedVarsEntries(varsNode, source)];
+ let preserved = preservedVarsEntries(varsNode, source);
+ // Converting a static `set` → drop its hold markers and give it a real duration
+ // so the keyframes span time.
+ if (setDuration !== undefined) {
+ preserved = preserved.filter((e) => !/^\s*(immediateRender|data|duration)\s*:/.test(e));
+ }
+ const parts: string[] = [`keyframes: ${kfCode}`, ...preserved];
+ if (setDuration !== undefined) parts.push(`duration: ${Math.max(0.001, setDuration)}`);
if (animation.ease) parts.push(`ease: "none"`);
return `{ ${parts.join(", ")} }`;
}
@@ -1229,18 +1241,36 @@ export function convertToKeyframesFromScript(
script: string,
animationId: string,
resolvedFromValues?: Record<string, number | string>,
+ setDuration = 1,
): string {
const parsed = parseGsapScriptAcornForWrite(script);
if (!parsed) return script;
const target = parsed.located.find((l) => l.id === animationId);
if (!target) return script;
const { animation, call } = target;
- if (animation.keyframes || call.method === "set") return script;
+ if (animation.keyframes) return script;
+ const isSet = call.method === "set";
const { fromProps, toProps } = resolveConversionProps(animation, resolvedFromValues);
const ms = new MagicString(script);
- if (call.method === "from" || call.method === "fromTo") {
+ // A GLOBAL `gsap.set(...)` is off-timeline; rewriting only the method emits
+ // `gsap.to(...)`, which fires once at load and isn't on the paused master
+ // timeline (the engine can't seek/render it). Re-root onto the timeline var
+ // and add the position arg the set lacks so the converted tween is seekable.
+ if (isSet && animation.global) {
+ const calleeObj = call.node.callee.object;
+ if (calleeObj?.type === "Identifier") {
+ ms.overwrite(calleeObj.start, calleeObj.end, parsed.timelineVar);
+ }
+ const args = call.node.arguments;
+ if (args.length > 0 && args.length < 3) {
+ ms.appendLeft(args[args.length - 1].end, ", 0");
+ }
+ }
+
+ // set/from/fromTo all become `to`; fromTo also drops its `from` argument.
+ if (call.method === "from" || call.method === "fromTo" || isSet) {
ms.overwrite(call.node.callee.property.start, call.node.callee.property.end, "to");
}
if (call.method === "fromTo" && call.fromArg) {
@@ -1249,7 +1279,14 @@ export function convertToKeyframesFromScript(
overwriteVarsArg(
ms,
call,
- buildKeyframesVarsCode(animation, fromProps, toProps, call.varsArg, script),
+ buildKeyframesVarsCode(
+ animation,
+ fromProps,
+ toProps,
+ call.varsArg,
+ script,
+ isSet ? setDuration : undefined,
+ ),
);
return ms.toString();
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.ts
index 215c5cada9..1b272e7941 100644
--- a/packages/core/src/runtime/init.test.ts
+++ b/packages/core/src/runtime/init.test.ts
@@ -371,6 +371,49 @@ describe("initSandboxRuntimeModular", () => {
expect(window.__player?.getDuration()).toBe(12);
});
+ // #6: a single timeline registered under a key that does NOT match the root's
+ // data-composition-id must still bind (sole-timeline fallback) instead of
+ // silently rendering the frozen t=0 DOM.
+ it("binds the sole registered timeline when its key does not match the root id", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-root", "true");
+ root.setAttribute("data-start", "0");
+ root.setAttribute("data-width", "1920");
+ root.setAttribute("data-height", "1080");
+ document.body.appendChild(root);
+
+ // Registered under "wrong-key", not "main".
+ window.__timelines = {
+ "wrong-key": createMockTimeline(7),
+ };
+
+ initSandboxRuntimeModular();
+
+ expect(window.__player?.getDuration()).toBe(7);
+ });
+
+ // #6: when the root id is missing AND two timelines are registered, the
+ // fallback is ambiguous, so nothing is bound (the loud warning fires instead).
+ it("does not bind any timeline when the root id is unmatched and multiple are registered", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-root", "true");
+ root.setAttribute("data-start", "0");
+ root.setAttribute("data-width", "1920");
+ root.setAttribute("data-height", "1080");
+ document.body.appendChild(root);
+
+ window.__timelines = {
+ "wrong-key-a": createMockTimeline(7),
+ "wrong-key-b": createMockTimeline(9),
+ };
+
+ initSandboxRuntimeModular();
+
+ expect(window.__player?.getDuration()).toBe(0);
+ });
+
it("pauses nested media that is outside the timed-media cache after a seek", () => {
const root = document.createElement("div");
root.setAttribute("data-composition-id", "main");
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index 599e89c31b..1c5e5f82a1 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -639,6 +639,29 @@ export function initSandboxRuntimeModular(): void {
const resolveRootTimelineFromDocument = (): TimelineResolution => {
const timelines = (window.__timelines ?? {}) as Record<string, RuntimeTimelineLike | undefined>;
+ // DX fallback (#6): when the root timeline cannot be resolved by id but
+ // EXACTLY ONE usable timeline is registered, bind it rather than silently
+ // rendering the frozen t=0 DOM. Safe because with a single registered
+ // timeline there is no ambiguity about which one is the composition's
+ // root. Multiple registered → ambiguous, so we still return null and let
+ // the loud warning fire.
+ const resolveSoleTimelineFallback = (reason: string): TimelineResolution => {
+ const usable = Object.entries(timelines).filter(
+ (entry): entry is [string, RuntimeTimelineLike] =>
+ !!entry[1] && typeof entry[1].play === "function" && typeof entry[1].pause === "function",
+ );
+ if (usable.length !== 1) return { timeline: null };
+ const [soleId, soleTimeline] = usable[0];
+ return {
+ timeline: soleTimeline,
+ selectedTimelineIds: [soleId],
+ selectedDurationSeconds: getTimelineDurationSeconds(soleTimeline),
+ diagnostics: {
+ code: "root_timeline_sole_registered_fallback",
+ details: { reason, soleTimelineId: soleId },
+ },
+ };
+ };
const startResolver = createRuntimeStartTimeResolver({
timelineRegistry: timelines,
includeAuthoredTimingAttrs: true,
@@ -740,7 +763,7 @@ export function initSandboxRuntimeModular(): void {
const rootCompositionNode = resolveRootCompositionElement();
const rootCompositionId = rootCompositionNode?.getAttribute("data-composition-id") ?? null;
if (!rootCompositionId) {
- return { timeline: null };
+ return resolveSoleTimelineFallback("root_missing_composition_id");
}
const rootTimeline = timelines[rootCompositionId] ?? null;
const collectRootChildCandidates = (): Array<{
@@ -1003,7 +1026,7 @@ export function initSandboxRuntimeModular(): void {
};
}
}
- return { timeline: null };
+ return resolveSoleTimelineFallback("root_composition_id_unmatched_in_registry");
};
// Track whether child composition timelines have been added to the root.
@@ -2102,6 +2125,39 @@ export function initSandboxRuntimeModular(): void {
clock.setDuration(boundDuration);
}
runAdapters("discover", state.currentTime);
+ // Loud, specific diagnostic for the #1 "looks fine, ships broken" trap:
+ // a root timeline never bound even though timelines ARE registered. Without
+ // this the render silently proceeds on the static build-time DOM (frozen at
+ // t=0). Only warn when GSAP timelines exist (CSS/WAAPI/Lottie-only
+ // compositions legitimately bind no GSAP timeline and use adapters).
+ if (!state.capturedTimeline) {
+ const registry = (window.__timelines ?? {}) as Record<string, unknown>;
+ const registeredKeys = Object.keys(registry).filter((k) => registry[k]);
+ if (registeredKeys.length > 0) {
+ const rootEl = resolveRootCompositionElement();
+ const rootCompositionId = rootEl?.getAttribute("data-composition-id") ?? null;
+ postRuntimeDiagnosticOnce(
+ "root_timeline_unbound_registry_present",
+ {
+ reason: rootCompositionId
+ ? "root data-composition-id has no matching key in window.__timelines"
+ : "root composition element has no data-composition-id attribute",
+ rootCompositionId,
+ registeredTimelineKeys: registeredKeys,
+ },
+ "root_timeline_unbound_registry_present",
+ );
+ // eslint-disable-next-line no-console -- loud author-facing warning; this render would otherwise freeze at t=0
+ console.warn(
+ `[hyperframes] Root timeline not bound — render will freeze at t=0. ` +
+ (rootCompositionId
+ ? `Root data-composition-id is "${rootCompositionId}" but window.__timelines has no such key. `
+ : `Root composition element has no data-composition-id. `) +
+ `Registered timeline keys: [${registeredKeys.join(", ")}]. ` +
+ `Register the root timeline under its data-composition-id (window.__timelines["${rootCompositionId ?? "<root-id>"}"] = tl).`,
+ );
+ }
+ }
// __renderReady = timeline binding attempted, safe for deterministic seeking.
// Set after any GSAP batching has completed. renderSeek works with or
// without a GSAP timeline (CSS/WAAPI/Lottie compositions use adapters only).
@@ -2232,11 +2288,30 @@ export function initSandboxRuntimeModular(): void {
if (opts?.activateChildren) {
activateSiblingTimelines(tl);
}
+ // #10: when data-duration exceeds the timeline's intrinsic length the
+ // engine requests frames past the last tween. Seeking a paused GSAP
+ // timeline past its end can revert from()-tweens to their empty initial
+ // state, blanking the final poster. Clamp the MASTER seek to the
+ // timeline's full extent so it holds the final computed frame instead.
+ // Adapters still receive the raw `t` (their media may run longer).
+ // totalDuration() includes repeats; Infinity (infinite repeat) → no clamp.
+ const tlWithTotal = tl as RuntimeTimelineLike & { totalDuration?: () => number };
+ let tlSeekTime = t;
+ if (typeof tlWithTotal.totalDuration === "function") {
+ try {
+ const total = Number(tlWithTotal.totalDuration());
+ if (Number.isFinite(total) && total > 0 && t > total) {
+ tlSeekTime = total;
+ }
+ } catch (err) {
+ swallow("runtime.init.transport.clampDuration", err);
+ }
+ }
try {
if (typeof tl.totalTime === "function") {
- tl.totalTime(t, false);
+ tl.totalTime(tlSeekTime, false);
} else {
- tl.seek(t, false);
+ tl.seek(tlSeekTime, false);
}
} catch (err) {
swallow("runtime.init.transport.seek", err);
diff --git a/packages/core/src/studio-api/routes/files.ts b/packages/core/src/studio-api/routes/files.ts
index df5cde235d..08d4fdd202 100644
--- a/packages/core/src/studio-api/routes/files.ts
+++ b/packages/core/src/studio-api/routes/files.ts
@@ -428,6 +428,14 @@ type GsapMutationRequest =
property: string;
value: number | string;
}
+ | {
+ // Merge MULTIPLE properties into an animation in ONE call. A per-property
+ // loop on a `set` can shift its group-derived id mid-way (e.g. adding `scale`
+ // to a rotation set), 404-ing the next update; this lands them all at once.
+ type: "update-properties";
+ animationId: string;
+ properties: Record<string, number | string>;
+ }
| {
type: "update-from-property";
animationId: string;
@@ -454,6 +462,8 @@ type GsapMutationRequest =
ease?: string;
properties: Record<string, number | string>;
fromProperties?: Record<string, number | string>;
+ /** Emit a base `gsap.set` (off-timeline, no keyframe marker) instead of `tl.set`. */
+ global?: boolean;
}
| { type: "delete"; animationId: string; stripStudioEdits?: boolean }
| {
@@ -490,6 +500,8 @@ type GsapMutationRequest =
type: "convert-to-keyframes";
animationId: string;
resolvedFromValues?: Record<string, number | string>;
+ /** Duration (s) to give a converted static `set`, which has none. */
+ duration?: number;
}
| { type: "remove-all-keyframes"; animationId: string }
| {
@@ -697,6 +709,13 @@ function executeGsapMutationAcorn(
properties: { ...r.anim.properties, [body.property]: val },
});
}
+ case "update-properties": {
+ const r = requireAnimation(block.scriptText, body.animationId);
+ if ("err" in r) return r.err;
+ return updateAnimationInScript(block.scriptText, body.animationId, {
+ properties: { ...r.anim.properties, ...body.properties },
+ });
+ }
case "update-from-property":
case "add-from-property": {
const r = requireFromToAnimation(block.scriptText, body.animationId);
@@ -721,6 +740,7 @@ function executeGsapMutationAcorn(
ease: body.ease,
properties: body.properties,
fromProperties: body.fromProperties,
+ ...(body.global ? { global: true } : {}),
});
return result.script;
}
@@ -788,6 +808,7 @@ function executeGsapMutationAcorn(
block.scriptText,
body.animationId,
body.resolvedFromValues,
+ body.duration,
);
}
case "remove-all-keyframes": {
@@ -979,6 +1000,13 @@ async function executeGsapMutationRecast(
properties: { ...r.anim.properties, [body.property]: val },
});
}
+ case "update-properties": {
+ const r = requireAnimation(block.scriptText, body.animationId);
+ if ("err" in r) return r.err;
+ return updateAnimationInScript(block.scriptText, body.animationId, {
+ properties: { ...r.anim.properties, ...body.properties },
+ });
+ }
case "update-from-property":
case "add-from-property": {
const r = requireFromToAnimation(block.scriptText, body.animationId);
@@ -1014,6 +1042,7 @@ async function executeGsapMutationRecast(
ease: body.ease,
properties: body.properties,
fromProperties: body.fromProperties,
+ ...(body.global ? { global: true } : {}),
});
return result.script;
}
@@ -1081,6 +1110,7 @@ async function executeGsapMutationRecast(
block.scriptText,
body.animationId,
body.resolvedFromValues,
+ body.duration,
);
}
case "remove-all-keyframes": {
diff --git a/packages/studio/src/components/StudioRightPanel.tsx b/packages/studio/src/components/StudioRightPanel.tsx
index aa0f028343..07df9b84fa 100644
--- a/packages/studio/src/components/StudioRightPanel.tsx
+++ b/packages/studio/src/components/StudioRightPanel.tsx
@@ -118,6 +118,7 @@ export function StudioRightPanel({
handleGsapAddFromProperty,
handleGsapRemoveFromProperty,
commitAnimatedProperty,
+ commitAnimatedProperties,
handleSetArcPath,
handleUpdateArcSegment,
handleUnroll,
@@ -269,9 +270,12 @@ export function StudioRightPanel({
onRemoveGsapFromProperty={handleGsapRemoveFromProperty}
onAddGsapAnimation={handleGsapAddAnimation}
onCommitAnimatedProperty={commitAnimatedProperty}
+ onCommitAnimatedProperties={commitAnimatedProperties}
onAddKeyframe={handleGsapAddKeyframe}
onRemoveKeyframe={handleGsapRemoveKeyframe}
- onConvertToKeyframes={handleGsapConvertToKeyframes}
+ onConvertToKeyframes={(animId, duration) =>
+ handleGsapConvertToKeyframes(animId, undefined, duration)
+ }
onSeekToTime={(t) => usePlayerStore.getState().requestSeek(t)}
onSetArcPath={handleSetArcPath}
onUpdateArcSegment={handleUpdateArcSegment}
diff --git a/packages/studio/src/components/editor/DomEditOverlay.tsx b/packages/studio/src/components/editor/DomEditOverlay.tsx
index 188d474ddb..bc1394afaa 100644
--- a/packages/studio/src/components/editor/DomEditOverlay.tsx
+++ b/packages/studio/src/components/editor/DomEditOverlay.tsx
@@ -2,6 +2,7 @@ import { memo, useEffect, useMemo, useRef, useState, type RefObject } from "reac
import { useMountEffect } from "../../hooks/useMountEffect";
import { type DomEditSelection } from "./domEditing";
import { useMarqueeGestures } from "./marqueeCommit";
+import { MarqueeOverlay } from "./MarqueeOverlay";
import { resolveDomEditGroupOverlayRect, toOverlayRect } from "./domEditOverlayGeometry";
import { collectDomEditLayerItems } from "./domEditingLayers";
import { isElementComputedVisible } from "./domEditingElement";
@@ -101,6 +102,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
const onMarqueeSelectRef = useRef(onMarqueeSelect);
onMarqueeSelectRef.current = onMarqueeSelect;
+ // fallow-ignore-next-line complexity
const selectionShapeStyles = (() => {
const fallback = {
borderRadius: 8 as string | number,
@@ -226,6 +228,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
// outside the composition bounds so users can find them.
const offCanvasElementsRef = useRef<Map<string, HTMLElement>>(new Map());
const [offCanvasRects, setOffCanvasRects] = useState<OffCanvasRect[]>([]);
+ // fallow-ignore-next-line complexity
useEffect(() => {
const iframe = iframeRef.current;
const overlay = overlayRef.current;
@@ -568,18 +571,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
activeCompositionPathRef={activeCompositionPathRef}
onSelectionChangeRef={onSelectionChangeRef}
/>
- {marquee.marqueeRect && (
- <div
- aria-hidden="true"
- className="pointer-events-none absolute border border-dashed border-studio-accent bg-studio-accent/10"
- style={{
- left: marquee.marqueeRect.left,
- top: marquee.marqueeRect.top,
- width: marquee.marqueeRect.width,
- height: marquee.marqueeRect.height,
- }}
- />
- )}
+ <MarqueeOverlay candidateRects={marquee.candidateRects} marqueeRect={marquee.marqueeRect} />
<GridOverlay
visible={gridVisible}
spacing={gridSpacing}
diff --git a/packages/studio/src/components/editor/MarqueeOverlay.tsx b/packages/studio/src/components/editor/MarqueeOverlay.tsx
new file mode 100644
index 0000000000..a3ebfc3395
--- /dev/null
+++ b/packages/studio/src/components/editor/MarqueeOverlay.tsx
@@ -0,0 +1,40 @@
+import type { Rect } from "../../utils/marqueeGeometry";
+
+interface MarqueeOverlayProps {
+ /** Elements the marquee currently intersects — outlined live before mouse-up. */
+ candidateRects: Rect[];
+ /** The marquee drag rectangle itself, or null when not marquee-selecting. */
+ marqueeRect: Rect | null;
+}
+
+/**
+ * The marquee selection visuals: a live "candidate" outline on each element the
+ * box currently touches, plus the dashed drag rectangle. Extracted from
+ * DomEditOverlay to keep that file under the 600-line cap.
+ */
+export function MarqueeOverlay({ candidateRects, marqueeRect }: MarqueeOverlayProps) {
+ return (
+ <>
+ {candidateRects.map((r, i) => (
+ <div
+ key={i}
+ aria-hidden="true"
+ className="pointer-events-none absolute rounded-sm border border-studio-accent bg-studio-accent/5"
+ style={{ left: r.left, top: r.top, width: r.width, height: r.height }}
+ />
+ ))}
+ {marqueeRect && (
+ <div
+ aria-hidden="true"
+ className="pointer-events-none absolute border border-dashed border-studio-accent bg-studio-accent/10"
+ style={{
+ left: marqueeRect.left,
+ top: marqueeRect.top,
+ width: marqueeRect.width,
+ height: marqueeRect.height,
+ }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/packages/studio/src/components/editor/OffCanvasIndicators.tsx b/packages/studio/src/components/editor/OffCanvasIndicators.tsx
index 19c5c08773..c671d59efd 100644
--- a/packages/studio/src/components/editor/OffCanvasIndicators.tsx
+++ b/packages/studio/src/components/editor/OffCanvasIndicators.tsx
@@ -24,7 +24,8 @@ interface OffCanvasIndicatorsProps {
/**
* Dashed teal indicators for elements whose bounds extend past the composition
* (the "gray zone"). The in-canvas portion is clipped away so only the
- * protruding sliver is dashed; the inside portion gets a solid outline.
+ * protruding sliver is dashed — the on-canvas part gets no outline, since a
+ * solid selection-style border on an unselected element reads as "selected".
* Extracted from DomEditOverlay to keep that file under the 600-LOC cap.
*/
export function OffCanvasIndicators({
@@ -57,7 +58,6 @@ export function OffCanvasIndicators({
const clipOutside = hasInside
? `polygon(evenodd, 0 0, ${r.width}px 0, ${r.width}px ${r.height}px, 0 ${r.height}px, 0 0, ${cL}px ${cT}px, ${cR}px ${cT}px, ${cR}px ${cB}px, ${cL}px ${cB}px, ${cL}px ${cT}px)`
: undefined;
- const clipInside = `inset(${cT}px ${Math.max(0, r.width - cR)}px ${Math.max(0, r.height - cB)}px ${cL}px round 6px)`;
const selectOffCanvas = async () => {
const el = elements.current.get(r.key);
if (!el) return;
@@ -98,11 +98,6 @@ export function OffCanvasIndicators({
}
}}
/>
- {/* Solid layer — clipped to canvas bounds, covers inside portion */}
- <div
- className="pointer-events-none absolute inset-0 border border-studio-accent/80 rounded-md bg-studio-accent/5 shadow-[0_0_0_1px_rgba(60,230,172,0.25)]"
- style={{ clipPath: clipInside }}
- />
</div>
);
})}
diff --git a/packages/studio/src/components/editor/PropertyPanel.tsx b/packages/studio/src/components/editor/PropertyPanel.tsx
index 287f91dd1f..17bb2c53e8 100644
--- a/packages/studio/src/components/editor/PropertyPanel.tsx
+++ b/packages/studio/src/components/editor/PropertyPanel.tsx
@@ -90,6 +90,7 @@ export const PropertyPanel = memo(function PropertyPanel({
onRemoveKeyframe,
onConvertToKeyframes,
onCommitAnimatedProperty,
+ onCommitAnimatedProperties,
onSeekToTime,
recordingState,
recordingDuration,
@@ -523,9 +524,20 @@ export const PropertyPanel = memo(function PropertyPanel({
elDuration={elDuration}
element={element}
onCommitAnimatedProperty={onCommitAnimatedProperty}
+ onCommitAnimatedProperties={onCommitAnimatedProperties}
onSeekToTime={onSeekToTime}
onRemoveKeyframe={onRemoveKeyframe}
onConvertToKeyframes={onConvertToKeyframes}
+ onLivePreviewProps={(el, props) => {
+ const iframe = iframeRef.current;
+ const win = iframe?.contentWindow as
+ | { gsap?: { set: (t: Element, v: Record<string, number>) => void } }
+ | null
+ | undefined;
+ const sel = el.id ? `#${el.id}` : el.selector;
+ const node = sel ? iframe?.contentDocument?.querySelector(sel) : null;
+ if (win?.gsap && node) win.gsap.set(node, props);
+ }}
/>
)}
<div className="mt-3">
diff --git a/packages/studio/src/components/editor/Transform3DCube.tsx b/packages/studio/src/components/editor/Transform3DCube.tsx
new file mode 100644
index 0000000000..8475b0419c
--- /dev/null
+++ b/packages/studio/src/components/editor/Transform3DCube.tsx
@@ -0,0 +1,313 @@
+import { useRef, useState } from "react";
+import { projectAxes, projectCubeFaces, wrapDeg } from "./transform3dProjection";
+
+export interface CubePose {
+ rotationX: number;
+ rotationY: number;
+ rotationZ: number;
+}
+
+const VIEW_W = 132;
+const VIEW_H = 112;
+const CX = VIEW_W / 2;
+const CY = 54;
+const RADIUS = 26;
+// The cube mirrors the element's orientation 1:1 — no decorative viewing camera,
+// so at rotation 0/0/0 it faces front (flat) exactly like the un-rotated element.
+// The X/Y/Z axis gizmo keeps the flat-at-rest state readable.
+const SENSITIVITY = 0.6; // degrees per pixel of drag
+
+/**
+ * Draggable 3D-orientation cube. Drag to tilt (X/Y); Shift-drag to roll (Z).
+ * Presentational only: emits a live draft pose while dragging and a final pose
+ * on release — the parent owns live-previewing and committing to GSAP props.
+ */
+// transformPerspective (px) is inversely related to effect strength, with 0 = off.
+// Map a 0..1 slider strength to px and to the cube's weak-perspective projection.
+const STRONG_PX = 200;
+const WEAK_PX = 1600;
+const PX_RANGE = WEAK_PX - STRONG_PX;
+const strengthToPx = (s: number) => (s <= 0.01 ? 0 : Math.round(WEAK_PX - s * PX_RANGE));
+const pxToStrength = (px: number) =>
+ px <= 0
+ ? 0
+ : Math.max(0, Math.min(1, (WEAK_PX - Math.max(STRONG_PX, Math.min(WEAK_PX, px))) / PX_RANGE));
+const pxToProjPersp = (px: number) => (px > 0 ? Math.max(2.2, Math.min(14, px / 130)) : 14);
+
+/** Horizontal "perspective strength" slider — left = none, right = dramatic. */
+function PerspectiveSlider({
+ value,
+ onDraft,
+ onCommit,
+}: {
+ value: number;
+ onDraft?: (px: number) => void;
+ onCommit: (px: number) => void;
+}) {
+ const trackRef = useRef<HTMLDivElement | null>(null);
+ const draggingRef = useRef(false);
+ const strength = pxToStrength(value);
+ const fromEvent = (clientX: number) => {
+ const r = trackRef.current?.getBoundingClientRect();
+ if (!r || r.width === 0) return 0;
+ return strengthToPx(Math.max(0, Math.min(1, (clientX - r.left) / r.width)));
+ };
+ return (
+ <div className="flex items-center gap-1.5 px-2 pb-1.5 pt-1">
+ <span className="text-[8px] font-medium uppercase tracking-wide text-neutral-600">Persp</span>
+ <div
+ ref={trackRef}
+ onPointerDown={(e) => {
+ e.currentTarget.setPointerCapture(e.pointerId);
+ draggingRef.current = true;
+ onDraft?.(fromEvent(e.clientX));
+ }}
+ onPointerMove={(e) => {
+ if (draggingRef.current) onDraft?.(fromEvent(e.clientX));
+ }}
+ onPointerUp={(e) => {
+ if (!draggingRef.current) return;
+ draggingRef.current = false;
+ onCommit(fromEvent(e.clientX));
+ }}
+ onPointerCancel={() => {
+ draggingRef.current = false;
+ }}
+ className="relative h-3 flex-1 cursor-ew-resize touch-none"
+ >
+ <div className="absolute top-1/2 h-0.5 w-full -translate-y-1/2 rounded-full bg-neutral-700" />
+ <div
+ className="absolute top-1/2 h-0.5 -translate-y-1/2 rounded-full bg-[#5ff0bf]"
+ style={{ width: `${strength * 100}%` }}
+ />
+ <div
+ className="absolute top-1/2 size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full border border-neutral-900 bg-[#5ff0bf]"
+ style={{ left: `${strength * 100}%` }}
+ />
+ </div>
+ </div>
+ );
+}
+
+export function Transform3DCube({
+ pose,
+ perspective = 0,
+ onPoseDraft,
+ onPoseCommit,
+ onPerspectiveDraft,
+ onPerspectiveCommit,
+ onRecenter,
+ onKeyframe,
+ keyframed,
+}: {
+ pose: CubePose;
+ /** Element's transformPerspective (px); drives the cube's foreshortening. */
+ perspective?: number;
+ /** Fires on every drag move with the in-progress pose (parent live-previews). */
+ onPoseDraft?: (pose: CubePose) => void;
+ /** Fires once on pointer release with the final pose (commit). */
+ onPoseCommit: (pose: CubePose) => void;
+ /** Live + committed perspective (px) from the in-cube slider. */
+ onPerspectiveDraft?: (px: number) => void;
+ onPerspectiveCommit?: (px: number) => void;
+ /** Reset to identity orientation. */
+ onRecenter?: () => void;
+ /** Toggle keyframing the 3D transform (convert the static set → keyframes). */
+ onKeyframe?: () => void;
+ /** Whether the 3D transform is already keyframed (drives the toggle's state). */
+ keyframed?: boolean;
+}) {
+ const [draft, setDraft] = useState<CubePose | null>(null);
+ const dragRef = useRef<{ x: number; y: number; pose: CubePose } | null>(null);
+ const shown = draft ?? pose;
+ const projOpts = {
+ cx: CX,
+ cy: CY,
+ r: RADIUS,
+ persp: pxToProjPersp(perspective),
+ };
+ const faces = projectCubeFaces(shown.rotationX, shown.rotationY, shown.rotationZ, projOpts);
+ const axes = projectAxes(shown.rotationX, shown.rotationY, shown.rotationZ, projOpts);
+
+ const onPointerDown = (e: React.PointerEvent<SVGSVGElement>) => {
+ e.currentTarget.setPointerCapture(e.pointerId);
+ dragRef.current = { x: e.clientX, y: e.clientY, pose: shown };
+ setDraft(shown);
+ };
+
+ const onPointerMove = (e: React.PointerEvent<SVGSVGElement>) => {
+ const d = dragRef.current;
+ if (!d) return;
+ const dx = e.clientX - d.x;
+ const dy = e.clientY - d.y;
+ const next: CubePose = e.shiftKey
+ ? { ...d.pose, rotationZ: wrapDeg(d.pose.rotationZ + dx * SENSITIVITY) }
+ : {
+ rotationX: wrapDeg(d.pose.rotationX - dy * SENSITIVITY),
+ rotationY: wrapDeg(d.pose.rotationY + dx * SENSITIVITY),
+ rotationZ: d.pose.rotationZ,
+ };
+ setDraft(next);
+ onPoseDraft?.(next);
+ };
+
+ const onPointerUp = () => {
+ if (!dragRef.current) return;
+ dragRef.current = null;
+ if (draft) onPoseCommit(draft);
+ setDraft(null);
+ };
+
+ return (
+ <div className="relative overflow-hidden rounded-lg border border-neutral-800 bg-gradient-to-b from-neutral-900 to-neutral-950">
+ <svg
+ viewBox={`0 0 ${VIEW_W} ${VIEW_H}`}
+ className="block w-full cursor-grab touch-none select-none active:cursor-grabbing"
+ style={{ aspectRatio: `${VIEW_W} / ${VIEW_H}` }}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerUp}
+ role="slider"
+ aria-label="Drag to rotate in 3D; hold Shift to roll"
+ aria-valuetext={`X ${Math.round(shown.rotationX)}°, Y ${Math.round(
+ shown.rotationY,
+ )}°, Z ${Math.round(shown.rotationZ)}°`}
+ >
+ <defs>
+ <radialGradient id="cube3d-bg" cx="50%" cy="40%" r="65%">
+ <stop offset="0%" stopColor="#172220" />
+ <stop offset="100%" stopColor="#070a09" />
+ </radialGradient>
+ {/* Soft halo so the cube floats; SourceGraphic stays crisp on top. */}
+ <filter id="cube3d-glow" x="-40%" y="-40%" width="180%" height="180%">
+ <feGaussianBlur stdDeviation="1.4" result="blur" />
+ <feMerge>
+ <feMergeNode in="blur" />
+ <feMergeNode in="SourceGraphic" />
+ </feMerge>
+ </filter>
+ </defs>
+ <rect x="0" y="0" width={VIEW_W} height={VIEW_H} fill="url(#cube3d-bg)" />
+ {/* Grounding shadow under the cube. */}
+ <ellipse
+ cx={CX}
+ cy={CY + RADIUS + 22}
+ rx={RADIUS * 1.2}
+ ry={6.5}
+ fill="#000"
+ opacity={0.4}
+ />
+ {/* Away-facing axes are drawn behind the cube, dimmed. */}
+ {axes
+ .filter((a) => !a.front)
+ .map((a) => (
+ <line
+ key={a.id}
+ x1={CX}
+ y1={CY}
+ x2={a.x2}
+ y2={a.y2}
+ stroke={a.color}
+ strokeWidth={1.4}
+ strokeLinecap="round"
+ opacity={0.3}
+ />
+ ))}
+ <g filter="url(#cube3d-glow)">
+ {faces.map((f) => (
+ <polygon
+ key={f.id}
+ points={f.points}
+ // Muted teal face, lit by direction; edges are a soft mint that
+ // brightens with how front-facing the face is, so corners read as
+ // crisp bevels instead of flat neon outlines.
+ fill={`hsl(166 44% ${Math.round(17 + f.shade * 37)}%)`}
+ stroke={`hsl(164 72% ${Math.round(56 + f.shade * 22)}%)`}
+ strokeWidth={1.1}
+ strokeOpacity={0.82}
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ paintOrder="stroke"
+ />
+ ))}
+ </g>
+ {/* Toward-facing axes on top, with a tip dot + X/Y/Z label. */}
+ {axes
+ .filter((a) => a.front)
+ .map((a) => (
+ <g key={a.id}>
+ <line
+ x1={CX}
+ y1={CY}
+ x2={a.x2}
+ y2={a.y2}
+ stroke={a.color}
+ strokeWidth={1.6}
+ strokeLinecap="round"
+ opacity={0.95}
+ />
+ <circle cx={a.x2} cy={a.y2} r={2.4} fill={a.color} />
+ <text
+ x={a.x2 + (a.x2 - CX) * 0.12}
+ y={a.y2 + (a.y2 - CY) * 0.12 + 2}
+ fill={a.color}
+ fontSize={7}
+ fontWeight={700}
+ textAnchor="middle"
+ >
+ {a.id.toUpperCase()}
+ </text>
+ </g>
+ ))}
+ </svg>
+ {onRecenter && (
+ <button
+ type="button"
+ onClick={onRecenter}
+ title="Reset 3D orientation"
+ aria-label="Reset 3D orientation"
+ className="absolute right-1.5 top-1.5 rounded p-0.5 text-neutral-500 hover:bg-neutral-800 hover:text-neutral-200"
+ >
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor">
+ <circle cx="12" cy="12" r="9" strokeWidth="2" />
+ <path d="M12 3v18M3 12h18" strokeWidth="1.5" />
+ </svg>
+ </button>
+ )}
+ {onKeyframe && (
+ <button
+ type="button"
+ onClick={onKeyframe}
+ title={
+ keyframed
+ ? "3D transform is keyframed — click a field diamond to add keyframes"
+ : "Keyframe the 3D transform (animate it over time)"
+ }
+ aria-label="Keyframe 3D transform"
+ aria-pressed={keyframed}
+ className={`absolute left-1.5 top-1.5 rounded p-0.5 hover:bg-neutral-800 ${
+ keyframed ? "text-[#5ff0bf]" : "text-neutral-500 hover:text-neutral-200"
+ }`}
+ >
+ <svg
+ width="12"
+ height="12"
+ viewBox="0 0 12 12"
+ fill={keyframed ? "currentColor" : "none"}
+ stroke="currentColor"
+ >
+ <path d="M6 1.5L10.5 6 6 10.5 1.5 6z" strokeWidth="1.4" strokeLinejoin="round" />
+ </svg>
+ </button>
+ )}
+ {onPerspectiveCommit && (
+ <PerspectiveSlider
+ value={perspective}
+ onDraft={onPerspectiveDraft}
+ onCommit={onPerspectiveCommit}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/packages/studio/src/components/editor/gsapAnimationConstants.ts b/packages/studio/src/components/editor/gsapAnimationConstants.ts
index cc8ba04e02..0c97947cf2 100644
--- a/packages/studio/src/components/editor/gsapAnimationConstants.ts
+++ b/packages/studio/src/components/editor/gsapAnimationConstants.ts
@@ -25,6 +25,7 @@ export const PROP_LABELS: Record<string, string> = {
rotationY: "Rotate Y",
rotationZ: "Rotate Z",
perspective: "Perspective",
+ transformPerspective: "Perspective",
transformOrigin: "Transform Origin",
opacity: "Opacity",
scale: "Scale",
@@ -57,6 +58,7 @@ export const PROP_UNITS: Record<string, string> = {
rotationY: "°",
rotationZ: "°",
perspective: "px",
+ transformPerspective: "px",
transformOrigin: "",
opacity: "%",
scale: "×",
@@ -80,6 +82,8 @@ export const PROP_TOOLTIPS: Record<string, string> = {
rotationZ: "Rotate around the screen-facing Z axis",
perspective:
"3D depth context for child elements; set it on a parent when rotating children in 3D",
+ transformPerspective:
+ "3D depth for THIS element's own X/Y rotation — lower = stronger perspective (try 600–1000)",
transformOrigin: "Pivot point for transforms, for example center center or 50% 50%",
width: "Element width",
height: "Element height",
@@ -150,6 +154,7 @@ export const PROP_CONSTRAINTS: Record<string, { min?: number; max?: number; step
rotationY: { step: 1 },
rotationZ: { step: 1 },
perspective: { min: 0, step: 1 },
+ transformPerspective: { min: 0, step: 1 },
skewX: { min: -90, max: 90, step: 1 },
skewY: { min: -90, max: 90, step: 1 },
width: { min: 0, step: 1 },
diff --git a/packages/studio/src/components/editor/marqueeCommit.ts b/packages/studio/src/components/editor/marqueeCommit.ts
index 6502d48c21..66202faee7 100644
--- a/packages/studio/src/components/editor/marqueeCommit.ts
+++ b/packages/studio/src/components/editor/marqueeCommit.ts
@@ -3,7 +3,8 @@ import type { DomEditSelection } from "./domEditing";
import { collectDomEditLayerItems, resolveDomEditSelection } from "./domEditingLayers";
import { isElementComputedVisible } from "./domEditingElement";
import { coversComposition } from "../../utils/studioPreviewHelpers";
-import { elementObbCorners, marqueeIntersectsObb } from "../../utils/marqueeGeometry";
+import { rectsOverlap, type Rect } from "../../utils/marqueeGeometry";
+import { toOverlayRect } from "./domEditOverlayGeometry";
interface MarqueeState {
startX: number;
@@ -16,13 +17,26 @@ interface MarqueeState {
const MARQUEE_THRESHOLD_PX = 4;
+interface MarqueeHit {
+ element: HTMLElement;
+ rect: Rect;
+}
+
+/**
+ * Synchronous core of the marquee: the elements whose overlay-space rect
+ * intersects the marquee rect. Uses the SAME `toOverlayRect` basis as the
+ * single-selection / group-selection boxes, so what the marquee highlights
+ * and selects is exactly the box the user sees when they click an element.
+ * Shared by the live candidate highlight (per pointer-move) and the mouse-up
+ * commit. No async source probe — that only happens once, on commit.
+ */
// fallow-ignore-next-line complexity
-async function runMarqueeIntersection(
- rect: { left: number; top: number; width: number; height: number },
+function collectMarqueeHits(
+ rect: Rect,
iframe: HTMLIFrameElement,
overlayEl: HTMLDivElement,
activeCompositionPath: string,
-): Promise<DomEditSelection[]> {
+): MarqueeHit[] {
const doc = iframe.contentDocument;
if (!doc) return [];
@@ -38,22 +52,42 @@ async function runMarqueeIntersection(
height: declH > 0 ? declH : rootEl.getBoundingClientRect().height || 1,
};
- const hits: DomEditSelection[] = [];
+ const hits: MarqueeHit[] = [];
for (const item of items) {
const el = item.element;
if (!isElementComputedVisible(el)) continue;
if (coversComposition(el.getBoundingClientRect(), viewport)) continue;
- const corners = elementObbCorners(el, overlayEl, iframe);
- if (!corners) continue;
- if (!marqueeIntersectsObb(rect, corners)) continue;
- const sel = await resolveDomEditSelection(el, {
+ const overlayRect = toOverlayRect(overlayEl, iframe, el);
+ if (!overlayRect) continue;
+ const r: Rect = {
+ left: overlayRect.left,
+ top: overlayRect.top,
+ width: overlayRect.width,
+ height: overlayRect.height,
+ };
+ if (!rectsOverlap(rect, r)) continue;
+ hits.push({ element: el, rect: r });
+ }
+
+ return hits;
+}
+
+async function runMarqueeIntersection(
+ rect: Rect,
+ iframe: HTMLIFrameElement,
+ overlayEl: HTMLDivElement,
+ activeCompositionPath: string,
+): Promise<DomEditSelection[]> {
+ const isMasterView = !activeCompositionPath || activeCompositionPath === "index.html";
+ const hits: DomEditSelection[] = [];
+ for (const { element } of collectMarqueeHits(rect, iframe, overlayEl, activeCompositionPath)) {
+ const sel = await resolveDomEditSelection(element, {
activeCompositionPath,
isMasterView,
skipSourceProbe: true,
});
if (sel) hits.push(sel);
}
-
return hits;
}
@@ -75,12 +109,12 @@ interface MarqueeGesturesDeps {
// fallow-ignore-next-line complexity
export function useMarqueeGestures(deps: MarqueeGesturesDeps) {
const marqueeRef = useRef<MarqueeState | null>(null);
- const [marqueeRect, setMarqueeRect] = useState<{
- left: number;
- top: number;
- width: number;
- height: number;
- } | null>(null);
+ const [marqueeRect, setMarqueeRect] = useState<Rect | null>(null);
+ // Live "candidate" highlight: the elements the marquee currently touches,
+ // shown before mouse-up so you can see what you're about to select. The
+ // iframe DOM doesn't mutate during a drag, so a sync intersection per move
+ // is cheap (clean layout → no thrash).
+ const [candidateRects, setCandidateRects] = useState<Rect[]>([]);
const commitMarquee = useCallback(
async (
@@ -111,17 +145,24 @@ export function useMarqueeGestures(deps: MarqueeGesturesDeps) {
if (Math.hypot(dx, dy) < MARQUEE_THRESHOLD_PX) return;
m.pastThreshold = true;
}
- setMarqueeRect({
+ const rect: Rect = {
left: Math.min(m.startX, m.currentX),
top: Math.min(m.startY, m.currentY),
width: Math.abs(m.currentX - m.startX),
height: Math.abs(m.currentY - m.startY),
- });
+ };
+ setMarqueeRect(rect);
+ const iframe = deps.iframeRef.current;
+ const overlay = deps.overlayRef.current;
+ if (iframe && overlay) {
+ const acp = deps.activeCompositionPathRef.current ?? "index.html";
+ setCandidateRects(collectMarqueeHits(rect, iframe, overlay, acp).map((h) => h.rect));
+ }
return;
}
deps.gestures.onPointerMove(event);
},
- [deps.gestures, deps.overlayRef],
+ [deps.gestures, deps.overlayRef, deps.iframeRef, deps.activeCompositionPathRef],
);
const onPointerUp = useCallback(
@@ -148,6 +189,7 @@ export function useMarqueeGestures(deps: MarqueeGesturesDeps) {
deps.onMarqueeSelectRef.current?.([], false);
}
setMarqueeRect(null);
+ setCandidateRects([]);
return;
}
deps.gestures.onPointerUp(event);
@@ -159,10 +201,11 @@ export function useMarqueeGestures(deps: MarqueeGesturesDeps) {
if (marqueeRef.current) {
marqueeRef.current = null;
setMarqueeRect(null);
+ setCandidateRects([]);
return;
}
deps.gestures.clearPointerState(deps.selectionRef);
}, [deps.gestures, deps.selectionRef]);
- return { marqueeRef, marqueeRect, onPointerMove, onPointerUp, onPointerCancel };
+ return { marqueeRef, marqueeRect, candidateRects, onPointerMove, onPointerUp, onPointerCancel };
}
diff --git a/packages/studio/src/components/editor/propertyPanel3dTransform.tsx b/packages/studio/src/components/editor/propertyPanel3dTransform.tsx
index 210ded863b..6710dc9bfb 100644
--- a/packages/studio/src/components/editor/propertyPanel3dTransform.tsx
+++ b/packages/studio/src/components/editor/propertyPanel3dTransform.tsx
@@ -1,8 +1,10 @@
+import { useState } from "react";
import type { DomEditSelection } from "./domEditingTypes";
import { STUDIO_KEYFRAMES_ENABLED } from "./manualEditingAvailability";
import { MetricField } from "./propertyPanelPrimitives";
import { KeyframeNavigation } from "./KeyframeNavigation";
import { formatPxMetricValue, parsePxMetricValue, RESPONSIVE_GRID } from "./propertyPanelHelpers";
+import { Transform3DCube, type CubePose } from "./Transform3DCube";
type KeyframeEntry = Array<{
percentage: number;
@@ -24,9 +26,216 @@ interface PropertyPanel3dTransformProps {
property: string,
value: number,
) => Promise<void>;
+ /** Batched commit — several props into one keyframe (the cube's rotationX/Y/Z). */
+ onCommitAnimatedProperties?: (
+ element: DomEditSelection,
+ props: Record<string, number | string>,
+ ) => Promise<void>;
onSeekToTime?: (time: number) => void;
onRemoveKeyframe?: (animId: string, pct: number) => void;
- onConvertToKeyframes?: (animId: string) => void;
+ onConvertToKeyframes?: (animId: string, duration?: number) => void;
+ /** Live-set props on the preview element during a cube drag (no source write). */
+ onLivePreviewProps?: (element: DomEditSelection, props: Record<string, number>) => void;
+}
+
+type CommitAnimatedProperty = (
+ element: DomEditSelection,
+ property: string,
+ value: number,
+) => Promise<void>;
+
+/** The draggable cube + its commit/recenter/live-preview wiring. */
+function Cube3dControl({
+ element,
+ gsapRuntimeValues,
+ onCommitAnimatedProperty,
+ onCommitAnimatedProperties,
+ onLivePreviewProps,
+ onKeyframe,
+ keyframed,
+}: {
+ element: DomEditSelection;
+ gsapRuntimeValues: Record<string, number>;
+ onCommitAnimatedProperty: CommitAnimatedProperty;
+ onCommitAnimatedProperties?: (
+ element: DomEditSelection,
+ props: Record<string, number | string>,
+ ) => Promise<void>;
+ onLivePreviewProps?: (element: DomEditSelection, props: Record<string, number>) => void;
+ onKeyframe?: () => void;
+ keyframed?: boolean;
+}) {
+ const pose: CubePose = {
+ rotationX: gsapRuntimeValues.rotationX ?? 0,
+ rotationY: gsapRuntimeValues.rotationY ?? 0,
+ rotationZ: gsapRuntimeValues.rotationZ ?? 0,
+ };
+ // Commit only the rotation axes the drag actually changed (each rounded to a
+ // whole degree). Reuses the keyframe-aware animated-property commit, so a drag
+ // at the playhead writes/updates a keyframe just like the numeric fields.
+ const commitPose = (next: CubePose) => {
+ const changedProps: Record<string, number> = {};
+ for (const axis of ["rotationX", "rotationY", "rotationZ"] as const) {
+ const rounded = Math.round(next[axis]);
+ if (rounded !== Math.round(pose[axis])) changedProps[axis] = rounded;
+ }
+ const axes = Object.keys(changedProps);
+ if (axes.length === 0) return;
+ // ONE keyframe for the whole pose change — avoids per-axis commits racing into
+ // adjacent duplicate keyframes. Fall back to per-axis if no batched commit.
+ if (onCommitAnimatedProperties) {
+ void onCommitAnimatedProperties(element, changedProps);
+ } else {
+ for (const [axis, v] of Object.entries(changedProps))
+ onCommitAnimatedProperty(element, axis, v);
+ }
+ };
+ const recenter = () => {
+ // ONE commit for the whole reset — six per-axis commits meant six soft-reloads
+ // (six flashes) for a single click. Batch like commitPose does.
+ const identity = {
+ rotationX: 0,
+ rotationY: 0,
+ rotationZ: 0,
+ z: 0,
+ scale: 1,
+ transformPerspective: 0,
+ };
+ if (onCommitAnimatedProperties) {
+ void onCommitAnimatedProperties(element, identity);
+ } else {
+ for (const [prop, v] of Object.entries(identity))
+ void onCommitAnimatedProperty(element, prop, v);
+ }
+ };
+ // Immediate element feedback while dragging — set the live transform without a
+ // source write; the release commits via onCommitAnimatedProperty.
+ const livePreview = (next: CubePose) =>
+ onLivePreviewProps?.(element, {
+ rotationX: next.rotationX,
+ rotationY: next.rotationY,
+ rotationZ: next.rotationZ,
+ });
+
+ return (
+ <div className="mb-2 px-2">
+ <div className="mx-auto max-w-[184px]">
+ <Transform3DCube
+ pose={pose}
+ perspective={gsapRuntimeValues.transformPerspective ?? 0}
+ onPoseDraft={livePreview}
+ onPoseCommit={commitPose}
+ onPerspectiveDraft={(px) => onLivePreviewProps?.(element, { transformPerspective: px })}
+ onPerspectiveCommit={(px) =>
+ void onCommitAnimatedProperty(element, "transformPerspective", px)
+ }
+ onRecenter={recenter}
+ onKeyframe={onKeyframe}
+ keyframed={keyframed}
+ />
+ <p className="mt-1 text-center text-[9px] leading-snug text-neutral-600">
+ Drag to tilt · Shift-drag to roll
+ </p>
+ </div>
+ </div>
+ );
+}
+
+interface FieldCtx {
+ element: DomEditSelection;
+ gsapRuntimeValues: Record<string, number>;
+ gsapKeyframes: KeyframeEntry;
+ gsapAnimId: string | null;
+ currentPct: number;
+ elStart: number;
+ elDuration: number;
+ resolveAnimIdForProp?: (prop: string) => string | null;
+ onCommitAnimatedProperty?: (
+ element: DomEditSelection,
+ property: string,
+ value: number,
+ ) => Promise<void>;
+ onSeekToTime?: (time: number) => void;
+ onRemoveKeyframe?: (animId: string, pct: number) => void;
+ onConvertToKeyframes?: (animId: string, duration?: number) => void;
+}
+
+const parseDeg = (s: string): number | null => {
+ const n = Number.parseFloat(s.replace("°", ""));
+ return Number.isFinite(n) ? n : null;
+};
+const parseScale = (s: string): number | null => {
+ const n = Number.parseFloat(s);
+ return Number.isFinite(n) ? n : null;
+};
+const parsePxNonNeg = (s: string): number | null => {
+ const v = parsePxMetricValue(s);
+ return v != null && v >= 0 ? v : null;
+};
+
+/**
+ * One 3D-transform field: a number/scrub input plus its keyframe diamond, so
+ * rotation / perspective / Z / scale can each be keyframed just like Layout's
+ * X / Y — the diamond was previously missing on the rotation + perspective rows.
+ */
+function Transform3dField({
+ label,
+ prop,
+ scrub,
+ format,
+ parse,
+ defaultValue,
+ ctx,
+}: {
+ label: string;
+ prop: string;
+ scrub?: boolean;
+ format: (v: number) => string;
+ parse: (s: string) => number | null;
+ defaultValue: number;
+ ctx: FieldCtx;
+}) {
+ const { gsapAnimId, onCommitAnimatedProperty } = ctx;
+ const idFor = (p: string) => ctx.resolveAnimIdForProp?.(p) ?? gsapAnimId;
+ const current = ctx.gsapRuntimeValues[prop] ?? defaultValue;
+ return (
+ <div className="flex items-center gap-1">
+ <div className="flex-1">
+ <MetricField
+ label={label}
+ value={format(current)}
+ scrub={scrub}
+ onCommit={(next) => {
+ const v = parse(next);
+ if (v != null && onCommitAnimatedProperty) {
+ void onCommitAnimatedProperty(ctx.element, prop, v);
+ }
+ }}
+ />
+ </div>
+ {STUDIO_KEYFRAMES_ENABLED && (gsapAnimId || onCommitAnimatedProperty) && (
+ <KeyframeNavigation
+ property={prop}
+ keyframes={ctx.gsapKeyframes}
+ currentPercentage={ctx.currentPct}
+ onSeek={(pct) => ctx.onSeekToTime?.(ctx.elStart + (pct / 100) * ctx.elDuration)}
+ onAddKeyframe={() => {
+ if (onCommitAnimatedProperty) void onCommitAnimatedProperty(ctx.element, prop, current);
+ }}
+ onRemoveKeyframe={(pct) => {
+ const id = idFor(prop);
+ if (id) ctx.onRemoveKeyframe?.(id, pct);
+ }}
+ onConvertToKeyframes={() => {
+ const id = idFor(prop);
+ // Pass the element's clip duration so a converted static 3D `set`
+ // spans the whole clip (keyframes land in range at any playhead).
+ if (id) ctx.onConvertToKeyframes?.(id, ctx.elDuration);
+ }}
+ />
+ )}
+ </div>
+ );
}
export function PropertyPanel3dTransform({
@@ -39,110 +248,120 @@ export function PropertyPanel3dTransform({
elDuration,
element,
onCommitAnimatedProperty,
+ onCommitAnimatedProperties,
onSeekToTime,
onRemoveKeyframe,
onConvertToKeyframes,
+ onLivePreviewProps,
}: PropertyPanel3dTransformProps) {
- const idFor = (prop: string) => resolveAnimIdForProp?.(prop) ?? gsapAnimId;
+ // Expanded by default — the cube gizmo is the headline of this panel, so show
+ // it up front rather than hiding it behind a collapsed header.
+ const [collapsed, setCollapsed] = useState(false);
+ const ctx: FieldCtx = {
+ element,
+ gsapRuntimeValues,
+ gsapKeyframes,
+ gsapAnimId,
+ currentPct,
+ elStart,
+ elDuration,
+ resolveAnimIdForProp,
+ onCommitAnimatedProperty,
+ onSeekToTime,
+ onRemoveKeyframe,
+ onConvertToKeyframes,
+ };
+
return (
<div className="mt-3 border-t border-neutral-800/40 pt-3">
- <div className="mb-2 text-[10px] font-medium uppercase tracking-wider text-neutral-600">
- 3D Transform
- </div>
- <div className={RESPONSIVE_GRID}>
- <div className="flex items-center gap-1">
- <div className="flex-1">
- <MetricField
- label="Z"
- value={formatPxMetricValue(gsapRuntimeValues.z ?? 0)}
- scrub
- onCommit={(next) => {
- const v = parsePxMetricValue(next);
- if (v != null && onCommitAnimatedProperty) {
- void onCommitAnimatedProperty(element, "z", v);
- }
- }}
- />
- </div>
- {STUDIO_KEYFRAMES_ENABLED && (gsapAnimId || onCommitAnimatedProperty) && (
- <KeyframeNavigation
- property="z"
- keyframes={gsapKeyframes}
- currentPercentage={currentPct}
- onSeek={(pct) => onSeekToTime?.(elStart + (pct / 100) * elDuration)}
- onAddKeyframe={() => {
- if (onCommitAnimatedProperty) {
- void onCommitAnimatedProperty(element, "z", gsapRuntimeValues?.z ?? 0);
- }
- }}
- onRemoveKeyframe={(pct) => {
- const id = idFor("z");
- if (id) onRemoveKeyframe?.(id, pct);
- }}
- onConvertToKeyframes={() => {
- const id = idFor("z");
- if (id) onConvertToKeyframes?.(id);
+ <button
+ type="button"
+ onClick={() => setCollapsed((v) => !v)}
+ className="mb-2 flex w-full items-center justify-between text-[10px] font-medium uppercase tracking-wider text-neutral-600 hover:text-neutral-400"
+ >
+ <span>3D Transform</span>
+ <svg width="9" height="9" viewBox="0 0 10 10" fill="currentColor" aria-hidden>
+ {collapsed ? <path d="M3 2l4 3-4 3z" /> : <path d="M2 3l3 4 3-4z" />}
+ </svg>
+ </button>
+ {collapsed ? null : (
+ <>
+ {onCommitAnimatedProperty && (
+ <Cube3dControl
+ element={element}
+ gsapRuntimeValues={gsapRuntimeValues}
+ onCommitAnimatedProperty={onCommitAnimatedProperty}
+ onCommitAnimatedProperties={onCommitAnimatedProperties}
+ onLivePreviewProps={onLivePreviewProps}
+ keyframed={(gsapKeyframes ?? []).some(
+ (kf) =>
+ "rotationX" in kf.properties ||
+ "rotationY" in kf.properties ||
+ "rotationZ" in kf.properties,
+ )}
+ onKeyframe={() => {
+ // Convert the 3D ("other"-group) static set to keyframes so the
+ // cube can animate; spans the element's clip via elDuration.
+ const id = resolveAnimIdForProp?.("rotationX") ?? gsapAnimId;
+ if (id) onConvertToKeyframes?.(id, elDuration);
}}
/>
)}
- </div>
- <div className="flex items-center gap-1">
- <div className="flex-1">
- <MetricField
+ <div className={RESPONSIVE_GRID}>
+ <Transform3dField
+ ctx={ctx}
+ label="Z"
+ prop="z"
+ scrub
+ format={formatPxMetricValue}
+ parse={parsePxMetricValue}
+ defaultValue={0}
+ />
+ <Transform3dField
+ ctx={ctx}
label="Scale"
- value={String(gsapRuntimeValues.scale ?? 1)}
+ prop="scale"
scrub
- onCommit={(next) => {
- const v = Number.parseFloat(next);
- if (Number.isFinite(v) && onCommitAnimatedProperty) {
- void onCommitAnimatedProperty(element, "scale", v);
- }
- }}
+ format={(v) => String(v)}
+ parse={parseScale}
+ defaultValue={1}
/>
- </div>
- {STUDIO_KEYFRAMES_ENABLED && (gsapAnimId || onCommitAnimatedProperty) && (
- <KeyframeNavigation
- property="scale"
- keyframes={gsapKeyframes}
- currentPercentage={currentPct}
- onSeek={(pct) => onSeekToTime?.(elStart + (pct / 100) * elDuration)}
- onAddKeyframe={() => {
- if (onCommitAnimatedProperty) {
- void onCommitAnimatedProperty(element, "scale", gsapRuntimeValues?.scale ?? 1);
- }
- }}
- onRemoveKeyframe={(pct) => {
- const id = idFor("scale");
- if (id) onRemoveKeyframe?.(id, pct);
- }}
- onConvertToKeyframes={() => {
- const id = idFor("scale");
- if (id) onConvertToKeyframes?.(id);
- }}
+ <Transform3dField
+ ctx={ctx}
+ label="RotX"
+ prop="rotationX"
+ format={(v) => `${v}°`}
+ parse={parseDeg}
+ defaultValue={0}
/>
- )}
- </div>
- <MetricField
- label="RotX"
- value={`${gsapRuntimeValues.rotationX ?? 0}°`}
- onCommit={(next) => {
- const v = Number.parseFloat(next.replace("°", ""));
- if (Number.isFinite(v) && onCommitAnimatedProperty) {
- void onCommitAnimatedProperty(element, "rotationX", v);
- }
- }}
- />
- <MetricField
- label="RotY"
- value={`${gsapRuntimeValues.rotationY ?? 0}°`}
- onCommit={(next) => {
- const v = Number.parseFloat(next.replace("°", ""));
- if (Number.isFinite(v) && onCommitAnimatedProperty) {
- void onCommitAnimatedProperty(element, "rotationY", v);
- }
- }}
- />
- </div>
+ <Transform3dField
+ ctx={ctx}
+ label="RotY"
+ prop="rotationY"
+ format={(v) => `${v}°`}
+ parse={parseDeg}
+ defaultValue={0}
+ />
+ <Transform3dField
+ ctx={ctx}
+ label="RotZ"
+ prop="rotationZ"
+ format={(v) => `${v}°`}
+ parse={parseDeg}
+ defaultValue={0}
+ />
+ <Transform3dField
+ ctx={ctx}
+ label="Perspective"
+ prop="transformPerspective"
+ scrub
+ format={formatPxMetricValue}
+ parse={parsePxNonNeg}
+ defaultValue={0}
+ />
+ </div>
+ </>
+ )}
</div>
);
}
diff --git a/packages/studio/src/components/editor/propertyPanelHelpers.ts b/packages/studio/src/components/editor/propertyPanelHelpers.ts
index 870860450e..b0944f2573 100644
--- a/packages/studio/src/components/editor/propertyPanelHelpers.ts
+++ b/packages/studio/src/components/editor/propertyPanelHelpers.ts
@@ -68,12 +68,18 @@ export interface PropertyPanelProps {
onRemoveKeyframe?: (animationId: string, percentage: number) => void;
onUpdateKeyframeEase?: (animationId: string, percentage: number, ease: string) => void;
onSetAllKeyframeEases?: (animationId: string, ease: string) => void;
- onConvertToKeyframes?: (animationId: string) => void;
+ onConvertToKeyframes?: (animationId: string, duration?: number) => void;
onCommitAnimatedProperty?: (
selection: DomEditSelection,
property: string,
value: number | string,
) => Promise<void>;
+ /** Batched variant: commit several props into ONE keyframe (e.g. the 3D cube's
+ * rotationX/Y/Z) so multi-axis edits don't race into adjacent duplicates. */
+ onCommitAnimatedProperties?: (
+ selection: DomEditSelection,
+ props: Record<string, number | string>,
+ ) => Promise<void>;
onSeekToTime?: (time: number) => void;
recordingState?: "idle" | "recording" | "preview";
recordingDuration?: number;
@@ -212,10 +218,8 @@ export const LABEL = "text-[11px] font-medium text-panel-text-3";
export const RESPONSIVE_GRID = "grid grid-cols-[repeat(auto-fit,minmax(118px,1fr))] gap-3";
export const EMPTY_STYLES: Record<string, string> = {};
-// fallow-ignore-next-line unused-exports -- pre-existing; surfaced in this file's diff by an unrelated line shift
-export const EMPTY_FILTER_VALUE = "none";
-// fallow-ignore-next-line unused-exports -- pre-existing; surfaced in this file's diff by an unrelated line shift
-export const BOX_SHADOW_PRESETS = {
+const EMPTY_FILTER_VALUE = "none";
+const BOX_SHADOW_PRESETS = {
none: "none",
soft: "0 12px 36px rgba(0, 0, 0, 0.28)",
lift: "0 18px 54px rgba(0, 0, 0, 0.38)",
@@ -275,13 +279,7 @@ export function parsePxMetricValue(value: string): number | null {
return token.value;
}
-// fallow-ignore-next-line unused-exports -- pre-existing; surfaced in this file's diff by an unrelated line shift
-export function clampPanelNumber(
- value: number,
- min: number,
- max: number,
- fallback: number,
-): number {
+function clampPanelNumber(value: number, min: number, max: number, fallback: number): number {
if (!Number.isFinite(value)) return fallback;
return Math.max(min, Math.min(max, value));
}
@@ -491,6 +489,38 @@ export function extractBackgroundImageUrl(value: string | undefined): string {
// ── GSAP runtime value readers (used by PropertyPanel) ────────────────────
// fallow-ignore-next-line complexity -- pre-existing; surfaced in this file's diff by an unrelated line shift
+// Core transform channels the panel ALWAYS reads live — even before a just-set
+// value (e.g. rotationX) has re-parsed into `gsapAnimations`. Without this the
+// cube + fields drop the prop and flicker to 0 on every commit; gsap.getProperty
+// reflects the in-place instant patch, so it's the true current value.
+const ALWAYS_READ_CHANNELS = [
+ "x",
+ "y",
+ "rotation",
+ "rotationX",
+ "rotationY",
+ "rotationZ",
+ "z",
+ "scale",
+ "transformPerspective",
+ "opacity",
+];
+
+/** Every property key the panel should read for an element: animated props + the
+ * always-read transform channels. */
+function collectPanelPropKeys(gsapAnimations: GsapAnimation[]): Set<string> {
+ const keys = new Set<string>(ALWAYS_READ_CHANNELS);
+ for (const anim of gsapAnimations) {
+ if (anim.keyframes) {
+ for (const kf of anim.keyframes.keyframes) {
+ for (const p of Object.keys(kf.properties)) keys.add(p);
+ }
+ }
+ for (const p of Object.keys(anim.properties)) keys.add(p);
+ }
+ return keys;
+}
+
export function readGsapRuntimeValuesForPanel(
gsapAnimId: string | null,
gsapAnimations: GsapAnimation[],
@@ -511,15 +541,7 @@ export function readGsapRuntimeValuesForPanel(
if (!gsap?.getProperty) return null;
const el = iframe.contentDocument?.querySelector(selector);
if (!el) return null;
- const propKeys = new Set<string>();
- for (const anim of gsapAnimations) {
- if (anim.keyframes) {
- for (const kf of anim.keyframes.keyframes) {
- for (const p of Object.keys(kf.properties)) propKeys.add(p);
- }
- }
- for (const p of Object.keys(anim.properties)) propKeys.add(p);
- }
+ const propKeys = collectPanelPropKeys(gsapAnimations);
const result: Record<string, number> = {};
for (const prop of propKeys) {
const v = Number(gsap.getProperty(el, prop));
diff --git a/packages/studio/src/components/editor/transform3dProjection.test.ts b/packages/studio/src/components/editor/transform3dProjection.test.ts
new file mode 100644
index 0000000000..ef02bcbc84
--- /dev/null
+++ b/packages/studio/src/components/editor/transform3dProjection.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from "vitest";
+import { projectAxes, projectCubeFaces, rotate, wrapDeg } from "./transform3dProjection";
+
+const OPTS = { cx: 50, cy: 50, r: 30, persp: 4 };
+
+describe("projectCubeFaces", () => {
+ it("shows the front face (and only front-facing faces) at identity", () => {
+ const faces = projectCubeFaces(0, 0, 0, OPTS);
+ const ids = faces.map((f) => f.id);
+ expect(ids).toContain("front");
+ // Head-on: side/top/bottom normals are edge-on (n.z ≈ 0) → culled.
+ expect(ids).not.toContain("back");
+ expect(faces.length).toBeGreaterThanOrEqual(1);
+ expect(faces.length).toBeLessThanOrEqual(3);
+ });
+
+ it("reveals the top face when tilted forward on X", () => {
+ const ids = projectCubeFaces(45, 0, 0, OPTS).map((f) => f.id);
+ expect(ids).toContain("front");
+ expect(ids).toContain("top");
+ expect(ids).not.toContain("bottom");
+ });
+
+ it("reveals a side face when rotated on Y (CSS rotateY convention)", () => {
+ const ids = projectCubeFaces(0, 45, 0, OPTS).map((f) => f.id);
+ expect(ids).toContain("front");
+ expect(ids).toContain("left");
+ expect(ids).not.toContain("right");
+ });
+
+ it("never returns more than 3 faces (a cube shows at most 3 at once)", () => {
+ for (const [rx, ry, rz] of [
+ [30, 30, 0],
+ [60, 60, 45],
+ [135, 20, 90],
+ ]) {
+ expect(projectCubeFaces(rx, ry, rz, OPTS).length).toBeLessThanOrEqual(3);
+ }
+ });
+
+ it("rotationZ rolls the silhouette without changing which faces are visible", () => {
+ const a = projectCubeFaces(0, 0, 0, OPTS)
+ .map((f) => f.id)
+ .sort();
+ const b = projectCubeFaces(0, 0, 90, OPTS)
+ .map((f) => f.id)
+ .sort();
+ expect(b).toEqual(a);
+ // …but the projected coordinates differ (it rolled).
+ expect(projectCubeFaces(0, 0, 90, OPTS)[0]?.points).not.toEqual(
+ projectCubeFaces(0, 0, 0, OPTS)[0]?.points,
+ );
+ });
+
+ it("paints far faces before near faces (painter's order)", () => {
+ const faces = projectCubeFaces(35, 35, 0, OPTS);
+ for (let i = 1; i < faces.length; i++) {
+ expect(faces[i]!.depth).toBeGreaterThanOrEqual(faces[i - 1]!.depth);
+ }
+ });
+});
+
+describe("projectAxes", () => {
+ it("returns the three X/Y/Z axes with standard colors", () => {
+ const axes = projectAxes(0, 0, 0, OPTS);
+ expect(axes.map((a) => a.id).sort()).toEqual(["x", "y", "z"]);
+ const z = axes.find((a) => a.id === "z")!;
+ expect(z.color).toMatch(/#/);
+ });
+
+ it("flags the toward-viewer axis as front at identity (Z points at the camera)", () => {
+ const z = projectAxes(0, 0, 0, OPTS).find((a) => a.id === "z")!;
+ expect(z.front).toBe(true);
+ });
+
+ it("rotating 180° on Y flips the Z axis away from the viewer", () => {
+ const z = projectAxes(0, 180, 0, OPTS).find((a) => a.id === "z")!;
+ expect(z.front).toBe(false);
+ });
+});
+
+describe("rotate", () => {
+ it("90° on Y maps +x to -z (right edge swings to the back)", () => {
+ const v = rotate({ x: 1, y: 0, z: 0 }, 0, 90, 0);
+ expect(v.x).toBeCloseTo(0, 5);
+ expect(v.z).toBeCloseTo(-1, 5);
+ });
+});
+
+describe("wrapDeg", () => {
+ it("wraps into (-180, 180]", () => {
+ expect(wrapDeg(0)).toBe(0);
+ expect(wrapDeg(180)).toBe(180);
+ expect(wrapDeg(190)).toBe(-170);
+ expect(wrapDeg(-190)).toBe(170);
+ expect(wrapDeg(360)).toBe(0);
+ expect(wrapDeg(540)).toBe(180);
+ });
+});
diff --git a/packages/studio/src/components/editor/transform3dProjection.ts b/packages/studio/src/components/editor/transform3dProjection.ts
new file mode 100644
index 0000000000..baef455617
--- /dev/null
+++ b/packages/studio/src/components/editor/transform3dProjection.ts
@@ -0,0 +1,172 @@
+/**
+ * Pure cube projection for the 3D-transform widget. Given an element's
+ * rotationX/Y/Z (degrees), project a unit cube to 2D SVG polygons with
+ * back-face culling and painter's-order sorting — no DOM, no React, so it
+ * unit-tests in isolation. Used by Transform3DCube to draw a live preview of
+ * the element's orientation.
+ */
+
+export interface Vec3 {
+ x: number;
+ y: number;
+ z: number;
+}
+
+export interface ProjectedFace {
+ /** Stable face id (front/back/left/right/top/bottom) for keying + theming. */
+ id: string;
+ /** SVG polygon points: "x,y x,y x,y x,y". */
+ points: string;
+ /** 0..1 brightness from how front-facing the rotated normal is (lighting cue). */
+ shade: number;
+ /** Mean depth of the face's corners; larger = nearer the viewer. */
+ depth: number;
+}
+
+const DEG = Math.PI / 180;
+
+/** Rotate a point intrinsically by X, then Y, then Z (degrees). */
+export function rotate(v: Vec3, rx: number, ry: number, rz: number): Vec3 {
+ let { x, y, z } = v;
+ const cx = Math.cos(rx * DEG);
+ const sx = Math.sin(rx * DEG);
+ [y, z] = [y * cx - z * sx, y * sx + z * cx];
+ const cy = Math.cos(ry * DEG);
+ const sy = Math.sin(ry * DEG);
+ [x, z] = [x * cy + z * sy, -x * sy + z * cy];
+ const cz = Math.cos(rz * DEG);
+ const sz = Math.sin(rz * DEG);
+ [x, y] = [x * cz - y * sz, x * sz + y * cz];
+ return { x, y, z };
+}
+
+// Unit-cube corners (±1) — 0-3 back face (z=-1), 4-7 front face (z=1).
+const CORNERS: Vec3[] = [
+ { x: -1, y: -1, z: -1 },
+ { x: 1, y: -1, z: -1 },
+ { x: 1, y: 1, z: -1 },
+ { x: -1, y: 1, z: -1 },
+ { x: -1, y: -1, z: 1 },
+ { x: 1, y: -1, z: 1 },
+ { x: 1, y: 1, z: 1 },
+ { x: -1, y: 1, z: 1 },
+];
+
+const FACES: { id: string; idx: [number, number, number, number]; normal: Vec3 }[] = [
+ { id: "front", idx: [4, 5, 6, 7], normal: { x: 0, y: 0, z: 1 } },
+ { id: "back", idx: [1, 0, 3, 2], normal: { x: 0, y: 0, z: -1 } },
+ { id: "left", idx: [0, 4, 7, 3], normal: { x: -1, y: 0, z: 0 } },
+ { id: "right", idx: [5, 1, 2, 6], normal: { x: 1, y: 0, z: 0 } },
+ // y=+1 corners project to screen-top (SVG y is flipped), so that face is "top".
+ { id: "top", idx: [7, 6, 2, 3], normal: { x: 0, y: 1, z: 0 } },
+ { id: "bottom", idx: [4, 5, 1, 0], normal: { x: 0, y: -1, z: 0 } },
+];
+
+export interface ProjectOpts {
+ /** Center of the SVG viewport. */
+ cx: number;
+ cy: number;
+ /** Half-extent of the cube in SVG units (drawn cube ≈ 2·r before perspective). */
+ r: number;
+ /** Weak-perspective strength in units of `r` (larger = flatter; ~3-6 reads as 3D). */
+ persp?: number;
+}
+
+function round(n: number): number {
+ return Math.round(n * 100) / 100;
+}
+
+// Directional light (upper-front-right), normalized — drives per-face shading so
+// top/front/side read as distinct planes instead of one flat fill.
+const LIGHT = (() => {
+ const v = { x: 0.32, y: 0.56, z: 0.76 };
+ const m = Math.hypot(v.x, v.y, v.z);
+ return { x: v.x / m, y: v.y / m, z: v.z / m };
+})();
+
+/**
+ * Project the cube at the given orientation. Returns only the front-facing
+ * faces (≤3), painter-sorted far→near so the SVG draws nearer faces on top.
+ * Screen Y is flipped (SVG y grows downward). `shade` is a 0..1 lambert term
+ * from {@link LIGHT} for clean directional face tones.
+ */
+export function projectCubeFaces(
+ rx: number,
+ ry: number,
+ rz: number,
+ opts: ProjectOpts,
+): ProjectedFace[] {
+ const { cx, cy, r } = opts;
+ const persp = opts.persp ?? 4;
+ const view = (v: Vec3) => rotate(v, rx, ry, rz);
+ const rotated = CORNERS.map(view);
+ const faces: ProjectedFace[] = [];
+ for (const f of FACES) {
+ const n = view(f.normal);
+ if (n.z <= 1e-6) continue; // back-face cull: normal must point toward viewer
+ const corners = f.idx.map((i) => rotated[i]!);
+ const depth = corners.reduce((s, p) => s + p.z, 0) / 4;
+ const points = corners
+ .map((p) => {
+ // Weak perspective: nearer corners (higher z) project slightly larger.
+ const s = persp / (persp - p.z);
+ return `${round(cx + p.x * r * s)},${round(cy - p.y * r * s)}`;
+ })
+ .join(" ");
+ const lum = Math.max(0, n.x * LIGHT.x + n.y * LIGHT.y + n.z * LIGHT.z);
+ faces.push({ id: f.id, points, shade: 0.3 + lum * 0.7, depth });
+ }
+ faces.sort((a, b) => a.depth - b.depth);
+ return faces;
+}
+
+export interface ProjectedAxis {
+ id: "x" | "y" | "z";
+ /** Axis color (standard X=red, Y=green, Z=blue). */
+ color: string;
+ /** Tip position in SVG coords. */
+ x2: number;
+ y2: number;
+ /** Whether the tip points toward the viewer (drawn in front of the cube). */
+ front: boolean;
+}
+
+const AXES: { id: "x" | "y" | "z"; dir: Vec3; color: string }[] = [
+ { id: "x", dir: { x: 1, y: 0, z: 0 }, color: "#ff6b81" },
+ { id: "y", dir: { x: 0, y: 1, z: 0 }, color: "#5ff08a" },
+ { id: "z", dir: { x: 0, y: 0, z: 1 }, color: "#62b6ff" },
+];
+
+/**
+ * Project the 3 orientation axes (from the cube center) for an X/Y/Z gizmo.
+ * Orthographic — thin lines don't need perspective. `front` lets the caller draw
+ * away-facing axes behind the cube and toward-facing axes on top.
+ */
+export function projectAxes(
+ rx: number,
+ ry: number,
+ rz: number,
+ opts: ProjectOpts,
+): ProjectedAxis[] {
+ const { cx, cy, r } = opts;
+ const len = r * 1.5;
+ const view = (v: Vec3) => rotate(v, rx, ry, rz);
+ return AXES.map((a) => {
+ const p = view(a.dir);
+ return {
+ id: a.id,
+ color: a.color,
+ x2: round(cx + p.x * len),
+ y2: round(cy - p.y * len),
+ front: p.z >= -1e-6,
+ };
+ });
+}
+
+/** Wrap an angle to (-180, 180] so drag accumulation never runs away. */
+export function wrapDeg(deg: number): number {
+ let d = deg % 360;
+ if (d > 180) d -= 360;
+ if (d <= -180) d += 360;
+ return d;
+}
diff --git a/packages/studio/src/components/sidebar/AssetsTab.tsx b/packages/studio/src/components/sidebar/AssetsTab.tsx
index c41d20f282..137ec33ad5 100644
--- a/packages/studio/src/components/sidebar/AssetsTab.tsx
+++ b/packages/studio/src/components/sidebar/AssetsTab.tsx
@@ -3,17 +3,17 @@ import { VideoFrameThumbnail } from "../ui/VideoFrameThumbnail";
import { MEDIA_EXT, IMAGE_EXT, VIDEO_EXT, FONT_EXT } from "../../utils/mediaTypes";
import { TIMELINE_ASSET_MIME } from "../../utils/timelineAssetDrop";
import { copyTextToClipboard } from "../../utils/clipboard";
-import { ContextMenu, DeleteConfirm } from "./AssetContextMenu";
+import { ContextMenu } from "./AssetContextMenu";
import { usePlayerStore } from "../../player/store/playerStore";
import {
type MediaCategory,
getCategory,
- getAudioSubtype,
basename,
ext,
CATEGORY_LABELS,
FILTER_ORDER,
} from "./assetHelpers";
+import { AudioRow } from "./AudioRow";
interface AssetsTabProps {
projectId: string;
@@ -23,215 +23,7 @@ interface AssetsTabProps {
onRename?: (oldPath: string, newPath: string) => void;
}
-function AudioRow({
- projectId,
- asset,
- used,
- meta,
- onCopy,
- isCopied,
- onDelete,
- onRename,
-}: {
- projectId: string;
- asset: string;
- used: boolean;
- meta?: { description?: string; duration?: number };
- onCopy: (path: string) => void;
- isCopied: boolean;
- onDelete?: (path: string) => void;
- onRename?: (oldPath: string, newPath: string) => void;
-}) {
- const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
- const [confirmDelete, setConfirmDelete] = useState(false);
- const [playing, setPlaying] = useState(false);
- const [bars, setBars] = useState<number[]>([]);
- const audioRef = useRef<HTMLAudioElement | null>(null);
- const actxRef = useRef<AudioContext | null>(null);
- const analyserRef = useRef<AnalyserNode | null>(null);
- const sourceRef = useRef<MediaElementAudioSourceNode | null>(null);
- const animRef = useRef<number>(0);
- const name = basename(asset);
- const subtype = getAudioSubtype(asset);
- const serveUrl = `/api/projects/${projectId}/preview/${asset}`;
-
- useEffect(() => {
- return () => {
- cancelAnimationFrame(animRef.current);
- audioRef.current?.pause();
- actxRef.current?.close();
- };
- }, []);
-
- useEffect(() => {
- if (playing) {
- const barCount = 24;
- const loop = () => {
- const analyser = analyserRef.current;
- if (!analyser) {
- animRef.current = requestAnimationFrame(loop);
- return;
- }
- const data = new Uint8Array(analyser.frequencyBinCount);
- analyser.getByteFrequencyData(data);
- const step = Math.floor(data.length / barCount);
- const next: number[] = [];
- for (let i = 0; i < barCount; i++) {
- let sum = 0;
- for (let j = 0; j < step; j++) sum += data[i * step + j];
- next.push(sum / step / 255);
- }
- setBars(next);
- if (audioRef.current && !audioRef.current.paused)
- animRef.current = requestAnimationFrame(loop);
- };
- animRef.current = requestAnimationFrame(loop);
- } else {
- setBars([]);
- }
- return () => cancelAnimationFrame(animRef.current);
- }, [playing]);
-
- const togglePlay = useCallback(async () => {
- if (playing) {
- audioRef.current?.pause();
- setPlaying(false);
- cancelAnimationFrame(animRef.current);
- return;
- }
-
- if (!actxRef.current) {
- actxRef.current = new AudioContext();
- analyserRef.current = actxRef.current.createAnalyser();
- analyserRef.current.fftSize = 256;
- analyserRef.current.smoothingTimeConstant = 0.7;
- }
-
- if (!audioRef.current) {
- const el = new Audio();
- el.onended = () => {
- setPlaying(false);
- cancelAnimationFrame(animRef.current);
- };
- audioRef.current = el;
- sourceRef.current = actxRef.current.createMediaElementSource(el);
- sourceRef.current.connect(analyserRef.current!);
- analyserRef.current!.connect(actxRef.current.destination);
- el.src = serveUrl;
- }
-
- if (actxRef.current.state === "suspended") await actxRef.current.resume();
- audioRef.current.currentTime = 0;
- await audioRef.current.play();
- setPlaying(true);
- }, [serveUrl, playing]);
-
- return (
- <>
- <div
- draggable
- onClick={() => onCopy(asset)}
- onDragStart={(e) => {
- e.dataTransfer.effectAllowed = "copy";
- e.dataTransfer.setData(TIMELINE_ASSET_MIME, JSON.stringify({ path: asset }));
- e.dataTransfer.setData("text/plain", asset);
- }}
- onContextMenu={(e) => {
- e.preventDefault();
- setContextMenu({ x: e.clientX, y: e.clientY });
- }}
- className={`group w-full text-left px-4 py-1.5 flex items-center gap-2.5 transition-all cursor-pointer ${
- playing
- ? "bg-panel-accent/[0.06]"
- : isCopied
- ? "bg-panel-accent/10"
- : "hover:bg-panel-surface-hover"
- }`}
- >
- <button
- className={`w-7 h-7 rounded-md flex-shrink-0 flex items-center justify-center transition-all ${
- playing
- ? "bg-panel-accent/15 text-panel-accent"
- : "text-panel-text-5 group-hover:text-panel-text-3"
- }`}
- onClick={(e) => {
- e.stopPropagation();
- togglePlay();
- }}
- >
- {playing ? (
- <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
- <rect x="6" y="4" width="4" height="16" rx="1" />
- <rect x="14" y="4" width="4" height="16" rx="1" />
- </svg>
- ) : (
- <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
- <polygon points="6,4 20,12 6,20" />
- </svg>
- )}
- </button>
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-1.5">
- <span
- className={`text-[12px] font-medium truncate ${used ? "text-panel-text-1" : "text-panel-text-3"}`}
- >
- {name}
- </span>
- {!playing && (
- <span className="text-[11px] text-panel-text-5 flex-shrink-0">
- {meta?.duration ? `${meta.duration}s · ` : ""}
- {subtype}
- </span>
- )}
- {used && (
- <span className="text-[9px] font-medium text-panel-accent bg-panel-accent/10 px-1.5 py-px rounded flex-shrink-0">
- in use
- </span>
- )}
- </div>
- {bars.length > 0 && (
- <div className="flex items-end gap-[2px] h-[14px] mt-0.5">
- {bars.map((v, i) => (
- <div
- key={i}
- className="flex-1 rounded-[1px]"
- style={{
- height: `${Math.max(10, v * 100)}%`,
- background: `linear-gradient(to top, rgba(60, 230, 172, ${0.3 + v * 0.5}), rgba(60, 230, 172, ${0.5 + v * 0.5}))`,
- transition: "height 80ms ease-out",
- }}
- />
- ))}
- </div>
- )}
- </div>
- </div>
-
- {contextMenu && (
- <ContextMenu
- x={contextMenu.x}
- y={contextMenu.y}
- asset={asset}
- onClose={() => setContextMenu(null)}
- onCopy={onCopy}
- onDelete={onDelete}
- onRename={onRename}
- />
- )}
- {confirmDelete && (
- <DeleteConfirm
- name={name}
- onConfirm={() => {
- onDelete?.(asset);
- setConfirmDelete(false);
- }}
- onCancel={() => setConfirmDelete(false)}
- />
- )}
- </>
- );
-}
-
+// fallow-ignore-next-line complexity
function ImageCard({
projectId,
asset,
@@ -396,10 +188,25 @@ export const AssetsTab = memo(function AssetsTab({
Map<string, { description?: string; duration?: number; width?: number; height?: number }>
>(new Map());
+ // Projects whose media manifest 404'd — most don't have one. Cache the miss so
+ // we don't re-fetch (and spam the console) on every re-render; the effect was
+ // also keyed on the `assets` array reference, which changes each render, so it
+ // re-fired constantly. Key on a stable join + skip known-missing manifests.
+ const manifest404Ref = useRef<Set<string>>(new Set());
+ const assetsKey = assets.join("|");
useEffect(() => {
+ if (manifest404Ref.current.has(projectId)) return;
+ let cancelled = false;
fetch(`/api/projects/${projectId}/preview/.media/manifest.jsonl`)
- .then((r) => (r.ok ? r.text() : ""))
+ .then((r) => {
+ if (!r.ok) {
+ manifest404Ref.current.add(projectId);
+ return "";
+ }
+ return r.text();
+ })
.then((text) => {
+ if (cancelled || !text) return;
const m = new Map<
string,
{ description?: string; duration?: number; width?: number; height?: number }
@@ -416,7 +223,10 @@ export const AssetsTab = memo(function AssetsTab({
setManifest(m);
})
.catch(() => {});
- }, [projectId, assets]);
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId, assetsKey]);
const handleDrop = useCallback(
(e: React.DragEvent) => {
diff --git a/packages/studio/src/components/sidebar/AudioRow.tsx b/packages/studio/src/components/sidebar/AudioRow.tsx
new file mode 100644
index 0000000000..4c9b442d31
--- /dev/null
+++ b/packages/studio/src/components/sidebar/AudioRow.tsx
@@ -0,0 +1,202 @@
+import { useState, useRef, useEffect, useCallback } from "react";
+import { ContextMenu } from "./AssetContextMenu";
+import { basename, getAudioSubtype } from "./assetHelpers";
+import { TIMELINE_ASSET_MIME } from "../../utils/timelineAssetDrop";
+
+export function AudioRow({
+ projectId,
+ asset,
+ used,
+ meta,
+ onCopy,
+ isCopied,
+ onDelete,
+ onRename,
+}: {
+ projectId: string;
+ asset: string;
+ used: boolean;
+ meta?: { description?: string; duration?: number };
+ onCopy: (path: string) => void;
+ isCopied: boolean;
+ onDelete?: (path: string) => void;
+ onRename?: (oldPath: string, newPath: string) => void;
+}) {
+ const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
+ const [playing, setPlaying] = useState(false);
+ const [bars, setBars] = useState<number[]>([]);
+ const audioRef = useRef<HTMLAudioElement | null>(null);
+ const actxRef = useRef<AudioContext | null>(null);
+ const analyserRef = useRef<AnalyserNode | null>(null);
+ const sourceRef = useRef<MediaElementAudioSourceNode | null>(null);
+ const animRef = useRef<number>(0);
+ const name = basename(asset);
+ const subtype = getAudioSubtype(asset);
+ const serveUrl = `/api/projects/${projectId}/preview/${asset}`;
+
+ useEffect(() => {
+ return () => {
+ cancelAnimationFrame(animRef.current);
+ audioRef.current?.pause();
+ actxRef.current?.close();
+ };
+ }, []);
+
+ useEffect(() => {
+ if (playing) {
+ const barCount = 24;
+ const loop = () => {
+ const analyser = analyserRef.current;
+ if (!analyser) {
+ animRef.current = requestAnimationFrame(loop);
+ return;
+ }
+ const data = new Uint8Array(analyser.frequencyBinCount);
+ analyser.getByteFrequencyData(data);
+ const step = Math.floor(data.length / barCount);
+ const next: number[] = [];
+ for (let i = 0; i < barCount; i++) {
+ let sum = 0;
+ for (let j = 0; j < step; j++) sum += data[i * step + j];
+ next.push(sum / step / 255);
+ }
+ setBars(next);
+ if (audioRef.current && !audioRef.current.paused)
+ animRef.current = requestAnimationFrame(loop);
+ };
+ animRef.current = requestAnimationFrame(loop);
+ } else {
+ setBars([]);
+ }
+ return () => cancelAnimationFrame(animRef.current);
+ }, [playing]);
+
+ const togglePlay = useCallback(async () => {
+ if (playing) {
+ audioRef.current?.pause();
+ setPlaying(false);
+ cancelAnimationFrame(animRef.current);
+ return;
+ }
+
+ if (!actxRef.current) {
+ actxRef.current = new AudioContext();
+ analyserRef.current = actxRef.current.createAnalyser();
+ analyserRef.current.fftSize = 256;
+ analyserRef.current.smoothingTimeConstant = 0.7;
+ }
+
+ if (!audioRef.current) {
+ const el = new Audio();
+ el.onended = () => {
+ setPlaying(false);
+ cancelAnimationFrame(animRef.current);
+ };
+ audioRef.current = el;
+ sourceRef.current = actxRef.current.createMediaElementSource(el);
+ sourceRef.current.connect(analyserRef.current!);
+ analyserRef.current!.connect(actxRef.current.destination);
+ el.src = serveUrl;
+ }
+
+ if (actxRef.current.state === "suspended") await actxRef.current.resume();
+ audioRef.current.currentTime = 0;
+ await audioRef.current.play();
+ setPlaying(true);
+ }, [serveUrl, playing]);
+
+ return (
+ <>
+ <div
+ draggable
+ onClick={() => onCopy(asset)}
+ onDragStart={(e) => {
+ e.dataTransfer.effectAllowed = "copy";
+ e.dataTransfer.setData(TIMELINE_ASSET_MIME, JSON.stringify({ path: asset }));
+ e.dataTransfer.setData("text/plain", asset);
+ }}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ setContextMenu({ x: e.clientX, y: e.clientY });
+ }}
+ className={`group w-full text-left px-4 py-1.5 flex items-center gap-2.5 transition-all cursor-pointer ${
+ playing
+ ? "bg-panel-accent/[0.06]"
+ : isCopied
+ ? "bg-panel-accent/10"
+ : "hover:bg-panel-surface-hover"
+ }`}
+ >
+ <button
+ className={`w-7 h-7 rounded-md flex-shrink-0 flex items-center justify-center transition-all ${
+ playing
+ ? "bg-panel-accent/15 text-panel-accent"
+ : "text-panel-text-5 group-hover:text-panel-text-3"
+ }`}
+ onClick={(e) => {
+ e.stopPropagation();
+ togglePlay();
+ }}
+ >
+ {playing ? (
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
+ <rect x="6" y="4" width="4" height="16" rx="1" />
+ <rect x="14" y="4" width="4" height="16" rx="1" />
+ </svg>
+ ) : (
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
+ <polygon points="6,4 20,12 6,20" />
+ </svg>
+ )}
+ </button>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <span
+ className={`text-[12px] font-medium truncate ${used ? "text-panel-text-1" : "text-panel-text-3"}`}
+ >
+ {name}
+ </span>
+ {!playing && (
+ <span className="text-[11px] text-panel-text-5 flex-shrink-0">
+ {meta?.duration ? `${meta.duration}s · ` : ""}
+ {subtype}
+ </span>
+ )}
+ {used && (
+ <span className="text-[9px] font-medium text-panel-accent bg-panel-accent/10 px-1.5 py-px rounded flex-shrink-0">
+ in use
+ </span>
+ )}
+ </div>
+ {bars.length > 0 && (
+ <div className="flex items-end gap-[2px] h-[14px] mt-0.5">
+ {bars.map((v, i) => (
+ <div
+ key={i}
+ className="flex-1 rounded-[1px]"
+ style={{
+ height: `${Math.max(10, v * 100)}%`,
+ background: `linear-gradient(to top, rgba(60, 230, 172, ${0.3 + v * 0.5}), rgba(60, 230, 172, ${0.5 + v * 0.5}))`,
+ transition: "height 80ms ease-out",
+ }}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {contextMenu && (
+ <ContextMenu
+ x={contextMenu.x}
+ y={contextMenu.y}
+ asset={asset}
+ onClose={() => setContextMenu(null)}
+ onCopy={onCopy}
+ onDelete={onDelete}
+ onRename={onRename}
+ />
+ )}
+ </>
+ );
+}
diff --git a/packages/studio/src/contexts/DomEditContext.tsx b/packages/studio/src/contexts/DomEditContext.tsx
index 7644f30699..0222a9bffb 100644
--- a/packages/studio/src/contexts/DomEditContext.tsx
+++ b/packages/studio/src/contexts/DomEditContext.tsx
@@ -55,6 +55,7 @@ export interface DomEditActionsValue extends Pick<
| "handleGsapRemoveAllKeyframes"
| "handleResetSelectedElementKeyframes"
| "commitAnimatedProperty"
+ | "commitAnimatedProperties"
| "handleSetArcPath"
| "handleUpdateArcSegment"
| "handleUnroll"
@@ -164,6 +165,7 @@ export function DomEditProvider({
handleGsapRemoveAllKeyframes,
handleResetSelectedElementKeyframes,
commitAnimatedProperty,
+ commitAnimatedProperties,
handleSetArcPath,
handleUpdateArcSegment,
handleUnroll,
@@ -238,6 +240,7 @@ export function DomEditProvider({
handleGsapRemoveAllKeyframes,
handleResetSelectedElementKeyframes,
commitAnimatedProperty,
+ commitAnimatedProperties,
handleSetArcPath,
handleUpdateArcSegment,
handleUnroll,
@@ -298,6 +301,7 @@ export function DomEditProvider({
handleGsapRemoveAllKeyframes,
handleResetSelectedElementKeyframes,
commitAnimatedProperty,
+ commitAnimatedProperties,
handleSetArcPath,
handleUpdateArcSegment,
handleUnroll,
diff --git a/packages/studio/src/hooks/gsapDragCommit.test.ts b/packages/studio/src/hooks/gsapDragCommit.test.ts
index 06461d2879..e25d510714 100644
--- a/packages/studio/src/hooks/gsapDragCommit.test.ts
+++ b/packages/studio/src/hooks/gsapDragCommit.test.ts
@@ -332,7 +332,7 @@ describe("commitStaticGsapPosition — instantPatch (value-only set)", () => {
expect(yPatch.change.props[xMutation.property]).toBe(xMutation.value);
});
- it("does NOT attach instantPatch when ADDING a new set (structural — new tween)", async () => {
+ it("ADDS a global gsap.set with a global-set instantPatch (off-timeline, no flash)", async () => {
const { commits, callbacks } = optionRecordingCallbacks();
await commitStaticGsapPosition(
@@ -340,13 +340,15 @@ describe("commitStaticGsapPosition — instantPatch (value-only set)", () => {
{ x: -50, y: 30 },
{ x: 0, y: 0 },
"#puck-a",
- null, // no existing set → `add` a new tween
+ null, // no existing set → `add` a new base gsap.set
callbacks,
);
expect(commits).toHaveLength(1);
expect(commits[0].mutation.type).toBe("add");
- expect(commits[0].options.instantPatch).toBeUndefined();
+ expect((commits[0].mutation as { global?: boolean }).global).toBe(true);
+ const patch = commits[0].options.instantPatch as { change: { kind: string } } | undefined;
+ expect(patch?.change.kind).toBe("global-set");
});
});
@@ -372,14 +374,16 @@ describe("commitStaticGsapRotation — instantPatch (value-only set)", () => {
expect(patch.change.props[m.property]).toBe(m.value);
});
- it("does NOT attach instantPatch when ADDING a new rotation set (structural)", async () => {
+ it("ADDS a global gsap.set with a global-set instantPatch (off-timeline, no flash)", async () => {
const { commits, callbacks } = optionRecordingCallbacks();
await commitStaticGsapRotation(selection(), 42, "#puck-a", null, callbacks);
expect(commits).toHaveLength(1);
expect(commits[0].mutation.type).toBe("add");
- expect(commits[0].options.instantPatch).toBeUndefined();
+ expect((commits[0].mutation as { global?: boolean }).global).toBe(true);
+ const patch = commits[0].options.instantPatch as { change: { kind: string } } | undefined;
+ expect(patch?.change.kind).toBe("global-set");
});
});
diff --git a/packages/studio/src/hooks/gsapDragCommit.ts b/packages/studio/src/hooks/gsapDragCommit.ts
index c2d452daa8..43260ae5e3 100644
--- a/packages/studio/src/hooks/gsapDragCommit.ts
+++ b/packages/studio/src/hooks/gsapDragCommit.ts
@@ -120,18 +120,22 @@ interface UpdatePropertyMutation {
function setPatchFromUpdateProperties(
selector: string,
mutations: UpdatePropertyMutation[],
+ global = false,
): { selector: string; change: RuntimeTweenChange } {
const props: SetPatchProps = {};
for (const m of mutations) props[m.property as keyof SetPatchProps] = m.value;
- return { selector, change: { kind: "set", props } };
+ // An off-timeline `gsap.set` has no runtime tween to patch — apply it to the
+ // element directly. An on-timeline `tl.set` mutates its tween (so a re-seek keeps it).
+ return { selector, change: { kind: global ? "global-set" : "set", props } };
}
/** Single-mutation convenience over {@link setPatchFromUpdateProperties}. */
function setPatchFromUpdateProperty(
selector: string,
mutation: UpdatePropertyMutation,
+ global = false,
): { selector: string; change: RuntimeTweenChange } {
- return setPatchFromUpdateProperties(selector, [mutation]);
+ return setPatchFromUpdateProperties(selector, [mutation], global);
}
/**
@@ -194,22 +198,25 @@ export async function commitStaticGsapPosition(
// preview still reflects what DID persist. The x commit carries skipReload
// (no reload), so its instantPatch gives instant feedback without a reload;
// the y commit triggers the soft reload (skipped when the patch applies).
+ const global = !!existingSet.global;
await callbacks.commitMutation(selection, xMutation, {
label: "Move layer",
skipReload: true,
coalesceKey,
- instantPatch: setPatchFromUpdateProperty(selector, xMutation),
+ instantPatch: setPatchFromUpdateProperty(selector, xMutation, global),
});
await callbacks.commitMutation(selection, yMutation, {
label: "Move layer",
softReload: true,
coalesceKey,
// Final commit of the coalesced x/y pair: carry both channels so the
- // runtime `tl.set` lands the complete {x,y} pose in place.
- instantPatch: setPatchFromUpdateProperties(selector, [xMutation, yMutation]),
+ // runtime set lands the complete {x,y} pose in place.
+ instantPatch: setPatchFromUpdateProperties(selector, [xMutation, yMutation], global),
});
return;
}
+ // New static hold → a base `gsap.set` (off-timeline, no 0% keyframe marker), with
+ // an instant patch so the first nudge shows immediately (no soft-reload flash).
await callbacks.commitMutation(
selection,
{
@@ -218,8 +225,13 @@ export async function commitStaticGsapPosition(
method: "set",
position: 0,
properties: { x: newX, y: newY },
+ global: true,
+ },
+ {
+ label: "Move layer",
+ softReload: true,
+ instantPatch: { selector, change: { kind: "global-set", props: { x: newX, y: newY } } },
},
- { label: "Move layer", softReload: true },
);
}
@@ -264,11 +276,13 @@ export async function commitStaticGsapRotation(
await callbacks.commitMutation(selection, rotationMutation, {
label: "Rotate layer",
softReload: true,
- // Value-only rotation set: patch the runtime `tl.set` rotation in place.
- instantPatch: setPatchFromUpdateProperty(selector, rotationMutation),
+ // Value-only rotation set — patch the runtime in place (off-timeline gsap.set
+ // applies to the element directly; on-timeline tl.set patches its tween).
+ instantPatch: setPatchFromUpdateProperty(selector, rotationMutation, !!existingSet.global),
});
return;
}
+ // New static hold → off-timeline `gsap.set` (no 0% keyframe marker) + instant patch.
await callbacks.commitMutation(
selection,
{
@@ -277,8 +291,13 @@ export async function commitStaticGsapRotation(
method: "set",
position: 0,
properties: { rotation: newRotation },
+ global: true,
+ },
+ {
+ label: "Rotate layer",
+ softReload: true,
+ instantPatch: { selector, change: { kind: "global-set", props: { rotation: newRotation } } },
},
- { label: "Rotate layer", softReload: true },
);
}
diff --git a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts b/packages/studio/src/hooks/gsapRuntimeKeyframes.ts
index b7e72b2857..01ef6c2c4d 100644
--- a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts
+++ b/packages/studio/src/hooks/gsapRuntimeKeyframes.ts
@@ -12,12 +12,23 @@ import { buildArcPath, type ArcPathConfig } from "@hyperframes/core/gsap-parser-
import { parsePercentageKeyframes, toAbsoluteTime } from "./gsapShared";
import { roundTo3 } from "../utils/rounding";
+/**
+ * A GSAP tween's `vars` object — intentionally open: it mixes channel values
+ * (numbers), easing (strings), flags (booleans), nested keyframes (objects) and
+ * callbacks. Named so call sites read as "GSAP config", not an untyped escape hatch.
+ */
+export type GsapVars = Record<string, unknown>;
+
export interface RuntimeTween {
targets?: () => Element[];
- vars?: Record<string, unknown>;
+ vars?: GsapVars;
duration?: () => number;
startTime?: () => number;
invalidate?: () => RuntimeTween;
+ /** Remove this tween from its parent timeline (GSAP `kill()`). */
+ kill?: () => void;
+ /** The timeline this tween lives in — used to re-insert a rebuilt tween. */
+ parent?: RuntimeTimeline;
}
export interface RuntimeTimeline {
@@ -25,6 +36,8 @@ export interface RuntimeTimeline {
duration?: () => number;
time?: () => number;
invalidate?: () => RuntimeTimeline;
+ /** Add a tween at an absolute position — used to rebuild a keyframe tween in place. */
+ to?: (targets: Element[], vars: GsapVars, position?: number) => RuntimeTween;
}
type Pct = { percentage: number; properties: Record<string, number | string> };
@@ -184,6 +197,26 @@ function varsCarryChannel(vars: Record<string, unknown> | undefined, channels: s
return false;
}
+/**
+ * Like `varsCarryChannel` but for a keyframe tween: the channels live inside the
+ * keyframe steps (`vars.keyframes`), not as own props of `vars`. Handles the object
+ * form (`{ "0%": {...} }`) and the array form (`[{...}, ...]`).
+ */
+function keyframeVarsCarryChannel(
+ vars: Record<string, unknown> | undefined,
+ channels: string[],
+): boolean {
+ const kf = vars?.keyframes;
+ if (!kf || typeof kf !== "object") return false;
+ const steps = Array.isArray(kf) ? kf : Object.values(kf);
+ return steps.some(
+ (step) =>
+ step != null &&
+ typeof step === "object" &&
+ channels.some((ch) => Object.prototype.hasOwnProperty.call(step, ch)),
+ );
+}
+
/**
* Resolve the live tween targeting `selector` using the SAME all-timelines scan
* `readRuntimeKeyframes` uses, so read and write agree on "which tween". With
@@ -197,6 +230,7 @@ function varsCarryChannel(vars: Record<string, unknown> | undefined, channels: s
* on a rotation-only set). With no channel-matching set, it falls back to the
* first matching set (back-compat). `channels` is ignored for `kind: "keyframe"`.
*/
+// fallow-ignore-next-line complexity
export function resolveRuntimeTween(
iframe: HTMLIFrameElement | null,
selector: string,
@@ -219,7 +253,12 @@ export function resolveRuntimeTween(
? [compositionId]
: Object.keys(timelines).filter((k) => typeof timelines[k]?.getChildren === "function");
- const wantChannels = kind === "set" && channels && channels.length > 0 ? channels : null;
+ // Channels disambiguate co-located tweens for BOTH kinds: a `set` carries them as
+ // own vars props, a keyframe tween carries them inside its keyframe steps. An
+ // element can have a rotation keyframe tween AND a position keyframe tween; a
+ // rotation edit must land on the former. The reader passes no channels, so its
+ // playhead-containment path below is unchanged.
+ const wantChannels = channels && channels.length > 0 ? channels : null;
let first: ResolvedRuntimeTween | null = null;
let channelMatch: ResolvedRuntimeTween | null = null;
@@ -233,11 +272,15 @@ export function resolveRuntimeTween(
const isSet = !(dur > 0);
if (kind === "set" ? !isSet : isSet) continue;
if (wantChannels) {
- if (varsCarryChannel(tween.vars, wantChannels)) {
+ const carries =
+ kind === "set"
+ ? varsCarryChannel(tween.vars, wantChannels)
+ : keyframeVarsCarryChannel(tween.vars, wantChannels);
+ if (carries) {
if (channelMatch === null) channelMatch = { tween, timeline };
} else if (first === null) {
- // A set carrying only disjoint channels: remember as last-resort
- // fallback, but never prefer it over a channel-matching set.
+ // A tween carrying only disjoint channels: remember as last-resort
+ // fallback, but never prefer it over a channel-matching one.
first = { tween, timeline };
}
continue;
@@ -267,6 +310,7 @@ function readCarriesChannel(read: ReadTween, channels: string[]): boolean {
* whenever the playhead sits in that tween's range but outside the position
* tween's). Omitted → any keyframed tween qualifies (back-compat).
*/
+// fallow-ignore-next-line complexity
export function readRuntimeKeyframes(
iframe: HTMLIFrameElement | null,
selector: string,
@@ -334,6 +378,7 @@ export function readRuntimeKeyframes(
* only a hold may remain, and resurrecting the deleted tween from the stale parse
* must be avoided.
*/
+// fallow-ignore-next-line complexity
export function hasNonHoldTweenForElement(
iframe: HTMLIFrameElement | null,
selector: string,
diff --git a/packages/studio/src/hooks/gsapRuntimePatch.ts b/packages/studio/src/hooks/gsapRuntimePatch.ts
index d8d9d5cbe4..a95f248f9b 100644
--- a/packages/studio/src/hooks/gsapRuntimePatch.ts
+++ b/packages/studio/src/hooks/gsapRuntimePatch.ts
@@ -13,13 +13,22 @@
* "Which tween" is resolved by the same all-timelines scan `readRuntimeKeyframes`
* uses (`resolveRuntimeTween`), so read and write agree on the target.
*/
-import { resolveRuntimeTween, type RuntimeTween } from "./gsapRuntimeKeyframes";
+import {
+ resolveRuntimeTween,
+ type RuntimeTween,
+ type RuntimeTimeline,
+} from "./gsapRuntimeKeyframes";
/** Value-only channels a `tl.set(...)` patch may touch. */
export interface SetPatchProps {
x?: number;
y?: number;
rotation?: number;
+ rotationX?: number;
+ rotationY?: number;
+ rotationZ?: number;
+ z?: number;
+ transformPerspective?: number;
scaleX?: number;
scaleY?: number;
scale?: number;
@@ -31,12 +40,28 @@ export type KeyframeStep = Record<string, number>;
export type RuntimeTweenChange =
| { kind: "set"; props: SetPatchProps }
- | { kind: "keyframes"; keyframes: KeyframeStep[] };
+ | { kind: "keyframes"; keyframes: KeyframeStep[] }
+ // Edit ONE step (at `pct`) of an object-form keyframe tween — the form the studio
+ // writes (`keyframes: { "0%": {...} }`). GSAP pre-compiles those into sub-tweens
+ // and won't re-read `vars.keyframes` on `invalidate()`, so this REBUILDS the tween
+ // (kill + recreate at the same position) instead of mutating it. Lets a design-panel
+ // keyframe edit show instantly rather than soft-reloading the iframe (a flash).
+ | { kind: "keyframe-rebuild"; pct: number; props: KeyframeStep }
+ // Apply a base `gsap.set` value to the element directly (`gsap.set(el, props)`).
+ // A base set lives OFF the timeline, so there's no runtime tween to patch — but
+ // the element is static on these channels, so setting them immediately reflects
+ // the edit with no soft reload (no flash) and leaves no keyframe marker.
+ | { kind: "global-set"; props: SetPatchProps };
const SET_CHANNELS: Array<keyof SetPatchProps> = [
"x",
"y",
"rotation",
+ "rotationX",
+ "rotationY",
+ "rotationZ",
+ "z",
+ "transformPerspective",
"scaleX",
"scaleY",
"scale",
@@ -45,8 +70,42 @@ const SET_CHANNELS: Array<keyof SetPatchProps> = [
type IframeWindow = Window & {
__player?: { getTime?: () => number; seek?: (t: number) => void };
+ gsap?: { set?: (target: Element, vars: Record<string, number>) => void };
};
+/**
+ * Apply a base `gsap.set` value to the element in the live runtime. Returns `true`
+ * if applied. Used for off-timeline static holds (position / 3D transform) — there's
+ * no tween to patch, so we set the channels directly. Safe because the element is
+ * static on these channels (the caller only uses this for non-animated values).
+ */
+/** The props as finite numbers, or null if any value is non-finite / none present. */
+function finiteNumericProps(props: SetPatchProps): Record<string, number> | null {
+ const numeric: Record<string, number> = {};
+ for (const [k, v] of Object.entries(props)) {
+ if (typeof v !== "number" || !Number.isFinite(v)) return null;
+ numeric[k] = v;
+ }
+ return Object.keys(numeric).length > 0 ? numeric : null;
+}
+
+function applyGlobalSet(
+ iframe: HTMLIFrameElement,
+ selector: string,
+ props: SetPatchProps,
+): boolean {
+ try {
+ const gsapLib = (iframe.contentWindow as IframeWindow | null)?.gsap;
+ const el = iframe.contentDocument?.querySelector(selector) ?? null;
+ const numeric = finiteNumericProps(props);
+ if (!gsapLib?.set || !el || !numeric) return false;
+ gsapLib.set(el, numeric);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
function playerOf(iframe: HTMLIFrameElement): IframeWindow["__player"] | null {
try {
return (iframe.contentWindow as IframeWindow | null)?.__player ?? null;
@@ -100,10 +159,95 @@ function patchKeyframes(tween: RuntimeTween, keyframes: KeyframeStep[]): boolean
return true;
}
+/** The object-form keyframes map with `props` merged into the step at `pct`. */
+function mergeKeyframeStep(
+ map: Record<string, Record<string, number>>,
+ pct: number,
+ props: KeyframeStep,
+): Record<string, Record<string, number>> {
+ const next: Record<string, Record<string, number>> = {};
+ for (const [k, step] of Object.entries(map)) next[k] = { ...step };
+ // Match the existing percentage key numerically ("50%" ≡ pct 50), else add one.
+ let key: string | null = null;
+ for (const k of Object.keys(next)) {
+ const n = parseFloat(k);
+ if (Number.isFinite(n) && Math.abs(n - pct) < 0.05) {
+ key = k;
+ break;
+ }
+ }
+ if (key === null) key = `${pct}%`;
+ next[key] = { ...(next[key] ?? {}), ...props };
+ return next;
+}
+
+/**
+ * Rebuild an object-form keyframe tween with `props` merged into the step at `pct`,
+ * in place: kill the old tween and recreate it on the SAME parent timeline at the
+ * SAME position, with all other vars (duration, ease, repeat, …) preserved. This
+ * is the only way to reflect an object-form keyframe edit live — GSAP compiles
+ * those keyframes into sub-tweens at creation and ignores later `vars.keyframes`
+ * mutations. Declines (→ caller soft-reloads) for array-form, motionPath arcs,
+ * non-finite/dynamic values, or a tween whose parent/targets can't be resolved.
+ */
+// fallow-ignore-next-line complexity
+function rebuildKeyframeTween(tween: RuntimeTween, pct: number, props: KeyframeStep): boolean {
+ const vars = tween.vars;
+ if (!vars || "motionPath" in vars) return false;
+ const kf = vars.keyframes;
+ if (!kf || typeof kf !== "object" || Array.isArray(kf)) return false;
+ for (const v of Object.values(props)) {
+ if (typeof v !== "number" || !Number.isFinite(v)) return false;
+ }
+ const parent = tween.parent;
+ const targets = tween.targets?.();
+ if (!parent?.to || !targets || targets.length === 0) return false;
+ if (typeof tween.startTime !== "function" || typeof tween.kill !== "function") return false;
+
+ const next = mergeKeyframeStep(kf as Record<string, Record<string, number>>, pct, props);
+ const newVars = { ...vars, keyframes: next };
+ const position = tween.startTime();
+ tween.kill();
+ parent.to(targets, newVars, position);
+ return true;
+}
+
+/** The channels a change writes, for the resolver to disambiguate co-located tweens. */
+function changeChannels(change: RuntimeTweenChange): string[] | undefined {
+ if (change.kind === "set") {
+ return Object.keys(change.props).filter(
+ (k) => change.props[k as keyof SetPatchProps] !== undefined,
+ );
+ }
+ if (change.kind === "keyframe-rebuild") return Object.keys(change.props);
+ return undefined;
+}
+
+/** Re-render the timeline at the current playhead after an in-place edit. */
+function seekToCurrent(iframe: HTMLIFrameElement, timeline: RuntimeTimeline): void {
+ const player = playerOf(iframe);
+ const currentTime =
+ typeof player?.getTime === "function"
+ ? player.getTime()
+ : typeof timeline.time === "function"
+ ? timeline.time()
+ : 0;
+ player?.seek?.(Number.isFinite(currentTime) ? currentTime : 0);
+}
+
+/** Apply `change` to the resolved tween. `true` if applied, `false` to soft-reload.
+ * `global-set` is handled before this (no tween) and never reaches here. */
+function applyChange(tween: RuntimeTween, change: RuntimeTweenChange): boolean {
+ if (change.kind === "set") return patchSet(tween, change.props);
+ if (change.kind === "keyframes") return patchKeyframes(tween, change.keyframes);
+ if (change.kind === "keyframe-rebuild")
+ return rebuildKeyframeTween(tween, change.pct, change.props);
+ return false;
+}
+
/**
- * Update one tween's values in `window.__timelines` in place + re-seek to the
- * current playhead. Returns `true` on a confident patch, `false` otherwise
- * (caller falls back to a soft reload).
+ * Edit one tween in `window.__timelines` in place + re-seek to the current playhead.
+ * Returns `true` on a confident patch, `false` otherwise (caller soft-reloads).
*/
export function patchRuntimeTweenInPlace(
iframe: HTMLIFrameElement | null,
@@ -112,46 +256,29 @@ export function patchRuntimeTweenInPlace(
compositionId?: string,
): boolean {
if (!iframe) return false;
+ // A base `gsap.set` has no timeline tween to resolve — apply the value straight
+ // to the element so the edit shows instantly (no soft reload, no flash).
+ if (change.kind === "global-set") return applyGlobalSet(iframe, selector, change.props);
try {
- // For a `set` patch, hand the resolver the channels actually being written so
- // it picks the set whose vars carry them — an element can have separate
- // {x,y} and {rotation} sets, and a position patch must not corrupt the
- // rotation set (channel-blind resolution would return the first match).
- const channels =
- change.kind === "set"
- ? Object.keys(change.props).filter(
- (k) => change.props[k as keyof SetPatchProps] !== undefined,
- )
- : undefined;
const resolved = resolveRuntimeTween(
iframe,
selector,
change.kind === "set" ? "set" : "keyframe",
compositionId,
- channels,
+ changeChannels(change),
);
if (!resolved) return false;
const { tween, timeline } = resolved;
- const applied =
- change.kind === "set"
- ? patchSet(tween, change.props)
- : patchKeyframes(tween, change.keyframes);
- if (!applied) return false;
-
- // Recompute the tween (and its timeline) from the new vars, then re-render at
- // the current playhead. `invalidate()` makes GSAP re-read vars on the next render.
- tween.invalidate?.();
- timeline.invalidate?.();
-
- const player = playerOf(iframe);
- const currentTime =
- typeof player?.getTime === "function"
- ? player.getTime()
- : typeof timeline.time === "function"
- ? timeline.time()
- : 0;
- player?.seek?.(Number.isFinite(currentTime) ? currentTime : 0);
+ if (!applyChange(tween, change)) return false;
+
+ // A rebuild already recreated the tween; set/keyframes mutate vars in place, so
+ // invalidate to make GSAP re-read them on the next render. Either way, re-seek.
+ if (change.kind !== "keyframe-rebuild") {
+ tween.invalidate?.();
+ timeline.invalidate?.();
+ }
+ seekToCurrent(iframe, timeline);
return true;
} catch {
return false;
diff --git a/packages/studio/src/hooks/useAnimatedPropertyCommit.ts b/packages/studio/src/hooks/useAnimatedPropertyCommit.ts
index e6e50a4349..eb49b1eb94 100644
--- a/packages/studio/src/hooks/useAnimatedPropertyCommit.ts
+++ b/packages/studio/src/hooks/useAnimatedPropertyCommit.ts
@@ -1,10 +1,11 @@
/**
* Unified helper for committing any GSAP property value from the design panel.
*
- * Handles three cases:
- * 1. Animation with keyframes → add-keyframe at current percentage
- * 2. Flat animation (no keyframes) → convert to keyframes, then add-keyframe
- * 3. No animation → create tl.to(), convert to keyframes, then add-keyframe
+ * Routing depends on whether the element is animated (has keyframes on any tween):
+ * - Animated → write the value into a keyframe at the current playhead (convert a
+ * flat tween first if needed). An existing static `set` auto-converts to keyframes.
+ * - Static (no keyframes anywhere) → persist as a `tl.set`, NEVER keyframes — same
+ * as manual drag / resize / rotate. Updates an existing set or creates one.
*/
import { useCallback } from "react";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
@@ -12,6 +13,7 @@ import { classifyPropertyGroup } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { usePlayerStore } from "../player/store/playerStore";
import { readAllAnimatedProperties, readGsapProperty } from "./gsapRuntimeBridge";
+import type { SetPatchProps } from "./gsapRuntimePatch";
import { selectorFromSelection, computeElementPercentage } from "./gsapShared";
interface CommitAnimatedPropertyDeps {
@@ -47,6 +49,7 @@ function pickBestAnimation(
const currentTime = usePlayerStore.getState().currentTime;
const targetGroup = property ? classifyPropertyGroup(property) : undefined;
+ // fallow-ignore-next-line complexity
const scored = animations.map((a) => {
let score = 0;
if (targetGroup && a.propertyGroup === targetGroup) score += 20;
@@ -62,96 +65,271 @@ function pickBestAnimation(
return scored[0]?.anim;
}
+/**
+ * Auto-keyframe a just-updated static `set`: if the element is already animated
+ * (its clip carries keyframes on another tween), convert the set to keyframes so
+ * subsequent edits at other playheads interpolate — matching the drag / resize /
+ * rotate UX. Purely static elements (no other keyframes) are left as a set.
+ */
+async function maybeAutoKeyframeSet(
+ selection: DomEditSelection,
+ setAnim: GsapAnimation,
+ animations: GsapAnimation[],
+ commit: NonNullable<CommitAnimatedPropertyDeps["gsapCommitMutation"]>,
+): Promise<void> {
+ const animatedTween = animations.find((a) => a.keyframes && a.id !== setAnim.id);
+ if (!animatedTween) return;
+ await commit(
+ selection,
+ {
+ type: "convert-to-keyframes",
+ animationId: setAnim.id,
+ duration: animatedTween.duration ?? 1,
+ },
+ { label: "Keyframe 3D transform", softReload: true },
+ );
+}
+
+type Commit = NonNullable<CommitAnimatedPropertyDeps["gsapCommitMutation"]>;
+
+/** Merge ALL props into the static `set` in ONE commit (value-only, instant), then
+ * auto-keyframe. One mutation — a per-property loop would shift the set's
+ * group-derived id mid-way (e.g. reset adding `scale` to a rotation set), 404-ing
+ * the next update. */
+async function commitSetProps(
+ selection: DomEditSelection,
+ setAnim: GsapAnimation,
+ propEntries: [string, number | string][],
+ selector: string | null,
+ animations: GsapAnimation[],
+ commit: Commit,
+): Promise<void> {
+ const properties = Object.fromEntries(propEntries);
+ const numericProps: SetPatchProps = {};
+ for (const [k, v] of propEntries) {
+ if (typeof v === "number") numericProps[k as keyof SetPatchProps] = v;
+ }
+ const instantPatch =
+ selector && Object.keys(numericProps).length > 0
+ ? {
+ selector,
+ change: {
+ kind: (setAnim.global ? "global-set" : "set") as "set" | "global-set",
+ props: numericProps,
+ },
+ }
+ : undefined;
+ await commit(
+ selection,
+ { type: "update-properties", animationId: setAnim.id, properties },
+ { label: "Set 3D transform", softReload: true, ...(instantPatch ? { instantPatch } : {}) },
+ );
+ await maybeAutoKeyframeSet(selection, setAnim, animations, commit);
+}
+
+/**
+ * Static element (no keyframes on ANY of its tweens): persist the 3D props as a
+ * `tl.set` — NEVER keyframes. Mirrors manual drag / resize / rotate, which `tl.set`
+ * a static element instead of animating it. Updates an existing `set` in place, or
+ * creates a dedicated `set` at position 0 when the element has none.
+ */
+async function commitStaticSet(
+ selection: DomEditSelection,
+ propEntries: [string, number | string][],
+ selector: string | null,
+ animations: GsapAnimation[],
+ commit: Commit,
+): Promise<void> {
+ if (!selector) return;
+ // Update an existing `set` in ONE batched commit — NEVER a flat `to`/`from`. A
+ // set's id is GROUP-derived, so a per-prop loop shifts it the instant a new-group
+ // prop lands (e.g. `scale` onto a rotation set), 404-ing the next prop; commitSetProps
+ // sends them together. A static element with no set gets a dedicated `set` carrying
+ // ALL props in ONE `add`.
+ const existingSet = animations.find((a) => a.method === "set" && a.targetSelector === selector);
+ if (existingSet) {
+ await commitSetProps(selection, existingSet, propEntries, selector, animations, commit);
+ return;
+ }
+ // Base `gsap.set` (off-timeline) — a static hold with no 0% keyframe marker, so
+ // adjusting a 3D transform on a non-keyframed element doesn't drop a keyframe on
+ // the timeline (matches the manual-drag UX). The global-set instant patch applies
+ // it straight to the element so the first edit shows with no soft-reload flash.
+ const numericProps: SetPatchProps = {};
+ for (const [k, v] of propEntries) {
+ if (typeof v === "number") numericProps[k as keyof SetPatchProps] = v;
+ }
+ await commit(
+ selection,
+ {
+ type: "add",
+ targetSelector: selector,
+ method: "set",
+ position: 0,
+ properties: Object.fromEntries(propEntries),
+ global: true,
+ },
+ {
+ label: "Set 3D transform",
+ softReload: true,
+ ...(Object.keys(numericProps).length > 0
+ ? {
+ instantPatch: {
+ selector,
+ change: { kind: "global-set" as const, props: numericProps },
+ },
+ }
+ : {}),
+ },
+ );
+}
+
+/** Convert-if-flat, then write ALL props into ONE keyframe at the playhead. */
+// fallow-ignore-next-line complexity
+async function commitKeyframeProps(
+ selection: DomEditSelection,
+ anim: GsapAnimation,
+ props: Record<string, number | string>,
+ propEntries: [string, number | string][],
+ primaryProp: string,
+ selector: string | null,
+ iframe: HTMLIFrameElement | null,
+ commit: Commit,
+): Promise<void> {
+ if (!anim.keyframes) {
+ await commit(
+ selection,
+ { type: "convert-to-keyframes", animationId: anim.id },
+ { label: "Convert to keyframes", skipReload: true },
+ );
+ }
+ const pct = computeElementPercentage(usePlayerStore.getState().currentTime, selection, anim);
+ const runtimeProps = selector ? readAllAnimatedProperties(iframe, selector, anim) : {};
+ const properties: Record<string, number | string> = { ...runtimeProps, ...props };
+
+ const backfillDefaults: Record<string, number | string> = { ...runtimeProps };
+ for (const [property, value] of propEntries) {
+ if (!(property in runtimeProps) && selector) {
+ const cssVal = readGsapProperty(iframe, selector, property);
+ if (cssVal != null) backfillDefaults[property] = cssVal;
+ }
+ backfillDefaults[property] = value;
+ }
+
+ const existingKf = anim.keyframes?.keyframes.some((kf) => Math.abs(kf.percentage - pct) < 0.05);
+ // Rebuild the live keyframe tween in place so the edit shows instantly (no flash);
+ // rebuildKeyframeTween declines → soft reload if the tween can't be safely rebuilt.
+ const numericProps: Record<string, number> = {};
+ for (const [k, v] of Object.entries(properties)) {
+ if (typeof v === "number") numericProps[k] = v;
+ }
+ const instantPatch =
+ selector && Object.keys(numericProps).length > 0
+ ? { selector, change: { kind: "keyframe-rebuild" as const, pct, props: numericProps } }
+ : undefined;
+ await commit(
+ selection,
+ existingKf
+ ? { type: "update-keyframe", animationId: anim.id, percentage: pct, properties }
+ : {
+ type: "add-keyframe",
+ animationId: anim.id,
+ percentage: pct,
+ properties,
+ backfillDefaults,
+ },
+ {
+ label: `Edit ${primaryProp} (keyframe ${pct}%)`,
+ softReload: true,
+ ...(instantPatch ? { instantPatch } : {}),
+ },
+ );
+}
+
export function useAnimatedPropertyCommit(deps: CommitAnimatedPropertyDeps) {
- const {
- selectedGsapAnimations,
- gsapCommitMutation,
- addGsapAnimation,
- previewIframeRef,
- bumpGsapCache,
- } = deps;
+ const { selectedGsapAnimations, gsapCommitMutation, previewIframeRef, bumpGsapCache } = deps;
- const commitAnimatedProperty = useCallback(
- async (
- selection: DomEditSelection,
- property: string,
- value: number | string,
- ): Promise<void> => {
+ const commitAnimatedProperties = useCallback(
+ async (selection: DomEditSelection, props: Record<string, number | string>): Promise<void> => {
if (!gsapCommitMutation) return;
+ const propEntries = Object.entries(props);
+ if (propEntries.length === 0) return;
+ const primaryProp = propEntries[0]![0];
const iframe = previewIframeRef.current;
const selector = selectorFromSelection(selection);
- let anim: GsapAnimation | undefined = pickBestAnimation(
+ const anim: GsapAnimation | undefined = pickBestAnimation(
selectedGsapAnimations,
selector,
- property,
+ primaryProp,
);
+ // Whether the element is animated at all. A 3D edit only creates/edits
+ // keyframes when it IS — a static element (no keyframes on any of its tweens)
+ // gets a `tl.set`, never new keyframes (matches manual drag / resize / rotate).
+ const elementHasKeyframes = selectedGsapAnimations.some((a) => !!a.keyframes);
- // Case 3: No animation — create one first
- if (!anim) {
- addGsapAnimation(selection, "to");
- // The addGsapAnimation triggers a reload. We need to wait for the cache
- // to update. Use a small delay then bump cache to re-fetch.
- await new Promise((r) => setTimeout(r, 500));
- bumpGsapCache();
- // After creation, we can't proceed in this call — the animation isn't
- // in our local state yet. The user's next edit will find it.
- // For immediate feedback, trigger a convert-to-keyframes on the new animation.
- return;
- }
+ // The picked anim comes from the (possibly stale) panel cache: if keyframes
+ // were just removed or the script changed underneath us, its id is gone
+ // server-side and the commit 404s. The raw commit already toasts; we catch
+ // so the rejection doesn't escape as an uncaught promise, and bump the cache
+ // so selectedGsapAnimations re-syncs and the user's next edit self-heals.
+ try {
+ // Existing static hold — merge the props into the `set`, then auto-keyframe
+ // ONLY if the element is already animated (maybeAutoKeyframeSet no-ops if not).
+ if (anim?.method === "set") {
+ await commitSetProps(
+ selection,
+ anim,
+ propEntries,
+ selector,
+ selectedGsapAnimations,
+ gsapCommitMutation,
+ );
+ return;
+ }
- // Case 2: Flat animation — convert to keyframes first
- if (!anim.keyframes) {
- await gsapCommitMutation(
+ // Static element — persist as a `tl.set`, never keyframes (incl. the
+ // no-animation case, which now creates a set instead of a keyframed tween).
+ if (!elementHasKeyframes) {
+ await commitStaticSet(
+ selection,
+ propEntries,
+ selector,
+ selectedGsapAnimations,
+ gsapCommitMutation,
+ );
+ return;
+ }
+
+ // Animated element — write ALL props into ONE keyframe so a multi-axis cube
+ // edit doesn't race into adjacent duplicates.
+ if (!anim) {
+ bumpGsapCache();
+ return;
+ }
+ await commitKeyframeProps(
selection,
- { type: "convert-to-keyframes", animationId: anim.id },
- { label: "Convert to keyframes", skipReload: true },
+ anim,
+ props,
+ propEntries,
+ primaryProp,
+ selector,
+ iframe,
+ gsapCommitMutation,
);
+ } catch {
+ bumpGsapCache();
}
-
- const pct = computeElementPercentage(usePlayerStore.getState().currentTime, selection, anim);
-
- // Read all currently animated properties from runtime for backfill
- const runtimeProps = selector ? readAllAnimatedProperties(iframe, selector, anim) : {};
-
- // Build the properties object: all runtime props + the new value
- const properties: Record<string, number | string> = { ...runtimeProps };
- properties[property] = value;
-
- // Compute backfill defaults for properties not in existing keyframes
- const backfillDefaults: Record<string, number | string> = { ...runtimeProps };
- if (!(property in runtimeProps) && selector) {
- const cssVal = readGsapProperty(iframe, selector, property);
- if (cssVal != null) backfillDefaults[property] = cssVal;
- }
- backfillDefaults[property] = typeof value === "number" ? value : value;
-
- const existingKf = anim.keyframes?.keyframes.some(
- (kf) => Math.abs(kf.percentage - pct) < 0.05,
- );
-
- await gsapCommitMutation(
- selection,
- existingKf
- ? {
- type: "update-keyframe",
- animationId: anim.id,
- percentage: pct,
- properties,
- }
- : {
- type: "add-keyframe",
- animationId: anim.id,
- percentage: pct,
- properties,
- backfillDefaults,
- },
- { label: `Edit ${property} (keyframe ${pct}%)`, softReload: true },
- );
},
- [selectedGsapAnimations, gsapCommitMutation, addGsapAnimation, previewIframeRef, bumpGsapCache],
+ [selectedGsapAnimations, gsapCommitMutation, previewIframeRef, bumpGsapCache],
+ );
+
+ const commitAnimatedProperty = useCallback(
+ (selection: DomEditSelection, property: string, value: number | string) =>
+ commitAnimatedProperties(selection, { [property]: value }),
+ [commitAnimatedProperties],
);
- return commitAnimatedProperty;
+ return { commitAnimatedProperty, commitAnimatedProperties };
}
diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.ts
index 8492b0ab97..38ab0c0b9c 100644
--- a/packages/studio/src/hooks/useDomEditCommits.ts
+++ b/packages/studio/src/hooks/useDomEditCommits.ts
@@ -301,7 +301,6 @@ export function useDomEditCommits({
const {
handleDomPathOffsetCommit,
- handleDomGroupPathOffsetCommit,
handleDomBoxSizeCommit,
handleDomRotationCommit,
handleDomManualEditsReset,
@@ -340,7 +339,6 @@ export function useDomEditCommits({
handleDomAddTextField,
handleDomRemoveTextField,
handleDomPathOffsetCommit,
- handleDomGroupPathOffsetCommit,
handleDomBoxSizeCommit,
handleDomRotationCommit,
handleDomManualEditsReset,
diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.ts
index 736d973303..96ffdbc09d 100644
--- a/packages/studio/src/hooks/useDomEditSession.ts
+++ b/packages/studio/src/hooks/useDomEditSession.ts
@@ -215,7 +215,6 @@ export function useDomEditSession({
handleDomTextFieldStyleCommit,
handleDomAddTextField,
handleDomRemoveTextField,
- handleDomGroupPathOffsetCommit,
handleDomBoxSizeCommit,
handleDomManualEditsReset,
handleDomEditElementDelete,
@@ -368,9 +367,11 @@ export function useDomEditSession({
const {
handleGsapAwarePathOffsetCommit,
+ handleGsapAwareGroupPathOffsetCommit,
handleGsapAwareBoxSizeCommit,
handleGsapAwareRotationCommit,
commitAnimatedProperty,
+ commitAnimatedProperties,
handleSetArcPath,
handleUpdateArcSegment,
handleUnroll,
@@ -452,7 +453,7 @@ export function useDomEditSession({
handleDomAttributeLiveCommit,
handleDomHtmlAttributeCommit,
handleDomPathOffsetCommit: handleGsapAwarePathOffsetCommit,
- handleDomGroupPathOffsetCommit,
+ handleDomGroupPathOffsetCommit: handleGsapAwareGroupPathOffsetCommit,
handleDomZIndexReorderCommit,
handleDomBoxSizeCommit: handleGsapAwareBoxSizeCommit,
handleDomRotationCommit: handleGsapAwareRotationCommit,
@@ -498,6 +499,7 @@ export function useDomEditSession({
handleUpdateKeyframeEase,
handleSetAllKeyframeEases,
commitAnimatedProperty,
+ commitAnimatedProperties,
handleSetArcPath,
handleUpdateArcSegment,
handleUnroll,
diff --git a/packages/studio/src/hooks/useDomGeometryCommits.ts b/packages/studio/src/hooks/useDomGeometryCommits.ts
index ffe3822da4..ab81e4adfc 100644
--- a/packages/studio/src/hooks/useDomGeometryCommits.ts
+++ b/packages/studio/src/hooks/useDomGeometryCommits.ts
@@ -16,11 +16,10 @@ import {
buildClearBoxSizePatches,
buildClearRotationPatches,
} from "../components/editor/manualEditsDomPatches";
-import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay";
import type { PatchOperation } from "../utils/sourcePatcher";
import { isElementGsapTargeted } from "./gsapTargetCache";
-export const GSAP_CSS_FALLBACK_BLOCKED_MESSAGE =
+const GSAP_CSS_FALLBACK_BLOCKED_MESSAGE =
"This element is GSAP-animated — dragging via CSS would corrupt keyframes";
// ── Hook ──
@@ -46,7 +45,8 @@ export function useDomGeometryCommits({
// elements fall through to commitPositionPatchToHtml → persistDomEditOperations →
// onTrySdkPersist and are already SDK-cut-over as setStyle/setAttribute (§3.3 done).
// Upgrade path for GSAP: add a moveElementGsap SDK op in a separate SDK PR.
- if (isElementGsapTargeted(previewIframeRef.current, selection.element)) {
+ const gsapTargeted = isElementGsapTargeted(previewIframeRef.current, selection.element);
+ if (gsapTargeted) {
const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
showToast(error.message, "error");
return Promise.reject(error);
@@ -60,33 +60,6 @@ export function useDomGeometryCommits({
[commitPositionPatchToHtml, previewIframeRef, showToast],
);
- const handleDomGroupPathOffsetCommit = useCallback(
- (updates: DomEditGroupPathOffsetCommit[]) => {
- if (updates.length === 0) return Promise.resolve();
- const blockedUpdate = updates.find(({ selection }) =>
- isElementGsapTargeted(previewIframeRef.current, selection.element),
- );
- if (blockedUpdate) {
- const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
- showToast(error.message, "error");
- return Promise.reject(error);
- }
- const coalesceKey = updates
- .map((u) => getDomEditTargetKey(u.selection))
- .sort()
- .join(":");
- const saves = updates.map(({ selection, next }) => {
- applyStudioPathOffset(selection.element, next);
- return commitPositionPatchToHtml(selection, buildPathOffsetPatches(selection.element), {
- label: `Move ${updates.length} layers`,
- coalesceKey: `group-path-offset:${coalesceKey}`,
- });
- });
- return Promise.all(saves).then(() => undefined);
- },
- [commitPositionPatchToHtml, previewIframeRef, showToast],
- );
-
const handleDomBoxSizeCommit = useCallback(
(selection: DomEditSelection, next: { width: number; height: number }) => {
if (isElementGsapTargeted(previewIframeRef.current, selection.element)) {
@@ -142,7 +115,6 @@ export function useDomGeometryCommits({
return {
handleDomPathOffsetCommit,
- handleDomGroupPathOffsetCommit,
handleDomBoxSizeCommit,
handleDomRotationCommit,
handleDomManualEditsReset,
diff --git a/packages/studio/src/hooks/useGsapAwareEditing.ts b/packages/studio/src/hooks/useGsapAwareEditing.ts
index da3f500364..f695595a57 100644
--- a/packages/studio/src/hooks/useGsapAwareEditing.ts
+++ b/packages/studio/src/hooks/useGsapAwareEditing.ts
@@ -21,6 +21,7 @@ import {
useSafeGsapCommitMutation,
} from "./useSafeGsapCommitMutation";
import type { CommitMutation } from "./gsapScriptCommitTypes";
+import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay";
export interface UseGsapAwareEditingParams {
domEditSelection: DomEditSelection | null;
@@ -122,6 +123,33 @@ export function useGsapAwareEditing({
],
);
+ // Multi-select (group) drag: route EACH element through the SAME GSAP intercept as
+ // a single drag, so every position is written as GSAP code (tl.set / keyframes /
+ // gsap.set) — NEVER the deprecated `--hf-studio-offset` CSS var, and GSAP-animated
+ // elements are no longer blocked in a group. No CSS fallback: with no GSAP
+ // composition there's nothing to write (a no-op, exactly like the single-drag path).
+ const handleGsapAwareGroupPathOffsetCommit = useCallback(
+ async (updates: DomEditGroupPathOffsetCommit[]) => {
+ if (!gsapCommitMutation) return;
+ for (const { selection, next } of updates) {
+ try {
+ await tryGsapDragIntercept(
+ selection,
+ next,
+ [],
+ previewIframeRef.current,
+ gsapCommitMutation,
+ makeFetchFallback(selection),
+ );
+ } catch (error) {
+ trackGsapInteractionFailure(error, selection, "drag", "Move animated layer (group)");
+ throw error;
+ }
+ }
+ },
+ [gsapCommitMutation, previewIframeRef, makeFetchFallback, trackGsapInteractionFailure],
+ );
+
const handleGsapAwareBoxSizeCommit = useCallback(
async (selection: DomEditSelection, next: { width: number; height: number }) => {
if (gsapCommitMutation) {
@@ -184,7 +212,7 @@ export function useGsapAwareEditing({
// ── Animated property commit ──
- const commitAnimatedProperty = useAnimatedPropertyCommit({
+ const { commitAnimatedProperty, commitAnimatedProperties } = useAnimatedPropertyCommit({
selectedGsapAnimations,
gsapCommitMutation,
addGsapAnimation: (sel, method, time) => addGsapAnimation(sel, method, time),
@@ -246,9 +274,11 @@ export function useGsapAwareEditing({
return {
handleGsapAwarePathOffsetCommit,
+ handleGsapAwareGroupPathOffsetCommit,
handleGsapAwareBoxSizeCommit,
handleGsapAwareRotationCommit,
commitAnimatedProperty,
+ commitAnimatedProperties,
handleSetArcPath,
handleUpdateArcSegment,
handleUnroll,
diff --git a/packages/studio/src/hooks/useGsapKeyframeOps.ts b/packages/studio/src/hooks/useGsapKeyframeOps.ts
index fbb247274c..bacb95a4b8 100644
--- a/packages/studio/src/hooks/useGsapKeyframeOps.ts
+++ b/packages/studio/src/hooks/useGsapKeyframeOps.ts
@@ -206,6 +206,7 @@ export function useGsapKeyframeOps({
selection: DomEditSelection,
animationId: string,
resolvedFromValues?: Record<string, number | string>,
+ duration?: number,
) => {
if (sdkSession && sdkDeps) {
const targetPath = selection.sourceFile || activeCompPath || "index.html";
@@ -221,7 +222,9 @@ export function useGsapKeyframeOps({
}
return commitMutation(
selection,
- { type: "convert-to-keyframes", animationId, resolvedFromValues },
+ // `duration` only applies when the target is a static `set` (which has
+ // none) — it spans the converted keyframes across the element's clip.
+ { type: "convert-to-keyframes", animationId, resolvedFromValues, duration },
{ label: "Convert to keyframes" },
);
},
diff --git a/packages/studio/src/hooks/useGsapSelectionHandlers.ts b/packages/studio/src/hooks/useGsapSelectionHandlers.ts
index 7a9ee09dba..d3d795e37b 100644
--- a/packages/studio/src/hooks/useGsapSelectionHandlers.ts
+++ b/packages/studio/src/hooks/useGsapSelectionHandlers.ts
@@ -76,6 +76,7 @@ export function useGsapSelectionHandlers({
sel: DomEditSelection,
animId: string,
resolvedFromValues?: Record<string, number | string>,
+ duration?: number,
) => Promise<void>;
removeAllKeyframes: (sel: DomEditSelection, animId: string) => void;
@@ -229,16 +230,18 @@ export function useGsapSelectionHandlers({
);
const handleGsapConvertToKeyframes = useCallback(
- (animId: string, resolvedFromValues?: Record<string, number | string>) => {
+ (animId: string, resolvedFromValues?: Record<string, number | string>, duration?: number) => {
if (!domEditSelection) return Promise.resolve();
- return convertToKeyframes(domEditSelection, animId, resolvedFromValues).catch((error) => {
- trackGsapHandlerFailure(
- error,
- domEditSelection,
- "convert-to-keyframes",
- "Convert to keyframes",
- );
- });
+ return convertToKeyframes(domEditSelection, animId, resolvedFromValues, duration).catch(
+ (error) => {
+ trackGsapHandlerFailure(
+ error,
+ domEditSelection,
+ "convert-to-keyframes",
+ "Convert to keyframes",
+ );
+ },
+ );
},
[domEditSelection, convertToKeyframes, trackGsapHandlerFailure],
);
diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.ts
index bec9757aec..985511271c 100644
--- a/packages/studio/src/hooks/useGsapTweenCache.ts
+++ b/packages/studio/src/hooks/useGsapTweenCache.ts
@@ -27,10 +27,12 @@ function deduplicateKeyframes(keyframes: GsapPercentageKeyframe[]): GsapPercenta
// fallow-ignore-next-line complexity
function synthesizeFlatTweenKeyframes(anim: GsapAnimation): GsapKeyframesData | null {
if (anim.method === "set") {
- return {
- format: "percentage",
- keyframes: [{ percentage: 0, properties: { ...anim.properties } }],
- };
+ // A `set` is a STATIC HOLD — a value applied at one point, not an animated
+ // keyframe. It must NOT synthesize a keyframe, or the timeline + panel show a
+ // phantom diamond for a value that doesn't animate. This holds for a base
+ // `gsap.set` (off-timeline) AND an on-timeline `tl.set`, and aligns the AST
+ // path with the runtime scan, which already skips every zero-duration set.
+ return null;
}
const toProps = anim.properties;
const fromProps = anim.fromProperties;
diff --git a/packages/studio/src/utils/marqueeGeometry.test.ts b/packages/studio/src/utils/marqueeGeometry.test.ts
index 23688da34f..75065b2e2e 100644
--- a/packages/studio/src/utils/marqueeGeometry.test.ts
+++ b/packages/studio/src/utils/marqueeGeometry.test.ts
@@ -1,34 +1,5 @@
import { describe, expect, it } from "vitest";
-import { marqueeIntersectsObb, rectsOverlap, type Point, type Rect } from "./marqueeGeometry";
-
-type Corners = [Point, Point, Point, Point];
-
-function rotateCorners(cx: number, cy: number, w: number, h: number, deg: number): Corners {
- const rad = (deg * Math.PI) / 180;
- const cos = Math.cos(rad);
- const sin = Math.sin(rad);
- const hw = w / 2;
- const hh = h / 2;
- const local: [number, number][] = [
- [-hw, -hh],
- [hw, -hh],
- [hw, hh],
- [-hw, hh],
- ];
- return local.map(([lx, ly]) => ({
- x: cx + cos * lx - sin * ly,
- y: cy + sin * lx + cos * ly,
- })) as Corners;
-}
-
-function aabbCorners(r: Rect): Corners {
- return [
- { x: r.left, y: r.top },
- { x: r.left + r.width, y: r.top },
- { x: r.left + r.width, y: r.top + r.height },
- { x: r.left, y: r.top + r.height },
- ];
-}
+import { rectsOverlap } from "./marqueeGeometry";
describe("rectsOverlap", () => {
it("overlapping rects", () => {
@@ -48,76 +19,22 @@ describe("rectsOverlap", () => {
),
).toBe(false);
});
-});
-
-describe("marqueeIntersectsObb", () => {
- it("axis-aligned overlap", () => {
- const marquee: Rect = { left: 0, top: 0, width: 100, height: 100 };
- const corners = aabbCorners({ left: 50, top: 50, width: 80, height: 80 });
- expect(marqueeIntersectsObb(marquee, corners)).toBe(true);
- });
-
- it("axis-aligned no overlap", () => {
- const marquee: Rect = { left: 0, top: 0, width: 50, height: 50 };
- const corners = aabbCorners({ left: 100, top: 100, width: 50, height: 50 });
- expect(marqueeIntersectsObb(marquee, corners)).toBe(false);
- });
- it("marquee fully contains element", () => {
- const marquee: Rect = { left: 0, top: 0, width: 200, height: 200 };
- const corners = aabbCorners({ left: 50, top: 50, width: 20, height: 20 });
- expect(marqueeIntersectsObb(marquee, corners)).toBe(true);
- });
-
- it("element fully contains marquee", () => {
- const marquee: Rect = { left: 50, top: 50, width: 10, height: 10 };
- const corners = aabbCorners({ left: 0, top: 0, width: 200, height: 200 });
- expect(marqueeIntersectsObb(marquee, corners)).toBe(true);
- });
-
- it("45-degree rotated square: AABB overlaps but OBB does not", () => {
- // 100x100 square rotated 45° centered at (200,200)
- // Its AABB extends to ~(129,129)-(271,271)
- // A marquee at (0,0)-(135,135) overlaps the AABB but NOT the diamond
- const corners = rotateCorners(200, 200, 100, 100, 45);
- const marquee: Rect = { left: 0, top: 0, width: 135, height: 135 };
- expect(marqueeIntersectsObb(marquee, corners)).toBe(false);
- });
-
- it("45-degree rotated square: OBB overlaps", () => {
- // Same rotated square, marquee reaches the diamond's left point
- const corners = rotateCorners(200, 200, 100, 100, 45);
- const marquee: Rect = { left: 0, top: 150, width: 155, height: 100 };
- expect(marqueeIntersectsObb(marquee, corners)).toBe(true);
- });
-
- it("zero-width marquee returns false", () => {
- const corners = aabbCorners({ left: 0, top: 0, width: 100, height: 100 });
- expect(marqueeIntersectsObb({ left: 50, top: 50, width: 0, height: 50 }, corners)).toBe(false);
- });
-
- it("zero-area element returns false for degenerate OBB", () => {
- const corners: Corners = [
- { x: 50, y: 50 },
- { x: 50, y: 50 },
- { x: 50, y: 50 },
- { x: 50, y: 50 },
- ];
- const marquee: Rect = { left: 0, top: 0, width: 100, height: 100 };
- // Degenerate point — SAT still works (projections are zero-length intervals)
- // A point inside the marquee should still intersect
- expect(marqueeIntersectsObb(marquee, corners)).toBe(true);
- });
-
- it("30-degree rotated rectangle clips marquee corner", () => {
- const corners = rotateCorners(150, 150, 200, 50, 30);
- const marquee: Rect = { left: 0, top: 0, width: 80, height: 130 };
- expect(marqueeIntersectsObb(marquee, corners)).toBe(true);
+ it("touching edges do not overlap", () => {
+ expect(
+ rectsOverlap(
+ { left: 0, top: 0, width: 10, height: 10 },
+ { left: 10, top: 0, width: 10, height: 10 },
+ ),
+ ).toBe(false);
});
- it("30-degree rotated rectangle misses marquee", () => {
- const corners = rotateCorners(300, 300, 50, 50, 30);
- const marquee: Rect = { left: 0, top: 0, width: 100, height: 100 };
- expect(marqueeIntersectsObb(marquee, corners)).toBe(false);
+ it("one rect fully inside another overlaps", () => {
+ expect(
+ rectsOverlap(
+ { left: 0, top: 0, width: 100, height: 100 },
+ { left: 25, top: 25, width: 10, height: 10 },
+ ),
+ ).toBe(true);
});
});
diff --git a/packages/studio/src/utils/marqueeGeometry.ts b/packages/studio/src/utils/marqueeGeometry.ts
index 4bf5d7e986..1a013f6c86 100644
--- a/packages/studio/src/utils/marqueeGeometry.ts
+++ b/packages/studio/src/utils/marqueeGeometry.ts
@@ -1,8 +1,3 @@
-export interface Point {
- x: number;
- y: number;
-}
-
export interface Rect {
left: number;
top: number;
@@ -10,14 +5,7 @@ export interface Rect {
height: number;
}
-type Corners = [Point, Point, Point, Point];
-
-function isIdentityMatrix(m: DOMMatrix): boolean {
- const e = 1e-6;
- return Math.abs(m.a - 1) < e && Math.abs(m.b) < e && Math.abs(m.c) < e && Math.abs(m.d - 1) < e;
-}
-
-function rectsOverlap(a: Rect, b: Rect): boolean {
+export function rectsOverlap(a: Rect, b: Rect): boolean {
return (
a.left < b.left + b.width &&
a.left + a.width > b.left &&
@@ -25,148 +13,3 @@ function rectsOverlap(a: Rect, b: Rect): boolean {
a.top + a.height > b.top
);
}
-
-function projectOntoAxis(corners: Corners, ax: number, ay: number): [number, number] {
- let min = Infinity;
- let max = -Infinity;
- for (const c of corners) {
- const dot = c.x * ax + c.y * ay;
- if (dot < min) min = dot;
- if (dot > max) max = dot;
- }
- return [min, max];
-}
-
-function projectionsOverlap(a: [number, number], b: [number, number]): boolean {
- return a[0] <= b[1] && b[0] <= a[1];
-}
-
-/**
- * SAT intersection test between an axis-aligned marquee rect and a
- * convex quadrilateral (the element's OBB corners in overlay space).
- *
- * Separating axes: 2 from the AABB (horizontal, vertical) + 2 from
- * the OBB's edge normals. If projections overlap on all 4 axes, the
- * shapes intersect.
- */
-export function marqueeIntersectsObb(marquee: Rect, corners: Corners): boolean {
- if (marquee.width <= 0 || marquee.height <= 0) return false;
-
- const mCorners: Corners = [
- { x: marquee.left, y: marquee.top },
- { x: marquee.left + marquee.width, y: marquee.top },
- { x: marquee.left + marquee.width, y: marquee.top + marquee.height },
- { x: marquee.left, y: marquee.top + marquee.height },
- ];
-
- // AABB axes: (1,0) and (0,1)
- const mProjX: [number, number] = [marquee.left, marquee.left + marquee.width];
- const mProjY: [number, number] = [marquee.top, marquee.top + marquee.height];
-
- const oProjX = projectOntoAxis(corners, 1, 0);
- const oProjY = projectOntoAxis(corners, 0, 1);
-
- if (!projectionsOverlap(mProjX, oProjX)) return false;
- if (!projectionsOverlap(mProjY, oProjY)) return false;
-
- // OBB edge normals (only need 2 — edges 0→1 and 1→2)
- for (let i = 0; i < 2; i++) {
- const edge = {
- x: corners[i + 1].x - corners[i].x,
- y: corners[i + 1].y - corners[i].y,
- };
- const len = Math.hypot(edge.x, edge.y);
- if (len < 1e-9) continue;
- const ax = -edge.y / len;
- const ay = edge.x / len;
-
- const mProj = projectOntoAxis(mCorners, ax, ay);
- const oProj = projectOntoAxis(corners, ax, ay);
- if (!projectionsOverlap(mProj, oProj)) return false;
- }
-
- return true;
-}
-
-/**
- * Compute the four corners of an element's OBB in overlay-pixel space.
- *
- * For elements with an identity transform, returns the axis-aligned
- * corners from the element's BCR mapped to overlay space (fast path).
- */
-// fallow-ignore-next-line complexity
-export function elementObbCorners(
- element: HTMLElement,
- overlayEl: HTMLDivElement,
- iframe: HTMLIFrameElement,
-): Corners | null {
- const doc = iframe.contentDocument;
- if (!doc) return null;
-
- const iframeRect = iframe.getBoundingClientRect();
- const overlayRect = overlayEl.getBoundingClientRect();
- const root = doc.querySelector<HTMLElement>("[data-composition-id]") ?? doc.documentElement;
- const declaredW = Number.parseFloat(root?.getAttribute("data-width") ?? "");
- const declaredH = Number.parseFloat(root?.getAttribute("data-height") ?? "");
- const rootW = declaredW > 0 ? declaredW : root?.getBoundingClientRect().width || 1;
- const rootH = declaredH > 0 ? declaredH : root?.getBoundingClientRect().height || 1;
-
- const scaleX = iframeRect.width / rootW;
- const scaleY = iframeRect.height / rootH;
- const offsetX = iframeRect.left - overlayRect.left;
- const offsetY = iframeRect.top - overlayRect.top;
-
- const win = element.ownerDocument.defaultView;
- if (!win) return null;
-
- const transform = win.getComputedStyle(element).transform;
- const m = transform && transform !== "none" ? new DOMMatrix(transform) : new DOMMatrix();
-
- if (isIdentityMatrix(m)) {
- const r = element.getBoundingClientRect();
- const left = offsetX + r.left * scaleX;
- const top = offsetY + r.top * scaleY;
- const w = r.width * scaleX;
- const h = r.height * scaleY;
- return [
- { x: left, y: top },
- { x: left + w, y: top },
- { x: left + w, y: top + h },
- { x: left, y: top + h },
- ];
- }
-
- // Walk offsetParent chain for pre-transform position
- let ox = 0;
- let oy = 0;
- let el: HTMLElement | null = element;
- while (el && el !== doc.body && el !== doc.documentElement) {
- ox += el.offsetLeft;
- oy += el.offsetTop;
- el = el.offsetParent as HTMLElement | null;
- }
-
- const w = element.offsetWidth;
- const h = element.offsetHeight;
- // ponytail: center-based transform — CSS transforms originate at 50% 50%
- const cx = ox + w / 2;
- const cy = oy + h / 2;
-
- const localCorners: [number, number][] = [
- [-w / 2, -h / 2],
- [w / 2, -h / 2],
- [w / 2, h / 2],
- [-w / 2, h / 2],
- ];
-
- return localCorners.map(([lx, ly]) => {
- const tx = m.a * lx + m.c * ly + cx;
- const ty = m.b * lx + m.d * ly + cy;
- return {
- x: offsetX + tx * scaleX,
- y: offsetY + ty * scaleY,
- };
- }) as Corners;
-}
-
-export { rectsOverlap };