Skip to content

Commit a3b5fe0

Browse files
fix(studio): a press on a sealed preview starts at once, as it does on an open one (#8904)
* fix(studio): a press on a sealed preview starts at once, as it does on an open one A sealed press waited on three frame requests (find, describe, gesture-start) before its gesture could start, so at 4x CPU it began 34-97 ms late behind a waiting outline. Studio now reads what the next press starts from ahead of it, while the frame is at rest, and drops that read on any frame fact change, raised through one signal in player/lib/frameFacts.ts: a draft or other write to the frame, a save, the playhead or playback, undo/redo, a load, the selection, the frame's size. Zoom only scales the shown frame, so the read keeps the frame's own px and is placed on the overlay at the press. * fix(studio): a sealed press made after the frame moved the layer itself starts from where it moved The frame can move a selected layer with nothing sent from Studio: a timer in the composition, a CSS animation, a late font or image load. A read made before that would start the press from the old box. The overlay already re-reads a sealed selection's box over the port; when the box it reports changes, that now counts as a frame fact change, so the read ahead is made again. One read ahead is in flight at a time, so a selection the frame keeps moving costs one read at a time. * refactor(studio): sealed press read-ahead keeps its reasons in names, not comments The comment ratchet holds a file's comment share at or below its base. The notes cut here restated their names; the reasoning is in the pull request.
1 parent 1cf8840 commit a3b5fe0

14 files changed

Lines changed: 619 additions & 12 deletions

‎packages/studio/src/components/editor/DomEditOverlay.tsx‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import { CanvasContextMenu } from "./CanvasContextMenu";
3535
import { useInlineTextEditing } from "./useInlineTextEditing";
3636
import { usePreviewReadOnly } from "./previewReadOnlyContext";
3737
import { useMountEffect } from "../../hooks/useMountEffect";
38+
import { useGestureStartReadAhead } from "./gestureStartReadAhead";
3839
import { countStudioManualEditSave as counted } from "./manualEditGesture";
3940
import type { ZOrderAction, ZOrderPatch } from "./canvasContextMenuZOrder";
4041
import { getPreviewTargetFromPointer } from "../../utils/studioPreviewHelpers";
@@ -279,7 +280,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
279280
activeCompositionPath,
280281
});
281282

