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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/core/package-subpaths.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
10 changes: 10 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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"
Expand Down
98 changes: 98 additions & 0 deletions packages/core/src/runtime/editing/scenes.test.ts
Original file line number Diff line number Diff line change
@@ -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: "<p>next</p>", timeoutMs: 5000 })).toEqual({ swapped: true });
expect(window.__hfSwapScenes).toHaveBeenCalledWith("<p>next</p>", 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: "<p></p>", 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: "<p></p>", 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 = `<meta name="hf-scene-parts" content='{"shared":"s","scenes":{"a":"1","b":"2"}}'>`;
document.body.innerHTML = `<div data-hf-scene="a"><div data-composition-file="card.html"></div></div>`;

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: "<p></p>", timeoutMs: 5000 })).toEqual({
html: "<p></p>",
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: "<p></p>", timeoutMs: 0 })],
["a swap with a script field", () => parseSwapScenes({ html: "x", timeoutMs: 1, script: "" })],
])("refuse %s", (_label, parse) => {
expect(parse()).toBeNull();
});
});
103 changes: 103 additions & 0 deletions packages/core/src/runtime/editing/scenes.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
__hfSwapScenes?: (html: string, signal?: AbortSignal) => Promise<void>;
};

const isRecord = (value: unknown): value is Record<string, unknown> =>
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<HTMLMetaElement>(`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<SwapScenesResult> {
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);
}
}
32 changes: 32 additions & 0 deletions packages/core/src/runtime/editingAgent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,9 @@ describe("installEditingAgent", () => {
"gsap-set",
"patch-tweens",
"soft-reload",
"hold-scenes",
"mark-scenes-stale",
"swap-scenes",
"assets-unloaded",
],
},
Expand Down Expand Up @@ -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: "<p></p>", 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 = `<p id="title" style="color: rgb(1, 2, 3); opacity: 0.5">Hi</p>
<canvas data-hf-preview-video-canvas style="opacity: 0.25"></canvas>
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/runtime/editingAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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) }),
};

Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/runtime/editingPort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ describe("createEditingPortClient", () => {
"gsap-set",
"patch-tweens",
"soft-reload",
"hold-scenes",
"mark-scenes-stale",
"swap-scenes",
"assets-unloaded",
],
});
Expand Down
18 changes: 18 additions & 0 deletions packages/core/src/runtime/editingPort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -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<K extends EditingRequestKind> = EditingRequests[K]["params"];
Expand Down Expand Up @@ -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,
};

Expand Down
1 change: 1 addition & 0 deletions packages/studio/src/hooks/useDomSelection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading