Skip to content

Write HTML. Render video. Built for agents.

feat(studio): a host can make the preview read-only (#4200)

Miguel Ángel84e65316683c
diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx
index 9ba30cfc1c..477ec4129a 100644
--- a/packages/studio/src/App.tsx
+++ b/packages/studio/src/App.tsx
@@ -63,8 +63,16 @@ import { useTimelineAddAtPlayhead } from "./hooks/useTimelineAddAtPlayhead";
import { readStudioUrlStateFromWindow, resolveMasterCompositionPath } from "./utils/studioUrlState";
import { useActiveComposition } from "./hooks/useActiveComposition";
const getTimelineSelectionSet = () => usePlayerStore.getState().selectedElementIds;
+
+export interface StudioAppProps {
+ /** Clicks still select and report; the preview cannot move, edit or delete anything. */
+ readOnlyPreview?: boolean;
+ /** Short text shown on disabled hand-edit controls while `readOnlyPreview` is set. */
+ readOnlyPreviewReason?: string;
+}
+
// fallow-ignore-next-line complexity
-export function StudioApp() {
+export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: StudioAppProps = {}) {
const { projectId, resolving, waitingForServer } = useServerConnection();
const initialUrlStateRef = useRef(readStudioUrlStateFromWindow());
useStudioSessionStart(projectId, resolving, waitingForServer);
@@ -252,6 +260,7 @@ export function StudioApp() {
activeCompPath,
forceReloadSdkSession: sdkHandle.forceReload,
onToggleRecording: () => handleToggleRecordingRef.current(),
+ readOnlyPreview,
});
const domEditSession = useDomEditSession({
projectId,
@@ -291,6 +300,7 @@ export function StudioApp() {
publishSdkSession: sdkHandle.publish,
forceReloadSdkSession: sdkHandle.forceReload,
handleTimelineElementsDelete: timelineEditing.handleTimelineElementsDelete,
+ readOnlyPreview,
});
domEditSelectionBridgeRef.current = domEditSession.domEditSelection;
handleDomZIndexReorderCommitRef.current = domEditSession.handleDomZIndexReorderCommit;
@@ -346,6 +356,7 @@ export function StudioApp() {
previewIframeRef,
showToast,
isGestureRecordingRef,
+ readOnlyPreview,
});
handleToggleRecordingRef.current = handleToggleRecording;
const canvasRectRef = useRef<DOMRect | null>(null);
@@ -465,6 +476,8 @@ export function StudioApp() {
)}
<ExternalFileConflictBanner coordinator={externalFileChanges} />
<EditorShell
+ readOnlyPreview={readOnlyPreview}
+ readOnlyPreviewReason={readOnlyPreviewReason}
panels={
<>
<StudioLeftPanels
diff --git a/packages/studio/src/components/EditorShell.readOnlyHostMount.test.tsx b/packages/studio/src/components/EditorShell.readOnlyHostMount.test.tsx
new file mode 100644
index 0000000000..c9b1c84902
--- /dev/null
+++ b/packages/studio/src/components/EditorShell.readOnlyHostMount.test.tsx
@@ -0,0 +1,116 @@
+// @vitest-environment happy-dom
+
+// A host that mounts EditorShell directly — no StudioApp, no App.tsx — must
+// still get its descendants gated purely from the readOnlyPreview prop.
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import "./EditorShellTestMocks";
+import { EditorShell } from "./EditorShell";
+import { usePreviewBlockDrop } from "./nle/usePreviewBlockDrop";
+import { TIMELINE_BLOCK_MIME } from "../utils/timelineAssetDrop";
+
+vi.mock("../hooks/useTimelineSelectionPreviewSync", () => ({
+ useTimelineSelectionPreviewSync: vi.fn(),
+}));
+vi.mock("./nle/PreviewOverlays", () => ({ PreviewOverlays: () => null }));
+
+// The real hook — this is the actual Tier-1 consumer a host relies on to gate
+// a drop onto the preview. Only PreviewPane's own DOM/player chrome is mocked.
+const stage = document.createElement("div");
+stage.getBoundingClientRect = () => ({ left: 0, top: 0, width: 100, height: 100 }) as DOMRect;
+const dropHandlers: { current: ReturnType<typeof usePreviewBlockDrop> | null } = { current: null };
+vi.mock("./nle/PreviewPane", () => ({
+ PreviewPane: (props: { onPreviewBlockDrop?: (name: string, pos: unknown) => void }) => {
+ dropHandlers.current = usePreviewBlockDrop({
+ stageRef: { current: stage },
+ compositionSize: { width: 1000, height: 1000 },
+ onBlockDrop: props.onPreviewBlockDrop,
+ });
+ return null;
+ },
+}));
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+
+let root: ReturnType<typeof createRoot> | null = null;
+
+afterEach(() => {
+ if (root) act(() => root!.unmount());
+ root = null;
+ document.body.innerHTML = "";
+});
+
+function mountShellAlone(
+ readOnlyPreview: boolean,
+ onPreviewBlockDrop: (...args: unknown[]) => void,
+) {
+ const host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ act(() =>
+ root!.render(
+ <EditorShell
+ panels={null}
+ timelineToolbar={null}
+ renderClipContent={() => null}
+ handleTimelineElementDelete={vi.fn()}
+ handleTimelineAssetDrop={vi.fn()}
+ handleTimelineFileDrop={vi.fn()}
+ handleTimelineElementMove={vi.fn()}
+ handleTimelineElementsMove={vi.fn()}
+ handleTimelineElementResize={vi.fn()}
+ handleTimelineGroupResize={vi.fn()}
+ handleToggleTrackHidden={vi.fn()}
+ setAudioGroupAttribute={{ setLive: vi.fn(), setQuiet: vi.fn() }}
+ handleBlockedTimelineEdit={vi.fn()}
+ handleTimelineElementSplit={vi.fn()}
+ handleRazorSplit={vi.fn()}
+ handleRazorSplitAll={vi.fn()}
+ onCopyClip={vi.fn(() => false)}
+ onPasteClip={vi.fn(async () => {})}
+ onDuplicateClip={vi.fn(async () => false)}
+ canPasteClip={vi.fn(() => false)}
+ setCompIdToSrc={vi.fn()}
+ setCompositionLoading={vi.fn()}
+ shouldShowMotionPath={false}
+ shouldShowSelectedDomBounds={false}
+ handlePreviewBlockDrop={onPreviewBlockDrop}
+ readOnlyPreview={readOnlyPreview}
+ />,
+ ),
+ );
+ return { host, root };
+}
+
+function dropEvent() {
+ return {
+ clientX: 50,
+ clientY: 50,
+ preventDefault: vi.fn(),
+ dataTransfer: {
+ types: [TIMELINE_BLOCK_MIME],
+ getData: () => JSON.stringify({ name: "lower-third" }),
+ },
+ };
+}
+
+describe("a host mounting EditorShell alone (no StudioApp, no App.tsx)", () => {
+ it("gates a Tier-1 descendant's drop handling purely from the prop", () => {
+ const onBlockDrop = vi.fn();
+ mountShellAlone(true, onBlockDrop);
+ const event = dropEvent();
+ act(() => dropHandlers.current!.handleDrop(event as never));
+ expect(onBlockDrop).not.toHaveBeenCalled();
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ });
+
+ it("control: with the flag off, the same descendant still places a drop", () => {
+ const onBlockDrop = vi.fn();
+ mountShellAlone(false, onBlockDrop);
+ const event = dropEvent();
+ act(() => dropHandlers.current!.handleDrop(event as never));
+ expect(onBlockDrop).toHaveBeenCalledWith("lower-third", { left: 500, top: 500 });
+ });
+});
diff --git a/packages/studio/src/components/EditorShell.selectionSync.test.tsx b/packages/studio/src/components/EditorShell.selectionSync.test.tsx
index 5d818c8d95..ba78b453e9 100644
--- a/packages/studio/src/components/EditorShell.selectionSync.test.tsx
+++ b/packages/studio/src/components/EditorShell.selectionSync.test.tsx
@@ -3,54 +3,27 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
+import "./EditorShellTestMocks";
import { EditorShell } from "./EditorShell";
+import { usePreviewReadOnly } from "./editor/previewReadOnlyContext";
const hookMocks = vi.hoisted(() => ({
useTimelineSelectionPreviewSync: vi.fn(),
}));
+const previewOverlaysProbe = vi.hoisted(() => ({ readOnly: null as boolean | null }));
vi.mock("../hooks/useTimelineSelectionPreviewSync", () => hookMocks);
-vi.mock("../contexts/StudioContext", () => ({
- useStudioPlaybackContext: () => ({
- captionEditMode: false,
- refreshKey: 0,
- refreshPreviewDocumentVersion: vi.fn(),
- timelineElements: [],
- }),
- useStudioShellContext: () => ({
- projectId: "project-1",
- activeCompPath: "index.html",
- setActiveCompPath: vi.fn(),
- handlePreviewIframeRef: vi.fn(),
- showToast: vi.fn(),
- }),
+vi.mock("./nle/PreviewPane", () => ({
+ // Renders its previewOverlay prop for real, so the mocked PreviewOverlays
+ // below (which reads the read-only context) actually mounts.
+ PreviewPane: (props: { previewOverlay?: React.ReactNode }) => props.previewOverlay ?? null,
}));
-vi.mock("../contexts/DomEditContext", () => ({
- useDomEditActionsContext: () => ({
- handleTimelineElementSelect: vi.fn(),
- buildDomSelectionForTimelineElement: vi.fn(),
- applyDomSelection: vi.fn(),
- applyMarqueeSelection: vi.fn(),
- }),
- useDomEditSelectionContext: () => ({
- domEditSelection: null,
- domEditGroupSelections: [],
- }),
-}));
-vi.mock("./nle/NLEContext", () => ({
- NLEProvider: ({ children }: { children: React.ReactNode }) => children,
- useNLEContext: () => ({
- compositionStack: [],
- updateCompositionStack: vi.fn(),
- }),
-}));
-vi.mock("./nle/useTimelineEditCallbacks", () => ({
- useTimelineEditCallbacks: () => ({}),
+vi.mock("./nle/PreviewOverlays", () => ({
+ PreviewOverlays: () => {
+ previewOverlaysProbe.readOnly = usePreviewReadOnly();
+ return null;
+ },
}));
-vi.mock("./nle/PreviewPane", () => ({ PreviewPane: () => null }));
-vi.mock("./nle/PreviewOverlays", () => ({ PreviewOverlays: () => null }));
-vi.mock("./nle/TimelinePane", () => ({ TimelinePane: () => null }));
-vi.mock("../captions/components/CaptionTimeline", () => ({ CaptionTimeline: () => null }));
Object.assign(globalThis, {
IS_REACT_ACT_ENVIRONMENT: true,
@@ -66,6 +39,36 @@ afterEach(() => {
hookMocks.useTimelineSelectionPreviewSync.mockClear();
});
+const shell = (readOnlyPreview?: boolean) => (
+ <EditorShell
+ panels={null}
+ timelineToolbar={null}
+ renderClipContent={() => null}
+ handleTimelineElementDelete={vi.fn()}
+ handleTimelineAssetDrop={vi.fn()}
+ handleTimelineFileDrop={vi.fn()}
+ handleTimelineElementMove={vi.fn()}
+ handleTimelineElementsMove={vi.fn()}
+ handleTimelineElementResize={vi.fn()}
+ handleTimelineGroupResize={vi.fn()}
+ handleToggleTrackHidden={vi.fn()}
+ setAudioGroupAttribute={{ setLive: vi.fn(), setQuiet: vi.fn() }}
+ handleBlockedTimelineEdit={vi.fn()}
+ handleTimelineElementSplit={vi.fn()}
+ handleRazorSplit={vi.fn()}
+ handleRazorSplitAll={vi.fn()}
+ onCopyClip={vi.fn(() => false)}
+ onPasteClip={vi.fn(async () => {})}
+ onDuplicateClip={vi.fn(async () => false)}
+ canPasteClip={vi.fn(() => false)}
+ setCompIdToSrc={vi.fn()}
+ setCompositionLoading={vi.fn()}
+ shouldShowMotionPath={false}
+ shouldShowSelectedDomBounds={false}
+ readOnlyPreview={readOnlyPreview}
+ />
+);
+
describe("EditorShell timeline selection sync", () => {
it("keeps the timeline store mirrored into the preview selection", () => {
const host = document.createElement("div");
@@ -73,34 +76,7 @@ describe("EditorShell timeline selection sync", () => {
const root = createRoot(host);
act(() => {
- root.render(
- <EditorShell
- panels={null}
- timelineToolbar={null}
- renderClipContent={() => null}
- handleTimelineElementDelete={vi.fn()}
- handleTimelineAssetDrop={vi.fn()}
- handleTimelineFileDrop={vi.fn()}
- handleTimelineElementMove={vi.fn()}
- handleTimelineElementsMove={vi.fn()}
- handleTimelineElementResize={vi.fn()}
- handleTimelineGroupResize={vi.fn()}
- handleToggleTrackHidden={vi.fn()}
- setAudioGroupAttribute={{ setLive: vi.fn(), setQuiet: vi.fn() }}
- handleBlockedTimelineEdit={vi.fn()}
- handleTimelineElementSplit={vi.fn()}
- handleRazorSplit={vi.fn()}
- handleRazorSplitAll={vi.fn()}
- onCopyClip={vi.fn(() => false)}
- onPasteClip={vi.fn(async () => {})}
- onDuplicateClip={vi.fn(async () => false)}
- canPasteClip={vi.fn(() => false)}
- setCompIdToSrc={vi.fn()}
- setCompositionLoading={vi.fn()}
- shouldShowMotionPath={false}
- shouldShowSelectedDomBounds={false}
- />,
- );
+ root.render(shell());
});
expect(hookMocks.useTimelineSelectionPreviewSync).toHaveBeenCalledOnce();
@@ -115,4 +91,18 @@ describe("EditorShell timeline selection sync", () => {
act(() => root.unmount());
});
+
+ it("threads the read-only prop into descendants via context, and follows it across renders", () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+
+ act(() => root.render(shell(true)));
+ expect(previewOverlaysProbe.readOnly).toBe(true);
+ act(() => root.render(shell(false)));
+ expect(previewOverlaysProbe.readOnly).toBe(false);
+ act(() => root.render(shell(true)));
+ expect(previewOverlaysProbe.readOnly).toBe(true);
+ act(() => root.unmount());
+ });
});
diff --git a/packages/studio/src/components/EditorShell.tsx b/packages/studio/src/components/EditorShell.tsx
index ad0324dafd..0c95fe538a 100644
--- a/packages/studio/src/components/EditorShell.tsx
+++ b/packages/studio/src/components/EditorShell.tsx
@@ -2,6 +2,7 @@ import { useCallback, type ReactNode } from "react";
import { PreviewPane } from "./nle/PreviewPane";
import { TimelinePane } from "./nle/TimelinePane";
import { PreviewOverlays } from "./nle/PreviewOverlays";
+import { PreviewReadOnlyProvider } from "./editor/previewReadOnlyContext";
import {
useTimelineEditCallbacks,
type TimelineEditCallbackDeps,
@@ -69,6 +70,10 @@ export interface EditorShellProps extends TimelineEditCallbackDeps {
* fullscreen and during a block preview; below the selection overlay past z-index 10.
*/
gestureOverlay?: ReactNode;
+ /** Clicks still select and report; the preview cannot move, edit or delete anything. */
+ readOnlyPreview?: boolean;
+ /** Short text shown on disabled hand-edit controls while `readOnlyPreview` is set. */
+ readOnlyPreviewReason?: string;
}
// The dockable shell: every panel lives in one Dock, arranged by the user's
@@ -109,6 +114,8 @@ export function EditorShell({
onToggleRecording,
blockPreview,
gestureOverlay,
+ readOnlyPreview = false,
+ readOnlyPreviewReason,
}: EditorShellProps) {
const { projectId, activeCompPath, setActiveCompPath, handlePreviewIframeRef, showToast } =
useStudioShellContext();
@@ -156,57 +163,59 @@ export function EditorShell({
});
return (
- <div className="flex flex-col flex-1 min-h-0">
- <TimelineEditProvider value={timelineEditCallbacks}>
- <NLEProvider
- projectId={projectId}
- refreshKey={refreshKey}
- activeCompositionPath={activeCompPath}
- onIframeRef={handlePreviewIframeRef}
- onCompIdToSrcChange={setCompIdToSrc}
- onCompositionLoadingChange={setCompositionLoading}
- onCompositionChange={(compPath) => {
- // Sync activeCompPath when the user drills down via the timeline or
- // navigates back — keeps sidebar + thumbnails in sync. Guard no-ops to
- // avoid circular refresh cascades (activeCompPath → stack → onChange).
- if (compPath !== activeCompPath) {
- setActiveCompPath(compPath);
- refreshPreviewDocumentVersion();
- }
- }}
- >
- <EditorShellBody
+ <PreviewReadOnlyProvider readOnly={readOnlyPreview} reason={readOnlyPreviewReason}>
+ <div className="flex flex-col flex-1 min-h-0">
+ <TimelineEditProvider value={timelineEditCallbacks}>
+ <NLEProvider
projectId={projectId}
- panels={panels}
- captionEditMode={captionEditMode}
- onSelectTimelineElement={handleTimelineElementSelect}
- onPreviewBlockDrop={handlePreviewBlockDrop}
- timelineToolbar={timelineToolbar}
- renderClipContent={renderClipContent}
- onFileDrop={handleTimelineFileDrop}
- onAssetDrop={handleTimelineAssetDrop}
- onBlockDrop={handleTimelineBlockDrop}
- onCompositionDrop={handleTimelineCompositionDrop}
- onDeleteElement={handleTimelineElementDelete}
- onCopyClip={onCopyClip}
- onPasteClip={onPasteClip}
- onDuplicateClip={onDuplicateClip}
- canPasteClip={canPasteClip}
- previewOverlay={
- <PreviewOverlays
- shouldShowMotionPath={shouldShowMotionPath}
- shouldShowSelectedDomBounds={shouldShowSelectedDomBounds}
- blockPreview={blockPreview}
- isGestureRecording={isGestureRecording}
- recordingState={recordingState}
- onToggleRecording={onToggleRecording}
- gestureOverlay={gestureOverlay}
- />
- }
- />
- </NLEProvider>
- </TimelineEditProvider>
- </div>
+ refreshKey={refreshKey}
+ activeCompositionPath={activeCompPath}
+ onIframeRef={handlePreviewIframeRef}
+ onCompIdToSrcChange={setCompIdToSrc}
+ onCompositionLoadingChange={setCompositionLoading}
+ onCompositionChange={(compPath) => {
+ // Sync activeCompPath when the user drills down via the timeline or
+ // navigates back — keeps sidebar + thumbnails in sync. Guard no-ops to
+ // avoid circular refresh cascades (activeCompPath → stack → onChange).
+ if (compPath !== activeCompPath) {
+ setActiveCompPath(compPath);
+ refreshPreviewDocumentVersion();
+ }
+ }}
+ >
+ <EditorShellBody
+ projectId={projectId}
+ panels={panels}
+ captionEditMode={captionEditMode}
+ onSelectTimelineElement={handleTimelineElementSelect}
+ onPreviewBlockDrop={handlePreviewBlockDrop}
+ timelineToolbar={timelineToolbar}
+ renderClipContent={renderClipContent}
+ onFileDrop={handleTimelineFileDrop}
+ onAssetDrop={handleTimelineAssetDrop}
+ onBlockDrop={handleTimelineBlockDrop}
+ onCompositionDrop={handleTimelineCompositionDrop}
+ onDeleteElement={handleTimelineElementDelete}
+ onCopyClip={onCopyClip}
+ onPasteClip={onPasteClip}
+ onDuplicateClip={onDuplicateClip}
+ canPasteClip={canPasteClip}
+ previewOverlay={
+ <PreviewOverlays
+ shouldShowMotionPath={shouldShowMotionPath}
+ shouldShowSelectedDomBounds={shouldShowSelectedDomBounds}
+ blockPreview={blockPreview}
+ isGestureRecording={isGestureRecording}
+ recordingState={recordingState}
+ onToggleRecording={onToggleRecording}
+ gestureOverlay={gestureOverlay}
+ />
+ }
+ />
+ </NLEProvider>
+ </TimelineEditProvider>
+ </div>
+ </PreviewReadOnlyProvider>
);
}
diff --git a/packages/studio/src/components/EditorShellTestMocks.ts b/packages/studio/src/components/EditorShellTestMocks.ts
new file mode 100644
index 0000000000..96d8154394
--- /dev/null
+++ b/packages/studio/src/components/EditorShellTestMocks.ts
@@ -0,0 +1,46 @@
+import React from "react";
+import { vi } from "vitest";
+
+vi.mock("../contexts/StudioContext", () => ({
+ useStudioPlaybackContext: () => ({
+ captionEditMode: false,
+ refreshKey: 0,
+ refreshPreviewDocumentVersion: vi.fn(),
+ timelineElements: [],
+ }),
+ useStudioShellContext: () => ({
+ projectId: "project-1",
+ activeCompPath: "index.html",
+ setActiveCompPath: vi.fn(),
+ handlePreviewIframeRef: vi.fn(),
+ showToast: vi.fn(),
+ }),
+}));
+
+vi.mock("../contexts/DomEditContext", () => ({
+ useDomEditActionsContext: () => ({
+ handleTimelineElementSelect: vi.fn(),
+ buildDomSelectionForTimelineElement: vi.fn(),
+ applyDomSelection: vi.fn(),
+ applyMarqueeSelection: vi.fn(),
+ }),
+ useDomEditSelectionContext: () => ({
+ domEditSelection: null,
+ domEditGroupSelections: [],
+ }),
+}));
+
+vi.mock("./nle/NLEContext", () => ({
+ NLEProvider: ({ children }: { children: React.ReactNode }) => children,
+ useNLEContext: () => ({
+ compositionStack: [],
+ updateCompositionStack: vi.fn(),
+ containerRef: { current: null },
+ }),
+}));
+
+vi.mock("./nle/useTimelineEditCallbacks", () => ({
+ useTimelineEditCallbacks: () => ({}),
+}));
+vi.mock("./nle/TimelinePane", () => ({ TimelinePane: () => null }));
+vi.mock("../captions/components/CaptionTimeline", () => ({ CaptionTimeline: () => null }));
diff --git a/packages/studio/src/components/editor/DomEditOverlay.tsx b/packages/studio/src/components/editor/DomEditOverlay.tsx
index 7676f5e158..2d68102d1d 100644
--- a/packages/studio/src/components/editor/DomEditOverlay.tsx
+++ b/packages/studio/src/components/editor/DomEditOverlay.tsx
@@ -1,4 +1,4 @@
-import { memo, useEffect, useMemo, useRef, useState, type RefObject } from "react";
+import { memo, useEffect, useMemo, useRef, type RefObject } from "react";
import { type DomEditSelection } from "./domEditing";
import type { PreviewMouseDownOptions } from "../../hooks/usePreviewInteraction";
import { useMarqueeGestures } from "./marqueeCommit";
@@ -16,7 +16,7 @@ import {
resolveShiftClickCandidate,
} from "./domEditOverlayGestures";
import { useDomEditOverlayRects } from "./useDomEditOverlayRects";
-import { ChildRectOutlines, OffCanvasIndicators, type OffCanvasRect } from "./OffCanvasIndicators";
+import { ChildRectOutlines, OffCanvasIndicators } from "./OffCanvasIndicators";
import { createDomEditOverlayGestureHandlers } from "./useDomEditOverlayGestures";
import { useDomEditNudge } from "./useDomEditNudge";
import { SnapGuideOverlay, type SnapGuidesState } from "./SnapGuideOverlay";
@@ -27,13 +27,13 @@ import { hugRectForElement } from "./domEditOverlayCrop";
import { useCropOverlay } from "../../hooks/useCropOverlay";
import { readDomEditSelectionShapeStyles, resolveBoxChromeClass } from "./domEditOverlayShape";
import { useDomEditCompositionRect } from "./useDomEditCompositionRect";
-import { useMountEffect } from "../../hooks/useMountEffect";
-import { startOffCanvasIndicatorRefresh } from "./offCanvasIndicatorRefresh";
import { CanvasContextMenu } from "./CanvasContextMenu";
import { useInlineTextEditing } from "./useInlineTextEditing";
+import { usePreviewReadOnly } from "./previewReadOnlyContext";
import type { ZOrderAction, ZOrderPatch } from "./canvasContextMenuZOrder";
import { getPreviewTargetFromPointer } from "../../utils/studioPreviewHelpers";
import { logSelect } from "../../utils/selectDebug";
+import { useOffCanvasIndicators } from "./useOffCanvasIndicators";
// Re-exports for external consumers — preserving existing import paths.
export {
@@ -137,6 +137,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
onDeleteSelection,
onApplyZIndex,
}: DomEditOverlayProps) {
+ const readOnly = usePreviewReadOnly();
const overlayRef = useRef<HTMLDivElement | null>(null);
const boxRef = useRef<HTMLDivElement | null>(null);
const onMarqueeSelectRef = useRef(onMarqueeSelect);
@@ -220,39 +221,13 @@ export const DomEditOverlay = memo(function DomEditOverlay({
const boxClipPath = hasCropInsets ? undefined : selectionShapeStyles.clipPath;
const boxChromeClass = resolveBoxChromeClass(Boolean(cropOutlineInsetPx), boxClipPath);
- // Off-canvas element indicators — dashed outlines for elements positioned
- // outside the composition bounds so users can find them.
- const offCanvasElementsRef = useRef<Map<string, HTMLElement>>(new Map());
- const [offCanvasRects, setOffCanvasRects] = useState<OffCanvasRect[]>([]);
- const offCanvasDirtyRef = useRef(true);
- const offCanvasSigRef = useRef("");
- const offCanvasObserverRef = useRef<MutationObserver | null>(null);
- const offCanvasObservedDocRef = useRef<Document | null>(null);
-
- // Positions depend on live iframe layout, not selection — the selected-element
- // suppression is a render-time filter, so selection/groupSelections stay out
- // of the geometry walk.
- useMountEffect(() =>
- startOffCanvasIndicatorRefresh({
- iframeRef,
- overlayRef,
- compRectRef,
- activeCompositionPathRef,
- dirtyRef: offCanvasDirtyRef,
- sigRef: offCanvasSigRef,
- observerRef: offCanvasObserverRef,
- observedDocRef: offCanvasObservedDocRef,
- elementsRef: offCanvasElementsRef,
- setRects: setOffCanvasRects,
- }),
- );
-
- // Switching compositions may not swap the iframe document (so the observer's
- // doc-swap detection wouldn't fire) yet changes which elements are off-canvas.
- // Force a recompute explicitly on comp change.
- useEffect(() => {
- offCanvasDirtyRef.current = true;
- }, [activeCompositionPath]);
+ const { offCanvasRects, offCanvasElementsRef } = useOffCanvasIndicators({
+ iframeRef,
+ overlayRef,
+ compRectRef,
+ activeCompositionPathRef,
+ activeCompositionPath,
+ });
const gestures = createDomEditOverlayGestureHandlers({
overlayRef,
@@ -280,12 +255,16 @@ export const DomEditOverlay = memo(function DomEditOverlay({
snapGuidesRef,
});
+ useEffect(() => {
+ if (readOnly) gestures.clearPointerState(selectionRef);
+ }, [gestures, readOnly, selectionRef]);
+
// Arrow-key nudge (1px, Shift = 10px) — commits through the same
// path-offset callbacks as a drag, one undo entry per key burst.
const { flushNudge } = useDomEditNudge({
selection,
groupSelections,
- allowCanvasMovement,
+ allowCanvasMovement: allowCanvasMovement && !readOnly,
selectionRef,
overlayRectRef,
groupOverlayItemsRef,
@@ -558,7 +537,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
selection={contextMenu.sel}
onClose={closeContextMenu}
onDelete={
- onDeleteSelection
+ onDeleteSelection && !readOnly
? (sel) => {
closeContextMenu();
onDeleteSelection(sel);
@@ -566,7 +545,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
: undefined
}
onApplyZIndex={
- onApplyZIndex
+ onApplyZIndex && !readOnly
? (patches, action, crossed) => {
onApplyZIndex(contextMenu.sel, patches, action, crossed);
}
diff --git a/packages/studio/src/components/editor/DomEditOverlayHover.test.tsx b/packages/studio/src/components/editor/DomEditOverlayHover.test.tsx
index c7e82693ec..6e36abfdff 100644
--- a/packages/studio/src/components/editor/DomEditOverlayHover.test.tsx
+++ b/packages/studio/src/components/editor/DomEditOverlayHover.test.tsx
@@ -4,6 +4,7 @@ import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { expect, it, vi } from "vitest";
import type { DomEditSelection } from "./domEditing";
+import "./domEditOverlayTestMocks";
import { DomEditOverlay } from "./DomEditOverlay";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -33,21 +34,6 @@ vi.mock("./useDomEditOverlayRects", () => ({
}),
}));
-vi.mock("./useDomEditCompositionRect", () => ({
- useDomEditCompositionRect: () => ({
- left: 0,
- top: 0,
- width: 800,
- height: 450,
- scaleX: 1,
- scaleY: 1,
- }),
-}));
-
-vi.mock("./offCanvasIndicatorRefresh", () => ({
- startOffCanvasIndicatorRefresh: () => () => undefined,
-}));
-
function renderHover(angle: number): string {
hoverState.angle = angle;
const host = document.createElement("div");
diff --git a/packages/studio/src/components/editor/DomEditSelectionChrome.tsx b/packages/studio/src/components/editor/DomEditSelectionChrome.tsx
index 720352e7ef..23aaaeeff2 100644
--- a/packages/studio/src/components/editor/DomEditSelectionChrome.tsx
+++ b/packages/studio/src/components/editor/DomEditSelectionChrome.tsx
@@ -6,6 +6,7 @@ import type { createDomEditOverlayGestureHandlers } from "./useDomEditOverlayGes
import { DomEditCropHandles } from "./DomEditCropHandles";
import { DomEditRotateHandle } from "./DomEditRotateHandle";
import { resolveRotatedResizeCursor } from "./domEditResizeLocal";
+import { usePreviewReadOnly } from "./previewReadOnlyContext";
// Corner resize handles, Canva-style: one per corner, diagonal cursors.
// Corners scale about the element center; the translate keeps the center
@@ -75,6 +76,7 @@ export function DomEditGroupChrome({
onBoxMouseDown,
onBoxClick,
}: DomEditGroupChromeProps) {
+ const canManipulate = allowCanvasMovement && !usePreviewReadOnly();
return (
<>
{groupOverlayItems.map((item) => (
@@ -98,10 +100,10 @@ export function DomEditGroupChrome({
top: groupBounds.top,
width: groupBounds.width,
height: groupBounds.height,
- cursor: allowCanvasMovement && groupCanMove ? "move" : "default",
+ cursor: canManipulate && groupCanMove ? "move" : "default",
}}
onPointerDown={(e) => {
- if (!allowCanvasMovement || !groupCanMove || e.shiftKey) return;
+ if (!canManipulate || !groupCanMove || e.shiftKey) return;
gestures.startGroupDrag(e);
}}
onMouseDown={onBoxMouseDown}
@@ -164,6 +166,8 @@ export function DomEditSelectionChrome({
// into: left interactive, it swallows every press, so the caret can never be
// moved and characters can never be selected by dragging.
const editing = inlineText?.editing ?? false;
+ const readOnly = usePreviewReadOnly();
+ const canManipulate = allowCanvasMovement && !readOnly;
return (
<>
@@ -174,7 +178,7 @@ export function DomEditSelectionChrome({
transform: overlayRect.angle ? `rotate(${overlayRect.angle}deg)` : undefined,
}}
>
- {allowCanvasMovement && !editing && selection.capabilities.canApplyManualRotation && (
+ {canManipulate && !editing && selection.capabilities.canApplyManualRotation && (
<DomEditRotateHandle
overlayRect={overlayRect}
cropOutlineInsetPx={cropOutlineInsetPx}
@@ -196,9 +200,7 @@ export function DomEditSelectionChrome({
height: overlayRect.height,
clipPath: boxClipPath,
cursor:
- allowCanvasMovement && selection.capabilities.canApplyManualOffset
- ? "move"
- : "default",
+ canManipulate && selection.capabilities.canApplyManualOffset ? "move" : "default",
}}
onPointerDown={(e) => {
// A second press opens the element's text for editing, and must be
@@ -211,7 +213,7 @@ export function DomEditSelectionChrome({
e.stopPropagation();
return;
}
- if (!allowCanvasMovement || e.shiftKey) return;
+ if (!canManipulate || e.shiftKey) return;
if (selection.capabilities.canApplyManualOffset) {
gestures.startGesture("drag", e);
return;
@@ -245,7 +247,7 @@ export function DomEditSelectionChrome({
children, so they paint strictly above the box border. Each handle
is positioned relative to the overlay container using the
overlayRect origin, matching the old child-relative offsets. */}
- {allowCanvasMovement &&
+ {canManipulate &&
!editing &&
selection.capabilities.canApplyManualSize &&
RESIZE_HANDLE_DEFS.map((def) =>
@@ -271,7 +273,7 @@ export function DomEditSelectionChrome({
</div>
{/* Crop owns its element-local oriented frame. Keep it outside the chrome's
rotated plane or a rotated selection applies the angle twice. */}
- {selection.capabilities.canCrop && !editing && groupSelectionCount <= 1 && (
+ {selection.capabilities.canCrop && !editing && !readOnly && groupSelectionCount <= 1 && (
<DomEditCropHandles
selection={selection}
overlayRect={overlayRect}
diff --git a/packages/studio/src/components/editor/PropertyPanel.deselect.test.tsx b/packages/studio/src/components/editor/PropertyPanel.deselect.test.tsx
new file mode 100644
index 0000000000..6b7bf7e75e
--- /dev/null
+++ b/packages/studio/src/components/editor/PropertyPanel.deselect.test.tsx
@@ -0,0 +1,71 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it, vi } from "vitest";
+import { PropertyPanel } from "./PropertyPanel";
+import type { PropertyPanelProps } from "./propertyPanelHelpers";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock("../../contexts/StudioContext", async () => {
+ const actual = await vi.importActual<typeof import("../../contexts/StudioContext")>(
+ "../../contexts/StudioContext",
+ );
+ return { ...actual, useStudioShellContext: () => ({ showToast: vi.fn() }) };
+});
+
+function selectedElement(): NonNullable<PropertyPanelProps["element"]> {
+ return {
+ element: document.createElement("div"),
+ id: "el",
+ selector: "#el",
+ label: "El",
+ tagName: "div",
+ sourceFile: "index.html",
+ compositionPath: "index.html",
+ isCompositionHost: false,
+ isInsideLockedComposition: false,
+ boundingBox: { x: 0, y: 0, width: 10, height: 10 },
+ textContent: "",
+ dataAttributes: {},
+ inlineStyles: {},
+ computedStyles: {},
+ textFields: [],
+ capabilities: {
+ canSelect: true,
+ canEditStyles: true,
+ canCrop: true,
+ canMove: true,
+ canResize: true,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: true,
+ },
+ };
+}
+
+describe("PropertyPanel deselect", () => {
+ it("re-renders to the empty state on deselect without a hooks-order crash", () => {
+ const props = {
+ element: selectedElement(),
+ assets: [],
+ onSetStyle: vi.fn(),
+ onSetText: vi.fn(),
+ onSetAttributeLive: vi.fn(),
+ onClearSelection: vi.fn(),
+ } as unknown as PropertyPanelProps;
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ act(() => root.render(<PropertyPanel {...props} />));
+
+ // A same-instance re-render with no element — Escape, clicking empty canvas,
+ // or "Clear selection" — must not change which hooks ran.
+ expect(() => {
+ act(() => root.render(<PropertyPanel {...props} element={null} />));
+ }).not.toThrow();
+
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/studio/src/components/editor/PropertyPanel.tsx b/packages/studio/src/components/editor/PropertyPanel.tsx
index ed13dd3afa..53fa5f1b4f 100644
--- a/packages/studio/src/components/editor/PropertyPanel.tsx
+++ b/packages/studio/src/components/editor/PropertyPanel.tsx
@@ -37,6 +37,7 @@ import { GestureRecordPanelButton } from "./GestureRecordControl";
import { PropertyPanelEmptyState } from "./PropertyPanelEmptyState";
import { DesignPanelInputProvider } from "../../contexts/DesignPanelInputContext";
import { isAudioDomElement } from "../../utils/timelineInspector";
+import { useManualEditDisabledFlags } from "./previewReadOnlyContext";
// Re-export helpers that external consumers import from this module
export {
@@ -175,6 +176,9 @@ export const PropertyPanel = memo(function PropertyPanel(props: PropertyPanelPro
scale: 1,
transformPerspective: 0,
};
+ // Unconditional like the hooks above: must not sit behind the `!element` return below.
+ const { manualOffsetEditingDisabled, manualSizeEditingDisabled, manualRotationEditingDisabled } =
+ useManualEditDisabledFlags(element?.capabilities);
if (!element) {
return (
@@ -189,9 +193,6 @@ export const PropertyPanel = memo(function PropertyPanel(props: PropertyPanelPro
);
}
- const manualOffsetEditingDisabled = !element.capabilities.canApplyManualOffset;
- const manualSizeEditingDisabled = !element.capabilities.canApplyManualSize;
- const manualRotationEditingDisabled = !element.capabilities.canApplyManualRotation;
const sourceLabel = element.id ? `#${element.id}` : (element.selector ?? "");
// Capabilities are already resolved on the selection; recompute only sections,
// feeding the live GSAP tween count (arrives on the gsapAnimations prop, not the
diff --git a/packages/studio/src/components/editor/SnapToolbar.test.tsx b/packages/studio/src/components/editor/SnapToolbar.test.tsx
index 2a3d060045..0abd1eee2a 100644
--- a/packages/studio/src/components/editor/SnapToolbar.test.tsx
+++ b/packages/studio/src/components/editor/SnapToolbar.test.tsx
@@ -54,6 +54,7 @@ function AppHotkeyHarness() {
handleDuplicate: vi.fn(async () => false),
onResetKeyframes: vi.fn(() => false),
onDeleteSelectedKeyframes: vi.fn(),
+ readOnlyPreview: false,
});
return null;
diff --git a/packages/studio/src/components/editor/domEditOverlayTestMocks.ts b/packages/studio/src/components/editor/domEditOverlayTestMocks.ts
new file mode 100644
index 0000000000..d9a5fbe916
--- /dev/null
+++ b/packages/studio/src/components/editor/domEditOverlayTestMocks.ts
@@ -0,0 +1,16 @@
+import { vi } from "vitest";
+
+vi.mock("./useDomEditCompositionRect", () => ({
+ useDomEditCompositionRect: () => ({
+ left: 0,
+ top: 0,
+ width: 800,
+ height: 450,
+ scaleX: 1,
+ scaleY: 1,
+ }),
+}));
+
+vi.mock("./offCanvasIndicatorRefresh", () => ({
+ startOffCanvasIndicatorRefresh: () => () => undefined,
+}));
diff --git a/packages/studio/src/components/editor/previewReadOnly.overlay.test.tsx b/packages/studio/src/components/editor/previewReadOnly.overlay.test.tsx
new file mode 100644
index 0000000000..5b48cf76a1
--- /dev/null
+++ b/packages/studio/src/components/editor/previewReadOnly.overlay.test.tsx
@@ -0,0 +1,260 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { makeSelection } from "../../hooks/domSelectionTestHarness";
+import { CANVAS_NUDGE_COMMIT_DEBOUNCE_MS } from "./domEditNudge";
+import { __resetForTests } from "../../utils/canvasNudgeGate";
+import { PreviewReadOnlyProvider } from "./previewReadOnlyContext";
+import "./domEditOverlayTestMocks";
+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[] }));
+
+vi.mock("./useDomEditOverlayRects", () => ({
+ useDomEditOverlayRects: () => ({
+ overlayRect: { left: 100, top: 100, width: 200, height: 100, editScaleX: 1, editScaleY: 1 },
+ overlayRectRef: {
+ current: { left: 100, top: 100, width: 200, height: 100, editScaleX: 1, editScaleY: 1 },
+ },
+ setOverlayRect: () => undefined,
+ hoverRect: null,
+ groupOverlayItems: layout.group,
+ groupOverlayItemsRef: { current: layout.group },
+ setGroupOverlayItems: () => undefined,
+ childRects: [],
+ }),
+}));
+const BOX = '[data-dom-edit-selection-box="true"]';
+let root: Root;
+let host: HTMLElement;
+
+function textElement(id: string): HTMLElement {
+ const element = document.createElement("h1");
+ element.id = id;
+ element.textContent = "Title";
+ document.body.append(element);
+ return element;
+}
+
+function fixture(
+ overrides: Partial<React.ComponentProps<typeof DomEditOverlay>> = {},
+ readOnly = false,
+) {
+ const spies = {
+ onCanvasMouseDown: vi.fn(),
+ onSelectionChange: vi.fn(),
+ onManualDragStart: vi.fn(),
+ onBlockedMove: vi.fn(),
+ onPathOffsetCommit: vi.fn(),
+ onGroupPathOffsetCommit: vi.fn(),
+ onBoxSizeCommit: vi.fn(),
+ onRotationCommit: vi.fn(),
+ onStyleCommit: vi.fn(),
+ onDeleteSelection: vi.fn(),
+ onApplyZIndex: vi.fn(),
+ };
+ const selection = makeSelection("Title", textElement("title"));
+ selection.capabilities.canApplyManualRotation = true;
+ selection.textFields = [{ key: "text", label: "Text", value: "Title" }] as never;
+ const props = {
+ iframeRef: { current: document.createElement("iframe") },
+ activeCompositionPath: null,
+ selection,
+ hoverSelection: null,
+ onCanvasPointerMove: () => Promise.resolve(selection),
+ onCanvasPointerLeave: () => undefined,
+ ...spies,
+ ...overrides,
+ };
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ act(() =>
+ root.render(
+ <PreviewReadOnlyProvider readOnly={readOnly}>
+ <DomEditOverlay {...props} />
+ </PreviewReadOnlyProvider>,
+ ),
+ );
+ return { spies, selection, overlay: host.firstElementChild as HTMLElement };
+}
+
+const fire = (target: Element, type: string, init: MouseEventInit = {}) => {
+ const event = new MouseEvent(type, { bubbles: true, cancelable: true, button: 0, ...init });
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ return event;
+};
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ __resetForTests();
+ HTMLElement.prototype.setPointerCapture = () => undefined;
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ document.body.innerHTML = "";
+ layout.group = [];
+ vi.useRealTimers();
+});
+
+describe("DomEditOverlay with the preview read-only", () => {
+ it("control: with the flag off a press on the box starts a move", () => {
+ const { spies, overlay } = fixture();
+ fire(overlay.querySelector(BOX)!, "pointerdown");
+ expect(spies.onManualDragStart).toHaveBeenCalledTimes(1);
+ });
+
+ it("refuses to start a move from the selection box", () => {
+ const { spies, overlay } = fixture({}, true);
+ const box = overlay.querySelector(BOX)!;
+ fire(box, "pointerdown");
+ fire(box, "pointermove", { clientX: 40 });
+ fire(box, "pointerup");
+ expect(spies.onManualDragStart).not.toHaveBeenCalled();
+ expect(spies.onBlockedMove).not.toHaveBeenCalled();
+ expect(spies.onPathOffsetCommit).not.toHaveBeenCalled();
+ });
+
+ it("offers no resize dots, and none can start a resize", () => {
+ const off = fixture();
+ expect(off.overlay.querySelectorAll("div.h-4.w-4")).toHaveLength(4);
+ act(() => root.unmount());
+ document.body.innerHTML = "";
+ const { spies, overlay } = fixture({}, true);
+ expect(overlay.querySelectorAll("div.h-4.w-4")).toHaveLength(0);
+ expect(spies.onBoxSizeCommit).not.toHaveBeenCalled();
+ });
+
+ it("offers no rotate handle", () => {
+ const off = fixture();
+ expect(off.overlay.querySelector('[aria-label="Rotate selection"]')).not.toBeNull();
+ act(() => root.unmount());
+ document.body.innerHTML = "";
+ const { spies, overlay } = fixture({}, true);
+ expect(overlay.querySelector('[aria-label="Rotate selection"]')).toBeNull();
+ expect(spies.onRotationCommit).not.toHaveBeenCalled();
+ });
+
+ it("offers no crop handles, so clip-path is never committed", () => {
+ const off = fixture();
+ expect(off.overlay.querySelector("[data-dom-edit-crop-frame]")).not.toBeNull();
+ act(() => root.unmount());
+ document.body.innerHTML = "";
+ const { spies, overlay } = fixture({}, true);
+ expect(overlay.querySelector("[data-dom-edit-crop-frame]")).toBeNull();
+ expect(spies.onStyleCommit).not.toHaveBeenCalled();
+ });
+
+ it("does not drag a multi-selection", () => {
+ const members = ["a", "b"].map((id) => {
+ const selection = makeSelection(id, textElement(id));
+ return { key: id, selection, element: selection.element, rect: RECT };
+ });
+ layout.group = members;
+ const { spies, overlay } = fixture(
+ {
+ selection: null,
+ groupSelections: members.map((m) => m.selection),
+ },
+ true,
+ );
+ fire(overlay.querySelector(BOX)!, "pointerdown");
+ expect(spies.onManualDragStart).not.toHaveBeenCalled();
+ expect(spies.onGroupPathOffsetCommit).not.toHaveBeenCalled();
+ });
+
+ const nudge = () => {
+ const event = new KeyboardEvent("keydown", {
+ key: "ArrowRight",
+ bubbles: true,
+ cancelable: true,
+ });
+ act(() => {
+ window.dispatchEvent(event);
+ vi.advanceTimersByTime(CANVAS_NUDGE_COMMIT_DEBOUNCE_MS + 10);
+ });
+ return event;
+ };
+
+ it("control: with the flag off an arrow key nudges", () => {
+ const { spies } = fixture();
+ expect(nudge().defaultPrevented).toBe(true);
+ expect(spies.onPathOffsetCommit).toHaveBeenCalledTimes(1);
+ });
+
+ it("neither nudges on an arrow key nor swallows it", () => {
+ const { spies } = fixture({}, true);
+ expect(nudge().defaultPrevented).toBe(false);
+ 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);
+ expect(selection.element.hasAttribute("contenteditable")).toBe(true);
+ });
+
+ it("does not open text for editing on Enter", () => {
+ const { selection, overlay } = fixture({}, true);
+ pressEnter(overlay);
+ 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);
+ expect(document.body.textContent).toContain("Delete");
+ });
+
+ it("offers no delete or z-order on right-click when read-only", async () => {
+ // Same fixture as the control test above (a real, already-selected element) so the
+ // context menu actually opens; `selection: null` here would close it via
+ // useCanvasContextMenuState's own deselect effect, before read-only ever mattered.
+ const { spies, overlay } = fixture({}, true);
+ await rightClick(overlay);
+ expect(document.body.textContent).not.toContain("Delete");
+ expect(spies.onDeleteSelection).not.toHaveBeenCalled();
+ expect(spies.onApplyZIndex).not.toHaveBeenCalled();
+ });
+
+ it("still selects and reports to the host on right-click of an unselected element", async () => {
+ const { spies, overlay } = fixture({ selection: null }, true);
+ await rightClick(overlay);
+ expect(spies.onSelectionChange).toHaveBeenCalledTimes(1);
+ });
+
+ it("still selects and reports to the host on a click", () => {
+ const { spies, overlay } = fixture({ selection: null }, true);
+ fire(overlay, "mousedown");
+ expect(spies.onCanvasMouseDown).toHaveBeenCalledTimes(1);
+ });
+
+ it("still selects on a click of the selection box", () => {
+ const { spies, overlay } = fixture({}, true);
+ fire(overlay.querySelector(BOX)!, "click");
+ expect(spies.onCanvasMouseDown).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/studio/src/components/editor/previewReadOnlyContext.tsx b/packages/studio/src/components/editor/previewReadOnlyContext.tsx
new file mode 100644
index 0000000000..037d6d8e6b
--- /dev/null
+++ b/packages/studio/src/components/editor/previewReadOnlyContext.tsx
@@ -0,0 +1,59 @@
+import { useContext, useMemo, type ReactNode } from "react";
+import { createStableContext } from "../../utils/hmrStableContext";
+
+interface PreviewReadOnlyValue {
+ readOnly: boolean;
+ reason: string;
+}
+
+const DEFAULT_REASON = "Preview is read-only.";
+
+// Real default (not a throwing required-provider context): most existing
+// mounts render with no wrapper at all and must stay editable, exactly as today.
+const PreviewReadOnlyContext = createStableContext<PreviewReadOnlyValue>("PreviewReadOnlyContext", {
+ readOnly: false,
+ reason: DEFAULT_REASON,
+});
+
+export function PreviewReadOnlyProvider({
+ readOnly,
+ reason,
+ children,
+}: {
+ readOnly: boolean;
+ reason?: string;
+ children: ReactNode;
+}) {
+ const value = useMemo(() => ({ readOnly, reason: reason ?? DEFAULT_REASON }), [readOnly, reason]);
+ return <PreviewReadOnlyContext value={value}>{children}</PreviewReadOnlyContext>;
+}
+
+export function usePreviewReadOnly(): boolean {
+ return useContext(PreviewReadOnlyContext).readOnly;
+}
+
+/** Short host-supplied text for why a hand-edit control is disabled. */
+export function usePreviewReadOnlyReason(): string {
+ return useContext(PreviewReadOnlyContext).reason;
+}
+
+interface ManualEditCapabilities {
+ canApplyManualOffset: boolean;
+ canApplyManualSize: boolean;
+ canApplyManualRotation: boolean;
+}
+
+/**
+ * The manual X/Y/W/H/rotation fields' disabled state: capability, or preview read-only.
+ * Call unconditionally, even with no selection — `capabilities` may be null/undefined.
+ */
+export function useManualEditDisabledFlags(
+ capabilities: ManualEditCapabilities | null | undefined,
+) {
+ const { readOnly } = useContext(PreviewReadOnlyContext);
+ return {
+ manualOffsetEditingDisabled: !capabilities?.canApplyManualOffset || readOnly,
+ manualSizeEditingDisabled: !capabilities?.canApplyManualSize || readOnly,
+ manualRotationEditingDisabled: !capabilities?.canApplyManualRotation || readOnly,
+ };
+}
diff --git a/packages/studio/src/components/editor/propertyPanelFlatLayoutSection.tsx b/packages/studio/src/components/editor/propertyPanelFlatLayoutSection.tsx
index e4f7160059..8aa07cc414 100644
--- a/packages/studio/src/components/editor/propertyPanelFlatLayoutSection.tsx
+++ b/packages/studio/src/components/editor/propertyPanelFlatLayoutSection.tsx
@@ -5,6 +5,7 @@ import { formatPxMetricValue } from "./propertyPanelHelpers";
import { resolveValueTier } from "./propertyPanelValueTier";
import { PropertyPanel3dTransform } from "./propertyPanel3dTransform";
import type { DomEditSelection } from "./domEditingTypes";
+import { usePreviewReadOnly, usePreviewReadOnlyReason } from "./previewReadOnlyContext";
type KeyframeEntry = Array<{
percentage: number;
@@ -119,6 +120,9 @@ export function LayoutGeometryRows({
onRemoveKeyframe,
onConvertToKeyframes,
}: GeometryRowsProps) {
+ const readOnlyPreview = usePreviewReadOnly();
+ const readOnlyPreviewReason = usePreviewReadOnlyReason();
+ const readOnlyTooltip = readOnlyPreview ? readOnlyPreviewReason : undefined;
const gutterProps = {
element,
gsapAnimId,
@@ -137,6 +141,7 @@ export function LayoutGeometryRows({
value={formatPxMetricValue(displayX)}
tier={displayX === 0 ? "default" : "explicitCustom"}
disabled={manualOffsetEditingDisabled}
+ tooltip={readOnlyTooltip}
onCommit={(next) => commitManualOffset("x", next)}
suffix={<KeyframeGutter property="x" displayValue={displayX} {...gutterProps} />}
/>
@@ -145,6 +150,7 @@ export function LayoutGeometryRows({
value={formatPxMetricValue(displayY)}
tier={displayY === 0 ? "default" : "explicitCustom"}
disabled={manualOffsetEditingDisabled}
+ tooltip={readOnlyTooltip}
onCommit={(next) => commitManualOffset("y", next)}
suffix={<KeyframeGutter property="y" displayValue={displayY} {...gutterProps} />}
/>
@@ -153,6 +159,7 @@ export function LayoutGeometryRows({
value={formatPxMetricValue(displayW)}
tier="default"
disabled={manualSizeEditingDisabled}
+ tooltip={readOnlyTooltip}
onCommit={(next) => commitManualSize("width", next)}
suffix={<KeyframeGutter property="width" displayValue={displayW} {...gutterProps} />}
/>
@@ -161,6 +168,7 @@ export function LayoutGeometryRows({
value={formatPxMetricValue(displayH)}
tier="default"
disabled={manualSizeEditingDisabled}
+ tooltip={readOnlyTooltip}
onCommit={(next) => commitManualSize("height", next)}
suffix={<KeyframeGutter property="height" displayValue={displayH} {...gutterProps} />}
/>
@@ -169,6 +177,7 @@ export function LayoutGeometryRows({
value={`${displayR}°`}
tier="default"
disabled={manualRotationEditingDisabled}
+ tooltip={readOnlyTooltip}
onCommit={(next) => commitManualRotation(next.replace("°", ""))}
suffix={<KeyframeGutter property="rotation" displayValue={displayR} {...gutterProps} />}
/>
diff --git a/packages/studio/src/components/editor/propertyPanelFlatPrimitives.tsx b/packages/studio/src/components/editor/propertyPanelFlatPrimitives.tsx
index 2af1c6387d..7bb75a6932 100644
--- a/packages/studio/src/components/editor/propertyPanelFlatPrimitives.tsx
+++ b/packages/studio/src/components/editor/propertyPanelFlatPrimitives.tsx
@@ -19,6 +19,7 @@ export function FlatRow({
value,
tier,
disabled,
+ tooltip,
liveCommit,
suffix,
dropdown,
@@ -30,6 +31,8 @@ export function FlatRow({
value: string;
tier: PropertyValueTier;
disabled?: boolean;
+ /** Shown as a title attribute, e.g. why the row is disabled. */
+ tooltip?: string;
liveCommit?: boolean;
suffix?: ReactNode;
/** Renders a trailing 10px caret-down, for select-backed rows. */
@@ -40,7 +43,7 @@ export function FlatRow({
}) {
const track = useTrackDesignInput();
return (
- <div className="group flex min-h-[30px] items-center justify-between gap-3">
+ <div className="group flex min-h-[30px] items-center justify-between gap-3" title={tooltip}>
<span className={`text-[11px] ${VALUE_TIER_LABEL_CLASS[tier]}`}>{label}</span>
<span className="flex min-w-0 shrink-0 items-center gap-1.5">
<span
diff --git a/packages/studio/src/components/editor/useDomEditNudge.ts b/packages/studio/src/components/editor/useDomEditNudge.ts
index cc76ff18b9..55d757783e 100644
--- a/packages/studio/src/components/editor/useDomEditNudge.ts
+++ b/packages/studio/src/components/editor/useDomEditNudge.ts
@@ -167,6 +167,15 @@ export function useDomEditNudge(params: UseDomEditNudgeParams): { flushNudge: ()
const commitSessionRef = useRef(commitSession);
commitSessionRef.current = commitSession;
+ useEffect(() => {
+ if (params.allowCanvasMovement || !sessionRef.current) return;
+ const session = sessionRef.current;
+ sessionRef.current = null;
+ if (session.timer) clearTimeout(session.timer);
+ restoreManualOffsetDragMembers(session.members);
+ endManualOffsetDragMembers(session.members);
+ }, [params.allowCanvasMovement]);
+
// Build drag members for the current target set — the same member snapshot a
// pointer drag starts from (startGesture / startGroupDrag), so the nudge
// commit converts offsets → GSAP x/y with identical math.
diff --git a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts
index 9f5dffbc56..b31b16f3a2 100644
--- a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts
+++ b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts
@@ -532,6 +532,10 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
restoreGestureOverlayRect(g);
}
if (g?.mode === "rotation" && sel) {
+ applyRotationDraftViaGsap(
+ sel.element,
+ g.actualRotation - (Number.parseFloat(g.initialRotation.studioRotation) || 0),
+ );
restoreStudioRotation(sel.element, g.initialRotation);
endStudioManualEditGesture(sel.element, g.manualEditDragToken);
}
diff --git a/packages/studio/src/components/editor/useOffCanvasIndicators.ts b/packages/studio/src/components/editor/useOffCanvasIndicators.ts
new file mode 100644
index 0000000000..608349659e
--- /dev/null
+++ b/packages/studio/src/components/editor/useOffCanvasIndicators.ts
@@ -0,0 +1,50 @@
+import { useEffect, useRef, useState, type RefObject } from "react";
+import { useMountEffect } from "../../hooks/useMountEffect";
+import type { DomEditCompositionRect } from "./useDomEditCompositionRect";
+import { type OffCanvasRect } from "./OffCanvasIndicators";
+import { startOffCanvasIndicatorRefresh } from "./offCanvasIndicatorRefresh";
+
+export function useOffCanvasIndicators({
+ iframeRef,
+ overlayRef,
+ compRectRef,
+ activeCompositionPathRef,
+ activeCompositionPath,
+}: {
+ iframeRef: RefObject<HTMLIFrameElement | null>;
+ overlayRef: RefObject<HTMLDivElement | null>;
+ compRectRef: React.MutableRefObject<DomEditCompositionRect>;
+ activeCompositionPathRef: React.MutableRefObject<string | null>;
+ activeCompositionPath: string | null;
+}): {
+ offCanvasRects: OffCanvasRect[];
+ offCanvasElementsRef: React.MutableRefObject<Map<string, HTMLElement>>;
+} {
+ const offCanvasElementsRef = useRef<Map<string, HTMLElement>>(new Map());
+ const [offCanvasRects, setOffCanvasRects] = useState<OffCanvasRect[]>([]);
+ const offCanvasDirtyRef = useRef(true);
+ const offCanvasSigRef = useRef("");
+ const offCanvasObserverRef = useRef<MutationObserver | null>(null);
+ const offCanvasObservedDocRef = useRef<Document | null>(null);
+
+ useMountEffect(() =>
+ startOffCanvasIndicatorRefresh({
+ iframeRef,
+ overlayRef,
+ compRectRef,
+ activeCompositionPathRef,
+ dirtyRef: offCanvasDirtyRef,
+ sigRef: offCanvasSigRef,
+ observerRef: offCanvasObserverRef,
+ observedDocRef: offCanvasObservedDocRef,
+ elementsRef: offCanvasElementsRef,
+ setRects: setOffCanvasRects,
+ }),
+ );
+
+ useEffect(() => {
+ offCanvasDirtyRef.current = true;
+ }, [activeCompositionPath]);
+
+ return { offCanvasRects, offCanvasElementsRef };
+}
diff --git a/packages/studio/src/components/nle/PreviewOverlays.topologyLens.test.tsx b/packages/studio/src/components/nle/PreviewOverlays.topologyLens.test.tsx
index 1b80925bcb..84a53c2e88 100644
--- a/packages/studio/src/components/nle/PreviewOverlays.topologyLens.test.tsx
+++ b/packages/studio/src/components/nle/PreviewOverlays.topologyLens.test.tsx
@@ -3,21 +3,13 @@
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 "./PreviewOverlaysTestMocks";
import { PreviewOverlays } from "./PreviewOverlays";
-(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const previewState = getPreviewState();
-const previewState = vi.hoisted(() => ({ captionEditMode: false }));
-const iframeRef = { current: null as HTMLIFrameElement | null };
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-vi.mock("../../contexts/StudioContext", () => ({
- useStudioShellContext: () => ({ activeCompPath: "index.html", previewIframeRef: iframeRef }),
- useStudioPlaybackContext: () => ({
- captionEditMode: previewState.captionEditMode,
- compositionLoading: false,
- isPlaying: false,
- }),
-}));
vi.mock("../../contexts/DomEditContext", () => ({
useDomEditSelectionContext: () => ({
domEditHoverSelection: null,
@@ -41,30 +33,7 @@ vi.mock("../../contexts/DomEditContext", () => ({
handleDomZIndexReorderCommit: vi.fn(),
}),
}));
-vi.mock("../../captions/store", () => {
- const state = {
- model: null,
- dismissed: false,
- syncError: null,
- clearSelection: vi.fn(),
- setDismissed: vi.fn(),
- setEditMode: vi.fn(),
- setSyncError: vi.fn(),
- };
- return {
- useCaptionStore: Object.assign(
- (selector: (value: typeof state) => unknown) => selector(state),
- { getState: () => state },
- ),
- };
-});
-vi.mock("../../hooks/useCompositionDimensions", () => ({
- useCompositionDimensions: () => null,
-}));
-vi.mock("../../utils/studioUiPreferences", () => ({ readStudioUiPreferences: () => ({}) }));
-vi.mock("./useCanvasZOrderTimelineMirror", () => ({
- useCanvasZOrderTimelineMirror: () => vi.fn(),
-}));
+
vi.mock("../editor/TopologyLens", async () => {
const { createElement } = await import("react");
return {
diff --git a/packages/studio/src/components/nle/PreviewOverlays.tsx b/packages/studio/src/components/nle/PreviewOverlays.tsx
index 6a6d26ae0f..293481c9b3 100644
--- a/packages/studio/src/components/nle/PreviewOverlays.tsx
+++ b/packages/studio/src/components/nle/PreviewOverlays.tsx
@@ -5,6 +5,7 @@ import { DomEditOverlay } from "../editor/DomEditOverlay";
import { TopologyLens } from "../editor/TopologyLens";
import { MotionPathOverlay } from "../editor/MotionPathOverlay";
import { SnapToolbar } from "../editor/SnapToolbar";
+import { usePreviewReadOnly } from "../editor/previewReadOnlyContext";
import { useCompositionDimensions } from "../../hooks/useCompositionDimensions";
import { useStudioPlaybackContext, useStudioShellContext } from "../../contexts/StudioContext";
import {
@@ -140,6 +141,8 @@ export function PreviewOverlays({
const { activeCompPath, previewIframeRef } = useStudioShellContext();
const { captionEditMode, compositionLoading, isPlaying } = useStudioPlaybackContext();
const compositionDimensions = useCompositionDimensions(previewIframeRef);
+ const readOnly = usePreviewReadOnly();
+ const previewCaptionEditMode = captionEditMode && !readOnly;
// Caption edit mode is entered automatically when captions are detected;
// these give the author an explicit way OUT (and back in). Without them the
@@ -216,7 +219,7 @@ export function PreviewOverlays({
);
}
- if (captionEditMode) {
+ if (previewCaptionEditMode) {
return (
<>
<TopologyLens iframeRef={previewIframeRef} activeCompositionPath={activeCompPath} />
@@ -267,7 +270,9 @@ export function PreviewOverlays({
iframeRef={previewIframeRef}
activeCompositionPath={activeCompPath}
hoverSelection={
- !captionEditMode && !compositionLoading && !isPlaying ? domEditHoverSelection : null
+ !previewCaptionEditMode && !compositionLoading && !isPlaying
+ ? domEditHoverSelection
+ : null
}
selection={shouldShowSelectedDomBounds ? domEditSelection : null}
groupSelections={shouldShowSelectedDomBounds ? domEditGroupSelections : []}
@@ -327,12 +332,14 @@ export function PreviewOverlays({
onMarqueeSelect={applyMarqueeSelection}
/>
<SnapToolbar onSnapChange={setSnapPrefs} />
- <MotionPathOverlay
- iframeRef={previewIframeRef}
- selection={shouldShowMotionPath ? domEditSelection : null}
- compositionSize={compositionDimensions}
- isPlaying={isPlaying}
- />
+ {!readOnly && (
+ <MotionPathOverlay
+ iframeRef={previewIframeRef}
+ selection={shouldShowMotionPath ? domEditSelection : null}
+ compositionSize={compositionDimensions}
+ isPlaying={isPlaying}
+ />
+ )}
{gestureOverlay}
{captionModelPresent && captionDismissed && (
<button
diff --git a/packages/studio/src/components/nle/PreviewOverlaysTestMocks.ts b/packages/studio/src/components/nle/PreviewOverlaysTestMocks.ts
new file mode 100644
index 0000000000..2eff52bae5
--- /dev/null
+++ b/packages/studio/src/components/nle/PreviewOverlaysTestMocks.ts
@@ -0,0 +1,40 @@
+import { vi } from "vitest";
+
+const previewState = vi.hoisted(() => ({ captionEditMode: false }));
+export function getPreviewState() {
+ return previewState;
+}
+export const iframeRef = { current: null as HTMLIFrameElement | null };
+
+vi.mock("../../contexts/StudioContext", () => ({
+ useStudioShellContext: () => ({ activeCompPath: "index.html", previewIframeRef: iframeRef }),
+ useStudioPlaybackContext: () => ({
+ captionEditMode: previewState.captionEditMode,
+ compositionLoading: false,
+ isPlaying: false,
+ }),
+}));
+vi.mock("../../captions/store", () => {
+ const state = {
+ model: null,
+ dismissed: false,
+ syncError: null,
+ clearSelection: vi.fn(),
+ setDismissed: vi.fn(),
+ setEditMode: vi.fn(),
+ setSyncError: vi.fn(),
+ };
+ return {
+ useCaptionStore: Object.assign(
+ (selector: (value: typeof state) => unknown) => selector(state),
+ { getState: () => state },
+ ),
+ };
+});
+vi.mock("../../hooks/useCompositionDimensions", () => ({
+ useCompositionDimensions: () => null,
+}));
+vi.mock("../../utils/studioUiPreferences", () => ({ readStudioUiPreferences: () => ({}) }));
+vi.mock("./useCanvasZOrderTimelineMirror", () => ({
+ useCanvasZOrderTimelineMirror: () => vi.fn(),
+}));
diff --git a/packages/studio/src/components/nle/TimelinePane.tsx b/packages/studio/src/components/nle/TimelinePane.tsx
index c1c82b0cca..828867cc87 100644
--- a/packages/studio/src/components/nle/TimelinePane.tsx
+++ b/packages/studio/src/components/nle/TimelinePane.tsx
@@ -255,7 +255,11 @@ export function TimelinePane({
);
return (
- <div className="relative flex h-full flex-col" aria-disabled={timelineDisabled || undefined}>
+ <div
+ className="relative flex h-full flex-col"
+ data-studio-timeline="true"
+ aria-disabled={timelineDisabled || undefined}
+ >
<div
className="flex flex-col flex-1 min-h-0 overflow-hidden rounded-lg border border-neutral-800/50 bg-neutral-950"
onDoubleClick={(e) => {
diff --git a/packages/studio/src/components/nle/previewReadOnly.test.tsx b/packages/studio/src/components/nle/previewReadOnly.test.tsx
new file mode 100644
index 0000000000..6d0c5edb9f
--- /dev/null
+++ b/packages/studio/src/components/nle/previewReadOnly.test.tsx
@@ -0,0 +1,128 @@
+// @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 "./PreviewOverlaysTestMocks";
+import { PreviewOverlays } from "./PreviewOverlays";
+import { usePreviewBlockDrop } from "./usePreviewBlockDrop";
+import { PreviewReadOnlyProvider } from "../editor/previewReadOnlyContext";
+import { TIMELINE_BLOCK_MIME } from "../../utils/timelineAssetDrop";
+
+const previewState = getPreviewState();
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock("../../contexts/DomEditContext", () => ({
+ useDomEditSelectionContext: () => ({
+ domEditHoverSelection: null,
+ domEditSelection: null,
+ domEditGroupSelections: [],
+ }),
+ useDomEditActionsContext: () => ({}),
+}));
+vi.mock("../editor/TopologyLens", () => ({ TopologyLens: () => null }));
+vi.mock("../../captions/components/CaptionOverlay", () => ({
+ CaptionOverlay: () => <i data-testid="caption-overlay" />,
+}));
+vi.mock("../editor/DomEditOverlay", () => ({
+ DomEditOverlay: () => <i data-testid="dom-edit-overlay" />,
+}));
+vi.mock("../editor/MotionPathOverlay", () => ({
+ MotionPathOverlay: () => <i data-testid="motion-path" />,
+}));
+vi.mock("../editor/SnapToolbar", () => ({ SnapToolbar: () => null }));
+
+let root: Root;
+let host: HTMLDivElement;
+
+function mount(node: React.ReactNode, readOnly = false): void {
+ host = document.createElement("div");
+ iframeRef.current = document.createElement("iframe");
+ document.body.append(host, iframeRef.current);
+ root = createRoot(host);
+ act(() =>
+ root.render(<PreviewReadOnlyProvider readOnly={readOnly}>{node}</PreviewReadOnlyProvider>),
+ );
+}
+
+afterEach(() => {
+ act(() => root.unmount());
+ previewState.captionEditMode = false;
+ document.body.replaceChildren();
+});
+
+const overlays = () => (
+ <PreviewOverlays shouldShowMotionPath={true} shouldShowSelectedDomBounds={true} />
+);
+const has = (id: string) => host.querySelector(`[data-testid="${id}"]`) !== null;
+
+describe("PreviewOverlays with the preview read-only", () => {
+ it("control: with the flag off the motion path can be edited", () => {
+ mount(overlays());
+ expect(has("motion-path")).toBe(true);
+ });
+
+ it("does not mount the motion path editor", () => {
+ mount(overlays(), true);
+ expect(has("motion-path")).toBe(false);
+ expect(has("dom-edit-overlay")).toBe(true);
+ });
+
+ it("control: with the flag off caption mode mounts the caption editor", () => {
+ previewState.captionEditMode = true;
+ mount(overlays());
+ expect(has("caption-overlay")).toBe(true);
+ });
+
+ it("does not mount the caption editor, and selection stays on the canvas overlay", () => {
+ previewState.captionEditMode = true;
+ mount(overlays(), true);
+ expect(has("caption-overlay")).toBe(false);
+ expect(has("dom-edit-overlay")).toBe(true);
+ });
+});
+
+describe("usePreviewBlockDrop with the preview read-only", () => {
+ function dropOnPreview(
+ onBlockDrop: (name: string, pos: { left: number; top: number }) => void,
+ readOnly = false,
+ ) {
+ const stage = document.createElement("div");
+ stage.getBoundingClientRect = () => ({ left: 0, top: 0, width: 100, height: 100 }) as DOMRect;
+ let handlers: ReturnType<typeof usePreviewBlockDrop> | null = null;
+ function Probe() {
+ handlers = usePreviewBlockDrop({
+ stageRef: { current: stage },
+ compositionSize: { width: 1000, height: 1000 },
+ onBlockDrop,
+ });
+ return null;
+ }
+ mount(<Probe />, readOnly);
+ const event = {
+ clientX: 50,
+ clientY: 50,
+ preventDefault: vi.fn(),
+ dataTransfer: {
+ types: [TIMELINE_BLOCK_MIME],
+ getData: () => JSON.stringify({ name: "lower-third" }),
+ },
+ };
+ act(() => handlers!.handleDrop(event as never));
+ return event;
+ }
+
+ it("control: with the flag off a dropped block is placed", () => {
+ const onBlockDrop = vi.fn();
+ dropOnPreview(onBlockDrop);
+ expect(onBlockDrop).toHaveBeenCalledWith("lower-third", { left: 500, top: 500 });
+ });
+
+ it("does not place a dropped block", () => {
+ const onBlockDrop = vi.fn();
+ const event = dropOnPreview(onBlockDrop, true);
+ expect(onBlockDrop).not.toHaveBeenCalled();
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/studio/src/components/nle/usePreviewBlockDrop.ts b/packages/studio/src/components/nle/usePreviewBlockDrop.ts
index 9c88e1b9f0..83cb9b0c43 100644
--- a/packages/studio/src/components/nle/usePreviewBlockDrop.ts
+++ b/packages/studio/src/components/nle/usePreviewBlockDrop.ts
@@ -1,5 +1,6 @@
import { useCallback, useRef, useState, type RefObject } from "react";
import { TIMELINE_BLOCK_MIME } from "../../utils/timelineAssetDrop";
+import { usePreviewReadOnly } from "../editor/previewReadOnlyContext";
interface UsePreviewBlockDropOptions {
portrait?: boolean;
@@ -67,8 +68,9 @@ export function usePreviewBlockDrop({
portrait,
compositionSize,
stageRef,
- onBlockDrop,
+ onBlockDrop: onBlockDropProp,
}: UsePreviewBlockDropOptions) {
+ const onBlockDrop = usePreviewReadOnly() ? undefined : onBlockDropProp;
const [isDragOver, setIsDragOver] = useState(false);
// dragenter/dragleave fire for every internal element boundary; a depth
// counter keeps the drop indicator steady instead of flickering.
diff --git a/packages/studio/src/hooks/appHotkeysDispatch.ts b/packages/studio/src/hooks/appHotkeysDispatch.ts
index f53da57a45..6a90a24b08 100644
--- a/packages/studio/src/hooks/appHotkeysDispatch.ts
+++ b/packages/studio/src/hooks/appHotkeysDispatch.ts
@@ -54,6 +54,11 @@ export interface HotkeyCallbacks {
onUngroupSelection?: () => void;
domEditSelectionRef: React.MutableRefObject<DomEditSelection | null>;
showToast: (message: string, tone?: "error" | "info") => void;
+ readOnlyPreview: boolean;
+}
+
+function timelineOwnsKey(event: KeyboardEvent): boolean {
+ return event.target instanceof Element && event.target.closest("[data-studio-timeline]") !== null;
}
/** Exported for tests, like dispatchPlainKey below: lets the Cmd+C/Cmd+V
@@ -95,6 +100,7 @@ export function dispatchModifierKey(
if (key === "g" && !event.altKey && !isTypingTarget(event.target)) {
event.preventDefault();
+ if (cb.readOnlyPreview) return true;
if (event.shiftKey) cb.onUngroupSelection?.();
else cb.onGroupSelection?.();
return true;
@@ -113,6 +119,12 @@ export function dispatchModifierKey(
}
return true;
}
+ const previewOwnsMutation =
+ cb.readOnlyPreview && cb.domEditSelectionRef.current !== null && !timelineOwnsKey(event);
+ if (previewOwnsMutation && ["v", "x", "d"].includes(key)) {
+ event.preventDefault();
+ return true;
+ }
if (key === "v") {
event.preventDefault();
trackStudioEvent("keyboard_shortcut", { action: "paste" });
@@ -158,6 +170,7 @@ export function dispatchPlainKey(event: KeyboardEvent, key: string, cb: HotkeyCa
// Reserve bare `s` for Split even when the current selection cannot split,
// so secondary listeners do not reinterpret the same key as Snap toggle.
event.preventDefault();
+ if (cb.readOnlyPreview) return;
const { selectedElementId, elements, currentTime } = usePlayerStore.getState();
if (selectedElementId) {
const el = elements.find((e) => (e.key ?? e.id) === selectedElementId);
@@ -240,8 +253,10 @@ export function dispatchPlainKey(event: KeyboardEvent, key: string, cb: HotkeyCa
// the timeline left other selected elements behind. Timeline stays as the
// fallback for rows with no canvas node (audio, an inactive comp).
const domSel = cb.domEditSelectionRef.current;
- if (domSel) {
+ const timelineOwnsDelete = timelineOwnsKey(event);
+ if (domSel && !timelineOwnsDelete) {
event.preventDefault();
+ if (cb.readOnlyPreview) return;
// The whole marquee group, not just the primary the ref holds.
void cb.handleDomEditElementDelete(domSel, { expandGroup: true });
return;
diff --git a/packages/studio/src/hooks/newTweenTargetHooks.test.tsx b/packages/studio/src/hooks/newTweenTargetHooks.test.tsx
index 8ed60bd791..fc023d6ff9 100644
--- a/packages/studio/src/hooks/newTweenTargetHooks.test.tsx
+++ b/packages/studio/src/hooks/newTweenTargetHooks.test.tsx
@@ -196,6 +196,7 @@ function renderGestureCommit(
previewIframeRef: { current: document.createElement("iframe") },
showToast: vi.fn(),
isGestureRecordingRef: { current: false },
+ readOnlyPreview: false,
});
toggle = handleToggleRecording;
return null;
diff --git a/packages/studio/src/hooks/useAppHotkeys.test.ts b/packages/studio/src/hooks/useAppHotkeys.test.ts
index bf9b93260c..aee36e0553 100644
--- a/packages/studio/src/hooks/useAppHotkeys.test.ts
+++ b/packages/studio/src/hooks/useAppHotkeys.test.ts
@@ -1,7 +1,8 @@
// @vitest-environment happy-dom
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { dispatchModifierKey, dispatchPlainKey } from "./appHotkeysDispatch";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { dispatchModifierKey, dispatchPlainKey, type HotkeyCallbacks } from "./appHotkeysDispatch";
import { usePlayerStore } from "../player/store/playerStore";
+import type { DomEditSelection } from "../components/editor/domEditing";
import { clearAutomationClipboard, copyRange } from "../player/components/automationClipboard";
import { VOLUME_RANGE } from "@hyperframes/core/audio-automation";
import type { TimelineElement } from "../player/store/timelineElement";
@@ -19,7 +20,7 @@ const bgmElement: TimelineElement = {
/** Every callback dispatchPlainKey can reach, so a test can assert which one
* a key resolved to. Unannotated on purpose: the parameter type is not
* exported, and structural inference checks it at the call site. */
-function callbacks() {
+function callbacks(overrides: Partial<HotkeyCallbacks> = {}) {
return {
handleTimelineElementDelete: vi.fn(async () => {}),
handleTimelineElementsDelete: vi.fn(async () => {}),
@@ -30,10 +31,15 @@ function callbacks() {
handleCopy: vi.fn(() => false),
handlePaste: vi.fn(async () => {}),
handleCut: vi.fn(async () => false),
+ handleDuplicate: vi.fn(async () => false),
+ onGroupSelection: vi.fn(),
+ onUngroupSelection: vi.fn(),
onResetKeyframes: vi.fn(() => true),
onDeleteSelectedKeyframes: vi.fn(),
showToast: vi.fn(),
domEditSelectionRef: { current: null },
+ readOnlyPreview: false,
+ ...overrides,
};
}
@@ -298,3 +304,65 @@ describe('dispatchPlainKey — "A" returns to select while the razor is armed',
expect(e.defaultPrevented).toBe(false);
});
});
+
+describe("hotkeys with the preview read-only", () => {
+ beforeEach(() => {
+ usePlayerStore.setState({ elements: [bgmElement], selectedElementId: null });
+ });
+
+ it("does not delete the selected element on Delete", () => {
+ const cb = callbacks({ readOnlyPreview: true });
+ cb.domEditSelectionRef.current = { id: "card" } as DomEditSelection;
+ dispatchPlainKey(press("Delete"), "delete", cb);
+ expect(cb.handleDomEditElementDelete).not.toHaveBeenCalled();
+ expect(cb.handleTimelineElementsDelete).not.toHaveBeenCalled();
+ });
+
+ it("does not split on s", () => {
+ usePlayerStore.setState({
+ currentTime: 3,
+ elements: [{ ...bgmElement, hfId: "hf-bgm" }],
+ selectedElementId: "bgm",
+ });
+ const cb = callbacks({ readOnlyPreview: true });
+ dispatchPlainKey(press("s"), "s", cb);
+ expect(cb.handleTimelineElementSplit).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["x", "handleCut"],
+ ["d", "handleDuplicate"],
+ ["v", "handlePaste"],
+ ["g", "onGroupSelection"],
+ ] as const)("does not run %s", (key, callback) => {
+ const cb = callbacks({ readOnlyPreview: true });
+ cb.domEditSelectionRef.current = { id: "card" } as DomEditSelection;
+ dispatchModifierKey(chord(key), key, cb);
+ expect(cb[callback]).not.toHaveBeenCalled();
+ });
+
+ it("still undoes, because history covers timeline edits", () => {
+ const cb = callbacks({ readOnlyPreview: true });
+ dispatchModifierKey(chord("z"), "z", cb);
+ expect(cb.handleUndo).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps timeline paste when the mirrored preview selection is not the owner", () => {
+ usePlayerStore.setState({ selectedElementId: "bgm" });
+ const cb = callbacks({ readOnlyPreview: true });
+ cb.domEditSelectionRef.current = { id: "card" } as DomEditSelection;
+ const event = chord("v");
+ const timeline = document.createElement("div");
+ timeline.dataset.studioTimeline = "true";
+ Object.defineProperty(event, "target", { value: timeline });
+ dispatchModifierKey(event, "v", cb);
+ expect(cb.handlePaste).toHaveBeenCalledTimes(1);
+ });
+
+ it("control: with the flag off Delete removes the selected element", () => {
+ const cb = callbacks();
+ cb.domEditSelectionRef.current = { id: "card" } as DomEditSelection;
+ dispatchPlainKey(press("Delete"), "delete", cb);
+ expect(cb.handleDomEditElementDelete).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx b/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx
index 247780f892..2958e28d66 100644
--- a/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx
+++ b/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx
@@ -93,6 +93,7 @@ function Harness() {
handleDuplicate: vi.fn(async () => false),
onResetKeyframes: vi.fn(() => false),
onDeleteSelectedKeyframes: keyframeDelete,
+ readOnlyPreview: false,
});
return (
diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts
index d271533140..49b60d8f13 100644
--- a/packages/studio/src/hooks/useAppHotkeys.ts
+++ b/packages/studio/src/hooks/useAppHotkeys.ts
@@ -101,6 +101,8 @@ interface UseAppHotkeysParams {
onUngroupSelection?: () => void;
/** Active composition path — used to decide whether undo/redo must resync the SDK session. */
activeCompPath?: string | null;
+ /** Clicks still select and report; the preview cannot move, edit or delete anything. */
+ readOnlyPreview: boolean;
/**
* Force-reload the SDK session after undo/redo reverts the active comp file,
* bypassing the self-write suppress window. Without this, the suppress window
@@ -135,6 +137,7 @@ export function useAppHotkeys({
onUngroupSelection,
activeCompPath,
forceReloadSdkSession,
+ readOnlyPreview,
}: UseAppHotkeysParams) {
const previewHistoryCleanupRef = useRef<(() => void) | null>(null);
@@ -203,6 +206,7 @@ export function useAppHotkeys({
onUngroupSelection,
domEditSelectionRef,
showToast,
+ readOnlyPreview,
};
// ── Keydown dispatch ──
diff --git a/packages/studio/src/hooks/useDomEditCommits.test.tsx b/packages/studio/src/hooks/useDomEditCommits.test.tsx
index 54dfaeaf81..dd8c190733 100644
--- a/packages/studio/src/hooks/useDomEditCommits.test.tsx
+++ b/packages/studio/src/hooks/useDomEditCommits.test.tsx
@@ -230,6 +230,7 @@ function renderDomEditCommits(
refreshDomEditSelectionFromPreview: vi.fn(),
buildDomSelectionFromTarget: vi.fn(async () => null),
onTrySdkPersist: options.onTrySdkPersist,
+ readOnlyPreview: false,
});
return null;
}
diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.ts
index 6937deba05..b5358f3723 100644
--- a/packages/studio/src/hooks/useDomEditCommits.ts
+++ b/packages/studio/src/hooks/useDomEditCommits.ts
@@ -89,6 +89,7 @@ export interface UseDomEditCommitsParams {
) => Promise<CutoverResult>;
/** Resolver-shadow tripwire for z-index reorder targets (telemetry-only, decoupled from cutover). */
onReorderShadow?: (targets: string[]) => void;
+ readOnlyPreview: boolean;
}
export function useDomEditCommits({
@@ -112,6 +113,7 @@ export function useDomEditCommits({
onTrySdkPersist,
onTrySdkDelete,
onReorderShadow,
+ readOnlyPreview,
}: UseDomEditCommitsParams) {
const resolveImportedFontAsset = useCallback(
(fontFamilyValue: string): ImportedFontAsset | null => {
@@ -452,6 +454,7 @@ export function useDomEditCommits({
previewIframeRef,
showToast,
commitPositionPatchToHtml,
+ readOnlyPreview,
});
// ── Element lifecycle (delete, z-index reorder) ──
diff --git a/packages/studio/src/hooks/useDomEditSession.test.tsx b/packages/studio/src/hooks/useDomEditSession.test.tsx
index 1a1edea7d8..66efe06fc1 100644
--- a/packages/studio/src/hooks/useDomEditSession.test.tsx
+++ b/packages/studio/src/hooks/useDomEditSession.test.tsx
@@ -99,6 +99,7 @@ function createSessionParams(
reloadPreview: vi.fn(),
setRefreshKey: vi.fn(),
handleTimelineElementsDelete: vi.fn(),
+ readOnlyPreview: false,
...overrides,
};
}
diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.ts
index a0e982100f..dfdfb99c89 100644
--- a/packages/studio/src/hooks/useDomEditSession.ts
+++ b/packages/studio/src/hooks/useDomEditSession.ts
@@ -58,6 +58,7 @@ export interface UseDomEditSessionParams extends DomEditTimelineParams {
/** The timeline context menu's delete op — a canvas selection that IS a
* timeline row hands off here instead of the REST remove-elements path. */
handleTimelineElementsDelete: (elements: TimelineElement[]) => Promise<void>;
+ readOnlyPreview: boolean;
}
export function useDomEditSession({
@@ -98,8 +99,10 @@ export function useDomEditSession({
publishSdkSession,
forceReloadSdkSession,
handleTimelineElementsDelete,
+ readOnlyPreview,
}: UseDomEditSessionParams) {
const isMasterView = !activeCompPath || activeCompPath === "index.html";
+ const previewCaptionEditMode = captionEditMode && !readOnlyPreview;
void _setRefreshKey;
const {
domEditSelection,
@@ -125,7 +128,7 @@ export function useDomEditSession({
activeCompPath,
isMasterView,
compIdToSrc,
- captionEditMode,
+ captionEditMode: previewCaptionEditMode,
previewIframeRef,
timelineElements,
getTimelineSelectionSet,
@@ -247,6 +250,7 @@ export function useDomEditSession({
refreshDomEditSelectionFromPreview,
buildDomSelectionFromTarget,
forceReloadSdkSession,
+ readOnlyPreview,
onTrySdkPersist: sdkSession
? (selection, operations, originalContent, targetPath, options) => {
// Decoupled tripwire, runs regardless of the cutover flag. originalContent lets
@@ -405,7 +409,6 @@ export function useDomEditSession({
handleGsapRemoveAllKeyframes,
handleResetSelectedElementKeyframes,
} = useDomEditWiring({
- // fallow-ignore-next-line code-duplication
projectId,
activeCompPath,
domEditSelection,
@@ -414,7 +417,7 @@ export function useDomEditSession({
refreshDomEditGroupSelectionsFromPreview,
previewIframeRef,
previewIframe,
- captionEditMode,
+ captionEditMode: previewCaptionEditMode,
refreshKey,
gsapCacheVersion,
bumpGsapCache,
@@ -451,7 +454,7 @@ export function useDomEditSession({
handleBlockedDomMove,
handleDomManualDragStart,
} = usePreviewInteraction({
- captionEditMode,
+ captionEditMode: previewCaptionEditMode,
compositionLoading,
previewIframeRef,
showToast,
diff --git a/packages/studio/src/hooks/useDomEditWiring.ts b/packages/studio/src/hooks/useDomEditWiring.ts
index 041634a890..c0b4dc0f5d 100644
--- a/packages/studio/src/hooks/useDomEditWiring.ts
+++ b/packages/studio/src/hooks/useDomEditWiring.ts
@@ -109,46 +109,46 @@ export interface UseDomEditWiringParams {
}
// fallow-ignore-next-line complexity
-export function useDomEditWiring({
- // fallow-ignore-next-line code-duplication
- projectId,
- activeCompPath,
- domEditSelection,
- domEditSelectionRef,
- domEditGroupSelectionsRef,
- refreshDomEditGroupSelectionsFromPreview,
- previewIframeRef,
- previewIframe,
- captionEditMode,
- refreshKey,
- gsapCacheVersion,
- bumpGsapCache,
- showToast,
- refreshPreviewDocumentVersion,
- syncPreviewHotkeys,
- applyStudioManualEditsToPreviewRef,
- applyDomSelection,
- buildDomSelectionFromTarget,
- openSourceForSelection,
- updateGsapProperty,
- updateGsapMeta,
- deleteGsapAnimation,
- deleteAllForSelector,
- addGsapAnimation,
- addGsapProperty,
- removeGsapProperty,
- updateGsapFromProperty,
- addGsapFromProperty,
- removeGsapFromProperty,
- addKeyframe,
- addKeyframeBatch,
- removeKeyframe,
- moveKeyframe,
- resizeKeyframedTween,
- convertToKeyframes,
- removeAllKeyframes,
- handleDomManualEditsReset,
-}: UseDomEditWiringParams) {
+export function useDomEditWiring(params: UseDomEditWiringParams) {
+ const {
+ projectId,
+ activeCompPath,
+ domEditSelection,
+ domEditSelectionRef,
+ domEditGroupSelectionsRef,
+ refreshDomEditGroupSelectionsFromPreview,
+ previewIframeRef,
+ previewIframe,
+ captionEditMode,
+ refreshKey,
+ gsapCacheVersion,
+ bumpGsapCache,
+ showToast,
+ refreshPreviewDocumentVersion,
+ syncPreviewHotkeys,
+ applyStudioManualEditsToPreviewRef,
+ applyDomSelection,
+ buildDomSelectionFromTarget,
+ openSourceForSelection,
+ updateGsapProperty,
+ updateGsapMeta,
+ deleteGsapAnimation,
+ deleteAllForSelector,
+ addGsapAnimation,
+ addGsapProperty,
+ removeGsapProperty,
+ updateGsapFromProperty,
+ addGsapFromProperty,
+ removeGsapFromProperty,
+ addKeyframe,
+ addKeyframeBatch,
+ removeKeyframe,
+ moveKeyframe,
+ resizeKeyframedTween,
+ convertToKeyframes,
+ removeAllKeyframes,
+ handleDomManualEditsReset,
+ } = params;
// ── Click-to-source navigation ──
const onClickToSource = useCallback(
diff --git a/packages/studio/src/hooks/useDomGeometryCommits.test.tsx b/packages/studio/src/hooks/useDomGeometryCommits.test.tsx
index 5f364f5cdf..a45a619f59 100644
--- a/packages/studio/src/hooks/useDomGeometryCommits.test.tsx
+++ b/packages/studio/src/hooks/useDomGeometryCommits.test.tsx
@@ -12,10 +12,30 @@ import {
readStudioPathOffset,
readStudioRotation,
} from "../components/editor/manualEdits";
-import { useDomGeometryCommits } from "./useDomGeometryCommits";
+import { useDomGeometryCommits, type UseDomGeometryCommitsParams } from "./useDomGeometryCommits";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+function mountCommits(
+ commitPositionPatchToHtml: UseDomGeometryCommitsParams["commitPositionPatchToHtml"],
+ readOnlyPreview = false,
+) {
+ let commits: ReturnType<typeof useDomGeometryCommits> | null = null;
+ function Probe() {
+ commits = useDomGeometryCommits({
+ previewIframeRef: { current: null },
+ showToast: vi.fn(),
+ commitPositionPatchToHtml,
+ readOnlyPreview,
+ });
+ return null;
+ }
+ const host = document.createElement("div");
+ const root = createRoot(host);
+ act(() => root.render(<Probe />));
+ return { commits: () => commits!, unmount: () => act(() => root.unmount()) };
+}
+
describe("useDomGeometryCommits rollback", () => {
it("restores every optimistic geometry mutation when persistence rejects", async () => {
const element = document.createElement("div");
@@ -30,7 +50,9 @@ describe("useDomGeometryCommits rollback", () => {
element,
} as unknown as DomEditSelection;
const failure = new Error("save failed");
- const commitPositionPatchToHtml = vi.fn().mockRejectedValue(failure);
+ const commitPositionPatchToHtml = vi
+ .fn<UseDomGeometryCommitsParams["commitPositionPatchToHtml"]>()
+ .mockRejectedValue(failure);
let commits: ReturnType<typeof useDomGeometryCommits> | null = null;
const host = document.createElement("div");
const root = createRoot(host);
@@ -40,6 +62,7 @@ describe("useDomGeometryCommits rollback", () => {
previewIframeRef: { current: null },
showToast: vi.fn(),
commitPositionPatchToHtml,
+ readOnlyPreview: false,
});
return null;
}
@@ -60,3 +83,63 @@ describe("useDomGeometryCommits rollback", () => {
act(() => root.unmount());
});
});
+
+describe("useDomGeometryCommits read-only preview", () => {
+ const selectionOn = (element: HTMLElement) =>
+ ({ id: element.id, selector: `#${element.id}`, element }) as unknown as DomEditSelection;
+
+ it("refuses a manual offset commit: no write, no history entry", async () => {
+ const element = document.createElement("div");
+ element.id = "ro-offset";
+ document.body.append(element);
+ applyStudioPathOffset(element, { x: 1, y: 2 });
+ const commitPositionPatchToHtml =
+ vi.fn<UseDomGeometryCommitsParams["commitPositionPatchToHtml"]>();
+ const { commits, unmount } = mountCommits(commitPositionPatchToHtml, true);
+ await commits().handleDomPathOffsetCommit(selectionOn(element), { x: 99, y: 99 });
+ expect(readStudioPathOffset(element)).toEqual({ x: 1, y: 2 });
+ expect(commitPositionPatchToHtml).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it("refuses a manual box-size commit: no write, no history entry", async () => {
+ const element = document.createElement("div");
+ element.id = "ro-size";
+ document.body.append(element);
+ applyStudioBoxSize(element, { width: 10, height: 20 });
+ const commitPositionPatchToHtml =
+ vi.fn<UseDomGeometryCommitsParams["commitPositionPatchToHtml"]>();
+ const { commits, unmount } = mountCommits(commitPositionPatchToHtml, true);
+ await commits().handleDomBoxSizeCommit(selectionOn(element), { width: 999, height: 999 });
+ expect(readStudioBoxSize(element)).toEqual({ width: 10, height: 20 });
+ expect(commitPositionPatchToHtml).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it("refuses a manual rotation commit: no write, no history entry", async () => {
+ const element = document.createElement("div");
+ element.id = "ro-rotate";
+ document.body.append(element);
+ applyStudioRotation(element, { angle: 5 });
+ const commitPositionPatchToHtml =
+ vi.fn<UseDomGeometryCommitsParams["commitPositionPatchToHtml"]>();
+ const { commits, unmount } = mountCommits(commitPositionPatchToHtml, true);
+ await commits().handleDomRotationCommit(selectionOn(element), { angle: 350 });
+ expect(readStudioRotation(element)).toEqual({ angle: 5 });
+ expect(commitPositionPatchToHtml).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it("still commits an offset with the flag off", async () => {
+ const element = document.createElement("div");
+ element.id = "rw-offset";
+ document.body.append(element);
+ const commitPositionPatchToHtml = vi
+ .fn<UseDomGeometryCommitsParams["commitPositionPatchToHtml"]>()
+ .mockResolvedValue(undefined);
+ const { commits, unmount } = mountCommits(commitPositionPatchToHtml);
+ await commits().handleDomPathOffsetCommit(selectionOn(element), { x: 5, y: 6 });
+ expect(commitPositionPatchToHtml).toHaveBeenCalledTimes(1);
+ unmount();
+ });
+});
diff --git a/packages/studio/src/hooks/useDomGeometryCommits.ts b/packages/studio/src/hooks/useDomGeometryCommits.ts
index b72c6e1e5e..69a13d7be0 100644
--- a/packages/studio/src/hooks/useDomGeometryCommits.ts
+++ b/packages/studio/src/hooks/useDomGeometryCommits.ts
@@ -28,9 +28,20 @@ import { isElementGsapTargeted } from "./gsapTargetCache";
const GSAP_CSS_FALLBACK_BLOCKED_MESSAGE =
"This element is GSAP-animated — dragging via CSS would corrupt keyframes";
+function rejectGsapCssFallback(
+ selection: DomEditSelection,
+ previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>,
+ showToast: (message: string, tone?: "error" | "info") => void,
+): Promise<never> | null {
+ if (!isElementGsapTargeted(previewIframeRef.current, selection.element)) return null;
+ const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
+ showToast(error.message, "error");
+ return Promise.reject(error);
+}
+
// ── Hook ──
-interface UseDomGeometryCommitsParams {
+export interface UseDomGeometryCommitsParams {
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
showToast: (message: string, tone?: "error" | "info") => void;
commitPositionPatchToHtml: (
@@ -38,25 +49,24 @@ interface UseDomGeometryCommitsParams {
patches: PatchOperation[],
options: { label: string; coalesceKey: string; skipRefresh?: boolean },
) => Promise<void>;
+ readOnlyPreview: boolean;
}
export function useDomGeometryCommits({
previewIframeRef,
showToast,
commitPositionPatchToHtml,
+ readOnlyPreview,
}: UseDomGeometryCommitsParams) {
const handleDomPathOffsetCommit = useCallback(
(selection: DomEditSelection, next: { x: number; y: number }) => {
+ if (readOnlyPreview) return Promise.resolve();
// ponytail: GSAP-targeted elements are blocked (no SDK position-in-script op); CSS-path
// elements fall through to commitPositionPatchToHtml → persistDomEditOperations →
// onTrySdkPersist and are already SDK-cut-over as setStyle/setAttribute (§3.3 done).
// Upgrade path for GSAP: add a moveElementGsap SDK op in a separate SDK PR.
- const gsapTargeted = isElementGsapTargeted(previewIframeRef.current, selection.element);
- if (gsapTargeted) {
- const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
- showToast(error.message, "error");
- return Promise.reject(error);
- }
+ const gsapFallback = rejectGsapCssFallback(selection, previewIframeRef, showToast);
+ if (gsapFallback) return gsapFallback;
const before = captureStudioPathOffset(selection.element);
applyStudioPathOffset(selection.element, next);
return commitPositionPatchToHtml(selection, buildPathOffsetPatches(selection.element), {
@@ -67,7 +77,7 @@ export function useDomGeometryCommits({
throw error;
});
},
- [commitPositionPatchToHtml, previewIframeRef, showToast],
+ [commitPositionPatchToHtml, previewIframeRef, showToast, readOnlyPreview],
);
const handleDomBoxSizeCommit = useCallback(
@@ -76,11 +86,9 @@ export function useDomGeometryCommits({
next: { width: number; height: number },
offset?: { x: number; y: number },
) => {
- if (isElementGsapTargeted(previewIframeRef.current, selection.element)) {
- const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
- showToast(error.message, "error");
- return Promise.reject(error);
- }
+ if (readOnlyPreview) return Promise.resolve();
+ const gsapFallback = rejectGsapCssFallback(selection, previewIframeRef, showToast);
+ if (gsapFallback) return gsapFallback;
const beforeSize = captureStudioBoxSize(selection.element);
const beforeOffset = offset ? captureStudioPathOffset(selection.element) : null;
applyStudioBoxSize(selection.element, next);
@@ -104,16 +112,14 @@ export function useDomGeometryCommits({
throw error;
});
},
- [commitPositionPatchToHtml, previewIframeRef, showToast],
+ [commitPositionPatchToHtml, previewIframeRef, showToast, readOnlyPreview],
);
const handleDomRotationCommit = useCallback(
(selection: DomEditSelection, next: { angle: number }) => {
- if (isElementGsapTargeted(previewIframeRef.current, selection.element)) {
- const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
- showToast(error.message, "error");
- return Promise.reject(error);
- }
+ if (readOnlyPreview) return Promise.resolve();
+ const gsapFallback = rejectGsapCssFallback(selection, previewIframeRef, showToast);
+ if (gsapFallback) return gsapFallback;
const before = captureStudioRotation(selection.element);
applyStudioRotation(selection.element, next);
return commitPositionPatchToHtml(selection, buildRotationPatches(selection.element), {
@@ -124,7 +130,7 @@ export function useDomGeometryCommits({
throw error;
});
},
- [commitPositionPatchToHtml, previewIframeRef, showToast],
+ [commitPositionPatchToHtml, previewIframeRef, showToast, readOnlyPreview],
);
const handleDomManualEditsReset = useCallback(
diff --git a/packages/studio/src/hooks/useGestureCommit.test.tsx b/packages/studio/src/hooks/useGestureCommit.test.tsx
index e67df39695..a2077c5e87 100644
--- a/packages/studio/src/hooks/useGestureCommit.test.tsx
+++ b/packages/studio/src/hooks/useGestureCommit.test.tsx
@@ -107,6 +107,7 @@ describe("useGestureCommit", () => {
previewIframeRef: { current: iframe },
showToast: vi.fn(),
isGestureRecordingRef: { current: false },
+ readOnlyPreview: false,
});
return null;
}
@@ -127,4 +128,32 @@ describe("useGestureCommit", () => {
expect(options[1]).toEqual(expect.objectContaining({ coalesceMs: Infinity, softReload: true }));
expect(options[1]).not.toHaveProperty("skipReload");
});
+
+ it("does not start a recording while the preview is read-only", () => {
+ const element = document.createElement("div");
+ const commitMutation = vi.fn(async () => {});
+ const captured: { hook: ReturnType<typeof useGestureCommit> | null } = { hook: null };
+ function Probe() {
+ captured.hook = useGestureCommit({
+ domEditSessionRef: {
+ current: {
+ domEditSelection: makeSelection(element),
+ selectedGsapAnimations: [],
+ commitMutation,
+ },
+ },
+ previewIframeRef: { current: document.createElement("iframe") },
+ showToast: vi.fn(),
+ isGestureRecordingRef: { current: false },
+ readOnlyPreview: true,
+ });
+ return null;
+ }
+ const root = mountReactHarness(<Probe />);
+ cleanup = () => act(() => root.unmount());
+
+ act(() => captured.hook?.handleToggleRecording());
+ expect(gestureRecording.startRecording).not.toHaveBeenCalled();
+ expect(commitMutation).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/studio/src/hooks/useGestureCommit.ts b/packages/studio/src/hooks/useGestureCommit.ts
index bc87caac39..0714f0caad 100644
--- a/packages/studio/src/hooks/useGestureCommit.ts
+++ b/packages/studio/src/hooks/useGestureCommit.ts
@@ -87,6 +87,7 @@ interface UseGestureCommitParams {
previewIframeRef: React.RefObject<HTMLIFrameElement | null>;
showToast: (message: string, tone?: "error" | "info") => void;
isGestureRecordingRef: React.MutableRefObject<boolean>;
+ readOnlyPreview: boolean;
}
export interface UseGestureCommitResult {
@@ -101,6 +102,7 @@ export function useGestureCommit({
previewIframeRef,
showToast,
isGestureRecordingRef,
+ readOnlyPreview,
}: UseGestureCommitParams): UseGestureCommitResult {
const gestureRecording = useGestureRecording();
const [gestureState, setGestureState] = useState<"idle" | "recording">("idle");
@@ -115,6 +117,20 @@ export function useGestureCommit({
// Unmount: clear auto-stop interval
useEffect(() => () => clearInterval(recordingAutoStopRef.current), []);
+ const cancelRecording = useCallback(() => {
+ clearInterval(recordingAutoStopRef.current);
+ gestureRecording.stopRecording();
+ gestureRecording.clearSamples();
+ gestureStateRef.current = "idle";
+ isGestureRecordingRef.current = false;
+ capturedSelectionRef.current = null;
+ setGestureState("idle");
+ }, [gestureRecording, isGestureRecordingRef]);
+
+ useEffect(() => {
+ if (readOnlyPreview && gestureStateRef.current === "recording") cancelRecording();
+ }, [cancelRecording, readOnlyPreview]);
+
// fallow-ignore-next-line complexity
const stopAndCommitRecording = useCallback(async () => {
clearInterval(recordingAutoStopRef.current);
@@ -335,9 +351,14 @@ export function useGestureCommit({
// fallow-ignore-next-line complexity
const handleToggleRecording = useCallback(() => {
if (gestureStateRef.current === "recording") {
+ if (readOnlyPreview) {
+ cancelRecording();
+ return;
+ }
void stopAndCommitRecording();
return;
}
+ if (readOnlyPreview) return;
const sel = domEditSessionRef.current.domEditSelection;
if (!sel) {
showToast("Select an element first", "error");
@@ -373,9 +394,11 @@ export function useGestureCommit({
gestureRecording,
showToast,
stopAndCommitRecording,
+ cancelRecording,
previewIframeRef,
domEditSessionRef,
isGestureRecordingRef,
+ readOnlyPreview,
]);
return { gestureState, gestureRecording, handleToggleRecording };
diff --git a/packages/studio/src/hooks/useInlineTextEdit.test.tsx b/packages/studio/src/hooks/useInlineTextEdit.test.tsx
index c09209eb1d..31ce1e688a 100644
--- a/packages/studio/src/hooks/useInlineTextEdit.test.tsx
+++ b/packages/studio/src/hooks/useInlineTextEdit.test.tsx
@@ -3,6 +3,7 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { PreviewReadOnlyProvider } from "../components/editor/previewReadOnlyContext";
import { useInlineTextEdit, type InlineTextEditControls } from "./useInlineTextEdit";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -20,7 +21,7 @@ function heading(text = "Motion Playground"): HTMLElement {
return element;
}
-function mount(onCommit = vi.fn(), onPause = vi.fn()) {
+function mount(onCommit = vi.fn(), onPause = vi.fn(), readOnly = false) {
const controls: { current: InlineTextEditControls | null } = { current: null };
function Probe() {
controls.current = useInlineTextEdit({ onCommit, onPause });
@@ -29,7 +30,13 @@ function mount(onCommit = vi.fn(), onPause = vi.fn()) {
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
- act(() => root.render(<Probe />));
+ act(() =>
+ root.render(
+ <PreviewReadOnlyProvider readOnly={readOnly}>
+ <Probe />
+ </PreviewReadOnlyProvider>,
+ ),
+ );
return { controls: () => controls.current!, root, onCommit, onPause };
}
@@ -552,4 +559,18 @@ describe("useInlineTextEdit with styled runs", () => {
expect(insertText).toHaveBeenCalledWith("insertText", false, "plain words");
act(() => root.unmount());
});
+
+ it("refuses to open an edit while the preview is read-only", () => {
+ const element = heading();
+ const { controls, root, onCommit, onPause } = mount(vi.fn(), vi.fn(), true);
+ let opened = true;
+ act(() => {
+ opened = controls().start(element);
+ });
+ expect(opened).toBe(false);
+ expect(element.hasAttribute("contenteditable")).toBe(false);
+ expect(onPause).not.toHaveBeenCalled();
+ expect(onCommit).not.toHaveBeenCalled();
+ act(() => root.unmount());
+ });
});
diff --git a/packages/studio/src/hooks/useInlineTextEdit.ts b/packages/studio/src/hooks/useInlineTextEdit.ts
index 5014cf5e08..f86cf04290 100644
--- a/packages/studio/src/hooks/useInlineTextEdit.ts
+++ b/packages/studio/src/hooks/useInlineTextEdit.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { sanitizeRichTextChildren } from "@hyperframes/core/rich-text-sanitize";
+import { usePreviewReadOnly } from "../components/editor/previewReadOnlyContext";
/**
* Editing an element's text where it sits, in the composition itself.
@@ -89,6 +90,7 @@ export function useInlineTextEdit({
/** Stop playback, so the element is not animating under the caret. */
onPause?: () => void;
}): InlineTextEditControls {
+ const readOnly = usePreviewReadOnly();
const [session, setSession] = useState<InlineTextEditSession | null>(null);
// The teardown reads this rather than the state, so an exit path that runs
// before React re-renders still sees the element it has to clean up.
@@ -123,7 +125,7 @@ export function useInlineTextEdit({
const start = useCallback(
(element: HTMLElement, caretAt?: { x: number; y: number }): boolean => {
- if (openRef.current) return false;
+ if (openRef.current || readOnly) return false;
const open = {
element,
@@ -156,7 +158,7 @@ export function useInlineTextEdit({
framesRef.current = raf ?? null;
return true;
},
- [onPause],
+ [onPause, readOnly],
);
const commit = useCallback(() => {
@@ -179,6 +181,13 @@ export function useInlineTextEdit({
teardown();
}, [teardown]);
+ // Read-only can be enabled while an edit is already open. Close that
+ // session as a cancellation so the preview cannot keep committing through
+ // the now-disabled editing surface.
+ useEffect(() => {
+ if (readOnly && openRef.current) cancel();
+ }, [cancel, readOnly]);
+
// The keys belong to the element, not to the document: the element lives in
// the preview's own document, so a listener on Studio's would never see them.
useEffect(() => {