diff --git a/packages/studio/src/hooks/stackingReorder.sealed.test.ts b/packages/studio/src/hooks/stackingReorder.sealed.test.ts
new file mode 100644
index 0000000000..8900262e5f
--- /dev/null
+++ b/packages/studio/src/hooks/stackingReorder.sealed.test.ts
@@ -0,0 +1,138 @@
+// @vitest-environment happy-dom
+
+import { act, createElement } from "react";
+import { afterEach, expect, it, vi } from "vitest";
+import { findPreviewElementForSelection, standInFor } from "../components/editor/previewSelection";
+import { useTimelineStackingSync } from "../player/components/useTimelineStackingSync";
+import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers";
+import { usePlayerStore, type TimelineElement } from "../player/store/playerStore";
+import type { DomEditPatchBatch } from "./domEditCommitTypes";
+import { mountReactHarness } from "./domSelectionTestHarness";
+import { makeLifecycleOpsParams } from "./elementLifecycleOpsTestUtils";
+import type { TimelineZIndexReorderCommit } from "./useTimelineEditingTypes";
+import { useElementLifecycleOps } from "./useElementLifecycleOps";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const unmounts: Array<() => void> = [];
+afterEach(() => {
+ unmounts.splice(0).forEach((unmount) => act(unmount));
+ document.body.innerHTML = "";
+ usePlayerStore.getState().setElements([]);
+});
+
+const PAGE = `
`;
+
+const clip = (id: string, track: number, zIndex: number): TimelineElement => ({
+ id,
+ key: id,
+ domId: id,
+ label: id,
+ tag: "div",
+ start: 0,
+ duration: 5,
+ track,
+ zIndex,
+ sourceFile: "index.html",
+});
+
+function stackingSync(iframe: HTMLIFrameElement, commit: TimelineZIndexReorderCommit) {
+ let sync!: ReturnType;
+ function Harness() {
+ sync = useTimelineStackingSync({
+ expandedElementsRef: { current: [clip("back", 1, 1), clip("front", 0, 2)] },
+ previewIframeRef: { current: iframe },
+ onZIndexReorder: commit,
+ });
+ return null;
+ }
+ const root = mountReactHarness(createElement(Harness));
+ unmounts.push(() => root.unmount());
+ return () => sync;
+}
+
+it("reads a sealed clip's z-index from the frame's stylesheet", async () => {
+ document.body.innerHTML = `${PAGE.replace("z-index: 1", "")}`;
+ const sync = stackingSync(sealedPreviewFrame().iframe, vi.fn());
+ await expect(sync().readClipZIndex({ ...clip("back", 1, 1), zIndex: undefined })).resolves.toBe(
+ 10,
+ );
+ await expect(sync().readClipZIndex(clip("gone", 1, 1))).resolves.toBeNaN();
+});
+
+it("reads the z-index an earlier gesture drew, not the one the drag started from", async () => {
+ document.body.innerHTML = PAGE;
+ const sync = stackingSync(sealedPreviewFrame().iframe, vi.fn());
+ document.getElementById("back")!.style.zIndex = "11";
+ await expect(sync().readClipZIndex(clip("back", 1, 1))).resolves.toBe(11);
+});
+
+it("saves the restack of a lane drag in a sealed preview", async () => {
+ document.body.innerHTML = PAGE;
+ const commit = vi.fn(async () => undefined);
+ const sync = stackingSync(sealedPreviewFrame().iframe, commit);
+ await act(() => sync().applyStackingPatches([{ key: "back", zIndex: 3 }], "clip-lane-move:1"));
+ expect(commit).toHaveBeenCalledOnce();
+ expect(commit.mock.calls[0]).toMatchObject([
+ [{ zIndex: 3, id: "back", sourceFile: "index.html", key: "back" }],
+ "clip-lane-move:1",
+ ]);
+});
+
+function reorderCommit(save: (batches: DomEditPatchBatch[]) => boolean) {
+ let commit!: TimelineZIndexReorderCommit;
+ function Harness() {
+ commit = useElementLifecycleOps(
+ makeLifecycleOpsParams({
+ commitDomEditPatchBatches: async (batches) => {
+ const durable = save(batches);
+ return { durable, allMatched: durable, changed: durable };
+ },
+ }),
+ ).handleDomZIndexReorderCommit;
+ return null;
+ }
+ const root = mountReactHarness(createElement(Harness));
+ unmounts.push(() => root.unmount());
+ return (...args: Parameters) => commit(...args);
+}
+
+async function restackBack(save: (batches: DomEditPatchBatch[]) => boolean) {
+ const iframe = sealedPreviewFrame().iframe;
+ const found = await findPreviewElementForSelection(
+ iframe,
+ { id: "back", sourceFile: "index.html" },
+ "index.html",
+ );
+ const element = standInFor(iframe, found!);
+ const commit = reorderCommit(save);
+ await act(() => commit([{ element, zIndex: 3, id: "back", sourceFile: "index.html" }]));
+}
+
+it("draws a sealed restack in the frame and saves the position it needs", async () => {
+ document.body.innerHTML = PAGE;
+ const saved: DomEditPatchBatch[][] = [];
+ await restackBack((batches) => (saved.push(batches), true));
+ const back = document.getElementById("back")!;
+ await vi.waitFor(() => expect(back.style.zIndex).toBe("3"));
+ expect(back.style.position).toBe("relative");
+ expect(saved).toHaveLength(1);
+ expect(saved[0]![0]!.patches[0]!.operations).toEqual([
+ { type: "inline-style", property: "z-index", value: "3" },
+ { type: "inline-style", property: "position", value: "relative" },
+ ]);
+});
+
+it("puts a sealed restack back when its save fails", async () => {
+ document.body.innerHTML = PAGE;
+ const back = document.getElementById("back")!;
+ const drawn: string[] = [];
+ const watch = new MutationObserver(() => drawn.push(back.style.zIndex));
+ watch.observe(back, { attributeFilter: ["style"] });
+ await restackBack(() => false);
+ await vi.waitFor(() => expect([...new Set(drawn)]).toEqual(["3", "1"]));
+ expect(back.getAttribute("style")).toBe("position: static; z-index: 1;");
+ watch.disconnect();
+});
diff --git a/packages/studio/src/hooks/useElementLifecycleOps.ts b/packages/studio/src/hooks/useElementLifecycleOps.ts
index d2dfe816e8..d117c590f6 100644
--- a/packages/studio/src/hooks/useElementLifecycleOps.ts
+++ b/packages/studio/src/hooks/useElementLifecycleOps.ts
@@ -13,6 +13,13 @@ import {
type DomEditSelection,
} from "../components/editor/domEditing";
import { LAYER_REVEAL_PRIOR_POSITION_ATTR } from "../player/lib/timelineElementHelpers";
+import { previewComputedStyles } from "../player/lib/previewChannel";
+import {
+ afterSealedDraw,
+ editPreviewElement,
+ type PreviewElementEdit,
+} from "../player/lib/previewElements";
+import { previewStandIn } from "../components/editor/previewDrafts";
import {
beginLayerRevealCommit,
beginLayerZPersist,
@@ -255,6 +262,15 @@ export function useElementLifecycleOps({
return (async () => {
const releaseZPersists = entries.map((entry) => beginLayerZPersist(entry.element));
try {
+ const sealed = entries.map((entry) => previewStandIn(entry.element));
+ const sealedPositions = sealed.some(Boolean)
+ ? await Promise.all(
+ sealed.map(
+ (frame) => frame && previewComputedStyles(frame.iframe, frame, ["position"]),
+ ),
+ )
+ : [];
+ const sealedEdits: PreviewElementEdit[] = [];
// Resolver shadow (telemetry-only, decoupled from cutover): record whether
// the SDK resolves each reordered element — the reorderElements op's targets.
onReorderShadow?.(
@@ -271,7 +287,8 @@ export function useElementLifecycleOps({
element: HTMLElement;
ownership: LayerRevealCommitOwnership;
}> = [];
- for (const entry of entries) {
+ for (const [index, entry] of entries.entries()) {
+ const frame = sealed[index];
const priorZIndex = entry.element.style.zIndex;
const priorPosition = entry.element.style.position;
const priorStoreEntry = entry.key
@@ -297,7 +314,11 @@ export function useElementLifecycleOps({
const win = entry.element.ownerDocument?.defaultView;
const effectivePosition =
liftPriorPosition ??
- (win ? win.getComputedStyle(entry.element).position : undefined);
+ (frame
+ ? sealedPositions[index]?.position
+ : win
+ ? win.getComputedStyle(entry.element).position
+ : undefined);
if (effectivePosition === "static") {
entry.element.style.position = "relative";
positionChanged = true;
@@ -311,7 +332,14 @@ export function useElementLifecycleOps({
.getState()
.updateElement(entry.key, { zIndex: entry.zIndex, hasExplicitZIndex: true });
}
+ const sealedEdit =
+ frame &&
+ editPreviewElement(frame.iframe, frame.handle, {
+ styles: patches.map((patch): [string, string] => [patch.property, patch.value]),
+ });
+ if (sealedEdit) sealedEdits.push(sealedEdit);
rollbacks.push(() => {
+ sealedEdit?.restore();
if (revealOwnership) {
rollbackLayerRevealCommit(entry.element, revealOwnership);
} else {
@@ -357,18 +385,19 @@ export function useElementLifecycleOps({
// commitDomEditPatchBatches still falls back to reloading whenever the
// server reports an unmatched patch target (live DOM ≠ disk).
try {
- const result = await commitDomEditPatchBatches(batches, {
- label: "Reorder layers",
- coalesceKey,
- // Unbounded window: every key this commit records under is unique per
- // gesture (zReorderCoalesceKey's gesture seq, or the lane drag's
- // clip-lane-move:), so the fold can only merge records of the SAME
- // gesture — and those records are separated by a server round-trip
- // (move→z on a lane drag, z→lane-mirror on a canvas action), which
- // under real network latency exceeds the 300ms default window.
- coalesceMs: Number.POSITIVE_INFINITY,
- skipReload: true,
- });
+ const drawn = sealedEdits.length
+ ? Promise.all(sealedEdits.map((edit) => edit.drawn)).then((all) => all.every(Boolean))
+ : null;
+ const result = await afterSealedDraw(drawn && { drawn }, (allDrawn) =>
+ commitDomEditPatchBatches(batches, {
+ label: "Reorder layers",
+ coalesceKey,
+ // Unbounded: each key is unique per gesture, and one gesture's records sit a
+ // server round-trip apart, longer than the 300ms default window.
+ coalesceMs: Number.POSITIVE_INFINITY,
+ skipReload: allDrawn,
+ }),
+ );
if (!result.durable) {
rollbackOptimisticState();
return result;
diff --git a/packages/studio/src/player/components/timelineClipDragCommit.ts b/packages/studio/src/player/components/timelineClipDragCommit.ts
index f7a2b4a7ea..c9f1810ee6 100644
--- a/packages/studio/src/player/components/timelineClipDragCommit.ts
+++ b/packages/studio/src/player/components/timelineClipDragCommit.ts
@@ -71,7 +71,7 @@ export interface DragCommitDeps {
* returns the clip's current z-index (from the live DOM inline style / computed;
* "auto" ⇒ 0).
*/
- readZIndex?: (element: TimelineElement) => number;
+ readZIndex?: (element: TimelineElement) => number | Promise;
/**
* Apply the computed z-index patches. Wiring (in the drag hook, which owns the
* DOM/persist plumbing) forwards these to the SAME atomic style-patch persist
@@ -550,24 +550,25 @@ function syncStackingForEdit(
// slips through). Every real lane-realization drop aims at a DIFFERENT lane.
if (aimedLane === currentLane) return Promise.resolve();
- // Discovery order is DOM order, which breaks equal-z ties.
- const stackingEls = candidate.map((el, domIndex) => ({
- key: keyOf(el),
- start: el.start,
- duration: el.duration,
- track: el.track,
- zIndex: readZIndex(el),
- isAudio: classifyZone(el) === "audio",
- sourceFile: el.sourceFile,
- domIndex,
- stackingContextId: el.stackingContextId ?? null,
- }));
-
- const patches = computeStackingPatches(
- stackingEls,
- [dragKey],
- aimedLane < currentLane ? "up" : "down",
- );
- if (patches.length === 0) return Promise.resolve();
- return Promise.resolve(onStackingPatches(patches, coalesceKey)).then(() => undefined);
+ return Promise.all(candidate.map((el) => readZIndex(el))).then((zIndexes) => {
+ // Discovery order is DOM order, which breaks equal-z ties.
+ const stackingEls = candidate.map((el, domIndex) => ({
+ key: keyOf(el),
+ start: el.start,
+ duration: el.duration,
+ track: el.track,
+ zIndex: zIndexes[domIndex]!,
+ isAudio: classifyZone(el) === "audio",
+ sourceFile: el.sourceFile,
+ domIndex,
+ stackingContextId: el.stackingContextId ?? null,
+ }));
+ const patches = computeStackingPatches(
+ stackingEls,
+ [dragKey],
+ aimedLane < currentLane ? "up" : "down",
+ );
+ if (patches.length === 0) return;
+ return Promise.resolve(onStackingPatches(patches, coalesceKey)).then(() => undefined);
+ });
}
diff --git a/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts b/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts
index a6854d3aa6..f3774343ad 100644
--- a/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts
+++ b/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts
@@ -2,7 +2,7 @@ import type { TimelineTrackInsertLayout } from "./timelineTrackInsertLayout";
import { matchesKey } from "./studioShortcuts";
import type { Dispatch, RefObject, SetStateAction } from "react";
import { resolveTimelineDragEscape } from "./timelineEditing";
-import { commitDraggedClipMove } from "./timelineClipDragCommit";
+import { commitDraggedClipMove, type DragCommitDeps } from "./timelineClipDragCommit";
import type {
BlockedClipState,
DraggedClipState,
@@ -75,7 +75,7 @@ interface TimelineClipDragGestureLifecycleInput {
((element: TimelineElement, intent: BlockedClipState["intent"]) => void) | undefined
>;
onLinkEditRef: RefObject;
- readZIndexRef: RefObject<((element: TimelineElement) => number) | undefined>;
+ readZIndexRef: RefObject;
onStackingPatchesRef: RefObject<
((patches: StackingPatch[]) => Promise | void) | undefined
>;
diff --git a/packages/studio/src/player/components/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.ts
index 9e6eafad14..861abe558a 100644
--- a/packages/studio/src/player/components/useTimelineClipDrag.ts
+++ b/packages/studio/src/player/components/useTimelineClipDrag.ts
@@ -48,6 +48,7 @@ import {
type TimelineTrackInsertLayout,
} from "./timelineTrackInsertLayout";
import type { TimelineRowGeometry } from "./timelineLayout";
+import type { DragCommitDeps } from "./timelineClipDragCommit";
import {
mountTimelineClipDragGestureLifecycle,
type TimelineGestureKind,
@@ -90,7 +91,7 @@ interface UseTimelineClipDragInput {
* iframe + the canvas z-order persist path; forwarded straight to
* commitDraggedClipMove. Both optional → absent = no-op (backward compatible).
*/
- readZIndex?: (element: TimelineElement) => number;
+ readZIndex?: DragCommitDeps["readZIndex"];
onStackingPatches?: (patches: StackingPatch[]) => Promise | void;
refreshAfterLaneMove?: () => void;
sessionEpoch?: number;
diff --git a/packages/studio/src/player/components/useTimelineStackingSync.ts b/packages/studio/src/player/components/useTimelineStackingSync.ts
index c0ccf16b8c..910db3c33a 100644
--- a/packages/studio/src/player/components/useTimelineStackingSync.ts
+++ b/packages/studio/src/player/components/useTimelineStackingSync.ts
@@ -3,7 +3,14 @@ import type { TimelineElement } from "../store/playerStore";
import { useDomEditActionsContextOptional } from "../../contexts/DomEditContext";
import { useStudioShellContextOptional } from "../../contexts/StudioContext";
import { findElementForSelection } from "../../components/editor/domEditingElement";
-import { readEffectiveZIndex } from "../../components/editor/canvasContextMenuZOrder";
+import {
+ findPreviewElementForSelection,
+ standInFor,
+} from "../../components/editor/previewSelection";
+import type { SelectionLookupTarget } from "../../components/editor/domEditSelectionRules";
+import { previewComputedStyles, previewFrameOpaque } from "../lib/previewChannel";
+import { parseZIndex, readEffectiveZIndex } from "../../components/editor/canvasContextMenuZOrder";
+import { readLayerRevealPriorZ } from "../lib/timelineElementHelpers";
import type { StackingPatch } from "./timelineStackingSync";
import type { TimelineZIndexReorderCommit } from "../../hooks/useTimelineEditingTypes";
@@ -33,24 +40,28 @@ export function useTimelineStackingSync({
// Resolve a TimelineElement to its live iframe HTMLElement via the same
// hfId ?? id ?? selector[selectorIndex] resolver the timeline's DOM patches use.
+ const lookupOf = useCallback(
+ (el: TimelineElement) => ({
+ hfId: el.hfId,
+ id: el.domId ?? el.id,
+ selector: el.selector,
+ selectorIndex: el.selectorIndex,
+ sourceFile: el.sourceFile ?? zSyncActiveCompPath ?? "index.html",
+ }),
+ [zSyncActiveCompPath],
+ );
const resolveIframeElement = useCallback(
(el: TimelineElement): HTMLElement | null => {
const doc = zSyncPreviewIframeRef?.current?.contentDocument ?? null;
if (!doc) return null;
- return findElementForSelection(
- doc,
- {
- hfId: el.hfId,
- id: el.domId ?? el.id,
- selector: el.selector,
- selectorIndex: el.selectorIndex,
- sourceFile: el.sourceFile ?? zSyncActiveCompPath ?? "index.html",
- },
- zSyncActiveCompPath,
- );
+ return findElementForSelection(doc, lookupOf(el), zSyncActiveCompPath);
},
- [zSyncPreviewIframeRef, zSyncActiveCompPath],
+ [zSyncPreviewIframeRef, zSyncActiveCompPath, lookupOf],
);
+ const sealedFrame = useCallback(() => {
+ const iframe = zSyncPreviewIframeRef?.current;
+ return iframe && previewFrameOpaque(iframe) ? iframe : null;
+ }, [zSyncPreviewIframeRef]);
// NaN (NOT 0) when the element can't be resolved in the preview iframe — a
// nested / unmounted sub-comp node, or one outside the active file. Fabricating
@@ -59,41 +70,63 @@ export function useTimelineStackingSync({
// clip instead. NaN (rather than null) keeps the return assignable to the
// `(el) => number` reader contract the drag hook / commit deps declare.
const readClipZIndex = useCallback(
- (el: TimelineElement): number => {
+ (el: TimelineElement): number | Promise => {
+ const iframe = sealedFrame();
+ if (iframe) return readSealedZIndex(iframe, lookupOf(el), zSyncActiveCompPath);
const node = resolveIframeElement(el);
return node ? readEffectiveZIndex(node) : Number.NaN;
},
- [resolveIframeElement],
+ [resolveIframeElement, sealedFrame, lookupOf, zSyncActiveCompPath],
);
const applyStackingPatches = useCallback(
(patches: StackingPatch[], coalesceKey?: string) => {
if (!handleDomZIndexReorderCommit) return Promise.resolve();
- const entries = patches.flatMap((p) => {
+ const moves = patches.flatMap((p) => {
const el = expandedElementsRef.current.find((e) => (e.key ?? e.id) === p.key);
- const node = el && resolveIframeElement(el);
- if (!el || !node) return [];
- return [
- {
- element: node,
- zIndex: p.zIndex,
- id: el.domId ?? el.id,
- selector: el.selector,
- selectorIndex: el.selectorIndex,
- sourceFile: el.sourceFile ?? zSyncActiveCompPath ?? "index.html",
- // The store key: lets the commit update the store's zIndex
- // synchronously (and roll it back on failure).
- key: p.key,
- },
- ];
+ return el ? [{ el, zIndex: p.zIndex, key: p.key }] : [];
});
- // Forward the drag-commit's shared coalesce key so the z-reorder history
- // entry merges with the lane change's move entry into one undo step.
- return entries.length
- ? handleDomZIndexReorderCommit(entries, coalesceKey).then(() => undefined)
- : Promise.resolve();
+ const commit = (nodes: Array) => {
+ const entries = moves.flatMap(({ el, zIndex, key }, index) => {
+ const node = nodes[index];
+ if (!node) return [];
+ return [
+ {
+ element: node,
+ zIndex,
+ id: el.domId ?? el.id,
+ selector: el.selector,
+ selectorIndex: el.selectorIndex,
+ sourceFile: el.sourceFile ?? zSyncActiveCompPath ?? "index.html",
+ // The store key: lets the commit update the store's zIndex
+ // synchronously (and roll it back on failure).
+ key,
+ },
+ ];
+ });
+ // Forward the drag-commit's shared coalesce key so the z-reorder history
+ // entry merges with the lane change's move entry into one undo step.
+ return entries.length
+ ? handleDomZIndexReorderCommit(entries, coalesceKey).then(() => undefined)
+ : Promise.resolve();
+ };
+ const iframe = sealedFrame();
+ if (!iframe) return commit(moves.map(({ el }) => resolveIframeElement(el)));
+ const found = moves.map(({ el }) =>
+ findPreviewElementForSelection(iframe, lookupOf(el), zSyncActiveCompPath).then((element) =>
+ element ? standInFor(iframe, element) : null,
+ ),
+ );
+ return Promise.all(found).then(commit);
},
- [handleDomZIndexReorderCommit, resolveIframeElement, zSyncActiveCompPath, expandedElementsRef],
+ [
+ handleDomZIndexReorderCommit,
+ resolveIframeElement,
+ sealedFrame,
+ lookupOf,
+ zSyncActiveCompPath,
+ expandedElementsRef,
+ ],
);
// Engage the z-sync only when the persist path is present (inside the NLE).
@@ -101,3 +134,17 @@ export function useTimelineStackingSync({
return { readClipZIndex, applyStackingPatches, zSyncEnabled };
}
+
+/** The frame's effective z-index when the gesture runs: a stylesheet's value, or one an earlier gesture saved. */
+async function readSealedZIndex(
+ iframe: HTMLIFrameElement,
+ lookup: SelectionLookupTarget,
+ activeCompPath: string | null,
+): Promise {
+ const found = await findPreviewElementForSelection(iframe, lookup, activeCompPath);
+ if (!found) return Number.NaN;
+ const prior = readLayerRevealPriorZ(standInFor(iframe, found));
+ if (prior != null) return prior;
+ const styles = await previewComputedStyles(iframe, found, ["z-index"]);
+ return styles ? parseZIndex(styles["z-index"]) : Number.NaN;
+}
diff --git a/packages/studio/src/player/lib/previewElements.ts b/packages/studio/src/player/lib/previewElements.ts
index f4f70d58eb..7e2d6eb148 100644
--- a/packages/studio/src/player/lib/previewElements.ts
+++ b/packages/studio/src/player/lib/previewElements.ts
@@ -365,7 +365,10 @@ export function editPreviewElement(
const SEALED_DRAW_WAIT_MS = 300;
/** Saves a live edit at once; a sealed one once the frame says it drew it, else after the wait. */
-export function afterSealedDraw(edit: PreviewElementEdit | null, save: (drawn: boolean) => T) {
+export function afterSealedDraw(
+ edit: Pick | null,
+ save: (drawn: boolean) => T,
+) {
if (!edit) return save(true);
let timer: ReturnType | undefined;
const late = new Promise((resolve) => {