fix(studio): a sealed crop draws a layer's insets at its own scale and follows a seek (#8451)

* test(studio): a sealed scaled card's crop insets draw at its own scale before any press

* test(studio): a sealed crop re-reads a resized card and drops a read from an earlier selection

* fix(studio): a sealed crop draws a scaled layer's insets at its own scale before any press

* style(studio): wrap the sealed crop read's comment under the line limit

* test(studio): a sealed scaled layer picked in the Layers panel crops at its own scale

* refactor(studio): read a sealed crop's start in its own hook

* test(studio): overlays wake on a sealed preview's posts and only on Studio's own preview frame

* fix(studio): a sealed preview's playhead posts wake the editor overlays after a seek

* test(studio): a seek that keeps a sealed card's painted box still re-reads its crop scale

* fix(studio): a sealed crop re-reads its layer's scale when the playhead moves

* test(studio): a sealed crop re-reads once the frame shows the seek, not on Studio's playhead

* fix(studio): a sealed crop re-reads its scale when the frame applies a seek
This commit is contained in:
Miguel Ángel
2026-11-22 08:40:03 +00:00
committed by GitHub
parent deb478a3f6
commit 05d1bc8b1c
8 changed files with 390 additions and 76 deletions
@@ -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";
@@ -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 };
}
@@ -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 = "";
});
@@ -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(
@@ -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 };
@@ -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,
@@ -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. */
@@ -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]);
@@ -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 {
@@ -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 {
@@ -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;
}
@@ -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"
@@ -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,
@@ -6,6 +6,7 @@ import { afterEach, expect, it, vi } from "vitest";
import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
import { usePreviewIframeStore } from "../../player/store/previewIframeStore";
import { LayersPanel } from "./LayersPanel";
import { DomEditCropHandles } from "./DomEditCropHandles";
import type { LayerReorderEvent } from "./useLayerDrag";
import type { DomEditLayerItem, DomEditSelection } from "./domEditing";
import { announcePreviewDocumentLoaded } from "../../player/sceneSwap";
@@ -242,3 +243,36 @@ it("lists the layers in their new order after an undo restacks them in place", a
expect(reload).not.toHaveBeenCalled();
await vi.waitFor(() => expect(rows()).toEqual(["Back", "Front"]));
});
// fails without the fix: a layer picked in the Layers panel was never pressed on the canvas, so its sealed crop drew
// the insets at the overlay's zoom alone, as if the layer had no scale of its own.
it("draws the crop of a sealed scaled layer picked in the Layers panel at the layer's own scale", async () => {
document.body.innerHTML = `<main data-composition-id="main"><div id="card" style="transform: matrix(2, 0, 0, 2, 0, 0); clip-path: inset(0px 20px 0px 0px)"></div></main>`;
const card = document.getElementById("card")!;
Object.defineProperty(card, "offsetWidth", { value: 200 });
Object.defineProperty(card, "offsetHeight", { value: 100 });
card.getBoundingClientRect = () =>
({ x: 0, y: 0, width: 400, height: 200, left: 0, top: 0, right: 400, bottom: 200 }) as DOMRect;
const rows = renderPanel(sealedPreviewFrame().iframe);
await vi.waitFor(() => expect(rows()).toHaveLength(1));
act(() => document.querySelector<HTMLElement>("[data-layer-index]")!.click());
await vi.waitFor(() => expect(mocks.applyDomSelection).toHaveBeenCalled());
const picked = mocks.applyDomSelection.mock.calls[0]![0] as DomEditSelection;
const host = document.body.appendChild(document.createElement("div"));
const root = createRoot(host);
act(() =>
root.render(
createElement(DomEditCropHandles, {
selection: picked,
overlayRect: { left: 0, top: 0, width: 400, height: 200, editScaleX: 1, editScaleY: 1 },
onStyleCommit: vi.fn(),
}),
),
);
closers.push(() => act(() => root.unmount()));
const outline = () =>
host.querySelector<HTMLElement>("[data-dom-edit-crop-frame] .border-dashed")?.style.width;
await vi.waitFor(() => expect(outline()).toBe("360px"));
});
@@ -10,6 +10,8 @@ import {
subscribeOverlayFrame,
} from "./overlayFrameLoop";
import { usePlayerStore } from "../../player/store/playerStore";
import { watchPreviewFrame } from "../../player/lib/bridgePlayback";
import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers";
/**
* The editor's overlay polls run on one shared, parkable frame loop. The two
@@ -20,6 +22,8 @@ describe("overlay frame loop", () => {
const originalRaf = window.requestAnimationFrame;
const originalCancelRaf = window.cancelAnimationFrame;
let queued: Array<() => void>;
/** The window of the preview frame Studio built, whose posts wake the loop. */
let preview: Window;
/** Run whatever frames are queued, once. */
const step = (): number => {
@@ -40,6 +44,9 @@ describe("overlay frame loop", () => {
};
beforeEach(() => {
const frame = document.body.appendChild(document.createElement("iframe"));
watchPreviewFrame(frame);
preview = frame.contentWindow!;
usePlayerStore.setState({ previewBooted: true });
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance", "Date"] });
queued = [];
@@ -54,6 +61,7 @@ describe("overlay frame loop", () => {
afterEach(() => {
resetOverlayFrameLoopForTests();
document.body.innerHTML = "";
vi.useRealTimers();
window.requestAnimationFrame = originalRaf;
window.cancelAnimationFrame = originalCancelRaf;
@@ -180,6 +188,7 @@ describe("overlay frame loop", () => {
new MessageEvent("message", {
data: { source: "hf-preview", type: "state", frame, isPlaying },
origin: window.location.origin,
source: preview,
}),
);
};
@@ -197,6 +206,67 @@ describe("overlay frame loop", () => {
expect(runs).toBeGreaterThan(5);
});
// fails without the fix: a sealed preview posts from an opaque origin, so after a seek the overlays waited for the
// idle poll (up to MAX_IDLE_POLL_MS) to redraw the selection at the layer's new size.
it("wakes to full rate when a sealed preview Studio built reports a new frame from its opaque origin", () => {
const { iframe, frame } = sealedPreviewFrame();
watchPreviewFrame(iframe);
let runs = 0;
subscribeOverlayFrame(() => {
runs += 1;
});
framesOver(1000);
runs = 0;
window.dispatchEvent(
new MessageEvent("message", {
data: { source: "hf-preview", type: "state", frame: 3, isPlaying: false },
origin: "null",
source: frame as unknown as Window,
}),
);
framesOver(200);
expect(runs).toBeGreaterThan(5);
});
it("ignores an opaque-origin preview post from a frame Studio did not build", () => {
const stranger = sealedPreviewFrame().frame;
let runs = 0;
subscribeOverlayFrame(() => {
runs += 1;
});
framesOver(1000);
runs = 0;
window.dispatchEvent(
new MessageEvent("message", {
data: { source: "hf-preview", type: "state", frame: 4, isPlaying: false },
origin: "null",
source: stranger as unknown as Window,
}),
);
framesOver(200);
expect(runs).toBeLessThanOrEqual(2);
});
// fails without the fix: any window on Studio's own origin could post the preview's payload and wake the loop.
it("ignores a same-origin preview post from a window that is not the preview frame Studio built", () => {
const stranger = document.body.appendChild(document.createElement("iframe")).contentWindow!;
let runs = 0;
subscribeOverlayFrame(() => {
runs += 1;
});
framesOver(1000);
runs = 0;
window.dispatchEvent(
new MessageEvent("message", {
data: { source: "hf-preview", type: "state", frame: 5, isPlaying: false },
origin: window.location.origin,
source: stranger,
}),
);
framesOver(200);
expect(runs).toBeLessThanOrEqual(2);
});
it("ignores the paused heartbeat, which repeats a frame the overlays already drew", () => {
let runs = 0;
subscribeOverlayFrame(() => {
@@ -309,6 +379,7 @@ describe("overlay frame loop", () => {
new MessageEvent("message", {
data: { source: "hf-preview", type: "timeline", clips: [] },
origin: window.location.origin,
source: preview,
}),
);
framesOver(200);
@@ -25,6 +25,7 @@
* the next couple of hundred milliseconds, and no further event is dispatched
* while it does.
*/
import { fromStudioPreview } from "../../player/lib/bridgePlayback";
import { usePlayerStore } from "../../player/store/playerStore";
const AWAKE_MS = 400;
@@ -64,17 +65,6 @@ const WINDOW_EVENTS = [
let lastPreviewFrame: number | null = null;
let lastPreviewPlaying: boolean | null = null;
/**
* The preview iframe is served by the editor's own origin (`useTimelinePlayer`
* builds its src against `window.location.origin`), so a message from anywhere
* else is not the preview whatever its payload claims. Answered before the
* payload is read, because a sender we do not trust controls every field in it.
*/
function isFromPreviewOrigin(event: MessageEvent): boolean {
if (typeof window === "undefined") return true;
return event.origin === window.location.origin;
}
/**
* `window` also receives postMessage traffic from extensions, devtools and any
* other embed on the page. Waking on those would hold the overlays awake for
@@ -98,7 +88,9 @@ function previewStateOf(data: {
}
function onPreviewMessage(event: MessageEvent): void {
if (!isFromPreviewOrigin(event)) return;
// Only a preview frame Studio built, from an origin it can have (a sealed one's is opaque): anything else on the page
// can post the same payload. Checked before the payload is read.
if (!fromStudioPreview(event)) return;
const data: unknown = event.data;
if (!isPreviewPayload(data)) return;
const state = previewStateOf(data);
@@ -15,6 +15,8 @@ interface PlaybackMirror {
seekUntil: number;
/** The composition's declared size from the runtime's `stage-size` post. */
stageSize: { width: number; height: number } | null;
/** The paused time the runtime last said it shows. */
shown: number | null;
}
const SEEK_CONFIRM_MS = 500;
@@ -37,6 +39,7 @@ function mirrorOf(iframe: HTMLIFrameElement): PlaybackMirror | null {
seekTo: null,
seekUntil: 0,
stageSize: null,
shown: null,
};
mirrors.set(frame, mirror);
}
@@ -112,6 +115,17 @@ function mirrorState(
mirror.seekTo = null;
mirror.time = currentTime;
mirror.playing = playing;
if (playing || mirror.shown === currentTime) return;
mirror.shown = currentTime;
for (const listener of shownListeners) listener(mirror.iframe);
}
const shownListeners = new Set<(iframe: HTMLIFrameElement) => void>();
/** Calls `listener` with a registered frame each time its runtime says it shows a new paused time: a seek applied. */
export function onFrameShowsTime(listener: (iframe: HTMLIFrameElement) => void): () => void {
shownListeners.add(listener);
return () => void shownListeners.delete(listener);
}
function mirrorPost(mirror: PlaybackMirror, message: Record<string, unknown>, fps: number | null) {
@@ -125,10 +139,18 @@ function mirrorPost(mirror: PlaybackMirror, message: Record<string, unknown>, fp
}
}
function mirrorRuntimePlayback(event: MessageEvent): void {
// Only a frame Studio built, posting from an origin that frame can have.
function studioPreviewMirror(event: MessageEvent): PlaybackMirror | undefined {
const mirror = event.source ? mirrors.get(event.source) : undefined;
if (!mirror || !frameOrigins(mirror.iframe).includes(event.origin)) return;
return mirror && frameOrigins(mirror.iframe).includes(event.origin) ? mirror : undefined;
}
/** Whether `event` came from a preview frame Studio built, a sealed one's opaque origin included. */
export const fromStudioPreview = (event: MessageEvent): boolean =>
studioPreviewMirror(event) !== undefined;
function mirrorRuntimePlayback(event: MessageEvent): void {
const mirror = studioPreviewMirror(event);
if (!mirror) return;
const post = runtimePost(event.data);
if (post) mirrorPost(mirror, post.message, post.fps);
}
@@ -42,3 +42,38 @@ export function sealedPreviewFrame(
onTestFinished(() => agent.dispose());
return { iframe, frame };
}
export type PortRequest = { id?: unknown; kind?: unknown; params?: unknown };
/** Studio's end of the frame's port, for `wrapHandedOverPort`: `hold` keeps the frame's answers to the requests it
* picks until the call it returns hands them to Studio, in order. */
export function answerTap() {
let pick: ((request: PortRequest) => boolean) | null = null;
const heldIds = new Set<unknown>();
const held: Array<() => void> = [];
const wrapHandedOverPort = (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 hold = (match: (request: PortRequest) => boolean) => {
pick = match;
return () => {
pick = null;
heldIds.clear();
held.splice(0).forEach((deliver) => deliver());
};
};
return { wrapHandedOverPort, hold, held };
}