Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import { act, createElement, Fragment, useRef } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, expect, it, vi } from "vitest";
import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers";
import {
answerTap,
sealedPreviewFrame,
type PortRequest,
} from "../../player/lib/sealedPreviewFrame.test-helpers";
import { previewRequest } from "../../player/lib/previewChannel";
import { usePreviewIframeStore } from "../../player/store/previewIframeStore";
import { useCaptionDetection } from "../../hooks/useCaptionDetection";
Expand Down Expand Up @@ -33,42 +37,12 @@ afterEach(() => {
vi.unstubAllGlobals();
});

type PortRequest = { id?: unknown; kind?: unknown; params?: unknown };

/** A frame Studio cannot read, whose runtime is the real editing agent over this document. */
function opaqueFrame() {
let pick: ((request: PortRequest) => boolean) | null = null;
const heldIds = new Set<unknown>();
const held: Array<() => void> = [];
// Studio's end of the port, so a test can keep the frame's answer to a request until it releases it.
const tap = (port: MessagePort) => {
const end = {
onmessage: null as ((event: MessageEvent) => void) | null,
postMessage(request: PortRequest) {
if (pick?.(request)) heldIds.add(request.id);
port.postMessage(request);
},
close: () => port.close(),
};
port.onmessage = (event) => {
const deliver = () => end.onmessage?.(event);
if (heldIds.has(event.data?.id)) held.push(deliver);
else deliver();
};
return end as unknown as MessagePort;
};
const { iframe } = sealedPreviewFrame({ wrapHandedOverPort: tap });
const { wrapHandedOverPort, hold, held } = answerTap();
const { iframe } = sealedPreviewFrame({ wrapHandedOverPort });
iframe.style.width = "1920px";
iframe.getBoundingClientRect = () => new DOMRect(0, 0, 1920, 1080);
/** Keeps the answers to the requests `match` picks; the returned call hands them to Studio. */
const hold = (match: (request: PortRequest) => boolean) => {
pick = match;
return () => {
pick = null;
heldIds.clear();
held.splice(0).forEach((deliver) => deliver());
};
};
return { iframe, hold, held };
}

