diff --git a/packages/studio/src/captions/components/CaptionOverlay.sealed.test.ts b/packages/studio/src/captions/components/CaptionOverlay.sealed.test.ts index 16443a1cae..d2d44f298a 100644 --- a/packages/studio/src/captions/components/CaptionOverlay.sealed.test.ts +++ b/packages/studio/src/captions/components/CaptionOverlay.sealed.test.ts @@ -2,10 +2,8 @@ import { act, createElement, Fragment, useRef } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, expect, it, vi } from "vitest"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness"; -import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; import { previewRequest } from "../../player/lib/previewChannel"; import { usePreviewIframeStore } from "../../player/store/previewIframeStore"; import { useCaptionDetection } from "../../hooks/useCaptionDetection"; @@ -39,14 +37,6 @@ 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() { - const frame: Record = {}; - const iframe = detachedFakeIframe(frame); - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); let pick: ((request: PortRequest) => boolean) | null = null; const heldIds = new Set(); const held: Array<() => void> = []; @@ -67,20 +57,7 @@ function opaqueFrame() { }; return end as unknown as MessagePort; }; - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { - source: frame as unknown as Window, - data, - ports: ports.map(tap), - }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); + const { iframe } = sealedPreviewFrame({ wrapHandedOverPort: tap }); 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. */ diff --git a/packages/studio/src/components/editor/LayersPanel.opaque.test.ts b/packages/studio/src/components/editor/LayersPanel.opaque.test.ts index a4088431a7..949bc17563 100644 --- a/packages/studio/src/components/editor/LayersPanel.opaque.test.ts +++ b/packages/studio/src/components/editor/LayersPanel.opaque.test.ts @@ -3,16 +3,14 @@ import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, expect, it, vi } from "vitest"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness"; -import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness"; import { usePreviewIframeStore } from "../../player/store/previewIframeStore"; import type { DomEditSelection } from "./domEditing"; import { LayersPanel } from "./LayersPanel"; import { announcePreviewDocumentLoaded } from "../../player/sceneSwap"; import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements"; import { standInFor } from "./previewSelection"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; installReactActEnvironment(); @@ -75,35 +73,12 @@ afterEach(() => { document.body.innerHTML = ""; }); -/** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ -function opaqueFrame() { - const frame: Record = {}; - const iframe = detachedFakeIframe(frame); - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); - return iframe; -} - it("lists an opaque frame's layers, selects a row, and drills into a group row", async () => { document.body.innerHTML = `

Hi

`; - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; mocks.previewIframeRef.current = iframe; usePreviewIframeStore.setState({ iframe }); const host = document.createElement("div"); @@ -149,7 +124,7 @@ function renderPanel(iframe: HTMLIFrameElement) { it("leaves a drill-in whose group a reload took, rather than list the whole page under it", async () => { document.body.innerHTML = `
`; - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; const [pair] = (await queryPreviewElements(iframe, "#pair"))!.matches; const [described] = (await describePreviewElements(iframe, [pair!.handle]))!; mocks.activeGroupElement = standInFor(iframe, described!); @@ -163,7 +138,7 @@ it("reads the layers once more when a refresh lands while a read is in flight", document.body.innerHTML = `
`; let release!: () => void; mocks.hold = new Promise((resolve) => (release = resolve)); - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; const rows = renderPanel(iframe); await vi.waitFor(() => expect(mocks.answered).toBe(1)); // Past the panel's settle timer, so only the announced refresh can bring the new layer. diff --git a/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts b/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts index 174a544935..b068791667 100644 --- a/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts +++ b/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts @@ -3,15 +3,12 @@ import { gsap } from "gsap"; import { parseGsapScriptAcorn } from "@hyperframes/parsers/gsap-parser-acorn"; import { afterEach, expect, it, vi } from "vitest"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import { makeSelection } from "../../hooks/domSelectionTestHarness"; import { freezeDragStamp } from "../../hooks/draggedGsapPosition"; import { settleGsapSnapshot } from "../../hooks/gsapFrameSnapshot"; import { tryGsapDragIntercept } from "../../hooks/gsapRuntimeBridge"; import { watchPreviewFrame } from "../../player/lib/bridgePlayback"; import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements"; -import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness"; import { usePlayerStore } from "../../player/store/playerStore"; import type { UseDomEditOverlayGesturesOptions } from "./domEditOverlayGestures"; import { startGesture } from "./domEditOverlayStartGesture"; @@ -22,6 +19,7 @@ import { } from "./manualOffsetDrag"; import { measurePreviewGestureStart } from "./previewGestureStartRead"; import { standInFor } from "./previewSelection"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; const timeline = (tweens: string) => `var tl = gsap.timeline({ paused: true }); ${tweens} @@ -52,7 +50,6 @@ function drawnAt(box: HTMLElement) { const mainTimeline = () => (window as unknown as { __timelines?: Record }).__timelines?.main; -const closers: Array<() => void> = []; function mount(script: string, extra = "") { document.body.innerHTML = `
${extra}
`; const box = document.getElementById("box")!; @@ -76,7 +73,6 @@ function mount(script: string, extra = "") { usePlayerStore.setState({ currentTime: 0.5, isPlaying: false, autoKeyframeEnabled: true }); } afterEach(() => { - closers.splice(0).forEach((close) => close()); mainTimeline()?.kill(); document.body.innerHTML = ""; for (const name of ["gsap", "__timelines"]) Reflect.deleteProperty(window, name); @@ -91,24 +87,8 @@ function sized(element: T, [x, y, width, height]: number[]): /** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ function opaqueFrame() { - const frame: Record = {}; - const iframe = sized(detachedFakeIframe(frame), [100, 50, 960, 540]) as HTMLIFrameElement; - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); + const { iframe: sealed, frame } = sealedPreviewFrame(); + const iframe = sized(sealed, [100, 50, 960, 540]) as HTMLIFrameElement; watchPreviewFrame(iframe); window.dispatchEvent( new MessageEvent("message", { diff --git a/packages/studio/src/components/editor/previewDrafts.test.ts b/packages/studio/src/components/editor/previewDrafts.test.ts index d09aa644be..827f1d86e6 100644 --- a/packages/studio/src/components/editor/previewDrafts.test.ts +++ b/packages/studio/src/components/editor/previewDrafts.test.ts @@ -1,9 +1,7 @@ // @vitest-environment happy-dom import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; -import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements"; import { resolvePreviewSelection, standInFor } from "./previewSelection"; import { manualOffsetMoveRevert } from "./gestureUndoRevert"; @@ -35,38 +33,14 @@ vi.mock("../../player/lib/previewChannel", async (importOriginal) => { const draftRequests = () => vi.mocked(previewRequest).mock.calls.filter(([, kind]) => kind === "draft"); -const closers: Array<() => void> = []; beforeEach(() => { document.body.innerHTML = `
`; }); afterEach(() => { - closers.splice(0).forEach((close) => close()); document.body.innerHTML = ""; }); /** A frame whose window refuses every read, as a cross-origin one does; its runtime serves this document. */ -function opaqueFrame(): HTMLIFrameElement { - const blocked = () => { - throw new DOMException("blocked", "SecurityError"); - }; - const target: Record = {}; - const frame = new Proxy(target, { - get: (_, key) => (key === "postMessage" ? target.postMessage : blocked()), - }); - const iframe = detachedFakeIframe(frame); - Object.defineProperty(iframe, "contentDocument", { value: null }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - target.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); - return iframe; -} async function described(iframe: HTMLIFrameElement, selector: string) { const handle = (await queryPreviewElements(iframe, selector))!.matches[0]!.handle; @@ -106,7 +80,7 @@ const shown = (element: HTMLElement) => describe("gesture drafts on an opaque frame", () => { it("moves the frame's element with a drag, and puts it back when the drag is cancelled", async () => { - const member = dragMember(await standIn(opaqueFrame(), "#card")); + const member = dragMember(await standIn(sealedPreviewFrame().iframe, "#card")); applyManualOffsetDragDraft(member, 10, 0); applyManualOffsetDragDraft(member, 40, 20); await vi.waitFor(() => expect(shown(card())).toEqual([80, 40])); @@ -117,7 +91,7 @@ describe("gesture drafts on an opaque frame", () => { }); it("holds a saved drag where it was dropped, and the next drag starts from there", async () => { - const element = await standIn(opaqueFrame(), "#card"); + const element = await standIn(sealedPreviewFrame().iframe, "#card"); const first = dragMember(element); applyManualOffsetDragCommit(first, 40, 20); endManualOffsetDragMembers([first]); @@ -128,7 +102,7 @@ describe("gesture drafts on an opaque frame", () => { }); it("draws a drag that grabs the layer again before the last save settles from where that one left it", async () => { - const element = await standIn(opaqueFrame(), "#card"); + const element = await standIn(sealedPreviewFrame().iframe, "#card"); const first = dragMember(element); applyManualOffsetDragCommit(first, 40, 20); await vi.waitFor(() => expect(shown(card())).toEqual([80, 40])); @@ -143,7 +117,7 @@ describe("gesture drafts on an opaque frame", () => { }); it("puts a move back on the frame when an undo painted over it does not go through", async () => { - const member = dragMember(await standIn(opaqueFrame(), "#card")); + const member = dragMember(await standIn(sealedPreviewFrame().iframe, "#card")); applyManualOffsetDragCommit(member, 40, 20); await vi.waitFor(() => expect(shown(card())).toEqual([80, 40])); const putBack = manualOffsetMoveRevert([member])(); @@ -155,7 +129,7 @@ describe("gesture drafts on an opaque frame", () => { }); it("moves a % translate from the px the frame renders it at, and keeps the author's value to reset to", async () => { - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; const options = { activeCompositionPath: "index.html", isMasterView: false }; const selection = await resolvePreviewSelection( iframe, @@ -175,7 +149,7 @@ describe("gesture drafts on an opaque frame", () => { }); it("refuses to move a % translate it has no rendered px for, rather than drop it", async () => { - const element = await standIn(opaqueFrame(), "#centred"); + const element = await standIn(sealedPreviewFrame().iframe, "#centred"); const made = createManualOffsetDragMember({ key: "k", selection: { element } as DomEditSelection, @@ -187,13 +161,13 @@ describe("gesture drafts on an opaque frame", () => { }); it("keeps the translate the author had before Studio moved the layer as the one to reset to", async () => { - const element = await standIn(opaqueFrame(), "#moved"); + const element = await standIn(sealedPreviewFrame().iframe, "#moved"); applyManualOffsetDragCommit(dragMember(element), 40, 0); expect(element.getAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR)).toBe(""); }); it("starts a drag on a freshly loaded frame from the translate its element has", async () => { - const member = dragMember(await standIn(opaqueFrame(), "#chip")); + const member = dragMember(await standIn(sealedPreviewFrame().iframe, "#chip")); expect(member.initialOffset).toEqual({ x: 30, y: 0 }); expect(applyManualOffsetDragCommit(member, 40, 0)).toEqual({ x: 110, y: 0 }); const chip = document.getElementById("chip")!; @@ -201,7 +175,7 @@ describe("gesture drafts on an opaque frame", () => { }); it("sends one request at a time and draws only the latest of the moves that waited", async () => { - const member = dragMember(await standIn(opaqueFrame(), "#card")); + const member = dragMember(await standIn(sealedPreviewFrame().iframe, "#card")); vi.mocked(previewRequest).mockClear(); for (let dx = 2; dx <= 40; dx += 2) applyManualOffsetDragDraft(member, dx, 0); await vi.waitFor(() => expect(shown(card())).toEqual([80, 0])); @@ -209,7 +183,7 @@ describe("gesture drafts on an opaque frame", () => { }); it("grows a resized box about its centre without measuring the frame, and draws it there", async () => { - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; const element = await standIn(iframe, "#card"); const g = { ...{ originLeft: 10, originTop: 20, originWidth: 100, originHeight: 50 }, @@ -230,7 +204,7 @@ describe("gesture drafts on an opaque frame", () => { }); it("keeps a saved resize with no offset member on the frame when a later restore runs", async () => { - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; const element = await standIn(iframe, "#card"); const before = captureStudioBoxSize(element); const token = beginStudioManualEditGesture(element, "resize"); @@ -258,6 +232,6 @@ describe("gesture drafts on an opaque frame", () => { }); it("reports a timeline rebind it cannot reach, so the caller syncs the preview another way", () => { - expect(applySoftReloadFinalization(opaqueFrame(), 1)).toBe(false); + expect(applySoftReloadFinalization(sealedPreviewFrame().iframe, 1)).toBe(false); }); }); diff --git a/packages/studio/src/components/editor/previewGestureStartRead.test.ts b/packages/studio/src/components/editor/previewGestureStartRead.test.ts index e449c8c00a..c8adec83d9 100644 --- a/packages/studio/src/components/editor/previewGestureStartRead.test.ts +++ b/packages/studio/src/components/editor/previewGestureStartRead.test.ts @@ -2,8 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import { makeSelection } from "../../hooks/domSelectionTestHarness"; import { computeDraggedGsapPosition } from "../../hooks/draggedGsapPosition"; import { tryGsapResizeIntercept } from "../../hooks/gsapResizeIntercept"; @@ -24,6 +22,7 @@ import { } from "./previewGestureStartRead"; import { standInFor } from "./previewSelection"; import { collectSnapContext } from "./snapTargetCollection"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; const FIXTURE = `
@@ -91,24 +90,8 @@ function liveFrame() { /** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ function opaqueFrame() { - const frame: Record = {}; - const iframe = sized(detachedFakeIframe(frame), [100, 50, 960, 540]) as HTMLIFrameElement; - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); + const { iframe: sealed, frame } = sealedPreviewFrame(); + const iframe = sized(sealed, [100, 50, 960, 540]) as HTMLIFrameElement; watchPreviewFrame(iframe); window.dispatchEvent( new MessageEvent("message", { diff --git a/packages/studio/src/components/editor/previewLayers.test.ts b/packages/studio/src/components/editor/previewLayers.test.ts index 2ae6df434c..e738443e9c 100644 --- a/packages/studio/src/components/editor/previewLayers.test.ts +++ b/packages/studio/src/components/editor/previewLayers.test.ts @@ -4,8 +4,6 @@ import { act, createElement, useRef } from "react"; import { MAX_QUERY_MATCHES } from "@hyperframes/core/runtime/editing-port"; import { createRoot } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness"; import { watchPreviewFrame } from "../../player/lib/bridgePlayback"; import { getElementZIndex } from "../../player/lib/layerOrdering"; @@ -21,6 +19,7 @@ import { useMarqueeGestures } from "./marqueeCommit"; import { collectPreviewLayerItems, layerDataAttribute } from "./previewLayers"; import { findPreviewElementForSelection, resolvePreviewSelection } from "./previewSelection"; import { isLayerDraggable } from "./useLayerDrag"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; installReactActEnvironment(); HTMLElement.prototype.setPointerCapture ??= () => {}; @@ -83,24 +82,8 @@ function liveFrame() { /** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ function opaqueFrame() { - const frame: Record = {}; - const iframe = sized(detachedFakeIframe(frame), FRAME) as HTMLIFrameElement; - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); + const { iframe: sealed, frame } = sealedPreviewFrame(); + const iframe = sized(sealed, FRAME) as HTMLIFrameElement; watchPreviewFrame(iframe); window.dispatchEvent( new MessageEvent("message", { diff --git a/packages/studio/src/components/editor/previewOverlayRects.test.ts b/packages/studio/src/components/editor/previewOverlayRects.test.ts index 57a8d9021a..9407b77b4a 100644 --- a/packages/studio/src/components/editor/previewOverlayRects.test.ts +++ b/packages/studio/src/components/editor/previewOverlayRects.test.ts @@ -3,8 +3,6 @@ import React, { act } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import { makeSelection, installReactActEnvironment } from "../../hooks/domSelectionTestHarness"; import { watchPreviewFrame } from "../../player/lib/bridgePlayback"; import { queryPreviewElements } from "../../player/lib/previewElements"; @@ -14,6 +12,7 @@ import { orientedGroupAwareOverlayRect, type OverlayRect } from "./domEditOverla import type { UseDomEditOverlayGesturesOptions } from "./domEditOverlayGestures"; import { createPreviewGestureStarts } from "./previewGestureStarts"; import { useDomEditOverlayRects } from "./useDomEditOverlayRects"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; const frames = vi.hoisted(() => new Set<() => void>()); vi.mock("./overlayFrameLoop", () => ({ @@ -117,24 +116,8 @@ function liveFrame() { /** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ function opaqueFrame() { - const frame: Record = {}; - const iframe = sized(detachedFakeIframe(frame), [100, 50, 960, 540]) as HTMLIFrameElement; - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); + const { iframe: sealed, frame } = sealedPreviewFrame(); + const iframe = sized(sealed, [100, 50, 960, 540]) as HTMLIFrameElement; // The size the runtime posts for its composition, as Studio mirrors it. watchPreviewFrame(iframe); window.dispatchEvent( diff --git a/packages/studio/src/components/editor/previewPointerTargets.test.ts b/packages/studio/src/components/editor/previewPointerTargets.test.ts index 1f547dafbb..86e5fe3255 100644 --- a/packages/studio/src/components/editor/previewPointerTargets.test.ts +++ b/packages/studio/src/components/editor/previewPointerTargets.test.ts @@ -3,8 +3,6 @@ import React, { act } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import { getAllPreviewTargetsFromPointer, getPreviewTargetFromPointer, @@ -23,6 +21,7 @@ import { useDomSelection } from "../../hooks/useDomSelection"; import { usePreviewInteraction } from "../../hooks/usePreviewInteraction"; import { useCanvasContextMenuState } from "./useCanvasContextMenuState"; import type { TimelineElement } from "../../player"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; installReactActEnvironment(); @@ -92,24 +91,8 @@ function liveFrame(): HTMLIFrameElement { /** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ function opaqueFrame(): HTMLIFrameElement { - const frame: Record = {}; - const iframe = sized(detachedFakeIframe(frame), FRAME) as HTMLIFrameElement; - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); + const { iframe: sealed } = sealedPreviewFrame(); + const iframe = sized(sealed, FRAME) as HTMLIFrameElement; return iframe; } diff --git a/packages/studio/src/components/editor/previewSelection.test.ts b/packages/studio/src/components/editor/previewSelection.test.ts index 844a5de910..2c3d7b8e73 100644 --- a/packages/studio/src/components/editor/previewSelection.test.ts +++ b/packages/studio/src/components/editor/previewSelection.test.ts @@ -4,8 +4,6 @@ import React, { act } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, describe, expect, it, vi } from "vitest"; import { EDITING_ELEMENT_HANDLE, MAX_ELEMENT_TEXT } from "@hyperframes/core/runtime/editing-port"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import { findElementForSelection, findElementForTimelineElement, @@ -30,6 +28,7 @@ import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness"; import { useDomSelection } from "../../hooks/useDomSelection"; import type { TimelineElement } from "../../player"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; installReactActEnvironment(); @@ -53,29 +52,6 @@ function liveFrame(): HTMLIFrameElement { return iframe; } -/** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ -function opaqueFrame(): HTMLIFrameElement { - const frame: Record = {}; - const iframe = detachedFakeIframe(frame); - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); - return iframe; -} - const CONTEXT: PreviewSelectionOptions = { activeCompositionPath: "index.html", isMasterView: false, @@ -102,7 +78,7 @@ async function describedOnOpaque(iframe: HTMLIFrameElement, element: Element) { } async function bothPaths(element: HTMLElement, options: PreviewSelectionOptions = CONTEXT) { - const opaque = opaqueFrame(); + const opaque = sealedPreviewFrame().iframe; const live = await resolveDomEditSelection(element, options); const remote = await resolvePreviewSelection( opaque, @@ -184,7 +160,7 @@ describe("opaque frame selections match same-origin ones", () => { it("follows a drilled-into group: its nested group, then its children, else the top level", async () => { document.body.innerHTML = FIXTURE; const member = document.querySelector("[data-hf-id=m1]")!; - const opaque = opaqueFrame(); + const opaque = sealedPreviewFrame().iframe; const described = await describedOnOpaque(opaque, member); const outerLive = document.querySelector('[data-hf-group="outer"]')!; const innerLive = document.querySelector('[data-hf-group="inner"]')!; @@ -225,7 +201,11 @@ describe("opaque frame selections match same-origin ones", () => { ])("finds an element for a selection %s", async (_name, selection) => { document.body.innerHTML = FIXTURE; const live = findElementForSelection(document, selection, "index.html"); - const found = await findPreviewElementForSelection(opaqueFrame(), selection, "index.html"); + const found = await findPreviewElementForSelection( + sealedPreviewFrame().iframe, + selection, + "index.html", + ); expect(live === null ? null : nameOf(live)).toBe(found === null ? null : found && named(found)); if (selection.selector !== ".missing" && selection.selector !== "p[") expect(live).not.toBeNull(); @@ -244,7 +224,11 @@ describe("opaque frame selections match same-origin ones", () => { document.body.innerHTML = FIXTURE; const options = { activeCompositionPath: "index.html", isMasterView }; const live = findElementForTimelineElement(document, element, options); - const found = await findPreviewElementForTimelineElement(opaqueFrame(), element, options); + const found = await findPreviewElementForTimelineElement( + sealedPreviewFrame().iframe, + element, + options, + ); expect(live && nameOf(live)).toBe(expected); expect(found && named(found)).toBe(expected); }); @@ -269,7 +253,7 @@ describe("opaque frame selection handles", () => { it("builds nothing for a removed element, and finds nothing the runtime cannot name", async () => { document.body.innerHTML = FIXTURE; - const opaque = opaqueFrame(); + const opaque = sealedPreviewFrame().iframe; const locked = document.querySelector("#locked")!; const described = await describedOnOpaque(opaque, locked); // A description whose parent is not the element its runtime names as the parent. @@ -301,7 +285,7 @@ describe("opaque frame selection handles", () => { it("says it cannot tell when a capped query does not reach the index", async () => { document.body.innerHTML = "".repeat(2_049); const found = await findPreviewElementForSelection( - opaqueFrame(), + sealedPreviewFrame().iframe, { selector: ".n", selectorIndex: 2_048 }, "index.html", ); @@ -358,7 +342,7 @@ describe("opaque frame selections read only what arrived whole", () => { it("builds nothing when the frame cannot read computed styles or the composition root", async () => { document.body.innerHTML = FIXTURE; - const opaque = opaqueFrame(); + const opaque = sealedPreviewFrame().iframe; const locked = await describedOnOpaque(opaque, document.querySelector("#locked")!); const bg = await describedOnOpaque(opaque, document.querySelector("#bg")!); expect(await resolvePreviewSelection(opaque, bg, CONTEXT)).not.toBeNull(); @@ -420,7 +404,7 @@ describe("useDomSelection on an opaque frame", () => { it("selects a timeline clip, refreshes it, and drops it once the frame no longer has it", async () => { document.body.innerHTML = FIXTURE; const liveHook = renderSelection(liveFrame()); - const hook = renderSelection(opaqueFrame()); + const hook = renderSelection(sealedPreviewFrame().iframe); await act(() => liveHook().handleTimelineElementSelect(clip("#locked"))); await act(() => hook().handleTimelineElementSelect(clip("#locked"))); const selected = hook().domEditSelection!; @@ -439,7 +423,7 @@ describe("useDomSelection on an opaque frame", () => { it("re-finds every group member on refresh", async () => { document.body.innerHTML = FIXTURE; - const hook = renderSelection(opaqueFrame()); + const hook = renderSelection(sealedPreviewFrame().iframe); await act(() => hook().handleTimelineElementSelect(clip("#locked"))); const first = hook().domEditSelection!; await act(() => hook().handleTimelineElementSelect(clip("#plain"))); @@ -455,7 +439,7 @@ describe("useDomSelection on an opaque frame", () => { it("leaves a group the user changed while its refresh was reading the frame", async () => { document.body.innerHTML = FIXTURE; - const hook = renderSelection(opaqueFrame()); + const hook = renderSelection(sealedPreviewFrame().iframe); await act(() => hook().handleTimelineElementSelect(clip("#plain"))); const plain = hook().domEditSelection!; await act(() => hook().handleTimelineElementSelect(clip("#locked"))); diff --git a/packages/studio/src/components/editor/useColorGradingController.sealed.test.ts b/packages/studio/src/components/editor/useColorGradingController.sealed.test.ts index 2720057737..85a1cb61e3 100644 --- a/packages/studio/src/components/editor/useColorGradingController.sealed.test.ts +++ b/packages/studio/src/components/editor/useColorGradingController.sealed.test.ts @@ -4,12 +4,10 @@ import React, { act } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, describe, expect, it, vi } from "vitest"; import { normalizeHfColorGrading } from "@hyperframes/core/color-grading"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness"; -import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness"; import type { DomEditSelection } from "./domEditing"; import { useColorGradingController } from "./useColorGradingController"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; installReactActEnvironment(); @@ -20,29 +18,6 @@ afterEach(() => { document.body.innerHTML = ""; }); -/** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ -function opaqueFrame(): HTMLIFrameElement { - const frame: Record = {}; - const iframe = detachedFakeIframe(frame); - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); - return iframe; -} - /** The frame's colour grading runtime, on the window the agent serves. */ function installFrameGrading() { const stopPlayback = vi.fn(); @@ -109,7 +84,7 @@ const settle = (check: () => void) => describe("grade preview sealed", () => { it("reads the frame's grading status over the editing port", async () => { const { grading } = installFrameGrading(); - const state = renderController(opaqueFrame()); + const state = renderController(sealedPreviewFrame().iframe); await settle(() => expect(state().runtimeStatus).toEqual({ state: "active", message: "Shader active" }), @@ -119,7 +94,7 @@ describe("grade preview sealed", () => { it("draws preset cards the frame renders, and drops any that are not image data", async () => { const { grading } = installFrameGrading(); - const state = renderController(opaqueFrame()); + const state = renderController(sealedPreviewFrame().iframe); act(() => state().requestPresetPreviews()); await settle(() => expect(state().presetPreviews.images["bright-pop"]).toBeDefined()); @@ -135,7 +110,7 @@ describe("grade preview sealed", () => { it("plays the hovered card in the frame and stops it when the hover ends", async () => { const { grading, stopPlayback } = installFrameGrading(); - const state = renderController(opaqueFrame()); + const state = renderController(sealedPreviewFrame().iframe); const look = normalizeHfColorGrading({ preset: "bright-pop", intensity: 1 })!; act(() => @@ -157,7 +132,7 @@ describe("grade preview sealed", () => { it("captures a graded frame from the frame", async () => { installFrameGrading(); - const state = renderController(opaqueFrame()); + const state = renderController(sealedPreviewFrame().iframe); const frame = await act(() => state().captureGradedFrame()); expect(frame).toEqual({ dataUrl: "data:image/png;base64,capture", width: 160, height: 90 }); diff --git a/packages/studio/src/components/editor/useMotionPathData.sealed.test.ts b/packages/studio/src/components/editor/useMotionPathData.sealed.test.ts index cfb85e6a08..2507d9fb36 100644 --- a/packages/studio/src/components/editor/useMotionPathData.sealed.test.ts +++ b/packages/studio/src/components/editor/useMotionPathData.sealed.test.ts @@ -2,16 +2,13 @@ import { act, createElement, useRef } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; -import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness"; import { usePlayerStore } from "../../player/store/playerStore"; import { resetOverlayFrameLoopForTests } from "./overlayFrameLoop"; import { useMotionPathData } from "./useMotionPathData"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true); -const closers: Array<() => void> = []; const originalRaf = window.requestAnimationFrame; let frames: Array<() => void> = []; const runFrames = () => @@ -28,43 +25,19 @@ beforeEach(() => { usePlayerStore.setState({ previewBooted: true, motionPathArmed: true }); }); afterEach(() => { - closers.splice(0).forEach((close) => close()); resetOverlayFrameLoopForTests(); window.requestAnimationFrame = originalRaf; usePlayerStore.setState({ previewBooted: false, motionPathArmed: false }); document.body.innerHTML = ""; }); -/** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ -function opaqueFrame() { - const frame: Record = {}; - const iframe = detachedFakeIframe(frame); - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); - return iframe; -} - // fails without the fix: the hook read the layer from the frame's document, which a sealed frame keeps. it("finds a sealed preview's layer home, so its motion path draws from the layer", async () => { document.body.innerHTML = `
`; const box = document.getElementById("box")!; const layout = { offsetLeft: 100, offsetTop: 50, offsetWidth: 200, offsetHeight: 100 }; for (const [key, value] of Object.entries(layout)) Object.defineProperty(box, key, { value }); - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; let home: unknown = null; function Probe() { const ref = useRef(iframe); diff --git a/packages/studio/src/components/nle/audioSealedPreview.test.ts b/packages/studio/src/components/nle/audioSealedPreview.test.ts index 4c48bfb7bb..2631ca2202 100644 --- a/packages/studio/src/components/nle/audioSealedPreview.test.ts +++ b/packages/studio/src/components/nle/audioSealedPreview.test.ts @@ -3,25 +3,22 @@ import { act, createElement } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; -// The frame's real runtime agent, serving the opaque frame from this document. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import { usePlayerStore, type TimelineElement } from "../../player"; import { ClipMenuAudioItems } from "../../player/components/clipMenuAudioItems"; import { usePreviewIframeStore } from "../../player/store/previewIframeStore"; import { TimelineEditProvider } from "../../contexts/TimelineEditContext"; import { createAudioGroupAndAssignMembers } from "../../hooks/timelineAudioGroupCreate"; import { mintGroupId } from "../editor/useFxCarveGrouping"; -import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness"; import { useAudioMetersVisible } from "../../utils/audioMeterVisibility"; import { useSetAudioGroupAttribute } from "../../hooks/timelineAudioGroupVolume"; import { previewDocumentCopy } from "../../player/lib/previewChannel"; import { AudioMeterStrip } from "./AudioMeterStrip"; +import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; type MeterWindow = Window & { __hf?: Record }; -const closers: Array<() => void> = []; const roots: Root[] = []; let frames: FrameRequestCallback[] = []; const tick = () => { @@ -38,7 +35,6 @@ beforeEach(() => { }); afterEach(() => { act(() => roots.splice(0).forEach((root) => root.unmount())); - closers.splice(0).forEach((close) => close()); delete (window as MeterWindow).__hf; vi.unstubAllGlobals(); usePlayerStore.getState().reset(); @@ -46,29 +42,6 @@ afterEach(() => { document.body.innerHTML = ""; }); -/** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ -function opaqueFrame() { - const frame: Record = {}; - const iframe = detachedFakeIframe(frame); - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); - return iframe; -} - const member = (domId: string): TimelineElement => ({ id: domId, key: `compositions/voices.html#${domId}`, @@ -112,7 +85,7 @@ it("meter moves + group volume sealed", async () => { }; (window as MeterWindow).__hf = { audioMeter: meter }; usePlayerStore.getState().setElements([member("voice-1")]); - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; const host = document.createElement("div"); document.body.append(host); @@ -168,7 +141,7 @@ it("groups clips in a sealed preview, and unwinds the preview when the save fail document.body.innerHTML = `
`; - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; const files = new Map([["index.html", document.body.innerHTML]]); stubProjectFiles(files); const elements = ["voice-1", "voice-2"].map((domId) => ({ @@ -210,7 +183,7 @@ it("groups clips in a sealed preview, and unwinds the preview when the save fail it("reads a sealed preview's groups and ids off an inert copy", async () => { document.body.innerHTML = ``; - const copy = await previewDocumentCopy(opaqueFrame()); + const copy = await previewDocumentCopy(sealedPreviewFrame().iframe); expect(copy).not.toBeNull(); expect(copy).not.toBe(document); expect(mintGroupId(copy!)).toBe("voiceover-2"); @@ -222,7 +195,7 @@ it("offers Duck under voice for a bed in a sealed preview", async () => { `; - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; usePreviewIframeStore.setState({ iframe }); usePlayerStore.getState().beginTimelineSession("project-1"); const bed: TimelineElement = { diff --git a/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx b/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx index 992f33e14d..6cd7f0a58e 100644 --- a/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx +++ b/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx @@ -16,6 +16,7 @@ import { detachedFakeIframe, serveEditingRequests, } from "../player/hooks/timelinePlayerTestHarness"; +import { previewRequest } from "../player/lib/previewChannel"; vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); @@ -205,6 +206,7 @@ describe("preview iframe hotkey forwarding", () => { serveEditingRequests( frame, (kind, params) => { + if (kind === "max-z-index") return { zIndex: 7 }; if (kind !== "watch-keys") return null; watched.push((params as { combos: string[] }).combos); return { watching: watched.at(-1)!.length }; @@ -230,6 +232,18 @@ describe("preview iframe hotkey forwarding", () => { return { iframe, watched, ports, keyDown, hasFocus }; } + it("leaves Studio's own reads of the preview answered while it forwards keys", async () => { + root = mountReactHarness(); + const { iframe, watched } = sealedFrame(); + let read: Promise | undefined; + act(() => { + sync?.(iframe); + read = previewRequest(iframe, "max-z-index", {}, 1_000); + }); + await vi.waitFor(() => expect(watched).toHaveLength(1)); + await expect(read).resolves.toEqual({ zIndex: 7 }); + }); + it("deletes the selection on a Delete pressed inside the preview", async () => { root = mountReactHarness(); const { iframe, watched, keyDown } = sealedFrame(); diff --git a/packages/studio/src/hooks/useEnableKeyframes.sealed.test.ts b/packages/studio/src/hooks/useEnableKeyframes.sealed.test.ts index 3f81cd815c..4fc617128f 100644 --- a/packages/studio/src/hooks/useEnableKeyframes.sealed.test.ts +++ b/packages/studio/src/hooks/useEnableKeyframes.sealed.test.ts @@ -2,46 +2,19 @@ import { afterEach, expect, it, vi } from "vitest"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; -// The frame's real runtime agent, serving the opaque frame from this document as Studio's marked preview page. -import { installMarkedEditingAgent } from "../../../core/src/runtime/editingAgent.test-helpers"; -import { detachedFakeIframe } from "../player/hooks/timelinePlayerTestHarness"; import { describePreviewElements, queryPreviewElements } from "../player/lib/previewElements"; import { usePlayerStore } from "../player/store/playerStore"; import { standInFor } from "../components/editor/previewSelection"; import type { DomEditSelection } from "../components/editor/domEditingTypes"; import { applyKeyframeAtPlayhead, type EnableKeyframesSession } from "./useEnableKeyframes"; +import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers"; -const closers: Array<() => void> = []; afterEach(() => { - closers.splice(0).forEach((close) => close()); usePlayerStore.setState({ currentTime: 0, isPlaying: false }); document.body.innerHTML = ""; for (const name of ["gsap", "__timelines", "__player"]) Reflect.deleteProperty(window, name); }); -/** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ -function opaqueFrame() { - const frame: Record = {}; - const iframe = detachedFakeIframe(frame); - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); - return iframe; -} - /** The frame's GSAP: one keyframed tween moving #box, paused half way where GSAP has it at 120, 40. */ function frameGsapAt(seconds: number) { const box = document.getElementById("box")!; @@ -81,7 +54,7 @@ it("adds a keyframe at the playhead with the sealed preview's GSAP values there" document.body.innerHTML = `
`; frameGsapAt(0.5); usePlayerStore.setState({ currentTime: 0.5, isPlaying: false }); - const iframe = opaqueFrame(); + const iframe = sealedPreviewFrame().iframe; const [match] = (await queryPreviewElements(iframe, "#box"))!.matches; const [described] = (await describePreviewElements(iframe, [match!.handle]))!; const sel = { id: "box", selector: "#box", element: standInFor(iframe, described!) }; diff --git a/packages/studio/src/player/hooks/timelinePlayerTestHarness.ts b/packages/studio/src/player/hooks/timelinePlayerTestHarness.ts index dad2cc5d6d..f1474a51ee 100644 --- a/packages/studio/src/player/hooks/timelinePlayerTestHarness.ts +++ b/packages/studio/src/player/hooks/timelinePlayerTestHarness.ts @@ -171,7 +171,8 @@ export function serveEditingRequests( }; const handoff = { source: "hf-preview", type: "editing-port", v: 1 }; const source = frame as unknown as Window; - window.dispatchEvent(new MessageEvent("message", { source, data: handoff, ports: [port2] })); + const init = { source, data: handoff, ports: [port2] }; + setTimeout(() => window.dispatchEvent(new MessageEvent("message", init))); }; return () => ports.forEach((port) => port.close()); } diff --git a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts index c3838d76de..b1e3cb9619 100644 --- a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts +++ b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.sealed.test.ts @@ -3,43 +3,16 @@ import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, expect, it, vi } from "vitest"; -// The frame's real runtime agent, serving the opaque frame from this document as Studio's marked preview page. -import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; import type { TimelineElement } from "../store/playerStore"; -import { detachedFakeIframe } from "./timelinePlayerTestHarness"; import { useTimelineSyncCallbacks } from "./useTimelineSyncCallbacks"; +import { sealedPreviewFrame } from "../lib/sealedPreviewFrame.test-helpers"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; -const closers: Array<() => void> = []; afterEach(() => { - closers.splice(0).forEach((close) => close()); document.body.innerHTML = ""; }); -/** A frame Studio cannot read, whose runtime is the real editing agent over this document. */ -function opaqueFrame() { - const frame: Record = {}; - const iframe = detachedFakeIframe(frame); - Object.defineProperty(iframe, "contentDocument", { value: null }); - Object.defineProperty(frame, "document", { - get: () => { - throw new DOMException("blocked", "SecurityError"); - }, - }); - const parent = { - postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => - window.dispatchEvent( - new MessageEvent("message", { source: frame as unknown as Window, data, ports }), - ), - } as unknown as Window; - const agent = installMarkedEditingAgent(parent); - frame.postMessage = (data: unknown) => - window.dispatchEvent(new MessageEvent("message", { source: parent, data })); - closers.push(() => agent.dispose()); - return iframe; -} - function processWith(iframe: HTMLIFrameElement) { const sync = vi.fn<(els: TimelineElement[], duration?: number) => void>(); let callbacks: ReturnType | undefined; @@ -84,7 +57,7 @@ it("binds a sealed preview's timeline row to its element, as an open preview doe document.body.innerHTML = `
`; - const { sync, process } = processWith(opaqueFrame()); + const { sync, process } = processWith(sealedPreviewFrame().iframe); process({ clips: [boxClip], durationInFrames: 60 }); diff --git a/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts b/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts new file mode 100644 index 0000000000..55080fd24e --- /dev/null +++ b/packages/studio/src/player/lib/sealedPreviewFrame.test-helpers.ts @@ -0,0 +1,38 @@ +// A preview frame Studio cannot script, served by the frame's real runtime agent over this document. +import { onTestFinished } from "vitest"; +import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers"; +import { detachedFakeIframe } from "../hooks/timelinePlayerTestHarness"; + +/** A browser's postMessage: delivered on a later task, to every listener present then. */ +function postLater(init: MessageEventInit): void { + setTimeout(() => window.dispatchEvent(new MessageEvent("message", init))); +} + +export interface SealedPreviewFrame { + iframe: HTMLIFrameElement; + /** The frame's window as Studio sees it: only `postMessage` answers, and it reaches the runtime. */ + frame: Record; +} + +export function sealedPreviewFrame( + options: { wrapHandedOverPort?: (port: MessagePort) => MessagePort } = {}, +): SealedPreviewFrame { + const target: Record = {}; + const frame = new Proxy(target, { + get: (_, key) => { + if (key === "postMessage") return target.postMessage; + throw new DOMException("blocked", "SecurityError"); + }, + }); + const iframe = detachedFakeIframe(frame); + Object.defineProperty(iframe, "contentDocument", { value: null }); + const wrap = options.wrapHandedOverPort ?? ((port: MessagePort) => port); + const parent = { + postMessage: (data: unknown, _origin: string, ports: MessagePort[]) => + postLater({ source: frame as unknown as Window, data, ports: ports.map(wrap) }), + } as unknown as Window; + const agent = installMarkedEditingAgent(parent); + frame.postMessage = (data: unknown) => postLater({ source: parent, data }); + onTestFinished(() => agent.dispose()); + return { iframe, frame }; +} diff --git a/packages/studio/tsconfig.json b/packages/studio/tsconfig.json index ee7066da64..3173a513e1 100644 --- a/packages/studio/tsconfig.json +++ b/packages/studio/tsconfig.json @@ -24,5 +24,5 @@ "ignoreDeprecations": "5.0" }, "include": ["src"], - "exclude": ["dist", "node_modules", "src/**/*.test.ts"] + "exclude": ["dist", "node_modules", "src/**/*.test.ts", "src/**/*.test-helpers.ts"] } diff --git a/scripts/check-pr-captures.mjs b/scripts/check-pr-captures.mjs index 31c941cd46..4ef5c50264 100644 --- a/scripts/check-pr-captures.mjs +++ b/scripts/check-pr-captures.mjs @@ -131,7 +131,7 @@ function parseRecord(record) { } const DOC_FILE = /\.mdx?$/i; -const TEST_PATH = /\/(?:tests|__tests__)\/|\.(?:test|spec)\./; +const TEST_PATH = /\/(?:tests|__tests__)\/|\.(?:test|spec)(?:-helpers)?\./; const isWatched = (path) => path !== "" && WATCHED_PREFIXES.some((prefix) => path.startsWith(prefix)) && diff --git a/scripts/check-pr-captures.test.mjs b/scripts/check-pr-captures.test.mjs index 4fcfd62968..80ae2c49c1 100644 --- a/scripts/check-pr-captures.test.mjs +++ b/scripts/check-pr-captures.test.mjs @@ -121,7 +121,8 @@ test("test files under a watched package need no capture", () => { "28\t0\tpackages/studio/tests/e2e/edit-accuracy/server.test.mjs\0" + "12\t4\tpackages/studio/tests/e2e/edit-accuracy/case.mjs\0" + "6\t1\tpackages/player/src/a.spec.tsx\0" + - "40\t0\tpackages/studio/src/b.test.ts\0", + "40\t0\tpackages/studio/src/b.test.ts\0" + + "39\t0\tpackages/studio/src/c.test-helpers.ts\0", ); assert.deepEqual(files, []); assert.equal(evaluate({ body: "", files }).ok, true);