fix(studio): a sealed drag draws and saves from the open preview's rounded position (#8587)

* test(studio): a second sealed resize of a scaled layer starts from its saved size

* fix(studio): a second sealed resize of a scaled layer no longer jumps and saves the jump

* test(studio): count and time the two-resize bench cases

* test(studio): a sealed frame's GSAP values are read again after a save reruns its script

* fix(studio): a second sealed resize scales from the size the first one saved

* test(studio): leave GSAP value reads out of the sealed save's sent-edit list

* refactor(studio): name the sealed rerun's re-read so the answer handler stays simple

* test(studio): a sealed drag on GSAP's route leaves no offset on the stand-in, one re-read per rerun

* fix(studio): a sealed drag that GSAP saves clears Studio's offset, as an unsealed one does

* fix(studio): a sealed drag of a GSAP-held layer moves GSAP's x/y, as an open preview does

* fix(studio): a sealed drag draws the rounded position an open preview's drag writes

* test(studio): a plain layer's frame draft is the open preview's rounded offset less its start

* fix(studio): a sealed restore keeps a later position write, and a rejected undo redraws the drop

* fix(studio): a sealed restore keeps each axis a later write set, per landed patch

* fix(studio): a sealed restore keeps a tween edit's axes only once that edit has drawn

* fix(studio): a failed sealed batch keeps the axes an earlier landed batch queued

* fix(studio): a sealed restore shows the base and whatever the timeline draws over it

* fix(studio): restoring one sealed draft leaves every other live draft where it is drawn