Expand Down
171 changes: 144 additions & 27 deletions packages/studio/src/components/editor/DomEditCropHandles.sealed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,23 @@ import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, expect, it, vi } from "vitest";
import { watchPreviewFrame } from "../../player/lib/bridgePlayback";
import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements";
import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers";
import { usePlayerStore } from "../../player/store/playerStore";
import {
describePreviewElements,
previewGeometry,
queryPreviewElements,
} from "../../player/lib/previewElements";
import { answerTap, sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers";
import type { DomEditSelection } from "./domEditing";
import { DomEditCropHandles } from "./DomEditCropHandles";
import { rememberFrameClipPath } from "./domEditOverlayCrop";
import { previewStandIn } from "./previewDrafts";
import { standInFor } from "./previewSelection";

(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

afterEach(() => {
usePlayerStore.getState().setCurrentTime(0);
document.body.innerHTML = "";
});

Expand All @@ -23,24 +31,25 @@ function sized(element: Element, [x, y, width, height]: number[]) {
return element;
}

/** A 200 x 100 card painted under `transform` on a frame Studio cannot script, and its stand-in. */
async function sealedCard(transform: string, painted: number[]) {
document.body.innerHTML = `<div data-composition-id="main"><div id="card" style="transform: ${transform}"></div></div>`;
const card = sized(document.getElementById("card")!, [0, 0, 200, 100]);
card.getBoundingClientRect = () => {
const [x, y, width, height] = painted;
return {
x,
y,
width,
height,
left: x,
top: y,
right: x + width,
bottom: y + height,
} as DOMRect;
};
const { iframe: sealed, frame } = sealedPreviewFrame();
/** `element` laid out at `width` x `height` and painted on screen at `painted`. */
function paint(element: Element, [width, height]: number[], painted: number[]) {
sized(element, [0, 0, width, height]);
const [x, y, w, h] = painted;
element.getBoundingClientRect = () =>
({ x, y, width: w, height: h, left: x, top: y, right: x + w, bottom: y + h }) as DOMRect;
}

type Card = { id: string; transform: string; painted: number[]; clip?: string };

/** 200 x 100 cards painted under their `transform` on a frame Studio cannot script, and their stand-ins. */
async function sealedCards(cards: Card[], options?: Parameters<typeof sealedPreviewFrame>[0]) {
const markup = cards.map(
({ id, transform, clip }) =>
`<div id="${id}" style="transform: ${transform};${clip ? ` clip-path: ${clip}` : ""}"></div>`,
);
document.body.innerHTML = `<div data-composition-id="main">${markup.join("")}</div>`;
for (const { id, painted } of cards) paint(document.getElementById(id)!, [200, 100], painted);
const { iframe: sealed, frame } = sealedPreviewFrame(options);
const iframe = sized(sealed, [0, 0, 1920, 1080]) as HTMLIFrameElement;
watchPreviewFrame(iframe);
window.dispatchEvent(
Expand All @@ -50,8 +59,21 @@ async function sealedCard(transform: string, painted: number[]) {
data: { source: "hf-preview", type: "stage-size", width: 1920, height: 1080 },
}),
);
const handle = (await queryPreviewElements(iframe, "#card"))!.matches[0]!.handle;
return standInFor(iframe, (await describePreviewElements(iframe, [handle]))![0]!);
const standIns: HTMLElement[] = [];
for (const { id } of cards) {
const handle = (await queryPreviewElements(iframe, `#${id}`))!.matches[0]!.handle;
const described = (await describePreviewElements(iframe, [handle]))![0]!;
const standIn = standInFor(iframe, described);
// As a selection takes it (previewSelection.ts): the stand-in's clip-path is the one the frame reports.
rememberFrameClipPath(standIn, described.inlineStyles["clip-path"] ?? "", "");
standIns.push(standIn);
}
return standIns;
}

/** A 200 x 100 card painted under `transform` on a frame Studio cannot script, and its stand-in. */
async function sealedCard(transform: string, painted: number[], clip?: string) {
return (await sealedCards([{ id: "card", transform, painted, clip }]))[0]!;
}

type Shown = { left: number; top: number; width: number; height: number; angle?: number };
Expand All @@ -61,14 +83,14 @@ function cropHandles(standIn: HTMLElement, onStyleCommit = vi.fn()) {
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
const show = (shown: Shown) =>
const show = (shown: Shown, element = standIn) =>
act(() =>
root.render(
createElement(DomEditCropHandles, {
selection: {
element: standIn,
id: "card",
selector: "#card",
element,
id: element.id || "card",
selector: `#${element.id || "card"}`,
} as unknown as DomEditSelection,
overlayRect: { ...shown, editScaleX: 1, editScaleY: 1 },
onStyleCommit,
Expand All @@ -77,7 +99,9 @@ function cropHandles(standIn: HTMLElement, onStyleCommit = vi.fn()) {
);
const turn = () =>
document.querySelector<HTMLElement>("[data-dom-edit-crop-frame]")!.style.transform;
return { root, show, turn };
const outline = () =>
document.querySelector<HTMLElement>("[data-dom-edit-crop-frame] .border-dashed")!.style.width;
return { root, show, turn, outline };
}

/** Drags the right crop edge by `dx, dy` screen px and lets go, all before the frame answers. */
Expand Down Expand Up @@ -132,6 +156,99 @@ it("draws a sealed turned card's crop frame turned before any press", async () =
act(() => root.unmount());
});

// fails without the fix: before a press, a sealed crop drew its insets at the overlay's zoom alone, as if the card
// had no scale of its own, until a press measured its size.
it("draws a sealed scaled card's crop insets at the card's own scale before any press", async () => {
const standIn = await sealedCard(
"matrix(2, 0, 0, 2, 0, 0)",
[0, 0, 400, 200],
"inset(0px 20px 0px 0px)",
);
const { root, show, outline } = cropHandles(standIn);

show({ left: 0, top: 0, width: 400, height: 200 });

await vi.waitFor(() => expect(outline()).toBe("360px"));
act(() => root.unmount());
});

// fails without the fix: the size read at selection was kept while the card's size changed under it.
it("re-reads a sealed card's size when it changes while selected, before any press", async () => {
const standIn = await sealedCard(
"matrix(2, 0, 0, 2, 0, 0)",
[0, 0, 400, 200],
"inset(0px 20px 0px 0px)",
);
const { root, show, outline } = cropHandles(standIn);
show({ left: 0, top: 0, width: 400, height: 200 });
await vi.waitFor(() => expect(outline()).toBe("360px"));

paint(document.getElementById("card")!, [300, 100], [0, 0, 600, 200]);
show({ left: 0, top: 0, width: 600, height: 200 });

await vi.waitFor(() => expect(outline()).toBe("560px"));
act(() => root.unmount());
});

// fails without the fix: the crop re-read when Studio's playhead moved, before the frame applied the seek, so a seek
// that changed the card's size and scale but kept its painted box drew the old scale (360 px where 380 px is right).
it("re-reads a sealed card's size once the frame shows the seek's time, not when Studio's playhead moves", async () => {
const standIn = await sealedCard(
"matrix(2, 0, 0, 2, 0, 0)",
[0, 0, 400, 200],
"inset(0px 20px 0px 0px)",
);
const { iframe, handle } = previewStandIn(standIn)!;
const { root, show, outline } = cropHandles(standIn);
show({ left: 0, top: 0, width: 400, height: 200 });
await vi.waitFor(() => expect(outline()).toBe("360px"));

act(() => usePlayerStore.getState().setCurrentTime(3.5));
// The frame answers in order: anything the playhead move asked is answered, at the old size, before this.
await previewGeometry(iframe, [handle]);
paint(document.getElementById("card")!, [400, 200], [0, 0, 400, 200]);
window.dispatchEvent(
new MessageEvent("message", {
source: iframe.contentWindow,
origin: "null",
data: { source: "hf-preview", type: "state", currentTime: 3.5, isPlaying: false },
}),
);

await vi.waitFor(() => expect(outline()).toBe("380px"));
act(() => root.unmount());
});

// fails without the fix: a read sent for a card's first selection, landing after it was selected again, was taken
// over the newer one.
it("draws a card selected again by its newest size, not by a read sent before it was left", async () => {
const tap = answerTap();
const [card, other] = await sealedCards(
[
{
id: "card",
transform: "matrix(2, 0, 0, 2, 0, 0)",
painted: [0, 0, 400, 200],
clip: "inset(0px 20px 0px 0px)",
},
{ id: "other", transform: "none", painted: [500, 0, 200, 100] },
],
{ wrapHandedOverPort: tap.wrapHandedOverPort },
);
const { root, show, outline } = cropHandles(card!);
const release = tap.hold(({ kind }) => kind === "gesture-start");
show({ left: 0, top: 0, width: 400, height: 200 });
await vi.waitFor(() => expect(tap.held).toHaveLength(1));

paint(document.getElementById("card")!, [300, 100], [0, 0, 600, 200]);
show({ left: 500, top: 0, width: 200, height: 100 }, other);
show({ left: 0, top: 0, width: 600, height: 200 }, card);
release();

await vi.waitFor(() => expect(outline()).toBe("560px"));
act(() => root.unmount());
});

// fails without the fix: the turn measured at a press was held until the selection changed.
it("redraws a sealed crop frame at the turn the card has after a scrub, once a press measured it", async () => {
const standIn = await sealedCard("rotate(30deg)", [0, 0, 223, 187]);
Expand Down
71 changes: 70 additions & 1 deletion packages/studio/src/components/editor/DomEditCropHandles.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { trackPreviewEditResult, type PreviewMethod } from "../../utils/previewFeatureUsage";
import { useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
import {
useEffect,
useRef,
useState,
type Dispatch,
type PointerEvent as ReactPointerEvent,
type SetStateAction,
} from "react";
import type { DomEditSelection } from "./domEditing";
import { type OverlayRect, RESIZE_HANDLE_HIT_PX } from "./domEditOverlayGeometry";
import {
Expand All @@ -22,6 +29,7 @@ import { isCropBarTarget, useCropPresetBarStore } from "./cropPresetStore";
import { CropPresetBar } from "./CropPresetBar";
import { movesGesture } from "./domEditOverlayGestures";
import { previewStandIn } from "./previewDrafts";
import { onFrameShowsTime } from "../../player/lib/bridgePlayback";
import { gestureStartLayout, readCropFrameStart } from "./previewGestureStartRead";

interface CropGestureState {
Expand Down Expand Up @@ -151,6 +159,64 @@ function insetsAfterDrag(gesture: CropGestureState, x: number, y: number): ClipP
return resolveCropInsetFromEdgeDrag({ ...drag, edge, width, height });
}

type StartReads = { token: number; busy: boolean; again: boolean; element: HTMLElement };

/** A stand-in has no size of its own: the frame measures it while selected and when its overlay size changes, so its
* insets draw at the element's own scale before any press, as an unsealed crop reads it live. One read at a time, one
* more when it lands if anything changed meanwhile; a new selection or a press (a new `token`) drops one still out. */
function readStandInStart(
r: StartReads,
take: (element: HTMLElement, start: CropFrameStart) => void,
): void {
const el = r.element;
const standIn = previewStandIn(el);
if (!standIn) return;
if (r.busy) return void (r.again = true);
r.busy = true;
const token = r.token;
void readCropFrameStart(standIn.iframe, standIn.handle).then((start) => {
r.busy = false;
if (start && token === r.token) take(el, start);
if (r.again) {
r.again = false;
readStandInStart(r, take);
}
});
}

/** `readStandInStart` while `element` is selected and not dragged: again when its box moves or a seek lands. */
/** Counts the seeks `element`'s sealed frame has applied, as its runtime reports them. */
function useFrameSeeks(element: HTMLElement): number {
const [seeks, setSeeks] = useState(0);
useEffect(() => {
const frame = previewStandIn(element)?.iframe;
if (!frame) return;
return onFrameShowsTime((iframe) => iframe === frame && setSeeks((n) => n + 1));
}, [element]);
return seeks;
}

function useStandInStart<S extends { element: HTMLElement; start?: CropFrameStart }>(
element: HTMLElement,
overlayRect: { width: number; height: number },
dragging: boolean,
setState: Dispatch<SetStateAction<S>>,
) {
const reads = useRef<StartReads>({ token: 0, busy: false, again: false, element });
const shownSize = `${Math.round(overlayRect.width)}x${Math.round(overlayRect.height)}`;
const seeks = useFrameSeeks(element);
useEffect(() => {
const r = reads.current;
if (r.element !== element) r.token++;
r.element = element;
if (!dragging)
readStandInStart(r, (el, start) =>
setState((prev) => (prev.element === el ? { ...prev, start } : prev)),
);
}, [element, shownSize, seeks, dragging, setState]);
return reads;
}

function letGoOf(ref: { current: CropGestureState | null }, gesture: CropGestureState): void {
if (ref.current === gesture) ref.current = null;
}
Expand Down Expand Up @@ -252,6 +318,8 @@ export function DomEditCropHandles({
return () => dropElementCropLift(el);
}, [selection.element]);

const reads = useStandInStart(selection.element, overlayRect, dragging, setState);

// The crop applies in the element's LOCAL frame (clip-path precedes the
// transform), so all crop UI is drawn inside a container rotated with the
// element — on a rotated element an axis-aligned dim visually "straightens"
Expand Down Expand Up @@ -296,6 +364,7 @@ export function DomEditCropHandles({
setState((prev) => ({ ...prev, insets: pressed }));
setDragging(true);
const { element } = selection;
reads.current.token++;
void measurePressOnFrame(element, overlayRect, gesture).then((start) =>
settleMeasuredPress(start, gesture, gestureRef.current, {
refuse: refuseCropPress,
Expand Down
Loading
Loading