Skip to content

Write HTML. Render video. Built for agents.

fix(studio): dragging a keyframed layer from its middle moves the layer, not a path node (#4941)

Miguel Ángel7faf2cc6c31f
diff --git a/packages/parsers/src/gsapParserAcorn.full.test.ts b/packages/parsers/src/gsapParserAcorn.full.test.ts
index e6348eff04..99acded541 100644
--- a/packages/parsers/src/gsapParserAcorn.full.test.ts
+++ b/packages/parsers/src/gsapParserAcorn.full.test.ts
@@ -358,6 +358,28 @@ describe("parseGsapScript", () => {
// ── resolvedStart ─────────────────────────────────────────────────────────────
+describe("timeline defaults", () => {
+ it("never gives a keyframed tween the timeline's default ease, as GSAP does not", () => {
+ const script = `
+ const tl = gsap.timeline({ defaults: { ease: "power2.out" } });
+ tl.to("#a", { keyframes: { "0%": { x: 0 }, "100%": { x: 100 } }, duration: 2 });
+ tl.to("#b", { x: 100, duration: 2 });
+ `;
+ const [keyed, flat] = parseGsapScriptAcorn(script).animations;
+ expect(keyed!.ease).toBeUndefined();
+ expect(flat!.ease).toBe("power2.out");
+ });
+
+ it("keeps a keyframes ease the file names by variable, so a rewrite can write it back", () => {
+ const script = `
+ const tl = gsap.timeline();
+ tl.to("#a", { keyframes: { "0%": { x: 0 }, "100%": { x: 100 }, ease: E, easeEach: F }, duration: 2 });
+ `;
+ const [anim] = parseGsapScriptAcorn(script).animations;
+ expect(anim!.keyframes).toMatchObject({ ease: "__raw:E", easeEach: "__raw:F" });
+ });
+});
+
describe("resolvedStart — timeline position resolution", () => {
it("resolves chained from() tweens with relative positions (sdk-test pattern)", () => {
const script = `
diff --git a/packages/parsers/src/gsapParserAcorn.ts b/packages/parsers/src/gsapParserAcorn.ts
index 7ca9187384..b46410234b 100644
--- a/packages/parsers/src/gsapParserAcorn.ts
+++ b/packages/parsers/src/gsapParserAcorn.ts
@@ -999,9 +999,14 @@ function findAllTweenCalls(
const PERCENTAGE_KEY_RE = /^(\d+(?:\.\d+)?)%$/;
-function tryResolveStringProp(propValue: any, scope: ScopeBindings): string | undefined {
+function tryResolveStringProp(
+ propValue: any,
+ scope: ScopeBindings,
+ source?: string,
+): string | undefined {
const val = resolveNode(propValue, scope);
- return typeof val === "string" ? val : undefined;
+ if (typeof val === "string") return val;
+ return source === undefined ? undefined : `__raw:${source.slice(propValue.start, propValue.end)}`;
}
// fallow-ignore-next-line complexity
@@ -1042,9 +1047,9 @@ function parsePercentageKeyframes(
}
keyframes.push({ percentage, properties, ...(kfEase ? { ease: kfEase } : {}) });
} else if (key === "ease") {
- ease = tryResolveStringProp(prop.value, scope) ?? ease;
+ ease = tryResolveStringProp(prop.value, scope, source) ?? ease;
} else if (key === "easeEach") {
- easeEach = tryResolveStringProp(prop.value, scope) ?? easeEach;
+ easeEach = tryResolveStringProp(prop.value, scope, source) ?? easeEach;
}
}
@@ -1645,7 +1650,7 @@ function applyTimelineDefaults(
if (defaults.duration !== undefined) anim.duration = defaults.duration;
else if (defaults.durationUnresolved) anim.durationUnresolved = true;
}
- if (anim.ease === undefined && defaults.ease !== undefined) {
+ if (anim.ease === undefined && defaults.ease !== undefined && !anim.keyframes) {
anim.ease = defaults.ease;
}
}
diff --git a/packages/parsers/src/gsapWriter.acorn.test.ts b/packages/parsers/src/gsapWriter.acorn.test.ts
index 880bb17dd3..67829fd503 100644
--- a/packages/parsers/src/gsapWriter.acorn.test.ts
+++ b/packages/parsers/src/gsapWriter.acorn.test.ts
@@ -567,6 +567,17 @@ tl.set("#b", { x: 5 }, 0);`;
);
});
+ it("writes an ease the file names by variable as that variable, not a string", () => {
+ const keyframes = [{ percentage: 100, properties: { x: 100 }, ease: "__raw:K" }];
+ const out = replaceTweenWithKeyframesInScript(
+ script,
+ tweenOn("#a").id,
+ edit(1, { keyframes, ease: "__raw:E", easeEach: "__raw:X" }),
+ );
+ expect(rewritten(out)).toContain('"100%": { x: 100, ease: K }, easeEach: X }');
+ expect(rewritten(out)).toContain("ease: E }");
+ });
+
it("moves a retargeted tween to the new position without its delay, with the edit's ease", () => {
const out = replaceTweenWithKeyframesInScript(
script,
diff --git a/packages/parsers/src/gsapWriter.varEase.test.ts b/packages/parsers/src/gsapWriter.varEase.test.ts
new file mode 100644
index 0000000000..7f6ad2f3fe
--- /dev/null
+++ b/packages/parsers/src/gsapWriter.varEase.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from "vitest";
+import { parseGsapScriptAcornForWrite } from "./gsapParserAcorn.js";
+import {
+ addAnimationWithKeyframesToScript,
+ addKeyframeToScript,
+ convertToKeyframesFromScript,
+ unrollDynamicAnimations,
+} from "./gsapWriterAcorn.js";
+
+const keyframes = [
+ { percentage: 0, properties: { x: 0 } },
+ { percentage: 100, properties: { x: 100 } },
+];
+const idOf = (script: string) => parseGsapScriptAcornForWrite(script)?.located[0]?.id ?? "";
+
+describe("an ease the file names by variable is written back as that variable", () => {
+ it("when a keyframed tween is added", () => {
+ const script = "var tl = gsap.timeline({ paused: true });";
+ const out = addAnimationWithKeyframesToScript(
+ script,
+ "#a",
+ 0,
+ 1,
+ keyframes,
+ "__raw:E",
+ "__raw:F",
+ );
+ expect(out.script).toContain("easeEach: F }");
+ expect(out.script).toContain("ease: E }");
+ expect(out.script).not.toContain("__raw");
+ });
+
+ it("when a flat tween is converted to keyframes", () => {
+ const script = `var tl = gsap.timeline({ paused: true });\ntl.to("#a", { x: 100, duration: 1, ease: E }, 0);`;
+ const out = convertToKeyframesFromScript(script, idOf(script));
+ expect(out).toContain("easeEach: E");
+ expect(out).not.toContain("__raw");
+ });
+
+ it("when a keyframe is added to a flat tween", () => {
+ const script = `var tl = gsap.timeline({ paused: true });\ntl.to("#a", { x: 100, duration: 1, ease: E }, 0);`;
+ const out = addKeyframeToScript(script, idOf(script), 50, { x: 50 });
+ expect(out).toContain("easeEach: E");
+ expect(out).not.toContain("__raw");
+ });
+
+ it("when a looped tween is unrolled beside the loop's other statements", () => {
+ const script = `var tl = gsap.timeline({ paused: true });
+for (let i = 0; i < 2; i++) {
+ tl.set(items[i], { autoAlpha: 0 }, 0);
+ tl.to(items[i], { x: 100, duration: 1, ease: E }, 0);
+}`;
+ const located = parseGsapScriptAcornForWrite(script)?.located ?? [];
+ const to = located.find((l) => l.animation.method === "to");
+ const out = unrollDynamicAnimations(script, to?.id ?? "", [
+ { selector: "#a", keyframes },
+ { selector: "#b", keyframes },
+ ]);
+ expect(out).toContain('tl.to("#b"');
+ expect(out).toContain("ease: E }");
+ expect(out).not.toContain("__raw");
+ });
+
+ it("when a looped tween is unrolled", () => {
+ const script = `var tl = gsap.timeline({ paused: true });
+for (let i = 0; i < 2; i++) {
+ tl.to(items[i], { x: 100, duration: 1, ease: E }, 0);
+}`;
+ const out = unrollDynamicAnimations(script, idOf(script), [
+ { selector: "#a", keyframes },
+ { selector: "#b", keyframes },
+ ]);
+ expect(out).toContain("ease: E }");
+ expect(out).not.toContain("__raw");
+ });
+});
diff --git a/packages/parsers/src/gsapWriterAcorn.ts b/packages/parsers/src/gsapWriterAcorn.ts
index edf8a203a8..47d822379f 100644
--- a/packages/parsers/src/gsapWriterAcorn.ts
+++ b/packages/parsers/src/gsapWriterAcorn.ts
@@ -802,7 +802,7 @@ function preservedVarsEntries(varsNode: Node, source: string): string[] {
function buildConvertedVarsCode(animation: GsapAnimation, varsNode: Node, source: string): string {
const { fromProps, toProps } = conversionEndpoints(animation);
const easeEach = animation.ease;
- const easeEachEntry = easeEach ? `, easeEach: ${JSON.stringify(easeEach)}` : "";
+ const easeEachEntry = easeEach ? `, easeEach: ${valueToCode(easeEach)}` : "";
const kfCode = `{ "0%": ${recordToCode(fromProps)}, "100%": ${recordToCode(toProps)}${easeEachEntry} }`;
const entries = [`keyframes: ${kfCode}`, ...preservedVarsEntries(varsNode, source)];
if (easeEach) entries.push(`ease: "none"`);
@@ -1638,7 +1638,7 @@ function buildKeyframesVarsCode(
): 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)}`);
- const easeEntry = animation.ease ? `, easeEach: ${JSON.stringify(animation.ease)}` : "";
+ const easeEntry = animation.ease ? `, easeEach: ${valueToCode(animation.ease)}` : "";
const kfCode = `{ "0%": { ${fromEntries.join(", ")} }, "100%": { ${toEntries.join(", ")} }${easeEntry} }`;
// Preserve every non-editable key (duration/delay/callbacks/stagger/yoyo/…)
// verbatim from source — rebuilding from the animation object alone dropped
@@ -1729,11 +1729,11 @@ function buildKeyframeObjectCode(
): string {
const entries = mergePercentageKeyframes(keyframes).map((kf) => {
const props = Object.entries(kf.properties).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);
- if (kf.ease) props.push(`ease: ${JSON.stringify(kf.ease)}`);
+ if (kf.ease) props.push(`ease: ${valueToCode(kf.ease)}`);
if (kf.auto) props.push(`_auto: 1`);
return `${JSON.stringify(`${kf.percentage}%`)}: { ${props.join(", ")} }`;
});
- if (easeEach) entries.push(`easeEach: ${JSON.stringify(easeEach)}`);
+ if (easeEach) entries.push(`easeEach: ${valueToCode(easeEach)}`);
return `{ ${entries.join(", ")} }`;
}
@@ -1832,7 +1832,7 @@ export function replaceTweenWithKeyframesInScript(
const sorted = [...edit.keyframes].sort((a, b) => a.percentage - b.percentage);
const parts = [`keyframes: ${buildKeyframeObjectCode(sorted, edit.easeEach)}`, ...kept];
parts.push(`duration: ${valueToCode(edit.duration)}`);
- if (edit.ease) parts.push(`ease: ${JSON.stringify(edit.ease)}`);
+ if (edit.ease) parts.push(`ease: ${valueToCode(edit.ease)}`);
if (animation.hasUnresolvedSelector || animation.targetSelector !== edit.targetSelector) {
const selectorArg = call.node.arguments[0];
ms.overwrite(selectorArg.start, selectorArg.end, JSON.stringify(edit.targetSelector));
@@ -1868,7 +1868,7 @@ export function addAnimationWithKeyframesToScript(
const sorted = [...keyframes].sort((a, b) => a.percentage - b.percentage);
const kfObjCode = buildKeyframeObjectCode(sorted, easeEach);
const varParts = [`keyframes: ${kfObjCode}`, `duration: ${valueToCode(duration)}`];
- if (ease) varParts.push(`ease: ${JSON.stringify(ease)}`);
+ if (ease) varParts.push(`ease: ${valueToCode(ease)}`);
const stmtCode = `${parsed.timelineVar}.to(${JSON.stringify(targetSelector)}, { ${varParts.join(", ")} }, ${valueToCode(position)});`;
const ms = new MagicString(script);
@@ -2788,7 +2788,7 @@ function buildUnrollReplacement(
const calls = elements.map((el) => {
const sorted = [...el.keyframes].sort((a, b) => a.percentage - b.percentage);
const kfCode = buildKeyframeObjectCode(sorted, el.easeEach);
- return `${timelineVar}.to(${JSON.stringify(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${JSON.stringify(ease)} }, ${posCode});`;
+ return `${timelineVar}.to(${JSON.stringify(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${valueToCode(ease)} }, ${posCode});`;
});
return calls.join("\n ");
}
@@ -2811,7 +2811,7 @@ function buildUnrollCallForElement(
const posCode = typeof pos === "number" ? String(pos) : JSON.stringify(pos);
const sorted = [...el.keyframes].sort((a, b) => a.percentage - b.percentage);
const kfCode = buildKeyframeObjectCode(sorted, el.easeEach);
- return `${timelineVar}.to(${JSON.stringify(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${JSON.stringify(ease)} }, ${posCode});`;
+ return `${timelineVar}.to(${JSON.stringify(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${valueToCode(ease)} }, ${posCode});`;
}
/** Sentinel: the unroll cannot safely reproduce the loop body — caller no-ops. */
diff --git a/packages/studio/src/components/editor/MotionPathNode.tsx b/packages/studio/src/components/editor/MotionPathNode.tsx
index b1e9c21cea..26f1c71030 100644
--- a/packages/studio/src/components/editor/MotionPathNode.tsx
+++ b/packages/studio/src/components/editor/MotionPathNode.tsx
@@ -1,4 +1,5 @@
import type React from "react";
+import { dotRadius } from "./motionPathLayerNode";
// Editor primary color (themeable via --hf-accent). Applied through inline
// style because CSS var() isn't valid in SVG presentation attributes.
@@ -29,7 +30,7 @@ export function MotionPathNode(props: {
// Diamond matching the timeline keyframe (a 45°-rotated rounded square).
// `side` is chosen so the diamond's points reach ~`r` from center, matching the
// old dot's footprint; selection is shown by enlarging it (no extra shape).
- const side = (selected ? r * 1.5 : r) * 1.414;
+ const side = dotRadius(r, selected) * 1.414;
return (
<g onPointerEnter={props.onEnter} onPointerLeave={props.onLeave}>
<rect
diff --git a/packages/studio/src/components/editor/MotionPathOverlay.layerPress.test.tsx b/packages/studio/src/components/editor/MotionPathOverlay.layerPress.test.tsx
new file mode 100644
index 0000000000..2aef7068a0
--- /dev/null
+++ b/packages/studio/src/components/editor/MotionPathOverlay.layerPress.test.tsx
@@ -0,0 +1,99 @@
+// @vitest-environment happy-dom
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vitest";
+import { usePlayerStore } from "../../player/store/playerStore";
+import { MotionPathOverlay } from "./MotionPathOverlay";
+import type { DomEditSelection } from "./domEditing";
+
+Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);
+
+vi.mock("../../contexts/DomEditContext", () => ({
+ useDomEditContext: () => ({ selectedGsapAnimations: [], commitMutation: vi.fn() }),
+}));
+vi.mock("./motionPathSelection", () => ({
+ selectorFor: () => "#box",
+ editableAnimationId: () => "a1",
+}));
+// GSAP renders the layer at the first keyframe: the playhead is on it.
+vi.mock("../../hooks/gsapPositionDetection", () => ({
+ readGsapPositionFromIframe: () => ({ x: 60, y: 30 }),
+}));
+vi.mock("./useMotionPathData", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./useMotionPathData")>()),
+ useMotionPathData: () => ({
+ rect: { left: 0, top: 0, width: 1920, height: 1080 },
+ geometry: {
+ kind: "linear",
+ points: "60,30 120,30",
+ nodes: [
+ { x: 60, y: 30, ref: { type: "keyframe", pct: 66.667 } },
+ { x: 120, y: 30, ref: { type: "keyframe", pct: 100 } },
+ ],
+ },
+ geometryResolved: true,
+ visibleInPreview: true,
+ home: { x: 0, y: 0 },
+ pScale: 1,
+ }),
+}));
+
+it("the layer's node and another node's ring inside the layer's box press the layer; a dot keeps its node", () => {
+ const box = document.createElement("div");
+ box.setAttribute("data-dom-edit-selection-box", "true");
+ const host = document.createElement("div");
+ document.body.append(box, host);
+ const boxPresses: number[] = [];
+ let boxStarts = true;
+ box.addEventListener("pointerdown", (e) => {
+ boxPresses.push((e as PointerEvent).clientX);
+ if (boxStarts) e.preventDefault();
+ });
+ const captured = vi.spyOn(Element.prototype, "setPointerCapture").mockImplementation(() => {});
+ const root = createRoot(host);
+ const selection = { element: document.createElement("div") } as unknown as DomEditSelection;
+ // Scale 1: client px are composition px. `inBox`: the layer's box is under the press.
+ const press = (node: number, x: number, inBox: boolean) => {
+ const hit = [...host.querySelectorAll("circle.pointer-events-auto")].find(
+ (c) => c.getAttribute("cx") === String(node),
+ )!;
+ document.elementsFromPoint = () => (inBox ? [hit, box] : [hit]);
+ const down = { bubbles: true, cancelable: true, button: 0, clientX: x, clientY: 30 };
+ act(() => void hit.dispatchEvent(new PointerEvent("pointerdown", down)));
+ };
+ try {
+ act(() =>
+ root.render(
+ <MotionPathOverlay
+ iframeRef={{ current: null }}
+ selection={selection}
+ compositionSize={{ width: 1920, height: 1080 }}
+ isPlaying={false}
+ />,
+ ),
+ );
+ press(60, 63, false);
+ press(120, 110, true);
+ expect(boxPresses).toEqual([63, 110]);
+ press(120, 118, true);
+ press(120, 110, false);
+ expect(boxPresses).toEqual([63, 110]);
+ // A selected node draws its dot 1.5x as large, and the larger dot is the node's.
+ act(() => usePlayerStore.setState({ activeKeyframePct: 100 }));
+ press(120, 112, true);
+ expect(boxPresses).toEqual([63, 110]);
+ act(() => usePlayerStore.setState({ activeKeyframePct: null }));
+ press(120, 112, true);
+ expect(boxPresses).toEqual([63, 110, 112]);
+ // A box that starts no gesture leaves the press to the node.
+ boxStarts = false;
+ captured.mockClear();
+ press(60, 63, false);
+ expect(captured).toHaveBeenCalledTimes(1);
+ } finally {
+ captured.mockRestore();
+ act(() => root.unmount());
+ box.remove();
+ host.remove();
+ }
+});
diff --git a/packages/studio/src/components/editor/MotionPathOverlay.tsx b/packages/studio/src/components/editor/MotionPathOverlay.tsx
index b66c1361ba..64030d137d 100644
--- a/packages/studio/src/components/editor/MotionPathOverlay.tsx
+++ b/packages/studio/src/components/editor/MotionPathOverlay.tsx
@@ -10,6 +10,8 @@ import { parkPlayheadOnKeyframe } from "../../hooks/gsapDragCommit";
import { commitWholePropertyOffset } from "../../hooks/gsapWholePropertyOffsetCommit";
import { nearestPointOnPath, type MotionNodeRef } from "./motionPathGeometry";
import { editableAnimationId, selectorFor } from "./motionPathSelection";
+import { dotRadius, pressBelongsToLayer, pressSelectedLayer } from "./motionPathLayerNode";
+import { readGsapPositionFromIframe } from "../../hooks/gsapPositionDetection";
import { ACCENT, MotionPathNode } from "./MotionPathNode";
import {
KeyframeDiamondContextMenu,
@@ -310,6 +312,10 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({
if (!interactive) return;
if (e.button !== 0) return;
e.stopPropagation();
+ const live = readGsapPositionFromIframe(iframeRef.current, selectorFor(selection) ?? "");
+ const dotR = dotRadius(nodeR, ref.type === "keyframe" && ref.pct === activeKeyframePct);
+ if (pressBelongsToLayer(e, clientToComp(e), abs[index]!, dotR, live) && pressSelectedLayer(e))
+ return;
(e.target as Element).setPointerCapture(e.pointerId);
dragRef.current = {
index,
diff --git a/packages/studio/src/components/editor/domEditOverlayStartGesture.blocked.test.ts b/packages/studio/src/components/editor/domEditOverlayStartGesture.blocked.test.ts
new file mode 100644
index 0000000000..4a02bed8a0
--- /dev/null
+++ b/packages/studio/src/components/editor/domEditOverlayStartGesture.blocked.test.ts
@@ -0,0 +1,57 @@
+// @vitest-environment happy-dom
+import { expect, it, vi } from "vitest";
+import type { DomEditSelection } from "./domEditing";
+import { readTranslatePx } from "./plainTranslate";
+import { createDomEditOverlayGestureHandlers } from "./useDomEditOverlayGestures";
+
+vi.mock("./plainTranslate", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./plainTranslate")>()),
+ readTranslatePx: vi.fn(() => ({ x: Number.NaN, y: 0 })),
+}));
+
+it("a drag press the layer cannot take gets the notice, counts as handled, and leaves the box live", () => {
+ const element = document.body.appendChild(document.createElement("div"));
+ const ref = <T>(current: T) => ({ current });
+ const onBlockedMove = vi.fn();
+ const opts = {
+ selectionRef: ref({
+ element,
+ capabilities: { canApplyManualOffset: true },
+ } as unknown as DomEditSelection),
+ overlayRectRef: ref({ left: 0, top: 0, width: 240, height: 160, editScaleX: 1, editScaleY: 1 }),
+ boxRef: ref(document.createElement("div")),
+ overlayRef: ref(null),
+ iframeRef: ref(null),
+ gestureRef: ref(null),
+ rafPausedRef: ref(false),
+ onManualDragStartRef: ref(vi.fn()),
+ onBlockedMoveRef: ref(onBlockedMove),
+ onPathOffsetCommitRef: ref(vi.fn()),
+ snapGuidesRef: ref(null),
+ groupGestureRef: ref(null),
+ blockedMoveRef: ref(null),
+ setOverlayRect: vi.fn(),
+ suppressNextBoxClickRef: ref(false),
+ hoverSelectionRef: ref(null),
+ onCanvasMouseDown: vi.fn(),
+ };
+ const press = new PointerEvent("pointerdown", { cancelable: true });
+ const e = {
+ clientX: 10,
+ clientY: 10,
+ pointerId: 1,
+ button: 0,
+ preventDefault: () => press.preventDefault(),
+ stopPropagation() {},
+ currentTarget: { setPointerCapture() {} },
+ };
+ const handlers = createDomEditOverlayGestureHandlers(opts as never);
+ expect(handlers.startGesture("drag", e as never)).toBe(false);
+ expect(onBlockedMove).toHaveBeenCalledTimes(1);
+ expect(press.defaultPrevented).toBe(true);
+ // The release lands outside the box, so nothing would ever resume it.
+ expect(opts.rafPausedRef.current).toBe(false);
+ // Playback pauses before setup reads which timelines are running.
+ const [paused] = opts.onManualDragStartRef.current.mock.invocationCallOrder;
+ expect(paused).toBeLessThan(vi.mocked(readTranslatePx).mock.invocationCallOrder[0]!);
+});
diff --git a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts
index ea43a7aa41..f04f8cdb29 100644
--- a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts
+++ b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts
@@ -185,7 +185,6 @@ export function startGesture(
if (kind === "drag") {
opts.onManualDragStartRef.current?.();
- opts.rafPausedRef.current = true;
const result = createManualOffsetDragMember({
key: selectionCacheKey(sel),
selection: sel,
@@ -195,6 +194,7 @@ export function startGesture(
});
if (!result.ok) {
opts.onBlockedMoveRef.current(result.selection, result.reason);
+ e.preventDefault();
return false;
}
pathOffsetMember = result.member;
diff --git a/packages/studio/src/components/editor/motionPathGeometry.test.ts b/packages/studio/src/components/editor/motionPathGeometry.test.ts
index fc66966836..be5f3840a6 100644
--- a/packages/studio/src/components/editor/motionPathGeometry.test.ts
+++ b/packages/studio/src/components/editor/motionPathGeometry.test.ts
@@ -17,6 +17,16 @@ describe("buildMotionPathGeometry", () => {
]);
});
+ it("puts an axis the tween does not animate where GSAP renders it, a folded CSS translate", () => {
+ const read: ReadTween = {
+ keyframes: [
+ { percentage: 66.667, properties: { x: 60 } },
+ { percentage: 100, properties: { x: 120 } },
+ ],
+ };
+ expect(buildMotionPathGeometry(read, { x: 40, y: 30 })!.points).toBe("60,30 120,30");
+ });
+
it("preserves order and percentages for intermediate keyframes", () => {
const read: ReadTween = { keyframes: [kf(0, 0, 0), kf(50, 50, 90), kf(100, 100, 0)] };
const geo = buildMotionPathGeometry(read);
diff --git a/packages/studio/src/components/editor/motionPathGeometry.ts b/packages/studio/src/components/editor/motionPathGeometry.ts
index 0499fa2bb5..6cbda07ca2 100644
--- a/packages/studio/src/components/editor/motionPathGeometry.ts
+++ b/packages/studio/src/components/editor/motionPathGeometry.ts
@@ -78,7 +78,10 @@ export function nearestPointOnPath(
return best;
}
-export function buildMotionPathGeometry(read: ReadTween | null): MotionPathGeometry | null {
+export function buildMotionPathGeometry(
+ read: ReadTween | null,
+ base: { x: number; y: number } = { x: 0, y: 0 },
+): MotionPathGeometry | null {
if (!read) return null;
const isArc = Boolean(read.arcPath);
const nodes: MotionPathNode[] = [];
@@ -87,8 +90,8 @@ export function buildMotionPathGeometry(read: ReadTween | null): MotionPathGeome
// anchor. Arc waypoints always carry x/y (never filtered), so source index
// and node order stay aligned.
// Which axes does the tween animate at all? A single-axis tween (e.g.
- // `to({ x: -260 })`) only carries x; its y stays at the base (0, the GSAP
- // transform identity), so we default it and still draw a path. But if the tween
+ // `to({ x: -260 })`) only carries x; its y stays at `base`, GSAP's live y (a CSS
+ // translate it folded in, else 0), so we default it and still draw a path. But if the tween
// DOES animate an axis and a given keyframe omits it, that value is interpolated
// (not 0) and can't be placed here → skip that node (the prior behavior).
const finite = (v: unknown): v is number => typeof v === "number" && isFinite(v);
@@ -100,8 +103,8 @@ export function buildMotionPathGeometry(read: ReadTween | null): MotionPathGeome
if (tweenHasX && !finite(kf.properties.x)) return;
if (tweenHasY && !finite(kf.properties.y)) return;
nodes.push({
- x: tweenHasX ? (kf.properties.x as number) : 0,
- y: tweenHasY ? (kf.properties.y as number) : 0,
+ x: tweenHasX ? (kf.properties.x as number) : base.x,
+ y: tweenHasY ? (kf.properties.y as number) : base.y,
ref: isArc ? { type: "waypoint", index: i } : { type: "keyframe", pct: kf.percentage },
});
});
diff --git a/packages/studio/src/components/editor/motionPathLayerNode.test.ts b/packages/studio/src/components/editor/motionPathLayerNode.test.ts
new file mode 100644
index 0000000000..2d7b11e41f
--- /dev/null
+++ b/packages/studio/src/components/editor/motionPathLayerNode.test.ts
@@ -0,0 +1,82 @@
+// @vitest-environment happy-dom
+import { expect, it } from "vitest";
+import { pressBelongsToLayer, pressSelectedLayer } from "./motionPathLayerNode";
+
+// Keyframe nodes at x 60 and 120 (y 30), drawn from home (500, 400); dots of radius 6.
+const atLayer = { x: 60, y: 30, ax: 560, ay: 430 };
+const other = { x: 120, y: 30, ax: 620, ay: 430 };
+const live = { x: 60, y: 30 };
+
+const box = document.createElement("div");
+box.setAttribute("data-dom-edit-selection-box", "true");
+const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
+document.body.append(box, circle);
+
+/** A press on `circle` at (x, y), with `under` what the document hit-tests there. */
+function press(x: number, y: number, under: Element[]) {
+ document.elementsFromPoint = () => [circle, ...under];
+ return { currentTarget: circle, clientX: x, clientY: y } as unknown as React.PointerEvent;
+}
+
+it("the node GSAP renders the layer at is the layer, inside the box or out", () => {
+ expect(pressBelongsToLayer(press(562, 431, [box]), { x: 562, y: 431 }, atLayer, 6, live)).toBe(
+ true,
+ );
+ expect(pressBelongsToLayer(press(570, 440, []), { x: 570, y: 440 }, atLayer, 6, live)).toBe(true);
+});
+
+it("inside the layer's box another node's grab ring is the layer's; its dot stays the node's", () => {
+ expect(pressBelongsToLayer(press(610, 430, [box]), { x: 610, y: 430 }, other, 6, live)).toBe(
+ true,
+ );
+ expect(pressBelongsToLayer(press(617, 430, [box]), { x: 617, y: 430 }, other, 6, live)).toBe(
+ false,
+ );
+});
+
+it("outside the layer's box a node's whole grab ring is the node's", () => {
+ expect(pressBelongsToLayer(press(610, 430, []), { x: 610, y: 430 }, other, 6, live)).toBe(false);
+ expect(pressBelongsToLayer(press(610, 430, [box]), { x: 610, y: 430 }, other, 6, null)).toBe(
+ true,
+ );
+});
+
+it("hands a press to the selected layer's box with its pointer and position", () => {
+ const got: number[][] = [];
+ const listen = (e: Event) => {
+ const p = e as PointerEvent;
+ got.push([p.pointerId, p.clientX, p.clientY, p.button]);
+ e.preventDefault();
+ };
+ box.addEventListener("pointerdown", listen);
+ const nativeEvent = new PointerEvent("pointerdown", {
+ pointerId: 7,
+ clientX: 12,
+ clientY: 34,
+ button: 0,
+ bubbles: true,
+ cancelable: true,
+ });
+ const down = { currentTarget: circle, nativeEvent } as unknown as React.PointerEvent;
+ expect(pressSelectedLayer(down)).toBe(true);
+ expect(got).toEqual([[7, 12, 34, 0]]);
+ box.removeEventListener("pointerdown", listen);
+ box.remove();
+ expect(pressSelectedLayer(down)).toBe(false);
+ document.body.append(box);
+});
+
+it("keeps the press when the box does not start a gesture with it, or takes no pointer", () => {
+ let got = 0;
+ const listen = () => void got++;
+ box.addEventListener("pointerdown", listen);
+ const nativeEvent = new PointerEvent("pointerdown", { bubbles: true, cancelable: true });
+ const down = { currentTarget: circle, nativeEvent } as unknown as React.PointerEvent;
+ expect(pressSelectedLayer(down)).toBe(false);
+ expect(got).toBe(1);
+ box.style.pointerEvents = "none";
+ expect(pressSelectedLayer(down)).toBe(false);
+ expect(got).toBe(1);
+ box.style.pointerEvents = "";
+ box.removeEventListener("pointerdown", listen);
+});
diff --git a/packages/studio/src/components/editor/motionPathLayerNode.ts b/packages/studio/src/components/editor/motionPathLayerNode.ts
new file mode 100644
index 0000000000..dd49d4712a
--- /dev/null
+++ b/packages/studio/src/components/editor/motionPathLayerNode.ts
@@ -0,0 +1,28 @@
+type Point = { x: number; y: number };
+type DrawnNode = Point & { ax: number; ay: number };
+
+const LAYER_BOX = '[data-dom-edit-selection-box="true"]';
+
+/** How far a node's dot reaches; a selected node draws it larger. */
+export const dotRadius = (r: number, selected: boolean) => (selected ? r * 1.5 : r);
+
+/** A press on the layer's own node, or in its box but off a node's dot, belongs to the layer. */
+export function pressBelongsToLayer(
+ e: React.PointerEvent,
+ point: Point,
+ pressed: DrawnNode,
+ dotR: number,
+ live: Point | null,
+): boolean {
+ if (live && Math.abs(pressed.x - live.x) < 0.5 && Math.abs(pressed.y - live.y) < 0.5) return true;
+ const hits = e.currentTarget.ownerDocument.elementsFromPoint(e.clientX, e.clientY);
+ const inBox = hits.some((el) => el.closest(LAYER_BOX));
+ return inBox && Math.hypot(point.x - pressed.ax, point.y - pressed.ay) > dotR;
+}
+
+/** Hands a press to the selected layer's box; true when the box started a gesture with it. */
+export function pressSelectedLayer(e: React.PointerEvent): boolean {
+ const box = e.currentTarget.ownerDocument.querySelector(LAYER_BOX);
+ if (!box || getComputedStyle(box).pointerEvents === "none") return false;
+ return !box.dispatchEvent(new PointerEvent("pointerdown", e.nativeEvent));
+}
diff --git a/packages/studio/src/components/editor/useDomEditNudge.test.tsx b/packages/studio/src/components/editor/useDomEditNudge.test.tsx
index af77cdcbfd..c2c467261d 100644
--- a/packages/studio/src/components/editor/useDomEditNudge.test.tsx
+++ b/packages/studio/src/components/editor/useDomEditNudge.test.tsx
@@ -34,9 +34,11 @@ let flushNudge = () => {};
function Harness({
selection,
onPathOffsetCommit,
+ onManualDragStart = () => {},
}: {
selection: DomEditSelection | null;
onPathOffsetCommit: UseDomEditNudgeParams["onPathOffsetCommitRef"]["current"];
+ onManualDragStart?: () => void;
}) {
flushNudge = useDomEditNudge({
selection,
@@ -48,7 +50,7 @@ function Harness({
gestureRef: makeRef(null),
groupGestureRef: makeRef(null),
blockedMoveRef: makeRef(null),
- onManualDragStartRef: makeRef(() => {}),
+ onManualDragStartRef: makeRef(onManualDragStart),
onBlockedMoveRef: makeRef(() => {}),
onPathOffsetCommitRef: makeRef(onPathOffsetCommit),
onGroupPathOffsetCommitRef: makeRef(async () => {}),
@@ -340,6 +342,56 @@ describe("useDomEditNudge carries the route its press chose", () => {
});
});
+describe("useDomEditNudge pauses playback before it snapshots the timelines", () => {
+ let reactRoot: ReturnType<typeof createRoot> | null = null;
+ const pause = vi.fn();
+ const mount = (selection: DomEditSelection | null) => {
+ reactRoot = createRoot(document.createElement("div"));
+ act(() => {
+ reactRoot!.render(
+ React.createElement(Harness, {
+ selection,
+ onPathOffsetCommit: vi.fn(),
+ onManualDragStart: pause,
+ }),
+ );
+ });
+ };
+ beforeEach(() => {
+ vi.useFakeTimers();
+ __resetForTests();
+ pause.mockReset();
+ });
+ afterEach(() => {
+ act(() => reactRoot?.unmount());
+ reactRoot = null;
+ document.body.innerHTML = "";
+ vi.useRealTimers();
+ delete (window as { __timelines?: unknown }).__timelines;
+ });
+
+ it("does not resume a timeline the playback pause stopped", () => {
+ let playing = true;
+ const root = { pause: () => void (playing = false), paused: () => !playing };
+ (window as { __timelines?: unknown }).__timelines = { root };
+ pause.mockImplementation(root.pause);
+ const element = document.body.appendChild(document.createElement("div"));
+ mount(makeSelection("Dot", element));
+
+ act(() => dispatchArrowRight());
+
+ expect(element.hasAttribute("data-hf-drag-paused-timelines")).toBe(false);
+ });
+
+ it("leaves playback alone when no layer can move", () => {
+ mount(null);
+
+ act(() => dispatchArrowRight());
+
+ expect(pause).not.toHaveBeenCalled();
+ });
+});
+
describe("useDomEditNudge — undo right after a burst", () => {
it("undo's drain commits a burst still inside its debounce and waits for its save", async () => {
__resetForTests();
diff --git a/packages/studio/src/components/editor/useDomEditNudge.ts b/packages/studio/src/components/editor/useDomEditNudge.ts
index b1dae8ffb1..ff09f0bff8 100644
--- a/packages/studio/src/components/editor/useDomEditNudge.ts
+++ b/packages/studio/src/components/editor/useDomEditNudge.ts
@@ -212,6 +212,8 @@ export function useDomEditNudge(params: UseDomEditNudgeParams): { flushNudge: ()
? resolveGroupNudgeTargets(groupItems)
: resolveSingleNudgeTarget(p.selectionRef.current, p.overlayRectRef.current);
if (!targets) return null;
+ // Same side effect a drag start has (pauses preview playback).
+ p.onManualDragStartRef.current?.();
const members: ManualOffsetDragMember[] = [];
for (const target of targets) {
const result = createManualOffsetDragMember({ ...target, gesture: "nudge" });
@@ -223,8 +225,6 @@ export function useDomEditNudge(params: UseDomEditNudgeParams): { flushNudge: ()
members.push(result.member);
}
if (members.length === 0) return null;
- // Same side effect a drag start has (pauses preview playback).
- p.onManualDragStartRef.current?.();
const edit = beginStudioPendingEdit(manualOffsetMoveRevert(members));
return { members, isGroup, accum: { x: 0, y: 0 }, timer: null, edit };
};
diff --git a/packages/studio/src/components/editor/useMotionPathData.test.tsx b/packages/studio/src/components/editor/useMotionPathData.test.tsx
index 84c666bbaa..e0869604ba 100644
--- a/packages/studio/src/components/editor/useMotionPathData.test.tsx
+++ b/packages/studio/src/components/editor/useMotionPathData.test.tsx
@@ -8,6 +8,12 @@ import { usePlayerStore } from "../../player/store/playerStore";
Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);
+const runtime = vi.hoisted(() => ({ read: null as unknown, gsapPosition: null as unknown }));
+vi.mock("../../hooks/gsapRuntimeKeyframes", () => ({ readRuntimeKeyframes: () => runtime.read }));
+vi.mock("../../hooks/gsapPositionDetection", () => ({
+ readGsapPositionFromIframe: () => runtime.gsapPosition,
+}));
+
const originalRaf = window.requestAnimationFrame;
let frames: Array<() => void> = [];
const runFrames = (count: number) => {
@@ -36,6 +42,30 @@ afterEach(() => {
vi.useRealTimers();
usePlayerStore.setState({ previewBooted: false, motionPathArmed: false });
document.body.innerHTML = "";
+ runtime.read = runtime.gsapPosition = null;
+});
+
+it("draws an axis the tween leaves alone where GSAP renders it, so the playhead node sits on the layer", () => {
+ runtime.read = {
+ keyframes: [
+ { percentage: 66.667, properties: { x: 60 } },
+ { percentage: 100, properties: { x: 120 } },
+ ],
+ };
+ runtime.gsapPosition = { x: 60, y: 30 };
+ let points: string | undefined;
+ function Probe() {
+ const ref = useRef(document.createElement("iframe"));
+ points = useMotionPathData(ref, "#box").geometry?.points;
+ return null;
+ }
+ const root = createRoot(document.body.appendChild(document.createElement("div")));
+ try {
+ act(() => root.render(<Probe />));
+ expect(points).toBe("60,30 120,30");
+ } finally {
+ act(() => root.unmount());
+ }
});
it("reads no layout per frame until there is a path or a create ring to draw", () => {
diff --git a/packages/studio/src/components/editor/useMotionPathData.ts b/packages/studio/src/components/editor/useMotionPathData.ts
index 52e5e1c3e0..db1b1a595f 100644
--- a/packages/studio/src/components/editor/useMotionPathData.ts
+++ b/packages/studio/src/components/editor/useMotionPathData.ts
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import { readRuntimeKeyframes } from "../../hooks/gsapRuntimeKeyframes";
+import { readGsapPositionFromIframe } from "../../hooks/gsapPositionDetection";
import { isElementVisibleForOverlay } from "./domEditOverlayGeometry";
import { buildMotionPathGeometry, type MotionPathGeometry } from "./motionPathGeometry";
import { subscribeOverlayFrame } from "./overlayFrameLoop";
@@ -169,7 +170,8 @@ export function useMotionPathData(
const recompute = () => {
// Position-only: never let a co-located size/scale tween shadow the path.
const read = readRuntimeKeyframes(iframeRef.current, selector, undefined, ["x", "y"]);
- const next = buildMotionPathGeometry(read);
+ const base = read ? readGsapPositionFromIframe(iframeRef.current, selector) : null;
+ const next = buildMotionPathGeometry(read, base ?? undefined);
setGeometry((prev) =>
prev?.points === next?.points && prev?.kind === next?.kind ? prev : next,
);
diff --git a/packages/studio/src/hooks/gsapValueAtPlayhead.test.ts b/packages/studio/src/hooks/gsapValueAtPlayhead.test.ts
index e2f5932fe4..ae5e46442c 100644
--- a/packages/studio/src/hooks/gsapValueAtPlayhead.test.ts
+++ b/packages/studio/src/hooks/gsapValueAtPlayhead.test.ts
@@ -527,9 +527,52 @@ describe("planValueAtPlayhead", () => {
]);
});
- it("refuses keyframes eased as a whole, whose segment curves it cannot keep", () => {
- const anim = { ...kf([{ percentage: 100, properties: { x: 20 } }]), ease: "power2.out" };
- expect(plan({ anim, values: { x: 5 } })).toEqual({ ok: false, reason: "eased-keyframes" });
+ describe("keyframes eased as a whole", () => {
+ const eased = {
+ ...kf([
+ { percentage: 0, properties: { x: 0 } },
+ { percentage: 100, properties: { x: 20 } },
+ ]),
+ ease: "power2.out",
+ };
+
+ it("changes the keyframe under the playhead and writes the ease back", () => {
+ const result = plan({ anim: eased, at: { time: 4 }, values: { x: 5 } });
+ expect(result.ok && result.mutation.keyframes.map((k) => k.properties.x)).toEqual([0, 5]);
+ expect(result.ok && result.mutation.ease).toBe("power2.out");
+ });
+
+ it("writes the keyframes' own ease as the tween's, as GSAP prefers it", () => {
+ const anim = { ...eased, keyframes: { ...eased.keyframes!, ease: "expo.in" } };
+ const result = plan({ anim, at: { time: 0 }, values: { x: 5 } });
+ expect(result.ok && result.mutation.ease).toBe("expo.in");
+ });
+
+ it("refuses an inner keyframe, which the ease shows at another time", () => {
+ const anim = {
+ ...kf([
+ { percentage: 0, properties: { x: 0 } },
+ { percentage: 50, properties: { x: 100 } },
+ { percentage: 100, properties: { x: 300 } },
+ ]),
+ ease: "power2.out",
+ };
+ expect(plan({ anim, at: { time: 2 }, values: { x: 5 } })).toEqual({
+ ok: false,
+ reason: "eased-keyframes",
+ });
+ });
+
+ it("refuses to add a keyframe, whose time the ease would move", () => {
+ expect(plan({ anim: eased, at: { time: 2 }, values: { x: 5 } })).toEqual({
+ ok: false,
+ reason: "eased-keyframes",
+ });
+ expect(plan({ anim: eased, at: { time: 6 }, values: { x: 5 } })).toEqual({
+ ok: false,
+ reason: "eased-keyframes",
+ });
+ });
});
});
diff --git a/packages/studio/src/hooks/gsapValueAtPlayhead.ts b/packages/studio/src/hooks/gsapValueAtPlayhead.ts
index 87c8fc701a..dc770c1c9b 100644
--- a/packages/studio/src/hooks/gsapValueAtPlayhead.ts
+++ b/packages/studio/src/hooks/gsapValueAtPlayhead.ts
@@ -55,6 +55,7 @@ export type PlayheadEditPlan =
position: number;
duration: number;
keyframes: Keyframe[];
+ ease?: string;
easeEach?: string;
};
/** A keyframe was added, not only changed: keyframe usage counts it as an add. */
@@ -70,6 +71,7 @@ const isLinear = (ease: string | undefined) => !ease || ease === "none" || ease
interface Normalized {
keyframes: Keyframe[];
+ runEase?: string;
easeEach?: string;
}
@@ -82,10 +84,10 @@ function normalize(edit: PlayheadEdit): Normalized | { reason: PlayheadEditRefus
const { anim } = edit;
const data = anim.keyframes;
if (data) {
- if (!isLinear(anim.ease) || !isLinear(data.ease)) return { reason: "eased-keyframes" };
if (data.format === "simple-array") return { reason: "simple-array-keyframes" };
const arrayStep = data.format === "object-array";
return {
+ runEase: data.ease ?? anim.ease,
keyframes: data.keyframes.map((kf) => ({
...kf,
properties: { ...kf.properties },
@@ -126,8 +128,11 @@ function valueAt(keyframes: Keyframe[], prop: string, side: "first" | "last") {
return kf ? { percentage: kf.percentage, value: kf.properties[prop]! } : null;
}
+const keyframeAt = (keyframes: Keyframe[], percentage: number) =>
+ keyframes.find((kf) => Math.abs(kf.percentage - percentage) <= KEYFRAME_PCT_MATCH);
+
function upsert(keyframes: Keyframe[], percentage: number, properties: Props, ease?: string) {
- const hit = keyframes.find((kf) => Math.abs(kf.percentage - percentage) <= KEYFRAME_PCT_MATCH);
+ const hit = keyframeAt(keyframes, percentage);
if (hit) {
Object.assign(hit.properties, properties);
return hit;
@@ -195,14 +200,18 @@ export function planValueAtPlayhead(edit: PlayheadEdit): PlayheadEditPlan {
"percentage" in edit.at
? edit.at.percentage
: roundPct(((edit.at.time - start) / duration) * 100);
+ const eased = !isLinear(norm.runEase);
if (pct >= -KEYFRAME_PCT_MATCH && pct <= 100 + KEYFRAME_PCT_MATCH) {
const at = Math.min(100, Math.max(0, pct));
+ const hit = keyframeAt(keyframes, at);
+ if (eased && hit?.percentage !== 0 && hit?.percentage !== 100) return refuse("eased-keyframes");
const next = [...keyframes]
.sort((a, b) => a.percentage - b.percentage)
.find((kf) => kf.percentage > at + KEYFRAME_PCT_MATCH);
// The new keyframe splits next's segment, so it takes next's ease.
upsert(keyframes, at, { ...values }, next?.ease);
} else {
+ if (eased) return refuse("eased-keyframes");
const time = (edit.at as { time: number }).time;
const before = time < start;
const held = heldEnds(norm, before ? "start" : "end", edit.implicitEndValue, backfilled);
@@ -232,6 +241,7 @@ export function planValueAtPlayhead(edit: PlayheadEdit): PlayheadEditPlan {
position: roundTo3(position),
duration: roundTo3(span),
keyframes,
+ ...(norm.runEase ? { ease: norm.runEase } : {}),
...(norm.easeEach ? { easeEach: norm.easeEach } : {}),
},
added: keyframes.length > authored,