mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
fix(studio): off-canvas indicators show in a sealed preview (#8680)
* fix(studio): off-canvas indicators show in a sealed preview * refactor(studio): off-canvas refresh picks the sealed or same-origin read in its own step
This commit is contained in:
@@ -556,6 +556,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
|
||||
groupSelections={groupSelections}
|
||||
activeCompositionPathRef={activeCompositionPathRef}
|
||||
onSelectionChangeRef={onSelectionChangeRef}
|
||||
iframeRef={iframeRef}
|
||||
/>
|
||||
<MarqueeOverlay candidateRects={marquee.candidateRects} marqueeRect={marquee.marqueeRect} />
|
||||
{contextMenu && (
|
||||
|
||||
@@ -21,6 +21,7 @@ it("rotates an off-canvas indicator with its element", () => {
|
||||
groupSelections={[]}
|
||||
activeCompositionPathRef={{ current: null }}
|
||||
onSelectionChangeRef={{ current: () => undefined }}
|
||||
iframeRef={{ current: null }}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -20,6 +20,7 @@ interface OffCanvasIndicatorsProps {
|
||||
onSelectionChangeRef: React.MutableRefObject<
|
||||
(selection: DomEditSelection, options?: { revealPanel?: boolean; additive?: boolean }) => void
|
||||
>;
|
||||
iframeRef: React.RefObject<HTMLIFrameElement | null>;
|
||||
}
|
||||
|
||||
function clipOutsideCanvas(
|
||||
@@ -75,6 +76,7 @@ export function OffCanvasIndicators({
|
||||
groupSelections,
|
||||
activeCompositionPathRef,
|
||||
onSelectionChangeRef,
|
||||
iframeRef,
|
||||
}: OffCanvasIndicatorsProps): React.ReactElement {
|
||||
return (
|
||||
<>
|
||||
@@ -100,13 +102,14 @@ export function OffCanvasIndicators({
|
||||
const selectOffCanvas = async () => {
|
||||
const el = elements.current.get(r.key);
|
||||
if (!el) return;
|
||||
const { resolveDomEditSelection } = await import("./domEditingLayers");
|
||||
const acp = activeCompositionPathRef.current ?? "index.html";
|
||||
const sel = await resolveDomEditSelection(el, {
|
||||
const options = {
|
||||
activeCompositionPath: acp,
|
||||
isMasterView: !acp || acp === "index.html",
|
||||
skipSourceProbe: true,
|
||||
});
|
||||
};
|
||||
const { resolveIndicatorSelection } = await import("./previewOffCanvas");
|
||||
const sel = await resolveIndicatorSelection(iframeRef.current, el, options);
|
||||
if (sel) onSelectionChangeRef.current(sel, { revealPanel: true });
|
||||
};
|
||||
const handleClick = (e: React.MouseEvent) => {
|
||||
|
||||
@@ -21,7 +21,7 @@ function offCanvasSignature(rects: OffCanvasRect[]): string {
|
||||
.join("|");
|
||||
}
|
||||
|
||||
function extendsOutside(
|
||||
export function extendsOutside(
|
||||
rect: Omit<OffCanvasRect, "key">,
|
||||
comp: { left: number; top: number; width: number; height: number },
|
||||
): boolean {
|
||||
@@ -126,9 +126,20 @@ export function recomputeOffCanvasIndicators(
|
||||
}
|
||||
}
|
||||
|
||||
publishOffCanvasRects(rects, elMap, sigRef, elementsRef, setRects);
|
||||
}
|
||||
|
||||
/** Shows `rects` unless they are what is already shown. */
|
||||
export function publishOffCanvasRects(
|
||||
rects: OffCanvasRect[],
|
||||
elements: Map<string, HTMLElement>,
|
||||
sigRef: React.MutableRefObject<string>,
|
||||
elementsRef: React.MutableRefObject<Map<string, HTMLElement>>,
|
||||
setRects: (rects: OffCanvasRect[]) => void,
|
||||
): void {
|
||||
const nextSig = offCanvasSignature(rects);
|
||||
if (nextSig === sigRef.current) return;
|
||||
sigRef.current = nextSig;
|
||||
elementsRef.current = elMap;
|
||||
elementsRef.current = elements;
|
||||
setRects(rects);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
createDomEditLayerWalkCache,
|
||||
drainPendingLayerMutations,
|
||||
} from "./domEditLayerWalkCache";
|
||||
import { recomputeOffCanvasIndicators } from "./offCanvasIndicatorGeometry";
|
||||
import { previewFrameOpaque } from "../../player/lib/previewChannel";
|
||||
import { publishOffCanvasRects, recomputeOffCanvasIndicators } from "./offCanvasIndicatorGeometry";
|
||||
import { measurePreviewOffCanvas } from "./previewOffCanvas";
|
||||
import { requestOverlayFrames, subscribeOverlayFrame } from "./overlayFrameLoop";
|
||||
|
||||
interface OffCanvasIndicatorRefreshOptions {
|
||||
@@ -101,7 +103,31 @@ export function startOffCanvasIndicatorRefresh(
|
||||
options.observedDocRef.current = doc;
|
||||
options.sigRef.current = "";
|
||||
};
|
||||
const update = () => {
|
||||
let stopped = false;
|
||||
let reading = false;
|
||||
// A sealed frame reports no mutations, so each due frame reads the frame again, one read at a time.
|
||||
const updateOverChannel = (iframe: HTMLIFrameElement, overlayEl: HTMLDivElement) => {
|
||||
const now = performance.now();
|
||||
if (reading || !rebuildDue(true, lastRecomputeAt, now)) return;
|
||||
lastRecomputeAt = now;
|
||||
reading = true;
|
||||
const comp = options.compRectRef.current;
|
||||
void measurePreviewOffCanvas(iframe, overlayEl, comp, options.activeCompositionPathRef.current)
|
||||
.then((read) => {
|
||||
if (!read || stopped || options.iframeRef.current !== iframe) return;
|
||||
publishOffCanvasRects(
|
||||
read.rects,
|
||||
read.elements,
|
||||
options.sigRef,
|
||||
options.elementsRef,
|
||||
options.setRects,
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
reading = false;
|
||||
});
|
||||
};
|
||||
const updateFromDocument = () => {
|
||||
const iframe = options.iframeRef.current;
|
||||
const overlayEl = options.overlayRef.current;
|
||||
const doc = iframe?.contentDocument ?? null;
|
||||
@@ -137,8 +163,15 @@ export function startOffCanvasIndicatorRefresh(
|
||||
walkCache,
|
||||
);
|
||||
};
|
||||
const update = () => {
|
||||
const iframe = options.iframeRef.current;
|
||||
const overlayEl = options.overlayRef.current;
|
||||
if (iframe && overlayEl && previewFrameOpaque(iframe)) updateOverChannel(iframe, overlayEl);
|
||||
else updateFromDocument();
|
||||
};
|
||||
const unsubscribe = subscribeOverlayFrame(update);
|
||||
return () => {
|
||||
stopped = true;
|
||||
unsubscribe();
|
||||
options.observerRef.current?.disconnect();
|
||||
options.observerRef.current = null;
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// Real Chrome: the off-canvas indicators a preview Studio cannot script (a sandboxed frame) gets are the ones a
|
||||
// same-origin preview gets, for an element past an edge, a turned one, a crop that keeps it inside, and one inside.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import type { Browser } from "puppeteer-core";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { closeTestChrome, launchTestChrome } from "../../../tests/chromeTestUtils";
|
||||
import { buildStudioBundle, openPreview, type Studio } from "../../../tests/sealedPreviewHarness";
|
||||
|
||||
vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 });
|
||||
const require = createRequire(import.meta.url);
|
||||
const MODES = process.env.HF_PARITY_MODE ? [process.env.HF_PARITY_MODE] : ["unsealed", "sealed"];
|
||||
let browser: Browser;
|
||||
let studioBundle: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
browser = await launchTestChrome();
|
||||
studioBundle = await buildStudioBundle([
|
||||
`export { startOffCanvasIndicatorRefresh } from "./components/editor/offCanvasIndicatorRefresh";`,
|
||||
]);
|
||||
});
|
||||
|
||||
afterAll(() => closeTestChrome(browser));
|
||||
|
||||
function previewHtml(): string {
|
||||
const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8");
|
||||
const clip = (id: string, track: number, style: string) =>
|
||||
`<div id="${id}" class="clip" data-start="0" data-duration="4" data-track-index="${track}" style="${style}"></div>`;
|
||||
return `<!doctype html><html><head><meta charset="UTF-8" />
|
||||
<meta name="hyperframes-studio-preview" content="1" />
|
||||
<style>html, body { margin: 0; width: 1920px; height: 1080px; overflow: hidden }
|
||||
.clip { position: absolute; width: 300px; height: 200px; background: #888 }</style></head><body>
|
||||
<main id="root" data-composition-id="main" data-start="0" data-duration="4" data-width="1920" data-height="1080">
|
||||
${clip("inside", 1, "left: 800px; top: 400px")}
|
||||
${clip("hangs-left", 2, "left: -150px; top: 100px")}
|
||||
${clip("turned", 3, "left: 1750px; top: 800px; transform: rotate(30deg)")}
|
||||
${clip("cropped", 4, "left: -200px; top: 600px; clip-path: inset(0 0 0 220px)")}
|
||||
</main>
|
||||
<script>${runtime}</script></body></html>`;
|
||||
}
|
||||
|
||||
type Shown = {
|
||||
key: string;
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
angle?: number;
|
||||
};
|
||||
|
||||
describe.each(MODES)("off-canvas indicators, %s preview", (mode) => {
|
||||
it("flags the elements that cross the composition edge, where they render", async () => {
|
||||
const { page } = await openPreview(browser, studioBundle, previewHtml(), mode);
|
||||
await page.evaluate(() => {
|
||||
const iframe = document.querySelector("iframe")!;
|
||||
const box = iframe.getBoundingClientRect();
|
||||
const overlay = document.createElement("div");
|
||||
overlay.style.cssText = `position: absolute; left: ${box.left}px; top: ${box.top}px; width: ${box.width}px; height: ${box.height}px; pointer-events: none`;
|
||||
document.body.append(overlay);
|
||||
const w = window as unknown as {
|
||||
hfStudio: Studio & { startOffCanvasIndicatorRefresh: (options: unknown) => () => void };
|
||||
__shown: unknown[];
|
||||
};
|
||||
w.__shown = [];
|
||||
const ref = <T>(current: T) => ({ current });
|
||||
// The overlay loop runs once Studio has seen the preview boot.
|
||||
w.hfStudio.usePlayerStore.setState({ previewBooted: true });
|
||||
w.hfStudio.startOffCanvasIndicatorRefresh({
|
||||
iframeRef: ref(iframe),
|
||||
overlayRef: ref(overlay),
|
||||
compRectRef: ref({ left: 0, top: 0, width: box.width, height: box.height }),
|
||||
activeCompositionPathRef: ref("index.html"),
|
||||
dirtyRef: ref(true),
|
||||
sigRef: ref(""),
|
||||
observerRef: ref(null),
|
||||
observedDocRef: ref(null),
|
||||
elementsRef: ref(new Map()),
|
||||
setRects: (rects: unknown[]) => {
|
||||
w.__shown = rects;
|
||||
},
|
||||
});
|
||||
});
|
||||
const shown = () => page.evaluate(() => (window as unknown as { __shown: Shown[] }).__shown);
|
||||
await expect.poll(async () => (await shown()).length, { timeout: 10_000 }).toBe(2);
|
||||
const rects = (await shown()).sort((a, b) => a.key.localeCompare(b.key));
|
||||
expect(rects.map((r) => r.key)).toEqual(["index.html:hangs-left:0", "index.html:turned:0"]);
|
||||
const [left, turned] = rects;
|
||||
expect(left).toMatchObject({ left: -150, top: 100, width: 300, height: 200 });
|
||||
expect(left!.angle ?? 0).toBeCloseTo(0, 3);
|
||||
expect(turned!.left).toBeCloseTo(1750, 1);
|
||||
expect(turned!.top).toBeCloseTo(800, 1);
|
||||
expect(turned!.width).toBeCloseTo(300, 1);
|
||||
expect(turned!.height).toBeCloseTo(200, 1);
|
||||
expect(turned!.angle).toBeCloseTo(30, 1);
|
||||
await page.close();
|
||||
});
|
||||
});
|
||||
@@ -101,6 +101,24 @@ async function allPreviewLayers(iframe: HTMLIFrameElement): Promise<EditingLayer
|
||||
return layers;
|
||||
}
|
||||
|
||||
export async function collectAllPreviewLayerItems(
|
||||
iframe: HTMLIFrameElement,
|
||||
activeCompositionPath: string | null,
|
||||
): Promise<DomEditLayerItem[] | null> {
|
||||
const layers = await allPreviewLayers(iframe);
|
||||
const described =
|
||||
layers &&
|
||||
(await describeAll(
|
||||
iframe,
|
||||
layers.map((layer) => layer.handle),
|
||||
));
|
||||
if (!layers || !described) return null;
|
||||
return layers.flatMap((layer, index) => {
|
||||
const element = described[index];
|
||||
return element ? [layerItem(iframe, layer, element, activeCompositionPath)] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** `getFamily` for a stand-in, read from its frame; null when the frame cannot say. */
|
||||
export async function previewStackingFamily(
|
||||
iframe: HTMLIFrameElement,
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/** Off-canvas indicators for a preview frame Studio cannot script, from its runtime's layers and geometry. */
|
||||
import {
|
||||
MAX_DESCRIBE_HANDLES,
|
||||
type EditingElementGeometry,
|
||||
} from "@hyperframes/core/runtime/editing-port";
|
||||
import { describePreviewElements, previewGeometry } from "../../player/lib/previewElements";
|
||||
import type { OffCanvasRect } from "./OffCanvasIndicators";
|
||||
import { computeOverlayRootScale } from "./domEditOverlayBasis";
|
||||
import { resolveDomEditSelection } from "./domEditingLayers";
|
||||
import type { DomEditSelection } from "./domEditingTypes";
|
||||
import { hugRectForClipPath } from "./domEditOverlayCrop";
|
||||
import { extendsOutside } from "./offCanvasIndicatorGeometry";
|
||||
import { groupAwareRect } from "./previewOverlayRects";
|
||||
import { collectAllPreviewLayerItems } from "./previewLayers";
|
||||
import {
|
||||
resolvePreviewSelection,
|
||||
standInHandle,
|
||||
type PreviewSelectionOptions,
|
||||
} from "./previewSelection";
|
||||
|
||||
async function geometryOf(iframe: HTMLIFrameElement, handles: string[]) {
|
||||
const boxes: Array<EditingElementGeometry | null> = [];
|
||||
for (let at = 0; at < handles.length; at += MAX_DESCRIBE_HANDLES) {
|
||||
const reply = await previewGeometry(iframe, handles.slice(at, at + MAX_DESCRIBE_HANDLES));
|
||||
if (!reply) return null;
|
||||
boxes.push(...reply.elements);
|
||||
}
|
||||
return boxes;
|
||||
}
|
||||
|
||||
/** `recomputeOffCanvasIndicators` over the frame's runtime; null when the frame cannot answer. */
|
||||
export async function measurePreviewOffCanvas(
|
||||
iframe: HTMLIFrameElement,
|
||||
overlay: HTMLDivElement,
|
||||
comp: { left: number; top: number; width: number; height: number },
|
||||
activeCompositionPath: string | null,
|
||||
): Promise<{ rects: OffCanvasRect[]; elements: Map<string, HTMLElement> } | null> {
|
||||
const rects: OffCanvasRect[] = [];
|
||||
const elements = new Map<string, HTMLElement>();
|
||||
if (comp.width <= 0) return { rects, elements };
|
||||
const items = await collectAllPreviewLayerItems(iframe, activeCompositionPath ?? "index.html");
|
||||
const boxes =
|
||||
items &&
|
||||
(await geometryOf(
|
||||
iframe,
|
||||
items.map((item) => item.preview!.handle),
|
||||
));
|
||||
const scale = boxes && computeOverlayRootScale(overlay, iframe, null);
|
||||
if (!items || !boxes || !scale) return null;
|
||||
items.forEach((item, index) => {
|
||||
const box = boxes[index];
|
||||
if (!box?.visible) return;
|
||||
// As the same-origin read: a group by its members' union, then hugged to its crop.
|
||||
const base = groupAwareRect(scale, box, true);
|
||||
const r = { ...base, ...hugRectForClipPath(base, box.clipPath) };
|
||||
if (!extendsOutside(r, comp)) return;
|
||||
rects.push({
|
||||
key: item.key,
|
||||
left: r.left,
|
||||
top: r.top,
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
angle: r.angle,
|
||||
});
|
||||
elements.set(item.key, item.element);
|
||||
});
|
||||
return { rects, elements };
|
||||
}
|
||||
|
||||
/** The selection a click on an indicator makes; a sealed frame's stand-in resolves through the frame. */
|
||||
export async function resolveIndicatorSelection(
|
||||
iframe: HTMLIFrameElement | null,
|
||||
element: HTMLElement,
|
||||
options: PreviewSelectionOptions,
|
||||
): Promise<DomEditSelection | null> {
|
||||
const handle = standInHandle(element);
|
||||
if (!handle || !iframe) return resolveDomEditSelection(element, options);
|
||||
const [described] = (await describePreviewElements(iframe, [handle])) ?? [];
|
||||
return described ? resolvePreviewSelection(iframe, described, options) : null;
|
||||
}
|
||||
@@ -20,6 +20,7 @@ export type Studio = typeof import("../src/utils/gsapSoftReload") & {
|
||||
markStudioWriteToken: typeof import("../src/utils/studioFileVersion").markStudioWriteToken;
|
||||
studioFileRevision: typeof import("../src/utils/studioFileVersion").studioFileRevision;
|
||||
previewLoadShows: typeof import("../src/utils/sealedPreviewLedger").previewLoadShows;
|
||||
watchPreviewFrame: typeof import("../src/player/lib/bridgePlayback").watchPreviewFrame;
|
||||
};
|
||||
|
||||
/** Studio's preview code, bundled for the page as `window.hfStudio`; `extra` adds export lines. */
|
||||
@@ -36,6 +37,7 @@ export async function buildStudioBundle(extra: string[] = []): Promise<string> {
|
||||
`export { usePlayerStore } from "./player/store/playerStore";`,
|
||||
`export { markStudioWriteToken, studioFileRevision } from "./utils/studioFileVersion";`,
|
||||
`export { previewLoadShows } from "./utils/sealedPreviewLedger";`,
|
||||
`export { watchPreviewFrame } from "./player/lib/bridgePlayback";`,
|
||||
...extra,
|
||||
].join(" "),
|
||||
resolveDir: fileURLToPath(new URL("../src", import.meta.url)),
|
||||
@@ -170,6 +172,8 @@ export async function openPreview(
|
||||
iframe.style.cssText = "width: 1920px; height: 1080px; border: 0";
|
||||
iframe.srcdoc = srcdoc;
|
||||
document.body.append(iframe);
|
||||
// As Studio's player does, before the frame loads: the frame's posted size reaches the mirror.
|
||||
(window as unknown as { hfStudio: Studio }).hfStudio.watchPreviewFrame(iframe);
|
||||
},
|
||||
html,
|
||||
mode === "sealed",
|
||||
|
||||
Reference in New Issue
Block a user