Skip to content

Write HTML. Render video. Built for agents.

feat(studio): export timeline editing for a host outside EditorShell (#4201)

Miguel Ángel5262062e7be2
diff --git a/packages/studio/src/components/nle/TimelinePane.tsx b/packages/studio/src/components/nle/TimelinePane.tsx
index 063916a1ad..c1c82b0cca 100644
--- a/packages/studio/src/components/nle/TimelinePane.tsx
+++ b/packages/studio/src/components/nle/TimelinePane.tsx
@@ -1,6 +1,6 @@
import { useCallback, type ReactNode } from "react";
import { Timeline } from "../../player";
-import type { TimelineElement } from "../../player";
+import type { TimelineElement, TimelineTimeRange } from "../../player";
import type { BlockedTimelineEditIntent } from "../../player/components/timelineEditing";
import { useTimelineEditContext } from "../../contexts/TimelineEditContext";
import { trackStudioExpandedClipEdit } from "../../telemetry/events";
@@ -77,6 +77,9 @@ export interface TimelinePaneProps {
timelineToolbar?: ReactNode;
/** Slot rendered below the timeline tracks */
timelineFooter?: ReactNode;
+ /** Slot for a host's own overlay spanning the whole timeline area (e.g. a draft/ghost
+ * clip), positioned absolutely the same way PreviewPane's previewOverlay is. */
+ timelineOverlay?: ReactNode;
/** Custom clip content renderer for timeline (thumbnails, waveforms, etc.) */
renderClipContent?: (
element: TimelineElement,
@@ -101,6 +104,7 @@ export interface TimelinePaneProps {
) => Promise<void> | void;
onBlockedEditAttempt?: (element: TimelineElement, intent: BlockedTimelineEditIntent) => void;
onSelectTimelineElement?: (element: TimelineElement | null) => void;
+ onRangeSelect?: (range: TimelineTimeRange | null) => void;
/** Copy/paste/duplicate act on the store's own selection, not a passed
* element, so unlike onDeleteElement they need no composition-basis wrapper. */
onCopyClip?: () => boolean;
@@ -113,6 +117,7 @@ export interface TimelinePaneProps {
export function TimelinePane({
timelineToolbar,
timelineFooter,
+ timelineOverlay,
renderClipContent,
onFileDrop,
onDeleteElement,
@@ -121,6 +126,7 @@ export function TimelinePane({
onCompositionDrop,
onBlockedEditAttempt,
onSelectTimelineElement,
+ onRangeSelect,
onCopyClip,
onPasteClip,
onDuplicateClip,
@@ -278,6 +284,7 @@ export function TimelinePane({
onBlockedEditAttempt={onBlockedEditAttempt}
onSplitElement={handleSplitElement}
onSelectElement={onSelectTimelineElement}
+ onRangeSelect={onRangeSelect}
onCopyClip={onCopyClip}
onPasteClip={onPasteClip}
onDuplicateClip={onDuplicateClip}
@@ -285,6 +292,9 @@ export function TimelinePane({
/>
</div>
{timelineFooter && <div className="shrink-0">{timelineFooter}</div>}
+ {timelineOverlay && (
+ <div className="pointer-events-none absolute inset-0 z-20">{timelineOverlay}</div>
+ )}
{timelineDisabled && (
<div
className="absolute inset-0 z-30 cursor-not-allowed bg-black/18 flex items-center justify-center"
diff --git a/packages/studio/src/hooks/timelineAudioGroupCreate.ts b/packages/studio/src/hooks/timelineAudioGroupCreate.ts
index af492e34e6..7fed1b4a62 100644
--- a/packages/studio/src/hooks/timelineAudioGroupCreate.ts
+++ b/packages/studio/src/hooks/timelineAudioGroupCreate.ts
@@ -28,6 +28,19 @@ import {
type UseTimelineElementVisibilityEditingInput,
} from "./timelineTrackVisibility";
+interface AudioGroupCarveInput extends UseTimelineElementVisibilityEditingInput {
+ checkEditable?: (elements: readonly TimelineElement[]) => boolean;
+}
+
+function assertAudioGroupEditable(
+ checkEditable: AudioGroupCarveInput["checkEditable"],
+ elements: readonly TimelineElement[],
+): void {
+ if (checkEditable && !checkEditable(elements)) {
+ throw new Error("Timeline edit blocked");
+ }
+}
+
/**
* Assign (or restore) `data-audio-group` across a set of members.
*
@@ -267,7 +280,8 @@ export function useAudioGroupCarveAssignment({
previewIframeRef,
pendingTimelineEditPathRef,
isRecordingRef,
-}: UseTimelineElementVisibilityEditingInput): (
+ checkEditable,
+}: AudioGroupCarveInput): (
clipIds: readonly string[],
groupId: string,
groupLabel?: string,
@@ -289,6 +303,7 @@ export function useAudioGroupCarveAssignment({
const domId = runtimeAudioId(item);
return domId !== null && wanted.has(domId);
});
+ if (elements.length === wanted.size) assertAudioGroupEditable(checkEditable, elements);
try {
// Loud, not silent: an unresolved id used to leave `elements` short,
// `createAudioGroupAndAssignMembers` returning early with no write, and
@@ -333,6 +348,7 @@ export function useAudioGroupCarveAssignment({
isRecordingRef,
showToast,
projectIdRef,
+ checkEditable,
],
);
}
diff --git a/packages/studio/src/hooks/timelineAudioGroupVolume.ts b/packages/studio/src/hooks/timelineAudioGroupVolume.ts
index c3d21927af..abec05d2c6 100644
--- a/packages/studio/src/hooks/timelineAudioGroupVolume.ts
+++ b/packages/studio/src/hooks/timelineAudioGroupVolume.ts
@@ -1,4 +1,4 @@
-import { useCallback } from "react";
+import { useCallback, useRef } from "react";
import { HF_AUDIO_FX_ATTR } from "@hyperframes/core/audio-fx";
import { HF_AUDIO_AUTOMATION_ATTR } from "@hyperframes/core/audio-automation";
import { usePlayerStore } from "../player";
@@ -29,6 +29,10 @@ function patchLiveGroupAttribute(
invalidateGroupInfoCache(iframe?.contentDocument);
}
+function audioGroupAttributeLiveKey(groupId: string, attr: string): string {
+ return `${groupId}\0${attr}`;
+}
+
/**
* `data-volume` exactly as core reads it (`readAudioGroupVolume`): an absent or
* empty attribute is UNITY, not zero.
@@ -210,9 +214,16 @@ export function useSetAudioGroupAttribute({
}: UseTimelineElementVisibilityEditingInput): {
setLive: (groupId: string, attr: string, value: string | null) => void;
setQuiet: (groupId: string, attr: string, value: string | null, label: string) => Promise<void>;
+ revertLive: (groupId: string, attr: string) => void;
} {
+ const liveBeforeRef = useRef(new Map<string, string | null>());
const setLive = useCallback(
(groupId: string, attr: string, value: string | null) => {
+ const key = audioGroupAttributeLiveKey(groupId, attr);
+ const target = previewIframeRef.current?.contentDocument?.getElementById(groupId);
+ if (!liveBeforeRef.current.has(key)) {
+ liveBeforeRef.current.set(key, target?.getAttribute(attr) ?? null);
+ }
patchLiveGroupAttribute(previewIframeRef.current, groupId, attr, value);
// Live too, not just on commit: a fader drag is `setLive` per frame and
// `setQuiet` once on release, so without this the strip's own readout
@@ -221,6 +232,26 @@ export function useSetAudioGroupAttribute({
},
[previewIframeRef],
);
+ const revertLive = useCallback(
+ (groupId: string, attr: string) => {
+ const key = audioGroupAttributeLiveKey(groupId, attr);
+ if (!liveBeforeRef.current.has(key)) return;
+ patchLiveGroupAttribute(
+ previewIframeRef.current,
+ groupId,
+ attr,
+ liveBeforeRef.current.get(key) ?? null,
+ );
+ syncStoredGroupAttribute(
+ groupId,
+ attr,
+ previewIframeRef.current?.contentDocument?.getElementById(groupId)?.getAttribute(attr) ??
+ null,
+ );
+ liveBeforeRef.current.delete(key);
+ },
+ [previewIframeRef],
+ );
const setQuiet = useCallback(
async (groupId: string, attr: string, value: string | null, label: string) => {
if (isRecordingRef?.current) {
@@ -242,6 +273,7 @@ export function useSetAudioGroupAttribute({
recordEdit,
pendingTimelineEditPathRef,
});
+ liveBeforeRef.current.delete(audioGroupAttributeLiveKey(groupId, attr));
syncStoredGroupAttribute(groupId, attr, value);
} catch (error) {
// `persistElementAttribute` leaves the live DOM at the previous value
@@ -257,6 +289,7 @@ export function useSetAudioGroupAttribute({
console.error("[Timeline] Failed to set group attribute", error);
const message = error instanceof Error ? error.message : "Failed to update group";
showToast(message);
+ liveBeforeRef.current.delete(audioGroupAttributeLiveKey(groupId, attr));
}
},
[
@@ -270,5 +303,5 @@ export function useSetAudioGroupAttribute({
projectIdRef,
],
);
- return { setLive, setQuiet };
+ return { setLive, setQuiet, revertLive };
}
diff --git a/packages/studio/src/hooks/timelineEditPermission.ts b/packages/studio/src/hooks/timelineEditPermission.ts
new file mode 100644
index 0000000000..1a9dde5912
--- /dev/null
+++ b/packages/studio/src/hooks/timelineEditPermission.ts
@@ -0,0 +1,31 @@
+import { useCallback } from "react";
+import type { TimelineElement } from "../player";
+
+/** A host's verdict on one element: editable, or blocked with a reason to show. */
+export type TimelineEditPermission = true | { blocked: true; reason: string };
+
+export type CanEditTimelineElement = (element: TimelineElement) => TimelineEditPermission;
+
+/**
+ * Refuses a write when any target element is blocked, toasting the host's
+ * reason. Absent `canEdit` never refuses, so Studio itself is unchanged.
+ */
+export function useTimelineEditGate(
+ canEdit: CanEditTimelineElement | undefined,
+ showToast: (message: string, tone?: "error" | "info") => void,
+) {
+ return useCallback(
+ (targets: readonly TimelineElement[]): boolean => {
+ if (!canEdit) return true;
+ for (const element of targets) {
+ const verdict = canEdit(element);
+ if (verdict !== true) {
+ showToast(verdict.reason, "error");
+ return false;
+ }
+ }
+ return true;
+ },
+ [canEdit, showToast],
+ );
+}
diff --git a/packages/studio/src/hooks/timelineElementFxAttribute.ts b/packages/studio/src/hooks/timelineElementFxAttribute.ts
index a28e818b9c..1f9c675736 100644
--- a/packages/studio/src/hooks/timelineElementFxAttribute.ts
+++ b/packages/studio/src/hooks/timelineElementFxAttribute.ts
@@ -7,7 +7,7 @@
* shared core `setAudioGroupAttribute` also uses.
*/
-import { useCallback } from "react";
+import { useCallback, useRef } from "react";
import type { TimelineElement } from "../player";
import {
buildPatchTarget,
@@ -32,6 +32,14 @@ function patchLiveElementAttribute(
else target.setAttribute(attr, value);
}
+function elementAttributeLiveKey(
+ element: TimelineElement,
+ activeCompPath: string | null,
+ attr: string,
+): string {
+ return `${element.sourceFile || activeCompPath || "index.html"}\0${element.key ?? element.domId ?? element.id}\0${attr}`;
+}
+
interface SetElementAttributeInput {
projectId: string;
activeCompPath: string | null;
@@ -92,13 +100,35 @@ export function useSetElementAttribute({
value: string | null,
label: string,
) => Promise<void>;
+ revertLive: (element: TimelineElement, attr: string) => void;
} {
+ const liveBeforeRef = useRef(new Map<string, string | null>());
const setLive = useCallback(
(element: TimelineElement, attr: string, value: string | null) => {
+ const key = elementAttributeLiveKey(element, activeCompPath, attr);
+ const target = findTimelineElementInIframe(previewIframeRef.current, element, activeCompPath);
+ if (!liveBeforeRef.current.has(key)) {
+ liveBeforeRef.current.set(key, target?.getAttribute(attr) ?? null);
+ }
patchLiveElementAttribute(previewIframeRef.current, element, attr, value, activeCompPath);
},
[previewIframeRef, activeCompPath],
);
+ const revertLive = useCallback(
+ (element: TimelineElement, attr: string) => {
+ const key = elementAttributeLiveKey(element, activeCompPath, attr);
+ if (!liveBeforeRef.current.has(key)) return;
+ patchLiveElementAttribute(
+ previewIframeRef.current,
+ element,
+ attr,
+ liveBeforeRef.current.get(key) ?? null,
+ activeCompPath,
+ );
+ liveBeforeRef.current.delete(key);
+ },
+ [previewIframeRef, activeCompPath],
+ );
const setQuiet = useCallback(
async (element: TimelineElement, attr: string, value: string | null, label: string) => {
if (isRecordingRef?.current) {
@@ -120,10 +150,12 @@ export function useSetElementAttribute({
recordEdit,
pendingTimelineEditPathRef,
});
+ liveBeforeRef.current.delete(elementAttributeLiveKey(element, activeCompPath, attr));
} catch (error) {
console.error("[Timeline] Failed to set element attribute", error);
const message = error instanceof Error ? error.message : "Failed to update effect";
showToast(message);
+ liveBeforeRef.current.delete(elementAttributeLiveKey(element, activeCompPath, attr));
}
},
[
@@ -137,5 +169,5 @@ export function useSetElementAttribute({
projectIdRef,
],
);
- return { setLive, setQuiet };
+ return { setLive, setQuiet, revertLive };
}
diff --git a/packages/studio/src/hooks/useFileManager.ts b/packages/studio/src/hooks/useFileManager.ts
index 929003e371..bacbf7c096 100644
--- a/packages/studio/src/hooks/useFileManager.ts
+++ b/packages/studio/src/hooks/useFileManager.ts
@@ -1,18 +1,13 @@
-import { useState, useCallback, useMemo, useRef } from "react";
+import { useState, useCallback, useRef } from "react";
import type { EditingFile } from "../utils/studioHelpers";
import { FONT_EXT, isMediaFile } from "../utils/mediaTypes";
import { fontFamilyFromAssetPath, type ImportedFontAsset } from "../components/editor/fontAssets";
import type { EditHistoryKind } from "../utils/editHistory";
import { findTagByTarget, type PatchTarget } from "../utils/sourcePatcher";
-import {
- createStudioSaveHttpError,
- retryStudioSave,
- StudioFileConflictError,
- StudioSaveNetworkError,
-} from "../utils/studioSaveDiagnostics";
-import { studioExpectedFileVersion, studioWriteHeaders } from "../utils/studioFileVersion";
+import { StudioFileConflictError } from "../utils/studioSaveDiagnostics";
import { useFileTree } from "./useFileTree";
import { useEditorSave } from "./useEditorSave";
+import { useProjectFileWriter } from "./useProjectFileWriter";
// ── Types ──
@@ -50,17 +45,13 @@ export function useFileManager({
projectIdRef.current = projectId;
const importedFontAssetsRef = useRef<ImportedFontAsset[]>([]);
- const fileVersionScope = useMemo(
- () => ({ projectId, versions: new Map<string, string | null>() }),
- [projectId],
- );
- const fileVersions = fileVersionScope.versions;
- const observeProjectFileVersion = useCallback(
- (path: string, version: string | null) => {
- fileVersions.set(path, version);
- },
- [fileVersions],
- );
+ const {
+ fileVersions,
+ readProjectFile,
+ writeProjectFile: writeProjectFileRaw,
+ readOptionalProjectFile,
+ observeProjectFileVersion,
+ } = useProjectFileWriter({ projectId });
// ── File tree ──
@@ -74,117 +65,24 @@ export function useFileManager({
fontAssets,
} = useFileTree({ projectId, projectIdRef });
- // ── Core file I/O ──
-
- const readProjectFile = useCallback(
- async (path: string): Promise<string> => {
- if (!projectId) throw new Error("No active project");
- const response = await fetch(
- `/api/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}`,
- );
- if (!response.ok) throw new Error(`Failed to read ${path}`);
- const data = (await response.json()) as { content?: string; version?: string };
- if (typeof data.content !== "string") throw new Error(`Missing file contents for ${path}`);
- fileVersions.set(path, data.version ?? response.headers.get("etag"));
- return data.content;
- },
- [fileVersions, projectId],
- );
-
- const writeProjectFile = useCallback(
- async (path: string, content: string, expectedContent?: string): Promise<void> => {
- if (!projectId) throw new Error("No active project");
- const writeProjectId = projectId;
- let expectedVersion = await studioExpectedFileVersion(fileVersions, path, expectedContent);
- if (expectedVersion === undefined) {
- const preflight = await fetch(
- `/api/projects/${encodeURIComponent(writeProjectId)}/files/${encodeURIComponent(path)}`,
- );
- if (preflight.ok) {
- const data = (await preflight.json()) as { content?: string; version?: string };
- throw new StudioFileConflictError({
- filePath: path,
- currentVersion: data.version ?? preflight.headers.get("etag"),
- currentContent: data.content ?? null,
- attemptedContent: content,
- });
- } else if (preflight.status === 404) {
- expectedVersion = null;
- } else {
- throw await createStudioSaveHttpError(preflight, `Failed to read ${path} before save`);
- }
- }
- await retryStudioSave(async () => {
- // Each request gets its own receipt identity. If a committed request loses its response,
- // the retry can produce a second filesystem receipt that must be suppressed independently.
- let response: Response;
- try {
- response = await fetch(
- `/api/projects/${encodeURIComponent(writeProjectId)}/files/${encodeURIComponent(path)}`,
- {
- method: "PUT",
- headers: {
- "Content-Type": "text/plain",
- ...studioWriteHeaders(),
- ...(expectedVersion ? { "If-Match": expectedVersion } : { "If-None-Match": "*" }),
- },
- body: content,
- },
- );
- } catch (error) {
- throw new StudioSaveNetworkError(`Failed to save ${path}: network error`, {
- cause: error,
- });
- }
- if (response.status === 409) {
- const conflict = (await response.json().catch(() => null)) as {
- currentVersion?: string | null;
- currentContent?: string | null;
- } | null;
- const currentVersion = conflict?.currentVersion ?? null;
- if (currentVersion && conflict?.currentContent === content) {
- fileVersions.set(path, currentVersion);
- return;
- }
- throw new StudioFileConflictError({
- filePath: path,
- currentVersion,
- currentContent: conflict?.currentContent ?? null,
- attemptedContent: content,
- });
- }
- if (!response.ok) throw await createStudioSaveHttpError(response, `Failed to save ${path}`);
- const result = (await response.json()) as { version?: string };
- const version = result.version ?? response.headers.get("etag");
- if (!version)
- throw new Error(`Save response for ${path} did not include a content version`);
- fileVersions.set(path, version);
- });
- if (projectIdRef.current === writeProjectId && editingPathRef.current === path) {
- setEditingFile({ path, content });
- }
- },
- [fileVersions, projectId],
- );
-
const updateEditingFileContent = useCallback((path: string, content: string) => {
if (editingPathRef.current === path) {
setEditingFile({ path, content });
}
}, []);
- const readOptionalProjectFile = useCallback(
- async (path: string): Promise<string> => {
- if (!projectId) throw new Error("No active project");
- const response = await fetch(
- `/api/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}?optional=1`,
- );
- if (!response.ok) throw new Error(`Failed to read ${path}`);
- const data = (await response.json()) as { content?: string; version?: string };
- fileVersions.set(path, data.version ?? response.headers.get("etag"));
- return typeof data.content === "string" ? data.content : "";
+ // Studio's own editor tab mirrors whatever it just wrote, on top of the
+ // shared writer — a host mounting useProjectFileWriter directly has no
+ // editor tab and does not need this.
+ const writeProjectFile = useCallback(
+ async (path: string, content: string, expectedContent?: string): Promise<void> => {
+ const writeProjectId = projectIdRef.current;
+ await writeProjectFileRaw(path, content, expectedContent);
+ if (projectIdRef.current === writeProjectId && editingPathRef.current === path) {
+ setEditingFile({ path, content });
+ }
},
- [fileVersions, projectId],
+ [writeProjectFileRaw],
);
// ── Editor save (debounced content change) ──
diff --git a/packages/studio/src/hooks/usePersistentEditHistory.ts b/packages/studio/src/hooks/usePersistentEditHistory.ts
index 5c87ca2616..40d6b893ac 100644
--- a/packages/studio/src/hooks/usePersistentEditHistory.ts
+++ b/packages/studio/src/hooks/usePersistentEditHistory.ts
@@ -33,7 +33,7 @@ interface ApplyCallbacks {
serialize?: <T>(paths: readonly string[], task: () => Promise<T>) => Promise<T>;
}
-interface UsePersistentEditHistoryOptions {
+export interface UsePersistentEditHistoryOptions {
projectId: string | null;
storage?: EditHistoryStorageAdapter;
now?: () => number;
diff --git a/packages/studio/src/hooks/useProjectFileWriter.ts b/packages/studio/src/hooks/useProjectFileWriter.ts
new file mode 100644
index 0000000000..93d10b8833
--- /dev/null
+++ b/packages/studio/src/hooks/useProjectFileWriter.ts
@@ -0,0 +1,150 @@
+import { useCallback, useMemo } from "react";
+import {
+ createStudioSaveHttpError,
+ retryStudioSave,
+ StudioFileConflictError,
+ StudioSaveNetworkError,
+} from "../utils/studioSaveDiagnostics";
+import { studioExpectedFileVersion, studioWriteHeaders } from "../utils/studioFileVersion";
+
+export interface UseProjectFileWriterOptions {
+ projectId: string | null;
+}
+
+// The etag-guarded project-file read/write pair every Studio save path
+// shares. A host mounting hand editing outside Studio needs only this, not
+// the full file manager (file tree, editor tabs, uploads, font assets).
+export function useProjectFileWriter({ projectId }: UseProjectFileWriterOptions) {
+ const fileVersionScope = useMemo(
+ () => ({ projectId, versions: new Map<string, string | null>() }),
+ [projectId],
+ );
+ const fileVersions = fileVersionScope.versions;
+
+ const observeProjectFileVersion = useCallback(
+ (path: string, version: string | null) => {
+ fileVersions.set(path, version);
+ },
+ [fileVersions],
+ );
+
+ const readProjectFile = useCallback(
+ async (path: string): Promise<string> => {
+ if (!projectId) throw new Error("No active project");
+ const response = await fetch(
+ `/api/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}`,
+ );
+ if (!response.ok) throw new Error(`Failed to read ${path}`);
+ const data = (await response.json()) as { content?: string; version?: string };
+ if (typeof data.content !== "string") throw new Error(`Missing file contents for ${path}`);
+ fileVersions.set(path, data.version ?? response.headers.get("etag"));
+ return data.content;
+ },
+ [fileVersions, projectId],
+ );
+
+ const readOptionalProjectFile = useCallback(
+ async (path: string): Promise<string> => {
+ if (!projectId) throw new Error("No active project");
+ const response = await fetch(
+ `/api/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}?optional=1`,
+ );
+ if (!response.ok) throw new Error(`Failed to read ${path}`);
+ const data = (await response.json()) as { content?: string; version?: string };
+ fileVersions.set(path, data.version ?? response.headers.get("etag"));
+ return typeof data.content === "string" ? data.content : "";
+ },
+ [fileVersions, projectId],
+ );
+
+ const writeProjectFile = useCallback(
+ async (path: string, content: string, expectedContent?: string): Promise<void> => {
+ if (!projectId) throw new Error("No active project");
+ const writeProjectId = projectId;
+ let expectedVersion = await studioExpectedFileVersion(fileVersions, path, expectedContent);
+ if (expectedVersion === undefined) {
+ const preflight = await fetch(
+ `/api/projects/${encodeURIComponent(writeProjectId)}/files/${encodeURIComponent(path)}`,
+ );
+ if (preflight.ok) {
+ const data = (await preflight.json()) as { content?: string; version?: string };
+ throw new StudioFileConflictError({
+ filePath: path,
+ currentVersion: data.version ?? preflight.headers.get("etag"),
+ currentContent: data.content ?? null,
+ attemptedContent: content,
+ });
+ } else if (preflight.status === 404) {
+ expectedVersion = null;
+ } else {
+ throw await createStudioSaveHttpError(preflight, `Failed to read ${path} before save`);
+ }
+ }
+ // fallow-ignore-next-line complexity
+ await retryStudioSave(async () => {
+ // Each request gets its own receipt identity. If a committed request loses its response,
+ // the retry can produce a second filesystem receipt that must be suppressed independently.
+ let response: Response;
+ try {
+ response = await fetch(
+ `/api/projects/${encodeURIComponent(writeProjectId)}/files/${encodeURIComponent(path)}`,
+ {
+ method: "PUT",
+ headers: {
+ "Content-Type": "text/plain",
+ ...studioWriteHeaders(),
+ ...(expectedVersion ? { "If-Match": expectedVersion } : { "If-None-Match": "*" }),
+ },
+ body: content,
+ },
+ );
+ } catch (error) {
+ throw new StudioSaveNetworkError(`Failed to save ${path}: network error`, {
+ cause: error,
+ });
+ }
+ if (response.status === 409) {
+ const conflict = (await response.json().catch(() => null)) as {
+ currentVersion?: string | null;
+ currentContent?: string | null;
+ } | null;
+ const currentVersion = conflict?.currentVersion ?? null;
+ if (currentVersion && conflict?.currentContent === content) {
+ fileVersions.set(path, currentVersion);
+ return;
+ }
+ throw new StudioFileConflictError({
+ filePath: path,
+ currentVersion,
+ currentContent: conflict?.currentContent ?? null,
+ attemptedContent: content,
+ });
+ }
+ if (!response.ok) throw await createStudioSaveHttpError(response, `Failed to save ${path}`);
+ const result = (await response.json()) as { version?: string };
+ const version = result.version ?? response.headers.get("etag");
+ if (!version)
+ throw new Error(`Save response for ${path} did not include a content version`);
+ fileVersions.set(path, version);
+ });
+ },
+ [fileVersions, projectId],
+ );
+
+ return useMemo(
+ () => ({
+ fileVersions,
+ readProjectFile,
+ writeProjectFile,
+ readOptionalProjectFile,
+ observeProjectFileVersion,
+ }),
+ [
+ fileVersions,
+ readProjectFile,
+ writeProjectFile,
+ readOptionalProjectFile,
+ observeProjectFileVersion,
+ ],
+ );
+}
diff --git a/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx b/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx
index c1ae287345..c322059e70 100644
--- a/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx
+++ b/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx
@@ -16,19 +16,29 @@ afterEach(() => {
});
type DropFn = ReturnType<typeof useTimelineAssetDropOps>["handleTimelineAssetDrop"];
+type FileDropFn = ReturnType<typeof useTimelineAssetDropOps>["handleTimelineFileDrop"];
+type CompositionDropFn = ReturnType<
+ typeof useTimelineAssetDropOps
+>["handleTimelineCompositionDrop"];
function renderDropHook(
sourceContent: string,
writeProjectFile: (path: string, content: string, expectedContent?: string) => Promise<void>,
timelineElements: TimelineElement[] = [],
+ checkEditable?: (targets: readonly TimelineElement[]) => boolean,
+ uploadProjectFiles: (files: Iterable<File>, dir?: string) => Promise<string[]> = vi
+ .fn()
+ .mockResolvedValue([]),
) {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({ ok: true, json: async () => ({ content: sourceContent }) }),
);
let drop: DropFn | null = null;
+ let fileDrop: FileDropFn | null = null;
+ let compositionDrop: CompositionDropFn | null = null;
function Harness() {
- const { handleTimelineAssetDrop } = useTimelineAssetDropOps({
+ const handlers = useTimelineAssetDropOps({
projectIdRef: { current: "project" },
activeCompPath: "index.html",
timelineElements,
@@ -36,13 +46,19 @@ function renderDropHook(
writeProjectFile,
recordEdit: vi.fn().mockResolvedValue(undefined),
reloadPreview: vi.fn(),
- uploadProjectFiles: vi.fn().mockResolvedValue([]),
+ uploadProjectFiles,
+ checkEditable,
});
- drop = handleTimelineAssetDrop;
+ drop = handlers.handleTimelineAssetDrop;
+ fileDrop = handlers.handleTimelineFileDrop;
+ compositionDrop = handlers.handleTimelineCompositionDrop;
return null;
}
mountReactHarness(<Harness />);
- return () => drop!;
+ return Object.assign(() => drop!, {
+ file: () => fileDrop!,
+ composition: () => compositionDrop!,
+ });
}
describe("useTimelineAssetDropOps handleTimelineAssetDrop", () => {
@@ -124,4 +140,46 @@ describe("useTimelineAssetDropOps handleTimelineAssetDrop", () => {
expect(written).toContain('id="hidden" data-start="0" data-track-index="1"');
expect(written).toMatch(/<video id="clip"[^>]*data-track-index="1"/);
});
+
+ it("refuses an asset drop before reading or writing when editing is blocked", async () => {
+ const writeProjectFile = vi.fn().mockResolvedValue(undefined);
+ const checkEditable = vi.fn(() => false);
+ const getDrop = renderDropHook(
+ '<main data-composition-id="scene" data-duration="10"></main>',
+ writeProjectFile,
+ [],
+ checkEditable,
+ );
+
+ await act(async () => {
+ await getDrop()("clip.mp4", { start: 1, track: 0 }, 2);
+ });
+
+ expect(writeProjectFile).not.toHaveBeenCalled();
+ expect(checkEditable).toHaveBeenCalledWith([
+ expect.objectContaining({ sourceFile: "index.html", start: 1, track: 0 }),
+ ]);
+ });
+
+ it("refuses file and composition drops before their writes when editing is blocked", async () => {
+ const writeProjectFile = vi.fn().mockResolvedValue(undefined);
+ const uploadProjectFiles = vi.fn().mockResolvedValue(["clip.mp4"]);
+ const getDrop = renderDropHook(
+ '<main data-composition-id="scene" data-duration="10"></main>',
+ writeProjectFile,
+ [],
+ () => false,
+ uploadProjectFiles,
+ );
+ const fetchMock = vi.mocked(globalThis.fetch);
+
+ await act(async () => {
+ await getDrop.file()([new File(["clip"], "clip.mp4")], { start: 1, track: 0 });
+ await getDrop.composition()("scene.html", { start: 1, track: 0 });
+ });
+
+ expect(uploadProjectFiles).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(writeProjectFile).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/studio/src/hooks/useTimelineAssetDropOps.ts b/packages/studio/src/hooks/useTimelineAssetDropOps.ts
index 82d3c4ad1b..96af6997cb 100644
--- a/packages/studio/src/hooks/useTimelineAssetDropOps.ts
+++ b/packages/studio/src/hooks/useTimelineAssetDropOps.ts
@@ -38,6 +38,20 @@ function fileDropPlacement(
return index === 0 ? { ...dropped, ...next } : { ...next, track: landedTrack ?? next.track };
}
+function timelineDropTarget(
+ sourceFile: string,
+ placement: Pick<TimelineElement, "start" | "track">,
+): TimelineElement {
+ return {
+ id: "timeline-drop",
+ tag: "div",
+ start: placement.start,
+ duration: 0,
+ track: placement.track,
+ sourceFile,
+ };
+}
+
interface UseTimelineAssetDropOpsOptions {
projectIdRef: MutableRefObject<string | null>;
activeCompPath: string | null;
@@ -50,6 +64,7 @@ interface UseTimelineAssetDropOpsOptions {
isRecordingRef?: RefObject<boolean>;
forceReloadSdkSession?: () => void;
observeProjectFileVersion?: (path: string, version: string | null) => void;
+ checkEditable?: (targets: readonly TimelineElement[]) => boolean;
}
export function useTimelineAssetDropOps({
@@ -64,6 +79,7 @@ export function useTimelineAssetDropOps({
isRecordingRef,
forceReloadSdkSession,
observeProjectFileVersion,
+ checkEditable,
}: UseTimelineAssetDropOpsOptions) {
// fallow-ignore-next-line complexity
const dropAssetAt = useCallback(
@@ -77,6 +93,10 @@ export function useTimelineAssetDropOps({
showToast("Cannot edit timeline while recording", "error");
return undefined;
}
+ const targetPath = activeCompPath || "index.html";
+ if (checkEditable && !checkEditable([timelineDropTarget(targetPath, placement)])) {
+ return undefined;
+ }
const pid = projectIdRef.current;
if (!pid) throw new Error("No active project");
@@ -86,7 +106,6 @@ export function useTimelineAssetDropOps({
return undefined;
}
- const targetPath = activeCompPath || "index.html";
try {
const originalContent = await readFileContent(pid, targetPath);
@@ -172,6 +191,7 @@ export function useTimelineAssetDropOps({
reloadPreview,
isRecordingRef,
forceReloadSdkSession,
+ checkEditable,
],
);
@@ -190,6 +210,11 @@ export function useTimelineAssetDropOps({
showToast("Cannot edit timeline while recording", "error");
return;
}
+ const targetPath = activeCompPath || "index.html";
+ const initialPlacement = placement ?? { start: 0, track: 0 };
+ if (checkEditable && !checkEditable([timelineDropTarget(targetPath, initialPlacement)])) {
+ return;
+ }
const pid = projectIdRef.current;
if (!pid) return;
const uploaded = await uploadProjectFiles(files);
@@ -215,7 +240,15 @@ export function useTimelineAssetDropOps({
if (index === 0) landedTrack = track;
}
},
- [dropAssetAt, projectIdRef, uploadProjectFiles, isRecordingRef, showToast],
+ [
+ activeCompPath,
+ checkEditable,
+ dropAssetAt,
+ projectIdRef,
+ uploadProjectFiles,
+ isRecordingRef,
+ showToast,
+ ],
);
const handleTimelineCompositionDrop = useCallback(
@@ -224,9 +257,12 @@ export function useTimelineAssetDropOps({
showToast("Cannot edit timeline while recording", "error");
return;
}
+ const targetPath = activeCompPath || "index.html";
+ if (checkEditable && !checkEditable([timelineDropTarget(targetPath, placement)])) {
+ return;
+ }
const pid = projectIdRef.current;
if (!pid) throw new Error("No active project");
- const targetPath = activeCompPath || "index.html";
try {
await commitTimelineCompositionInsertion({
projectId: pid,
@@ -251,6 +287,7 @@ export function useTimelineAssetDropOps({
},
[
activeCompPath,
+ checkEditable,
forceReloadSdkSession,
isRecordingRef,
observeProjectFileVersion,
diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx
index 682cb5e829..add8d450f3 100644
--- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx
+++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx
@@ -5,6 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { TimelineElement } from "../player";
import { applyRippleShifts, useTimelineDeleteOps } from "./useTimelineDeleteOps";
import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness";
+import { useTrackPendingTimelineEdit } from "./useTrackPendingTimelineEdit";
+import { flushStudioPendingEdits } from "../utils/studioPendingEdits";
installReactActEnvironment();
@@ -117,3 +119,112 @@ describe("useTimelineDeleteOps: ripple undo label", () => {
);
});
});
+
+// Regression: a delete's write can reach disk before its history entry is
+// recorded, so an Undo fired in that window found nothing to restore.
+// Fails without useTrackPendingTimelineEdit's wrap (see that file).
+describe("useTimelineDeleteOps: undo race", () => {
+ // data-composition-id (readRootCompositionDuration's key) plus a
+ // remove-element mock that actually drops hf-c: needed for a real diff.
+ const html = `<!DOCTYPE html><html data-composition-variables='[]'><body>
+<div data-hf-id="hf-stage" data-composition-id="main" data-duration="6">
+<div data-hf-id="hf-a" data-start="0" data-duration="2"></div>
+<div data-hf-id="hf-b" data-start="2" data-duration="2"></div>
+<div data-hf-id="hf-c" data-start="4" data-duration="2"></div>
+</div>
+</body></html>`;
+ const htmlAfterDeletingC = `<!DOCTYPE html><html data-composition-variables='[]'><body>
+<div data-hf-id="hf-stage" data-composition-id="main" data-duration="6">
+<div data-hf-id="hf-a" data-start="0" data-duration="2"></div>
+<div data-hf-id="hf-b" data-start="2" data-duration="2"></div>
+</div>
+</body></html>`;
+
+ beforeEach(() => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.includes("/file-mutations/remove-element/")) {
+ return new Response(JSON.stringify({ changed: true, content: htmlAfterDeletingC }), {
+ status: 200,
+ });
+ }
+ return new Response(JSON.stringify({ content: html }), { status: 200 });
+ }),
+ );
+ });
+
+ afterEach(() => {
+ document.body.innerHTML = "";
+ vi.unstubAllGlobals();
+ });
+
+ // A manually-resolved gate stands in for the delete's write landing — a
+ // real timer raced the fix's own microtasks unpredictably (verified: it
+ // kept passing even with the fix's tracking call deleted).
+ function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => (resolve = r));
+ return { promise, resolve };
+ }
+
+ function mountRaceHarness() {
+ const elements = [el("hf-a", 0, 2), el("hf-b", 2, 2), el("hf-c", 4, 2)];
+ const gate = deferred<void>();
+ const recordEdit = vi.fn(() => gate.promise);
+ let tracked: ((elements: TimelineElement[]) => Promise<void>) | null = null;
+ function Harness() {
+ const track = useTrackPendingTimelineEdit();
+ const hook = useTimelineDeleteOps({
+ projectIdRef: { current: "test-project" },
+ activeCompPath: "index.html",
+ timelineElements: elements,
+ showToast: vi.fn(),
+ writeProjectFile: vi.fn().mockResolvedValue(undefined),
+ recordEdit,
+ reloadPreview: vi.fn(),
+ previewIframeRef: { current: null },
+ handleTimelineGroupMove: vi.fn().mockResolvedValue(undefined),
+ });
+ tracked = track(hook.handleTimelineElementsDelete);
+ return null;
+ }
+ mountReactHarness(<Harness />);
+ // Deletes the LAST clip (not the middle one): only this shrinks the
+ // composition's furthest-clip-end duration, so the write actually
+ // differs from the original content and recordEdit is reached — the
+ // middle clip's delete leaves duration unchanged and is a no-op write.
+ return { gate, recordEdit, deleteSelection: () => tracked!([elements[2]]) };
+ }
+
+ it("the pending-edit flush waits while the delete's history write is still landing", async () => {
+ const { gate, recordEdit, deleteSelection } = mountRaceHarness();
+ const order: string[] = [];
+ const deletePromise = deleteSelection().then(() => order.push("deleted"));
+ // Let the delete run up to (and call) recordEdit, which is now gated —
+ // this is the exact window a fast Undo used to race into.
+ await vi.waitFor(() => expect(recordEdit).toHaveBeenCalled());
+ // No React state changes happen inside the flush itself here (no
+ // pending-edit-flush listeners are registered in this harness), so it
+ // does not need act()'s wrapping — only awaiting the delete's own
+ // resolution below does.
+ const flushPromise = flushStudioPendingEdits().then(() => order.push("flushed"));
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(order).toEqual([]);
+ gate.resolve();
+ await deletePromise;
+ await flushPromise;
+ expect(order).toEqual(["deleted", "flushed"]);
+ });
+
+ it("the pending-edit flush resolves immediately once the delete has already finished", async () => {
+ const { gate, deleteSelection } = mountRaceHarness();
+ gate.resolve();
+ await deleteSelection();
+ await act(async () => {
+ await flushStudioPendingEdits();
+ });
+ });
+});
diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx
index 945633688e..0e98da3b62 100644
--- a/packages/studio/src/hooks/useTimelineEditing.test.tsx
+++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx
@@ -1,7 +1,7 @@
// fallow-ignore-file code-duplication
// @vitest-environment happy-dom
-import React, { act, useRef } from "react";
+import React, { act, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { openComposition } from "@hyperframes/sdk";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -122,12 +122,16 @@ function renderTimelineEditingHook(input: {
forceReloadSdkSession?: () => void;
invalidateGsapCache?: () => void;
showToast?: (message: string, kind?: string) => void;
+ canEdit?: NonNullable<Parameters<typeof useTimelineEditing>[0]["canEdit"]>;
}): {
move: ReturnType<typeof useTimelineEditing>["handleTimelineElementMove"];
resize: ReturnType<typeof useTimelineEditing>["handleTimelineElementResize"];
groupMove: ReturnType<typeof useTimelineEditing>["handleTimelineGroupMove"];
groupResize: ReturnType<typeof useTimelineEditing>["handleTimelineGroupResize"];
del: ReturnType<typeof useTimelineEditing>["handleTimelineElementDelete"];
+ elementsDelete: ReturnType<typeof useTimelineEditing>["handleTimelineElementsDelete"];
+ handleAutoGroupCarveSources: ReturnType<typeof useTimelineEditing>["handleAutoGroupCarveSources"];
+ setAudioGroupAttribute: ReturnType<typeof useTimelineEditing>["setAudioGroupAttribute"];
unmount: () => void;
} {
let move: ReturnType<typeof useTimelineEditing>["handleTimelineElementMove"] | null = null;
@@ -135,6 +139,14 @@ function renderTimelineEditingHook(input: {
let groupMove: ReturnType<typeof useTimelineEditing>["handleTimelineGroupMove"] | null = null;
let groupResize: ReturnType<typeof useTimelineEditing>["handleTimelineGroupResize"] | null = null;
let del: ReturnType<typeof useTimelineEditing>["handleTimelineElementDelete"] | null = null;
+ let elementsDelete: ReturnType<typeof useTimelineEditing>["handleTimelineElementsDelete"] | null =
+ null;
+ let handleAutoGroupCarveSources:
+ | ReturnType<typeof useTimelineEditing>["handleAutoGroupCarveSources"]
+ | null = null;
+ let setAudioGroupAttribute:
+ | ReturnType<typeof useTimelineEditing>["setAudioGroupAttribute"]
+ | null = null;
function Harness() {
const commitRef = useRef(input.onZIndexCommit);
@@ -155,12 +167,16 @@ function renderTimelineEditingHook(input: {
forceReloadSdkSession: input.forceReloadSdkSession,
invalidateGsapCache: input.invalidateGsapCache,
handleDomZIndexReorderCommitRef: commitRef,
+ canEdit: input.canEdit,
});
move = hook.handleTimelineElementMove;
resize = hook.handleTimelineElementResize;
groupMove = hook.handleTimelineGroupMove;
groupResize = hook.handleTimelineGroupResize;
del = hook.handleTimelineElementDelete;
+ elementsDelete = hook.handleTimelineElementsDelete;
+ handleAutoGroupCarveSources = hook.handleAutoGroupCarveSources;
+ setAudioGroupAttribute = hook.setAudioGroupAttribute;
return null;
}
@@ -170,7 +186,20 @@ function renderTimelineEditingHook(input: {
if (!groupMove) throw new Error("Expected hook to expose group move handler");
if (!groupResize) throw new Error("Expected hook to expose group resize handler");
if (!del) throw new Error("Expected hook to expose delete handler");
- return { move, resize, groupMove, groupResize, del, unmount };
+ if (!elementsDelete) throw new Error("Expected hook to expose elements-delete handler");
+ if (!handleAutoGroupCarveSources) throw new Error("Expected hook to expose group handler");
+ if (!setAudioGroupAttribute) throw new Error("Expected hook to expose audio group handler");
+ return {
+ move,
+ resize,
+ groupMove,
+ groupResize,
+ del,
+ elementsDelete,
+ handleAutoGroupCarveSources,
+ setAudioGroupAttribute,
+ unmount,
+ };
}
type TimelineRecordEdit = NonNullable<
@@ -289,6 +318,7 @@ function setupSingleClipHarness(options?: {
source?: string;
clipStyle?: string;
onZIndexCommit?: (entries: ZIndexEntry[]) => Promise<void>;
+ canEdit?: NonNullable<Parameters<typeof useTimelineEditing>[0]["canEdit"]>;
}) {
const iframe = createPreviewIframe([{ id: "clip", track: 0, style: options?.clipStyle }]);
const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
@@ -300,16 +330,30 @@ function setupSingleClipHarness(options?: {
const fetchMock = stubProjectFetch(
options?.source ?? '<div id="clip" data-start="0" data-track-index="0"></div>',
);
+ const recordEdit = vi.fn(async () => {});
+ const showToast = vi.fn();
const hook = renderTimelineEditingHook({
timelineElements: [clip],
iframe,
onZIndexCommit: commit,
projectId: "p1",
writeProjectFile,
- recordEdit: vi.fn(async () => {}),
+ recordEdit,
reloadPreview,
+ showToast,
+ canEdit: options?.canEdit,
});
- return { iframe, clip, commit, writeProjectFile, reloadPreview, fetchMock, ...hook };
+ return {
+ iframe,
+ clip,
+ commit,
+ writeProjectFile,
+ recordEdit,
+ showToast,
+ reloadPreview,
+ fetchMock,
+ ...hook,
+ };
}
const SDK_KEYFRAMED_SOURCE = [
@@ -1431,3 +1475,436 @@ describe("useTimelineEditing duration rollback on failed persist", () => {
succeeding.unmount();
});
});
+
+// Blocked means no fetch write, no recordEdit, and the host's reason
+// toasted. Absent canEdit behaves exactly as before (asserted above).
+describe("useTimelineEditing: canEdit gate", () => {
+ it("re-reads canEdit after the host changes its verdict", async () => {
+ const iframe = createPreviewIframe([{ id: "clip", track: 0 }]);
+ const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
+ const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ const showToast = vi.fn();
+ const recordEdit = vi.fn(async () => {});
+ const pendingTimelineEditPathRef = { current: new Set<string>() };
+ const previewIframeRef = { current: iframe };
+ const uploadProjectFiles = vi.fn();
+ const reloadPreview = vi.fn();
+ let setBlocked = () => {};
+ let hook: ReturnType<typeof useTimelineEditing> | null = null;
+
+ function Harness() {
+ const [blocked, updateBlocked] = useState(false);
+ setBlocked = () => updateBlocked(true);
+ hook = useTimelineEditing({
+ projectId: "p1",
+ activeCompPath: "index.html",
+ timelineElements: [clip],
+ showToast,
+ writeProjectFile,
+ recordEdit,
+ reloadPreview,
+ previewIframeRef,
+ pendingTimelineEditPathRef,
+ uploadProjectFiles,
+ canEdit: () => (blocked ? { blocked: true, reason: "Reserved by an agent" } : true),
+ });
+ return null;
+ }
+
+ const { unmount } = mountHarness(<Harness />);
+ if (!hook) throw new Error("Expected hook to mount");
+ act(() => setBlocked());
+
+ await act(async () => {
+ await hook!.handleTimelineElementMove(clip, { start: 3, track: clip.track });
+ await flushAsyncWork();
+ });
+
+ expect(writeProjectFile).not.toHaveBeenCalled();
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(showToast).toHaveBeenCalledWith("Reserved by an agent", "error");
+ unmount();
+ });
+
+ it("refuses a move with the host's reason, writing nothing", async () => {
+ const { clip, move, writeProjectFile, recordEdit, showToast, unmount } = setupSingleClipHarness(
+ {
+ canEdit: () => ({ blocked: true, reason: "Reserved by an agent" }),
+ },
+ );
+
+ await act(async () => {
+ await move(clip, { start: 3, track: clip.track });
+ await flushAsyncWork();
+ });
+
+ expect(writeProjectFile).not.toHaveBeenCalled();
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(showToast).toHaveBeenCalledWith("Reserved by an agent", "error");
+ unmount();
+ });
+
+ it("refuses a delete (single and multi) with nothing written", async () => {
+ const { clip, del, elementsDelete, writeProjectFile, recordEdit, unmount } =
+ setupSingleClipHarness({
+ canEdit: () => ({ blocked: true, reason: "Reserved by an agent" }),
+ });
+
+ await act(async () => {
+ await del(clip);
+ await elementsDelete([clip]);
+ await flushAsyncWork();
+ });
+
+ expect(writeProjectFile).not.toHaveBeenCalled();
+ expect(recordEdit).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it("resolves toggle-track-hidden against the expanded rows, not the raw timelineElements prop", async () => {
+ // Regression: canEdit must resolve against the expanded rows
+ // (timelineTrackVisibility.ts's own invariant), not the raw
+ // timelineElements prop — proven by making the two disagree below.
+ const iframe = createPreviewIframe([{ id: "clip", track: 0 }]);
+ const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
+ usePlayerStore.getState().setElements([clip]);
+ const showToast = vi.fn();
+ const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ let hook: ReturnType<typeof useTimelineEditing> | null = null;
+ function Harness() {
+ hook = useTimelineEditing({
+ projectId: "p1",
+ activeCompPath: "index.html",
+ timelineElements: [], // deliberately does not contain `clip`
+ showToast,
+ writeProjectFile,
+ recordEdit: vi.fn(),
+ reloadPreview: vi.fn(),
+ previewIframeRef: { current: iframe },
+ pendingTimelineEditPathRef: { current: new Set<string>() },
+ uploadProjectFiles: vi.fn(),
+ canEdit: (element) =>
+ element.id === "clip" ? { blocked: true, reason: "Reserved by an agent" } : true,
+ });
+ return null;
+ }
+ const { unmount } = mountHarness(<Harness />);
+ if (!hook) throw new Error("Expected hook to mount");
+
+ await act(async () => {
+ await hook!.handleToggleTrackHidden(0, true);
+ await flushAsyncWork();
+ });
+
+ expect(showToast).toHaveBeenCalledWith("Reserved by an agent", "error");
+ expect(writeProjectFile).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it("lets an unblocked element through while a blocked one is refused", async () => {
+ const iframe = createPreviewIframe([
+ { id: "free", track: 0 },
+ { id: "locked", track: 1 },
+ ]);
+ const free = timelineElement({ id: "free", track: 0, zIndex: 0 });
+ const locked = timelineElement({ id: "locked", track: 1, zIndex: 0 });
+ const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ const recordEdit = vi.fn(async () => {});
+ stubProjectFetch(
+ '<div id="free" data-start="0" data-track-index="0"></div>' +
+ '<div id="locked" data-start="0" data-track-index="1"></div>',
+ );
+ const hook = renderTimelineEditingHook({
+ timelineElements: [free, locked],
+ iframe,
+ onZIndexCommit: vi.fn().mockResolvedValue(undefined),
+ projectId: "p1",
+ writeProjectFile,
+ recordEdit,
+ canEdit: (element) =>
+ element.id === "locked" ? { blocked: true, reason: "Reserved by an agent" } : true,
+ });
+
+ await act(async () => {
+ await hook.move(locked, { start: 3, track: locked.track });
+ await flushAsyncWork();
+ });
+ expect(writeProjectFile).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await hook.move(free, { start: 3, track: free.track });
+ await flushAsyncWork();
+ });
+ expect(writeProjectFile).toHaveBeenCalled();
+ hook.unmount();
+ });
+
+ it("refuses razor-split-all when it would split a blocked clip, writing nothing", async () => {
+ const iframe = createPreviewIframe([{ id: "clip", track: 0 }]);
+ const clip = timelineElement({ id: "clip", track: 0, zIndex: 0, start: 0, duration: 2 });
+ usePlayerStore.getState().setElements([clip]);
+ const showToast = vi.fn();
+ const fetchMock = vi.fn(async () => {
+ throw new Error("must not be called: canEdit should have refused the split");
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ let hook: ReturnType<typeof useTimelineEditing> | null = null;
+ function Harness() {
+ hook = useTimelineEditing({
+ projectId: "p1",
+ activeCompPath: "index.html",
+ timelineElements: [clip],
+ showToast,
+ writeProjectFile: vi.fn(),
+ recordEdit: vi.fn(),
+ reloadPreview: vi.fn(),
+ previewIframeRef: { current: iframe },
+ pendingTimelineEditPathRef: { current: new Set<string>() },
+ uploadProjectFiles: vi.fn(),
+ canEdit: () => ({ blocked: true, reason: "Reserved by an agent" }),
+ });
+ return null;
+ }
+ const { unmount } = mountHarness(<Harness />);
+ if (!hook) throw new Error("Expected hook to mount");
+
+ await act(async () => {
+ await hook!.handleRazorSplitAll(1);
+ await flushAsyncWork();
+ });
+
+ expect(showToast).toHaveBeenCalledWith("Reserved by an agent", "error");
+ expect(fetchMock).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it("refuses a blocked group's audio attribute write, writing nothing", async () => {
+ const iframe = createPreviewIframe([{ id: "member", track: 0 }]);
+ const member = timelineElement({ id: "member", track: 0, zIndex: 0 });
+ usePlayerStore.getState().setElements([{ ...member, audioGroup: "hf-group" }]);
+ const showToast = vi.fn();
+ const fetchMock = vi.fn(async () => {
+ throw new Error("must not be called: canEdit should have refused the write");
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ let hook: ReturnType<typeof useTimelineEditing> | null = null;
+ function Harness() {
+ hook = useTimelineEditing({
+ projectId: "p1",
+ activeCompPath: "index.html",
+ timelineElements: [member],
+ showToast,
+ writeProjectFile: vi.fn(),
+ recordEdit: vi.fn(),
+ reloadPreview: vi.fn(),
+ previewIframeRef: { current: iframe },
+ pendingTimelineEditPathRef: { current: new Set<string>() },
+ uploadProjectFiles: vi.fn(),
+ canEdit: (element) =>
+ element.id === "member" ? { blocked: true, reason: "Reserved by an agent" } : true,
+ });
+ return null;
+ }
+ const { unmount } = mountHarness(<Harness />);
+ if (!hook) throw new Error("Expected hook to mount");
+
+ await act(async () => {
+ await hook!.setAudioGroupAttribute.setQuiet("hf-group", "data-volume", "0.5", "Set volume");
+ await flushAsyncWork();
+ });
+
+ expect(showToast).toHaveBeenCalledWith("Reserved by an agent", "error");
+ expect(fetchMock).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it("refuses a group write when its members live only inside a sub-composition", async () => {
+ // syncStoredGroupAttribute mirrors into domClipChildren for a group with
+ // no flat twin (timelineAudioGroupVolume.ts) — the resolver must check
+ // that array too, or a sub-comp-only group's write goes ungated.
+ const iframe = createPreviewIframe([]);
+ usePlayerStore.getState().setElements([]);
+ usePlayerStore.getState().setDomClipChildren([
+ {
+ id: "sub-member",
+ parentId: "host",
+ hostId: "host",
+ label: "Sub member",
+ stackingContextId: "root",
+ audioGroup: "hf-group",
+ },
+ ]);
+ const showToast = vi.fn();
+ const fetchMock = vi.fn(async () => {
+ throw new Error("must not be called: canEdit should have refused the write");
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ let hook: ReturnType<typeof useTimelineEditing> | null = null;
+ function Harness() {
+ hook = useTimelineEditing({
+ projectId: "p1",
+ activeCompPath: "index.html",
+ timelineElements: [],
+ showToast,
+ writeProjectFile: vi.fn(),
+ recordEdit: vi.fn(),
+ reloadPreview: vi.fn(),
+ previewIframeRef: { current: iframe },
+ pendingTimelineEditPathRef: { current: new Set<string>() },
+ uploadProjectFiles: vi.fn(),
+ canEdit: (element) =>
+ element.id === "sub-member" ? { blocked: true, reason: "Reserved by an agent" } : true,
+ });
+ return null;
+ }
+ const { unmount } = mountHarness(<Harness />);
+ if (!hook) throw new Error("Expected hook to mount");
+
+ await act(async () => {
+ await hook!.setAudioGroupAttribute.setQuiet("hf-group", "data-volume", "0.5", "Set volume");
+ await flushAsyncWork();
+ });
+
+ expect(showToast).toHaveBeenCalledWith("Reserved by an agent", "error");
+ expect(fetchMock).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it("refuses auto-grouping before it patches existing clips", async () => {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const doc = iframe.contentDocument;
+ if (!doc) throw new Error("Expected iframe document");
+ doc.body.innerHTML =
+ '<audio id="voice-1" data-start="0" data-duration="5"></audio>' +
+ '<audio id="voice-2" data-start="5" data-duration="5"></audio>';
+ const voice1 = timelineElement({ id: "voice-1", tag: "audio", track: 0, zIndex: 0 });
+ const voice2 = timelineElement({ id: "voice-2", tag: "audio", track: 1, zIndex: 0 });
+ usePlayerStore.getState().setElements([voice1, voice2]);
+ const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ const recordEdit = vi.fn(async () => {});
+ const showToast = vi.fn();
+ const fetchMock = stubProjectFetch(
+ '<audio id="voice-1" data-start="0" data-duration="5"></audio>' +
+ '<audio id="voice-2" data-start="5" data-duration="5"></audio>',
+ );
+ const hook = renderTimelineEditingHook({
+ timelineElements: [voice1, voice2],
+ iframe,
+ onZIndexCommit: vi.fn().mockResolvedValue(undefined),
+ projectId: "p1",
+ writeProjectFile,
+ recordEdit,
+ showToast,
+ canEdit: (element) =>
+ element.id === "voice-2" ? { blocked: true, reason: "Reserved by an agent" } : true,
+ });
+
+ await expect(
+ hook.handleAutoGroupCarveSources(["voice-1", "voice-2"], "voiceover"),
+ ).rejects.toThrow("Timeline edit blocked");
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(writeProjectFile).not.toHaveBeenCalled();
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(showToast).toHaveBeenCalledWith("Reserved by an agent", "error");
+ expect(doc.getElementById("voice-1")?.getAttribute("data-audio-group")).toBeNull();
+ expect(doc.getElementById("voiceover")).toBeNull();
+ hook.unmount();
+ });
+
+ it("reverts an optimistic group live value when the commit is refused", async () => {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const doc = iframe.contentDocument;
+ if (!doc) throw new Error("Expected iframe document");
+ doc.body.innerHTML =
+ '<hf-audio-group id="voiceover" data-volume="1"></hf-audio-group>' +
+ '<audio id="voice-1" data-start="0" data-duration="5"></audio>';
+ const member = {
+ ...timelineElement({ id: "voice-1", tag: "audio", track: 0, zIndex: 0 }),
+ audioGroup: "voiceover",
+ audioGroupVolume: 1,
+ };
+ usePlayerStore.getState().setElements([member]);
+ const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ const recordEdit = vi.fn(async () => {});
+ const showToast = vi.fn();
+ const hook = renderTimelineEditingHook({
+ timelineElements: [member],
+ iframe,
+ onZIndexCommit: vi.fn().mockResolvedValue(undefined),
+ projectId: "p1",
+ writeProjectFile,
+ recordEdit,
+ showToast,
+ canEdit: () => ({ blocked: true, reason: "Reserved by an agent" }),
+ });
+
+ await act(async () => {
+ hook.setAudioGroupAttribute.setLive("voiceover", "data-volume", "0.4");
+ });
+ expect(doc.getElementById("voiceover")?.getAttribute("data-volume")).toBe("0.4");
+ expect(usePlayerStore.getState().elements[0]?.audioGroupVolume).toBe(0.4);
+
+ await act(async () => {
+ await hook.setAudioGroupAttribute.setQuiet("voiceover", "data-volume", "0.4", "Set volume");
+ });
+
+ expect(doc.getElementById("voiceover")?.getAttribute("data-volume")).toBe("1");
+ expect(usePlayerStore.getState().elements[0]?.audioGroupVolume).toBe(1);
+ expect(writeProjectFile).not.toHaveBeenCalled();
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(showToast).toHaveBeenCalledWith("Reserved by an agent", "error");
+ hook.unmount();
+ });
+});
+
+// Regression: track()/guard() must return the same wrapped handler across
+// renders for the same fn, or a consumer using it as a memo/effect
+// dependency re-runs on every render for nothing.
+describe("useTimelineEditing: handler identity is stable across renders", () => {
+ it("returns the same handleTimelineElementMove reference on a re-render", () => {
+ const iframe = createPreviewIframe([{ id: "clip", track: 0 }]);
+ const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
+ stubProjectFetch('<div id="clip" data-start="0" data-track-index="0"></div>');
+ // Every option below is hoisted (created once), matching a real caller's
+ // stable useCallback/selector inputs — a fresh vi.fn() per render would
+ // change handleTimelineElementMove's own identity regardless of the fix.
+ const timelineElements = [clip];
+ const showToast = vi.fn();
+ const writeProjectFile = vi.fn();
+ const recordEdit = vi.fn();
+ const reloadPreview = vi.fn();
+ const uploadProjectFiles = vi.fn();
+ const previewIframeRef = { current: iframe };
+ const pendingTimelineEditPathRef = { current: new Set<string>() };
+ const seen: unknown[] = [];
+ let bumpTick = 0;
+ let bump = () => {};
+ function Harness() {
+ const [, setTick] = React.useState(0);
+ bump = () => setTick((t) => t + 1);
+ bumpTick += 1;
+ const hook = useTimelineEditing({
+ projectId: "p1",
+ activeCompPath: "index.html",
+ timelineElements,
+ showToast,
+ writeProjectFile,
+ recordEdit,
+ reloadPreview,
+ previewIframeRef,
+ pendingTimelineEditPathRef,
+ uploadProjectFiles,
+ });
+ seen.push(hook.handleTimelineElementMove);
+ return null;
+ }
+ const { unmount } = mountHarness(<Harness />);
+ act(() => bump());
+ expect(bumpTick).toBeGreaterThan(1);
+ expect(seen[0]).toBe(seen[1]);
+ unmount();
+ });
+});
diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts
index ab6b37df18..efc0787e60 100644
--- a/packages/studio/src/hooks/useTimelineEditing.ts
+++ b/packages/studio/src/hooks/useTimelineEditing.ts
@@ -1,7 +1,9 @@
// fallow-ignore-file complexity
import { useCallback, useRef } from "react";
import type { TimelineElement } from "../player";
+import { usePlayerStore } from "../player";
import { useRazorSplit } from "./useRazorSplit";
+import { selectSplittableElements } from "../utils/timelineElementSplit";
import { useTimelineAssetDropOps } from "./useTimelineAssetDropOps";
import {
applyTimelineStackingReorder,
@@ -23,6 +25,8 @@ import type { PersistTimelineEditInput } from "./timelineEditingHelpers";
import { useSetAudioGroupAttribute } from "./timelineAudioGroupVolume";
import { useSetElementAttribute } from "./timelineElementFxAttribute";
import { useTimelineDeleteOps } from "./useTimelineDeleteOps";
+import { useTimelineRowElements } from "../player/hooks/useTimelineRowElements";
+import { useTrackPendingTimelineEdit } from "./useTrackPendingTimelineEdit";
import { useAudioGroupCarveAssignment } from "./timelineAudioGroupCreate";
import {
useTimelineElementVisibilityEditing,
@@ -30,11 +34,22 @@ import {
} from "./timelineTrackVisibility";
import { useTimelineGroupEditing } from "./useTimelineGroupEditing";
import { useBlockedTimelineEditToast } from "./useBlockedTimelineEditToast";
+import { useTimelineEditGate } from "./timelineEditPermission";
import { serializeZLaneGesture } from "../components/nle/zLaneGesture";
import { cutoverCommittedOrThrow, sdkTimingPersist } from "../utils/sdkCutover";
import type { TimelineMoveUpdates, UseTimelineEditingOptions } from "./useTimelineEditingTypes";
import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics";
+type GuardedTimelineHandler = (...args: never[]) => Promise<void>;
+type GuardedTimelineResolver = (...args: never[]) => readonly TimelineElement[];
+type GuardedTimelineRefusal = (...args: never[]) => void;
+
+interface GuardedTimelineEntry {
+ resolveTargets: GuardedTimelineResolver;
+ onRefused?: GuardedTimelineRefusal;
+ wrapped: GuardedTimelineHandler;
+}
+
export function useTimelineEditing({
projectId,
activeCompPath,
@@ -53,10 +68,51 @@ export function useTimelineEditing({
forceReloadSdkSession,
invalidateGsapCache,
handleDomZIndexReorderCommitRef,
+ canEdit,
}: UseTimelineEditingOptions) {
const projectIdRef = useRef(projectId);
projectIdRef.current = projectId;
const editQueueRef = useRef(Promise.resolve());
+ const track = useTrackPendingTimelineEdit();
+ const checkEditable = useTimelineEditGate(canEdit, showToast);
+ const checkEditableRef = useRef(checkEditable);
+ checkEditableRef.current = checkEditable;
+ // Same expanded-row source the hide handlers themselves resolve against
+ // (timelineTrackVisibility.ts) — a virtual sub-comp child's track/key
+ // only exists here, not in the raw store list canEdit would otherwise miss.
+ const timelineRowElements = useTimelineRowElements();
+ const guardedRef = useRef(new WeakMap<GuardedTimelineHandler, GuardedTimelineEntry>());
+ // Refuses (no call, no write, no history entry) when any target is
+ // blocked; otherwise runs fn as before. Cached by fn identity — like
+ // track() — so a fresh closure here doesn't defeat track's own cache.
+ const guard = useCallback(
+ <H extends (...args: never[]) => Promise<void>>(
+ resolveTargets: (...args: Parameters<H>) => readonly TimelineElement[],
+ fn: H,
+ onRefused?: (...args: Parameters<H>) => void,
+ ): H => {
+ const key = fn as unknown as GuardedTimelineHandler;
+ const cached = guardedRef.current.get(key);
+ if (cached) {
+ cached.resolveTargets = resolveTargets as unknown as GuardedTimelineResolver;
+ cached.onRefused = onRefused as unknown as GuardedTimelineRefusal | undefined;
+ return cached.wrapped as H;
+ }
+ const entry = {} as GuardedTimelineEntry;
+ entry.resolveTargets = resolveTargets as unknown as GuardedTimelineResolver;
+ entry.onRefused = onRefused as unknown as GuardedTimelineRefusal | undefined;
+ entry.wrapped = ((...args: Parameters<H>) => {
+ if (!checkEditableRef.current(entry.resolveTargets(...(args as never[])))) {
+ entry.onRefused?.(...(args as never[]));
+ return Promise.resolve();
+ }
+ return fn(...args);
+ }) as H as unknown as GuardedTimelineHandler;
+ guardedRef.current.set(key, entry);
+ return entry.wrapped as H;
+ },
+ [],
+ );
const enqueueEdit = useCallback(
(
@@ -378,9 +434,10 @@ export function useTimelineEditing({
previewIframeRef,
pendingTimelineEditPathRef,
isRecordingRef,
+ checkEditable,
});
- const setElementFxAttribute = useSetElementAttribute({
+ const { revertLive: revertElementFxLive, ...setElementFxAttribute } = useSetElementAttribute({
projectIdRef,
activeCompPath,
showToast,
@@ -391,16 +448,18 @@ export function useTimelineEditing({
isRecordingRef,
});
- const setAudioGroupAttribute = useSetAudioGroupAttribute({
- projectIdRef,
- activeCompPath,
- showToast,
- writeProjectFile,
- recordEdit,
- previewIframeRef,
- pendingTimelineEditPathRef,
- isRecordingRef,
- });
+ const { revertLive: revertAudioGroupLive, ...setAudioGroupAttribute } = useSetAudioGroupAttribute(
+ {
+ projectIdRef,
+ activeCompPath,
+ showToast,
+ writeProjectFile,
+ recordEdit,
+ previewIframeRef,
+ pendingTimelineEditPathRef,
+ isRecordingRef,
+ },
+ );
const { handleTimelineElementsDelete, handleTimelineElementDelete } = useTimelineDeleteOps({
projectIdRef,
@@ -429,6 +488,7 @@ export function useTimelineEditing({
isRecordingRef,
forceReloadSdkSession,
observeProjectFileVersion,
+ checkEditable,
});
const handleBlockedTimelineEdit = useBlockedTimelineEditToast(showToast);
@@ -445,23 +505,87 @@ export function useTimelineEditing({
forceReloadSdkSession,
});
+ // Every write-handler is tracked here, the one place all hand edits
+ // converge, so undo never races a write; canEdit gates the same point.
+ // Coverage boundary: see the PR body, not every kind resolves an element.
+ const trackedRazorSplit = track(guard((element) => [element], handleRazorSplit));
return {
- handleTimelineElementMove,
- handleTimelineElementResize,
- handleToggleTrackHidden,
- handleToggleElementHidden,
- handleAutoGroupCarveSources,
- setAudioGroupAttribute,
- setElementFxAttribute,
- handleTimelineElementDelete,
- handleTimelineElementsDelete,
- handleTimelineElementSplit: handleRazorSplit,
- handleRazorSplit,
- handleRazorSplitAll,
- handleTimelineAssetDrop,
- handleTimelineFileDrop,
- handleTimelineCompositionDrop,
+ handleTimelineElementMove: track(guard((element) => [element], handleTimelineElementMove)),
+ handleTimelineElementResize: track(guard((element) => [element], handleTimelineElementResize)),
+ handleToggleTrackHidden: track(
+ guard(
+ (trackIndex) => timelineRowElements.filter((el) => el.track === trackIndex),
+ handleToggleTrackHidden,
+ ),
+ ),
+ handleToggleElementHidden: track(
+ guard((elementKey) => {
+ const keys = new Set(Array.isArray(elementKey) ? elementKey : [elementKey]);
+ return timelineRowElements.filter((el) => keys.has(el.key ?? el.id));
+ }, handleToggleElementHidden),
+ ),
+ handleAutoGroupCarveSources: track(handleAutoGroupCarveSources),
+ setAudioGroupAttribute: {
+ ...setAudioGroupAttribute,
+ // Same two-array member lookup syncStoredGroupAttribute mirrors into
+ // (timelineAudioGroupVolume.ts): a sub-composition's group members have
+ // no flat twin, only a domClipChildren entry, so both are checked.
+ setQuiet: track(
+ guard(
+ (groupId) => {
+ const state = usePlayerStore.getState();
+ const flatMembers = state.elements.filter((el) => el.audioGroup === groupId);
+ const domMembers = state.domClipChildren
+ .filter((child) => child.audioGroup === groupId)
+ .map(
+ (child): TimelineElement => ({
+ id: child.id,
+ domId: child.id,
+ tag: "div",
+ start: 0,
+ duration: 0,
+ track: -1,
+ }),
+ );
+ return [...flatMembers, ...domMembers];
+ },
+ setAudioGroupAttribute.setQuiet,
+ (groupId, attr) => revertAudioGroupLive(groupId, attr),
+ ),
+ ),
+ },
+ setElementFxAttribute: {
+ ...setElementFxAttribute,
+ setQuiet: track(
+ guard(
+ (element) => [element],
+ setElementFxAttribute.setQuiet,
+ (element, attr) => revertElementFxLive(element, attr),
+ ),
+ ),
+ },
+ handleTimelineElementDelete: track(guard((element) => [element], handleTimelineElementDelete)),
+ handleTimelineElementsDelete: track(
+ guard((elements) => elements, handleTimelineElementsDelete),
+ ),
+ handleTimelineElementSplit: trackedRazorSplit,
+ handleRazorSplit: trackedRazorSplit,
+ // Same selection the handler itself splits (useRazorSplit.ts).
+ handleRazorSplitAll: track(
+ guard(
+ (splitTime) => selectSplittableElements(usePlayerStore.getState().elements, splitTime),
+ handleRazorSplitAll,
+ ),
+ ),
+ handleTimelineAssetDrop: track(handleTimelineAssetDrop),
+ handleTimelineFileDrop: track(handleTimelineFileDrop),
+ handleTimelineCompositionDrop: track(handleTimelineCompositionDrop),
handleBlockedTimelineEdit,
- ...groupEditing,
+ handleTimelineGroupMove: track(
+ guard((changes) => changes.map((c) => c.element), groupEditing.handleTimelineGroupMove),
+ ),
+ handleTimelineGroupResize: track(
+ guard((changes) => changes.map((c) => c.element), groupEditing.handleTimelineGroupResize),
+ ),
};
}
diff --git a/packages/studio/src/hooks/useTimelineEditingTypes.ts b/packages/studio/src/hooks/useTimelineEditingTypes.ts
index 67212df12c..9c0cf886d2 100644
--- a/packages/studio/src/hooks/useTimelineEditingTypes.ts
+++ b/packages/studio/src/hooks/useTimelineEditingTypes.ts
@@ -4,6 +4,7 @@ import type { TimelineElement } from "../player";
import type { TimelineStackingReorderIntent } from "../player/components/timelineEditing";
import type { EditHistoryKind } from "../utils/editHistory";
import type { PublishSdkSession } from "../utils/sdkCutover";
+import type { CanEditTimelineElement } from "./timelineEditPermission";
interface RecordEditInput {
label: string;
@@ -49,6 +50,8 @@ export interface UseTimelineEditingOptions {
/** Reparse authored animations after a timing rewrite changes their positions. */
invalidateGsapCache?: () => void;
handleDomZIndexReorderCommitRef?: MutableRefObject<TimelineZIndexReorderCommit | null>;
+ /** Refuses a hand edit at the persist boundary when set; absent = Studio unchanged. */
+ canEdit?: CanEditTimelineElement;
}
export type TimelineFileDropHandler = (
diff --git a/packages/studio/src/hooks/useTrackPendingTimelineEdit.test.tsx b/packages/studio/src/hooks/useTrackPendingTimelineEdit.test.tsx
new file mode 100644
index 0000000000..be7d2a6e62
--- /dev/null
+++ b/packages/studio/src/hooks/useTrackPendingTimelineEdit.test.tsx
@@ -0,0 +1,62 @@
+// @vitest-environment happy-dom
+
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, describe, expect, it } from "vitest";
+import { flushStudioPendingEdits } from "../utils/studioPendingEdits";
+import { useTrackPendingTimelineEdit } from "./useTrackPendingTimelineEdit";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | null = null;
+afterEach(() => act(() => root?.unmount()));
+
+function mount() {
+ let track!: ReturnType<typeof useTrackPendingTimelineEdit>;
+ function Probe() {
+ track = useTrackPendingTimelineEdit();
+ return null;
+ }
+ root = createRoot(document.createElement("div"));
+ act(() => root!.render(createElement(Probe)));
+ return track;
+}
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => (resolve = r));
+ return { promise, resolve };
+};
+
+describe("useTrackPendingTimelineEdit", () => {
+ it("feeds Studio's shared pending-edit registry, so the app-wide flush waits for it", async () => {
+ const track = mount();
+ const gate = deferred<void>();
+ const order: string[] = [];
+ const tracked = track(() => gate.promise.then(() => order.push("edit-settled")));
+ const call = tracked();
+ const flushPromise = flushStudioPendingEdits().then(() => order.push("flushed"));
+ // Give the flush's own microtasks a turn: if tracking did nothing, it
+ // would already show "flushed" here, before the edit ever settles.
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(order).toEqual([]);
+ gate.resolve();
+ await call;
+ await flushPromise;
+ expect(order).toEqual(["edit-settled", "flushed"]);
+ });
+
+ it("returns the same wrapper for the same handler across calls", () => {
+ const track = mount();
+ const handler = () => Promise.resolve();
+ expect(track(handler)).toBe(track(handler));
+ });
+
+ it("returns a different wrapper for a different handler", () => {
+ const track = mount();
+ const a = () => Promise.resolve();
+ const b = () => Promise.resolve();
+ expect(track(a)).not.toBe(track(b));
+ });
+});
diff --git a/packages/studio/src/hooks/useTrackPendingTimelineEdit.ts b/packages/studio/src/hooks/useTrackPendingTimelineEdit.ts
new file mode 100644
index 0000000000..9687e671f0
--- /dev/null
+++ b/packages/studio/src/hooks/useTrackPendingTimelineEdit.ts
@@ -0,0 +1,22 @@
+import { useCallback, useRef } from "react";
+import { trackStudioPendingEdit } from "../utils/studioPendingEdits";
+
+type AsyncFn = (...args: never[]) => Promise<unknown>;
+
+// Tracks a hand-edit handler's write so undo/redo (already draining this
+// registry) waits for it. Same `fn` in, same wrapper out, so memoized deps stay stable.
+export function useTrackPendingTimelineEdit() {
+ const wrappedRef = useRef(new WeakMap<AsyncFn, AsyncFn>());
+ return useCallback(<Args extends unknown[], R>(fn: (...args: Args) => Promise<R>) => {
+ const key = fn as unknown as AsyncFn;
+ const cached = wrappedRef.current.get(key);
+ if (cached) return cached as unknown as (...args: Args) => Promise<R>;
+ const wrapped = (...args: Args): Promise<R> => {
+ const result = fn(...args);
+ trackStudioPendingEdit(result);
+ return result;
+ };
+ wrappedRef.current.set(key, wrapped as unknown as AsyncFn);
+ return wrapped;
+ }, []);
+}
diff --git a/packages/studio/src/hostMount.test.tsx b/packages/studio/src/hostMount.test.tsx
new file mode 100644
index 0000000000..77592f075d
--- /dev/null
+++ b/packages/studio/src/hostMount.test.tsx
@@ -0,0 +1,222 @@
+// @vitest-environment happy-dom
+
+// Proves the package's public exports, not internal hook paths, are enough
+// for a host to mount hand editing outside EditorShell: an edit writes
+// through the history path, Undo restores it, and a 409 shows the banner.
+import { act, createElement, useRef } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+// Backend/storage mocking only, standing in for a host's own server and
+// persistence — not part of the host's integration code under test.
+import { studioFileContentVersion } from "./utils/studioFileVersion";
+import { createMemoryEditHistoryStorage } from "./utils/editHistoryStorage";
+import {
+ flushStudioPendingEdits,
+ useTimelineEditing,
+ useProjectFileWriter,
+ usePersistentEditHistory,
+ useEditHistoryActions,
+ ExternalFileConflictBanner,
+ StudioFileConflictError,
+ type ExternalFileChangeCoordinatorHandle,
+ type TimelineElement,
+} from "./index";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const ORIGINAL_HTML = '<div id="clip" data-start="0" data-track-index="0"></div>';
+
+let root: Root | null = null;
+afterEach(() => {
+ act(() => root?.unmount());
+ document.body.innerHTML = "";
+ vi.unstubAllGlobals();
+});
+
+/** A minimal disk with etag-guarded PUT, faithful enough to exercise a real
+ * conflict: a stale If-Match gets a 409 with the current version + content. */
+function stubHostProjectDisk(
+ initial: Record<string, string>,
+ options?: { editElsewhereAfterFirstRead?: boolean },
+) {
+ const content = { ...initial };
+ const readsSeen = new Set<string>();
+ // The real backend's etag is a content hash (useProjectFileWriter derives
+ // If-Match the same way) — an arbitrary counter here would make every
+ // write from a host that hasn't just read the file look stale.
+ const versionOf = (path: string) => studioFileContentVersion(content[path]);
+
+ async function handlePut(path: string, init: RequestInit | undefined) {
+ const ifMatch = new Headers(init?.headers).get("If-Match");
+ const currentVersion = await versionOf(path);
+ if (ifMatch && ifMatch !== currentVersion) {
+ return new Response(JSON.stringify({ currentVersion, currentContent: content[path] }), {
+ status: 409,
+ });
+ }
+ content[path] = String(init?.body ?? "");
+ return new Response(JSON.stringify({ version: await versionOf(path) }), { status: 200 });
+ }
+
+ async function handleGet(path: string) {
+ const served = content[path];
+ // Simulates another writer landing between this read and the caller's
+ // own write: content moves on right after being served once, so the
+ // caller's hash of what it just read no longer matches disk.
+ if (options?.editElsewhereAfterFirstRead && !readsSeen.has(path)) {
+ readsSeen.add(path);
+ content[path] = `${served} <!--edited elsewhere-->`;
+ }
+ return new Response(
+ JSON.stringify({ content: served, version: await studioFileContentVersion(served) }),
+ { status: 200 },
+ );
+ }
+
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const match = String(input).match(/\/files\/([^?]+)/);
+ const path = match ? decodeURIComponent(match[1]) : "";
+ return (init?.method ?? "GET") === "PUT" ? handlePut(path, init) : handleGet(path);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return { content, fetchMock };
+}
+
+type TimelineEditingHandle = {
+ handleTimelineElementMove: (
+ element: TimelineElement,
+ updates: { start: number; track: number },
+ ) => Promise<void>;
+};
+
+function mountHost(
+ clip: TimelineElement,
+ iframe: HTMLIFrameElement,
+): {
+ timelineEditing: TimelineEditingHandle;
+ undo: () => Promise<void>;
+ bannerHost: HTMLDivElement;
+} {
+ let timelineEditing: TimelineEditingHandle | null = null;
+ let undo: (() => Promise<void>) | null = null;
+ let conflict: ExternalFileChangeCoordinatorHandle = {
+ blocked: null,
+ retry: async () => {},
+ useExternalFile: async () => {},
+ keepStudioFile: async () => {},
+ };
+ const bannerHost = document.createElement("div");
+ document.body.append(bannerHost);
+ const bannerRoot = createRoot(bannerHost);
+ // Created once: a fresh storage object on every render would change
+ // usePersistentEditHistory's effect deps each time and loop forever.
+ const storage = createMemoryEditHistoryStorage();
+
+ function Harness() {
+ const writer = useProjectFileWriter({ projectId: "p1" });
+ const editHistory = usePersistentEditHistory({ projectId: "p1", storage });
+ const historyActions = useEditHistoryActions({
+ editHistory,
+ readOptionalProjectFile: writer.readOptionalProjectFile,
+ readProjectFile: writer.readProjectFile,
+ writeProjectFile: writer.writeProjectFile,
+ showToast: () => {},
+ syncHistoryPreviewAfterApply: async () => {},
+ // The pattern a host's own dom-edit queue would also drain through —
+ // this is the one gate that closes the undo/delete race (#4194).
+ waitForPendingDomEditSaves: async () => {
+ const result = await flushStudioPendingEdits();
+ if (result.status !== "clean") throw result.error;
+ },
+ });
+ undo = historyActions.undo;
+ const commitRef = useRef(null);
+ timelineEditing = useTimelineEditing({
+ projectId: "p1",
+ activeCompPath: "index.html",
+ timelineElements: [clip],
+ showToast: () => {},
+ writeProjectFile: async (path, content, expectedContent) => {
+ try {
+ await writer.writeProjectFile(path, content, expectedContent);
+ } catch (error) {
+ if (error instanceof StudioFileConflictError) {
+ conflict = {
+ ...conflict,
+ blocked: { status: "conflict", generation: 0, error, payload: null },
+ };
+ bannerRoot.render(createElement(ExternalFileConflictBanner, { coordinator: conflict }));
+ }
+ throw error;
+ }
+ },
+ observeProjectFileVersion: writer.observeProjectFileVersion,
+ recordEdit: editHistory.recordEdit,
+ reloadPreview: () => {},
+ previewIframeRef: { current: iframe },
+ pendingTimelineEditPathRef: { current: new Set<string>() },
+ uploadProjectFiles: async () => [],
+ handleDomZIndexReorderCommitRef: commitRef,
+ });
+ return null;
+ }
+
+ root = createRoot(document.createElement("div"));
+ act(() => root!.render(createElement(Harness)));
+ if (!timelineEditing) throw new Error("Expected hook to mount");
+ if (!undo) throw new Error("Expected undo to be exposed");
+ return { timelineEditing, undo, bannerHost };
+}
+
+describe("public export surface: a host mounting hand editing outside EditorShell", () => {
+ it("writes a move through the history path and undo restores it", async () => {
+ const disk = stubHostProjectDisk({ "index.html": ORIGINAL_HTML });
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ iframe.contentDocument!.body.innerHTML = ORIGINAL_HTML;
+ const clip: TimelineElement = {
+ id: "clip",
+ domId: "clip",
+ tag: "div",
+ start: 0,
+ duration: 2,
+ track: 0,
+ };
+
+ const { timelineEditing, undo } = mountHost(clip, iframe);
+ await act(async () => {
+ await timelineEditing.handleTimelineElementMove(clip, { start: 5, track: 0 });
+ });
+ expect(disk.content["index.html"]).toContain('data-start="5"');
+
+ await act(async () => {
+ await undo();
+ });
+ expect(disk.content["index.html"]).toContain('data-start="0"');
+ });
+
+ it("surfaces the conflict banner on a 409", async () => {
+ stubHostProjectDisk({ "index.html": ORIGINAL_HTML }, { editElsewhereAfterFirstRead: true });
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ iframe.contentDocument!.body.innerHTML = ORIGINAL_HTML;
+ const clip: TimelineElement = {
+ id: "clip",
+ domId: "clip",
+ tag: "div",
+ start: 0,
+ duration: 2,
+ track: 0,
+ };
+
+ const { timelineEditing, bannerHost } = mountHost(clip, iframe);
+
+ await act(async () => {
+ await expect(
+ timelineEditing.handleTimelineElementMove(clip, { start: 5, track: 0 }),
+ ).rejects.toBeInstanceOf(StudioFileConflictError);
+ });
+
+ expect(bannerHost.textContent).toContain("changed outside Studio");
+ });
+});
diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.ts
index 9eb5473131..dc692dae2d 100644
--- a/packages/studio/src/index.ts
+++ b/packages/studio/src/index.ts
@@ -1,10 +1,12 @@
// UI primitives
export { Button, buttonBase, buttonSizes, buttonVariants } from "./components/ui/Button";
export type { ButtonSize, ButtonVariant, PreviewState } from "./components/ui/Button";
+export { HyperframesLogo } from "./components/StudioHeader";
export { IconButton } from "./components/ui/IconButton";
export { Tab, TabPanel, Tabs, TabsList } from "./components/ui/Tabs";
+export { HyperframesLoader } from "./components/ui/HyperframesLoader";
+export type { HyperframesLoaderProps } from "./components/ui/HyperframesLoader";
export { Tooltip } from "./components/ui/Tooltip";
-export { HyperframesLogo } from "./components/StudioHeader";
export { cn } from "./components/ui/cn";
export {
ContextMenu,
@@ -49,7 +51,7 @@ export {
liveTime,
formatTime,
} from "./player";
-export type { TimelineElement } from "./player";
+export type { TimelineElement, TimelineTimeRange } from "./player";
// Host overlays: draw over the preview in composition coordinates (see EditorShellProps.gestureOverlay)
export { usePreviewCompositionRect } from "./components/editor/usePreviewCompositionRect";
@@ -97,3 +99,39 @@ export type { PickedElement } from "./hooks/useElementPicker";
export { resolveSourceFile, applyPatch } from "./utils/sourcePatcher";
export type { PatchOperation } from "./utils/sourcePatcher";
export { parseStyleString, mergeStyleIntoTag, findElementBlock } from "./utils/htmlEditor";
+
+// Timeline editing: Studio's own hand-edit path, undo/redo, the
+// etag-guarded writer and the conflict banner, for a host mounting the
+// timeline outside EditorShell.
+export { usePersistentEditHistory } from "./hooks/usePersistentEditHistory";
+export type { UsePersistentEditHistoryOptions } from "./hooks/usePersistentEditHistory";
+export { useTimelineEditing } from "./hooks/useTimelineEditing";
+export type { UseTimelineEditingOptions } from "./hooks/useTimelineEditingTypes";
+// A host's own waitForPendingDomEditSaves must also call this, or undo/redo
+// can race a write still in flight (see useTrackPendingTimelineEdit.ts).
+export { flushStudioPendingEdits } from "./utils/studioPendingEdits";
+export type { StudioPendingEditsDrainResult } from "./utils/studioPendingEdits";
+export type {
+ CanEditTimelineElement,
+ TimelineEditPermission,
+} from "./hooks/timelineEditPermission";
+export { useEditHistoryActions } from "./hooks/useEditHistoryActions";
+export type {
+ EditHistoryHandle,
+ UseEditHistoryActionsOptions,
+} from "./hooks/useEditHistoryActions";
+export { useProjectFileWriter } from "./hooks/useProjectFileWriter";
+export type { UseProjectFileWriterOptions } from "./hooks/useProjectFileWriter";
+// A host's writeProjectFile throws this on a 409; catch it to know when
+// to show ExternalFileConflictBanner.
+export { StudioFileConflictError } from "./utils/studioSaveDiagnostics";
+export { ExternalFileConflictBanner } from "./components/ExternalFileConflictBanner";
+export type {
+ ExternalFileChangeCoordinatorHandle,
+ ExternalFileChangeBlockedState,
+} from "./hooks/useExternalFileChangeCoordinator";
+export { TimelinePane } from "./components/nle/TimelinePane";
+export type { TimelinePaneProps } from "./components/nle/TimelinePane";
+export { TimelineEditProvider } from "./contexts/TimelineEditContext";
+export type { TimelineEditCallbacks } from "./player/components/timelineCallbacks";
+export type { BlockedTimelineEditIntent } from "./player/components/timelineEditing";
diff --git a/packages/studio/src/player/components/Timeline.tsx b/packages/studio/src/player/components/Timeline.tsx
index c50e8d362a..94199fe513 100644
--- a/packages/studio/src/player/components/Timeline.tsx
+++ b/packages/studio/src/player/components/Timeline.tsx
@@ -4,6 +4,7 @@ import { usePlayerStore, type TimelineElement } from "../store/playerStore";
import { useTimelineRowElements } from "../hooks/useTimelineRowElements";
import { defaultTimelineTheme } from "./timelineTheme";
import { useTimelineRangeSelection } from "./useTimelineRangeSelection";
+import { usePublishRangeSelection } from "./usePublishRangeSelection";
import { useTimelinePlayhead } from "./useTimelinePlayhead";
import { useTimelineZoom } from "./useTimelineZoom";
import { useTimelineAssetDrop } from "./timelineDragDrop";
@@ -80,6 +81,7 @@ export const Timeline = memo(function Timeline({
onBlockedEditAttempt: onBlockedEditAttemptOverride,
onSplitElement: onSplitElementOverride,
onSelectElement,
+ onRangeSelect,
onCopyClip,
onPasteClip,
onDuplicateClip,
@@ -167,10 +169,10 @@ export const Timeline = memo(function Timeline({
selectedElementIds,
);
const expandedElementsRef = useRef(expandedElements);
- expandedElementsRef.current = expandedElements;
+ expandedElementsRef.current = expandedElements; // oxlint-disable-line react/refs -- event handlers read the latest elements
const ppsRef = useRef(100);
const durationRef = useRef(effectiveDuration);
- durationRef.current = effectiveDuration;
+ durationRef.current = effectiveDuration; // oxlint-disable-line react/refs -- event handlers read the latest duration
const fitPpsRef = useRef(100);
const {
pinZoomBeforeEdit,
@@ -214,7 +216,6 @@ export const Timeline = memo(function Timeline({
onMoveElements: pinnedOnMoveElements,
});
const onContextMenuClip = useClipContextMenu(onSelectElement, dismissGapMenu, setClipContextMenu);
-
const {
draggedClip,
setDraggedClip,
@@ -241,7 +242,6 @@ export const Timeline = memo(function Timeline({
refreshAfterLaneMove,
sessionEpoch,
});
-
const assetDrop = useTimelineAssetDrop({
scrollRef,
ppsRef,
@@ -320,7 +320,6 @@ export const Timeline = memo(function Timeline({
setKfContextMenu,
toggleSelectedKeyframe,
});
-
const { clipIndex, renderTimeRange, visibleTimeRange, pinnedClipIdentities } =
useTimelineClipRenderWindow({
tracks,
@@ -415,7 +414,8 @@ export const Timeline = memo(function Timeline({
contentOrigin,
sessionEpoch,
});
- setRangeSelectionRef.current = setRangeSelection; // stable ref consumed by useTimelineClipDrag
+ usePublishRangeSelection(rangeSelection, onRangeSelect);
+ setRangeSelectionRef.current = setRangeSelection; // oxlint-disable-line react/refs -- stable ref consumed by useTimelineClipDrag
useTimelineSelectionLifecycle(expandedElements, selectedElementId, setShowPopover, () =>
setRangeSelection(null),
diff --git a/packages/studio/src/player/components/TimelineTypes.ts b/packages/studio/src/player/components/TimelineTypes.ts
index da7a727046..4d6aa3f83c 100644
--- a/packages/studio/src/player/components/TimelineTypes.ts
+++ b/packages/studio/src/player/components/TimelineTypes.ts
@@ -1,5 +1,6 @@
import type { ReactNode } from "react";
import type { TimelineElement } from "../store/playerStore";
+import type { TimelineTimeRange } from "../store/rangeSelectionSlice";
import type { TimelineDropCallbacks } from "./timelineCallbacks";
import type { TimelineTheme } from "./timelineTheme";
import type { TimelineEditOverrides } from "./useResolvedTimelineEditCallbacks";
@@ -23,6 +24,8 @@ export interface TimelineProps extends TimelineDropCallbacks, TimelineEditOverri
renderClipOverlay?: (element: TimelineElement) => ReactNode;
onDeleteElement?: (element: TimelineElement) => Promise<void> | void;
onSelectElement?: (element: TimelineElement | null) => void;
+ /** Notification only; null when cleared. The value lives in usePlayerStore.rangeSelection. */
+ onRangeSelect?: (range: TimelineTimeRange | null) => void;
onCopyClip?: () => boolean;
onPasteClip?: () => Promise<void>;
onDuplicateClip?: () => Promise<boolean>;
diff --git a/packages/studio/src/player/components/usePublishRangeSelection.test.tsx b/packages/studio/src/player/components/usePublishRangeSelection.test.tsx
new file mode 100644
index 0000000000..22e825a3e1
--- /dev/null
+++ b/packages/studio/src/player/components/usePublishRangeSelection.test.tsx
@@ -0,0 +1,60 @@
+// @vitest-environment happy-dom
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { usePlayerStore } from "../store/playerStore";
+import type { TimelineTimeRange } from "../store/rangeSelectionSlice";
+import type { TimelineRangeSelection } from "./timelineEditing";
+import { usePublishRangeSelection } from "./usePublishRangeSelection";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+function mount(onRangeSelect: (range: TimelineTimeRange | null) => void) {
+ const host = document.createElement("div");
+ const root = createRoot(host);
+ const Harness = ({ selection }: { selection: TimelineRangeSelection | null }) => {
+ usePublishRangeSelection(selection, onRangeSelect);
+ return null;
+ };
+ const render = (selection: TimelineRangeSelection | null) =>
+ act(() => root.render(<Harness selection={selection} />));
+ return { render, unmount: () => act(() => root.unmount()) };
+}
+
+const selection = (start: number, end: number): TimelineRangeSelection => ({
+ start,
+ end,
+ anchorX: 0,
+ anchorY: 0,
+});
+
+describe("usePublishRangeSelection", () => {
+ afterEach(() => usePlayerStore.setState({ rangeSelection: null }));
+
+ it("publishes an ordered range to the store and the host, and clears with null", () => {
+ const onRangeSelect = vi.fn();
+ const view = mount(onRangeSelect);
+
+ view.render(selection(3, 1));
+ expect(usePlayerStore.getState().rangeSelection).toEqual({ t0: 1, t1: 3 });
+ expect(onRangeSelect).toHaveBeenLastCalledWith({ t0: 1, t1: 3 });
+
+ view.render(null);
+ expect(usePlayerStore.getState().rangeSelection).toBeNull();
+ expect(onRangeSelect).toHaveBeenLastCalledWith(null);
+ view.unmount();
+ });
+
+ it("does not re-notify for an unchanged range and preserves a newer store value on unmount", () => {
+ const onRangeSelect = vi.fn();
+ const view = mount(onRangeSelect);
+
+ view.render(selection(1, 3));
+ view.render(selection(3, 1));
+ expect(onRangeSelect).toHaveBeenCalledTimes(1);
+
+ usePlayerStore.setState({ rangeSelection: { t0: 9, t1: 10 } });
+ view.unmount();
+ expect(usePlayerStore.getState().rangeSelection).toEqual({ t0: 9, t1: 10 });
+ });
+});
diff --git a/packages/studio/src/player/components/usePublishRangeSelection.ts b/packages/studio/src/player/components/usePublishRangeSelection.ts
new file mode 100644
index 0000000000..5d13841379
--- /dev/null
+++ b/packages/studio/src/player/components/usePublishRangeSelection.ts
@@ -0,0 +1,42 @@
+import { useEffect, useRef } from "react";
+import { usePlayerStore } from "../store/playerStore";
+import type { TimelineTimeRange } from "../store/rangeSelectionSlice";
+import type { TimelineRangeSelection } from "./timelineEditing";
+
+/** Mirrors the gesture's range into the store and notifies the host. */
+export function usePublishRangeSelection(
+ rangeSelection: TimelineRangeSelection | null,
+ onRangeSelect?: (range: TimelineTimeRange | null) => void,
+) {
+ const onRangeSelectRef = useRef(onRangeSelect);
+ const publishedRangeRef = useRef<TimelineTimeRange | null>(null);
+
+ useEffect(() => {
+ onRangeSelectRef.current = onRangeSelect;
+ }, [onRangeSelect]);
+
+ useEffect(() => {
+ const range = rangeSelection
+ ? {
+ t0: Math.min(rangeSelection.start, rangeSelection.end),
+ t1: Math.max(rangeSelection.start, rangeSelection.end),
+ }
+ : null;
+ const store = usePlayerStore.getState();
+ const current = store.rangeSelection;
+ if (current?.t0 === range?.t0 && current?.t1 === range?.t1) return;
+ publishedRangeRef.current = range;
+ usePlayerStore.setState({ rangeSelection: range });
+ onRangeSelectRef.current?.(range);
+ }, [rangeSelection]);
+
+ useEffect(
+ () => () => {
+ const current = usePlayerStore.getState().rangeSelection;
+ const published = publishedRangeRef.current;
+ if (current?.t0 !== published?.t0 || current?.t1 !== published?.t1) return;
+ usePlayerStore.setState({ rangeSelection: null });
+ },
+ [],
+ );
+}
diff --git a/packages/studio/src/player/index.ts b/packages/studio/src/player/index.ts
index 89417ac576..b8852fe5ba 100644
--- a/packages/studio/src/player/index.ts
+++ b/packages/studio/src/player/index.ts
@@ -12,6 +12,7 @@ export { resolveIframe } from "./lib/timelineDOM";
// Store
export { usePlayerStore, liveTime } from "./store/playerStore";
export type { SelectElementOptions, TimelineElement, ZoomMode } from "./store/playerStore";
+export type { TimelineTimeRange } from "./store/rangeSelectionSlice";
// Utils
export { formatTime } from "./lib/time";
diff --git a/packages/studio/src/player/store/playerStore.ts b/packages/studio/src/player/store/playerStore.ts
index 636c182b40..d11478e335 100644
--- a/packages/studio/src/player/store/playerStore.ts
+++ b/packages/studio/src/player/store/playerStore.ts
@@ -2,7 +2,6 @@ import { create } from "zustand";
import { attachPlayerStoreDevHandle } from "./playerStoreDevHandle";
import { nextSelectionSet, revealTargetsSelection } from "./playerStoreSelection";
import type { MusicBeatAnalysis } from "@hyperframes/core/beats";
-import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { BeatEditState } from "../../utils/beatEditing";
import type { ClipManifestClip } from "../lib/playbackTypes";
import {
@@ -11,7 +10,7 @@ import {
type TimelineTimeDisplayMode,
} from "../../utils/studioUiPreferences";
import { clampTimelineZoomPercent, computePinnedZoomPercent } from "../components/timelineZoom";
-import { createKeyframeSlice, type KeyframeCacheEntry, type KeyframeSlice } from "./keyframeSlice";
+import { createKeyframeSlice, type KeyframeSlice } from "./keyframeSlice";
import {
createAutomationSelectionSlice,
type AutomationSelectionSlice,
@@ -19,10 +18,12 @@ import {
import { createEditingModeSlice, type EditingModeSlice } from "./editingModeSlice";
import { createTimelineFocusRequest, type TimelineFocusRequest } from "./timelineFocusState";
import { createThumbnailSlice, type ThumbnailSlice } from "./thumbnailSlice";
-import { createPlaybackReadinessSlice, resetPlaybackReadinessState } from "./readinessSlice";
-
+import { createPlaybackReadinessSlice } from "./readinessSlice";
+import { createRangeSelectionSlice, type RangeSelectionSlice } from "./rangeSelectionSlice";
+import { createTimelineResetState } from "./timelineResetState";
export type { KeyframeCacheEntry } from "./keyframeSlice";
export { liveTime } from "./liveTime";
+export { createTimelineResetState };
import type {
TimelineElement,
@@ -59,7 +60,8 @@ type PlayerStoreSlices = KeyframeSlice &
AutomationSelectionSlice &
ThumbnailSlice &
EditingModeSlice &
- ReturnType<typeof createPlaybackReadinessSlice>;
+ ReturnType<typeof createPlaybackReadinessSlice> &
+ RangeSelectionSlice;
interface PlayerState extends PlayerStoreSlices {
isPlaying: boolean;
currentTime: number;
@@ -250,52 +252,6 @@ interface BeatHistoryEntry {
label: string;
}
-export function createTimelineResetState() {
- return {
- isPlaying: false,
- currentTime: 0,
- duration: 0,
- ...resetPlaybackReadinessState(),
- beatDragging: false,
- elements: [],
- selectedElementId: null,
- zEditVersion: 0,
- inPoint: null,
- outPoint: null,
- activeTool: "select" as const,
- activeKeyframePct: null,
- motionPathArmed: false,
- motionPathCreateAvailable: false,
- selectedKeyframes: new Set<string>(),
- // Ephemeral like every other selection here. A range surviving a project
- // switch can match a same-keyed clip in the new project and redirect a
- // paste through `sel.elementKey === paste.elementKey` to a stale t0.
- automationSelection: null,
- expandedClipIds: new Set<string>(),
- // Per-composition: ids from comp A match nothing in B, silencing all of it.
- collapsedGroupIds: new Set<string>(),
- expandedLaneOwnerIds: new Set<string>(),
- focusedEaseSegment: null,
- revealedAudioFxTarget: null,
- selectedElementIds: new Set<string>(),
- requestedSeekTime: null,
- lintFindingsByElement: new Map<string, { count: number; messages: string[] }>(),
- timelineFocus: null,
- keyframeCache: new Map<string, KeyframeCacheEntry>(),
- gsapAnimations: new Map<string, GsapAnimation[]>(),
- beatAnalysis: null,
- beatEdits: null,
- beatUndo: [],
- beatRedo: [],
- beatPersist: null,
- clipManifest: null,
- clipParentMap: new Map<string, string>(),
- topLevelIds: null,
- domClipChildren: [],
- subCompositionHostState: new Map<string, SubCompositionHostState>(),
- };
-}
-
export const usePlayerStore = create<PlayerState>((set, get) => ({
isPlaying: false,
currentTime: 0,
@@ -328,6 +284,7 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
...createAutomationSelectionSlice(set),
...createEditingModeSlice(set),
+ ...createRangeSelectionSlice(),
...createPlaybackReadinessSlice(set),
activeKeyframePct: null,
diff --git a/packages/studio/src/player/store/rangeSelectionSlice.ts b/packages/studio/src/player/store/rangeSelectionSlice.ts
new file mode 100644
index 0000000000..e7aef3ab41
--- /dev/null
+++ b/packages/studio/src/player/store/rangeSelectionSlice.ts
@@ -0,0 +1,13 @@
+export interface TimelineTimeRange {
+ t0: number;
+ t1: number;
+}
+
+export interface RangeSelectionSlice {
+ /** Shift-drag ruler range in seconds, normalized so t0 <= t1. */
+ rangeSelection: TimelineTimeRange | null;
+}
+
+export function createRangeSelectionSlice(): RangeSelectionSlice {
+ return { rangeSelection: null };
+}
diff --git a/packages/studio/src/player/store/timelineResetState.ts b/packages/studio/src/player/store/timelineResetState.ts
new file mode 100644
index 0000000000..1c1099bc93
--- /dev/null
+++ b/packages/studio/src/player/store/timelineResetState.ts
@@ -0,0 +1,51 @@
+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
+import type { KeyframeCacheEntry } from "./keyframeSlice";
+import { resetPlaybackReadinessState } from "./readinessSlice";
+import type { SubCompositionHostState } from "./timelineElement";
+
+export function createTimelineResetState() {
+ return {
+ isPlaying: false,
+ currentTime: 0,
+ duration: 0,
+ ...resetPlaybackReadinessState(),
+ beatDragging: false,
+ elements: [],
+ selectedElementId: null,
+ zEditVersion: 0,
+ inPoint: null,
+ outPoint: null,
+ rangeSelection: null,
+ activeTool: "select" as const,
+ activeKeyframePct: null,
+ motionPathArmed: false,
+ motionPathCreateAvailable: false,
+ selectedKeyframes: new Set<string>(),
+ // Ephemeral like every other selection here. A range surviving a project
+ // switch can match a same-keyed clip in the new project and redirect a
+ // paste through `sel.elementKey === paste.elementKey` to a stale t0.
+ automationSelection: null,
+ expandedClipIds: new Set<string>(),
+ // Per-composition: ids from comp A match nothing in B, silencing all of it.
+ collapsedGroupIds: new Set<string>(),
+ expandedLaneOwnerIds: new Set<string>(),
+ focusedEaseSegment: null,
+ revealedAudioFxTarget: null,
+ selectedElementIds: new Set<string>(),
+ requestedSeekTime: null,
+ lintFindingsByElement: new Map<string, { count: number; messages: string[] }>(),
+ timelineFocus: null,
+ keyframeCache: new Map<string, KeyframeCacheEntry>(),
+ gsapAnimations: new Map<string, GsapAnimation[]>(),
+ beatAnalysis: null,
+ beatEdits: null,
+ beatUndo: [],
+ beatRedo: [],
+ beatPersist: null,
+ clipManifest: null,
+ clipParentMap: new Map<string, string>(),
+ topLevelIds: null,
+ domClipChildren: [],
+ subCompositionHostState: new Map<string, SubCompositionHostState>(),
+ };
+}