diff --git a/packages/studio/src/components/editor/previewDrafts.ts b/packages/studio/src/components/editor/previewDrafts.ts index d9b270be63..cbee034e88 100644 --- a/packages/studio/src/components/editor/previewDrafts.ts +++ b/packages/studio/src/components/editor/previewDrafts.ts @@ -24,6 +24,7 @@ interface Queue { ops: EditingDraft[]; drawn: Map; 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(); 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 { + const queue = queueFor(iframe); + if (!queue.sending && !queue.ops.length) return Promise.resolve(); + return new Promise((done) => queue.sent.push(done)); +} diff --git a/packages/studio/src/hooks/gsapResizeDropPoint.test.ts b/packages/studio/src/hooks/gsapResizeDropPoint.test.ts index 139b83c83b..3c15db927f 100644 --- a/packages/studio/src/hooks/gsapResizeDropPoint.test.ts +++ b/packages/studio/src/hooks/gsapResizeDropPoint.test.ts @@ -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 = `
`; + 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) => { + 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); + } +}); diff --git a/packages/studio/src/hooks/gsapResizeIntercept.ts b/packages/studio/src/hooks/gsapResizeIntercept.ts index bfdce8302d..1ab2e634d1 100644 --- a/packages/studio/src/hooks/gsapResizeIntercept.ts +++ b/packages/studio/src/hooks/gsapResizeIntercept.ts @@ -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 => { - // 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 }); diff --git a/packages/studio/src/hooks/scaleDropOnFrame.ts b/packages/studio/src/hooks/scaleDropOnFrame.ts new file mode 100644 index 0000000000..0da6860ccb --- /dev/null +++ b/packages/studio/src/hooks/scaleDropOnFrame.ts @@ -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 { + 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) => + 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 { + 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 }); diff --git a/packages/studio/src/hooks/scaleDropPoint.ts b/packages/studio/src/hooks/scaleDropPoint.ts new file mode 100644 index 0000000000..c4819f2292 --- /dev/null +++ b/packages/studio/src/hooks/scaleDropPoint.ts @@ -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: (run: () => T) => T, +): Promise { + 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 { + 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; +}