fix(studio): a reload waits for a drag to end in a sealed preview (#8164)

* fix(studio): a scene edit swaps in place and a far scene mounts for selection in a sealed preview

* test(studio): a sealed undo that reloads marks its scenes stale first

* fix(studio): a timing drag moves the animation in place in a sealed preview

* fix(studio): a sealed timing drag moves the clip's window and the film length with its tweens

* test(studio): the sealed retime test checks both requests were sent before comparing them

* refactor(studio): the sealed live retime code passes the quality audit

* style(core): format the sealed live retime parser

* fix(studio): a reload waits for a drag to end in a sealed preview

* refactor(studio): manual edit gesture tracking lives in its own module
This commit is contained in:
Miguel Ángel
2026-11-20 20:13:38 +00:00
committed by GitHub
parent d3d3350d41
commit aa05198583
18 changed files with 190 additions and 107 deletions
@@ -35,7 +35,7 @@ import { CanvasContextMenu } from "./CanvasContextMenu";
import { useInlineTextEditing } from "./useInlineTextEditing";
import { usePreviewReadOnly } from "./previewReadOnlyContext";
import { useMountEffect } from "../../hooks/useMountEffect";
import { countStudioManualEditSave as counted } from "./manualEditsDom";
import { countStudioManualEditSave as counted } from "./manualEditGesture";
import type { ZOrderAction, ZOrderPatch } from "./canvasContextMenuZOrder";
import { getPreviewTargetFromPointer } from "../../utils/studioPreviewHelpers";
import { pointerMayHitElement } from "./previewSelection";
@@ -4,7 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { DomEditSelection } from "./domEditingTypes";
import type { DomEditGroupPathOffsetCommit } from "./domEditOverlayGestures";
import { STUDIO_OFFSET_X_PROP, STUDIO_OFFSET_Y_PROP } from "./manualEdits";
import { isStudioManualEditGestureLiveIn } from "./manualEditsDom";
import { isStudioManualEditGestureLiveIn } from "./manualEditGesture";
import { readTranslatePx } from "./plainTranslate";
import { moveDomGroupBy } from "./domGroupMoveBy";
import { GsapEditBlockedError } from "../../hooks/gsapEditOutcome";
@@ -2,7 +2,7 @@ import type { DomEditSelection } from "./domEditing";
import type { DomEditGroupPathOffsetCommit } from "./domEditOverlayGestures";
import { canCanvasNudgeTargets } from "./domEditNudge";
import { isStudioManualEditGestureCurrent, restoreStudioPathOffset } from "./manualEdits";
import { countStudioManualEditSave } from "./manualEditsDom";
import { countStudioManualEditSave } from "./manualEditGesture";
import {
applyManualOffsetDragCommit,
createManualOffsetDragMember,
@@ -0,0 +1,104 @@
import {
STUDIO_OFFSET_X_PROP,
STUDIO_OFFSET_Y_PROP,
STUDIO_WIDTH_PROP,
STUDIO_HEIGHT_PROP,
STUDIO_ROTATION_PROP,
STUDIO_MANUAL_EDIT_GESTURE_ATTR,
STUDIO_EDIT_MOMENT_ATTR,
type EditMoment,
} from "./manualEditsTypes";
import { BOX_SIZE_STYLE_PROPS } from "./manualEditsDomPatches";
let studioManualEditGestureId = 0;
const detachedStandInGestures = new WeakMap<Document, Set<Element>>();
export type StudioGestureDraws = "move" | "resize" | "rotate" | "edit";
const MOVE_DRAWS = ["translate", STUDIO_OFFSET_X_PROP, STUDIO_OFFSET_Y_PROP];
const GESTURE_DRAWS: Record<StudioGestureDraws, readonly string[]> = {
move: MOVE_DRAWS,
resize: [...MOVE_DRAWS, STUDIO_WIDTH_PROP, STUDIO_HEIGHT_PROP, ...BOX_SIZE_STYLE_PROPS],
rotate: ["rotate", "transform", "transform-origin", "display", STUDIO_ROTATION_PROP],
edit: [],
};
export function beginStudioManualEditGesture(
element: HTMLElement,
draws: StudioGestureDraws,
at?: EditMoment,
): string {
studioManualEditGestureId += 1;
const token = `gesture-${studioManualEditGestureId}:${draws}`;
element.setAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR, token);
if (!element.isConnected) {
const doc = element.ownerDocument;
detachedStandInGestures.set(doc, (detachedStandInGestures.get(doc) ?? new Set()).add(element));
}
if (at) element.setAttribute(STUDIO_EDIT_MOMENT_ATTR, JSON.stringify(at));
else element.removeAttribute(STUDIO_EDIT_MOMENT_ATTR);
return token;
}
const GESTURE_ENDED = "hf-manual-edit-gesture-ended";
export function endStudioManualEditGesture(element: HTMLElement, token?: string): void {
if (token && element.getAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR) !== token) return;
if (!element.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR)) return;
element.removeAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
element.removeAttribute(STUDIO_EDIT_MOMENT_ATTR);
const doc = element.ownerDocument;
detachedStandInGestures.get(doc)?.delete(element);
doc.dispatchEvent(new (doc.defaultView?.Event ?? Event)(GESTURE_ENDED));
}
export function isStudioManualEditGestureLiveIn(doc: Document): boolean {
if (doc.querySelector(`[${STUDIO_MANUAL_EDIT_GESTURE_ATTR}]`) !== null) return true;
const standIns = [...(detachedStandInGestures.get(doc) ?? [])];
return standIns.some((el) => el.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR));
}
/** Runs `run` once the last gesture in `doc` ends; the returned function stops waiting. */
export function afterStudioManualEditGestures(doc: Document, run: () => void): () => void {
const onEnded = () => {
if (isStudioManualEditGestureLiveIn(doc)) return;
stop();
run();
};
const stop = () => doc.removeEventListener(GESTURE_ENDED, onEnded);
doc.addEventListener(GESTURE_ENDED, onEnded);
return stop;
}
const gestureSaves = new WeakMap<Document, number>();
export function studioManualEditSavesIn(doc: Document): number {
return gestureSaves.get(doc) ?? 0;
}
export function countStudioPreviewChange(doc: Document): void {
gestureSaves.set(doc, studioManualEditSavesIn(doc) + 1);
}
/** Runs a gesture's save, counted as it starts and as it settles: a reload requested before shows the old file. */
export function countStudioManualEditSave<R>(element: HTMLElement, save: () => R): R {
const doc = element.ownerDocument;
const count = () => countStudioPreviewChange(doc);
count();
const result = save();
void Promise.resolve(result).then(count, count);
return result;
}
export function studioGestureDraws(element: Element): readonly string[] | null {
const token = element.getAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
if (token === null) return null;
return GESTURE_DRAWS[token.split(":")[1] as StudioGestureDraws] ?? [];
}
export function isStudioManualEditGestureActive(element: HTMLElement): boolean {
return element.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
}
export function isStudioManualEditGestureCurrent(element: HTMLElement, token: string): boolean {
return element.getAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR) === token;
}
@@ -21,6 +21,9 @@ export {
beginStudioManualEditGesture,
endStudioManualEditGesture,
isStudioManualEditGestureCurrent,
} from "./manualEditGesture";
export {
readStudioPathOffset,
readAppliedStudioPathOffset,
readStudioBoxSize,
@@ -0,0 +1,50 @@
// @vitest-environment happy-dom
import { expect, it, vi } from "vitest";
vi.mock("../../player/lib/previewChannel", async (importOriginal) => ({
...(await importOriginal<typeof import("../../player/lib/previewChannel")>()),
previewFrameOpaque: () => true,
}));
import {
afterStudioManualEditGestures,
beginStudioManualEditGesture,
countStudioManualEditSave,
endStudioManualEditGesture,
isStudioManualEditGestureLiveIn,
studioManualEditSavesIn,
} from "./manualEditGesture";
import { gestureDocumentOf } from "./previewSelection";
const iframe = document.createElement("iframe");
it("holds a sealed preview's reload while a gesture runs on a stand-in, and lets it go when the gesture ends", () => {
const doc = gestureDocumentOf(iframe)!;
const standIn = doc.createElement("div");
const released = vi.fn();
const token = beginStudioManualEditGesture(standIn, "move");
expect(isStudioManualEditGestureLiveIn(gestureDocumentOf(iframe)!)).toBe(true);
afterStudioManualEditGestures(doc, released);
endStudioManualEditGesture(standIn, token);
expect(isStudioManualEditGestureLiveIn(gestureDocumentOf(iframe)!)).toBe(false);
expect(released).toHaveBeenCalledOnce();
});
it("counts a sealed preview's gesture saves where its reload looks for them", async () => {
const before = studioManualEditSavesIn(gestureDocumentOf(iframe)!);
const standIn = gestureDocumentOf(iframe)!.createElement("div");
await countStudioManualEditSave(standIn, async () => {});
expect(studioManualEditSavesIn(gestureDocumentOf(iframe)!)).toBe(before + 2);
});
it("does not count a gesture on an element its own document no longer holds", () => {
const live = document.createElement("div");
document.body.append(live);
beginStudioManualEditGesture(live, "move");
live.remove();
expect(isStudioManualEditGestureLiveIn(document)).toBe(false);
});
@@ -6,8 +6,6 @@ import {
STUDIO_ROTATION_PROP,
STUDIO_PATH_OFFSET_ATTR,
STUDIO_MANUAL_EDIT_GESTURE_ATTR,
STUDIO_EDIT_MOMENT_ATTR,
type EditMoment,
STUDIO_BOX_SIZE_ATTR,
STUDIO_ROTATION_ATTR,
STUDIO_ORIGINAL_TRANSLATE_ATTR,
@@ -37,93 +35,7 @@ import {
import { gsapWritesChannels } from "../../hooks/gsapRuntimeKeyframes";
import { splitTopLevelWhitespace } from "./manualEditsStyleHelpers";
import { roundTo3, roundToLayoutSize } from "../../utils/rounding";
import { BOX_SIZE_STYLE_PROPS } from "./manualEditsDomPatches";
/* ── Gesture tracking ─────────────────────────────────────────────── */
let studioManualEditGestureId = 0;
export type StudioGestureDraws = "move" | "resize" | "rotate" | "edit";
const MOVE_DRAWS = ["translate", STUDIO_OFFSET_X_PROP, STUDIO_OFFSET_Y_PROP];
const GESTURE_DRAWS: Record<StudioGestureDraws, readonly string[]> = {
move: MOVE_DRAWS,
resize: [...MOVE_DRAWS, STUDIO_WIDTH_PROP, STUDIO_HEIGHT_PROP, ...BOX_SIZE_STYLE_PROPS],
rotate: ["rotate", "transform", "transform-origin", "display", STUDIO_ROTATION_PROP],
edit: [],
};
export function beginStudioManualEditGesture(
element: HTMLElement,
draws: StudioGestureDraws,
at?: EditMoment,
): string {
studioManualEditGestureId += 1;
const token = `gesture-${studioManualEditGestureId}:${draws}`;
element.setAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR, token);
if (at) element.setAttribute(STUDIO_EDIT_MOMENT_ATTR, JSON.stringify(at));
else element.removeAttribute(STUDIO_EDIT_MOMENT_ATTR);
return token;
}
const GESTURE_ENDED = "hf-manual-edit-gesture-ended";
export function endStudioManualEditGesture(element: HTMLElement, token?: string): void {
if (token && element.getAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR) !== token) return;
if (!element.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR)) return;
element.removeAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
element.removeAttribute(STUDIO_EDIT_MOMENT_ATTR);
const doc = element.ownerDocument;
doc.dispatchEvent(new (doc.defaultView?.Event ?? Event)(GESTURE_ENDED));
}
export function isStudioManualEditGestureLiveIn(doc: Document): boolean {
return doc.querySelector(`[${STUDIO_MANUAL_EDIT_GESTURE_ATTR}]`) !== null;
}
/** Runs `run` once the last gesture in `doc` ends; the returned function stops waiting. */
export function afterStudioManualEditGestures(doc: Document, run: () => void): () => void {
const onEnded = () => {
if (isStudioManualEditGestureLiveIn(doc)) return;
stop();
run();
};
const stop = () => doc.removeEventListener(GESTURE_ENDED, onEnded);
doc.addEventListener(GESTURE_ENDED, onEnded);
return stop;
}
const gestureSaves = new WeakMap<Document, number>();
export function studioManualEditSavesIn(doc: Document): number {
return gestureSaves.get(doc) ?? 0;
}
export function countStudioPreviewChange(doc: Document): void {
gestureSaves.set(doc, studioManualEditSavesIn(doc) + 1);
}
/** Runs a gesture's save, counted as it starts and as it settles: a reload requested before shows the old file. */
export function countStudioManualEditSave<R>(element: HTMLElement, save: () => R): R {
const doc = element.ownerDocument;
const count = () => countStudioPreviewChange(doc);
count();
const result = save();
void Promise.resolve(result).then(count, count);
return result;
}
export function studioGestureDraws(element: Element): readonly string[] | null {
const token = element.getAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
if (token === null) return null;
return GESTURE_DRAWS[token.split(":")[1] as StudioGestureDraws] ?? [];
}
function isStudioManualEditGestureActive(element: HTMLElement): boolean {
return element.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
}
export function isStudioManualEditGestureCurrent(element: HTMLElement, token: string): boolean {
return element.getAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR) === token;
}
import { isStudioManualEditGestureActive } from "./manualEditGesture";
/* ── CSS custom-property readers ──────────────────────────────────── */
function readPxCustomProperty(element: HTMLElement, property: string): number {
@@ -486,6 +486,11 @@ export async function findOpaqueTimelineElement(
export const standInHandle = (element: Element) => standInHandles.get(element);
export function gestureDocumentOf(iframe: HTMLIFrameElement | null): Document | null {
if (!iframe) return null;
return previewFrameOpaque(iframe) ? inert() : iframe.contentDocument;
}
export function elementWithin(container: HTMLElement, element: HTMLElement): boolean {
const handle = standInHandles.get(container);
if (handle === undefined) return container.contains(element);
@@ -8,7 +8,7 @@ import {
} from "./manualEdits";
import { getOffsetDragGsap } from "./manualOffsetDrag";
import { splitTopLevelWhitespace } from "./manualEditsStyleHelpers";
import { endStudioManualEditGesture, isStudioManualEditGestureCurrent } from "./manualEditsDom";
import { endStudioManualEditGesture, isStudioManualEditGestureCurrent } from "./manualEditGesture";
import { drawPreviewDraft, endPreviewDraft } from "./previewDrafts";
function lastRuleTransform(element: HTMLElement): string {
@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { DomEditSelection } from "../components/editor/domEditing";
import type { PatchOperation } from "../utils/sourcePatcher";
import type { CutoverResult } from "../utils/sdkCutover";
import { studioManualEditSavesIn } from "../components/editor/manualEditsDom";
import { studioManualEditSavesIn } from "../components/editor/manualEditGesture";
import {
DomEditPersistPreparedWriteError,
DomEditPersistUnresolvableError,
@@ -16,7 +16,7 @@ import {
writePreparedContent,
} from "./useDomEditCommitsHelpers";
import { importedFontFaceCssFor } from "../utils/studioFontHelpers";
import { countStudioManualEditSave } from "../components/editor/manualEditsDom";
import { countStudioManualEditSave } from "../components/editor/manualEditGesture";
import type { CutoverResult } from "../utils/sdkCutover";
import { reseekPreviewRuntime } from "./timelineTrackVisibility";
import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";
@@ -6,7 +6,7 @@ import {
beginStudioManualEditGesture,
endStudioManualEditGesture,
countStudioManualEditSave,
} from "../components/editor/manualEditsDom";
} from "../components/editor/manualEditGesture";
/**
* Editing an element's text where it sits, in the composition itself.
@@ -7,8 +7,9 @@ import {
import {
afterStudioManualEditGestures,
isStudioManualEditGestureLiveIn,
} from "../components/editor/manualEditsDom";
} from "../components/editor/manualEditGesture";
import { STUDIO_MOTION_PATH } from "../components/editor/studioMotion";
import { gestureDocumentOf } from "../components/editor/previewSelection";
import { markScenesStale } from "../player/sceneSwap";
import {
createDomEditSaveQueue,
@@ -221,7 +222,7 @@ export function usePreviewPersistence({
// Undo never repaints under a live gesture; the preview reloads once the last one ends.
const heldPreviewDoc = useCallback(() => {
const doc = previewIframeRef.current?.contentDocument;
const doc = gestureDocumentOf(previewIframeRef.current);
return doc && isStudioManualEditGestureLiveIn(doc) ? doc : null;
}, [previewIframeRef]);
@@ -7,8 +7,9 @@ import {
afterStudioManualEditGestures,
isStudioManualEditGestureLiveIn,
studioManualEditSavesIn,
} from "../../components/editor/manualEditsDom";
} from "../../components/editor/manualEditGesture";
import { refusedPreviewStatus } from "@hyperframes/core/studio-preview-mark";
import { gestureDocumentOf } from "../../components/editor/previewSelection";
import { logReload } from "../../utils/reloadDebug";
import {
useTimelineSyncCallbacks,
@@ -242,7 +243,7 @@ export function useShadowPreviewReload({
);
const gestureSavesOnScreen = useCallback(() => {
const liveDoc = iframeRef.current?.contentDocument;
const liveDoc = gestureDocumentOf(iframeRef.current);
return liveDoc ? studioManualEditSavesIn(liveDoc) : 0;
}, [iframeRef]);
@@ -265,7 +266,7 @@ export function useShadowPreviewReload({
// shows the file before it: once that write has landed, a fresh one loads instead.
const heldOrStale = useCallback(
(gen: number) => {
const liveDoc = iframeRef.current?.contentDocument;
const liveDoc = gestureDocumentOf(iframeRef.current);
if (liveDoc && isStudioManualEditGestureLiveIn(liveDoc))
return waitThenRetry(gen, "gesture", (retry) =>
afterStudioManualEditGestures(liveDoc, retry),
@@ -39,11 +39,12 @@ import { hasTimelinePerformanceFixtureLease } from "../lib/timelinePerformanceFi
import { applyCachedSourceDurations, probeMissingSourceDurations } from "../lib/mediaProbe";
import { shouldResumeForwardPlaybackAfterSeek, shouldStopAfterSeek } from "../lib/playbackSeek";
import { applyPreviewVariablesToUrl } from "../../hooks/previewVariablesStore";
import { isStudioManualEditGestureLiveIn } from "../../components/editor/manualEditsDom";
import { isStudioManualEditGestureLiveIn } from "../../components/editor/manualEditGesture";
import { createPreviewMessageHandler } from "./previewMessageRouter";
import { usePreviewQualityForwarding } from "./usePreviewQualityForwarding";
import { timelineElementsChanged } from "./timelinePlayerSync";
import { safeContentDocument } from "./timelineSyncHydration";
import { gestureDocumentOf } from "../../components/editor/previewSelection";
import { sceneSwapFor, supersededByNewerEdit, swapFreshly } from "../sceneSwap";
export interface UseTimelinePlayerOptions {
@@ -502,8 +503,8 @@ export function useTimelinePlayer({
// A newer edit, or anything replacing the live preview (a reload, a composition switch), wins.
const isCurrent = () => gen === refreshGenRef.current && slot === previewGeneration();
const swap = sceneSwapFor(iframe);
const swapWouldReplaceGestureNode =
!!iframe.contentDocument && isStudioManualEditGestureLiveIn(iframe.contentDocument);
const gestureDoc = gestureDocumentOf(iframe);
const swapWouldReplaceGestureNode = !!gestureDoc && isStudioManualEditGestureLiveIn(gestureDoc);
if (!swap || isRefreshingRef.current || swapWouldReplaceGestureNode)
return reloadWholeFilm(url.toString());
swapFreshly(swap, url, isCurrent, cancel.signal, reloadWholeFilm);
@@ -96,8 +96,11 @@ describe("undo on a sealed preview", () => {
it("reloads when the frame cannot re-run the changed script", async () => {
channel.request.mockResolvedValue({ result: "cannot-soft-reload" });
const { reload } = undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 2 }"));
const { reload, iframe } = undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 2 }"));
await settled();
expect(reload).toHaveBeenCalledOnce();
expect(channel.request).toHaveBeenCalledWith(iframe, "mark-scenes-stale", {
files: ["index.html"],
});
});
});
@@ -22,7 +22,7 @@ import {
import { recordLiveSet } from "@hyperframes/core/runtime/soft-reload";
import { applyPatch } from "./sourcePatcher";
import { beginStudioManualEditGesture } from "../components/editor/manualEdits";
import { studioManualEditSavesIn } from "../components/editor/manualEditsDom";
import { studioManualEditSavesIn } from "../components/editor/manualEditGesture";
import { writePlainMove, writeTranslatePx } from "../components/editor/plainTranslate";
// ── Bug 2: undo/redo restore soft-apply ──────────────────────────────────────
+4 -1
View File
@@ -19,7 +19,10 @@ import { announcePreviewRestoredInPlace, markScenesStale } from "../player/scene
import { previewFrameOpaque, previewRequest } from "../player/lib/previewChannel";
import type { EditingParams } from "@hyperframes/core/runtime/editing-port";
import { STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR } from "../components/editor/manualEditsTypes";
import { countStudioPreviewChange, studioGestureDraws } from "../components/editor/manualEditsDom";
import {
countStudioPreviewChange,
studioGestureDraws,
} from "../components/editor/manualEditGesture";
type PreviewWindow = Window & {
__player?: { seek?: (t: number) => void };