From e8ac313ed017a4195828c4e5758b5a0f77df677b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 10:05:19 +0000 Subject: [PATCH] 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 --- .../src/components/editor/DomEditOverlay.tsx | 1 + .../editor/OffCanvasIndicators.test.tsx | 1 + .../components/editor/OffCanvasIndicators.tsx | 9 +- .../editor/offCanvasIndicatorGeometry.ts | 15 ++- .../editor/offCanvasIndicatorRefresh.ts | 37 ++++++- .../offCanvasIndicators.browser.test.ts | 97 +++++++++++++++++++ .../src/components/editor/previewLayers.ts | 18 ++++ .../src/components/editor/previewOffCanvas.ts | 80 +++++++++++++++ packages/studio/tests/sealedPreviewHarness.ts | 4 + 9 files changed, 255 insertions(+), 7 deletions(-) create mode 100644 packages/studio/src/components/editor/offCanvasIndicators.browser.test.ts create mode 100644 packages/studio/src/components/editor/previewOffCanvas.ts diff --git a/packages/studio/src/components/editor/DomEditOverlay.tsx b/packages/studio/src/components/editor/DomEditOverlay.tsx index a54a892db2..913e6ca342 100644 --- a/packages/studio/src/components/editor/DomEditOverlay.tsx +++ b/packages/studio/src/components/editor/DomEditOverlay.tsx @@ -556,6 +556,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({ groupSelections={groupSelections} activeCompositionPathRef={activeCompositionPathRef} onSelectionChangeRef={onSelectionChangeRef} + iframeRef={iframeRef} /> {contextMenu && ( diff --git a/packages/studio/src/components/editor/OffCanvasIndicators.test.tsx b/packages/studio/src/components/editor/OffCanvasIndicators.test.tsx index 159528aff4..7a05902dc0 100644 --- a/packages/studio/src/components/editor/OffCanvasIndicators.test.tsx +++ b/packages/studio/src/components/editor/OffCanvasIndicators.test.tsx @@ -21,6 +21,7 @@ it("rotates an off-canvas indicator with its element", () => { groupSelections={[]} activeCompositionPathRef={{ current: null }} onSelectionChangeRef={{ current: () => undefined }} + iframeRef={{ current: null }} />, ); }); diff --git a/packages/studio/src/components/editor/OffCanvasIndicators.tsx b/packages/studio/src/components/editor/OffCanvasIndicators.tsx index a24be76372..689683c49a 100644 --- a/packages/studio/src/components/editor/OffCanvasIndicators.tsx +++ b/packages/studio/src/components/editor/OffCanvasIndicators.tsx @@ -20,6 +20,7 @@ interface OffCanvasIndicatorsProps { onSelectionChangeRef: React.MutableRefObject< (selection: DomEditSelection, options?: { revealPanel?: boolean; additive?: boolean }) => void >; + iframeRef: React.RefObject; } 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) => { diff --git a/packages/studio/src/components/editor/offCanvasIndicatorGeometry.ts b/packages/studio/src/components/editor/offCanvasIndicatorGeometry.ts index 806342f3a8..105db2ea20 100644 --- a/packages/studio/src/components/editor/offCanvasIndicatorGeometry.ts +++ b/packages/studio/src/components/editor/offCanvasIndicatorGeometry.ts @@ -21,7 +21,7 @@ function offCanvasSignature(rects: OffCanvasRect[]): string { .join("|"); } -function extendsOutside( +export function extendsOutside( rect: Omit, 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, + sigRef: React.MutableRefObject, + elementsRef: React.MutableRefObject>, + 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); } diff --git a/packages/studio/src/components/editor/offCanvasIndicatorRefresh.ts b/packages/studio/src/components/editor/offCanvasIndicatorRefresh.ts index 6bf169c148..e7b9b31d95 100644 --- a/packages/studio/src/components/editor/offCanvasIndicatorRefresh.ts +++ b/packages/studio/src/components/editor/offCanvasIndicatorRefresh.ts @@ -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; diff --git a/packages/studio/src/components/editor/offCanvasIndicators.browser.test.ts b/packages/studio/src/components/editor/offCanvasIndicators.browser.test.ts new file mode 100644 index 0000000000..918c924418 --- /dev/null +++ b/packages/studio/src/components/editor/offCanvasIndicators.browser.test.ts @@ -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) => + `
`; + return ` + + +
+ ${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)")} +
+ `; +} + +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 = (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(); + }); +}); diff --git a/packages/studio/src/components/editor/previewLayers.ts b/packages/studio/src/components/editor/previewLayers.ts index 19247f2048..c9fdf5e6c8 100644 --- a/packages/studio/src/components/editor/previewLayers.ts +++ b/packages/studio/src/components/editor/previewLayers.ts @@ -101,6 +101,24 @@ async function allPreviewLayers(iframe: HTMLIFrameElement): Promise { + 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, diff --git a/packages/studio/src/components/editor/previewOffCanvas.ts b/packages/studio/src/components/editor/previewOffCanvas.ts new file mode 100644 index 0000000000..fdac33e883 --- /dev/null +++ b/packages/studio/src/components/editor/previewOffCanvas.ts @@ -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 = []; + 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 } | null> { + const rects: OffCanvasRect[] = []; + const elements = new Map(); + 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 { + const handle = standInHandle(element); + if (!handle || !iframe) return resolveDomEditSelection(element, options); + const [described] = (await describePreviewElements(iframe, [handle])) ?? []; + return described ? resolvePreviewSelection(iframe, described, options) : null; +} diff --git a/packages/studio/tests/sealedPreviewHarness.ts b/packages/studio/tests/sealedPreviewHarness.ts index 9e0663a7f5..39a44d8952 100644 --- a/packages/studio/tests/sealedPreviewHarness.ts +++ b/packages/studio/tests/sealedPreviewHarness.ts @@ -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 { `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",