diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json index b22dac1060..0e69fb4464 100644 --- a/packages/core/package-subpaths.json +++ b/packages/core/package-subpaths.json @@ -476,6 +476,12 @@ "types": "./dist/runtime/editing/softReload.d.ts", "environments": ["browser", "bun", "node"] }, + "./runtime/scenes": { + "source": "./src/runtime/editing/scenes.ts", + "runtime": "./dist/runtime/editing/scenes.js", + "types": "./dist/runtime/editing/scenes.d.ts", + "environments": ["browser", "bun", "node"] + }, "./runtime/clip-window": { "source": "./src/runtime/clipWindow.ts", "runtime": "./dist/runtime/clipWindow.js", diff --git a/packages/core/package.json b/packages/core/package.json index a882730235..4002b219d3 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -483,6 +483,12 @@ "import": "./src/runtime/editing/softReload.ts", "types": "./src/runtime/editing/softReload.ts" }, + "./runtime/scenes": { + "bun": "./src/runtime/editing/scenes.ts", + "node": "./dist/runtime/editing/scenes.js", + "import": "./src/runtime/editing/scenes.ts", + "types": "./src/runtime/editing/scenes.ts" + }, "./runtime/clip-window": { "bun": "./src/runtime/clipWindow.ts", "node": "./dist/runtime/clipWindow.js", @@ -1003,6 +1009,10 @@ "import": "./dist/runtime/editing/softReload.js", "types": "./dist/runtime/editing/softReload.d.ts" }, + "./runtime/scenes": { + "import": "./dist/runtime/editing/scenes.js", + "types": "./dist/runtime/editing/scenes.d.ts" + }, "./runtime/clip-window": { "import": "./dist/runtime/clipWindow.js", "types": "./dist/runtime/clipWindow.d.ts" diff --git a/packages/core/src/runtime/editing/scenes.test.ts b/packages/core/src/runtime/editing/scenes.test.ts new file mode 100644 index 0000000000..84f4e7b7bd --- /dev/null +++ b/packages/core/src/runtime/editing/scenes.test.ts @@ -0,0 +1,98 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + holdScenes, + markScenesStaleIn, + parseHoldScenes, + parseMarkScenesStale, + parseSwapScenes, + swapScenes, +} from "./scenes"; + +afterEach(() => { + delete window.__hfHoldScenes; + delete window.__hfSwapScenes; + document.head.innerHTML = ""; + document.body.innerHTML = ""; +}); + +describe("hold-scenes", () => { + it("waits for the runtime to mount the named scenes", async () => { + let mounted = false; + window.__hfHoldScenes = vi.fn(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + mounted = true; + }); + expect(await holdScenes({ names: ["intro"] })).toEqual({ held: true }); + expect(window.__hfHoldScenes).toHaveBeenCalledWith(["intro"]); + expect(mounted).toBe(true); + }); + + it("says nothing was held where the preview mounts every scene", async () => { + expect(await holdScenes({ names: ["intro"] })).toEqual({ held: false }); + }); +}); + +describe("swap-scenes", () => { + it("swaps from the sent document", async () => { + window.__hfSwapScenes = vi.fn(async () => {}); + expect(await swapScenes({ html: "

next

", timeoutMs: 5000 })).toEqual({ swapped: true }); + expect(window.__hfSwapScenes).toHaveBeenCalledWith("

next

", expect.any(AbortSignal)); + }); + + it("answers the runtime's refusal as data", async () => { + window.__hfSwapScenes = async () => { + throw new Error("scenes were added or removed"); + }; + expect(await swapScenes({ html: "

", timeoutMs: 5000 })).toEqual({ + swapped: false, + reason: "Error: scenes were added or removed", + }); + }); + + it("aborts a swap that outlasts its time", async () => { + let signal: AbortSignal | undefined; + window.__hfSwapScenes = (_html, s) => { + signal = s; + return new Promise((_resolve, reject) => + s?.addEventListener("abort", () => reject(s.reason)), + ); + }; + const reply = await swapScenes({ html: "

", timeoutMs: 20 }); + expect(signal?.aborted).toBe(true); + expect(reply).toEqual({ swapped: false, reason: "Error: the swap took too long" }); + }); +}); + +describe("mark-scenes-stale", () => { + it("clears the hash of each scene a file is inlined in, and the shared hash for a file with no host", () => { + document.head.innerHTML = ``; + document.body.innerHTML = `
`; + + markScenesStaleIn(document, ["card.html", "index.html"]); + + const meta = document.querySelector("meta")!; + expect(JSON.parse(meta.content)).toEqual({ shared: "", scenes: { a: "", b: "2" } }); + }); +}); + +describe("scene parsers", () => { + it("accept bounded requests", () => { + expect(parseHoldScenes({ names: ["a"] })).toEqual({ names: ["a"] }); + expect(parseMarkScenesStale({ files: ["a.html"] })).toEqual({ files: ["a.html"] }); + expect(parseSwapScenes({ html: "

", timeoutMs: 5000 })).toEqual({ + html: "

", + timeoutMs: 5000, + }); + }); + + it.each([ + ["a hold with an extra field", () => parseHoldScenes({ names: [], holder: "x" })], + ["a hold of a non-string", () => parseHoldScenes({ names: [1] })], + ["a stale mark of too many files", () => parseMarkScenesStale({ files: Array(257).fill("a") })], + ["a swap with no html", () => parseSwapScenes({ html: "", timeoutMs: 5000 })], + ["a swap with no deadline", () => parseSwapScenes({ html: "

", timeoutMs: 0 })], + ["a swap with a script field", () => parseSwapScenes({ html: "x", timeoutMs: 1, script: "" })], + ])("refuse %s", (_label, parse) => { + expect(parse()).toBeNull(); + }); +}); diff --git a/packages/core/src/runtime/editing/scenes.ts b/packages/core/src/runtime/editing/scenes.ts new file mode 100644 index 0000000000..9b608dfc5d --- /dev/null +++ b/packages/core/src/runtime/editing/scenes.ts @@ -0,0 +1,103 @@ +// A scene-windowed preview mounts only the scenes near the playhead. Studio holds the scenes an element +// lives in, swaps edited scenes in place, and marks scenes stale; a sealed frame does each on itself. +import { SCENE_PART_ATTR, SCENE_PARTS_META, type SceneParts } from "../../sceneParts"; +import { escapeCssString } from "../editingElement"; +import { wallClearTimeout, wallSetTimeout } from "../wallClock"; + +const MAX_SCENE_NAMES = 256; +const MAX_NAME = 512; +const MAX_FILES = 256; +const MAX_FILE = 2_048; +export const MAX_SWAP_HTML = 50_000_000; +const MAX_SWAP_MS = 60_000; +const MAX_REASON = 500; + +type SceneWindow = Window & { + __hfHoldScenes?: (names: string[]) => Promise; + __hfSwapScenes?: (html: string, signal?: AbortSignal) => Promise; +}; + +const isRecord = (value: unknown): value is Record => + Object.prototype.toString.call(value) === "[object Object]"; + +const stringList = (value: unknown, count: number, length: number): value is string[] => + Array.isArray(value) && + value.length <= count && + value.every((item) => typeof item === "string" && item.length <= length); + +/** Each preview file is inlined under a host marked with it; clearing a scene's hash makes the next swap redo it. */ +export function markScenesStaleIn(doc: Document, files: readonly string[]): void { + const meta = doc.querySelector(`meta[name="${SCENE_PARTS_META}"]`); + if (!meta) return; + let parts: SceneParts; + try { + parts = JSON.parse(meta.content); + } catch { + return; + } + for (const file of files) { + const hosts = doc.querySelectorAll(`[data-composition-file="${escapeCssString(file)}"]`); + if (hosts.length === 0 && file.endsWith(".html")) parts.shared = ""; + for (const host of hosts) { + const scene = host.closest(`[${SCENE_PART_ATTR}]`)?.getAttribute(SCENE_PART_ATTR); + if (scene && scene in parts.scenes) parts.scenes[scene] = ""; + } + } + meta.content = JSON.stringify(parts); +} + +export type HoldScenesParams = { names: string[] }; +export type MarkScenesStaleParams = { files: string[] }; +export type SwapScenesParams = { html: string; timeoutMs: number }; +export type SwapScenesResult = { swapped: true } | { swapped: false; reason: string }; + +export function parseHoldScenes(params: unknown): HoldScenesParams | null { + if (!isRecord(params) || Object.keys(params).join() !== "names") return null; + return stringList(params.names, MAX_SCENE_NAMES, MAX_NAME) ? { names: params.names } : null; +} + +export function parseMarkScenesStale(params: unknown): MarkScenesStaleParams | null { + if (!isRecord(params) || Object.keys(params).join() !== "files") return null; + return stringList(params.files, MAX_FILES, MAX_FILE) ? { files: params.files } : null; +} + +export function parseSwapScenes(params: unknown): SwapScenesParams | null { + if (!isRecord(params) || Object.keys(params).sort().join() !== "html,timeoutMs") return null; + const { html, timeoutMs } = params; + if (typeof html !== "string" || html.length === 0 || html.length > MAX_SWAP_HTML) return null; + const okTimeout = typeof timeoutMs === "number" && timeoutMs > 0 && timeoutMs <= MAX_SWAP_MS; + return okTimeout ? { html, timeoutMs } : null; +} + +/** Waits until the named scenes are mounted; false when this preview mounts every scene anyway. */ +export async function holdScenes({ names }: HoldScenesParams): Promise<{ held: boolean }> { + const hold = (window as SceneWindow).__hfHoldScenes; + if (typeof hold !== "function") return { held: false }; + await hold(names); + return { held: true }; +} + +export function markScenesStale({ files }: MarkScenesStaleParams): { marked: true } { + markScenesStaleIn(document, files); + return { marked: true }; +} + +/** Swaps the edited scenes from the preview document Studio fetched; a swap past its time is aborted. */ +export async function swapScenes({ html, timeoutMs }: SwapScenesParams): Promise { + const swap = (window as SceneWindow).__hfSwapScenes; + if (typeof swap !== "function") + return { swapped: false, reason: "the preview cannot swap scenes" }; + const deadline = new AbortController(); + const timer = wallSetTimeout( + () => deadline.abort(new Error("the swap took too long")), + timeoutMs, + ); + try { + await swap(html, deadline.signal); + return { swapped: true }; + } catch (error) { + return { swapped: false, reason: String(error).slice(0, MAX_REASON) }; + } finally { + wallClearTimeout(timer); + } +} diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts index 5b36eb780e..5aebfba7cf 100644 --- a/packages/core/src/runtime/editingAgent.test.ts +++ b/packages/core/src/runtime/editingAgent.test.ts @@ -204,6 +204,9 @@ describe("installEditingAgent", () => { "gsap-set", "patch-tweens", "soft-reload", + "hold-scenes", + "mark-scenes-stale", + "swap-scenes", "assets-unloaded", ], }, @@ -555,6 +558,35 @@ describe("installEditingAgent", () => { for (const key of ["gsap", "__timelines", "__hfForceTimelineRebind"]) delete frame[key]; }); + it("holds and swaps scenes through the port, and refuses a hold carrying anything extra", async () => { + const hold = vi.fn(async () => {}); + window.__hfHoldScenes = hold; + window.__hfSwapScenes = async () => { + throw new Error("no scene changed"); + }; + const port = connectedPort(); + + const extra = { names: ["intro"], holder: "frame" }; + expect(await ask(port, { v: 1, id: 1, kind: "hold-scenes", params: extra })).toMatchObject({ + ok: false, + }); + expect(hold).not.toHaveBeenCalled(); + const held = await ask(port, { + v: 1, + id: 2, + kind: "hold-scenes", + params: { names: ["intro"] }, + }); + expect(held).toMatchObject({ ok: true, result: { held: true } }); + const swap = { html: "

", timeoutMs: 1000 }; + expect(await ask(port, { v: 1, id: 3, kind: "swap-scenes", params: swap })).toMatchObject({ + ok: true, + result: { swapped: false, reason: "Error: no scene changed" }, + }); + delete window.__hfHoldScenes; + delete window.__hfSwapScenes; + }); + it("answers computed styles for the element a selector names", async () => { document.body.innerHTML = `

Hi

diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts index 9736c41c05..03fc3997e8 100644 --- a/packages/core/src/runtime/editingAgent.ts +++ b/packages/core/src/runtime/editingAgent.ts @@ -43,6 +43,7 @@ import { stackingFamily } from "./editingLayers"; import { gsapSet } from "./editing/gsapSet"; import { patchTweens } from "./editing/patchTween"; import { softReload } from "./editing/softReload"; +import { holdScenes, markScenesStale, swapScenes } from "./editing/scenes"; import { previewAssetsUnloaded } from "../lottieReadiness"; import { getLogicalOpacity, @@ -229,6 +230,9 @@ const HANDLERS: Handlers = { "gsap-set": gsapSet, "patch-tweens": patchTweens, "soft-reload": softReload, + "hold-scenes": holdScenes, + "mark-scenes-stale": markScenesStale, + "swap-scenes": swapScenes, "assets-unloaded": () => ({ unloaded: previewAssetsUnloaded(document, window.__hfLottie) }), }; diff --git a/packages/core/src/runtime/editingPort.test.ts b/packages/core/src/runtime/editingPort.test.ts index 0120fa6a37..b01ee519dd 100644 --- a/packages/core/src/runtime/editingPort.test.ts +++ b/packages/core/src/runtime/editingPort.test.ts @@ -107,6 +107,9 @@ describe("createEditingPortClient", () => { "gsap-set", "patch-tweens", "soft-reload", + "hold-scenes", + "mark-scenes-stale", + "swap-scenes", "assets-unloaded", ], }); diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index 32efc6a1bd..5e81d83adf 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -36,6 +36,15 @@ import { type SoftReloadParams, type SoftReloadResult, } from "./editing/softReload"; +import { + parseHoldScenes, + parseMarkScenesStale, + parseSwapScenes, + type HoldScenesParams, + type MarkScenesStaleParams, + type SwapScenesParams, + type SwapScenesResult, +} from "./editing/scenes"; import type { RuntimeTimelineMessage } from "./types"; import { wallClearTimeout, wallSetTimeout } from "./wallClock"; import { parseCombo } from "../keyCombo"; @@ -193,6 +202,9 @@ export const EDITING_REQUEST_KINDS = [ "gsap-set", "patch-tweens", "soft-reload", + "hold-scenes", + "mark-scenes-stale", + "swap-scenes", "assets-unloaded", ] as const; export type EditingRequestKind = (typeof EDITING_REQUEST_KINDS)[number]; @@ -335,6 +347,9 @@ export interface EditingRequests { "gsap-set": { params: GsapSetParams; result: { applied: boolean } }; "patch-tweens": { params: PatchTweensParams; result: { patched: boolean } }; "soft-reload": { params: SoftReloadParams; result: { result: SoftReloadResult } }; + "hold-scenes": { params: HoldScenesParams; result: { held: boolean } }; + "mark-scenes-stale": { params: MarkScenesStaleParams; result: { marked: true } }; + "swap-scenes": { params: SwapScenesParams; result: SwapScenesResult }; "assets-unloaded": { params: NoParams; result: { unloaded: boolean } }; } export type EditingParams = EditingRequests[K]["params"]; @@ -549,6 +564,9 @@ const PARAM_PARSERS: { "gsap-set": parseGsapSet, "patch-tweens": parsePatchTweens, "soft-reload": parseSoftReload, + "hold-scenes": parseHoldScenes, + "mark-scenes-stale": parseMarkScenesStale, + "swap-scenes": parseSwapScenes, "assets-unloaded": noParams, }; diff --git a/packages/studio/src/hooks/useDomSelection.ts b/packages/studio/src/hooks/useDomSelection.ts index c0063c94ad..69bbeb04e0 100644 --- a/packages/studio/src/hooks/useDomSelection.ts +++ b/packages/studio/src/hooks/useDomSelection.ts @@ -331,6 +331,7 @@ export function useDomSelection({ return null; } if (!doc) { + await holdScenesOf(iframe, element); const found = await findOpaqueTimelineElement(iframe, element, lookup); return found ? buildDomSelectionFromTarget(found, { preferClipAncestor: false }, iframe) diff --git a/packages/studio/src/player/sceneSwap.sealed.test.ts b/packages/studio/src/player/sceneSwap.sealed.test.ts new file mode 100644 index 0000000000..59008695dc --- /dev/null +++ b/packages/studio/src/player/sceneSwap.sealed.test.ts @@ -0,0 +1,76 @@ +// @vitest-environment happy-dom +import { beforeEach, expect, it, vi } from "vitest"; + +const { previewRequest, studioApiFetch } = vi.hoisted(() => ({ + previewRequest: vi.fn(), + studioApiFetch: vi.fn(), +})); +vi.mock("./lib/previewChannel", async (importOriginal) => ({ + ...(await importOriginal()), + previewFrameOpaque: () => true, + previewRequest, +})); +vi.mock("../utils/studioApiFetch", () => ({ studioApiFetch })); + +import { + markScenesStale, + onPreviewContentReplaced, + SCENE_SWAP_MS, + sceneSwapFor, +} from "./sceneSwap"; + +const iframe = document.createElement("iframe"); +const PREVIEW = "the rebuilt preview"; + +beforeEach(() => { + previewRequest.mockReset(); + studioApiFetch.mockReset(); + studioApiFetch.mockResolvedValue(new Response(PREVIEW)); +}); + +it("swaps a sealed preview's scenes from the document Studio fetched, and says the content changed", async () => { + previewRequest.mockResolvedValue({ swapped: true }); + const replaced = vi.fn(); + onPreviewContentReplaced(iframe, replaced); + + const swap = sceneSwapFor(iframe); + await swap!("/preview/index.html?_t=1", () => true); + + expect(studioApiFetch).toHaveBeenCalledWith("/preview/index.html?_t=1", expect.anything()); + expect(previewRequest).toHaveBeenCalledExactlyOnceWith( + iframe, + "swap-scenes", + { html: PREVIEW, timeoutMs: SCENE_SWAP_MS }, + SCENE_SWAP_MS, + ); + expect(replaced).toHaveBeenCalledOnce(); +}); + +it.each([ + ["refuses", { swapped: false, reason: "scenes were added or removed" }], + ["does not answer", null], + ["answers with an extra field", { swapped: true, html: "" }], +])("rejects, so the film reloads, when the frame %s", async (_label, reply) => { + previewRequest.mockResolvedValue(reply); + const replaced = vi.fn(); + onPreviewContentReplaced(iframe, replaced); + + await expect(sceneSwapFor(iframe)!("/preview/index.html", () => true)).rejects.toThrow( + "the preview did not swap its scenes", + ); + expect(replaced).not.toHaveBeenCalled(); +}); + +it("sends nothing when a newer edit superseded the fetched document", async () => { + await expect(sceneSwapFor(iframe)!("/preview/index.html", () => false)).rejects.toThrow( + "superseded", + ); + expect(previewRequest).not.toHaveBeenCalled(); +}); + +it("marks a sealed preview's edited scenes stale through the frame", () => { + markScenesStale(iframe, ["card.html"]); + expect(previewRequest).toHaveBeenCalledExactlyOnceWith(iframe, "mark-scenes-stale", { + files: ["card.html"], + }); +}); diff --git a/packages/studio/src/player/sceneSwap.test.ts b/packages/studio/src/player/sceneSwap.test.ts index e603ff1451..de88f2227a 100644 --- a/packages/studio/src/player/sceneSwap.test.ts +++ b/packages/studio/src/player/sceneSwap.test.ts @@ -24,7 +24,7 @@ function swappableIframe(swap: Swap = vi.fn(async () => {})) { } describe("sceneSwapFor", () => { - it("returns no swap for an opaque frame, without reading its window", () => { + it("swaps an opaque frame through its editing port, without reading its window", () => { const iframe = document.createElement("iframe"); const blocked = new Proxy({} as Window, { get: () => { @@ -33,7 +33,7 @@ describe("sceneSwapFor", () => { }); Object.defineProperty(iframe, "contentWindow", { value: blocked }); Object.defineProperty(iframe, "contentDocument", { value: null }); - expect(sceneSwapFor(iframe)).toBeNull(); + expect(sceneSwapFor(iframe)).toBeTypeOf("function"); }); it("gives up on a preview download that never finishes, so the caller can reload", async () => { diff --git a/packages/studio/src/player/sceneSwap.ts b/packages/studio/src/player/sceneSwap.ts index db1cc8aa48..3b68c8eca9 100644 --- a/packages/studio/src/player/sceneSwap.ts +++ b/packages/studio/src/player/sceneSwap.ts @@ -2,8 +2,10 @@ import { studioApiFetch } from "../utils/studioApiFetch"; import { studioFileRevision } from "../utils/studioFileVersion"; import { logReload } from "../utils/reloadDebug"; import { whileScriptWrites } from "./previewReloading"; -import { previewFrameOpaque } from "./lib/previewChannel"; +import { markScenesStaleIn } from "@hyperframes/core/runtime/scenes"; +import { previewFrameOpaque, previewRequest } from "./lib/previewChannel"; +type ApplySwap = (html: string, signal: AbortSignal) => Promise; type SwapWindow = Window & { __hfSwapScenes?: (html: string, signal?: AbortSignal) => Promise; }; @@ -56,24 +58,12 @@ export function onPreviewPromoted( } export function markScenesStale(iframe: HTMLIFrameElement | null, files: readonly string[]): void { - const doc = iframe?.contentDocument; - const meta = doc?.querySelector('meta[name="hf-scene-parts"]'); - if (!doc || !meta) return; - let parts: { shared: string; scenes: Record }; - try { - parts = JSON.parse(meta.content); - } catch { + if (iframe && previewFrameOpaque(iframe)) { + void previewRequest(iframe, "mark-scenes-stale", { files: [...files] }); return; } - for (const file of files) { - const hosts = doc.querySelectorAll(`[data-composition-file="${CSS.escape(file)}"]`); - if (hosts.length === 0 && file.endsWith(".html")) parts.shared = ""; - for (const host of hosts) { - const scene = host.closest("[data-hf-scene]")?.getAttribute("data-hf-scene"); - if (scene && scene in parts.scenes) parts.scenes[scene] = ""; - } - } - meta.content = JSON.stringify(parts); + const doc = iframe?.contentDocument; + if (doc) markScenesStaleIn(doc, files); } export const supersededByNewerEdit = () => @@ -111,14 +101,33 @@ export function swapFreshly( }); } +function reachableSwap(iframe: HTMLIFrameElement): ApplySwap | null { + const win = iframe.contentWindow as SwapWindow | null; + const swap = win?.__hfSwapScenes; + return typeof swap === "function" ? (html, signal) => swap.call(win, html, signal) : null; +} + +function sealedSwap(iframe: HTMLIFrameElement): ApplySwap { + return async (html) => { + const reply: unknown = await previewRequest( + iframe, + "swap-scenes", + { html, timeoutMs: SCENE_SWAP_MS }, + SCENE_SWAP_MS, + ); + const { swapped, reason } = (reply ?? {}) as { swapped?: unknown; reason?: unknown }; + if (swapped === true && Object.keys(reply as object).length === 1) return; + const why = typeof reason === "string" ? reason.slice(0, 500) : "no answer"; + throw new Error(`the preview did not swap its scenes: ${why}`); + }; +} + /** Null when the preview cannot swap; rejects when superseded, cancelled or a full reload is needed. */ export function sceneSwapFor( iframe: HTMLIFrameElement, ): ((url: string, isCurrent: () => boolean, cancel?: AbortSignal) => Promise) | null { - if (previewFrameOpaque(iframe)) return null; - const win = iframe.contentWindow as SwapWindow | null; - const swap = win?.__hfSwapScenes; - if (typeof swap !== "function") return null; + const apply = previewFrameOpaque(iframe) ? sealedSwap(iframe) : reachableSwap(iframe); + if (!apply) return null; return async (url, isCurrent, cancel) => { if (cancel?.aborted) throw cancel.reason; const deadline = new AbortController(); @@ -134,7 +143,7 @@ export function sceneSwapFor( const html = await response.text(); if (!isCurrent()) throw new Error("superseded by a newer reload"); // Aborted with the deadline, so a swap still waiting cannot land after the reload has begun. - await swap.call(win, html, deadline.signal); + await apply(html, deadline.signal); })(); const expired = new Promise((_resolve, reject) => deadline.signal.addEventListener("abort", () => reject(deadline.signal.reason)), diff --git a/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts b/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts index eadd4f8554..7505c7a3d3 100644 --- a/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts +++ b/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts @@ -65,9 +65,14 @@ describe("undo on a sealed preview", () => { undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 1 }")); expect(channel.request.mock.calls[0]![2]).toMatchObject({ scripted: true }); channel.request.mockReset(); - const { reload, strategy } = undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 2 }")); + const { reload, strategy, iframe } = undo( + box(90) + script("{ x: 1 }"), + box(0) + script("{ x: 2 }"), + ); expect(strategy).toBe("full"); expect(reload).toHaveBeenCalledOnce(); - expect(channel.request).not.toHaveBeenCalled(); + expect(channel.request).toHaveBeenCalledExactlyOnceWith(iframe, "mark-scenes-stale", { + files: ["index.html"], + }); }); }); diff --git a/packages/studio/src/utils/sceneHold.sealed.test.ts b/packages/studio/src/utils/sceneHold.sealed.test.ts new file mode 100644 index 0000000000..3e90cb7371 --- /dev/null +++ b/packages/studio/src/utils/sceneHold.sealed.test.ts @@ -0,0 +1,42 @@ +// @vitest-environment happy-dom +import { expect, it, vi } from "vitest"; + +const { previewRequest } = vi.hoisted(() => ({ previewRequest: vi.fn() })); +vi.mock("../player/lib/previewChannel", async (importOriginal) => ({ + ...(await importOriginal()), + previewFrameOpaque: () => true, + previewRequest, +})); + +import type { TimelineElement } from "../player"; +import { holdScenesOf } from "./sceneHold"; + +const iframe = document.createElement("iframe"); + +it("holds a sealed preview's scenes of an element through the frame, and waits until they are mounted", async () => { + let answer: (value: unknown) => void = () => {}; + previewRequest.mockReturnValue(new Promise((resolve) => (answer = resolve))); + const element = { + compositionAncestors: ["film"], + parentCompositionId: "intro", + } as TimelineElement; + + let mounted = false; + const held = holdScenesOf(iframe, element)?.then(() => (mounted = true)); + await Promise.resolve(); + + expect(previewRequest).toHaveBeenCalledExactlyOnceWith(iframe, "hold-scenes", { + names: ["film", "intro"], + }); + expect(mounted).toBe(false); + answer({ held: true }); + await held; + expect(mounted).toBe(true); +}); + +it("releases a sealed preview's held scenes when nothing is selected", () => { + previewRequest.mockReset(); + previewRequest.mockResolvedValue({ held: true }); + void holdScenesOf(iframe, null); + expect(previewRequest).toHaveBeenCalledExactlyOnceWith(iframe, "hold-scenes", { names: [] }); +}); diff --git a/packages/studio/src/utils/sceneHold.ts b/packages/studio/src/utils/sceneHold.ts index 5efc34d120..bdf2802678 100644 --- a/packages/studio/src/utils/sceneHold.ts +++ b/packages/studio/src/utils/sceneHold.ts @@ -1,4 +1,5 @@ import type { TimelineElement } from "../player"; +import { previewFrameOpaque, previewRequest } from "../player/lib/previewChannel"; type SceneHoldingWindow = Window & { __hfHoldScenes?: (names: string[]) => Promise }; @@ -7,6 +8,11 @@ export function holdScenesOf( iframe: HTMLIFrameElement | null, element: TimelineElement | null, ): Promise | undefined { + const names = element + ? [...(element.compositionAncestors ?? []), element.parentCompositionId ?? ""].filter(Boolean) + : []; + if (iframe && previewFrameOpaque(iframe)) + return previewRequest(iframe, "hold-scenes", { names }).then(() => {}); let hold: SceneHoldingWindow["__hfHoldScenes"]; try { hold = (iframe?.contentWindow as SceneHoldingWindow | null)?.__hfHoldScenes; @@ -14,8 +20,5 @@ export function holdScenesOf( return undefined; } if (!hold) return undefined; - const names = element - ? [...(element.compositionAncestors ?? []), element.parentCompositionId ?? ""] - : []; - return hold(names.filter(Boolean)).catch(() => {}); + return hold(names).catch(() => {}); }