Skip to content

Write HTML. Render video. Built for agents.

fix(studio): moving one word moves only that word, not every word sharing its animation (#4705)

Miguel Ángel5606b31020e1
diff --git a/packages/studio/src/components/editor/MotionPathOverlay.tsx b/packages/studio/src/components/editor/MotionPathOverlay.tsx
index df1faabc06..eeaa18824b 100644
--- a/packages/studio/src/components/editor/MotionPathOverlay.tsx
+++ b/packages/studio/src/components/editor/MotionPathOverlay.tsx
@@ -127,7 +127,11 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({
// just in render, after the early returns) so the park-timer cleanup can key on
// it: a pending park seek belongs to the OLD animation, so firing it after the
// active animation changed would jump the playhead onto a stale keyframe.
- const animId = editableAnimationId(selectedGsapAnimations ?? [], geometry?.kind ?? "linear");
+ const animId = editableAnimationId(
+ selectedGsapAnimations ?? [],
+ geometry?.kind ?? "linear",
+ selection,
+ );
// Clear the debounced park timer on unmount AND whenever the active animation id
// changes — not unmount-only, or a queued seek from the previous selection still
// fires against the new one.
diff --git a/packages/studio/src/components/editor/commitPreflightHandles.test.tsx b/packages/studio/src/components/editor/commitPreflightHandles.test.tsx
index 0ea8c5f722..aa48cdd01b 100644
--- a/packages/studio/src/components/editor/commitPreflightHandles.test.tsx
+++ b/packages/studio/src/components/editor/commitPreflightHandles.test.tsx
@@ -377,45 +377,32 @@ describe("handles follow what Studio would commit", () => {
expect(flags(seen.selection)[0]).toBe(true);
});
- it("refuses a group move carried by one shared tween, while a single member stays movable", async () => {
+ // The per-element left/top channel supersedes the old refusal: each member saves its own move.
+ it("lets a group move carried by one shared tween through as each member's own offset", async () => {
const dots = [element("dot-1", "dot"), element("dot-2", "dot")];
const preview = livePreview(dots, { y: 40 });
const stagger = tween({ y: 40 }, { targetSelector: ".dot", method: "from" } as never);
const [a, b] = dots.map(resolved);
- const { seen, overlay, spies, render } = await select([stagger], {
+ const { seen, overlay, spies } = await select([stagger], {
selection: a!,
groups: [a!, b!],
preview,
});
- expect(seen.groups.map((s) => flags(s)[0])).toEqual([false, false]);
- expect(seen.groups[0]?.capabilities.reasonIfDisabled).toBe(
- GSAP_EDIT_BLOCK_COPY["source-uneditable"],
- );
+ expect(seen.groups.map((s) => flags(s)[0])).toEqual([true, true]);
fire(overlay().querySelector(BOX)!, "pointerdown", { clientX: 150, clientY: 150 });
- expect(spies.onBlockedMove).toHaveBeenCalledTimes(1);
- const commitList = getAnimationsForElement(
- [stagger],
- { id: "dot-1", selector: "#dot-1" },
- dots[0],
- );
+ expect(spies.onBlockedMove).not.toHaveBeenCalled();
const groupPreflight = { preflightOnly: true, group: true };
const commit = tryGsapDragIntercept(
a!,
{ x: 0, y: 0 },
- commitList,
+ [stagger],
preview,
vi.fn(),
undefined,
groupPreflight,
);
- expect(await commit).toMatchObject({
- status: "blocked",
- detail: "live-position-no-source-tween",
- });
-
- render({ selection: a!, preview });
- expect(flags(seen.selection)[0]).toBe(true);
+ expect(await commit).toEqual({ status: "element-offset" });
});
it("toasts once on the primary press of a blocked element, before any travel", async () => {
diff --git a/packages/studio/src/components/editor/elementPositionOffset.test.ts b/packages/studio/src/components/editor/elementPositionOffset.test.ts
new file mode 100644
index 0000000000..de11b22bb0
--- /dev/null
+++ b/packages/studio/src/components/editor/elementPositionOffset.test.ts
@@ -0,0 +1,62 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import { applyElementPositionOffset } from "./elementPositionOffset";
+
+// jsdom has no layout: offsets follow left/top unless the box is anchored elsewhere.
+function word(style: string, anchoredRight = false): HTMLElement {
+ const el = document.createElement("span");
+ el.setAttribute("style", style);
+ const px = (v: string) => Number.parseFloat(v) || 0;
+ Object.defineProperties(el, {
+ offsetLeft: { get: () => (anchoredRight ? 500 : 100 + px(el.style.left)) },
+ offsetTop: { get: () => 200 + px(el.style.top) },
+ offsetWidth: { get: () => 80 },
+ offsetHeight: { get: () => 40 },
+ });
+ el.setAttribute("data-hf-drag-initial-offset-x", "0");
+ el.setAttribute("data-hf-drag-initial-offset-y", "0");
+ document.body.append(el);
+ return el;
+}
+
+describe("applyElementPositionOffset", () => {
+ it("persists position for a static word the Layers panel lifted to relative", () => {
+ const el = word("position: relative");
+ el.setAttribute("data-hf-reveal-prior-pos", "static");
+ expect(applyElementPositionOffset(el, { x: 40, y: 20 })).toEqual([
+ { type: "inline-style", property: "position", value: "relative" },
+ { type: "inline-style", property: "left", value: "40px" },
+ { type: "inline-style", property: "top", value: "20px" },
+ ]);
+ expect(el.hasAttribute("data-hf-reveal-prior-pos")).toBe(false);
+ });
+
+ it("names percent positioning as the reason it refuses", () => {
+ const el = word("position: relative; left: 10%; top: 0px");
+ expect(applyElementPositionOffset(el, { x: 40, y: 20 })).toBe("percent");
+ expect(el.style.left).toBe("10%");
+ });
+
+ it("moves a static element by relative left/top", () => {
+ const el = word("");
+ expect(applyElementPositionOffset(el, { x: 40, y: 20 })).toEqual([
+ { type: "inline-style", property: "position", value: "relative" },
+ { type: "inline-style", property: "left", value: "40px" },
+ { type: "inline-style", property: "top", value: "20px" },
+ ]);
+ });
+
+ it("adds to left/top the element already has, so a second drag accumulates", () => {
+ const el = word("position: relative; left: 40px; top: 20px");
+ expect(applyElementPositionOffset(el, { x: 40, y: 20 })).toEqual([
+ { type: "inline-style", property: "left", value: "80px" },
+ { type: "inline-style", property: "top", value: "40px" },
+ ]);
+ });
+
+ it("refuses, leaving the element untouched, when left does not move the box", () => {
+ const el = word("position: absolute; right: 30px", true);
+ expect(applyElementPositionOffset(el, { x: 40, y: 20 })).toBe("anchored");
+ expect([el.style.left, el.style.top, el.style.right]).toEqual(["", "", "30px"]);
+ });
+});
diff --git a/packages/studio/src/components/editor/elementPositionOffset.ts b/packages/studio/src/components/editor/elementPositionOffset.ts
new file mode 100644
index 0000000000..9b68e8fc22
--- /dev/null
+++ b/packages/studio/src/components/editor/elementPositionOffset.ts
@@ -0,0 +1,64 @@
+import type { PatchOperation } from "../../utils/sourcePatcher";
+import { LAYER_REVEAL_PRIOR_POSITION_ATTR } from "../../player/lib/timelineElementHelpers";
+
+interface LayoutBox {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+}
+
+const layoutBox = (el: HTMLElement): LayoutBox => ({
+ left: el.offsetLeft,
+ top: el.offsetTop,
+ width: el.offsetWidth,
+ height: el.offsetHeight,
+});
+
+function readDragStart(el: HTMLElement, axis: "x" | "y"): number {
+ const value = Number.parseFloat(el.getAttribute(`data-hf-drag-initial-offset-${axis}`) ?? "");
+ return Number.isFinite(value) ? value : 0;
+}
+
+export type ElementOffsetRefusal = "percent" | "anchored";
+
+/** Moves one element by adding to its own `left`/`top` (GSAP never parses them), or
+ * names why not, leaving the element untouched. */
+export function applyElementPositionOffset(
+ el: HTMLElement,
+ gestureOffset: { x: number; y: number },
+): PatchOperation[] | ElementOffsetRefusal {
+ const cs = el.ownerDocument.defaultView?.getComputedStyle(el);
+ if (!cs) return "anchored";
+ const dx = Math.round(gestureOffset.x - readDragStart(el, "x"));
+ const dy = Math.round(gestureOffset.y - readDragStart(el, "y"));
+ // A Layers-panel pick lifts a static element to relative for display only.
+ const lifted = el.getAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR) === "static";
+ const isStatic = lifted || !/^(relative|absolute|fixed|sticky)$/.test(cs.position);
+ if (!isStatic && (cs.left.endsWith("%") || cs.top.endsWith("%"))) return "percent";
+ const baseLeft = isStatic ? 0 : Number.parseFloat(cs.left) || 0;
+ const baseTop = isStatic ? 0 : Number.parseFloat(cs.top) || 0;
+ const previous = { position: el.style.position, left: el.style.left, top: el.style.top };
+ const before = layoutBox(el);
+ if (isStatic) el.style.position = "relative";
+ el.style.left = `${Math.round(baseLeft) + dx}px`;
+ el.style.top = `${Math.round(baseTop) + dy}px`;
+ const after = layoutBox(el);
+ const shiftedExactly =
+ Math.abs(after.left - before.left - dx) <= 1 &&
+ Math.abs(after.top - before.top - dy) <= 1 &&
+ Math.abs(after.width - before.width) <= 1 &&
+ Math.abs(after.height - before.height) <= 1;
+ if (!shiftedExactly) {
+ Object.assign(el.style, previous);
+ return "anchored";
+ }
+ if (lifted) el.removeAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR);
+ return [
+ ...(isStatic
+ ? [{ type: "inline-style", property: "position", value: "relative" } as const]
+ : []),
+ { type: "inline-style", property: "left", value: el.style.left },
+ { type: "inline-style", property: "top", value: el.style.top },
+ ];
+}
diff --git a/packages/studio/src/components/editor/motionPathCommit.test.ts b/packages/studio/src/components/editor/motionPathCommit.test.ts
index 5eae75de99..1b91c20c21 100644
--- a/packages/studio/src/components/editor/motionPathCommit.test.ts
+++ b/packages/studio/src/components/editor/motionPathCommit.test.ts
@@ -1,3 +1,4 @@
+// @vitest-environment jsdom
import { describe, it, expect, vi } from "vitest";
import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser";
import { editableAnimationId } from "./motionPathSelection";
@@ -19,10 +20,13 @@ const anim = (over: Partial<GsapAnimation>): GsapAnimation =>
...over,
}) as GsapAnimation;
+// The element the default `#el` tweens target.
+const elSel = { id: "el" } as never;
+
describe("editableAnimationId", () => {
it("picks the arc animation for an arc path", () => {
const arc = anim({ id: "arc1", arcPath: { enabled: true, autoRotate: false, segments: [] } });
- expect(editableAnimationId([anim({ id: "other" }), arc], "arc")).toBe("arc1");
+ expect(editableAnimationId([anim({ id: "other" }), arc], "arc", elSel)).toBe("arc1");
});
it("picks a position-keyframe animation for a linear path", () => {
@@ -34,7 +38,7 @@ describe("editableAnimationId", () => {
keyframes: [{ percentage: 0, properties: { x: 0, y: 0 } }],
} as never,
});
- expect(editableAnimationId([kf], "linear")).toBe("kf1");
+ expect(editableAnimationId([kf], "linear", elSel)).toBe("kf1");
});
it("returns null for dynamic (unresolved) tweens — read-only", () => {
@@ -43,7 +47,7 @@ describe("editableAnimationId", () => {
arcPath: { enabled: true, autoRotate: false, segments: [] },
hasUnresolvedKeyframes: true,
});
- expect(editableAnimationId([dyn], "arc")).toBeNull();
+ expect(editableAnimationId([dyn], "arc", elSel)).toBeNull();
});
it("returns null for non-literal (helper) provenance — read-only", () => {
@@ -52,11 +56,27 @@ describe("editableAnimationId", () => {
arcPath: { enabled: true, autoRotate: false, segments: [] },
provenance: { kind: "helper" } as never,
});
- expect(editableAnimationId([helper], "arc")).toBeNull();
+ expect(editableAnimationId([helper], "arc", elSel)).toBeNull();
+ });
+
+ it("leaves a tween that also moves the element's siblings read-only", () => {
+ document.body.innerHTML = `<span class="w" data-hf-id="w0">How</span><span class="w" data-hf-id="w1">we</span>`;
+ const word = document.querySelector<HTMLElement>('[data-hf-id="w0"]')!;
+ const stagger = anim({
+ id: "stagger",
+ targetSelector: ".w",
+ propertyGroup: "position",
+ keyframes: {
+ format: "percentage",
+ keyframes: [{ percentage: 0, properties: { x: 0, y: 0 } }],
+ } as never,
+ });
+ const wordSel = { selector: ".w", selectorIndex: 0, hfId: "w0", element: word } as never;
+ expect(editableAnimationId([stagger], "linear", wordSel)).toBeNull();
});
it("returns null when nothing matches", () => {
- expect(editableAnimationId([anim({ id: "x" })], "linear")).toBeNull();
+ expect(editableAnimationId([anim({ id: "x" })], "linear", elSel)).toBeNull();
});
});
diff --git a/packages/studio/src/components/editor/motionPathSelection.ts b/packages/studio/src/components/editor/motionPathSelection.ts
index c869ace83d..cbcff804a1 100644
--- a/packages/studio/src/components/editor/motionPathSelection.ts
+++ b/packages/studio/src/components/editor/motionPathSelection.ts
@@ -5,7 +5,7 @@
*/
import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser";
import type { DomEditSelection } from "./domEditing";
-import { writeTargetSelector } from "../../hooks/gsapShared";
+import { tweenTargetsElement, writeTargetSelector } from "../../hooks/gsapShared";
/**
* The selector the overlay both MEASURES the element by and authors a new
@@ -24,13 +24,20 @@ export function selectorFor(sel: DomEditSelection | null): string | null {
/** The animation whose path is editable on-canvas: literal, statically resolved,
* and matching the rendered geometry kind. Returns null when the path can only
- * be displayed (dynamic/helper tweens) — those nodes stay read-only. */
+ * be displayed (dynamic/helper tweens, or a tween that also moves other
+ * elements) — those nodes stay read-only and a press drags the element itself. */
export function editableAnimationId(
animations: GsapAnimation[],
kind: "linear" | "arc",
+ sel: DomEditSelection | null,
): string | null {
+ const own = selectorFor(sel);
const ok = (a: GsapAnimation) =>
- !a.hasUnresolvedKeyframes && !a.hasUnresolvedSelector && !a.provenance;
+ !a.hasUnresolvedKeyframes &&
+ !a.hasUnresolvedSelector &&
+ !a.provenance &&
+ !!own &&
+ tweenTargetsElement(a.targetSelector, own, sel?.element);
if (kind === "arc") return animations.find((a) => a.arcPath?.enabled && ok(a))?.id ?? null;
const a = animations.find(
(anim) =>
diff --git a/packages/studio/src/components/editor/useLayerRevealOverride.test.ts b/packages/studio/src/components/editor/useLayerRevealOverride.test.ts
index b761211bd7..52208d6700 100644
--- a/packages/studio/src/components/editor/useLayerRevealOverride.test.ts
+++ b/packages/studio/src/components/editor/useLayerRevealOverride.test.ts
@@ -56,6 +56,14 @@ describe("liftElementToTop / restoreLiftedElement", () => {
expect(el.style.zIndex).toBe("");
});
+ it("keeps a position a move authored while the element was lifted", () => {
+ const el = makeEl();
+ const lift = liftElementToTop(el)!;
+ el.removeAttribute("data-hf-reveal-prior-pos");
+ restoreLiftedElement(el, lift);
+ expect(el.style.position).toBe("relative");
+ });
+
it("a z-reorder commit consumes the lift: restore becomes a no-op", () => {
const el = makeEl("3", "absolute");
const lift = liftElementToTop(el)!;
diff --git a/packages/studio/src/components/editor/useLayerRevealOverride.ts b/packages/studio/src/components/editor/useLayerRevealOverride.ts
index 2dd481f3a4..792d7ca39d 100644
--- a/packages/studio/src/components/editor/useLayerRevealOverride.ts
+++ b/packages/studio/src/components/editor/useLayerRevealOverride.ts
@@ -271,12 +271,13 @@ export function restoreLiftedElement(element: HTMLElement, lift: RevealLift): vo
}
return;
}
+ const positionStillLifted = element.hasAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR);
element.removeAttribute(LAYER_REVEAL_PRIOR_Z_ATTR);
element.removeAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR);
if (element.style.zIndex === LAYER_REVEAL_LIFT_Z) {
restoreInline(element, "z-index", lift.priors.zIndex);
}
- if (lift.positionLifted && element.style.position === "relative") {
+ if (lift.positionLifted && positionStillLifted && element.style.position === "relative") {
restoreInline(element, "position", lift.priors.position);
}
}
diff --git a/packages/studio/src/hooks/domEditPersistFailure.ts b/packages/studio/src/hooks/domEditPersistFailure.ts
index 7e04e6f75b..d1aaa31344 100644
--- a/packages/studio/src/hooks/domEditPersistFailure.ts
+++ b/packages/studio/src/hooks/domEditPersistFailure.ts
@@ -46,6 +46,13 @@ function getSelectionLabel(selection: DomEditPersistFailureSelection): string {
return selection.label || selection.selector || selection.id || "this element";
}
+export function wasAlreadyToasted(error: unknown): boolean {
+ return (
+ (error instanceof DomEditPersistUnsafeValueError || error instanceof StudioSaveHttpError) &&
+ error.alreadyToasted
+ );
+}
+
export function reportDomEditPersistFailure(
selection: DomEditPersistFailureSelection,
operations: PatchOperation[],
@@ -59,12 +66,7 @@ export function reportDomEditPersistFailure(
error: detail,
});
- const wasAlreadyToasted =
- (error instanceof DomEditPersistUnsafeValueError || error instanceof StudioSaveHttpError) &&
- error.alreadyToasted;
- if (wasAlreadyToasted) {
- return;
- }
+ if (wasAlreadyToasted(error)) return;
showToast(`Couldn't save "${getSelectionLabel(selection)}": ${detail}`, "error");
}
diff --git a/packages/studio/src/hooks/elementOffsetStager.ts b/packages/studio/src/hooks/elementOffsetStager.ts
new file mode 100644
index 0000000000..00397e7c7d
--- /dev/null
+++ b/packages/studio/src/hooks/elementOffsetStager.ts
@@ -0,0 +1,65 @@
+import { getDomEditTargetKey, type DomEditSelection } from "../components/editor/domEditing";
+import {
+ applyElementPositionOffset,
+ type ElementOffsetRefusal,
+} from "../components/editor/elementPositionOffset";
+import { LAYER_REVEAL_PRIOR_POSITION_ATTR } from "../player/lib/timelineElementHelpers";
+import type { PatchOperation } from "../utils/sourcePatcher";
+
+const ELEMENT_OFFSET_REFUSED: Record<ElementOffsetRefusal, string> = {
+ anchored: "This layer is anchored from its right or bottom edge. Move it in the Code tab.",
+ percent: "This layer's position is set in percent. Move it in the Code tab.",
+};
+
+export interface ElementOffsetStagerDeps {
+ commitPositionPatchToHtml: (
+ selection: DomEditSelection,
+ patches: PatchOperation[],
+ options: { label: string; coalesceKey: string; coalesceMs?: number },
+ ) => Promise<void>;
+ showToast: (message: string, tone?: "error" | "info") => void;
+ readOnlyPreview?: boolean;
+}
+
+/** The drag draft moved GSAP's x/y; left/top carries the move now, so put them back. */
+function settleGsapDraftAtGestureStart(el: HTMLElement): void {
+ const gsap = (el.ownerDocument.defaultView as { gsap?: { set: (t: Element, v: object) => void } })
+ ?.gsap;
+ const x = Number.parseFloat(el.getAttribute("data-hf-drag-gsap-base-x") ?? "");
+ const y = Number.parseFloat(el.getAttribute("data-hf-drag-gsap-base-y") ?? "");
+ if (gsap && Number.isFinite(x) && Number.isFinite(y)) gsap.set(el, { x, y });
+}
+
+/** Applies a shared-tween element's move live now; `save` persists it as left/top on that
+ * element, `rollback` takes the live move back. Throws, after a toast, when it cannot. */
+export function stageElementOffset(
+ { commitPositionPatchToHtml, showToast, readOnlyPreview }: ElementOffsetStagerDeps,
+ selection: DomEditSelection,
+ next: { x: number; y: number },
+ coalesceKey?: string,
+): { save: () => Promise<void>; rollback: () => void } {
+ const el = selection.element;
+ if (readOnlyPreview) return { save: () => Promise.resolve(), rollback: () => undefined };
+ const previous = { position: el.style.position, left: el.style.left, top: el.style.top };
+ const liftMarker = el.getAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR);
+ const result = applyElementPositionOffset(el, next);
+ if (!Array.isArray(result)) {
+ showToast(ELEMENT_OFFSET_REFUSED[result], "error");
+ throw new Error(ELEMENT_OFFSET_REFUSED[result]);
+ }
+ settleGsapDraftAtGestureStart(el);
+ const rollback = () => {
+ Object.assign(el.style, previous);
+ if (liftMarker !== null) el.setAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR, liftMarker);
+ };
+ const save = () =>
+ commitPositionPatchToHtml(selection, result, {
+ label: "Move layer",
+ coalesceKey: coalesceKey ?? `element-offset:${getDomEditTargetKey(selection)}`,
+ ...(coalesceKey && { coalesceMs: Number.POSITIVE_INFINITY }),
+ }).catch((error) => {
+ rollback();
+ throw error;
+ });
+ return { save, rollback };
+}
diff --git a/packages/studio/src/hooks/gestureTransaction.ts b/packages/studio/src/hooks/gestureTransaction.ts
index da7d61f487..affd363120 100644
--- a/packages/studio/src/hooks/gestureTransaction.ts
+++ b/packages/studio/src/hooks/gestureTransaction.ts
@@ -14,7 +14,8 @@ export interface GestureTransaction {
element: HTMLElement;
label: string;
settle(): void;
- persist(commit: TxCommit): Promise<void>;
+ persist(commit: TxCommit, coalesceKey: string): Promise<void>;
+ afterBufferedCommitsSaved?(): Promise<void>;
restore(): void;
skipPixelAssert?: boolean;
}
@@ -142,9 +143,10 @@ export function runGestureTransaction(tx: GestureTransaction): Promise<void> {
};
return tx
- .persist(commit)
+ .persist(commit, coalesceKey)
.then(async () => {
reloadCount = await dispatchBufferedCommits(bufferedCommits);
+ await tx.afterBufferedCommitsSaved?.();
const durationMs = Math.round(performance.now() - startedAt);
logCommit("persisted", { label: tx.label, coalesceKey });
if (before) {
diff --git a/packages/studio/src/hooks/gsapDragCommit.ts b/packages/studio/src/hooks/gsapDragCommit.ts
index d2d17c50b3..e34de843e4 100644
--- a/packages/studio/src/hooks/gsapDragCommit.ts
+++ b/packages/studio/src/hooks/gsapDragCommit.ts
@@ -29,6 +29,7 @@ export interface GsapDragCommitCallbacks {
options: {
label: string;
coalesceKey?: string;
+ coalesceMs?: number;
softReload?: boolean;
skipReload?: boolean;
beforeReload?: () => void;
diff --git a/packages/studio/src/hooks/gsapEditOutcome.ts b/packages/studio/src/hooks/gsapEditOutcome.ts
index 1459f4e8ff..72a4aa362e 100644
--- a/packages/studio/src/hooks/gsapEditOutcome.ts
+++ b/packages/studio/src/hooks/gsapEditOutcome.ts
@@ -43,7 +43,8 @@ export type GsapEditOutcome =
*/
ownsDragOffset?: boolean;
}
- | { status: "blocked"; reason: GsapEditBlockReason; detail?: GsapEditBlockDetail };
+ | { status: "blocked"; reason: GsapEditBlockReason; detail?: GsapEditBlockDetail }
+ | { status: "element-offset" };
export const GSAP_EDIT_BLOCK_COPY: Record<GsapEditBlockReason, string> = {
"no-selector": "This layer needs a stable selector before Studio can save the edit.",
diff --git a/packages/studio/src/hooks/gsapRuntimeBridge.sharedTween.test.ts b/packages/studio/src/hooks/gsapRuntimeBridge.sharedTween.test.ts
new file mode 100644
index 0000000000..3d9fe60e73
--- /dev/null
+++ b/packages/studio/src/hooks/gsapRuntimeBridge.sharedTween.test.ts
@@ -0,0 +1,157 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
+import type { DomEditSelection } from "../components/editor/domEditingTypes";
+import { tryGsapDragIntercept } from "./gsapRuntimeBridge";
+
+const WORDS = ["How", "we", "build", "videos", "at", "scale", "every", "day"];
+
+function mountPhrase(): HTMLElement[] {
+ document.body.innerHTML = `<h1>${WORDS.map(
+ (word, i) => `<span class="w" data-hf-id="hf-w${i}">${word}</span>`,
+ ).join("")}</h1>`;
+ return [...document.querySelectorAll<HTMLElement>(".w")];
+}
+
+function wordSelection(element: HTMLElement, index: number): DomEditSelection {
+ return {
+ selector: ".w",
+ selectorIndex: index,
+ hfId: element.getAttribute("data-hf-id") ?? undefined,
+ element,
+ } as unknown as DomEditSelection;
+}
+
+// One staggered entrance on the shared class, the way generated titles are written.
+const staggerIn = {
+ id: ".w-from-200",
+ targetSelector: ".w",
+ method: "from",
+ properties: { y: 60, opacity: 0 },
+ position: 0.2,
+ resolvedStart: 0.2,
+ duration: 0.6,
+ stagger: 0.08,
+} as unknown as GsapAnimation;
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+});
+
+describe("tryGsapDragIntercept: one word of a staggered phrase", () => {
+ it("leaves the shared tween alone and hands the move to that word's own offset", async () => {
+ const words = mountPhrase();
+ const commitMutation = vi.fn();
+ const outcome = await tryGsapDragIntercept(
+ wordSelection(words[0]!, 0),
+ { x: -40, y: 0 },
+ [staggerIn],
+ null,
+ commitMutation,
+ async () => [staggerIn],
+ );
+ expect(outcome).toEqual({ status: "element-offset" });
+ expect(commitMutation).not.toHaveBeenCalled();
+ });
+
+ it("still edits a tween that targets only the dragged word", async () => {
+ const words = mountPhrase();
+ const own = { ...staggerIn, id: "own", targetSelector: '[data-hf-id="hf-w0"]' };
+ const commitMutation = vi.fn();
+ const outcome = await tryGsapDragIntercept(
+ wordSelection(words[0]!, 0),
+ { x: -40, y: 0 },
+ [own as GsapAnimation],
+ null,
+ commitMutation,
+ async () => [own as GsapAnimation],
+ );
+ expect(outcome.status).toBe("persisted");
+ expect(commitMutation).toHaveBeenCalled();
+ });
+});
+
+describe("tryGsapDragIntercept: which tweens a word's drag may use", () => {
+ it("edits the word's own position tween, not the shared one, when it has both", async () => {
+ const words = mountPhrase();
+ const own = {
+ ...staggerIn,
+ id: "own",
+ method: "set",
+ targetSelector: '[data-hf-id="hf-w0"]',
+ properties: { x: 10, y: 0 },
+ duration: 0,
+ propertyGroup: "position",
+ } as unknown as GsapAnimation;
+ const commitMutation = vi.fn();
+ const outcome = await tryGsapDragIntercept(
+ wordSelection(words[0]!, 0),
+ { x: -40, y: 0 },
+ [staggerIn, own],
+ null,
+ commitMutation,
+ async () => [staggerIn, own],
+ );
+ expect(outcome.status).toBe("persisted");
+ const touched = commitMutation.mock.calls.map((call) => JSON.stringify(call[1]));
+ expect(touched.length).toBeGreaterThan(0);
+ expect(touched.every((m) => !m.includes(staggerIn.id))).toBe(true);
+ expect(touched.some((m) => m.includes('"own"'))).toBe(true);
+ });
+
+ it("ignores a tween whose target never reaches the word", async () => {
+ document.body.innerHTML = `<div id="title"><span class="w">A</span><span class="w">B</span></div>
+ <div id="subtitle"><span class="w" data-hf-id="hf-s0">C</span></div>`;
+ const word = document.querySelector<HTMLElement>('[data-hf-id="hf-s0"]')!;
+ const titleOnly = { ...staggerIn, id: "title-only", targetSelector: "#title .w" };
+ const commitMutation = vi.fn();
+ const outcome = await tryGsapDragIntercept(
+ wordSelection(word, 2),
+ { x: -40, y: 0 },
+ [titleOnly as GsapAnimation],
+ null,
+ commitMutation,
+ async () => [titleOnly as GsapAnimation],
+ );
+ expect(outcome.status).toBe("persisted");
+ const touched = commitMutation.mock.calls.map((call) => JSON.stringify(call[1]));
+ expect(touched.every((m) => !m.includes("title-only"))).toBe(true);
+ });
+});
+
+describe("tryGsapDragIntercept: one drag is one undo step", () => {
+ it("records the split and the move under one gesture key", async () => {
+ document.body.innerHTML = `<div id="hero"></div>`;
+ const hero = document.getElementById("hero")!;
+ const mixed = {
+ id: "#hero-fromTo-0",
+ targetSelector: "#hero",
+ method: "fromTo",
+ fromProperties: { x: 0, opacity: 0 },
+ properties: { x: 100, opacity: 1 },
+ position: 0,
+ resolvedStart: 0,
+ duration: 1,
+ } as unknown as GsapAnimation;
+ const split = [
+ { ...mixed, id: "#hero-fromTo-0-position", propertyGroup: "position" },
+ { ...mixed, id: "#hero-fromTo-0-opacity", propertyGroup: "opacity" },
+ ] as GsapAnimation[];
+ let fetches = 0;
+ const commitMutation = vi.fn();
+ await tryGsapDragIntercept(
+ { id: "hero", selector: "#hero", element: hero } as unknown as DomEditSelection,
+ { x: 20, y: 0 },
+ [mixed],
+ null,
+ commitMutation,
+ async () => (fetches++ === 0 ? [mixed] : split),
+ );
+ const options = commitMutation.mock.calls.map((call) => call[2]);
+ expect(options.length).toBeGreaterThan(1);
+ expect(new Set(options.map((o) => o.coalesceKey)).size).toBe(1);
+ expect(options[0].coalesceKey).toMatch(/^gsap:drag:/);
+ expect(options.every((o) => o.coalesceMs === Number.POSITIVE_INFINITY)).toBe(true);
+ });
+});
diff --git a/packages/studio/src/hooks/gsapRuntimeBridge.ts b/packages/studio/src/hooks/gsapRuntimeBridge.ts
index 08efd9fad0..074e292e0c 100644
--- a/packages/studio/src/hooks/gsapRuntimeBridge.ts
+++ b/packages/studio/src/hooks/gsapRuntimeBridge.ts
@@ -24,6 +24,8 @@ import {
materializeIfDynamic,
} from "./gsapDragCommit";
import { commitWholePropertyOffset } from "./gsapWholePropertyOffsetCommit";
+import { isGestureTransactionCommit } from "./gestureTransaction";
+import { tweenReach, tweensForThisElement } from "./gsapTweenReach";
import { resolveTweenDuration } from "../utils/globalTimeCompiler";
import type { GsapDragCommitCallbacks } from "./gsapDragCommit";
import { isInstantHold, selectorFromSelection, writeTargetSelector } from "./gsapShared";
@@ -128,12 +130,18 @@ export async function resolveGroupTween(
export type { GsapDragCommitCallbacks };
-/**
- * Attempt to handle a drag commit via the GSAP script mutation path.
- *
- * Returns an explicit persisted/blocked outcome. Callers must reject blocked
- * outcomes so the gesture layer restores its runtime and overlay drafts.
- */
+const writesPosition = (a: GsapAnimation) => animationWritesAnyProperty(a, POSITION_CHANNEL_SET);
+
+/** Only a tween shared with siblings positions this element (a stagger on `.w`). */
+function positionedOnlyBySharedTween(selection: DomEditSelection, animations: GsapAnimation[]) {
+ const positioning = animations.filter(writesPosition);
+ return (
+ positioning.some((a) => tweenReach(a, selection.element) === "shared") &&
+ tweensForThisElement(selection, positioning).length === 0
+ );
+}
+
+// fallow-ignore-next-line complexity
async function preflightGsapDragIntercept(
selection: DomEditSelection,
animations: GsapAnimation[],
@@ -161,9 +169,18 @@ export function dragEditOutcome(
// set as well: ignoring it would let a transient fetch failure bypass helper /
// runtime-source ownership and reach a destructive split or property write.
const allKnownAnimations = [...animations, ...fetchedAnimations];
- const editability = directEditOutcomeForProperties(allKnownAnimations, POSITION_CHANNEL_SET);
+ const reaching = allKnownAnimations.filter(
+ (a) => tweenReach(a, selection.element) !== "elsewhere",
+ );
+ const editability = directEditOutcomeForProperties(reaching, POSITION_CHANNEL_SET);
if (editability.status === "blocked") return editability;
- const sourceAnimations = fetchedAnimations.length > 0 ? fetchedAnimations : animations;
+ if (positionedOnlyBySharedTween(selection, allKnownAnimations)) {
+ return { status: "element-offset" };
+ }
+ const sourceAnimations = tweensForThisElement(
+ selection,
+ fetchedAnimations.length > 0 ? fetchedAnimations : animations,
+ );
// In a group only a tween naming this member by id or by its own selector counts,
// so a class tween shared with id-selected members cannot take one member's write.
const positionSources = group
@@ -187,13 +204,28 @@ export function dragEditOutcome(
return { status: "persisted" };
}
+let dragGestureCounter = 0;
+
+/** Every write one drag makes (a split, then the move) records as ONE undo step. A
+ * transaction or group commit already owns its key. */
+function oneUndoStep(
+ commit: GsapDragCommitCallbacks["commitMutation"],
+): GsapDragCommitCallbacks["commitMutation"] {
+ if (isGestureTransactionCommit(commit)) return commit;
+ const coalesceKey = `gsap:drag:${++dragGestureCounter}`;
+ return (selection, mutation, options) =>
+ commit(selection, mutation, { ...options, coalesceKey, coalesceMs: Number.POSITIVE_INFINITY });
+}
+
+/** Commits a drag through the GSAP script. Callers reject `blocked` (the gesture layer
+ * restores its drafts) and save `element-offset` on the element itself. */
export async function tryGsapDragIntercept(
selection: DomEditSelection,
offset: { x: number; y: number },
- animations: GsapAnimation[],
+ allAnimations: GsapAnimation[],
iframe: HTMLIFrameElement | null,
- commitMutation: GsapDragCommitCallbacks["commitMutation"],
- fetchFallbackAnimations?: () => Promise<GsapAnimation[]>,
+ gestureCommit: GsapDragCommitCallbacks["commitMutation"],
+ fetchAllAnimations?: () => Promise<GsapAnimation[]>,
options?: {
altKey?: boolean;
preflightOnly?: boolean;
@@ -204,16 +236,20 @@ export async function tryGsapDragIntercept(
if (!options?.preflightPassed) {
const preflight = await preflightGsapDragIntercept(
selection,
- animations,
+ allAnimations,
iframe,
- fetchFallbackAnimations,
+ fetchAllAnimations,
options?.group,
);
- if (preflight.status === "blocked" || options?.preflightOnly) return preflight;
+ if (preflight.status !== "persisted" || options?.preflightOnly) return preflight;
}
+ const animations = tweensForThisElement(selection, allAnimations);
+ const fetchFallbackAnimations =
+ fetchAllAnimations && (async () => tweensForThisElement(selection, await fetchAllAnimations()));
const selector = selectorFromSelection(selection);
// The preflight above proves this; retain a defensive result for DOM churn.
if (!selector) return { status: "blocked", reason: "no-selector" };
+ const commitMutation = oneUndoStep(gestureCommit);
// Self-heal: enforce a single position write BEFORE committing. A corrupted
// file can carry 2+ conflicting position writes for one selector (e.g. a
diff --git a/packages/studio/src/hooks/gsapTweenReach.ts b/packages/studio/src/hooks/gsapTweenReach.ts
new file mode 100644
index 0000000000..90abde736d
--- /dev/null
+++ b/packages/studio/src/hooks/gsapTweenReach.ts
@@ -0,0 +1,30 @@
+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
+import type { DomEditSelection } from "../components/editor/domEditingTypes";
+
+type TweenReach = "own" | "shared" | "elsewhere" | "unknown";
+
+/** Which elements a tween's target resolves to in the live preview, relative to `el`. */
+export function tweenReach(animation: GsapAnimation, el: Element | null | undefined): TweenReach {
+ const doc = el?.ownerDocument;
+ if (!el?.isConnected || !doc || animation.hasUnresolvedSelector) return "unknown";
+ let hits: Element[];
+ try {
+ hits = [...doc.querySelectorAll(animation.targetSelector)];
+ } catch {
+ return "unknown";
+ }
+ if (!hits.includes(el)) return "elsewhere";
+ return hits.length === 1 ? "own" : "shared";
+}
+
+/** The tweens a one-element edit may rewrite: not one shared with siblings, nor one
+ * that never reaches the element. */
+export function tweensForThisElement(
+ selection: DomEditSelection,
+ animations: GsapAnimation[],
+): GsapAnimation[] {
+ return animations.filter((a) => {
+ const reach = tweenReach(a, selection.element);
+ return reach === "own" || reach === "unknown";
+ });
+}
diff --git a/packages/studio/src/hooks/useCommitPreflightCapabilities.ts b/packages/studio/src/hooks/useCommitPreflightCapabilities.ts
index d08b2518e3..e1b1664213 100644
--- a/packages/studio/src/hooks/useCommitPreflightCapabilities.ts
+++ b/packages/studio/src/hooks/useCommitPreflightCapabilities.ts
@@ -51,8 +51,8 @@ const MANUAL_FLAGS = [
/** Null when the commit would go through; "" while the check is still running. */
function refusal(preflight: CommitPreflight | null, check: keyof CommitPreflight): string | null {
const outcome = preflight?.[check];
- if (outcome?.status === "persisted") return null;
- return outcome ? GSAP_EDIT_BLOCK_COPY[outcome.reason] : "";
+ if (!outcome) return "";
+ return outcome.status === "blocked" ? GSAP_EDIT_BLOCK_COPY[outcome.reason] : null;
}
/** Closes each manual flag whose commit Studio would refuse, and says why. */
diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.ts
index 8726a95822..fdff1119d4 100644
--- a/packages/studio/src/hooks/useDomEditCommits.ts
+++ b/packages/studio/src/hooks/useDomEditCommits.ts
@@ -269,6 +269,7 @@ export function useDomEditCommits({
// ── Geometry commits (path offset, box size, rotation) ──
const {
+ stageElementPositionOffset,
handleDomPathOffsetCommit,
handleDomBoxSizeCommit,
handleDomRotationCommit,
@@ -312,6 +313,7 @@ export function useDomEditCommits({
handleDomTextFieldStyleCommit,
handleDomAddTextField,
handleDomRemoveTextField,
+ stageElementPositionOffset,
handleDomPathOffsetCommit,
handleDomBoxSizeCommit,
handleDomRotationCommit,
diff --git a/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts b/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts
index dd693fff97..1b8b4aaa12 100644
--- a/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts
+++ b/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts
@@ -4,6 +4,7 @@ import type { PatchOperation } from "../utils/sourcePatcher";
import { trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";
import { DomEditSaveQueueOpenError } from "../utils/domEditSaveQueue";
import type { PersistDomEditOperations } from "./domEditCommitTypes";
+import { wasAlreadyToasted } from "./domEditPersistFailure";
interface UseDomEditPositionPatchCommitParams {
activeCompPath: string | null;
@@ -39,7 +40,9 @@ export function useDomEditPositionPatchCommit({
// resolved the commit, which skipped the caller's revert, so the element
// stayed where the drag put it while nothing reached the file.
if (error instanceof DomEditSaveQueueOpenError) throw error;
- showToast(error instanceof Error ? error.message : "Failed to save position");
+ if (!wasAlreadyToasted(error)) {
+ showToast(error instanceof Error ? error.message : "Failed to save position");
+ }
trackStudioSaveFailure({
source: "dom_edit",
error,
diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.ts
index abc965be8e..2d1d48ae7d 100644
--- a/packages/studio/src/hooks/useDomEditSession.ts
+++ b/packages/studio/src/hooks/useDomEditSession.ts
@@ -229,6 +229,7 @@ export function useDomEditSession({
handleDomTextFieldStyleCommit,
handleDomAddTextField,
handleDomRemoveTextField,
+ stageElementPositionOffset,
handleDomBoxSizeCommit,
handleDomManualEditsReset,
handleDomEditElementsDelete,
@@ -487,6 +488,7 @@ export function useDomEditSession({
bumpGsapCache,
makeFetchFallback,
trackGsapInteractionFailure,
+ stageElementPositionOffset,
handleDomBoxSizeCommit,
addGsapAnimation,
convertToKeyframes,
diff --git a/packages/studio/src/hooks/useDomGeometryCommit.test.tsx b/packages/studio/src/hooks/useDomGeometryCommit.test.tsx
index c966b7075c..4577d7c8f6 100644
--- a/packages/studio/src/hooks/useDomGeometryCommit.test.tsx
+++ b/packages/studio/src/hooks/useDomGeometryCommit.test.tsx
@@ -224,3 +224,105 @@ describe("useDomGeometryCommit, from the package entry", () => {
unmount();
});
});
+
+describe("useDomGeometryCommit, one word of a staggered phrase", () => {
+ const WORDS = ["How", "we", "build", "videos", "at", "scale", "every", "day"];
+ const PHRASE = WORDS.map((w, i) => `<span class="w" data-hf-id="hf-w${i}">${w}</span>`).join("");
+
+ function stubPhraseServer(patchStatuses: number[] = []) {
+ const calls = { patches: [] as unknown[], gsapMutations: [] as unknown[] };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ const json = (body: unknown) =>
+ new Response(JSON.stringify(body), { headers: { "content-type": "application/json" } });
+ if (url.includes("/api/projects/p1/gsap-animations/")) {
+ return json({
+ animations: [
+ {
+ id: ".w-from-200",
+ targetSelector: ".w",
+ method: "from",
+ position: 0.2,
+ duration: 0.6,
+ properties: { y: 60, opacity: 0 },
+ },
+ ],
+ });
+ }
+ if (url.includes("/api/projects/p1/files/")) return json({ content: PHRASE });
+ if (url.includes("/api/projects/p1/file-mutations/patch-element/")) {
+ calls.patches.push(JSON.parse(String(init?.body)));
+ const status = patchStatuses.shift();
+ if (status) {
+ return new Response(JSON.stringify({ error: "the file changed on disk" }), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+ }
+ return json({ ok: true, changed: true, matched: true, content: "AFTER", version: "v2" });
+ }
+ if (url.includes("/api/projects/p1/gsap-mutations/")) {
+ calls.gsapMutations.push(JSON.parse(String(init?.body)));
+ return json({ ok: true, changed: true, before: "B", after: "A" });
+ }
+ throw new Error(`Unexpected fetch: ${url}`);
+ }),
+ );
+ return calls;
+ }
+
+ function mountWord(element: HTMLElement) {
+ element.ownerDocument.body.innerHTML = PHRASE;
+ const word = element.ownerDocument.querySelector<HTMLElement>('[data-hf-id="hf-w0"]')!;
+ Object.defineProperties(word, {
+ offsetLeft: { get: () => 100 + (Number.parseFloat(word.style.left) || 0) },
+ offsetTop: { get: () => 200 + (Number.parseFloat(word.style.top) || 0) },
+ });
+ return { ...makeSelection("How", word), id: undefined, selector: ".w", hfId: "hf-w0" };
+ }
+
+ it("saves left/top on the dragged word only and never rewrites the shared tween", async () => {
+ const calls = stubPhraseServer();
+ const { element, recordEdit, hook, unmount } = renderHost();
+ const selection = mountWord(element);
+
+ await expect(hook().commitPathOffset(selection, { x: 40, y: 20 })).resolves.toEqual({
+ ok: true,
+ });
+
+ expect(calls.gsapMutations).toHaveLength(0);
+ expect(calls.patches).toEqual([
+ expect.objectContaining({
+ target: expect.objectContaining({ hfId: "hf-w0" }),
+ operations: [
+ { type: "inline-style", property: "position", value: "relative" },
+ { type: "inline-style", property: "left", value: "40px" },
+ { type: "inline-style", property: "top", value: "20px" },
+ ],
+ }),
+ ]);
+ expect(recordEdit).toHaveBeenCalledTimes(1);
+ unmount();
+ });
+
+ it("saves a later move after a conflict refused the first, and says what happened", async () => {
+ const calls = stubPhraseServer([409]);
+ const showToast = vi.fn();
+ const { element, recordEdit, hook, unmount } = renderHost({ showToast });
+ const selection = mountWord(element);
+
+ await expect(hook().commitPathOffset(selection, { x: 40, y: 20 })).rejects.toThrow();
+ expect(showToast.mock.calls.map((call) => call[0])).toEqual([
+ "Couldn't save edit: the file changed on disk",
+ ]);
+ await expect(hook().commitPathOffset(selection, { x: 40, y: 20 })).resolves.toEqual({
+ ok: true,
+ });
+
+ expect(calls.patches).toHaveLength(2);
+ expect(recordEdit).toHaveBeenCalledTimes(1);
+ unmount();
+ });
+});
diff --git a/packages/studio/src/hooks/useDomGeometryCommit.ts b/packages/studio/src/hooks/useDomGeometryCommit.ts
index 862a1d47a7..39853af316 100644
--- a/packages/studio/src/hooks/useDomGeometryCommit.ts
+++ b/packages/studio/src/hooks/useDomGeometryCommit.ts
@@ -1,4 +1,4 @@
-import { useCallback, useMemo, useRef } from "react";
+import { useCallback, useMemo, useRef, useState } from "react";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditing";
import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay";
@@ -10,6 +10,11 @@ import { useGsapAwareEditing } from "./useGsapAwareEditing";
import { useGsapInteractionFailureTelemetry } from "./useGsapInteractionFailureTelemetry";
import { useGsapScriptCommits } from "./useGsapScriptCommits";
import { useGsapCacheVersion } from "./useGsapTweenCache";
+import { createDomEditSaveQueue } from "../utils/domEditSaveQueue";
+import { useDomEditPersist } from "./useDomEditPersist";
+import { useDomEditPositionPatchCommit } from "./useDomEditPositionPatchCommit";
+import { useMountEffect } from "./useMountEffect";
+import { stageElementOffset } from "./elementOffsetStager";
/**
* Studio's `Player` must show the project, with `beginTimelineSession(projectId)` run before it
@@ -77,6 +82,41 @@ export function useDomGeometryCommit({
showToast,
writeProjectFile,
});
+ const [queue] = useState(createDomEditSaveQueue);
+ useMountEffect(() => () => queue.destroy());
+ const persistDomEditOperations = useDomEditPersist({
+ activeCompPath,
+ previewIframeRef: iframeRef,
+ showToast,
+ queueDomEditSave: queue.enqueue,
+ writeProjectFile,
+ editHistory,
+ projectIdRef,
+ reloadPreview: noop,
+ });
+ const commitPositionPatchToHtml = useDomEditPositionPatchCommit({
+ activeCompPath,
+ persistDomEditOperations,
+ showToast,
+ });
+ // No paused-save banner in a host: each save is a retry, as in useDomStyleCommit.
+ const commitWithFreshQueue = useCallback<typeof commitPositionPatchToHtml>(
+ (...args) => {
+ queue.reset();
+ return commitPositionPatchToHtml(...args);
+ },
+ [commitPositionPatchToHtml, queue],
+ );
+ const stageElementPositionOffset = useCallback(
+ (selection: DomEditSelection, next: { x: number; y: number }, coalesceKey?: string) =>
+ stageElementOffset(
+ { commitPositionPatchToHtml: commitWithFreshQueue, showToast },
+ selection,
+ next,
+ coalesceKey,
+ ),
+ [commitWithFreshQueue, showToast],
+ );
const makeFetchFallback = useGsapAnimationFetchFallback(projectId);
const trackGsapInteractionFailure = useGsapInteractionFailureTelemetry(activeCompPath, showToast);
const {
@@ -94,6 +134,7 @@ export function useDomGeometryCommit({
bumpGsapCache,
makeFetchFallback,
trackGsapInteractionFailure,
+ stageElementPositionOffset,
handleDomBoxSizeCommit: noDomBoxSizeRoute,
addGsapAnimation: gsap.addGsapAnimation,
convertToKeyframes: gsap.convertToKeyframes,
diff --git a/packages/studio/src/hooks/useDomGeometryCommits.test.tsx b/packages/studio/src/hooks/useDomGeometryCommits.test.tsx
index a45a619f59..5f5c9e6a71 100644
--- a/packages/studio/src/hooks/useDomGeometryCommits.test.tsx
+++ b/packages/studio/src/hooks/useDomGeometryCommits.test.tsx
@@ -143,3 +143,30 @@ describe("useDomGeometryCommits read-only preview", () => {
unmount();
});
});
+
+describe("useDomGeometryCommits element position offset", () => {
+ it("persists left/top on the element and no translate offset", async () => {
+ const element = document.createElement("span");
+ Object.defineProperties(element, {
+ offsetLeft: { get: () => 100 + (Number.parseFloat(element.style.left) || 0) },
+ offsetTop: { get: () => 200 + (Number.parseFloat(element.style.top) || 0) },
+ });
+ document.body.append(element);
+ const selection = { hfId: "w0", selector: ".w", element } as unknown as DomEditSelection;
+ const commitPositionPatchToHtml = vi
+ .fn<UseDomGeometryCommitsParams["commitPositionPatchToHtml"]>()
+ .mockResolvedValue(undefined);
+ const { commits, unmount } = mountCommits(commitPositionPatchToHtml);
+
+ await commits().stageElementPositionOffset(selection, { x: 40, y: 20 }).save();
+
+ const patches = commitPositionPatchToHtml.mock.calls[0]![1];
+ expect(patches).toEqual([
+ { type: "inline-style", property: "position", value: "relative" },
+ { type: "inline-style", property: "left", value: "40px" },
+ { type: "inline-style", property: "top", value: "20px" },
+ ]);
+ expect(element.style.getPropertyValue("translate")).toBe("");
+ unmount();
+ });
+});
diff --git a/packages/studio/src/hooks/useDomGeometryCommits.ts b/packages/studio/src/hooks/useDomGeometryCommits.ts
index 69a13d7be0..8fefd3f63e 100644
--- a/packages/studio/src/hooks/useDomGeometryCommits.ts
+++ b/packages/studio/src/hooks/useDomGeometryCommits.ts
@@ -14,6 +14,7 @@ import {
clearStudioBoxSize,
clearStudioRotation,
} from "../components/editor/manualEdits";
+import { stageElementOffset } from "./elementOffsetStager";
import {
buildPathOffsetPatches,
buildBoxSizePatches,
@@ -47,7 +48,7 @@ export interface UseDomGeometryCommitsParams {
commitPositionPatchToHtml: (
selection: DomEditSelection,
patches: PatchOperation[],
- options: { label: string; coalesceKey: string; skipRefresh?: boolean },
+ options: { label: string; coalesceKey: string; coalesceMs?: number; skipRefresh?: boolean },
) => Promise<void>;
readOnlyPreview: boolean;
}
@@ -58,6 +59,17 @@ export function useDomGeometryCommits({
commitPositionPatchToHtml,
readOnlyPreview,
}: UseDomGeometryCommitsParams) {
+ const stageElementPositionOffset = useCallback(
+ (selection: DomEditSelection, next: { x: number; y: number }, coalesceKey?: string) =>
+ stageElementOffset(
+ { commitPositionPatchToHtml, showToast, readOnlyPreview },
+ selection,
+ next,
+ coalesceKey,
+ ),
+ [commitPositionPatchToHtml, readOnlyPreview, showToast],
+ );
+
const handleDomPathOffsetCommit = useCallback(
(selection: DomEditSelection, next: { x: number; y: number }) => {
if (readOnlyPreview) return Promise.resolve();
@@ -163,6 +175,7 @@ export function useDomGeometryCommits({
);
return {
+ stageElementPositionOffset,
handleDomPathOffsetCommit,
handleDomBoxSizeCommit,
handleDomRotationCommit,
diff --git a/packages/studio/src/hooks/useGsapAwareEditing.test.tsx b/packages/studio/src/hooks/useGsapAwareEditing.test.tsx
index 07b3095de2..3866109387 100644
--- a/packages/studio/src/hooks/useGsapAwareEditing.test.tsx
+++ b/packages/studio/src/hooks/useGsapAwareEditing.test.tsx
@@ -52,6 +52,9 @@ function mountResizeHandler(
const element = document.createElement("div");
const selection = { element, id: "clip", selector: "#clip" } as unknown as DomEditSelection;
const fallback = vi.fn().mockResolvedValue(undefined);
+ const anchorSave = vi.fn().mockResolvedValue(undefined);
+ const anchorRollback = vi.fn();
+ const elementOffset = vi.fn(() => ({ save: anchorSave, rollback: anchorRollback }));
const commitMutation = vi.fn().mockResolvedValue(undefined);
let resize:
| ((
@@ -71,6 +74,7 @@ function mountResizeHandler(
bumpGsapCache: vi.fn(),
makeFetchFallback: () => vi.fn().mockResolvedValue(targetAnimations),
trackGsapInteractionFailure: vi.fn(),
+ stageElementPositionOffset: elementOffset,
handleDomBoxSizeCommit: fallback,
addGsapAnimation: vi.fn(),
convertToKeyframes: vi.fn(),
@@ -80,7 +84,16 @@ function mountResizeHandler(
return null;
}
const root = mountReactHarness(<Harness />);
- return { selection, fallback, commitMutation, resize: resize!, root };
+ return {
+ selection,
+ fallback,
+ elementOffset,
+ anchorSave,
+ anchorRollback,
+ commitMutation,
+ resize: resize!,
+ root,
+ };
}
type AwareEditingParams = Parameters<typeof useGsapAwareEditing>[0];
@@ -89,11 +102,16 @@ function mountGroupHandler({
gsapCommitMutation,
makeFetchFallback,
trackGsapInteractionFailure = vi.fn(),
+ stageElementPositionOffset = vi.fn(),
}: Pick<AwareEditingParams, "gsapCommitMutation" | "makeFetchFallback"> &
- Partial<Pick<AwareEditingParams, "trackGsapInteractionFailure">>) {
+ Partial<Pick<AwareEditingParams, "trackGsapInteractionFailure" | "stageElementPositionOffset">>) {
let groupCommit!: (updates: DomEditGroupPathOffsetCommit[]) => Promise<void>;
+ let pathOffsetCommit!: (
+ selection: DomEditSelection,
+ next: { x: number; y: number },
+ ) => Promise<void>;
function Harness() {
- groupCommit = useGsapAwareEditing({
+ const editing = useGsapAwareEditing({
domEditSelection: null,
selectedGsapAnimations: [],
gsapCommitMutation,
@@ -102,18 +120,75 @@ function mountGroupHandler({
bumpGsapCache: vi.fn(),
makeFetchFallback,
trackGsapInteractionFailure,
+ stageElementPositionOffset,
handleDomBoxSizeCommit: vi.fn(),
addGsapAnimation: vi.fn(),
convertToKeyframes: vi.fn(),
setArcPath: vi.fn(),
updateArcSegment: vi.fn(),
- }).handleGsapAwareGroupPathOffsetCommit;
+ });
+ groupCommit = editing.handleGsapAwareGroupPathOffsetCommit;
+ pathOffsetCommit = editing.handleGsapAwarePathOffsetCommit;
return null;
}
const root = mountReactHarness(<Harness />);
- return { groupCommit: (updates: DomEditGroupPathOffsetCommit[]) => groupCommit(updates), root };
+ return {
+ groupCommit: (updates: DomEditGroupPathOffsetCommit[]) => groupCommit(updates),
+ pathOffsetCommit: (selection: DomEditSelection, next: { x: number; y: number }) =>
+ pathOffsetCommit(selection, next),
+ root,
+ };
}
+describe("useGsapAwareEditing shared-tween moves", () => {
+ it("saves a single drag through the element's own offset", async () => {
+ mocks.drag.mockResolvedValue({ status: "element-offset" });
+ const save = vi.fn().mockResolvedValue(undefined);
+ const stageElementPositionOffset = vi.fn(() => ({ save, rollback: vi.fn() }));
+ const commitMutation = vi.fn();
+ const { pathOffsetCommit, root } = mountGroupHandler({
+ gsapCommitMutation: commitMutation,
+ makeFetchFallback: () => vi.fn().mockResolvedValue([]),
+ stageElementPositionOffset,
+ });
+ const word = { element: document.createElement("span"), hfId: "w0", selector: ".w" };
+ await act(() => pathOffsetCommit(word as unknown as DomEditSelection, { x: 40, y: 20 }));
+ expect(stageElementPositionOffset).toHaveBeenCalledWith(word, { x: 40, y: 20 });
+ expect(save).toHaveBeenCalledTimes(1);
+ expect(commitMutation).not.toHaveBeenCalled();
+ act(() => root.unmount());
+ });
+
+ it("saves a group member that shares a tween through its own offset, under the group key", async () => {
+ mocks.drag.mockImplementation(async (selection, _next, _a, _i, commit, _f, options) => {
+ if (selection.hfId === "w0") return { status: "element-offset" };
+ if (!options?.preflightOnly) await commit(selection, { type: "move" }, { label: "Move" });
+ return { status: "persisted" };
+ });
+ const save = vi.fn().mockResolvedValue(undefined);
+ const stageElementPositionOffset = vi.fn(() => ({ save, rollback: vi.fn() }));
+ const { groupCommit, root } = mountGroupHandler({
+ gsapCommitMutation: vi.fn().mockResolvedValue(undefined),
+ makeFetchFallback: () => vi.fn().mockResolvedValue([]),
+ stageElementPositionOffset,
+ });
+ const word = { element: document.createElement("span"), hfId: "w0", selector: ".w" };
+ const box = { element: document.createElement("div"), id: "box", selector: "#box" };
+ await act(() =>
+ groupCommit([
+ { selection: word, next: { x: 40, y: 20 } },
+ { selection: box, next: { x: 40, y: 20 } },
+ ] as unknown as DomEditGroupPathOffsetCommit[]),
+ );
+ expect(stageElementPositionOffset).toHaveBeenCalledWith(
+ word,
+ { x: 40, y: 20 },
+ expect.stringMatching(/^group-drag:\d+$/),
+ );
+ act(() => root.unmount());
+ });
+});
+
describe("useGsapAwareEditing anchored resize", () => {
it("uses the explicit target's animations instead of the human selection cache", async () => {
const humanAnimation = { id: "human", propertyGroup: "scale" } as GsapAnimation;
@@ -161,6 +236,39 @@ describe("useGsapAwareEditing anchored resize", () => {
act(() => h.root.unmount());
});
+ function resizeWritesSize() {
+ mocks.resize.mockImplementation(async (selection, _next, _a, _i, commit) => {
+ await commit(selection, { type: "size" }, { label: "Resize", softReload: true });
+ return { status: "persisted" };
+ });
+ mocks.drag.mockResolvedValue({ status: "element-offset" });
+ }
+
+ it("saves a shared-tween word's anchor move after its size, under the resize's undo key", async () => {
+ resizeWritesSize();
+ const h = mountResizeHandler([]);
+ await act(() => h.resize(h.selection, { width: 300, height: 200 }, { x: -50, y: -25 }));
+ const key = h.commitMutation.mock.calls[0]![2].coalesceKey;
+ expect(key).toMatch(/^tx:/);
+ expect(h.elementOffset).toHaveBeenCalledWith(h.selection, { x: -50, y: -25 }, key);
+ expect(h.anchorSave.mock.invocationCallOrder[0]).toBeGreaterThan(
+ h.commitMutation.mock.invocationCallOrder[0]!,
+ );
+ act(() => h.root.unmount());
+ });
+
+ it("does not keep the anchor move when the size save fails", async () => {
+ resizeWritesSize();
+ const h = mountResizeHandler([]);
+ h.commitMutation.mockRejectedValueOnce(new Error("size save failed"));
+ await expect(
+ act(() => h.resize(h.selection, { width: 300, height: 200 }, { x: -50, y: -25 })),
+ ).rejects.toThrow("size save failed");
+ expect(h.anchorSave).not.toHaveBeenCalled();
+ expect(h.anchorRollback).toHaveBeenCalledTimes(1);
+ act(() => h.root.unmount());
+ });
+
it("settles the live GSAP position before resize persistence reaches its first await", async () => {
let resolveResize!: (outcome: { status: "persisted" }) => void;
const pendingResize = new Promise<{ status: "persisted" }>((resolve) => {
diff --git a/packages/studio/src/hooks/useGsapAwareEditing.ts b/packages/studio/src/hooks/useGsapAwareEditing.ts
index 0d505a78b9..4f294423c5 100644
--- a/packages/studio/src/hooks/useGsapAwareEditing.ts
+++ b/packages/studio/src/hooks/useGsapAwareEditing.ts
@@ -34,9 +34,15 @@ import { logResize, logResizeSettle } from "../utils/resizeDebug";
import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay";
import { runGestureTransaction } from "./gestureTransaction";
import { hasNonHoldTweenForElement } from "./gsapRuntimeKeyframes";
-import { assertGsapEditPersisted } from "./gsapEditOutcome";
+import { assertGsapEditPersisted, type GsapEditOutcome } from "./gsapEditOutcome";
import type { GsapAnimationFetchOptions } from "./useGsapAnimationFetchFallback";
+/** A move only a shared tween positions is saved on the element itself; a blocked one throws. */
+async function saveMove(outcome: GsapEditOutcome, saveOnElement: () => Promise<void>) {
+ if (outcome.status === "element-offset") return saveOnElement();
+ assertGsapEditPersisted(outcome);
+}
+
// Distinct coalesceKey per group drag so consecutive group drags don't fold
// into one another's undo entry (module-local counter, not Date.now()).
let groupDragCommitCounter = 0;
@@ -71,6 +77,11 @@ export interface UseGsapAwareEditingParams {
label: string,
) => void;
// DOM fallbacks (from useDomEditCommits)
+ stageElementPositionOffset: (
+ selection: DomEditSelection,
+ next: { x: number; y: number },
+ coalesceKey?: string,
+ ) => { save: () => Promise<void>; rollback: () => void };
handleDomBoxSizeCommit: (
selection: DomEditSelection,
next: { width: number; height: number },
@@ -117,6 +128,7 @@ export function useGsapAwareEditing({
bumpGsapCache,
makeFetchFallback,
trackGsapInteractionFailure,
+ stageElementPositionOffset,
handleDomBoxSizeCommit,
addGsapAnimation,
convertToKeyframes,
@@ -154,7 +166,7 @@ export function useGsapAwareEditing({
makeFetchFallback(selection),
modifiers,
);
- assertGsapEditPersisted(outcome);
+ await saveMove(outcome, () => stageElementPositionOffset(selection, next).save());
} catch (error) {
trackGsapInteractionFailure(error, selection, "drag", "Move animated layer");
throw error;
@@ -167,6 +179,7 @@ export function useGsapAwareEditing({
makeFetchFallback,
trackGsapInteractionFailure,
getGsapAnimationsForSelection,
+ stageElementPositionOffset,
],
);
@@ -222,6 +235,7 @@ export function useGsapAwareEditing({
return Promise.resolve();
};
const preflightAnimations = new Map<DomEditSelection, GsapAnimation[]>();
+ const offsetMembers = new Set<DomEditSelection>();
// Editability is user-atomic: prove every member can be written before
// the first source mutation. Network failures after this point retain the
// existing multi-request semantics, but a blocked member can never leave
@@ -242,6 +256,7 @@ export function useGsapAwareEditing({
undefined,
{ preflightOnly: true, group: true },
);
+ if (outcome.status === "element-offset") offsetMembers.add(selection);
assertGsapEditPersisted(outcome);
}),
);
@@ -255,8 +270,15 @@ export function useGsapAwareEditing({
);
throw preflightFailure.error;
}
+ const lastScriptWrite = updates.findLastIndex(
+ ({ selection }) => !offsetMembers.has(selection),
+ );
for (const [index, { selection, next }] of updates.entries()) {
- renderOnCommit = index === updates.length - 1;
+ renderOnCommit = index === lastScriptWrite;
+ if (offsetMembers.has(selection)) {
+ await stageElementPositionOffset(selection, next, coalesceKey).save();
+ continue;
+ }
try {
const outcome = await tryGsapDragIntercept(
selection,
@@ -288,7 +310,13 @@ export function useGsapAwareEditing({
throw error;
}
},
- [gsapCommitMutation, previewIframeRef, makeFetchFallback, trackGsapInteractionFailure],
+ [
+ gsapCommitMutation,
+ previewIframeRef,
+ makeFetchFallback,
+ trackGsapInteractionFailure,
+ stageElementPositionOffset,
+ ],
);
const handleGsapAwareBoxSizeCommit = useCallback(
@@ -324,6 +352,7 @@ export function useGsapAwareEditing({
animCount: targetAnimations.length,
animGroups: targetAnimations.map((a) => `${a.propertyGroup}:${a.method}`),
});
+ let anchorMove: ReturnType<typeof stageElementPositionOffset> | null = null;
return runGestureTransaction({
element: selection.element,
label: "Resize layer",
@@ -339,7 +368,7 @@ export function useGsapAwareEditing({
logResize("sync-settle", { gsapPos, offset, newX, newY });
setElementGsapPosition(selection.element, newX, newY);
},
- persist: async (commit) => {
+ persist: async (commit, coalesceKey) => {
if (gsapCommitMutation) {
const commitMutation = commit(gsapCommitMutation);
try {
@@ -375,7 +404,10 @@ export function useGsapAwareEditing({
commitMutation,
makeFetchFallback(selection),
);
- assertGsapEditPersisted(dragOutcome);
+ // Saved after the size, under its undo key, so the two are one step.
+ await saveMove(dragOutcome, async () => {
+ anchorMove = stageElementPositionOffset(selection, offset, coalesceKey);
+ });
}
logResizeSettle(selection.element, ownsDragOffset ? "gsap-scale" : "gsap-size");
return;
@@ -392,12 +424,17 @@ export function useGsapAwareEditing({
logResizeSettle(selection.element, "dom-route");
await handleDomBoxSizeCommit(selection, next, offset);
},
- restore,
+ afterBufferedCommitsSaved: () => anchorMove?.save() ?? Promise.resolve(),
+ restore: () => {
+ anchorMove?.rollback();
+ restore();
+ },
skipPixelAssert: hasLivePositionTween,
});
},
[
handleDomBoxSizeCommit,
+ stageElementPositionOffset,
gsapCommitMutation,
previewIframeRef,
makeFetchFallback,
diff --git a/packages/studio/src/hooks/useGsapInteractionFailureTelemetry.test.tsx b/packages/studio/src/hooks/useGsapInteractionFailureTelemetry.test.tsx
index 39252bbcdc..3d981075c9 100644
--- a/packages/studio/src/hooks/useGsapInteractionFailureTelemetry.test.tsx
+++ b/packages/studio/src/hooks/useGsapInteractionFailureTelemetry.test.tsx
@@ -12,7 +12,8 @@ const { trackStudioEditBlocked, trackStudioSaveFailure } = vi.hoisted(() => ({
trackStudioEditBlocked: vi.fn(),
trackStudioSaveFailure: vi.fn(),
}));
-vi.mock("../utils/studioSaveDiagnostics", () => ({
+vi.mock("../utils/studioSaveDiagnostics", async (importOriginal) => ({
+ ...(await importOriginal<object>()),
trackStudioEditBlocked,
trackStudioSaveFailure,
}));
diff --git a/packages/studio/src/hooks/useGsapInteractionFailureTelemetry.ts b/packages/studio/src/hooks/useGsapInteractionFailureTelemetry.ts
index 8502e27e5a..6a1bebdc83 100644
--- a/packages/studio/src/hooks/useGsapInteractionFailureTelemetry.ts
+++ b/packages/studio/src/hooks/useGsapInteractionFailureTelemetry.ts
@@ -2,6 +2,12 @@ import { useCallback } from "react";
import type { DomEditSelection } from "../components/editor/domEditing";
import { trackStudioEditBlocked, trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";
import { isGsapEditBlockedError } from "./gsapEditOutcome";
+import { wasAlreadyToasted } from "./domEditPersistFailure";
+
+function failureToast(error: unknown): string | null {
+ if (wasAlreadyToasted(error)) return null;
+ return isGsapEditBlockedError(error) ? error.message : "Failed to save animated edit.";
+}
export function useGsapInteractionFailureTelemetry(
activeCompPath: string | null,
@@ -22,10 +28,8 @@ export function useGsapInteractionFailureTelemetry(
targetSelector: selection?.selector,
targetSourceFile: selection?.sourceFile,
});
- showToast(
- isGsapEditBlockedError(error) ? error.message : "Failed to save animated edit.",
- "error",
- );
+ const message = failureToast(error);
+ if (message) showToast(message, "error");
},
[activeCompPath, showToast],
);