* fix(studio): a sealed restore replays only what each live draft draws, rotation included
This commit is contained in:
Miguel Ángel
2026-11-24 07:05:46 +00:00
committed by GitHub
parent 5a1b992a08
commit 7a1828f8ee
17 changed files with 576 additions and 42 deletions
@@ -1,6 +1,7 @@
// Studio's live value preview (a 3D-transform slider mid-drag) in a frame it cannot script.
import { EDITING_ELEMENT_HANDLE, type EditingElementHandle } from "../editingElement";
import { elementForHandle } from "../editingHandles";
import { rebaseDrawnPosition } from "../editingDraft";
const GSAP_SET_CHANNELS = new Set([
"x",
@@ -44,5 +45,6 @@ export function gsapSet({ handle, props }: GsapSetParams): { applied: boolean }
const gsap = (window as { gsap?: FrameGsap }).gsap;
if (!element || typeof gsap?.set !== "function") return { applied: false };
gsap.set(element, { ...props });
rebaseDrawnPosition(element, props);
return { applied: true };
}
@@ -3,7 +3,7 @@
// a sealed frame on itself through the editing port.
import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading";
import { recordLiveSet, swapWaiting } from "./softReload";
import { drawDrafts } from "../editingDraft";
import { drawDrafts, rebaseDrawnPosition } from "../editingDraft";
import { markRestingScenesForRedraw } from "../sceneRest";
import { redrawGsapTimelineAt } from "../adapters/gsap";
import type { RuntimeTimelineLike } from "../types";
@@ -202,6 +202,7 @@ export function applyGlobalSet(
const numeric = finiteNumericProps(props);
if (typeof target.gsap?.set !== "function" || !el || !numeric) return null;
target.gsap.set(el, numeric);
rebaseDrawnPosition(el, numeric);
recordLiveSet(el, numeric);
return el;
}
@@ -430,6 +430,8 @@ describe("installEditingAgent", () => {
{ drafts: [{ handle: H, translate: { x: "1", y: 0 }, size: null }] },
{ drafts: [{ handle: H, translate: { x: Infinity, y: 0 }, size: null }] },
{ drafts: [{ handle: H, translate: { x: 1e6, y: 0 }, size: null }] },
{ drafts: [{ handle: H, translate: { x: 1, y: 0, route: "css" }, size: null }] },
{ drafts: [{ handle: H, translate: { x: 1e6, y: 0, route: "gsap" }, size: null }] },
{ drafts: [{ handle: H, translate: null, size: { width: -1, height: 2 } }] },
{ drafts: [{ handle: H, translate: null, size: { width: 1, height: 2, depth: 3 } }] },
{ drafts: [{ handle: H, translate: null, size: null, rotate: { angle: 1 } }] },
@@ -679,6 +681,27 @@ describe("installEditingAgent", () => {
expect(spun.style.transform).toBe(value);
});
// fails without the fix: the frame refused a move routed through its GSAP, so a sealed drag drew a CSS translate.
it("moves a GSAP-held element's x/y through the port", async () => {
const port = connectedPort();
document.body.insertAdjacentHTML("beforeend", '<div id="held"></div>');
const held = document.getElementById("held")!;
const position = { x: 40, y: 30 };
Object.assign(window, {
gsap: {
getProperty: (_: Element, axis: "x" | "y") => position[axis],
set: (_: Element, props: Partial<typeof position>) => Object.assign(position, props),
},
});
const translate = { x: 35, y: 33, route: "gsap" };
const drafts = [{ handle: handleFor(held), translate, size: null }];
expect(await ask(port, { v: 1, id: 1, kind: "draft", params: { drafts } })).toMatchObject({
ok: true,
});
expect(position).toEqual({ x: 35, y: 33 });
Reflect.deleteProperty(window, "gsap");
});
it("answers computed styles for the element a selector names", async () => {
document.body.innerHTML = `<p id="title" style="color: rgb(1, 2, 3); opacity: 0.5">Hi</p>
<canvas data-hf-preview-video-canvas style="opacity: 0.25"></canvas>
@@ -1,4 +1,6 @@
import { afterEach, describe, expect, it } from "vitest";
import { gsapSet } from "./editing/gsapSet";
import { patchTweens } from "./editing/patchTween";
import { drawDrafts } from "./editingDraft";
import { handleFor } from "./editingHandles";
@@ -173,3 +175,98 @@ describe("draft ends by number", () => {
expect(element.style.translate).toBe("");
});
});
// fails without the fix: a sealed drag of a GSAP-held layer drew an unrounded CSS translate on top of GSAP's, where an
// open preview gives GSAP the rounded x/y, so the sealed drop point and saved x came out 0.001 px off.
describe("moves through GSAP", () => {
function gsapHeld() {
const { element, handle } = card("translate: 4px 2px; width: 50px");
const position = { x: 40, y: 30 };
(window as { gsap?: unknown }).gsap = {
getProperty: (_: Element, axis: "x" | "y") => position[axis],
set: (_: Element, props: Partial<typeof position>) => Object.assign(position, props),
};
const move = (x: number, y: number) =>
drawDrafts([{ handle, translate: { x, y, route: "gsap" }, size: null }]);
return { element, handle, position, move };
}
it("draws GSAP's x/y where Studio's drag puts them, with no translate on top", () => {
const { element, position, move } = gsapHeld();
move(35, 33);
move(30, 36);
expect([position, element.style.translate]).toEqual([{ x: 30, y: 36 }, "none"]);
});
it("puts GSAP's x/y and the translate back when the draft is restored", () => {
const { element, handle, position, move } = gsapHeld();
move(30, 36);
drawDrafts([{ handle, end: "restore" }]);
expect([position, element.style.translate]).toEqual([{ x: 40, y: 30 }, "4px 2px"]);
});
it("leaves GSAP where the drag drew it when the draft ends keeping its size", () => {
const { element, handle, position, move } = gsapHeld();
move(30, 36);
drawDrafts([{ handle, end: "keep-size" }]);
expect([position, element.style.translate]).toEqual([{ x: 30, y: 36 }, "4px 2px"]);
});
// fails without the fix: restore compared GSAP's x/y with the drawn one, so a later set to that same value, or one
// within 0.001 px, read as the draft's own and was thrown back to where the drag began.
it.each([
["the drawn value", 30],
["a value within 0.001 px of it", 30.0005],
])(
"leaves a position set over the port to %s after the draw when the draft is restored",
(_name, x) => {
const { handle, position, move } = gsapHeld();
move(30, 36);
gsapSet({ handle, props: { x, y: 36 } });
drawDrafts([{ handle, end: "restore" }]);
expect(position).toEqual({ x, y: 36 });
},
);
// fails without the fix: a write of x alone also dropped the draft's y, so a restore kept the cancelled drag's y.
it("puts back only the axis no later write took when the draft is restored", () => {
const { handle, position, move } = gsapHeld();
move(30, 36);
gsapSet({ handle, props: { x: 25 } });
drawDrafts([{ handle, end: "restore" }]);
expect(position).toEqual({ x: 25, y: 30 });
});
// fails without the fix: the hold dropped only when the whole batch landed, so a restore after a batch with a missed
// patch threw back the position an earlier patch had already written.
it("keeps a patch's position written before a later patch in the batch misses", () => {
const { handle, position, move } = gsapHeld();
move(30, 36);
const patches = [
{ selector: "#card", change: { kind: "global-set" as const, props: { x: 50, y: 60 } } },
{ selector: "#missing", change: { kind: "global-set" as const, props: { x: 1 } } },
];
expect(patchTweens({ patches, seek: false }).patched).toBe(false);
drawDrafts([{ handle, end: "restore" }]);
expect(position).toEqual({ x: 50, y: 60 });
});
it("leaves the position a save's patch sets after the draw when the draft is restored", () => {
const { handle, position, move } = gsapHeld();
move(30, 36);
const change = { kind: "global-set" as const, props: { x: 30, y: 36 } };
expect(patchTweens({ patches: [{ selector: "#card", change }], seek: false }).patched).toBe(
true,
);
drawDrafts([{ handle, end: "restore" }]);
expect(position).toEqual({ x: 30, y: 36 });
});
it("leaves a position set over the port after the draw when the draft is restored", () => {
const { handle, position, move } = gsapHeld();
move(30, 36);
gsapSet({ handle, props: { x: 12, y: 7 } });
drawDrafts([{ handle, end: "restore" }]);
expect(position).toEqual({ x: 12, y: 7 });
});
});
+68 -6
View File
@@ -3,10 +3,12 @@
* resize here, on the element's inline style, so the preview moves with the pointer. What the
* element had before its first draft is kept until the parent ends the draft or the frame loads again.
*/
import { seekGsapTimeline } from "./adapters/gsap";
import { isStylableElement, type StylableElement as Styled } from "./domRealm";
import { elementForHandle } from "./editingHandles";
import type { EditingDraftEnd, EditingDraftReply } from "./editingDraftEnd";
import type { EditingDraft, EditingDraftRotate } from "./editingPort";
import type { RuntimeTimelineLike } from "./types";
export const SIZE_PROPERTIES = [
"box-sizing",
@@ -26,6 +28,7 @@ interface Before {
translate: string[];
/** GSAP's rotation before the first GSAP turn drawn, to put back on "restore". */
gsapRotation?: number;
gsapPosition?: { x: number; y: number };
drewTransform?: boolean;
}
@@ -36,6 +39,7 @@ type Gsap = {
const frameGsap = () => (window as unknown as { gsap?: Gsap }).gsap;
const before = new WeakMap<Element, Before>();
const liveDrafts = new Map<Styled, EditingDraft>();
let lastDraft = 0;
/** "calc(50% + 2px) 4px" as its top-level parts. */
@@ -115,8 +119,42 @@ export function movedTranslate(
return `calc(${x} + ${offset.x}px) calc(${y} + ${offset.y}px)${z ? ` ${z}` : ""}`;
}
function drawTranslate(element: Styled, offset: { x: number; y: number }): void {
element.style.setProperty("translate", movedTranslate(beforeOf(element).translate, offset));
type DraftTranslate = NonNullable<Extract<EditingDraft, { translate: unknown }>["translate"]>;
function drawTranslate(element: Styled, offset: DraftTranslate): void {
const saved = beforeOf(element);
if (offset.route !== "gsap")
return void element.style.setProperty("translate", movedTranslate(saved.translate, offset));
const gsap = frameGsap();
const read = (axis: string) => Number(gsap?.getProperty?.(element, axis)) || 0;
saved.gsapPosition ??= { x: read("x"), y: read("y") };
element.style.setProperty("translate", "none");
gsap?.set?.(element, { x: offset.x, y: offset.y });
}
export function rebaseDrawnPosition(element: Element, props: Record<string, unknown>): void {
const position = before.get(element)?.gsapPosition;
for (const axis of ["x", "y"] as const) {
const value = props[axis];
if (position && typeof value === "number" && Number.isFinite(value)) position[axis] = value;
}
}
function restoreGsapPosition(element: Styled): void {
const { gsapPosition } = before.get(element) ?? {};
if (gsapPosition) frameGsap()?.set?.(element, { ...gsapPosition });
}
function redrawTimelines(): void {
const timelines = Object.values(
(window as { __timelines?: Record<string, RuntimeTimelineLike> }).__timelines ?? {},
);
for (const timeline of timelines) {
const time = timeline.totalTime?.();
if (typeof time !== "number") continue;
seekGsapTimeline(timeline, 0, true);
seekGsapTimeline(timeline, time, true);
}
}
export function writeDrawnSize(
@@ -158,37 +196,61 @@ function drawRotate(element: Styled, rotate: EditingDraftRotate | null): void {
gsap?.set?.(element, { rotation: rotate.angle });
}
function end(element: Styled, ending: EditingDraftEnd): void {
function end(element: Styled, ending: EditingDraftEnd): boolean {
const saved = before.get(element);
if (!saved || ("draft" in ending && ending.draft !== saved.draft)) return;
if (!saved || ("draft" in ending && ending.draft !== saved.draft)) return false;
if (ending.end === "restore") {
restore(element, DRAWN);
restoreGsapPosition(element);
restoreGsapRotation(element);
}
if (ending.end === "keep-size") restore(element, ["translate"]);
before.delete(element);
liveDrafts.delete(element);
return ending.end === "restore";
}
function apply(element: Styled, draft: EditingDraft): void {
function apply(element: Styled, draft: EditingDraft): boolean {
if ("end" in draft) return end(element, draft);
const last = liveDrafts.get(element);
const keepsRotation = !("rotate" in draft) && last && "rotate" in last;
liveDrafts.set(element, keepsRotation ? { ...draft, rotate: last.rotate } : draft);
if ("rotate" in draft) drawRotate(element, draft.rotate ?? null);
if (draft.translate) drawTranslate(element, draft.translate);
else restore(element, ["translate"]);
if (draft.size) drawSize(element, draft.size);
else restore(element, SIZE_PROPERTIES);
return false;
}
/** Re-renders the timelines, then puts every live draft back over what they drew. */
function redrawOwned(element: Styled, draft: Exclude<EditingDraft, { end: unknown }>): void {
if ("rotate" in draft && draft.rotate) drawRotate(element, draft.rotate);
if (draft.translate) drawTranslate(element, draft.translate);
if (draft.size) drawSize(element, draft.size);
}
function redrawKeepingLiveDrafts(): void {
redrawTimelines();
for (const [element, draft] of liveDrafts) {
if (element.isConnected && !("end" in draft)) redrawOwned(element, draft);
else liveDrafts.delete(element);
}
}
/** Applies each draft in order; one for an element this load no longer has is skipped. */
export function drawDrafts(drafts: readonly EditingDraft[]): EditingDraftReply {
let drawn = 0;
let restored = false;
const numbers: Record<string, number> = {};
for (const draft of drafts) {
const element = elementForHandle(draft.handle);
if (!isStylableElement(element)) continue;
apply(element, draft);
restored = apply(element, draft) || restored;
drawn++;
const saved = before.get(element);
if (saved) numbers[draft.handle] = saved.draft;
}
if (restored) redrawKeepingLiveDrafts();
return { drawn, drafts: numbers };
}
@@ -0,0 +1,151 @@
import gsap from "gsap";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { drawDrafts } from "./editingDraft";
import { handleFor } from "./editingHandles";
import { gsapSet } from "./editing/gsapSet";
import { patchTweens } from "./editing/patchTween";
import { initSandboxRuntimeModular } from "./init";
import { resetRuntimeFixtureDom } from "./runtimeSeekFixture.test-helpers";
import type { RuntimeTimelineLike } from "./types";
beforeEach(() => {
resetRuntimeFixtureDom();
window.gsap = gsap as unknown as typeof window.gsap;
});
afterEach(() => {
window.__hfRuntimeTeardown?.();
vi.restoreAllMocks();
delete window.__player;
delete window.__playerReady;
delete window.__hf;
});
/** At 1 s, `#a` held at x 40 by scene a's set (or `holdA`'s) and at y 30 by a base set, then dragged to (30, 36). */
function dragged(holdA = (a: gsap.core.Timeline) => a.set("#a", { x: 40 }, 0), baseX?: number) {
const clip = (id: string) =>
`<div class="clip" data-composition-id="${id}" data-start="0" data-duration="10"><div id="${id}"></div></div>`;
document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-duration="10">${clip("a")}${clip("b")}</div>`;
const scene = () => gsap.timeline({ paused: true }).to({}, { duration: 5 }, 0);
window.__timelines = {
main: scene(),
a: holdA(scene()),
b: scene().set("#b", { x: 10, rotation: 0 }, 0),
} as unknown as Record<string, RuntimeTimelineLike>;
initSandboxRuntimeModular();
window.__player?.seek(1);
gsap.set("#a", { y: 30, ...(baseX !== undefined && { x: baseX }) });
const handle = handleFor(document.getElementById("a")!);
drawDrafts([{ handle, translate: { x: 30, y: 36, route: "gsap" }, size: null }]);
const restored = () => {
drawDrafts([{ handle, end: "restore" }]);
return { x: Number(gsap.getProperty("#a", "x")), y: Number(gsap.getProperty("#a", "y")) };
};
return { handle, restored };
}
const setX = (selector: string, x: number) => ({
selector,
change: { kind: "set" as const, props: { x } },
});
// fails without the fix: the restore threw x back to the draft's start, 40, under a tween edit the timeline keeps.
// It reverses round 3's (40, 30): after this failure Studio re-runs the saved script, with the edit, sealed or open.
it("shows the timeline's edited x when a batch's later patch misses", () => {
const { restored } = dragged();
expect(patchTweens({ patches: [setX("#a", 50), setX("#missing", 1)], seek: true })).toEqual({
patched: false,
});
expect(restored()).toEqual({ x: 50, y: 30 });
});
// fails without the fix: a drawing batch released x though #a's only tween starts after the playhead, so the restore
// left the cancelled drag's 30.
it("puts back the base when the tween holding the axis has not started", () => {
const { restored } = dragged((a) => a.set("#a", { x: 70 }, 3), 40);
patchTweens({ patches: [setX("#a", 60), setX("#b", 20)], seek: true });
expect(restored()).toEqual({ x: 40, y: 30 });
});
// fails without the fix: the batch's seek drew x 50, then its global-set missed, and the restore threw x back to 40.
it("keeps the x a batch's seek drew when a later base set in it misses", () => {
const { restored } = dragged();
const missingSet = {
selector: "#missing",
change: { kind: "global-set" as const, props: { x: 1 } },
};
expect(
patchTweens({ patches: [setX("#a", 50), setX("#b", 20), missingSet], seek: true }),
).toEqual({
patched: false,
});
expect(restored()).toEqual({ x: 50, y: 30 });
});
it("keeps an earlier batch's x when a batch between it and the drawing batch fails", () => {
const { restored } = dragged();
expect(patchTweens({ patches: [setX("#a", 50)], seek: false })).toEqual({ patched: true });
expect(patchTweens({ patches: [setX("#missing", 1)], seek: false })).toEqual({ patched: false });
expect(patchTweens({ patches: [setX("#b", 20)], seek: true })).toEqual({ patched: true });
expect(restored()).toEqual({ x: 50, y: 30 });
});
it("gives an axis a tween holds at the playhead to the tween, over a base set after the draw", () => {
const { handle, restored } = dragged();
gsapSet({ handle, props: { x: 25, y: 33 } });
expect(restored()).toEqual({ x: 40, y: 33 });
});
it("runs none of the timeline's callbacks when it restores", () => {
const ran = vi.fn();
const { restored } = dragged((a) =>
a.set("#a", { x: 40 }, 0).call(ran, [], 0).call(ran, [], 0.5).eventCallback("onUpdate", ran),
);
ran.mockClear();
restored();
expect(ran).not.toHaveBeenCalled();
});
// fails without the fix: restoring A re-rendered the timelines over B's live drag, back to its scene's x 10.
it("leaves another element's live drag where it is drawn when one draft is restored", () => {
const { restored } = dragged();
const other = handleFor(document.getElementById("b")!);
drawDrafts([{ handle: other, translate: { x: 81, y: 0, route: "gsap" }, size: null }]);
restored();
expect(gsap.getProperty("#b", "x")).toBe(81);
});
// fails without the fix: a restore for a draft already ended still re-rendered, putting the next drag's 71 back to 40.
it("repaints nothing for a restore of a draft that has already ended", () => {
const { handle } = dragged();
const [first] = Object.values(
drawDrafts([{ handle, translate: { x: 30, y: 36, route: "gsap" }, size: null }]).drafts,
);
drawDrafts([{ handle, end: "keep-size" }]);
drawDrafts([{ handle, translate: { x: 71, y: 36, route: "gsap" }, size: null }]);
drawDrafts([{ handle, end: "restore", draft: first! }]);
expect(gsap.getProperty("#a", "x")).toBe(71);
});
// fails without the fix: replaying B's live drag put back B's whole draft, its size too, so restoring A reset the
// width B was given after its draw (120) to the width before it (70).
it("leaves what another live draft does not draw as it is when one draft is restored", () => {
const { restored } = dragged();
const b = document.getElementById("b")!;
b.style.width = "70px";
const other = handleFor(b);
drawDrafts([{ handle: other, translate: { x: 81, y: 0, route: "gsap" }, size: null }]);
gsapSet({ handle: other, props: { width: 120 } });
restored();
expect([b.style.width, gsap.getProperty("#b", "x")]).toEqual(["120px", 81]);
});
// fails without the fix: the replay kept only B's last draft, a move with no rotation in it, so the redraw left B at
// its scene's rotation 0 and lost the 30 an earlier draft turned it to.
it("keeps the rotation an earlier draft drew on another live element when one draft is restored", () => {
const { restored } = dragged();
const other = handleFor(document.getElementById("b")!);
drawDrafts([{ handle: other, rotate: { route: "gsap", angle: 30 }, size: null }]);
drawDrafts([{ handle: other, translate: { x: 81, y: 0, route: "gsap" }, size: null }]);
restored();
expect([gsap.getProperty("#b", "rotation"), gsap.getProperty("#b", "x")]).toEqual([30, 81]);
});
@@ -179,7 +179,12 @@ describe("gesture start", () => {
])("owns its position through %s", (_name, make, moving) => {
const card = turnedCard("");
gsapWith([make(card), tween(card, { opacity: 0 }, 3)]);
expect(gestureStart([handleFor(card)]).elements[0]!.gsap).toEqual({ x: 200, y: 5, moving });
expect(gestureStart([handleFor(card)]).elements[0]!.gsap).toEqual({
x: 200,
y: 5,
moving,
drawsTranslate: true,
});
});
// fails without the fix: a sealed rotate never learned GSAP turns the element, so it saved a CSS rotate.
@@ -30,7 +30,7 @@ export interface EditingGestureStart extends EditingElementGeometry {
/** Frame px its centre moves per px of drawn width, `a, b`, and height, `c, d`; null when it has no box. */
grow: { a: number; b: number; c: number; d: number } | null;
/** Set when GSAP owns its position: its x/y now, and whether a tween with a duration moves it. */
gsap: { x: number; y: number; moving: boolean } | null;
gsap: { x: number; y: number; moving: boolean; drawsTranslate: true } | null;
/** GSAP's rotation now when it owns the element's turn; null when it turns by its own CSS `rotate`. */
gsapRotation: number | null;
cssRotation: CssRotationStart | null;
@@ -186,7 +186,7 @@ function gsapPosition(element: Element): EditingGestureStart["gsap"] {
const tweens = tweensOn(element).filter((tween) => tween.vars && carries(tween.vars, MOVES));
if (!rendersTransform(element) && !tweens.length) return null;
const moving = tweens.some((tween) => (tween.duration?.() ?? 0) > 0);
return { x: readGsap(element, "x"), y: readGsap(element, "y"), moving };
return { x: readGsap(element, "x"), y: readGsap(element, "y"), moving, drawsTranslate: true };
}
function gsapRotation(element: Element): number | null {
+9 -6
View File
@@ -265,7 +265,7 @@ export type { EditingDraftEnd };
export type EditingDraft =
| {
handle: EditingElementHandle;
translate: { x: number; y: number } | null;
translate: { x: number; y: number; route?: "gsap" } | null;
size: { width: number; height: number } | null;
rotate?: EditingDraftRotate | null;
}
@@ -509,6 +509,13 @@ const isRotateRoute = (value: unknown): value is Record<string, unknown> =>
value.route === "transform" &&
isTransformList(value.value));
function draftTranslate(value: unknown): boolean {
if (!hasKeys(value, "route,x,y")) return draftPart(value, "x,y", -MAX_DRAFT_PX);
return (
value.route === "gsap" && isDraftPx(value.x, -MAX_DRAFT_PX) && isDraftPx(value.y, -MAX_DRAFT_PX)
);
}
function draftRotate(value: unknown): boolean {
if (value === undefined || value === null) return true;
if (!isRotateRoute(value)) return false;
@@ -525,11 +532,7 @@ function drawnParts(value: Record<string, unknown>): boolean {
const { translate, size, rotate } = value;
if (!hasKeys(value, "handle,size,translate") && !hasKeys(value, "handle,rotate,size,translate"))
return false;
return (
draftPart(translate, "x,y", -MAX_DRAFT_PX) &&
draftPart(size, "height,width", 0) &&
draftRotate(rotate)
);
return draftTranslate(translate) && draftPart(size, "height,width", 0) && draftRotate(rotate);
}
function draftList(params: unknown): EditingParams<"draft"> | null {
@@ -5,7 +5,7 @@ import {
type StudioPathOffsetSnapshot,
} from "./manualEdits";
import { readTranslatePx } from "./plainTranslate";
import { drawPreviewDraft } from "./previewDrafts";
import { drawPreviewDraft, frameDraftTranslate } from "./previewDrafts";
import { getOffsetDragGsap, type ManualOffsetDragMember } from "./manualOffsetDrag";
import { stampGestureBase } from "../../hooks/draggedGsapPosition";
import type { StudioEditRevert } from "../../utils/studioPendingEdits";
@@ -50,11 +50,15 @@ function showMemberPosition(member: ManualOffsetDragMember, position: MemberPosi
}
function redrawMemberOnFrame(member: ManualOffsetDragMember): void {
const { element, initialOffset } = member;
const { element, committedOnFrame } = member;
if (member.frameDraftRoute === "gsap") {
if (committedOnFrame !== undefined) drawPreviewDraft(element, { translate: committedOnFrame });
return;
}
const offset = member.plainTranslate
? readTranslatePx(element)
: readAppliedStudioPathOffset(element);
const translate = { x: offset.x - initialOffset.x, y: offset.y - initialOffset.y };
const translate = frameDraftTranslate(member, offset);
if (Number.isFinite(translate.x) && Number.isFinite(translate.y) && (translate.x || translate.y))
drawPreviewDraft(element, { translate });
}
@@ -17,9 +17,11 @@ import {
applyManualOffsetDragDraft,
createManualOffsetDragMember,
endManualOffsetDragMembers,
restoreManualOffsetDragMembers,
type ManualOffsetDragMember,
} from "./manualOffsetDrag";
import { armPreviewDraftEnd, drawPreviewDraft, endPreviewDraft } from "./previewDrafts";
import { manualOffsetMoveRevert } from "./gestureUndoRevert";
import { patchSealedPreview } from "../../hooks/sealedTweenPatch";
import { takePreviewTicket } from "../../utils/sealedPreviewLedger";
import { previewAnswer, previewRequest } from "../../player/lib/previewChannel";
@@ -152,14 +154,8 @@ const press = () =>
currentTarget: { setPointerCapture() {} },
}) as unknown as React.PointerEvent<HTMLElement>;
/** Presses the box on a sealed frame, drags it 10 page px right and lets go, as the overlay does. */
async function dragBoxOnSealedFrame(
script: string,
beforePress?: (iframe: HTMLIFrameElement) => void,
beforeEnd?: (standIn: Element, member: ManualOffsetDragMember) => void,
save?: (iframe: HTMLIFrameElement, standIn: Element) => Promise<unknown>,
) {
const box = document.getElementById("box")!;
/** Presses the box on a sealed frame, as the overlay does. */
async function pressBoxOnSealedFrame(beforePress?: (iframe: HTMLIFrameElement) => void) {
const iframe = opaqueFrame();
beforePress?.(iframe);
const handle = (await queryPreviewElements(iframe, "#box"))!.matches[0]!.handle;
@@ -171,10 +167,23 @@ async function dragBoxOnSealedFrame(
const started = startGesture("drag", press(), opts, { selection, rect, start, snap: read!.snap });
expect(opts.onBlockedMoveRef.current).not.toHaveBeenCalled();
const member = opts.gestureRef.current!.pathOffsetMember!;
return { iframe, standIn, selection, start, started, member };
}
/** Presses the box on a sealed frame, drags it 10 page px right and lets go, as the overlay does. */
async function dragBoxOnSealedFrame(
script: string,
beforePress?: (iframe: HTMLIFrameElement) => void,
beforeEnd?: (standIn: Element, member: ManualOffsetDragMember) => void,
save?: (iframe: HTMLIFrameElement, standIn: Element) => Promise<unknown>,
) {
const box = document.getElementById("box")!;
const { iframe, standIn, selection, start, started, member } =
await pressBoxOnSealedFrame(beforePress);
// A page px is two frame px: the frame shows 1920 px in 960.
applyManualOffsetDragDraft(member, 10, 0);
await vi.waitFor(() => expect(drawnAt(box)).toEqual({ x: 120, y: 40 }));
await vi.waitFor(() => expect(drawnAt(box)).toEqual({ x: start.gsap!.x + 20, y: start.gsap!.y }));
const offset = applyManualOffsetDragCommit(member, 10, 0);
const commit = vi.fn(async () => undefined);
@@ -213,6 +222,73 @@ it("leaves no Studio offset on the stand-in once a sealed drag ends on GSAP's ro
expect((standIn as HTMLElement).style.getPropertyValue("--hf-studio-offset-x")).toBe("");
});
const writes = (box: HTMLElement) => [box.style.transform, box.style.translate];
// fails without the fix: the sealed draft drew a CSS translate on top of GSAP's, at another precision than the x/y an
// open preview's drag gives GSAP, so a sealed drop point and the x it saved came out 0.001 px off.
it("draws a sealed drag of a GSAP-held layer with the writes an open preview's drag makes", async () => {
mount(SCRIPT);
let sealed: string[] = [];
await dragBoxOnSealedFrame(SCRIPT, undefined, () => (sealed = writes(box())));
mount(SCRIPT);
const rect = { left: 300, top: 200, width: 100, height: 50, editScaleX: 1, editScaleY: 1 };
const element = box();
const open = createManualOffsetDragMember({
key: "box",
selection: makeSelection("box", element),
element,
rect,
gesture: "drag",
});
if (!open.ok) throw new Error("no open member");
applyManualOffsetDragDraft(open.member, 20, 0);
expect(writes(element)).toEqual(sealed);
});
/** The frame's writes for a drag of `frameDx` frame px, sealed then open: a page px is two frame px sealed. */
async function sealedAndOpenWrites(script: string, frameDx: number) {
mount(script);
const { member } = await pressBoxOnSealedFrame();
const from = drawnAt(box()).x;
applyManualOffsetDragDraft(member, frameDx / 2, 0);
await vi.waitFor(() => expect(drawnAt(box()).x).toBeGreaterThan(from + frameDx - 1));
const sealed = [writes(box()), drawnAt(box())];
mount(script);
const element = box();
const rect = { left: 300, top: 200, width: 100, height: 50, editScaleX: 1, editScaleY: 1 };
const selection = makeSelection("box", element);
const open = createManualOffsetDragMember({
key: "box",
selection,
element,
rect,
gesture: "drag",
});
if (!open.ok) throw new Error("no open member");
applyManualOffsetDragDraft(open.member, frameDx, 0);
return { sealed, open: [writes(element), drawnAt(element)] };
}
// fails without the fix: a sealed drag gave the frame the unrounded offset, where an open preview's drag rounds the
// position it writes to 3 decimals, so the drawn box and the drop point measured from it came out up to 0.0005 px off.
it.each([
["a GSAP-held layer, on GSAP's route", SCRIPT],
["a layer GSAP leaves alone, on its own translate", timeline("")],
])("draws a sealed drag of %s at the position an open drag rounds to", async (_name, script) => {
const { sealed, open } = await sealedAndOpenWrites(script, 20.00074);
expect(sealed[1]).toEqual(open[1]);
});
it("puts a cancelled sealed drag of a GSAP-held layer back where GSAP had it", async () => {
mount(SCRIPT);
await dragBoxOnSealedFrame(SCRIPT, undefined, (_standIn, member) =>
restoreManualOffsetDragMembers([member]),
);
await vi.waitFor(() =>
expect([box().style.translate, drawnAt(box())]).toEqual(["", { x: 100, y: 40 }]),
);
});
// fails without the fix: ending the draft on GSAP's route took back the size a resize had drawn too.
it("keeps the size a sealed resize drew when its anchor ends on GSAP's route", async () => {
mount(SCRIPT);
@@ -241,7 +317,7 @@ it("drags a layer its tween moves in a sealed preview: it moves live and saves a
mount(SCRIPT);
const { started, start, anim, outcome, commit } = await dragBoxOnSealedFrame(SCRIPT);
expect(start.gsap).toEqual({ x: 100, y: 40, moving: true });
expect(start.gsap).toEqual({ x: 100, y: 40, moving: true, drawsTranslate: true });
expect(started).toBe(true);
expect(outcome).toEqual({ status: "persisted" });
expect(commit).toHaveBeenCalledTimes(1);
@@ -287,7 +363,7 @@ it("saves nothing for a moving layer when the sealed preview's tweens can't be r
mount(script, SPANS);
const { start, outcome, commit } = await dragBoxOnSealedFrame(script);
expect(start.gsap).toEqual({ x: 100, y: 40, moving: true });
expect(start.gsap).toEqual({ x: 100, y: 40, moving: true, drawsTranslate: true });
// Routed without the frame's tweens, the move would save a `set` that pins the layer.
expect(outcome).toEqual({
status: "blocked",
@@ -302,7 +378,7 @@ it("still saves a layer GSAP only holds when the sealed preview's tweens can't b
mount(script, SPANS);
const { start, outcome, commit } = await dragBoxOnSealedFrame(script);
expect(start.gsap).toEqual({ x: 100, y: 40, moving: false });
expect(start.gsap).toEqual({ x: 100, y: 40, moving: false, drawsTranslate: true });
expect(outcome).toEqual({ status: "persisted" });
expect(commit).toHaveBeenCalledTimes(1);
// The hold's own `set` takes the new place, as when the frame's tweens are read.
@@ -332,7 +408,7 @@ it("a resize in a sealed preview keeps the anchor of a layer its tween moves on
start,
});
expect(start.gsap).toEqual({ x: 100, y: 40, moving: true });
expect(start.gsap).toEqual({ x: 100, y: 40, moving: true, drawsTranslate: true });
expect(result.ok && result.member.plainTranslate).toBe(false);
});
@@ -460,7 +536,7 @@ it("keeps a sealed element's move start when GSAP's rotation is out of range, an
const overlay = sized(document.createElement("div"), [20, 10, 1200, 800]);
const { start } = (await measurePreviewGestureStart(iframe, overlay, [handle]))!.elements[0]!;
expect(start.gsap).toEqual({ x: 100, y: 40, moving: true });
expect(start.gsap).toEqual({ x: 100, y: 40, moving: true, drawsTranslate: true });
expect(start.gsapRotation).toBeUndefined();
});
@@ -510,6 +586,31 @@ it("a sealed move's save ends its draft in the same frame message, and the teard
expect(iframe).toBeDefined();
});
// fails without the fix: the undo's redraw on GSAP's route sent the press position (the stand-in keeps no path offset
// there), and skipped a draft of (0, 0) as a relative move of nothing; the layer stayed where the undo had put it.
it.each([
[
"(0, 0)",
timeline(`tl.to("#box", { x: -40, y: 0, duration: 1, ease: "none" }, 0);`),
{ x: -20, y: 0 },
],
["(120, 40)", SCRIPT, { x: 100, y: 40 }],
])(
"puts a sealed GSAP move that ended at %s back there when its undo does not go through",
async (_name, script, start) => {
mount(script);
const { member } = await dragBoxOnSealedFrame(script);
const box = document.getElementById("box")!;
const end = { x: start.x + 20, y: start.y };
await vi.waitFor(() => expect(drawnAt(box)).toEqual(end));
const putBack = manualOffsetMoveRevert([member])();
// The undo's write reaching the frame, which the redraw must paint over.
gsap.set(box, start);
putBack();
await vi.waitFor(() => expect(drawnAt(box)).toEqual(end));
},
);
// fails without the fix: a gesture with no save ended its draft as {translate:null} then {end:keep}, two messages.
it("a sealed move with no save ends its draft once, as one end", async () => {
mount(SCRIPT);
@@ -554,9 +655,11 @@ describe("a newer gesture that takes the element before the older save lands", (
});
});
// The box's tween starts after the playhead, so the older save's base set is what the frame shows there.
it("puts a cancelled regrab back where the older save left it, not where the older drag began", async () => {
mount(SCRIPT);
await dragBoxOnSealedFrame(SCRIPT, undefined, regrab(7), async (iframe, standIn) => {
const later = timeline(`tl.to("#box", { x: 200, y: 80, duration: 1, ease: "none" }, 5);`);
mount(later);
await dragBoxOnSealedFrame(later, undefined, regrab(7), async (iframe, standIn) => {
await savePosition({ kind: "global-set", props: { x: 110, y: 40 } })(iframe);
endPreviewDraft(standIn, "restore");
await vi.waitFor(() => expect(box().style.translate).toBe(""));
@@ -21,7 +21,7 @@ import {
} from "../../hooks/draggedGsapPosition";
import { editsPlainCss } from "../../hooks/gsapRuntimeKeyframes";
import { readTranslatePx, UNREADABLE_TRANSLATE, writeTranslatePx } from "./plainTranslate";
import { drawPreviewDraft, endPreviewDraft } from "./previewDrafts";
import { drawPreviewDraft, endPreviewDraft, frameDraftTranslate } from "./previewDrafts";
import {
armDraftEndOnRelease,
endDraftKeepingWhatTheSaveWrites,
@@ -96,6 +96,8 @@ export interface ManualOffsetDragMember {
/** The move writes the element's own inline `translate`; offsets are then absolute translate px. */
plainTranslate: boolean;
gsapOwnsPosition: boolean;
frameDraftRoute?: "gsap";
committedOnFrame?: { x: number; y: number; route?: "gsap" };
sizeSavedAsScale?: boolean;
/**
* The element's GSAP x/y at gesture start, captured in JS so a mid-drag
@@ -358,6 +360,7 @@ export function createManualOffsetDragMember(input: {
const baseGsap = start?.gsap ? { x: start.gsap.x, y: start.gsap.y } : { x: gsapX, y: gsapY };
const moving = start?.gsap?.moving === true;
const gsapOwnsPosition = !plainTranslate && Boolean(start ?? getOffsetDragGsap(input.element));
const frameDraftRoute = gsapOwnsPosition && start?.gsap?.drawsTranslate ? "gsap" : undefined;
if (!plainTranslate) stampGestureBase(input.element, initialOffset, baseGsap, moving);
if (win?.__timelines) {
@@ -404,6 +407,7 @@ export function createManualOffsetDragMember(input: {
initialOffset,
plainTranslate,
gsapOwnsPosition,
...(frameDraftRoute && { frameDraftRoute }),
baseGsap,
...(moving && { moving }),
initialPathOffset,
@@ -423,6 +427,7 @@ export function createManualOffsetDragMember(input: {
initialOffset,
plainTranslate,
gsapOwnsPosition,
...(frameDraftRoute && { frameDraftRoute }),
baseGsap,
...(moving && { moving }),
initialPathOffset,
@@ -452,8 +457,9 @@ function drawMemberOffset(
offset: { x: number; y: number },
commit: boolean,
): void {
const { x, y } = member.initialOffset;
drawPreviewDraft(member.element, { translate: { x: offset.x - x, y: offset.y - y } });
const translate = frameDraftTranslate(member, offset);
drawPreviewDraft(member.element, { translate });
if (commit) member.committedOnFrame = translate;
if (member.plainTranslate) writeTranslatePx(member.element, offset);
else if (applyOffsetDragDraftViaGsap(member.element, offset, member.baseGsap)) return;
else if (commit) applyStudioPathOffset(member.element, offset);
@@ -21,7 +21,12 @@ import {
type ManualOffsetDragMember,
} from "./manualOffsetDrag";
import { endResizeWithoutMember, resolveResizeDraftRect } from "./resizeDraft";
import { armPreviewDraftEnd, drawPreviewDraft, takePreviewDraftEnds } from "./previewDrafts";
import {
armPreviewDraftEnd,
drawPreviewDraft,
frameDraftTranslate,
takePreviewDraftEnds,
} from "./previewDrafts";
import { applySoftReloadFinalization } from "../../utils/gsapSoftReload";
import type { DomEditSelection } from "./domEditing";
import type { GestureState } from "./domEditOverlayGestures";
@@ -79,6 +84,21 @@ const shown = (element: HTMLElement) =>
[...axis.matchAll(/-?[\d.]+px/g)].reduce((sum, [px]) => sum + parseFloat(px), 0),
);
// fails without the fix: the frame got the raw offset, where an open preview's drag writes it rounded to 3 decimals.
describe("the translate a drag sends the frame", () => {
it("is the open preview's rounded offset less where the layer started", () => {
const member = {
element: document.createElement("div"),
initialOffset: { x: 10.5555, y: -3.25 },
baseGsap: { x: 0, y: 0 },
};
expect(frameDraftTranslate(member, { x: 30.55624, y: 4.0004 })).toEqual({
x: 30.556 - 10.5555,
y: 4 + 3.25,
});
});
});
describe("gesture drafts on an opaque frame", () => {
it("moves the frame's element with a drag, and puts it back when the drag is cancelled", async () => {
const member = dragMember(await standIn(sealedPreviewFrame().iframe, "#card"));
@@ -9,10 +9,12 @@ import {
type EditingDraftEnd,
type EditingDraftRotate,
} from "@hyperframes/core/runtime/editing-port";
import { computeDraggedGsapPosition } from "../../hooks/draggedGsapPosition";
import { roundTo3 } from "../../utils/rounding";
import { previewRequest } from "../../player/lib/previewChannel";
type Drawn = {
translate: { x: number; y: number } | null;
translate: { x: number; y: number; route?: "gsap" } | null;
size: { width: number; height: number } | null;
rotate?: EditingDraftRotate | null;
};
@@ -87,6 +89,24 @@ function sendOnMicrotask(iframe: HTMLIFrameElement, queue: Queue): void {
});
}
type Point = { x: number; y: number };
type DraftedMember = {
element: HTMLElement;
initialOffset: Point;
baseGsap: Point;
frameDraftRoute?: "gsap";
};
export function frameDraftTranslate(member: DraftedMember, offset: Point) {
if (member.frameDraftRoute !== "gsap")
return {
x: roundTo3(offset.x) - member.initialOffset.x,
y: roundTo3(offset.y) - member.initialOffset.y,
};
const { newX, newY } = computeDraggedGsapPosition(member.element, offset, member.baseGsap);
return { x: newX, y: newY, route: "gsap" as const };
}
/** Draws `part` of the stand-in's draft on its frame element; any other element is left alone. */
export function drawPreviewDraft(element: Element, part: Partial<Drawn>): void {
const target = standIns.get(element);
@@ -216,7 +216,7 @@ describe("a gesture's start on an opaque frame", () => {
expect(start).toEqual({
layout: { width: 200, height: 100 },
screenToOffset: { a: -2, b: 0, c: 0, d: 2 },
gsap: { x: 200, y: 5, moving: false },
gsap: { x: 200, y: 5, moving: false, drawsTranslate: true },
gsapRotation: 0,
grow: { a: -0.25, b: 0, c: 0, d: 0.25 },
cssRotation: null,
@@ -17,7 +17,7 @@ export interface PreviewGestureStart {
/** Pointer px to translate px, as `measureManualOffsetDragScreenToOffsetMatrix`; null when unmeasured. */
screenToOffset: ManualOffsetDragMatrix | null;
/** GSAP's x/y when it owns the element's position, and whether a tween with a duration moves it. */
gsap: { x: number; y: number; moving: boolean } | null;
gsap: { x: number; y: number; moving: boolean; drawsTranslate?: true } | null;
gsapRotation?: number | null;
grow?: { a: number; b: number; c: number; d: number };
cssRotation?: EditingGestureStart["cssRotation"];
@@ -116,6 +116,43 @@ it("leaves the render to the group's last write", () => {
expect(previewRequest.mock.calls[0]?.[2]).toMatchObject({ seek: false });
});
// A failed batch leaves a person the saved script re-run, as an open preview's one-miss batch does (the test of
// applyPreviewSync's unsealed path, "one patch that misses falls the whole batch back to the reload").
it("re-runs the saved script after a batch whose second patch misses", async () => {
const saved = {
ok: true,
scriptText: `window.__timelines["main"] = gsap.timeline().set("#a", { x: 50 });`,
before: "<html><body><div id='a'></div><div id='b'></div></body></html>",
after: "<html><body><div id='a'></div><div id='b'></div></body></html>",
};
previewRequest.mockImplementation(async (_iframe, kind) =>
kind === "patch-tweens" ? { patched: false } : { result: "applied" },
);
const reloadPreview = vi.fn();
applyPreviewSync(
iframe,
saved,
{
label: "Move animated layer (group)",
softReload: true,
instantPatches: [
{ selector: "#a", change: { kind: "set" as const, props: { x: 50 } } },
{ selector: "#b", change: { kind: "set" as const, props: { x: 2 } } },
],
},
reloadPreview,
);
await vi.waitFor(() =>
expect(
previewRequest.mock.calls.map(([, kind]) => kind).filter((kind) => kind !== "gsap-snapshot"),
).toEqual(["patch-tweens", "soft-reload"]),
);
const rerun = previewRequest.mock.calls.find(([, kind]) => kind === "soft-reload")?.[2];
expect(JSON.stringify(rerun)).toContain("x: 50");
expect(reloadPreview).not.toHaveBeenCalled();
});
// fails without the fix: a refused sealed patch remounted the whole preview instead of re-running the script.
it("re-runs the saved script in place when the frame refuses a patch of a soft-reloadable edit", async () => {
const saved = {