Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): hosts can apply the canvas menu's z-order through useDomEditZOrder (#4793)
Miguel Ángelc0f2780b8e76
diff --git a/packages/studio/src/components/editor/CanvasContextMenu.test.tsx b/packages/studio/src/components/editor/CanvasContextMenu.test.tsxindex f67372a086..e0b6117f94 100644--- a/packages/studio/src/components/editor/CanvasContextMenu.test.tsx+++ b/packages/studio/src/components/editor/CanvasContextMenu.test.tsx@@ -3,7 +3,7 @@ import React, { act } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { installReactActEnvironment, makeSelection } from "../../hooks/domSelectionTestHarness";-import { resolveZIndexEntries } from "./ConnectedDomEditOverlay";+import { resolveZIndexEntries } from "./useDomEditZOrder";import { useElementLifecycleOps } from "../../hooks/useElementLifecycleOps";import { makeLifecycleOpsParams } from "../../hooks/elementLifecycleOpsTestUtils";import type { DomEditPatchBatch } from "../../hooks/domEditCommitTypes";@@ -193,6 +193,27 @@ function renderCommitHook(captured: CapturedBatchCall[]) {return { commit: commit!, cleanup: () => act(() => hookRoot.unmount()) };}+describe("resolveZIndexEntries", () => {+ it("keys a same-class sibling by its index among them, not as the first of its class", () => {+ const parent = document.body.appendChild(document.createElement("div"));+ const [first, second, selected] = ["card", "card", "picked"].map((name) => {+ const child = parent.appendChild(document.createElement("div"));+ child.className = name;+ return child;+ });+ const { entries } = resolveZIndexEntries(+ makeSelection("Picked", selected!),+ [first!, second!].map((element, zIndex) => ({ element, zIndex })),+ null,+ );+ expect(entries.map((entry) => [entry.selector, entry.selectorIndex])).toEqual([+ [".card", 0],+ [".card", 1],+ ]);+ parent.remove();+ });+});+describe("CanvasContextMenu — z-action commit path", () => {it("never mutates live styles itself and persists the position patch for a static element", async () => {const { target } = makeStaticFamily();@@ -208,7 +229,7 @@ describe("CanvasContextMenu — z-action commit path", () => {selection,onApplyZIndex: (patches, action) => {stylesAtApply.push({ zIndex: target.style.zIndex, position: target.style.position });- const { entries } = resolveZIndexEntries(selection, patches);+ const { entries } = resolveZIndexEntries(selection, patches, null);void commit(entries, undefined, action);},});diff --git a/packages/studio/src/components/editor/CanvasContextMenu.tsx b/packages/studio/src/components/editor/CanvasContextMenu.tsxindex f1a5947f67..0c70614e2a 100644--- a/packages/studio/src/components/editor/CanvasContextMenu.tsx+++ b/packages/studio/src/components/editor/CanvasContextMenu.tsx@@ -16,7 +16,7 @@* flow, and captures the TRUE prior styles for its failure rollback.** The prop MUST be wired at the call site to route through the full persist- * path. ConnectedDomEditOverlay.tsx builds the per-patch PatchTargets (the selected+ * path. useDomEditZOrder.ts builds the per-patch PatchTargets (the selected* element carries its full selection identity; sibling elements are iframe DOM* nodes, so their id / selector are derived from the node and they share the* selection's sourceFile) and forwards them to handleDomZIndexReorderCommit.@@ -29,8 +29,7 @@ import type { DomEditSelection } from "./domEditing";import { useContextMenuDismiss } from "../../hooks/useContextMenuDismiss";import {isZOrderActionEnabled,- resolveCrossedNeighbor,- resolveZOrderChange,+ resolveZOrderStep,type ZOrderAction,type ZOrderPatch,} from "./canvasContextMenuZOrder";@@ -170,13 +169,11 @@ export const CanvasContextMenu = memo(function CanvasContextMenu({function handleZAction(action: ZAction) {if (!onApplyZIndex) return;- const patches = resolveZOrderChange(el, action);- if (patches === null) return;- // Resolve the crossed neighbor BEFORE the commit path mutates live styles —- // both resolvers must read the same pre-change render order. Always resolved- // (not only for the flash): onApplyZIndex forwards it so the host can mirror- // the z step into a timeline lane move.- const crossed = resolveCrossedNeighbor(el, action);+ // Resolved BEFORE the commit path mutates live styles. `crossed` is always+ // resolved (not only for the flash): the host mirrors it into a lane move.+ const step = resolveZOrderStep(el, action);+ if (step === null) return;+ const { patches, crossed } = step;// Do NOT pre-apply styles here: handleDomZIndexReorderCommit writes the// live z-index (and injects position:relative for static elements) in the// same synchronous flow, so feedback is still instant — and it must readdiff --git a/packages/studio/src/components/editor/ConnectedDomEditOverlay.tsx b/packages/studio/src/components/editor/ConnectedDomEditOverlay.tsxindex 6f2e2cad3b..f2af05af66 100644--- a/packages/studio/src/components/editor/ConnectedDomEditOverlay.tsx+++ b/packages/studio/src/components/editor/ConnectedDomEditOverlay.tsx@@ -4,12 +4,7 @@ import {useDomEditActionsContext,useDomEditSelectionContext,} from "../../contexts/DomEditContext";-import { readHfId, type DomEditSelection } from "./domEditing";-import { buildStableSelector } from "./domEditingDom";-import { deriveTimelineStoreKey } from "../../player/lib/timelineElementHelpers";-import { zReorderCoalesceKey } from "../../hooks/useElementLifecycleOps";-import { useCanvasZOrderTimelineMirror } from "../nle/useCanvasZOrderTimelineMirror";-import { runZLaneGesture } from "../nle/zLaneGesture";+import { useDomEditZOrder } from "./useDomEditZOrder";type HostInputProps = Pick<ComponentProps<typeof DomEditOverlay>,@@ -25,94 +20,6 @@ export interface ConnectedDomEditOverlayProps extends HostInputProps {onTextEditingChange?: (editing: boolean) => void;}-type ZIndexReorderEntry = {- element: HTMLElement;- zIndex: number;- id?: string;- selector?: string;- selectorIndex?: number;- sourceFile: string;- /** Timeline store key — lets the commit update the store zIndex synchronously. */- key?: string;-};--/** Can this element be robustly re-targeted for a persisted z change? */-function canTargetZIndexElement(- element: HTMLElement,- id: string | undefined,- selector: string | undefined,-): boolean {- return Boolean(id || selector || readHfId(element));-}--/** The selected element carries its full selection identity. */-function selectedZIndexEntry(sel: DomEditSelection, zIndex: number): ZIndexReorderEntry {- return {- element: sel.element,- zIndex,- id: sel.id ?? undefined,- selector: sel.selector,- selectorIndex: sel.selectorIndex,- sourceFile: sel.sourceFile,- key: deriveTimelineStoreKey({- domId: sel.id ?? undefined,- selector: sel.selector,- selectorIndex: sel.selectorIndex,- sourceFile: sel.sourceFile,- }),- };-}--/** A raw iframe sibling in the selection's file; null with no id or selector (z stays live). */-function siblingZIndexEntry(- element: HTMLElement,- zIndex: number,- sourceFile: string,-): ZIndexReorderEntry | null {- const id = element.id || undefined;- const selector = buildStableSelector(element);- if (!canTargetZIndexElement(element, id, selector)) return null;- return {- element,- zIndex,- id,- selector,- selectorIndex: undefined,- sourceFile,- key: deriveTimelineStoreKey({ domId: id, selector, sourceFile }),- };-}--/** Short human-readable label for a dropped sibling, for the console warning below. */-function describeZIndexElement(element: HTMLElement): string {- if (element.id) return `#${element.id}`;- const firstClass = element.classList.item(0);- return firstClass- ? `${element.tagName.toLowerCase()}.${firstClass}`- : element.tagName.toLowerCase();-}--// Resolve z-index patches into commit entries; a sibling with no stable-// id/selector can't be written to source, so it is returned as `dropped` for-// the revert-on-reload warning. Exported so tests can drive the menu → commit path.-export function resolveZIndexEntries(- sel: DomEditSelection,- patches: ReadonlyArray<{ element: HTMLElement; zIndex: number }>,-): { entries: ZIndexReorderEntry[]; dropped: Array<{ element: HTMLElement; zIndex: number }> } {- const entries: ZIndexReorderEntry[] = [];- const dropped: Array<{ element: HTMLElement; zIndex: number }> = [];- for (const patch of patches) {- if (patch.element === sel.element) {- entries.push(selectedZIndexEntry(sel, patch.zIndex));- continue;- }- const entry = siblingZIndexEntry(patch.element, patch.zIndex, sel.sourceFile);- if (entry) entries.push(entry);- else dropped.push(patch);- }- return { entries, dropped };-}-// Studio's DomEditOverlay wired to the session in DomEditProvider, so a host// outside EditorShell mounts the same canvas editing without its own callbacks.export function ConnectedDomEditOverlay({@@ -142,9 +49,8 @@ export function ConnectedDomEditOverlay({handleDomStyleCommit,applyMarqueeSelection,handleDomEditElementDelete,- handleDomZIndexReorderCommit,} = useDomEditActionsContext();- const mirrorZOrderToTimeline = useCanvasZOrderTimelineMirror();+ const zOrder = useDomEditZOrder();return (<DomEditOverlay@@ -170,38 +76,7 @@ export function ConnectedDomEditOverlay({onRotationCommit={handleDomRotationCommit}onStyleCommit={handleDomStyleCommit}onDeleteSelection={handleDomEditElementDelete}- onApplyZIndex={(sel, patches, action, crossed) => {- const { entries, dropped } = resolveZIndexEntries(sel, patches);- if (dropped.length > 0) {- // These siblings can't be written to source. Apply their live z- // anyway so the resolved stacking order renders coherently — it- // just reverts to the prior order on the next reload.- for (const patch of dropped) patch.element.style.zIndex = String(patch.zIndex);- console.warn(- "[studio] z-index reorder: dropping sibling(s) with no stable id/selector " +- "(will revert on reload):",- dropped.map((patch) => describeZIndexElement(patch.element)).join(", "),- );- }- if (entries.length === 0) return;- // One coalesce key for the z persist AND the lane mirror folds both into one undo entry;- // passed explicitly so the mirror shares it by construction, not by formula duplication.- const coalesceKey = zReorderCoalesceKey(entries, action);- // One serialized z→lane transaction: the mirror runs only AFTER a durable z commit and- // no second gesture interleaves (see runZLaneGesture). A failed z commit has already- // toasted and rolled back, so the catch only keeps its rejection from going unhandled.- runZLaneGesture({- commitZ: () => handleDomZIndexReorderCommit(entries, coalesceKey, action),- mirror: () =>- mirrorZOrderToTimeline({- selectionKey: entries.find((e) => e.element === sel.element)?.key,- action,- crossed,- sourceFile: sel.sourceFile,- coalesceKey,- }),- }).catch(() => undefined);- }}+ onApplyZIndex={zOrder.commit}onMarqueeSelect={applyMarqueeSelection}/>);diff --git a/packages/studio/src/components/editor/canvasContextMenuZOrder.ts b/packages/studio/src/components/editor/canvasContextMenuZOrder.tsindex 6e5be92c2f..47b69c1483 100644--- a/packages/studio/src/components/editor/canvasContextMenuZOrder.ts+++ b/packages/studio/src/components/editor/canvasContextMenuZOrder.ts@@ -511,3 +511,16 @@ export function isZOrderActionEnabled(): boolean {return resolveZOrderChange(target, action, options) !== null;}++/**+ * One z-order step: the patches plus the sibling it crosses, both read from the+ * same pre-change render order. Null when the action is a no-op.+ */+export function resolveZOrderStep(+ target: HTMLElement,+ action: ZOrderAction,+): { patches: ZOrderPatch[]; crossed: HTMLElement | null } | null {+ const patches = resolveZOrderChange(target, action);+ if (patches === null) return null;+ return { patches, crossed: resolveCrossedNeighbor(target, action) };+}diff --git a/packages/studio/src/components/editor/useDomEditZOrder.ts b/packages/studio/src/components/editor/useDomEditZOrder.tsnew file mode 100644index 0000000000..e504327741--- /dev/null+++ b/packages/studio/src/components/editor/useDomEditZOrder.ts@@ -0,0 +1,185 @@+import { useCallback, useMemo } from "react";+import { useDomEditActionsContext } from "../../contexts/DomEditContext";+import { readHfId, type DomEditSelection } from "./domEditing";+import { buildStableSelector, getSelectorIndex } from "./domEditingDom";+import { usePreviewReadOnly } from "./previewReadOnlyContext";+import { useStudioShellContextOptional } from "../../contexts/StudioContext";+import { deriveTimelineStoreKey } from "../../player/lib/timelineElementHelpers";+import { zReorderCoalesceKey } from "../../hooks/useElementLifecycleOps";+import { useCanvasZOrderTimelineMirror } from "../nle/useCanvasZOrderTimelineMirror";+import { runZLaneGesture } from "../nle/zLaneGesture";+import {+ isZOrderActionEnabled,+ resolveZOrderStep,+ type ZOrderAction,+ type ZOrderPatch,+} from "./canvasContextMenuZOrder";++type ZIndexReorderEntry = {+ element: HTMLElement;+ zIndex: number;+ id?: string;+ selector?: string;+ selectorIndex?: number;+ sourceFile: string;+ /** Timeline store key — lets the commit update the store zIndex synchronously. */+ key?: string;+};++/** Can this element be robustly re-targeted for a persisted z change? */+function canTargetZIndexElement(+ element: HTMLElement,+ id: string | undefined,+ selector: string | undefined,+): boolean {+ return Boolean(id || selector || readHfId(element));+}++/** The selected element carries its full selection identity. */+function selectedZIndexEntry(sel: DomEditSelection, zIndex: number): ZIndexReorderEntry {+ return {+ element: sel.element,+ zIndex,+ id: sel.id ?? undefined,+ selector: sel.selector,+ selectorIndex: sel.selectorIndex,+ sourceFile: sel.sourceFile,+ key: deriveTimelineStoreKey({+ domId: sel.id ?? undefined,+ selector: sel.selector,+ selectorIndex: sel.selectorIndex,+ sourceFile: sel.sourceFile,+ }),+ };+}++/** A raw iframe sibling in the selection's file; null with no id or selector (z stays live). Its selector index+ * picks it among same-class siblings, the way the lane mirror keys `crossed`. */+function siblingZIndexEntry(+ element: HTMLElement,+ zIndex: number,+ sourceFile: string,+ activeCompPath: string | null,+): ZIndexReorderEntry | null {+ const id = element.id || undefined;+ const selector = buildStableSelector(element);+ if (!canTargetZIndexElement(element, id, selector)) return null;+ const selectorIndex = id+ ? undefined+ : getSelectorIndex(element.ownerDocument, element, selector, sourceFile, activeCompPath);+ return {+ element,+ zIndex,+ id,+ selector,+ selectorIndex,+ sourceFile,+ key: deriveTimelineStoreKey({ domId: id, selector, selectorIndex, sourceFile }),+ };+}++/** Short human-readable label for a dropped sibling, for the console warning below. */+function describeZIndexElement(element: HTMLElement): string {+ if (element.id) return `#${element.id}`;+ const firstClass = element.classList.item(0);+ return firstClass+ ? `${element.tagName.toLowerCase()}.${firstClass}`+ : element.tagName.toLowerCase();+}++// Patches as commit entries; a sibling with no id or selector is `dropped` and reverts on reload.+export function resolveZIndexEntries(+ sel: DomEditSelection,+ patches: ReadonlyArray<{ element: HTMLElement; zIndex: number }>,+ activeCompPath: string | null,+): { entries: ZIndexReorderEntry[]; dropped: Array<{ element: HTMLElement; zIndex: number }> } {+ const entries: ZIndexReorderEntry[] = [];+ const dropped: Array<{ element: HTMLElement; zIndex: number }> = [];+ for (const patch of patches) {+ if (patch.element === sel.element) {+ entries.push(selectedZIndexEntry(sel, patch.zIndex));+ continue;+ }+ const entry = siblingZIndexEntry(patch.element, patch.zIndex, sel.sourceFile, activeCompPath);+ if (entry) entries.push(entry);+ else dropped.push(patch);+ }+ return { entries, dropped };+}++export interface DomEditZOrder {+ /** False in a read-only preview, for an element no longer in the live preview, or at that end of its stacking set. */+ enabled: (sel: DomEditSelection, action: ZOrderAction) => boolean;+ /** Resolve and commit one step; false when nothing is sent to be saved. */+ apply: (sel: DomEditSelection, action: ZOrderAction) => boolean;+ /** Commit patches already resolved (the canvas menu resolves its own); false when none could be sent to be saved. */+ commit: (+ sel: DomEditSelection,+ patches: ReadonlyArray<ZOrderPatch>,+ action: ZOrderAction,+ crossed: HTMLElement | null,+ ) => boolean;+}++/** A selection from before a preview reload holds an element of a document no window shows, with stale z values. */+const isLive = (element: HTMLElement) =>+ element.isConnected && element.ownerDocument.defaultView !== null;++// The canvas menu's z-order (write, undo, lane mirror) for any caller in DomEditProvider.+export function useDomEditZOrder(): DomEditZOrder {+ const { handleDomZIndexReorderCommit } = useDomEditActionsContext();+ const mirrorZOrderToTimeline = useCanvasZOrderTimelineMirror();+ const readOnly = usePreviewReadOnly();+ const activeCompPath = useStudioShellContextOptional()?.activeCompPath ?? null;++ const enabled = useCallback<DomEditZOrder["enabled"]>(+ (sel, action) => !readOnly && isLive(sel.element) && isZOrderActionEnabled(sel.element, action),+ [readOnly],+ );++ const commit = useCallback<DomEditZOrder["commit"]>(+ (sel, patches, action, crossed) => {+ if (readOnly) return false;+ const { entries, dropped } = resolveZIndexEntries(sel, patches, activeCompPath);+ if (dropped.length > 0) {+ // Not writable to source: their live z still applies, so the order renders, until a reload.+ for (const patch of dropped) patch.element.style.zIndex = String(patch.zIndex);+ console.warn(+ "[studio] z-index reorder: dropping sibling(s) with no stable id/selector " ++ "(will revert on reload):",+ dropped.map((patch) => describeZIndexElement(patch.element)).join(", "),+ );+ }+ if (entries.length === 0) return false;+ // One coalesce key for the z write and the lane mirror: one undo entry.+ const coalesceKey = zReorderCoalesceKey(entries, action);+ // One serialized z→lane transaction: the mirror runs only AFTER a durable z commit and+ // no second gesture interleaves (see runZLaneGesture). A failed z commit has already+ // toasted and rolled back, so the catch only keeps its rejection from going unhandled.+ runZLaneGesture({+ commitZ: () => handleDomZIndexReorderCommit(entries, coalesceKey, action),+ mirror: () =>+ mirrorZOrderToTimeline({+ selectionKey: entries.find((e) => e.element === sel.element)?.key,+ action,+ crossed,+ sourceFile: sel.sourceFile,+ coalesceKey,+ }),+ }).catch(() => undefined);+ return true;+ },+ [activeCompPath, handleDomZIndexReorderCommit, mirrorZOrderToTimeline, readOnly],+ );++ const apply = useCallback<DomEditZOrder["apply"]>(+ (sel, action) => {+ if (!isLive(sel.element)) return false;+ const step = resolveZOrderStep(sel.element, action);+ return step !== null && commit(sel, step.patches, action, step.crossed);+ },+ [commit],+ );++ return useMemo(() => ({ enabled, apply, commit }), [enabled, apply, commit]);+}diff --git a/packages/studio/src/components/nle/PreviewOverlaysTestMocks.ts b/packages/studio/src/components/nle/PreviewOverlaysTestMocks.tsindex dddea3fd65..356d031770 100644--- a/packages/studio/src/components/nle/PreviewOverlaysTestMocks.ts+++ b/packages/studio/src/components/nle/PreviewOverlaysTestMocks.ts@@ -8,6 +8,10 @@ export const iframeRef = { current: null as HTMLIFrameElement | null };vi.mock("../../contexts/StudioContext", () => ({useStudioShellContext: () => ({ activeCompPath: "index.html", previewIframeRef: iframeRef }),+ useStudioShellContextOptional: () => ({+ activeCompPath: "index.html",+ previewIframeRef: iframeRef,+ }),useStudioPlaybackContext: () => ({captionEditMode: previewState.captionEditMode,compositionLoading: false,diff --git a/packages/studio/src/domEditExports.test.tsx b/packages/studio/src/domEditExports.test.tsxindex 4536914b2f..f67a900730 100644--- a/packages/studio/src/domEditExports.test.tsx+++ b/packages/studio/src/domEditExports.test.tsx@@ -9,13 +9,17 @@ import {PreviewReadOnlyProvider,useDomEditSelectionContext,useDomEditSession,+ useDomEditZOrder,usePreviewPersistence,type ConnectedDomEditOverlayProps,type DomEditCapabilities,type DomEditSelection,+ type DomEditZOrder,type UseDomEditSessionParams,type UsePreviewPersistenceParams,+ type ZOrderAction,} from "@hyperframes/studio";+import { makeSelection } from "./hooks/domSelectionTestHarness";Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });@@ -66,4 +70,92 @@ describe("DOM editing package exports", () => {expect(canvas?.className).toContain("pointer-events-none");await act(async () => root.unmount());});++ it("gives a host the canvas menu's z-order: enabled, then one step through the session's commit", async () => {+ const parent = document.createElement("div");+ const back = document.createElement("div");+ back.id = "back";+ const front = document.createElement("div");+ front.id = "front";+ parent.append(back, front);+ document.body.append(parent);+ const commitZ = vi.fn(() => Promise.resolve());+ const session = {+ handleDomZIndexReorderCommit: commitZ,+ } as unknown as Parameters<typeof DomEditProvider>[0]["value"];+ let zOrder: DomEditZOrder | undefined;+ function Probe() {+ zOrder = useDomEditZOrder();+ return null;+ }+ const el = document.createElement("div");+ document.body.append(el);+ const root = createRoot(el);+ await act(async () =>+ root.render(+ <DomEditProvider value={session}>+ <Probe />+ </DomEditProvider>,+ ),+ );+ const sel = makeSelection("Back", back);+ const toFront: ZOrderAction = "bring-to-front";+ expect(zOrder?.enabled(sel, "send-to-back")).toBe(false);+ expect(zOrder?.enabled(sel, toFront)).toBe(true);+ expect(zOrder?.apply(sel, "send-to-back")).toBe(false);+ expect(commitZ).not.toHaveBeenCalled();+ await act(async () => {+ expect(zOrder?.apply(sel, toFront)).toBe(true);+ });+ expect(commitZ).toHaveBeenCalledTimes(1);+ expect(commitZ).toHaveBeenCalledWith(+ expect.arrayContaining([expect.objectContaining({ element: back, id: "back" })]),+ expect.stringContaining(toFront),+ toFront,+ );+ await act(async () => root.unmount());+ parent.remove();+ });++ it("gives a read-only preview or a detached element no z-order, and never asks the session", async () => {+ const parent = document.createElement("div");+ const back = document.createElement("div");+ back.id = "back";+ parent.append(back, document.createElement("div"));+ document.body.append(parent);+ const commitZ = vi.fn(() => Promise.resolve());+ const session = {+ handleDomZIndexReorderCommit: commitZ,+ } as unknown as Parameters<typeof DomEditProvider>[0]["value"];+ let zOrder: DomEditZOrder | undefined;+ function Probe() {+ zOrder = useDomEditZOrder();+ return null;+ }+ const el = document.body.appendChild(document.createElement("div"));+ const root = createRoot(el);+ const mount = (readOnly: boolean) =>+ act(async () =>+ root.render(+ <PreviewReadOnlyProvider readOnly={readOnly}>+ <DomEditProvider value={session}>+ <Probe />+ </DomEditProvider>+ </PreviewReadOnlyProvider>,+ ),+ );+ const sel = makeSelection("Back", back);+ await mount(true);+ expect(zOrder?.enabled(sel, "bring-to-front")).toBe(false);+ expect(zOrder?.apply(sel, "bring-to-front")).toBe(false);+ expect(zOrder?.commit(sel, [{ element: back, zIndex: 1 }], "bring-to-front", null)).toBe(false);+ await mount(false);+ // A reload leaves the old nodes connected to their old document, one no window shows.+ document.implementation.createHTMLDocument().body.append(parent);+ expect(back.isConnected).toBe(true);+ expect(zOrder?.enabled(sel, "bring-to-front"), "a selection from before a reload").toBe(false);+ expect(zOrder?.apply(sel, "bring-to-front")).toBe(false);+ expect(commitZ).not.toHaveBeenCalled();+ await act(async () => root.unmount());+ });});diff --git a/packages/studio/src/hooks/useDomEditCommits.test.tsx b/packages/studio/src/hooks/useDomEditCommits.test.tsxindex 6e118c35c8..cd6cba745f 100644--- a/packages/studio/src/hooks/useDomEditCommits.test.tsx+++ b/packages/studio/src/hooks/useDomEditCommits.test.tsx@@ -42,6 +42,7 @@ interface RenderDomEditCommitsOptions {onTrySdkPersist?: () => Promise<CutoverResult>;queueDomEditSave?: <T>(save: () => Promise<T>) => Promise<T>;projectIdRef?: MutableRefObject<string | null>;+ readOnlyPreview?: boolean;}type FetchHandler = (@@ -232,7 +233,7 @@ function renderDomEditCommits(target === selection.element ? selection : null,),onTrySdkPersist: options.onTrySdkPersist,- readOnlyPreview: false,+ readOnlyPreview: options.readOnlyPreview ?? false,});return null;}@@ -266,97 +267,100 @@ describe("useDomEditCommits z-index reorder persistence", () => {document.body.replaceChildren();});- it("persists an N-element reorder with one batch POST, one undo entry, and NO iframe reload", async () => {- const original =- '<div id="a" style="z-index: 1"></div><div id="b" style="z-index: 2"></div><div id="c" style="z-index: 3"></div>';- const after =- '<div id="a" style="z-index: 3"></div><div id="b" style="z-index: 2"></div><div id="c" style="z-index: 1"></div>';- const fetchMock = vi.fn(- async (- input: Parameters<typeof fetch>[0],- _init?: Parameters<typeof fetch>[1],- ): Promise<Response> => {- const url = requestUrl(input);- if (url.endsWith("/file-mutations/patch-element-batches")) {- return jsonResponse({- durable: true,- files: [- {- sourceFile: "index.html",- changed: true,- matched: [true, true, true],- before: original,- after,- },- ],- });- }- throw new Error(`Unexpected fetch: ${url}`);- },- );- vi.stubGlobal("fetch", fetchMock);- const { iframe, element } = createPreviewElement(- '<div data-hf-id="hf-card"></div><div id="b"></div><div id="c"></div>',- );- element.id = "a";- const elements = [- element,- iframe.contentDocument!.getElementById("b")!,- iframe.contentDocument!.getElementById("c")!,- ];- const rendered = renderDomEditCommits(createSelection(element), iframe);-- try {- await act(async () => {- await rendered.hook.handleDomZIndexReorderCommit(- elements.map((item, index) => ({- element: item,- zIndex: 3 - index,- id: item.id,- sourceFile: "index.html",- })),- "z-reorder:test",- );- });-- const batchPosts = fetchMock.mock.calls.filter(([input]) =>- requestUrl(input).endsWith("/file-mutations/patch-element-batches"),+ it.each([false, true])(+ "persists an N-element reorder with one batch POST, one undo entry, and NO iframe reload (read-only preview %s: the timeline's z sync stays editable)",+ async (readOnlyPreview) => {+ const original =+ '<div id="a" style="z-index: 1"></div><div id="b" style="z-index: 2"></div><div id="c" style="z-index: 3"></div>';+ const after =+ '<div id="a" style="z-index: 3"></div><div id="b" style="z-index: 2"></div><div id="c" style="z-index: 1"></div>';+ const fetchMock = vi.fn(+ async (+ input: Parameters<typeof fetch>[0],+ _init?: Parameters<typeof fetch>[1],+ ): Promise<Response> => {+ const url = requestUrl(input);+ if (url.endsWith("/file-mutations/patch-element-batches")) {+ return jsonResponse({+ durable: true,+ files: [+ {+ sourceFile: "index.html",+ changed: true,+ matched: [true, true, true],+ before: original,+ after,+ },+ ],+ });+ }+ throw new Error(`Unexpected fetch: ${url}`);+ },);- const singlePosts = fetchMock.mock.calls.filter(([input]) =>- requestUrl(input).includes("/file-mutations/patch-elements-batch/"),+ vi.stubGlobal("fetch", fetchMock);+ const { iframe, element } = createPreviewElement(+ '<div data-hf-id="hf-card"></div><div id="b"></div><div id="c"></div>',);- expect(batchPosts).toHaveLength(1);- expect(singlePosts).toHaveLength(0);- expect(JSON.parse(String(batchPosts[0]?.[1]?.body))).toEqual({- batches: [- {- sourceFile: "index.html",- patches: expect.arrayContaining([- expect.objectContaining({ target: expect.objectContaining({ id: "a" }) }),- expect.objectContaining({ target: expect.objectContaining({ id: "b" }) }),- expect.objectContaining({ target: expect.objectContaining({ id: "c" }) }),- ]),- },- ],- });- expect(rendered.recordEdit).toHaveBeenCalledTimes(1);- expect(rendered.recordEdit).toHaveBeenCalledWith({- label: "Reorder layers",- coalesceKey: "z-reorder:test",- // Unbounded per-gesture fold window (keys are unique per gesture):- // the z entry and its mirror/lane counterpart fold across the server- // round-trip that separates them.- coalesceMs: Number.POSITIVE_INFINITY,- files: { "index.html": { before: original, after } },- });- // FIX: a z-only reorder must NOT remount the preview iframe ("the blink").- // The live DOM + store already hold the final state and the server matched- // every style-only patch, so the reload is provably redundant.- expect(rendered.reloadPreview).not.toHaveBeenCalled();- } finally {- rendered.cleanup();- }- });+ element.id = "a";+ const elements = [+ element,+ iframe.contentDocument!.getElementById("b")!,+ iframe.contentDocument!.getElementById("c")!,+ ];+ const rendered = renderDomEditCommits(createSelection(element), iframe, { readOnlyPreview });++ try {+ await act(async () => {+ await rendered.hook.handleDomZIndexReorderCommit(+ elements.map((item, index) => ({+ element: item,+ zIndex: 3 - index,+ id: item.id,+ sourceFile: "index.html",+ })),+ "z-reorder:test",+ );+ });++ const batchPosts = fetchMock.mock.calls.filter(([input]) =>+ requestUrl(input).endsWith("/file-mutations/patch-element-batches"),+ );+ const singlePosts = fetchMock.mock.calls.filter(([input]) =>+ requestUrl(input).includes("/file-mutations/patch-elements-batch/"),+ );+ expect(batchPosts).toHaveLength(1);+ expect(singlePosts).toHaveLength(0);+ expect(JSON.parse(String(batchPosts[0]?.[1]?.body))).toEqual({+ batches: [+ {+ sourceFile: "index.html",+ patches: expect.arrayContaining([+ expect.objectContaining({ target: expect.objectContaining({ id: "a" }) }),+ expect.objectContaining({ target: expect.objectContaining({ id: "b" }) }),+ expect.objectContaining({ target: expect.objectContaining({ id: "c" }) }),+ ]),+ },+ ],+ });+ expect(rendered.recordEdit).toHaveBeenCalledTimes(1);+ expect(rendered.recordEdit).toHaveBeenCalledWith({+ label: "Reorder layers",+ coalesceKey: "z-reorder:test",+ // Unbounded per-gesture fold window (keys are unique per gesture):+ // the z entry and its mirror/lane counterpart fold across the server+ // round-trip that separates them.+ coalesceMs: Number.POSITIVE_INFINITY,+ files: { "index.html": { before: original, after } },+ });+ // FIX: a z-only reorder must NOT remount the preview iframe ("the blink").+ // The live DOM + store already hold the final state and the server matched+ // every style-only patch, so the reload is provably redundant.+ expect(rendered.reloadPreview).not.toHaveBeenCalled();+ } finally {+ rendered.cleanup();+ }+ },+ );it("falls back to reloading when the server response omits matched[]", async () => {// Without a matched[] confirmation the persist can't be proven in sync withdiff --git a/packages/studio/src/index.ts b/packages/studio/src/index.tsindex 9a3434ce97..2f6dff8f85 100644--- a/packages/studio/src/index.ts+++ b/packages/studio/src/index.ts@@ -187,6 +187,9 @@ export { DomEditProvider, useDomEditSelectionContext } from "./contexts/DomEditCexport { PreviewReadOnlyProvider } from "./components/editor/previewReadOnlyContext";export { ConnectedDomEditOverlay } from "./components/editor/ConnectedDomEditOverlay";export type { ConnectedDomEditOverlayProps } from "./components/editor/ConnectedDomEditOverlay";+export { useDomEditZOrder } from "./components/editor/useDomEditZOrder";+export type { DomEditZOrder } from "./components/editor/useDomEditZOrder";+export type { ZOrderAction } from "./components/editor/canvasContextMenuZOrder";export type { DomEditCapabilities, DomEditSelection } from "./components/editor/domEditingTypes";export { useDomStyleCommit } from "./hooks/useDomStyleCommit";export type { UseDomStyleCommitOptions } from "./hooks/useDomStyleCommit";