fix(core): a film without a declared size reports its measured size to a sealed Studio (#8578)

* fix(core): a film without a declared size reports its measured size to a sealed Studio

* fix(studio): say why a sealed press or nudge can't move a layer when the frame never answers

* refactor(studio): split the sealed press and nudge replies so each says why it didn't start
This commit is contained in:
Miguel Ángel
2026-11-23 19:57:39 +00:00
committed by GitHub
parent d3c16bbe98
commit 19f98a3ed7
11 changed files with 271 additions and 45 deletions
+71
View File
@@ -919,6 +919,77 @@ describe("initSandboxRuntimeModular", () => {
expect(clip.style.height).toBe("0.5px");
});
// fails without the fix: a root with no declared size posted no stage size at all, so a sealed Studio, which can't
// measure the frame itself, had no scale for its overlay.
describe("a root that declares no size", () => {
const capture = () => {
const outbound: Array<Record<string, unknown>> = [];
vi.spyOn(window.parent, "postMessage").mockImplementation((message: unknown) => {
if (typeof message === "object" && message !== null)
outbound.push(message as Record<string, unknown>);
});
return () => outbound.filter((m) => m.type === "stage-size");
};
const mountUndeclared = (width: number, height: number) => {
document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-duration="4"></div>`;
const root = document.querySelector<HTMLElement>("[data-composition-id]")!;
Object.defineProperty(root, "offsetWidth", { value: width, configurable: true });
Object.defineProperty(root, "offsetHeight", { value: height, configurable: true });
window.__timelines = { main: createMockTimeline(4) };
return root;
};
it("posts its measured layout box as measuredSize, with no width or height a host would size by", () => {
const sent = capture();
mountUndeclared(1280, 720);
initSandboxRuntimeModular();
expect(sent().length).toBeGreaterThan(0);
for (const message of sent()) {
expect(message.measuredSize).toEqual({ width: 1280, height: 720 });
expect(message).not.toHaveProperty("width");
expect(message).not.toHaveProperty("height");
}
});
it("posts the box again when the root resizes, and stops at teardown", () => {
let resized: (() => void) | null = null;
const disconnect = vi.fn();
vi.stubGlobal(
"ResizeObserver",
class {
constructor(callback: () => void) {
resized = callback;
}
observe() {}
disconnect() {
disconnect();
}
},
);
try {
const sent = capture();
const root = mountUndeclared(1280, 720);
initSandboxRuntimeModular();
Object.defineProperty(root, "offsetWidth", { value: 640, configurable: true });
resized!();
expect(sent().at(-1)?.measuredSize).toEqual({ width: 640, height: 720 });
window.__hfRuntimeTeardown?.();
expect(disconnect).toHaveBeenCalled();
} finally {
vi.unstubAllGlobals();
}
});
it("leaves measuredSize off a root that declares its size", () => {
const sent = capture();
document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-duration="4" data-width="1920" data-height="1080"></div>`;
window.__timelines = { main: createMockTimeline(4) };
initSandboxRuntimeModular();
expect(sent().length).toBeGreaterThan(0);
for (const message of sent()) expect(message).not.toHaveProperty("measuredSize");
});
});
it("reports the explicit root's size when another composition comes first", () => {
const outbound: Array<Record<string, unknown>> = [];
vi.spyOn(window.parent, "postMessage").mockImplementation((message: unknown) => {
+20 -7
View File
@@ -4138,18 +4138,29 @@ export function initSandboxRuntimeModular(): void {
),
);
};
let measuredRootObserver: ResizeObserver | null = null;
const postStageSize = () => {
const root = resolveRootCompositionElement();
if (!root) return;
const { width, height } = readCompositionSize(root);
if (width !== null && height !== null) {
postRuntimeMessage({ source: "hf-preview", type: "stage-size", width, height });
return;
}
if (!measuredRootObserver && typeof ResizeObserver !== "undefined") {
measuredRootObserver = new ResizeObserver(postStageSize);
measuredRootObserver.observe(root);
}
const measuredSize = { width: root.offsetWidth, height: root.offsetHeight };
if (measuredSize.width > 0 && measuredSize.height > 0)
postRuntimeMessage({ source: "hf-preview", type: "stage-size", measuredSize });
};
const postTimeline = () => {
sanitizeCompositionDurationAttributes();
applyCompositionSizing();
applyClipLayout();
// Post resolved stage size so the parent can scale the iframe container
const stageSizeRootEl = resolveRootCompositionElement();
if (stageSizeRootEl) {
const { width, height } = readCompositionSize(stageSizeRootEl);
if (width !== null && height !== null) {
postRuntimeMessage({ source: "hf-preview", type: "stage-size", width, height });
}
}
postStageSize();
bindRootTimelineIfAvailable();
timelinePostHeld = clock.isPlaying();
if (timelinePostHeld) {
@@ -6969,6 +6980,8 @@ export function initSandboxRuntimeModular(): void {
const teardown = () => {
if (state.tornDown) return;
state.tornDown = true;
measuredRootObserver?.disconnect();
measuredRootObserver = null;
previewSeek?.cancel();
cancelTransportTick();
document.removeEventListener("visibilitychange", onTransportVisibilityChange);
+3 -6
View File
@@ -178,12 +178,9 @@ export type RuntimeStaticCompositionMessage = {
height: number | null;
};
export type RuntimeStageSizeMessage = {
source: "hf-preview";
type: "stage-size";
width: number;
height: number;
};
export type RuntimeStageSizeMessage =
| { source: "hf-preview"; type: "stage-size"; width: number; height: number }
| { source: "hf-preview"; type: "stage-size"; measuredSize: { width: number; height: number } };
/**
* Fired once per session when the runtime's attempt to play a timed media
@@ -43,6 +43,23 @@ const stageSizeEvent = (width: unknown, height: unknown, source: object): Messag
}) as unknown as MessageEvent;
describe("handleRuntimeMessage stage-size", () => {
it("leaves the frame's size alone for a root's measured box, which follows the frame", () => {
const frameWindow = {} as Window;
const callbacks = makeCallbacks();
const measured = {
source: frameWindow,
data: {
source: "hf-preview",
type: "stage-size",
measuredSize: { width: 1280, height: 720 },
},
} as unknown as MessageEvent;
handleRuntimeMessage(measured, frameWindow, callbacks);
expect(callbacks.setCompositionSize).not.toHaveBeenCalled();
});
it("applies a finite positive stage size", () => {
const frameWindow = {} as Window;
const callbacks = makeCallbacks();
@@ -16,10 +16,14 @@ import {
restoreManualOffsetDragMembers,
} from "./manualOffsetDrag";
import {
askShownGestureStarts,
gestureStartLayout,
measurePreviewGestureStart,
UNANSWERED,
unansweredMoveReason,
type PreviewGestureStart,
} from "./previewGestureStartRead";
import { computeOverlayRootScale } from "./domEditOverlayBasis";
import { standInFor } from "./previewSelection";
import { collectSnapContext } from "./snapTargetCollection";
import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers";
@@ -130,6 +134,62 @@ function gsapHoldsCard(tweens: unknown[] = []) {
});
}
/** An opaque frame whose runtime hasn't posted a size yet; `post` sends one. */
function unsizedOpaqueFrame() {
const { iframe: sealed, frame } = sealedPreviewFrame();
const iframe = sized(sealed, [100, 50, 960, 540]) as HTMLIFrameElement;
watchPreviewFrame(iframe);
const post = (data: Record<string, unknown>) =>
window.dispatchEvent(
new MessageEvent("message", {
source: frame as unknown as Window,
origin: window.location.origin,
data: { source: "hf-preview", type: "stage-size", ...data },
}),
);
return { iframe, post };
}
// fails without the fix: a sealed frame whose root declares no size never had a stage size, so the overlay had no
// scale, and a press or nudge read gave up at once and was dropped.
describe("an opaque frame whose root declares no size", () => {
it("scales the overlay by the root's measured box, as the unsealed overlay measures the root", () => {
const { iframe, post } = unsizedOpaqueFrame();
post({ measuredSize: { width: 1280, height: 720 } });
const doc = document.implementation.createHTMLDocument("");
doc.body.innerHTML = `<div data-composition-id="main"></div>`;
sized(doc.querySelector("[data-composition-id]")!, [0, 0, 1280, 720]);
const scale = (frame: HTMLIFrameElement, read: Document | null) => {
const basis = computeOverlayRootScale(overlayEl(), frame, read);
return basis && [basis.rootScaleX, basis.rootScaleY];
};
expect(scale(iframe, null)).toEqual([0.75, 0.75]);
expect(scale(iframe, null)).toEqual(scale(liveFrame(), doc));
});
it("tells a frame that answered without a size from one that never answered", () => {
const silent = unsizedOpaqueFrame();
expect(unansweredMoveReason(silent.iframe)).toBe(
"The preview didn't answer, so Studio can't move this layer. Try again.",
);
const sizeless = unsizedOpaqueFrame();
sizeless.post({ type: "timeline", durationSeconds: 4 });
expect(unansweredMoveReason(sizeless.iframe)).toBe(
"This composition has no size, so Studio can't move its layers. Give its root a width and height.",
);
});
it("waits for the frame's size before reading a press, instead of giving up", async () => {
const { iframe, post } = unsizedOpaqueFrame();
const card = makeSelection("Card", document.getElementById("card")!);
const read = askShownGestureStarts(iframe, overlayEl(), "index.html", [card]);
await new Promise((resolve) => setTimeout(resolve, 50));
post({ measuredSize: { width: 1920, height: 1080 } });
const answer = await read;
expect(answer !== UNANSWERED && answer?.shown.length).toBe(1);
});
});
describe("a gesture's start on an opaque frame", () => {
it("reads the snap targets a scriptable frame collects, without the pressed element", async () => {
const overlay = overlayEl();
@@ -1,6 +1,7 @@
/** A gesture on a frame Studio cannot script starts from one `gesture-start` read (core `editingGestureStart.ts`). */
import type { EditingGestureStart } from "@hyperframes/core/runtime/editing-port";
import { previewGestureStart } from "../../player/lib/previewElements";
import { previewRootHasNoSize, whenPreviewStageSized } from "../../player/lib/bridgePlayback";
import { computeOverlayRootScale } from "./domEditOverlayBasis";
import type { DomEditSelection } from "./domEditing";
import type { CropFrameStart } from "./domEditOverlayCrop";
@@ -95,18 +96,13 @@ export async function measurePreviewGestureStart(
export type Shown = { selection: DomEditSelection; rect: OverlayRect; start?: PreviewGestureStart };
export type OverChannel = { shown: Shown[]; snap?: SnapContext };
/** An opaque frame's `selections` on the page it shows now and what a gesture on them starts from. */
export async function readShownGestureStarts(
iframe: HTMLIFrameElement,
overlay: HTMLDivElement | null,
path: string | null,
selections: DomEditSelection[],
): Promise<OverChannel | null> {
const answer = await askShownGestureStarts(iframe, overlay, path, selections);
return answer === UNANSWERED ? null : answer;
}
export const UNANSWERED = "unanswered";
export const PRESS_WAIT_MAX_MS = 10_000;
export const unansweredMoveReason = (iframe: HTMLIFrameElement) =>
previewRootHasNoSize(iframe)
? "This composition has no size, so Studio can't move its layers. Give its root a width and height."
: "The preview didn't answer, so Studio can't move this layer. Try again.";
export async function askShownGestureStarts(
iframe: HTMLIFrameElement,
@@ -120,6 +116,7 @@ export async function askShownGestureStarts(
if (found.includes(undefined)) return UNANSWERED;
const handles = found.map((element) => element?.handle);
if (!overlay || !handles.length || !handles.every(Boolean)) return null;
await whenPreviewStageSized(iframe, PRESS_WAIT_MAX_MS);
const read = await measurePreviewGestureStart(iframe, overlay, handles as string[]);
if (!read) return UNANSWERED;
const shown = selections.flatMap((selection, i) => {
@@ -24,7 +24,9 @@ import { previewFrameOpaque } from "../../player/lib/previewChannel";
import { pressOutlineOf } from "./pressOutline";
import {
askShownGestureStarts,
PRESS_WAIT_MAX_MS,
UNANSWERED,
unansweredMoveReason,
type OverChannel,
type Shown,
} from "./previewGestureStartRead";
@@ -37,7 +39,7 @@ type ShownStart = (
) => boolean;
const MAX_SETTLED_WAIT_FRAMES = 60;
export const PRESS_WAIT_MAX_MS = 10_000;
export { PRESS_WAIT_MAX_MS };
export function createPreviewGestureStarts(
opts: UseDomEditOverlayGesturesOptions,
@@ -238,8 +240,9 @@ export function createPreviewGestureStarts(
return;
}
endWaitingPress(press, !!channel);
const replayed = replay(startsFrom(step));
outline.replayEnded(replayed && channel ? opts.iframeRef.current : null);
const read = startsFrom(step);
if (read === false) sayWhyNotStarted(step);
outline.replayEnded(replay(read) && channel ? opts.iframeRef.current : null);
};
const replay = (read: ReturnType<typeof startsFrom>): boolean => {
const pointerDown = down as unknown as React.PointerEvent<HTMLElement>;
@@ -248,6 +251,11 @@ export function createPreviewGestureStarts(
if (press.released) releaseActiveGesture(press.released);
return true;
};
const sayWhyNotStarted = (step: "lost" | "run" | "drawn") => {
const pressed = opts.selectionRef.current;
if (step === "drawn" && channel && pressed)
opts.onBlockedMoveRef.current(pressed, unansweredMoveReason(channel));
};
press.frame = requestAnimationFrame(poll);
return true;
};
@@ -431,6 +431,7 @@ describe("a press held across a preview change on an opaque frame", () => {
selectionRef: { current: selection },
overlayRectRef: { current: overlayRect },
setOverlayRect: vi.fn((rect: OverlayRect | null) => (opts.overlayRectRef.current = rect)),
onBlockedMoveRef: { current: vi.fn() },
} as unknown as UseDomEditOverlayGesturesOptions;
const starts = createPreviewGestureStarts(opts, vi.fn(), vi.fn());
const down = {
@@ -642,6 +643,20 @@ describe("a press held across a preview change on an opaque frame", () => {
expect(standInHandle(started.selection.element)).toBe(started.selection.handle);
});
// fails without the fix: a press the frame never answered, with no box drawn to start from, ended with nothing.
it("says the preview didn't answer when it never does and no box was drawn", async () => {
const turned = makeSelection("turned", document.getElementById("turned")!);
const { opts } = await pressDuringChange(turned, { iframe: silentFrame() });
await vi.waitFor(() => expect(opts.onBlockedMoveRef.current).toHaveBeenCalledOnce(), {
timeout: 3000,
});
expect(press.start).not.toHaveBeenCalled();
expect(opts.onBlockedMoveRef.current).toHaveBeenCalledWith(
turned,
"The preview didn't answer, so Studio can't move this layer. Try again.",
);
});
it("starts from the box Studio drew when the frame shown never answers", async () => {
const turned = makeSelection("turned", document.getElementById("turned")!);
const drawn = { left: 1, top: 2, width: 3, height: 4 } as OverlayRect;
@@ -10,14 +10,14 @@ import type { WaitingPressState } from "./domEditOverlayGestures";
import type { OverChannel, Shown } from "./previewGestureStartRead";
import { useDomEditNudge } from "./useDomEditNudge";
const { readShownGestureStarts } = vi.hoisted(() => ({ readShownGestureStarts: vi.fn() }));
const { askShownGestureStarts } = vi.hoisted(() => ({ askShownGestureStarts: vi.fn() }));
vi.mock("../../player/lib/previewChannel", async (importOriginal) => ({
...(await importOriginal<typeof import("../../player/lib/previewChannel")>()),
previewFrameOpaque: () => true,
}));
vi.mock("./previewGestureStartRead", async (importOriginal) => ({
...(await importOriginal<typeof import("./previewGestureStartRead")>()),
readShownGestureStarts,
askShownGestureStarts,
}));
installReactActEnvironment();
@@ -35,11 +35,13 @@ function Harness({
selection,
flush,
pressing = ref(null),
onBlocked = () => {},
}: {
commit: () => Promise<unknown>;
selection: ReturnType<typeof sealed>;
flush?: { current: () => void };
pressing?: { current: WaitingPressState | null };
onBlocked?: (selection: unknown, reason?: string) => void;
}) {
const { flushNudge } = useDomEditNudge({
selection,
@@ -56,7 +58,7 @@ function Harness({
blockedMoveRef: ref(null),
waitingPressRef: pressing,
onManualDragStartRef: ref(() => {}),
onBlockedMoveRef: ref(() => {}),
onBlockedMoveRef: ref(onBlocked),
onPathOffsetCommitRef: ref(commit),
onGroupPathOffsetCommitRef: ref(async () => {}),
});
@@ -70,11 +72,11 @@ const arrowRight = () =>
/** Each frame read waits until the test answers it, in any order. */
function heldReads() {
const answers: ((read: OverChannel) => void)[] = [];
readShownGestureStarts.mockImplementation(
askShownGestureStarts.mockImplementation(
() => new Promise<OverChannel>((resolve) => answers.push(resolve)),
);
return async (i: number) => {
const [, , , [selection]] = readShownGestureStarts.mock.calls[i]!;
const [, , , [selection]] = askShownGestureStarts.mock.calls[i]!;
const shown: Shown = {
selection,
rect: RECT,
@@ -103,7 +105,7 @@ function mount(props: React.ComponentProps<typeof Harness>) {
beforeEach(() => {
vi.useFakeTimers();
__resetForTests();
readShownGestureStarts.mockReset();
askShownGestureStarts.mockReset();
dot = sealed("Dot", "e1");
});
afterEach(() => {
@@ -125,7 +127,7 @@ it("moves a sealed element GSAP animates by its tween, counting the keys pressed
await answer(0);
act(() => vi.advanceTimersByTime(CANVAS_NUDGE_COMMIT_DEBOUNCE_MS));
expect(readShownGestureStarts).toHaveBeenCalledOnce();
expect(askShownGestureStarts).toHaveBeenCalledOnce();
expect(commit).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ handle: "e1" }),
{ x: 3, y: 0 },
@@ -205,7 +207,7 @@ it("asks the frame nothing for an arrow pressed while a canvas press waits, and
mount({ commit, selection: dot, pressing });
act(() => arrowRight());
expect(readShownGestureStarts).not.toHaveBeenCalled();
expect(askShownGestureStarts).not.toHaveBeenCalled();
pressing.current = null;
act(() => arrowRight());
@@ -217,3 +219,16 @@ it("asks the frame nothing for an arrow pressed while a canvas press waits, and
{ plainTranslate: false },
);
});
// fails without the fix: a nudge the frame never answered was dropped without a word.
it("says the preview didn't answer when a sealed nudge's read never does", async () => {
askShownGestureStarts.mockResolvedValue("unanswered");
const onBlocked = vi.fn();
mount({ commit: vi.fn(async () => {}), selection: dot, onBlocked });
act(() => void arrowRight());
await settle();
expect(onBlocked).toHaveBeenCalledWith(
expect.objectContaining({ handle: "e1" }),
"The preview didn't answer, so Studio can't move this layer. Try again.",
);
});
@@ -45,7 +45,12 @@ import {
} from "./domEditNudge";
import { selectionElementLive } from "./previewSelection";
import { previewFrameOpaque } from "../../player/lib/previewChannel";
import { readShownGestureStarts, type PreviewGestureStart } from "./previewGestureStartRead";
import {
askShownGestureStarts,
UNANSWERED,
unansweredMoveReason,
type PreviewGestureStart,
} from "./previewGestureStartRead";
interface NudgeSession {
members: ManualOffsetDragMember[];
@@ -281,22 +286,27 @@ export function useDomEditNudge(params: UseDomEditNudgeParams): { flushNudge: ()
if (!iframe || !found) return null;
const selections = found.targets.map((target) => target.selection);
const read: SealedStartRead = { accum: { x: 0, y: 0 }, dropped: false };
void readShownGestureStarts(
void askShownGestureStarts(
iframe,
p.overlayRef.current,
p.activeCompositionPathRef.current,
selections,
)
.catch(() => null)
.then((shown) => {
.then((answer) => {
if (readingRef.current === read) readingRef.current = null;
if (read.dropped || !shown) return;
const targets = found.targets.map((target, i) => ({ ...target, ...shown.shown[i] }));
const session = beginSession({ targets, isGroup: found.isGroup }, false);
if (!session || session === "refused") return;
session.accum = read.accum;
startBurst(session);
if (!read.dropped) startFrom(answer);
});
const startFrom = (answer: Awaited<ReturnType<typeof askShownGestureStarts>> | null) => {
if (answer === UNANSWERED && selections[0])
p.onBlockedMoveRef.current(selections[0], unansweredMoveReason(iframe));
if (!answer || answer === UNANSWERED) return;
const targets = found.targets.map((target, i) => ({ ...target, ...answer.shown[i] }));
const session = beginSession({ targets, isGroup: found.isGroup }, false);
if (!session || session === "refused") return;
session.accum = read.accum;
startBurst(session);
};
return read;
};
@@ -17,6 +17,7 @@ interface PlaybackMirror {
stageSize: { width: number; height: number } | null;
/** The paused time the runtime last said it shows. */
shown: number | null;
timelinePosted: boolean;
}
const SEEK_CONFIRM_MS = 500;
@@ -40,6 +41,7 @@ function mirrorOf(iframe: HTMLIFrameElement): PlaybackMirror | null {
seekUntil: 0,
stageSize: null,
shown: null,
timelinePosted: false,
};
mirrors.set(frame, mirror);
}
@@ -60,6 +62,25 @@ export function previewStageSize(
return (frame && mirrors.get(frame)?.stageSize) ?? null;
}
/** The runtime answered with its timeline but never a size: its root measures 0x0 or isn't laid out. */
export function previewRootHasNoSize(iframe: HTMLIFrameElement): boolean {
const frame = iframe.contentWindow;
const mirror = frame ? mirrors.get(frame) : undefined;
return !!mirror?.timelinePosted && !mirror.stageSize;
}
/** Resolves once the frame's runtime has posted its size, or after `maxMs` without one. */
export function whenPreviewStageSized(iframe: HTMLIFrameElement, maxMs: number): Promise<void> {
const until = performance.now() + maxMs;
return new Promise((resolve) => {
const check = () => {
if (previewStageSize(iframe) || performance.now() >= until) resolve();
else requestAnimationFrame(check);
};
check();
});
}
/** The origins a post from this frame can carry; a page its server sandboxed posts as `null` without the attribute. */
export function frameOrigins(iframe: HTMLIFrameElement): string[] {
const sandbox = iframe.getAttribute("sandbox")?.toLowerCase().split(/\s+/);
@@ -131,10 +152,12 @@ export function onFrameShowsTime(listener: (iframe: HTMLIFrameElement) => void):
function mirrorPost(mirror: PlaybackMirror, message: Record<string, unknown>, fps: number | null) {
if (message.type === "timeline" && finiteAtLeastZero(message.durationSeconds)) {
mirror.duration = message.durationSeconds;
mirror.timelinePosted = true;
} else if (message.type === "state" && finiteAtLeastZero(message.currentTime)) {
mirrorState(mirror, message.currentTime, message.isPlaying === true, fps);
} else if (message.type === "stage-size") {
const { width, height } = message;
const measured = message.measuredSize as Record<string, unknown> | undefined;
const { width, height } = measured ?? message;
if (finitePositive(width) && finitePositive(height)) mirror.stageSize = { width, height };
}
}