fix(studio): a sealed scale resize lands where it was dropped (#8301)

* fix(studio): arrow keys nudge the selected element in a sealed preview

A sealed preview's selection is a stand-in that is never in the page, so the nudge's check that the element is still
there refused every key and nothing moved. It now uses the same check the selection publisher uses, which keeps a
sealed selection until it is replaced.

* fix(studio): a sealed nudge moves an animated element by its tween and saves where it was drawn

A sealed preview's selected element is a stand-in with no animation or translate of its own, so a nudge guessed both from an empty page: it wrote a plain translate over the stylesheet's and the element landed elsewhere after a reload. The nudge now waits for the frame's gesture-start read, the one a press uses, and keys pressed meanwhile join the burst.

* test(studio): pass the nudge its frame refs in the undo paint test

* fix(studio): a sealed move on GSAP's route lands where it was drawn, not twice as far

When a move ends, the sealed frame kept the translate the gesture drew. A move on GSAP's route saves the new position as GSAP's x and y, so the layer then showed the move twice until the frame loaded again. The frame now drops the drawn translate for those moves; a move saved as a plain translate still keeps it.

* refactor(studio): split the sealed nudge key handler so each step reads on its own

* fix(studio): a sealed nudge waiting on its frame gives way to a drag, selection or other edit

* fix(studio): an arrow pressed while a canvas press waits on the preview does not start a nudge

* fix(studio): a sealed resize on GSAP's route keeps the size it drew when it ends

* refactor(studio): name the size-keeping draft end instead of commenting it

* fix(studio): a sealed resize saved as GSAP scale drops the size it drew when it ends

* fix(studio): a sealed scale resize lands on its drop point

* fix(studio): a sealed resize keeps its drawn size unless its save wrote the size as scale

* refactor(studio): measure a scale resize's drop in helpers, live or sealed

* chore(studio): keep the resize intercept's complexity exemption on the intercept

* fix(studio): a whole-tween resize of a width/height tween says it saved the size, not scale

* test(studio): cover the resize writer's held-size and unnamed-element returns

* test(studio): reach the resize writer's no-selector refusal with an element no selector addresses

* fix(studio): read a live scale resize's pre-gesture position while its edit is shown, as before

* refactor(studio): move the scale drop-point correction out of the resize intercept
This commit is contained in:
Miguel Ángel
2026-11-22 23:20:50 +00:00
committed by GitHub
parent cda1b00820
commit 513dcce820
5 changed files with 243 additions and 60 deletions
@@ -24,6 +24,7 @@ interface Queue {
ops: EditingDraft[];
drawn: Map<string, Entry>;
sending: boolean;
sent: Array<() => void>;
sendsAtTaskEnd: boolean;
}
@@ -50,7 +51,7 @@ export function previewDraftLive(standIn: Element): boolean {
function queueFor(iframe: HTMLIFrameElement): Queue {
let queue = queues.get(iframe);
if (!queue) {
queue = { ops: [], drawn: new Map(), sending: false, sendsAtTaskEnd: false };
queue = { ops: [], drawn: new Map(), sending: false, sent: [], sendsAtTaskEnd: false };
queues.set(iframe, queue);
}
return queue;
@@ -59,7 +60,8 @@ function queueFor(iframe: HTMLIFrameElement): Queue {
const opGesture = new WeakMap<EditingDraft, object>();
function send(iframe: HTMLIFrameElement, queue: Queue): void {
if (queue.sending || !queue.ops.length) return;
if (queue.sending) return;
if (!queue.ops.length) return void queue.sent.splice(0).forEach((done) => done());
const drafts = queue.ops.splice(0, MAX_DESCRIBE_HANDLES);
queue.sending = true;
void previewRequest(iframe, "draft", { drafts })
@@ -168,3 +170,9 @@ function endDraft(element: Element, end: EditingDraftEnd["end"]): void {
);
send(target.iframe, queue);
}
export function previewDraftsSent(iframe: HTMLIFrameElement): Promise<void> {
const queue = queueFor(iframe);
if (!queue.sending && !queue.ops.length) return Promise.resolve();
return new Promise((done) => queue.sent.push(done));
}
@@ -20,6 +20,13 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { usePlayerStore } from "../player/store/playerStore";
import { tryGsapResizeIntercept } from "./gsapResizeIntercept";
import { drawPreviewDraft, previewDraftsSent } from "../components/editor/previewDrafts";
import { measurePreviewGestureStart } from "../components/editor/previewGestureStartRead";
import {
findPreviewElementForSelection,
resolvePreviewSelection,
} from "../components/editor/previewSelection";
import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers";
afterEach(() => {
vi.restoreAllMocks();
@@ -431,3 +438,83 @@ it("lands on the drop point when undo paints the box back while its animations l
expect(settled.y).toBeCloseTo(dropPoint.y, 0);
expect(settled.w).toBeCloseTo(dropPoint.w, 0);
});
it("lands on the drop point in a sealed preview, measured by the frame, with no second move", async () => {
const box = { w: 630, h: 252 };
const base = { x: 489, y: 195 };
const drop = { w: 900, h: 360, x: 300, y: 100 };
document.body.innerHTML = `<div id="clip"></div>`;
const el = document.getElementById("clip")!;
Object.defineProperties(el, { offsetWidth: { value: box.w }, offsetHeight: { value: box.h } });
const live: Pose = { box: { ...box }, pos: { ...base }, scale: { x: 1, y: 1 } };
// The frame's element: the draft's inline size and translate while drawn, GSAP's pose under them.
el.getBoundingClientRect = () => {
const [tx = 0, ty = 0] = (el.style.getPropertyValue("translate") || "0 0")
.split(" ")
.map((axis) => Number.parseFloat(axis) || 0);
const w = Number.parseFloat(el.style.width) || box.w;
const h = Number.parseFloat(el.style.height) || box.h;
const pos = { x: live.pos.x + tx, y: live.pos.y + ty };
const rect = renderRect({ ...live, pos, box: { w, h } }, 0);
return { ...rect, width: rect.w, height: rect.h } as unknown as DOMRect;
};
Object.assign(window, {
gsap: {
set: (_target: Element, vars: Record<string, number>) => {
if (vars.x != null) live.pos.x = vars.x;
if (vars.y != null) live.pos.y = vars.y;
if (vars.scaleX != null) live.scale.x = vars.scaleX;
if (vars.scaleY != null) live.scale.y = vars.scaleY;
},
getProperty: () => 0,
},
});
const { iframe } = sealedPreviewFrame();
const found = await findPreviewElementForSelection(
iframe,
{ id: "clip", sourceFile: "index.html" },
"index.html",
);
const selection = (await resolvePreviewSelection(iframe, found!, {
activeCompositionPath: "index.html",
isMasterView: false,
skipSourceProbe: true,
}))!;
await measurePreviewGestureStart(iframe, document.createElement("div"), [selection.handle!]);
drawPreviewDraft(selection.element, {
size: { width: drop.w, height: drop.h },
translate: { x: drop.x - base.x, y: drop.y - base.y },
});
await previewDraftsSent(iframe);
const dropPoint = el.getBoundingClientRect();
const animations = [scaleTween(false), positionAnimation("static-set", base)!];
const commitMutation = vi.fn();
const outcome = await tryGsapResizeIntercept(
selection,
{ width: drop.w, height: drop.h },
animations,
iframe,
commitMutation,
async () => animations,
{ x: drop.x - base.x, y: drop.y - base.y },
undefined,
{
origX: 0,
origY: 0,
baseX: base.x,
baseY: base.y,
at: { time: 0, keyframePct: null },
frozen: true,
},
);
expect(outcome).toMatchObject({ status: "persisted", ownsDragOffset: true });
const written = persistedPositions(commitMutation.mock.calls).at(-1);
const scale = persistedScale(commitMutation.mock.calls)!;
const settled = renderRect({ box, pos: { x: written!.x!, y: written!.y! }, scale }, 0);
for (const shown of [settled, el.getBoundingClientRect()]) {
expect(shown.x).toBeCloseTo(dropPoint.x, 0);
expect(shown.y).toBeCloseTo(dropPoint.y, 0);
}
});
@@ -12,11 +12,7 @@ import {
STUDIO_ORIGINAL_BOX_HEIGHT_ATTR,
STUDIO_ORIGINAL_BOX_WIDTH_ATTR,
} from "../components/editor/manualEditsTypes";
import {
setElementGsapPosition,
setElementGsapScale,
setElementGsapSize,
} from "../utils/elementGsap";
import { setElementGsapPosition, setElementGsapSize } from "../utils/elementGsap";
import { usePlayerStore } from "../player/store/playerStore";
import { readGsapProperty } from "./gsapRuntimeReaders";
import { gestureStartLayout } from "../components/editor/previewGestureStartRead";
@@ -50,6 +46,8 @@ import {
import { commitValueAtPlayhead } from "./gsapValueAtPlayhead";
import { preflightGsapResizeIntercept, resizeRoute } from "./gsapResizePreflight";
import { singleKeyTweenMutation } from "./useEnableKeyframes";
import { drawFramePosition, sealedScaleFrame } from "./scaleDropOnFrame";
import { correctOnElement, correctOnFrame, dropPointOf } from "./scaleDropPoint";
const SIZE_PROPS = new Set(["width", "height"]);
const POSITION_XY = new Set(["x", "y"]);
@@ -185,10 +183,6 @@ function tweenUsesScaleLonghands(anim: GsapAnimation | null): boolean {
// ── Resize intercept ──────────────────────────────────────────────────────
// The resize is centre-anchored, so a scale that cannot reproduce the dragged size splits the gap evenly.
function rectCentre(rect: DOMRect): { x: number; y: number } {
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
}
// fallow-ignore-next-line complexity
export async function tryGsapResizeIntercept(
selection: DomEditSelection,
@@ -393,9 +387,7 @@ export async function tryGsapResizeIntercept(
: { x: newScaleX, y: newScaleX };
// Where the user DROPPED the box: the draft is still applied, so this is what the preview showed
// at release. The finalize step below moves the committed scale's box onto it.
if (el) {
scaleDraftDropPoint = draw(() => rectCentre(el.getBoundingClientRect()));
}
scaleDraftDropPoint = await dropPointOf(el, selection.element, draw);
} else {
resizeProps = {
width: roundToLayoutPx(size.width),
@@ -415,25 +407,19 @@ export async function tryGsapResizeIntercept(
// perspective it is approximate.
// fallow-ignore-next-line complexity
const finalizeScaleResizeCommit = async (): Promise<boolean> => {
// Only the scale route captures the element, so a null draft means this
// resize took the size route and never moved anything: the drop point is
// the drag's to settle, not ours.
if (!scaleDraftEl) return false;
// Only the scale route captures the element (sealed: its frame's), so without one this
// resize took the size route and never moved anything: the drop point is the drag's to settle.
const frame = scaleDraftEl ? null : sealedScaleFrame(selection.element);
if (!scaleDraftEl && !frame) return false;
const draftEl = scaleDraftEl;
if (!scaleDraftDropPoint || !selector) {
draw(() => clearStudioBoxSize(draftEl));
if (draftEl) draw(() => clearStudioBoxSize(draftEl));
return false;
}
const dropPoint = scaleDraftDropPoint;
const measured = draw(() => {
clearStudioBoxSize(draftEl);
// Draw the committed scale before measuring: on a first resize the timeline has not re-seeked yet,
// so the box would read at its natural size and the correction would be skipped.
if (committedScale) {
setElementGsapScale(draftEl, committedScale.x, committedScale.y);
}
// Measure from the pre-gesture position: the scale route never saves the draft's translation, and
// the position write composes the residual onto that same base.
// Measure from the pre-gesture position: the scale route never saves the draft's translation, and
// the position write composes the residual onto that same base.
const preGesture = () => {
const gsapPos = readGsapPositionFromIframe(iframe, selector) ?? { x: 0, y: 0 };
const { baseGsapX, baseGsapY } = computeDraggedGsapPosition(
selection.element,
@@ -441,38 +427,13 @@ export async function tryGsapResizeIntercept(
gsapPos,
stamp,
);
const base = { x: baseGsapX, y: baseGsapY };
setElementGsapPosition(draftEl, base.x, base.y);
const post = rectCentre(draftEl.getBoundingClientRect());
const residual = { x: dropPoint.x - post.x, y: dropPoint.y - post.y };
if (!Number.isFinite(residual.x) || !Number.isFinite(residual.y)) return null;
// The ONE corrected position — rounded once so the live runtime and the
// persisted file agree exactly (commitStaticGsapPosition composes the same
// rounded value from this delta).
const corrected = {
x: roundTo3(base.x + residual.x),
y: roundTo3(base.y + residual.y),
};
if (corrected.x === roundTo3(base.x) && corrected.y === roundTo3(base.y)) {
logResize("scale-finalize", { skipped: "already-on-drop-point", residual, base });
// Settled, with nothing to write. Still ours: forwarding the drag offset
// on top would move the box off the point it is already sitting on.
return "settled" as const;
}
logResize("scale-finalize", {
dropPoint,
post,
residual,
gsapPos,
base,
corrected,
});
// Correct the live box in the same task as the measurement, so no frame shows it off the drop
// point while the position write is in flight.
setElementGsapPosition(draftEl, corrected.x, corrected.y);
return { base, corrected, residual };
});
return { base: { x: baseGsapX, y: baseGsapY }, gsapPos };
};
const measured = draftEl
? draw(() => correctOnElement(draftEl, committedScale, dropPoint, preGesture()))
: await correctOnFrame(frame!, committedScale ?? { x: 1, y: 1 }, dropPoint, preGesture());
if (measured === null) return false;
// Already on the drop point, and still ours: forwarding the drag offset would move it off.
if (measured === "settled") return true;
const { base, corrected, residual } = measured;
// Re-fetch: the scale commit above just rewrote the script, so the caller's
@@ -499,7 +460,8 @@ export async function tryGsapResizeIntercept(
if (positionTween) {
// A sub-pixel correction is not worth a keyframe in an authored tween.
if (Math.abs(residual.x) < 0.5 && Math.abs(residual.y) < 0.5) {
draw(() => setElementGsapPosition(draftEl, base.x, base.y));
if (draftEl) draw(() => setElementGsapPosition(draftEl, base.x, base.y));
else await drawFramePosition(frame!, base);
return true;
}
logResize("scale-finalize", { route: "position-keyframe", tweenId: positionTween.id });
@@ -0,0 +1,41 @@
/** The scale route's drop correction on a sealed frame: the frame draws and measures, over its port. */
import {
drawPreviewDraft,
previewDraftsSent,
previewStandIn,
} from "../components/editor/previewDrafts";
import { previewRequest } from "../player/lib/previewChannel";
import { previewGeometry } from "../player/lib/previewElements";
type Point = { x: number; y: number };
export type SealedScaleFrame = { standIn: Element; iframe: HTMLIFrameElement; handle: string };
export function sealedScaleFrame(standIn: Element): SealedScaleFrame | null {
const target = previewStandIn(standIn);
return target ? { standIn, ...target } : null;
}
/** The centre of the frame element's box, as the frame shows it once every drawn draft has landed. */
export async function frameBoxCentre(frame: SealedScaleFrame): Promise<Point | null> {
await previewDraftsSent(frame.iframe);
const rect = (await previewGeometry(frame.iframe, [frame.handle]))?.elements[0]?.rect;
return rect ? { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 } : null;
}
const gsapSet = (frame: SealedScaleFrame, props: Record<string, number>) =>
previewRequest(frame.iframe, "gsap-set", { handle: frame.handle, props });
/** The box with the committed scale at `at` and no draft, as the save will render it; its centre. */
export async function frameCentreScaledAt(
frame: SealedScaleFrame,
scale: Point,
at: Point,
): Promise<Point | null> {
drawPreviewDraft(frame.standIn, { size: null, translate: null });
await previewDraftsSent(frame.iframe);
await gsapSet(frame, { scaleX: scale.x, scaleY: scale.y, x: at.x, y: at.y });
return frameBoxCentre(frame);
}
export const drawFramePosition = (frame: SealedScaleFrame, at: Point) =>
gsapSet(frame, { x: at.x, y: at.y });
@@ -0,0 +1,85 @@
import { clearStudioBoxSize } from "../components/editor/manualEdits";
import { setElementGsapPosition, setElementGsapScale } from "../utils/elementGsap";
import { roundTo3 } from "../utils/rounding";
import { logResize } from "../utils/resizeDebug";
import {
drawFramePosition,
frameBoxCentre,
frameCentreScaledAt,
sealedScaleFrame,
type SealedScaleFrame,
} from "./scaleDropOnFrame";
function rectCentre(rect: DOMRect): { x: number; y: number } {
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
}
type ScaleDrop = { base: Point; corrected: Point; residual: Point };
type Point = { x: number; y: number };
/** Where the scale route's committed box lands against the drop point; "settled" when already on it. */
function scaleDropCorrection(
dropPoint: Point,
post: Point,
base: Point,
gsapPos: Point,
): ScaleDrop | "settled" | null {
const residual = { x: dropPoint.x - post.x, y: dropPoint.y - post.y };
if (!Number.isFinite(residual.x) || !Number.isFinite(residual.y)) return null;
// The ONE corrected position — rounded once so the live runtime and the
// persisted file agree exactly (commitStaticGsapPosition composes the same
// rounded value from this delta).
const corrected = { x: roundTo3(base.x + residual.x), y: roundTo3(base.y + residual.y) };
if (corrected.x === roundTo3(base.x) && corrected.y === roundTo3(base.y)) {
logResize("scale-finalize", { skipped: "already-on-drop-point", residual, base });
return "settled";
}
logResize("scale-finalize", { dropPoint, post, residual, gsapPos, base, corrected });
return { base, corrected, residual };
}
export async function dropPointOf(
el: HTMLElement | null,
standIn: Element,
draw: <T>(run: () => T) => T,
): Promise<Point | null> {
if (el) return draw(() => rectCentre(el.getBoundingClientRect()));
const frame = sealedScaleFrame(standIn);
return frame ? frameBoxCentre(frame) : null;
}
export function correctOnElement(
draftEl: HTMLElement,
committedScale: Point | null,
dropPoint: Point,
{ base, gsapPos }: { base: Point; gsapPos: Point },
): ScaleDrop | "settled" | null {
clearStudioBoxSize(draftEl);
// Draw the committed scale before measuring: on a first resize the timeline has not re-seeked yet,
// so the box would read at its natural size and the correction would be skipped.
if (committedScale) setElementGsapScale(draftEl, committedScale.x, committedScale.y);
setElementGsapPosition(draftEl, base.x, base.y);
const found = scaleDropCorrection(
dropPoint,
rectCentre(draftEl.getBoundingClientRect()),
base,
gsapPos,
);
// Correct the live box in the same task as the measurement, so no frame shows it off the drop
// point while the position write is in flight.
if (found && found !== "settled")
setElementGsapPosition(draftEl, found.corrected.x, found.corrected.y);
return found;
}
export async function correctOnFrame(
frame: SealedScaleFrame,
scale: Point,
dropPoint: Point,
{ base, gsapPos }: { base: Point; gsapPos: Point },
): Promise<ScaleDrop | "settled" | null> {
const post = await frameCentreScaledAt(frame, scale, base);
const found = post && scaleDropCorrection(dropPoint, post, base, gsapPos);
if (found && found !== "settled") await drawFramePosition(frame, found.corrected);
return found;
}