Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): export DOM editing for a host outside EditorShell (#4640)
Miguel Ángel2251e5fad01f
diff --git a/packages/studio/src/components/editor/CanvasContextMenu.test.tsx b/packages/studio/src/components/editor/CanvasContextMenu.test.tsxindex ccb00a088f..f67372a086 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 "../nle/PreviewOverlays";+import { resolveZIndexEntries } from "./ConnectedDomEditOverlay";import { useElementLifecycleOps } from "../../hooks/useElementLifecycleOps";import { makeLifecycleOpsParams } from "../../hooks/elementLifecycleOpsTestUtils";import type { DomEditPatchBatch } from "../../hooks/domEditCommitTypes";@@ -138,7 +138,7 @@ describe("CanvasContextMenu — handler gating", () => {});});-// ── Menu z-action → commit path (wired the way PreviewOverlays wires the app) ──+// ── Menu z-action → commit path (wired the way ConnectedDomEditOverlay wires the app) ──function pressMenuItem(label: string) {const button = zOrderButtons().find((b) => b.textContent === label);@@ -200,7 +200,7 @@ describe("CanvasContextMenu — z-action commit path", () => {const captured: CapturedBatchCall[] = [];const { commit, cleanup } = renderCommitHook(captured);- // Wire onApplyZIndex the way the app does (PreviewOverlays → the commit+ // Wire onApplyZIndex the way the app does (ConnectedDomEditOverlay → the commit// hook), asserting the menu has NOT touched the DOM when it fires — the// hook must capture true pre-change styles for its rollback.const stylesAtApply: Array<{ zIndex: string; position: string }> = [];diff --git a/packages/studio/src/components/editor/CanvasContextMenu.tsx b/packages/studio/src/components/editor/CanvasContextMenu.tsxindex a042c44c42..f1a5947f67 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. PreviewOverlays.tsx builds the per-patch PatchTargets (the selected+ * path. ConnectedDomEditOverlay.tsx 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.diff --git a/packages/studio/src/components/editor/ConnectedDomEditOverlay.test.tsx b/packages/studio/src/components/editor/ConnectedDomEditOverlay.test.tsxnew file mode 100644index 0000000000..cc0888d3cb--- /dev/null+++ b/packages/studio/src/components/editor/ConnectedDomEditOverlay.test.tsx@@ -0,0 +1,163 @@+// @vitest-environment happy-dom++import React, { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import { getPreviewState, iframeRef } from "../nle/PreviewOverlaysTestMocks";+import { PreviewOverlays } from "../nle/PreviewOverlays";+import { ConnectedDomEditOverlay } from "./ConnectedDomEditOverlay";++// Overlay prop -> session handler, as PreviewOverlays wired DomEditOverlay itself.+const WIRING = {+ onCanvasMouseDown: "handlePreviewCanvasMouseDown",+ onCanvasPointerMove: "handlePreviewCanvasPointerMove",+ onCanvasPointerLeave: "handlePreviewCanvasPointerLeave",+ onSelectionChange: "applyDomSelection",+ onBlockedMove: "handleBlockedDomMove",+ onManualDragStart: "handleDomManualDragStart",+ onPathOffsetCommit: "handleDomPathOffsetCommit",+ onGroupPathOffsetCommit: "handleDomGroupPathOffsetCommit",+ onBoxSizeCommit: "handleDomBoxSizeCommit",+ onRotationCommit: "handleDomRotationCommit",+ onStyleCommit: "handleDomStyleCommit",+ onDeleteSelection: "handleDomEditElementDelete",+ onMarqueeSelect: "applyMarqueeSelection",+} as const;++const ctx = vi.hoisted(() => ({+ overlayProps: null as Record<string, unknown> | null,+ actions: {} as Record<string, unknown>,+ selection: {+ domEditHoverSelection: { label: "hover" },+ domEditSelection: { label: "selected" },+ domEditGroupSelections: [{ label: "member" }],+ },+}));++vi.mock("../../contexts/DomEditContext", () => ({+ useDomEditSelectionContext: () => ctx.selection,+ useDomEditActionsContext: () => ctx.actions,+}));+vi.mock("./DomEditOverlay", () => ({+ DomEditOverlay: (props: Record<string, unknown>) => {+ ctx.overlayProps = props;+ return null;+ },+}));+vi.mock("./TopologyLens", () => ({ TopologyLens: () => null }));+vi.mock("./MotionPathOverlay", () => ({ MotionPathOverlay: () => null }));+vi.mock("./SnapToolbar", () => ({ SnapToolbar: () => null }));+vi.mock("./GridOverlay", () => ({ GridOverlay: () => null }));++(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root;++function mount(node: React.ReactNode): Record<string, unknown> {+ ctx.actions = {+ previewIframeRef: iframeRef,+ handleDomZIndexReorderCommit: vi.fn(() => Promise.resolve(undefined)),+ };+ for (const name of Object.values(WIRING)) ctx.actions[name] = vi.fn();+ const host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+ act(() => root.render(node));+ return ctx.overlayProps!;+}++afterEach(() => {+ act(() => root.unmount());+ ctx.overlayProps = null;+ getPreviewState().isPlaying = false;+ document.body.replaceChildren();+});++describe("ConnectedDomEditOverlay", () => {+ it("is what PreviewOverlays renders, with every handler from the session", () => {+ const props = mount(+ <PreviewOverlays+ shouldShowMotionPath={false}+ shouldShowSelectedDomBounds={true}+ recordingState={"idle" as never}+ onToggleRecording={vi.fn()}+ />,+ );+ // The overlay never read these, so the connected wrapper does not pass them.+ expect(props).not.toHaveProperty("recordingState");+ expect(props).not.toHaveProperty("onToggleRecording");+ for (const [prop, handler] of Object.entries(WIRING)) {+ expect(props[prop], prop).toBe(ctx.actions[handler]);+ }+ expect(props).toMatchObject({+ iframeRef,+ activeCompositionPath: "index.html",+ hoverSelection: ctx.selection.domEditHoverSelection,+ selection: ctx.selection.domEditSelection,+ groupSelections: ctx.selection.domEditGroupSelections,+ allowCanvasMovement: true,+ canvasInput: undefined,+ onTextEditingChange: undefined,+ });+ });++ it("shows no hover box while playback runs", () => {+ getPreviewState().isPlaying = true;+ const props = mount(+ <PreviewOverlays shouldShowMotionPath={false} shouldShowSelectedDomBounds={true} />,+ );+ expect(props.hoverSelection).toBeNull();+ expect(props.selection).toBe(ctx.selection.domEditSelection);+ });++ it("hides the selection and stops movement while a gesture records", () => {+ const props = mount(+ <PreviewOverlays+ shouldShowMotionPath={false}+ shouldShowSelectedDomBounds={false}+ isGestureRecording={true}+ />,+ );+ expect(props).toMatchObject({+ selection: null,+ groupSelections: [],+ allowCanvasMovement: false,+ });+ });++ it("persists a z-order change through the session's reorder commit", () => {+ const props = mount(+ <PreviewOverlays shouldShowMotionPath={false} shouldShowSelectedDomBounds={true} />,+ );+ const element = document.createElement("div");+ element.id = "card";+ const sel = { element, id: "card", selector: "#card", sourceFile: "index.html" };+ const apply = props.onApplyZIndex as (...args: unknown[]) => void;+ act(() => apply(sel, [{ element, zIndex: 4 }], "bring-forward", null));+ expect(ctx.actions.handleDomZIndexReorderCommit).toHaveBeenCalledWith(+ [expect.objectContaining({ element, zIndex: 4, id: "card", sourceFile: "index.html" })],+ expect.stringContaining("z-reorder:bring-forward"),+ "bring-forward",+ );+ });++ it("passes a host's canvas input, text-editing listener and hover gate to the overlay", () => {+ const onTextEditingChange = vi.fn();+ const props = mount(+ <ConnectedDomEditOverlay+ activeCompositionPath={null}+ showHoverSelection={false}+ shouldShowSelectedDomBounds={true}+ canvasInput="host"+ onTextEditingChange={onTextEditingChange}+ />,+ );+ expect(props).toMatchObject({+ canvasInput: "host",+ onTextEditingChange,+ hoverSelection: null,+ selection: ctx.selection.domEditSelection,+ iframeRef,+ });+ });+});diff --git a/packages/studio/src/components/editor/ConnectedDomEditOverlay.tsx b/packages/studio/src/components/editor/ConnectedDomEditOverlay.tsxnew file mode 100644index 0000000000..f677c46c2c--- /dev/null+++ b/packages/studio/src/components/editor/ConnectedDomEditOverlay.tsx@@ -0,0 +1,206 @@+import type { ComponentProps } from "react";+import { DomEditOverlay } from "./DomEditOverlay";+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";++type HostInputProps = Pick<+ ComponentProps<typeof DomEditOverlay>,+ "canvasInput" | "onSelectionBoxClick"+>;++export interface ConnectedDomEditOverlayProps extends HostInputProps {+ activeCompositionPath: string | null;+ showHoverSelection: boolean;+ shouldShowSelectedDomBounds: boolean;+ isGestureRecording?: boolean;+ /** True when an in-place text edit opens its caret, false when it ends or unmounts. */+ 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({+ activeCompositionPath,+ showHoverSelection,+ shouldShowSelectedDomBounds,+ isGestureRecording,+ canvasInput,+ onTextEditingChange,+ onSelectionBoxClick,+}: ConnectedDomEditOverlayProps) {+ const { domEditHoverSelection, domEditSelection, domEditGroupSelections } =+ useDomEditSelectionContext();+ const {+ previewIframeRef,+ handlePreviewCanvasMouseDown,+ handlePreviewCanvasPointerMove,+ handlePreviewCanvasPointerLeave,+ applyDomSelection,+ handleBlockedDomMove,+ handleDomManualDragStart,+ handleDomPathOffsetCommit,+ handleDomGroupPathOffsetCommit,+ handleDomBoxSizeCommit,+ handleDomRotationCommit,+ handleDomStyleCommit,+ applyMarqueeSelection,+ handleDomEditElementDelete,+ handleDomZIndexReorderCommit,+ } = useDomEditActionsContext();+ const mirrorZOrderToTimeline = useCanvasZOrderTimelineMirror();++ return (+ <DomEditOverlay+ iframeRef={previewIframeRef}+ activeCompositionPath={activeCompositionPath}+ hoverSelection={showHoverSelection ? domEditHoverSelection : null}+ selection={shouldShowSelectedDomBounds ? domEditSelection : null}+ groupSelections={shouldShowSelectedDomBounds ? domEditGroupSelections : []}+ allowCanvasMovement={!isGestureRecording}+ canvasInput={canvasInput}+ onTextEditingChange={onTextEditingChange}+ onSelectionBoxClick={onSelectionBoxClick}+ onCanvasMouseDown={handlePreviewCanvasMouseDown}+ onCanvasPointerMove={handlePreviewCanvasPointerMove}+ onCanvasPointerLeave={handlePreviewCanvasPointerLeave}+ onSelectionChange={applyDomSelection}+ onBlockedMove={handleBlockedDomMove}+ onManualDragStart={handleDomManualDragStart}+ onPathOffsetCommit={handleDomPathOffsetCommit}+ onGroupPathOffsetCommit={handleDomGroupPathOffsetCommit}+ onBoxSizeCommit={handleDomBoxSizeCommit}+ 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);+ }}+ onMarqueeSelect={applyMarqueeSelection}+ />+ );+}diff --git a/packages/studio/src/components/editor/DomEditOverlay.tsx b/packages/studio/src/components/editor/DomEditOverlay.tsxindex 8586fc8442..61421d72de 100644--- a/packages/studio/src/components/editor/DomEditOverlay.tsx+++ b/packages/studio/src/components/editor/DomEditOverlay.tsx@@ -54,6 +54,14 @@ interface DomEditOverlayProps {groupSelections?: DomEditSelection[];hoverSelection: DomEditSelection | null;allowCanvasMovement?: boolean;+ /** "host": no hover, marquee or box re-select; Enter with nothing focused still opens text. */+ canvasInput?: "overlay" | "host";+ onTextEditingChange?: (editing: boolean) => void;+ /** A click on a single selection's box, in either mode; the event may be the pointerup. */+ onSelectionBoxClick?: (+ event: React.MouseEvent<HTMLDivElement>,+ selection: DomEditSelection,+ ) => void;onCanvasMouseDown: (event: React.MouseEvent<HTMLDivElement>,options?: PreviewMouseDownOptions,@@ -117,7 +125,10 @@ export const DomEditOverlay = memo(function DomEditOverlay({groupSelections = [],hoverSelection,allowCanvasMovement = true,- onCanvasMouseDown,+ canvasInput = "overlay",+ onTextEditingChange,+ onSelectionBoxClick,+ onCanvasMouseDown: onCanvasMouseDownProp,onCanvasPointerMove,onCanvasPointerLeave,onSelectionChange,@@ -133,6 +144,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({onApplyZIndex,}: DomEditOverlayProps) {const readOnly = usePreviewReadOnly();+ const hostInput = canvasInput === "host";const overlayRef = useRef<HTMLDivElement | null>(null);const boxRef = useRef<HTMLDivElement | null>(null);const onMarqueeSelectRef = useRef(onMarqueeSelect);@@ -150,6 +162,13 @@ export const DomEditOverlay = memo(function DomEditOverlay({const selectionRef = useRef(selection);selectionRef.current = selection;+ const onCanvasMouseDown: typeof onCanvasMouseDownProp = (event, options) => {+ const sel = selectionRef.current;+ if (sel && boxRef.current?.contains(event.target as Node | null)) {+ onSelectionBoxClick?.(event, sel);+ }+ if (!hostInput) onCanvasMouseDownProp(event, options);+ };// Brief highlight on the sibling a forward/backward z step crossed — drawn// in this studio overlay, never in the iframe DOM (see useZOrderCrossedFlash).@@ -163,7 +182,14 @@ export const DomEditOverlay = memo(function DomEditOverlay({hoverSelectionRef.current = hoverSelection;// Double-click an element to edit its text where it sits.- const inlineText = useInlineTextEditing(selectionRef);+ const inlineText = useInlineTextEditing(selectionRef, { enterFromWindow: hostInput });+ const onTextEditingChangeRef = useRef(onTextEditingChange);+ onTextEditingChangeRef.current = onTextEditingChange;+ useEffect(() => {+ if (!inlineText.editing) return;+ onTextEditingChangeRef.current?.(true);+ return () => onTextEditingChangeRef.current?.(false);+ }, [inlineText.editing]);const onPathOffsetCommitRef = useRef(onPathOffsetCommit);onPathOffsetCommitRef.current = onPathOffsetCommit;const onGroupPathOffsetCommitRef = useRef(onGroupPathOffsetCommit);@@ -322,7 +348,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({// fallow-ignore-next-line complexityconst handleOverlayPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {- if (!allowCanvasMovement || event.button !== 0) return;+ if (!allowCanvasMovement || hostInput || event.button !== 0) return;if (event.shiftKey) {const shiftIframe = iframeRef.current;const candidate = resolveShiftClickCandidate({@@ -428,7 +454,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({// Standing aside is the only way the caret below can be reached, and is// what keeps selection, drag and marquee from firing mid-edit.className={`absolute inset-0 z-10 outline-hidden ${- inlineText.editing ? "pointer-events-none" : "pointer-events-auto"+ inlineText.editing || hostInput ? "pointer-events-none" : "pointer-events-auto"}`}data-editing-text={inlineText.editing ? "true" : undefined}tabIndex={-1}@@ -439,6 +465,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({// A pointer gesture supersedes a pending nudge burst — commit it first// so the gesture's member snapshot starts from the nudged position.flushNudge();+ suppressNextBoxClickRef.current = false;// Not while editing: taking focus back would send the keystroke nowhere.if (!inlineText.editing) {focusDomEditOverlayElement(event.currentTarget as FocusableDomEditOverlay);@@ -455,9 +482,9 @@ export const DomEditOverlay = memo(function DomEditOverlay({onPointerLeave={() => onCanvasPointerLeaveRef.current()}onPointerUp={marquee.onPointerUp}onPointerCancel={marquee.onPointerCancel}- onContextMenu={handleContextMenu}+ onContextMenu={hostInput ? undefined : handleContextMenu}>- {hoverSelection && hoverRect && compRect.width > 0 && (+ {!hostInput && hoverSelection && hoverRect && compRect.width > 0 && (<divaria-hidden="true"data-dom-edit-hover-box="true"@@ -504,7 +531,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({editing session, which does. */}{inlineText.toolbar}<OffCanvasIndicators- rects={offCanvasRects}+ rects={hostInput ? [] : offCanvasRects}elements={offCanvasElementsRef}compRect={compRect}selection={selection}diff --git a/packages/studio/src/components/editor/LayersPanel.tsx b/packages/studio/src/components/editor/LayersPanel.tsxindex 6063b5d627..f465c03326 100644--- a/packages/studio/src/components/editor/LayersPanel.tsx+++ b/packages/studio/src/components/editor/LayersPanel.tsx@@ -343,7 +343,7 @@ export const LayersPanel = memo(function LayersPanel() {// ONE undo entry for the whole gesture: the z persist and the timeline// lane mirror below share this per-gesture-unique key (same contract as- // the canvas menu's wiring in PreviewOverlays).+ // the canvas menu's wiring in ConnectedDomEditOverlay).const coalesceKey = zReorderCoalesceKey(entries, "layer-drag");const desiredOrderKeys = desiredBottomToTop.map((l) =>diff --git a/packages/studio/src/components/editor/previewReadOnly.overlay.test.tsx b/packages/studio/src/components/editor/previewReadOnly.overlay.test.tsxindex 5b48cf76a1..7d187572b3 100644--- a/packages/studio/src/components/editor/previewReadOnly.overlay.test.tsx+++ b/packages/studio/src/components/editor/previewReadOnly.overlay.test.tsx@@ -13,7 +13,19 @@ import { DomEditOverlay } from "./DomEditOverlay";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const RECT = { left: 100, top: 100, width: 200, height: 100, editScaleX: 1, editScaleY: 1 };-const layout = vi.hoisted(() => ({ group: [] as unknown[] }));+const layout = vi.hoisted(() => ({+ group: [] as unknown[],+ hover: null as unknown,+ offCanvas: [] as unknown[],+ offCanvasElements: new Map<string, HTMLElement>(),+}));++vi.mock("./useOffCanvasIndicators", () => ({+ useOffCanvasIndicators: () => ({+ offCanvasRects: layout.offCanvas,+ offCanvasElementsRef: { current: layout.offCanvasElements },+ }),+}));vi.mock("./useDomEditOverlayRects", () => ({useDomEditOverlayRects: () => ({@@ -22,7 +34,7 @@ vi.mock("./useDomEditOverlayRects", () => ({current: { left: 100, top: 100, width: 200, height: 100, editScaleX: 1, editScaleY: 1 },},setOverlayRect: () => undefined,- hoverRect: null,+ hoverRect: layout.hover,groupOverlayItems: layout.group,groupOverlayItemsRef: { current: layout.group },setGroupOverlayItems: () => undefined,@@ -57,6 +69,8 @@ function fixture(onStyleCommit: vi.fn(),onDeleteSelection: vi.fn(),onApplyZIndex: vi.fn(),+ onMarqueeSelect: vi.fn(),+ onTextEditingChange: vi.fn(),};const selection = makeSelection("Title", textElement("title"));selection.capabilities.canApplyManualRotation = true;@@ -92,6 +106,33 @@ const fire = (target: Element, type: string, init: MouseEventInit = {}) => {return event;};+const pressEnter = (overlay: HTMLElement) =>+ act(() => {+ overlay.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }),+ );+ });++const clickBox = (overlay: HTMLElement) => {+ const box = overlay.querySelector(BOX)!;+ for (const type of ["pointerdown", "pointerup", "click"]) fire(box, type);+};++const enterOn = (target: Element) =>+ act(() => {+ target.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }),+ );+ });++const rightClick = async (overlay: HTMLElement) => {+ await act(async () => {+ overlay.dispatchEvent(+ new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }),+ );+ });+};+beforeEach(() => {vi.useFakeTimers();__resetForTests();@@ -102,6 +143,9 @@ afterEach(() => {act(() => root.unmount());document.body.innerHTML = "";layout.group = [];+ layout.hover = null;+ layout.offCanvas = [];+ layout.offCanvasElements.clear();vi.useRealTimers();});@@ -196,13 +240,6 @@ describe("DomEditOverlay with the preview read-only", () => {expect(spies.onPathOffsetCommit).not.toHaveBeenCalled();});- const pressEnter = (overlay: HTMLElement) =>- act(() => {- overlay.dispatchEvent(- new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }),- );- });-it("control: with the flag off Enter opens the text for editing", () => {const { selection, overlay } = fixture();pressEnter(overlay);@@ -215,14 +252,6 @@ describe("DomEditOverlay with the preview read-only", () => {expect(selection.element.hasAttribute("contenteditable")).toBe(false);});- const rightClick = async (overlay: HTMLElement) => {- await act(async () => {- overlay.dispatchEvent(- new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }),- );- });- };-it("control: with the flag off right-click offers delete and z-order", async () => {const { overlay } = fixture();await rightClick(overlay);@@ -258,3 +287,177 @@ describe("DomEditOverlay with the preview read-only", () => {expect(spies.onCanvasMouseDown).toHaveBeenCalledTimes(1);});});++describe("DomEditOverlay with canvasInput host", () => {+ const HOST = { canvasInput: "host" } as const;++ it("lets presses through its root, and the overlay default keeps them", () => {+ expect(fixture().overlay.className).toContain("pointer-events-auto");+ act(() => root.unmount());+ expect(fixture(HOST).overlay.className).toContain("pointer-events-none");+ });++ it("draws no hover box", () => {+ layout.hover = RECT;+ const hovered = (props = {}) => {+ const { overlay } = fixture(props);+ const box = overlay.querySelector('[data-dom-edit-hover-box="true"]');+ act(() => root.unmount());+ return box;+ };+ const selection = makeSelection("Hover", textElement("hover"));+ expect(hovered({ hoverSelection: selection })).not.toBeNull();+ expect(hovered({ ...HOST, hoverSelection: selection })).toBeNull();+ });++ it("starts no marquee and makes no selection from a press on empty canvas", () => {+ const off = fixture({ selection: null });+ fire(off.overlay, "pointerdown");+ fire(off.overlay, "pointerup");+ expect(off.spies.onMarqueeSelect).toHaveBeenCalledWith([], false);+ act(() => root.unmount());+ const { spies, overlay } = fixture({ ...HOST, selection: null });+ fire(overlay, "pointerdown");+ fire(overlay, "mousedown");+ fire(overlay, "pointerup");+ expect(spies.onMarqueeSelect).not.toHaveBeenCalled();+ expect(spies.onCanvasMouseDown).not.toHaveBeenCalled();+ });++ it("opens no context menu and selects nothing on right-click", async () => {+ const { spies, overlay } = fixture({ ...HOST, selection: null });+ await rightClick(overlay);+ expect(spies.onSelectionChange).not.toHaveBeenCalled();+ act(() => root.unmount());+ await rightClick(fixture(HOST).overlay);+ expect(document.body.textContent).not.toContain("Delete");+ });++ it("does not re-select on a click of the selection box", () => {+ const off = fixture();+ clickBox(off.overlay);+ expect(off.spies.onCanvasMouseDown).toHaveBeenCalledTimes(1);+ act(() => root.unmount());+ const { spies, overlay } = fixture(HOST);+ clickBox(overlay);+ fire(overlay.querySelector(BOX)!, "click");+ expect(spies.onCanvasMouseDown).not.toHaveBeenCalled();+ });++ it("offers no off-canvas indicator to press, so nothing re-selects from one", async () => {+ const MARK = '[aria-label="Select off-canvas element stray"]';+ const offCanvas = (props = {}) => {+ layout.offCanvasElements.set("stray", textElement("stray"));+ layout.offCanvas = [{ key: "stray", left: 820, top: 10, width: 120, height: 40 }];+ return fixture(props);+ };+ const off = offCanvas();+ fire(off.overlay.querySelector(MARK)!, "click");+ await vi.waitFor(() => expect(off.spies.onSelectionChange).toHaveBeenCalledTimes(1));+ act(() => root.unmount());+ const { spies, overlay } = offCanvas(HOST);+ expect(overlay.querySelector(MARK)).toBeNull();+ expect(spies.onSelectionChange).not.toHaveBeenCalled();+ });++ it("reports each selection-box click to the host once, by either route", () => {+ const cases = [+ { props: {}, movable: true, reselects: 1 },+ { props: HOST, movable: true, reselects: 0 },+ { props: HOST, movable: false, reselects: 0 },+ ];+ for (const { props, movable, reselects } of cases) {+ const onSelectionBoxClick = vi.fn();+ const { spies, selection, overlay } = fixture({ ...props, onSelectionBoxClick });+ selection.capabilities.canApplyManualOffset = movable;+ clickBox(overlay);+ expect(onSelectionBoxClick).toHaveBeenCalledTimes(1);+ expect(onSelectionBoxClick).toHaveBeenCalledWith(expect.anything(), selection);+ expect(spies.onCanvasMouseDown).toHaveBeenCalledTimes(reselects);+ act(() => root.unmount());+ }+ });++ it("does not report a press off the box, or a click on a group's box", () => {+ const onSelectionBoxClick = vi.fn();+ const off = fixture({ onSelectionBoxClick, onMarqueeSelect: undefined });+ for (const type of ["pointerdown", "mousedown", "pointerup", "click"]) fire(off.overlay, type);+ expect(off.spies.onCanvasMouseDown).toHaveBeenCalledTimes(1);+ act(() => root.unmount());+ const members = ["a", "b"].map((id) => {+ const selection = makeSelection(id, textElement(id));+ return { key: id, selection, element: selection.element, rect: RECT };+ });+ members[1].selection.capabilities.canApplyManualOffset = false;+ layout.group = members;+ const { spies, overlay } = fixture({+ onSelectionBoxClick,+ selection: members[0].selection,+ groupSelections: members.map((m) => m.selection),+ });+ clickBox(overlay);+ expect(spies.onCanvasMouseDown).toHaveBeenCalledTimes(1);+ expect(onSelectionBoxClick).not.toHaveBeenCalled();+ });++ it("reports the first box click after a handle resize", () => {+ const onSelectionBoxClick = vi.fn();+ const { selection, overlay } = fixture({ ...HOST, onSelectionBoxClick });+ for (const type of ["pointerdown", "pointerup", "click"]) {+ fire(overlay.querySelector("div.h-4.w-4")!, type);+ }+ selection.capabilities.canApplyManualOffset = false;+ clickBox(overlay);+ expect(onSelectionBoxClick).toHaveBeenCalledTimes(1);+ });++ it("opens the text on Enter when nothing else has focus, not from a focused field", () => {+ const off = fixture();+ enterOn(document.body);+ expect(off.selection.element.hasAttribute("contenteditable")).toBe(false);+ act(() => root.unmount());+ const { spies, selection } = fixture(HOST);+ const field = document.createElement("input");+ document.body.append(field);+ enterOn(field);+ expect(selection.element.hasAttribute("contenteditable")).toBe(false);+ enterOn(document.body);+ expect(selection.element.hasAttribute("contenteditable")).toBe(true);+ expect(spies.onTextEditingChange.mock.calls).toEqual([[true]]);+ });++ it("keeps the handles working: drag, resize dots and rotate", () => {+ const { spies, overlay } = fixture(HOST);+ fire(overlay.querySelector(BOX)!, "pointerdown");+ expect(spies.onManualDragStart).toHaveBeenCalledTimes(1);+ fire(overlay.querySelector(BOX)!, "pointerup");+ expect(overlay.querySelectorAll("div.h-4.w-4")).toHaveLength(4);+ const rotate = overlay.querySelector('[aria-label="Rotate selection"]')!;+ fire(rotate, "pointerdown", { clientX: 200, clientY: 250 });+ fire(rotate, "pointermove", { clientX: 300, clientY: 150 });+ fire(rotate, "pointerup", { clientX: 300, clientY: 150 });+ expect(spies.onRotationCommit).toHaveBeenCalledTimes(1);+ });+});++describe("DomEditOverlay onTextEditingChange", () => {+ it("reports true when the caret goes live and false when the edit ends", () => {+ const { spies, selection, overlay } = fixture();+ expect(spies.onTextEditingChange).not.toHaveBeenCalled();+ pressEnter(overlay);+ expect(spies.onTextEditingChange.mock.calls).toEqual([[true]]);+ act(() => {+ selection.element.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }),+ );+ });+ expect(spies.onTextEditingChange.mock.calls).toEqual([[true], [false]]);+ });++ it("reports false when the overlay unmounts mid-edit", () => {+ const { spies, overlay } = fixture();+ pressEnter(overlay);+ act(() => root.unmount());+ expect(spies.onTextEditingChange.mock.calls).toEqual([[true], [false]]);+ });+});diff --git a/packages/studio/src/components/editor/useInlineTextEditing.tsx b/packages/studio/src/components/editor/useInlineTextEditing.tsxindex 588feadf3d..c4700083bb 100644--- a/packages/studio/src/components/editor/useInlineTextEditing.tsx+++ b/packages/studio/src/components/editor/useInlineTextEditing.tsx@@ -1,4 +1,4 @@-import { useRef, type ReactNode, type RefObject } from "react";+import { useEffect, useRef, type ReactNode, type RefObject } from "react";import { InlineTextToolbar } from "./InlineTextToolbar";import { useDomEditActionsContextOptional } from "../../contexts/DomEditContext";import { useInlineTextEdit } from "../../hooks/useInlineTextEdit";@@ -12,6 +12,8 @@ import {} from "./domEditInlineText";import type { DomEditSelection } from "./domEditingTypes";+type KeyChord = Pick<KeyboardEvent, "key" | "shiftKey" | "ctrlKey" | "metaKey" | "altKey">;+/*** The canvas' side of editing text where it sits.*@@ -23,18 +25,15 @@ import type { DomEditSelection } from "./domEditingTypes";* props, the same way the agent surfaces in that overlay read it, and it is* absent in standalone player mounts, which have no project to edit.*/-export function useInlineTextEditing(selectionRef: RefObject<DomEditSelection | null>): {+export function useInlineTextEditing(+ selectionRef: RefObject<DomEditSelection | null>,+ { enterFromWindow = false }: { enterFromWindow?: boolean } = {},+): {editing: boolean;/** Open an edit when this press pairs with the last one. */startFromPress: (event: { clientX: number; clientY: number }) => boolean;/** Handle a key on the canvas. Returns true when it opened an edit. */- handleKeyDown: (event: {- key: string;- shiftKey: boolean;- ctrlKey: boolean;- metaKey: boolean;- altKey: boolean;- }) => boolean;+ handleKeyDown: (event: KeyChord) => boolean;/*** The styling controls for the current selection, for the caller to render.*@@ -84,6 +83,32 @@ export function useInlineTextEditing(selectionRef: RefObject<DomEditSelection |return { x: (event.clientX - box.left) / scale, y: (event.clientY - box.top) / scale };};+ // Enter opens the selected element's text, the way every design tool does,+ // and is the dependable way in: a double press has to survive the canvas'+ // gesture machinery, while this is one key on a selection that has settled.+ const handleKeyDown = (event: KeyChord) => {+ if (event.key !== "Enter" || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey)+ return false;+ const target = selectionRef.current;+ if (inlineText.session || !target || !canEditTextInline(target)) return false;+ return inlineText.start(target.element);+ };+ const handleKeyDownRef = useRef(handleKeyDown);+ handleKeyDownRef.current = handleKeyDown;+ // A host-mode canvas takes no presses of its own, so it is rarely focused;+ // with nothing focused, Enter comes via the window.+ useEffect(() => {+ if (!enterFromWindow) return;+ const onKeyDown = (event: KeyboardEvent) => {+ const { body, documentElement } = window.document;+ if (event.defaultPrevented || (event.target !== body && event.target !== documentElement))+ return;+ if (handleKeyDownRef.current(event)) event.preventDefault();+ };+ window.addEventListener("keydown", onKeyDown);+ return () => window.removeEventListener("keydown", onKeyDown);+ }, [enterFromWindow]);+return {editing: inlineText.session !== null,toolbar: (@@ -92,16 +117,7 @@ export function useInlineTextEditing(selectionRef: RefObject<DomEditSelection |iframe={actions?.previewIframeRef?.current ?? null}/>),- // Enter opens the selected element's text, the way every design tool does,- // and is the dependable way in: a double press has to survive the canvas'- // gesture machinery, while this is one key on a selection that has settled.- handleKeyDown: (event) => {- if (event.key !== "Enter" || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey)- return false;- const target = selectionRef.current;- if (inlineText.session || !target || !canEditTextInline(target)) return false;- return inlineText.start(target.element);- },+ handleKeyDown,startFromPress: (event) => {if (inlineText.session) return false;const element = elementUnderPress(event);diff --git a/packages/studio/src/components/nle/PreviewOverlays.tsx b/packages/studio/src/components/nle/PreviewOverlays.tsxindex 3a94ec227b..4a4f61d25c 100644--- a/packages/studio/src/components/nle/PreviewOverlays.tsx+++ b/packages/studio/src/components/nle/PreviewOverlays.tsx@@ -1,7 +1,7 @@import { useCallback } from "react";import { CaptionOverlay } from "../../captions/components/CaptionOverlay";import { useCaptionStore } from "../../captions/store";-import { DomEditOverlay } from "../editor/DomEditOverlay";+import { ConnectedDomEditOverlay } from "../editor/ConnectedDomEditOverlay";import { TopologyLens } from "../editor/TopologyLens";import { MotionPathOverlay } from "../editor/MotionPathOverlay";import { SnapToolbar } from "../editor/SnapToolbar";@@ -9,16 +9,7 @@ import { GridOverlay } from "../editor/GridOverlay";import { usePreviewReadOnly } from "../editor/previewReadOnlyContext";import { useCompositionDimensions } from "../../hooks/useCompositionDimensions";import { useStudioPlaybackContext, useStudioShellContext } from "../../contexts/StudioContext";-import {- useDomEditActionsContext,- useDomEditSelectionContext,-} from "../../contexts/DomEditContext";-import { readHfId, type DomEditSelection } from "../editor/domEditing";-import { buildStableSelector } from "../editor/domEditingDom";-import { deriveTimelineStoreKey } from "../../player/lib/timelineElementHelpers";-import { zReorderCoalesceKey } from "../../hooks/useElementLifecycleOps";-import { useCanvasZOrderTimelineMirror } from "./useCanvasZOrderTimelineMirror";-import { runZLaneGesture } from "./zLaneGesture";+import { useDomEditSelectionContext } from "../../contexts/DomEditContext";import type { BlockPreviewInfo } from "../sidebar/BlocksTab";import type { GestureRecordingState } from "../editor/GestureRecordControl";import type { ReactNode } from "react";@@ -33,109 +24,12 @@ export interface PreviewOverlaysProps {gestureOverlay?: ReactNode;}-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,- }),- };-}--/**- * Sibling elements are raw iframe DOM nodes with no selection object: derive a- * PatchTarget from the node itself (siblings live in the same document, so they- * share the selection's sourceFile). Null when it cannot be robustly targeted- * (no id and no selector) — its z stays live-only.- */-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 (and a live-only style write, so the resolved-// stacking order still renders coherently). Exported so tests can drive the-// menu → commit path through the same wiring the app uses.-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 };-}-// fallow-ignore-next-line complexityexport function PreviewOverlays({shouldShowMotionPath,shouldShowSelectedDomBounds,blockPreview,isGestureRecording,- recordingState,- onToggleRecording,gestureOverlay,}: PreviewOverlaysProps) {const { activeCompPath, previewIframeRef } = useStudioShellContext();@@ -162,25 +56,7 @@ export function PreviewOverlays({store.setEditMode(true);}, []);- const { domEditHoverSelection, domEditSelection, domEditGroupSelections } =- useDomEditSelectionContext();- const {- handlePreviewCanvasMouseDown,- handlePreviewCanvasPointerMove,- handlePreviewCanvasPointerLeave,- applyDomSelection,- handleBlockedDomMove,- handleDomManualDragStart,- handleDomPathOffsetCommit,- handleDomGroupPathOffsetCommit,- handleDomBoxSizeCommit,- handleDomRotationCommit,- handleDomStyleCommit,- applyMarqueeSelection,- handleDomEditElementDelete,- handleDomZIndexReorderCommit,- } = useDomEditActionsContext();- const mirrorZOrderToTimeline = useCanvasZOrderTimelineMirror();+ const { domEditSelection } = useDomEditSelectionContext();if (blockPreview) {return (@@ -256,68 +132,11 @@ export function PreviewOverlays({<><TopologyLens iframeRef={previewIframeRef} activeCompositionPath={activeCompPath} /><GridOverlay />- <DomEditOverlay- iframeRef={previewIframeRef}+ <ConnectedDomEditOverlayactiveCompositionPath={activeCompPath}- hoverSelection={- !previewCaptionEditMode && !compositionLoading && !isPlaying- ? domEditHoverSelection- : null- }- selection={shouldShowSelectedDomBounds ? domEditSelection : null}- groupSelections={shouldShowSelectedDomBounds ? domEditGroupSelections : []}- allowCanvasMovement={!isGestureRecording}- onCanvasMouseDown={handlePreviewCanvasMouseDown}- onCanvasPointerMove={handlePreviewCanvasPointerMove}- onCanvasPointerLeave={handlePreviewCanvasPointerLeave}- onSelectionChange={applyDomSelection}- onBlockedMove={handleBlockedDomMove}- onManualDragStart={handleDomManualDragStart}- onPathOffsetCommit={handleDomPathOffsetCommit}- onGroupPathOffsetCommit={handleDomGroupPathOffsetCommit}- onBoxSizeCommit={handleDomBoxSizeCommit}- 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;- // Shared undo coalesce key: passed to BOTH the z persist and the- // timeline lane mirror below so editHistory folds the two records- // into one undo entry (same value handleDomZIndexReorderCommit would- // default to — 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 the- // z commit resolved AND reported durable targets, and a second rapid- // gesture cannot interleave between the two phases — see- // runZLaneGesture. A failed z commit already toasted + rolled back.- 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);- }}- recordingState={recordingState}- onToggleRecording={onToggleRecording}- onMarqueeSelect={applyMarqueeSelection}+ showHoverSelection={!previewCaptionEditMode && !compositionLoading && !isPlaying}+ shouldShowSelectedDomBounds={shouldShowSelectedDomBounds}+ isGestureRecording={isGestureRecording}/><SnapToolbar />{!readOnly && (diff --git a/packages/studio/src/components/nle/PreviewOverlaysTestMocks.ts b/packages/studio/src/components/nle/PreviewOverlaysTestMocks.tsindex 2eff52bae5..dddea3fd65 100644--- a/packages/studio/src/components/nle/PreviewOverlaysTestMocks.ts+++ b/packages/studio/src/components/nle/PreviewOverlaysTestMocks.ts@@ -1,6 +1,6 @@import { vi } from "vitest";-const previewState = vi.hoisted(() => ({ captionEditMode: false }));+const previewState = vi.hoisted(() => ({ captionEditMode: false, isPlaying: false }));export function getPreviewState() {return previewState;}@@ -11,7 +11,7 @@ vi.mock("../../contexts/StudioContext", () => ({useStudioPlaybackContext: () => ({captionEditMode: previewState.captionEditMode,compositionLoading: false,- isPlaying: false,+ isPlaying: previewState.isPlaying,}),}));vi.mock("../../captions/store", () => {diff --git a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.tsindex c066293226..eb8b87831d 100644--- a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts+++ b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts@@ -30,7 +30,7 @@ export interface MirrorZOrderInput {/*** Mirror a successful canvas z-order menu action into a timeline LANE move.*- * The caller (PreviewOverlays) invokes the returned callback AFTER the z commit+ * The caller (ConnectedDomEditOverlay) invokes the returned callback AFTER the z commit* resolved — serializing the two same-file writes, exactly like the lane-drag's* move→z ordering (see persistMoveEdits' doc) — and with the SAME coalesce key* the z persist recorded, so editHistory folds both records into one undo entry.diff --git a/packages/studio/src/domEditExports.test.tsx b/packages/studio/src/domEditExports.test.tsxnew file mode 100644index 0000000000..4536914b2f--- /dev/null+++ b/packages/studio/src/domEditExports.test.tsx@@ -0,0 +1,69 @@+// @vitest-environment happy-dom+// Imports DOM editing the way a host app does: by package name, mounted outside EditorShell.+import { act } from "react";+import { createRoot } from "react-dom/client";+import { describe, expect, expectTypeOf, it, vi } from "vitest";+import {+ ConnectedDomEditOverlay,+ DomEditProvider,+ PreviewReadOnlyProvider,+ useDomEditSelectionContext,+ useDomEditSession,+ usePreviewPersistence,+ type ConnectedDomEditOverlayProps,+ type DomEditCapabilities,+ type DomEditSelection,+ type UseDomEditSessionParams,+ type UsePreviewPersistenceParams,+} from "@hyperframes/studio";++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });++describe("DOM editing package exports", () => {+ it("exposes the session and persistence hooks with their params types", () => {+ expect(typeof useDomEditSession).toBe("function");+ expect(typeof usePreviewPersistence).toBe("function");+ expectTypeOf<UseDomEditSessionParams>().toHaveProperty("writeProjectFile");+ expectTypeOf<UsePreviewPersistenceParams>().toHaveProperty("recordEdit");+ expectTypeOf<DomEditSelection>().toHaveProperty("capabilities");+ expectTypeOf<DomEditCapabilities>().toHaveProperty("canApplyManualOffset");+ expectTypeOf<ConnectedDomEditOverlayProps>().toHaveProperty("canvasInput");+ });++ it("mounts the connected overlay in host mode inside a host's providers", async () => {+ const seen: Array<DomEditSelection | null> = [];+ function Probe() {+ seen.push(useDomEditSelectionContext().domEditSelection);+ return null;+ }+ const session = {+ domEditSelection: null,+ domEditGroupSelections: [],+ domEditHoverSelection: null,+ previewIframeRef: { current: null },+ handlePreviewCanvasPointerLeave: vi.fn(),+ } as unknown as Parameters<typeof DomEditProvider>[0]["value"];+ const el = document.createElement("div");+ document.body.append(el);+ const root = createRoot(el);+ await act(async () =>+ root.render(+ <PreviewReadOnlyProvider readOnly={false}>+ <DomEditProvider value={session}>+ <Probe />+ <ConnectedDomEditOverlay+ activeCompositionPath={null}+ showHoverSelection={false}+ shouldShowSelectedDomBounds={true}+ canvasInput="host"+ />+ </DomEditProvider>+ </PreviewReadOnlyProvider>,+ ),+ );+ expect(seen.at(-1)).toBeNull();+ const canvas = el.querySelector('[aria-label="Composition canvas"]');+ expect(canvas?.className).toContain("pointer-events-none");+ await act(async () => root.unmount());+ });+});diff --git a/packages/studio/src/hooks/useElementLifecycleOps.ts b/packages/studio/src/hooks/useElementLifecycleOps.tsindex 3352457c81..25c934da88 100644--- a/packages/studio/src/hooks/useElementLifecycleOps.ts+++ b/packages/studio/src/hooks/useElementLifecycleOps.ts@@ -56,7 +56,7 @@ let zReorderGestureSeq = 0;* fold can only ever merge records of the SAME gesture.** Exported as THE single implementation of the key: the canvas z-order wiring- * (PreviewOverlays) mints it once per gesture and passes the same instance to+ * (ConnectedDomEditOverlay) mints it once per gesture and passes the same instance to* both the z persist and the timeline lane mirror (useCanvasZOrderTimelineMirror)* so editHistory folds the z write and the track write into one undo entry —* recomputing the key per record would silently split the undo.diff --git a/packages/studio/src/hooks/usePreviewPersistence.ts b/packages/studio/src/hooks/usePreviewPersistence.tsindex e62eae6735..cf32cc505f 100644--- a/packages/studio/src/hooks/usePreviewPersistence.ts+++ b/packages/studio/src/hooks/usePreviewPersistence.ts@@ -29,7 +29,7 @@ interface RecordEditInput {files: Record<string, { before: string; after: string }>;}-interface UsePreviewPersistenceParams {+export interface UsePreviewPersistenceParams {showToast: (message: string, tone?: "error" | "info") => void;readOptionalProjectFile: (path: string) => Promise<string>;writeProjectFile: (path: string, content: string) => Promise<void>;diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.tsindex cae9bd0ef3..aaccee0aaf 100644--- a/packages/studio/src/index.ts+++ b/packages/studio/src/index.ts@@ -196,6 +196,17 @@ export type { AudioMeterStripProps } from "./components/nle/AudioMeterStrip";export { useClipboard } from "./hooks/useClipboard";export type { UseClipboardOptions } from "./hooks/useClipboard";+// DOM editing: the canvas session, persistence and overlay, for a host outside EditorShell.+export { useDomEditSession } from "./hooks/useDomEditSession";+export type { UseDomEditSessionParams } from "./hooks/useDomEditSession";+export { usePreviewPersistence } from "./hooks/usePreviewPersistence";+export type { UsePreviewPersistenceParams } from "./hooks/usePreviewPersistence";+export { DomEditProvider, useDomEditSelectionContext } from "./contexts/DomEditContext";+export { PreviewReadOnlyProvider } from "./components/editor/previewReadOnlyContext";+export { ConnectedDomEditOverlay } from "./components/editor/ConnectedDomEditOverlay";+export type { ConnectedDomEditOverlayProps } from "./components/editor/ConnectedDomEditOverlay";+export type { DomEditCapabilities, DomEditSelection } from "./components/editor/domEditingTypes";+export {playSeamTransitionLoop,type SeamTransitionFrameSource,