diff --git a/packages/studio/src/components/editor/previewGestureStartRead.ts b/packages/studio/src/components/editor/previewGestureStartRead.ts index 844903f505..c451a32091 100644 --- a/packages/studio/src/components/editor/previewGestureStartRead.ts +++ b/packages/studio/src/components/editor/previewGestureStartRead.ts @@ -7,7 +7,7 @@ import type { CropFrameStart } from "./domEditOverlayCrop"; import type { OverlayRect } from "./domEditOverlayGeometry"; import { invertManualOffsetDragMatrix, type ManualOffsetDragMatrix } from "./manualOffsetDrag"; import { flatVisibleRect, groupAwareRect } from "./previewOverlayRects"; -import { findPreviewElementForSelection } from "./previewSelection"; +import { findPreviewElementForSelection, standInFor } from "./previewSelection"; import { snapContextFromRects, type SnapContext } from "./snapTargetCollection"; export interface PreviewGestureStart { @@ -93,7 +93,7 @@ export async function measurePreviewGestureStart( } export type Shown = { selection: DomEditSelection; rect: OverlayRect; start?: PreviewGestureStart }; -export type OverChannel = { shown: Shown[]; snap: SnapContext }; +export type OverChannel = { shown: Shown[]; snap?: SnapContext }; /** An opaque frame's `selections` on the page it shows now and what a gesture on them starts from. */ export async function readShownGestureStarts( @@ -102,17 +102,34 @@ export async function readShownGestureStarts( path: string | null, selections: DomEditSelection[], ): Promise { + const answer = await askShownGestureStarts(iframe, overlay, path, selections); + return answer === UNANSWERED ? null : answer; +} + +export const UNANSWERED = "unanswered"; + +export async function askShownGestureStarts( + iframe: HTMLIFrameElement, + overlay: HTMLDivElement | null, + path: string | null, + selections: DomEditSelection[], +): Promise { const found = await Promise.all( selections.map((selection) => findPreviewElementForSelection(iframe, selection, path)), ); + if (found.includes(undefined)) return UNANSWERED; const handles = found.map((element) => element?.handle); if (!overlay || !handles.length || !handles.every(Boolean)) return null; const read = await measurePreviewGestureStart(iframe, overlay, handles as string[]); + if (!read) return UNANSWERED; const shown = selections.flatMap((selection, i) => { - const element = read?.elements[i]; - return element ? [{ selection: { ...selection, handle: handles[i] }, ...element }] : []; + const start = read.elements[i]; + const onFrame = found[i]; + if (!start || !onFrame) return []; + const element = standInFor(iframe, onFrame); + return [{ selection: { ...selection, handle: onFrame.handle, element }, ...start }]; }); - return read && shown.length === selections.length ? { shown, snap: read.snap } : null; + return shown.length === selections.length ? { shown, snap: read.snap } : null; } export async function readCropFrameStart( diff --git a/packages/studio/src/components/editor/previewGestureStarts.ts b/packages/studio/src/components/editor/previewGestureStarts.ts index 59d8c64719..fa96b3bf0c 100644 --- a/packages/studio/src/components/editor/previewGestureStarts.ts +++ b/packages/studio/src/components/editor/previewGestureStarts.ts @@ -22,7 +22,12 @@ import { setStudioWaitingPressCancel } from "../../utils/studioPendingEdits"; import { playheadMoment } from "../../hooks/editMoment"; import type { EditMoment } from "./manualEditsTypes"; import { previewFrameOpaque } from "../../player/lib/previewChannel"; -import { readShownGestureStarts, type OverChannel, type Shown } from "./previewGestureStartRead"; +import { + askShownGestureStarts, + UNANSWERED, + type OverChannel, + type Shown, +} from "./previewGestureStartRead"; type ShownStart = ( e: React.PointerEvent, @@ -144,6 +149,7 @@ export function createPreviewGestureStarts( start: ShownStart, draw: WaitingPressState["draw"] = null, targets: () => DomEditSelection[] = () => [], + drawn: () => OverChannel | null = () => null, ): boolean => { const at = playheadMoment(); const iframe = opts.iframeRef.current; @@ -183,28 +189,33 @@ export function createPreviewGestureStarts( settledFrames = settled ? settledFrames + 1 : 0; return elements.length; }; - // An opaque frame's pressed elements are found over its channel, once the preview settles. - let overChannel: OverChannel | null | undefined; - let asked = false; - const channelStep = (frame: HTMLIFrameElement): "wait" | "lost" | "run" => { + // An opaque frame's pressed elements are found over the channel of the frame shown once the preview settles. + let overChannel: OverChannel | null | typeof UNANSWERED | undefined; + let askedOf: HTMLIFrameElement | null = null; + let asks = 0; + const askShownFrame = () => { + const frame = opts.iframeRef.current ?? channel!; + if (askedOf === frame || asks >= 2) return; + [askedOf, asks, overChannel] = [frame, asks + 1, undefined]; + void askShownGestureStarts( + frame, + opts.overlayRef.current, + opts.activeCompositionPathRef.current, + targets(), + ).then((answer) => askedOf === frame && (overChannel = answer)); + }; + const channelStep = (): "wait" | "lost" | "run" | "drawn" => { const overdue = performance.now() - since > PRESS_WAIT_MAX_MS; if (overdue) giveUpOnPreviewChange(); if (isPreviewChanging() && !overdue) return "wait"; - if (!asked) { - asked = true; - void readShownGestureStarts( - frame, - opts.overlayRef.current, - opts.activeCompositionPathRef.current, - targets(), - ).then((shown) => (overChannel = shown)); - } + askShownFrame(); if (overChannel === undefined) return "wait"; + if (overChannel === UNANSWERED) return "drawn"; return overChannel ? "run" : "lost"; }; - const waitStep = (): "wait" | "lost" | "run" => { + const waitStep = (): "wait" | "lost" | "run" | "drawn" => { if (press.after && !press.after.ended) return "wait"; - if (channel) return channelStep(channel); + if (channel) return channelStep(); const found = countFrame(); // A change that never ends (a save with no reply) would hold every press: run on the page shown. const overdue = performance.now() - since > PRESS_WAIT_MAX_MS; @@ -213,6 +224,11 @@ export function createPreviewGestureStarts( if (found === 0 || settledFrames > MAX_SETTLED_WAIT_FRAMES) return "lost"; return overdue || shownFrames >= 2 ? "run" : "wait"; }; + const startsFrom = (step: "lost" | "run" | "drawn"): OverChannel | undefined | false => { + if (step === "lost") return false; + if (step === "drawn") return drawn() ?? false; + return typeof overChannel === "object" && overChannel ? overChannel : undefined; + }; const poll = () => { if (press.ended) return; const step = waitStep(); @@ -222,7 +238,8 @@ export function createPreviewGestureStarts( } endWaitingPress(press); const pointerDown = down as unknown as React.PointerEvent; - if (step === "lost" || !start(pointerDown, at, true, overChannel ?? undefined)) return; + const read = startsFrom(step); + if (read === false || !start(pointerDown, at, true, read)) return; if (press.moved) moveActiveGesture(press.moved); if (press.released) releaseActiveGesture(press.released); }; @@ -291,6 +308,7 @@ export function createPreviewGestureStarts( items.map((item) => ({ ...item, rect: shiftedOverlayRect(item.rect, dx, dy) })), ), () => items.map((item) => item.selection), + () => ({ shown: items.map(({ selection, rect }) => ({ selection, rect })) }), ); }; const startGesture = ( @@ -305,13 +323,11 @@ export function createPreviewGestureStarts( ) => { // A replay edits what was pressed, though another element may be selected by then. const target = options?.selection ?? opts.selectionRef.current; + const pressedRect = opts.overlayRectRef.current; let draw: WaitingPressState["draw"] = null; - if (kind === "drag") draw = drawPressedBox(opts.overlayRectRef.current); + if (kind === "drag") draw = drawPressedBox(pressedRect); if (kind === "resize") - draw = drawResizedBox( - opts.overlayRectRef.current, - options?.resizeCorner ?? { x: e.clientX, y: e.clientY }, - ); + draw = drawResizedBox(pressedRect, options?.resizeCorner ?? { x: e.clientX, y: e.clientY }); return startOnShownPreview( e, () => { @@ -336,6 +352,7 @@ export function createPreviewGestureStarts( }, draw, () => (target ? [target] : []), + () => (target && pressedRect ? { shown: [{ selection: target, rect: pressedRect }] } : null), ); }; diff --git a/packages/studio/src/components/editor/previewOverlayRects.test.ts b/packages/studio/src/components/editor/previewOverlayRects.test.ts index 9407b77b4a..0be5ac8022 100644 --- a/packages/studio/src/components/editor/previewOverlayRects.test.ts +++ b/packages/studio/src/components/editor/previewOverlayRects.test.ts @@ -11,6 +11,7 @@ import type { DomEditSelection } from "./domEditing"; import { orientedGroupAwareOverlayRect, type OverlayRect } from "./domEditOverlayGeometry"; import type { UseDomEditOverlayGesturesOptions } from "./domEditOverlayGestures"; import { createPreviewGestureStarts } from "./previewGestureStarts"; +import { standInHandle } from "./previewSelection"; import { useDomEditOverlayRects } from "./useDomEditOverlayRects"; import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; @@ -238,11 +239,34 @@ describe("overlay rects on an opaque frame match a scriptable one", () => { }); }); +/** A sealed frame whose runtime never answers, as a frame the page has dropped. */ +function silentFrame() { + const frameWindow = new Proxy({ postMessage() {} } as Record, { + get: (target, key) => { + if (key === "postMessage") return target.postMessage; + throw new DOMException("blocked", "SecurityError"); + }, + }); + const iframe = detachedFakeIframe(frameWindow); + Object.defineProperty(iframe, "contentDocument", { value: null }); + return sized(iframe, [100, 50, 960, 540]) as HTMLIFrameElement; +} + describe("a press held across a preview change on an opaque frame", () => { - async function pressDuringChange(selection: DomEditSelection) { + async function pressDuringChange( + selection: DomEditSelection, + { + iframe = opaqueFrame(), + overlayRect = null, + whileWaiting = () => {}, + }: { + iframe?: HTMLIFrameElement; + overlayRect?: OverlayRect | null; + whileWaiting?: (opts: UseDomEditOverlayGesturesOptions) => void; + } = {}, + ) { press.changing = true; press.start.mockClear(); - const iframe = opaqueFrame(); const overlay = sized(document.createElement("div"), [20, 10, 1200, 800]) as HTMLDivElement; const opts = { waitingPressRef: { current: null }, @@ -252,8 +276,8 @@ describe("a press held across a preview change on an opaque frame", () => { overlayRef: { current: overlay }, activeCompositionPathRef: { current: "index.html" }, selectionRef: { current: selection }, - overlayRectRef: { current: null }, - setOverlayRect: vi.fn(), + overlayRectRef: { current: overlayRect }, + setOverlayRect: vi.fn((rect: OverlayRect | null) => (opts.overlayRectRef.current = rect)), } as unknown as UseDomEditOverlayGesturesOptions; const { startGesture } = createPreviewGestureStarts(opts, vi.fn(), vi.fn()); const down = { @@ -267,6 +291,7 @@ describe("a press held across a preview change on an opaque frame", () => { startGesture("drag", down as unknown as React.PointerEvent); await new Promise((resolve) => setTimeout(resolve, 50)); expect(press.start).not.toHaveBeenCalled(); + whileWaiting(opts); press.changing = false; return { opts, overlay }; } @@ -289,6 +314,86 @@ describe("a press held across a preview change on an opaque frame", () => { expect(started.rect.angle).toBeCloseTo(36.87, 2); }); + // fails without the fix: the press read over the frame it was pressed on, which the change had removed, so no + // answer came and the drag was dropped. + it("reads over the frame shown once the change ends, when the change swapped frames", async () => { + const turned = document.getElementById("turned")!; + const pressedOn = opaqueFrame(); + await pressDuringChange(makeSelection("turned", turned), { + iframe: pressedOn, + whileWaiting: (opts) => { + opts.iframeRef.current = opaqueFrame(); + Object.defineProperty(pressedOn, "contentWindow", { value: null }); + }, + }); + await vi.waitFor(() => expect(press.start).toHaveBeenCalledOnce(), { timeout: 3000 }); + const [, , , started] = press.start.mock.calls[0] as [ + unknown, + unknown, + unknown, + { selection: DomEditSelection }, + ]; + expect(started.selection.id).toBe("turned"); + // fails without the fix: the gesture drew through the stand-in of the frame it was pressed on, now removed. + expect(started.selection.element).not.toBe(turned); + expect(standInHandle(started.selection.element)).toBe(started.selection.handle); + }); + + it("starts from the box Studio drew when the frame shown never answers", async () => { + const turned = makeSelection("turned", document.getElementById("turned")!); + const drawn = { left: 1, top: 2, width: 3, height: 4 } as OverlayRect; + await pressDuringChange(turned, { iframe: silentFrame(), overlayRect: drawn }); + await vi.waitFor(() => expect(press.start).toHaveBeenCalledOnce(), { timeout: 3000 }); + const [, , , started] = press.start.mock.calls[0] as [ + unknown, + unknown, + unknown, + { selection: DomEditSelection; rect: OverlayRect }, + ]; + expect(started).toMatchObject({ selection: turned, rect: drawn }); + expect(started.selection.element).toBe(turned.element); + }); + + // fails without the fix: the waiting box's redraws had already moved the box the drag started from. + it("starts from the box as it was at the press, though the pointer moved while it waited", async () => { + const turned = makeSelection("turned", document.getElementById("turned")!); + const drawn = { left: 1, top: 2, width: 3, height: 4 } as OverlayRect; + await pressDuringChange(turned, { + iframe: silentFrame(), + overlayRect: drawn, + whileWaiting: (opts) => opts.waitingPressRef.current!.draw!(30, 0), + }); + await vi.waitFor(() => expect(press.start).toHaveBeenCalledOnce(), { timeout: 3000 }); + const [, , , started] = press.start.mock.calls[0] as [ + unknown, + unknown, + unknown, + { rect: OverlayRect }, + ]; + expect(started.rect).toEqual(drawn); + }); + + it("asks the frame shown again when a swap comes after its first ask", async () => { + const turned = document.getElementById("turned")!; + const drawn = { left: 1, top: 2, width: 3, height: 4 } as OverlayRect; + const { opts, overlay } = await pressDuringChange(makeSelection("turned", turned), { + iframe: silentFrame(), + overlayRect: drawn, + }); + await new Promise((resolve) => setTimeout(resolve, 50)); + opts.iframeRef.current = opaqueFrame(); + await vi.waitFor(() => expect(press.start).toHaveBeenCalledOnce(), { timeout: 3000 }); + const [, , , started] = press.start.mock.calls[0] as [ + unknown, + unknown, + unknown, + { rect: OverlayRect }, + ]; + expect(close(started.rect)).toEqual( + close(orientedGroupAwareOverlayRect(overlay, liveFrame(), turned)), + ); + }); + it("drops the press when the page shown no longer has the element", async () => { const turned = document.getElementById("turned")!; const { opts } = await pressDuringChange(makeSelection("turned", turned));