282-
const gestures = createDomEditOverlayGestureHandlers({
283+
const gestureOptions = {
283284
activeCompositionPathRef,
284285
overlayRef,
285286
iframeRef,
@@ -305,7 +306,9 @@ export const DomEditOverlay = memo(function DomEditOverlay({
305306
onCanvasPointerMoveRef,
306307
onCanvasMouseDown,
307308
snapGuidesRef,
308-
});
309+
};
310+
const gestures = createDomEditOverlayGestureHandlers(gestureOptions);
311+
useGestureStartReadAhead(gestureOptions);
309312

310313
useEffect(() => {
311314
if (readOnly) gestures.clearPointerState(selectionRef, true);
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
// @vitest-environment happy-dom
2+
3+
import React, { act } from "react";
4+
import { createRoot } from "react-dom/client";
5+
import { afterEach, expect, it, onTestFinished, vi } from "vitest";
6+
import { installReactActEnvironment, makeSelection } from "../../hooks/domSelectionTestHarness";
7+
import { watchPreviewFrame } from "../../player/lib/bridgePlayback";
8+
import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements";
9+
import { previewRequest } from "../../player/lib/previewChannel";
10+
import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers";
11+
import { usePlayerStore } from "../../player/store/playerStore";
12+
import { isStudioEditSaving, trackStudioPendingEdit } from "../../utils/studioPendingEdits";
13+
import type { UseDomEditOverlayGesturesOptions } from "./domEditOverlayGestures";
14+
import { gestureStartReadAhead, keepGestureStartReadAhead } from "./gestureStartReadAhead";
15+
import { createPreviewGestureStarts } from "./previewGestureStarts";
16+
import { standInFor } from "./previewSelection";
17+
import { useDomEditOverlayRects } from "./useDomEditOverlayRects";
18+
19+
const frames = vi.hoisted(() => new Set<() => void>());
20+
vi.mock("./overlayFrameLoop", () => ({
21+
subscribeOverlayFrame: (update: () => void) => {
22+
frames.add(update);
23+
return () => frames.delete(update);
24+
},
25+
}));
26+
installReactActEnvironment();
27+
28+
vi.mock("../../player/lib/previewChannel", async (importOriginal) => {
29+
const actual = await importOriginal<typeof import("../../player/lib/previewChannel")>();
30+
return { ...actual, previewRequest: vi.fn(actual.previewRequest) };
31+
});
32+
33+
function sized<T extends Element>(element: T, [x, y, width, height]: number[]): T {
34+
element.getBoundingClientRect = () =>
35+
({ x, y, width, height, left: x, top: y, right: x + width, bottom: y + height }) as DOMRect;
36+
return element;
37+
}
38+
39+
/** The frame's document is this one: #box is drawn at 300 + its translate x, 200. */
40+
function mountBox() {
41+
document.body.innerHTML = `<div data-composition-id="main" data-width="1920" data-height="1080"><div id="box"></div></div>`;
42+
const box = document.getElementById("box")!;
43+
box.getBoundingClientRect = () => {
44+
const x = 300 + (Number.parseFloat(box.style.translate) || 0);
45+
return {
46+
x,
47+
y: 200,
48+
width: 100,
49+
height: 50,
50+
left: x,
51+
top: 200,
52+
right: x + 100,
53+
bottom: 250,
54+
} as DOMRect;
55+
};
56+
Object.defineProperty(box, "offsetWidth", { value: 100 });
57+
Object.defineProperty(box, "offsetHeight", { value: 50 });
58+
usePlayerStore.setState({ currentTime: 0.5, isPlaying: false });
59+
return box;
60+
}
61+
afterEach(() => {
62+
document.body.innerHTML = "";
63+
usePlayerStore.setState({ currentTime: 0, isPlaying: false });
64+
});
65+
66+
function opaqueFrame() {
67+
const { iframe: sealed, frame } = sealedPreviewFrame();
68+
const iframe = sized(sealed, [100, 50, 960, 540]) as HTMLIFrameElement;
69+
watchPreviewFrame(iframe);
70+
window.dispatchEvent(
71+
new MessageEvent("message", {
72+
source: frame as unknown as Window,
73+
origin: window.location.origin,
74+
data: { source: "hf-preview", type: "stage-size", width: 1920, height: 1080 },
75+
}),
76+
);
77+
return iframe;
78+
}
79+
80+
const ref = <T>(current: T) => ({ current });
81+
82+
/** The box selected on a sealed frame, with the refs an overlay mount holds. */
83+
async function selectBoxOnSealedFrame() {
84+
const box = mountBox();
85+
const iframe = opaqueFrame();
86+
const handle = (await queryPreviewElements(iframe, "#box"))!.matches[0]!.handle;
87+
const standIn = standInFor(iframe, (await describePreviewElements(iframe, [handle]))![0]!);
88+
const selection = { ...makeSelection("box", standIn), id: "box", handle };
89+
const opts = {
90+
selectionRef: ref(selection),
91+
overlayRectRef: ref({
92+
left: 100,
93+
top: 75,
94+
width: 50,
95+
height: 25,
96+
editScaleX: 0.5,
97+
editScaleY: 0.5,
98+
}),
99+
boxRef: ref(document.createElement("div")),
100+
overlayRef: ref(sized(document.createElement("div"), [20, 10, 1200, 800])),
101+
iframeRef: ref(iframe),
102+
activeCompositionPathRef: ref(null),
103+
gestureRef: ref(null),
104+
groupGestureRef: ref(null),
105+
groupOverlayItemsRef: ref([]),
106+
waitingPressRef: ref(null),
107+
rafPausedRef: ref(false),
108+
setOverlayRect: vi.fn(),
109+
setGroupOverlayItems: vi.fn(),
110+
onManualDragStartRef: ref(vi.fn()),
111+
onBlockedMoveRef: ref(vi.fn()),
112+
} as unknown as UseDomEditOverlayGesturesOptions;
113+
onTestFinished(keepGestureStartReadAhead(opts));
114+
await vi.waitFor(() =>
115+
expect(gestureStartReadAhead(opts, iframe, [selection], false)).not.toBeNull(),
116+
);
117+
return { box, iframe, selection, opts };
118+
}
119+
120+
const press = () =>
121+
({
122+
clientX: 400,
123+
clientY: 300,
124+
pointerId: 1,
125+
button: 0,
126+
preventDefault() {},
127+
stopPropagation() {},
128+
currentTarget: { setPointerCapture() {} },
129+
}) as unknown as React.PointerEvent<HTMLElement>;
130+
131+
const asked = (kind: string) =>
132+
vi.mocked(previewRequest).mock.calls.filter(([, k]) => k === kind).length;
133+
134+
// fails without the fix: the press waited on query, describe and gesture-start answers before its gesture started.
135+
it("starts a press on a sealed preview at once from the read made before it, asking the frame nothing", async () => {
136+
const { selection, opts } = await selectBoxOnSealedFrame();
137+
vi.mocked(previewRequest).mockClear();
138+
139+
const starts = createPreviewGestureStarts(opts, vi.fn(), vi.fn());
140+
expect(starts.startGesture("drag", press(), { selection })).toBe(true);
141+
142+
expect(opts.gestureRef.current?.selection.handle).toBe(selection.handle);
143+
expect(opts.waitingPressRef.current).toBeNull();
144+
expect(opts.boxRef.current!.hasAttribute("data-dom-edit-press-waiting")).toBe(false);
145+
expect(["query", "describe", "gesture-start"].map(asked)).toEqual([0, 0, 0]);
146+
});
147+
148+
it("starts a press made after an edit from where the edit left the layer, not from the read before it", async () => {
149+
const { box, selection, opts } = await selectBoxOnSealedFrame();
150+
let saved!: () => void;
151+
const save = trackStudioPendingEdit(new Promise<void>((resolve) => (saved = resolve)));
152+
// The edit moves the layer 40 frame px right, 20 page px at this preview's scale.
153+
box.style.translate = "40px 0px";
154+
saved();
155+
await save;
156+
// Pressed as soon as the edit is saved, before anything reads the frame again.
157+
expect(isStudioEditSaving()).toBe(false);
158+
159+
const starts = createPreviewGestureStarts(opts, vi.fn(), vi.fn());
160+
expect(starts.startGesture("drag", press(), { selection })).toBe(true);
161+
expect(opts.gestureRef.current).toBeNull();
162+
163+
await vi.waitFor(() => expect(opts.gestureRef.current).not.toBeNull());
164+
// Frame x 340 is page x 100 + 340 / 2 = 270, overlay x 250; the read before the edit had 230.
165+
expect(opts.gestureRef.current!.originLeft).toBe(250);
166+
});
167+
168+
/** The overlay's own rect loop over the sealed frame, as an overlay mount runs it; `frame` runs one of its frames. */
169+
function overlayLoopOn(opts: UseDomEditOverlayGesturesOptions) {
170+
let shown: ReturnType<typeof useDomEditOverlayRects> | null = null;
171+
function Harness() {
172+
shown = useDomEditOverlayRects({
173+
iframeRef: opts.iframeRef,
174+
overlayRef: opts.overlayRef,
175+
selectionRef: opts.selectionRef,
176+
activeCompositionPathRef: opts.activeCompositionPathRef,
177+
groupSelectionsRef: { current: [] },
178+
hoverSelectionRef: { current: null },
179+
rafPausedRef: opts.rafPausedRef,
180+
});
181+
return null;
182+
}
183+
const root = createRoot(document.createElement("div"));
184+
act(() => root.render(React.createElement(Harness)));
185+
onTestFinished(() => act(() => root.unmount()));
186+
return {
187+
shownLeft: () => shown!.overlayRectRef.current?.left,
188+
frame: () => act(() => frames.forEach((update) => update())),
189+
};
190+
}
191+
192+
// fails without the fix: the press started at once from the read made before the frame moved the layer, at 230.
193+
it("starts a press made after the frame moved the layer on its own from where it moved it", async () => {
194+
const { box, selection, opts } = await selectBoxOnSealedFrame();
195+
const overlay = overlayLoopOn(opts);
196+
await vi.waitFor(() => {
197+
overlay.frame();
198+
expect(overlay.shownLeft()).toBe(230);
199+
});
200+
// A timer in the composition moves the layer 40 frame px right; Studio sends the frame nothing.
201+
box.style.translate = "40px 0px";
202+
await vi.waitFor(() => {
203+
overlay.frame();
204+
expect(overlay.shownLeft()).toBe(250);
205+
});
206+
207+
const starts = createPreviewGestureStarts(opts, vi.fn(), vi.fn());
208+
expect(starts.startGesture("drag", press(), { selection })).toBe(true);
209+
210+
await vi.waitFor(() => expect(opts.gestureRef.current).not.toBeNull());
211+
expect(opts.gestureRef.current!.originLeft).toBe(250);
212+
});

0 commit comments

Comments
 (0)