Skip to content

Write HTML. Render video. Built for agents.

fix(studio): restore golden-branch timeline behaviors dropped by the stack rebuild

ukimsanov54f41b41b6ff
diff --git a/packages/studio/src/components/nle/AssetPreviewOverlay.tsx b/packages/studio/src/components/nle/AssetPreviewOverlay.tsx
index 6245c4985e..63721f7c55 100644
--- a/packages/studio/src/components/nle/AssetPreviewOverlay.tsx
+++ b/packages/studio/src/components/nle/AssetPreviewOverlay.tsx
@@ -2,15 +2,20 @@
* CapCut-style asset preview overlay rendered inside PreviewPane.
*
* Shown when the user clicks an asset card that has NOT yet been added to the
- * timeline. Displays the media (image / video / audio) without modifying the
- * composition — no undo entry, no file mutation.
+ * timeline. Displays the media (image / video / audio) as a compact floating
+ * card over the canvas — the canvas stays visible behind a barely-tinted
+ * click-catcher — without modifying the composition (no undo entry, no file
+ * mutation).
*
- * Dismiss: X button, Escape key, or click on the scrim.
+ * Dismiss: X button, Escape key, click outside the card, or any playhead
+ * activity (starting playback / seeking) — the canvas refocuses.
* Switching to another not-added asset replaces the current preview.
*/
import { useEffect, useCallback } from "react";
import { VIDEO_EXT, IMAGE_EXT } from "../../utils/mediaTypes";
import { useAssetPreviewStore } from "../../utils/assetPreviewStore";
+import { usePlayerStore } from "../../player/store/playerStore";
+import { shouldDismissAssetPreview } from "../../utils/assetPreviewDismiss";
import { resolveMediaPreviewUrl } from "../../player/components/thumbnailUtils";
function basename(path: string): string {
@@ -37,11 +42,7 @@ function AssetPreviewMedia({
}) {
if (kind === "image") {
return (
- <img
- src={serveUrl}
- alt={name}
- className="max-w-full max-h-[70vh] rounded-md object-contain shadow-2xl"
- />
+ <img src={serveUrl} alt={name} className="max-w-full max-h-[40vh] rounded object-contain" />
);
}
if (kind === "video") {
@@ -52,12 +53,12 @@ function AssetPreviewMedia({
autoPlay
muted
playsInline
- className="max-w-full max-h-[70vh] rounded-md shadow-2xl"
+ className="max-w-full max-h-[40vh] rounded"
/>
);
}
return (
- <div className="flex flex-col items-center gap-4 px-6 py-8 rounded-xl bg-neutral-900 border border-neutral-800">
+ <div className="flex flex-col items-center gap-3 px-6 py-4">
<svg
width="40"
height="40"
@@ -94,6 +95,18 @@ export function AssetPreviewOverlay() {
return () => window.removeEventListener("keydown", handleKeyDown);
}, [previewAsset, handleKeyDown]);
+ // The canvas refocuses on any playhead activity: starting playback or a
+ // seek/scrub away from where the playhead sat when the preview opened
+ // dismisses it. openedTime is captured per preview open (previewAsset dep),
+ // so a stale render can never dismiss against the wrong reference time.
+ useEffect(() => {
+ if (!previewAsset) return;
+ const openedTime = usePlayerStore.getState().currentTime;
+ return usePlayerStore.subscribe((state) => {
+ if (shouldDismissAssetPreview(openedTime, state)) clearPreviewAsset();
+ });
+ }, [previewAsset, clearPreviewAsset]);
+
if (!previewAsset || !previewProjectId) return null;
const serveUrl = resolveMediaPreviewUrl(previewAsset, previewProjectId);
@@ -101,40 +114,39 @@ export function AssetPreviewOverlay() {
return (
<div
- className="absolute inset-0 z-50 flex flex-col items-center justify-center bg-black/80"
+ className="absolute inset-0 z-50 flex flex-col items-center justify-center bg-black/20"
onClick={clearPreviewAsset}
role="dialog"
aria-label={`Preview: ${name}`}
- aria-modal="true"
>
- {/* Close button */}
- <button
- className="absolute top-3 right-3 w-7 h-7 rounded-full bg-neutral-800 hover:bg-neutral-700 text-neutral-300 hover:text-white flex items-center justify-center transition-colors z-10"
- onClick={(e) => {
- e.stopPropagation();
- clearPreviewAsset();
- }}
- aria-label="Close preview"
- >
- <svg
- width="12"
- height="12"
- viewBox="0 0 24 24"
- stroke="currentColor"
- strokeWidth="2.5"
- fill="none"
- strokeLinecap="round"
- >
- <line x1="18" y1="6" x2="6" y2="18" />
- <line x1="6" y1="6" x2="18" y2="18" />
- </svg>
- </button>
-
- {/* Media */}
+ {/* Floating preview card — compact, canvas stays visible around it */}
<div
- className="flex flex-col items-center gap-3 max-w-[90%] max-h-[85%]"
+ className="relative flex flex-col items-center gap-2 max-w-[58%] rounded-lg border border-neutral-800 bg-neutral-950/95 p-2 pt-8 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
+ {/* Close button */}
+ <button
+ className="absolute top-2 right-2 w-6 h-6 rounded-full bg-neutral-800 hover:bg-neutral-700 text-neutral-300 hover:text-white flex items-center justify-center transition-colors z-10"
+ onClick={(e) => {
+ e.stopPropagation();
+ clearPreviewAsset();
+ }}
+ aria-label="Close preview"
+ >
+ <svg
+ width="12"
+ height="12"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ fill="none"
+ strokeLinecap="round"
+ >
+ <line x1="18" y1="6" x2="6" y2="18" />
+ <line x1="6" y1="6" x2="18" y2="18" />
+ </svg>
+ </button>
+
<AssetPreviewMedia kind={resolveAssetKind(previewAsset)} serveUrl={serveUrl} name={name} />
{/* Filename label */}
diff --git a/packages/studio/src/components/sidebar/AssetCard.tsx b/packages/studio/src/components/sidebar/AssetCard.tsx
index a083d34d25..f67e43a87e 100644
--- a/packages/studio/src/components/sidebar/AssetCard.tsx
+++ b/packages/studio/src/components/sidebar/AssetCard.tsx
@@ -133,6 +133,7 @@ export function AssetCard({
const pointerDownRef = useRef<{ x: number; y: number } | null>(null);
const setSelectedElementId = usePlayerStore((s) => s.setSelectedElementId);
+ const requestClipReveal = usePlayerStore((s) => s.requestClipReveal);
const elements = usePlayerStore((s) => s.elements);
const setPreviewAsset = useAssetPreviewStore((s) => s.setPreviewAsset);
@@ -150,14 +151,17 @@ export function AssetCard({
if (used) {
const clip = findClipForAsset(elements, asset);
if (clip) {
- setSelectedElementId(clip.key ?? clip.id);
+ const clipKey = clip.key ?? clip.id;
+ setSelectedElementId(clipKey);
+ // Scroll the timeline so the selected clip is actually visible.
+ requestClipReveal(clipKey);
return;
}
}
// Not added (or no matching clip found) → preview overlay
setPreviewAsset(asset, projectId);
},
- [used, elements, asset, projectId, setSelectedElementId, setPreviewAsset],
+ [used, elements, asset, projectId, setSelectedElementId, requestClipReveal, setPreviewAsset],
);
return (
diff --git a/packages/studio/src/components/sidebar/AudioRow.tsx b/packages/studio/src/components/sidebar/AudioRow.tsx
index 445ea6732d..2dc26f8c12 100644
--- a/packages/studio/src/components/sidebar/AudioRow.tsx
+++ b/packages/studio/src/components/sidebar/AudioRow.tsx
@@ -43,6 +43,7 @@ export function AudioRow({
// CapCut-style click behavior: drag-threshold gate.
const pointerDownRef = useRef<{ x: number; y: number } | null>(null);
const setSelectedElementId = usePlayerStore((s) => s.setSelectedElementId);
+ const requestClipReveal = usePlayerStore((s) => s.requestClipReveal);
const elements = usePlayerStore((s) => s.elements);
const setPreviewAsset = useAssetPreviewStore((s) => s.setPreviewAsset);
@@ -59,14 +60,17 @@ export function AudioRow({
if (used) {
const clip = findClipForAsset(elements, asset);
if (clip) {
- setSelectedElementId(clip.key ?? clip.id);
+ const clipKey = clip.key ?? clip.id;
+ setSelectedElementId(clipKey);
+ // Scroll the timeline so the selected clip is actually visible.
+ requestClipReveal(clipKey);
return;
}
}
// Not added → preview overlay (audio player)
setPreviewAsset(asset, projectId);
},
- [used, elements, asset, projectId, setSelectedElementId, setPreviewAsset],
+ [used, elements, asset, projectId, setSelectedElementId, requestClipReveal, setPreviewAsset],
);
useEffect(() => {
diff --git a/packages/studio/src/hooks/timelineEditingHelpers.test.ts b/packages/studio/src/hooks/timelineEditingHelpers.test.ts
index 238f30f2cb..d76f4898e6 100644
--- a/packages/studio/src/hooks/timelineEditingHelpers.test.ts
+++ b/packages/studio/src/hooks/timelineEditingHelpers.test.ts
@@ -2,8 +2,11 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
applyTimelineStackingReorder,
+ buildTimelineMoveTimingPatch,
deleteSelectedKeyframes,
extendRootDurationIfNeeded,
+ persistTimelineBatchEdit,
+ type PersistTimelineBatchChange,
} from "./timelineEditingHelpers";
import type { TimelineElement } from "../player/store/playerStore";
import { usePlayerStore } from "../player/store/playerStore";
@@ -108,6 +111,91 @@ describe("extendRootDurationIfNeeded", () => {
});
});
+describe("persistTimelineBatchEdit", () => {
+ const SOURCE = `<div id="root"><video id="a" class="clip" data-start="1" data-track-index="0"></video><video id="b" class="clip" data-start="2" data-track-index="1"></video></div>`;
+
+ function batchInput(changes: PersistTimelineBatchChange[], writes: Array<[string, string]>) {
+ return {
+ projectId: "p1",
+ activeCompPath: "index.html",
+ label: "Move timeline clips",
+ changes,
+ writeProjectFile: async (path: string, content: string) => {
+ writes.push([path, content]);
+ },
+ recordEdit: async () => {},
+ domEditSaveTimestampRef: { current: 0 },
+ pendingTimelineEditPathRef: { current: new Set<string>() },
+ };
+ }
+
+ function stubReadFileContent(content: string) {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => ({
+ ok: true,
+ json: async () => ({ content }),
+ })),
+ );
+ }
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("skips no-op members instead of aborting the batch (track-insert renumber)", async () => {
+ // A track-insert renumber can include a member whose attributes already
+ // hold the target values — its patch is string-identical. The batch must
+ // skip it and still persist the members that DID change.
+ stubReadFileContent(SOURCE);
+ const writes: Array<[string, string]> = [];
+
+ await persistTimelineBatchEdit(
+ batchInput(
+ [
+ {
+ // no-op: data-start already "1", track already 0
+ element: el({ id: "a", tag: "video", domId: "a", start: 1, track: 0 }),
+ buildPatches: (original, target) =>
+ buildTimelineMoveTimingPatch(original, target, 1, 5, 0),
+ },
+ {
+ // real change: track 1 -> 2
+ element: el({ id: "b", tag: "video", domId: "b", start: 2, track: 1 }),
+ buildPatches: (original, target) =>
+ buildTimelineMoveTimingPatch(original, target, 2, 5, 2),
+ },
+ ],
+ writes,
+ ),
+ );
+
+ expect(writes).toHaveLength(1);
+ expect(writes[0]![0]).toBe("index.html");
+ expect(writes[0]![1]).toContain('id="b" class="clip" data-start="2" data-track-index="2"');
+ });
+
+ it("saves nothing when every member is a no-op", async () => {
+ stubReadFileContent(SOURCE);
+ const writes: Array<[string, string]> = [];
+
+ await persistTimelineBatchEdit(
+ batchInput(
+ [
+ {
+ element: el({ id: "a", tag: "video", domId: "a", start: 1, track: 0 }),
+ buildPatches: (original, target) =>
+ buildTimelineMoveTimingPatch(original, target, 1, 5, 0),
+ },
+ ],
+ writes,
+ ),
+ );
+
+ expect(writes).toHaveLength(0);
+ });
+});
+
describe("deleteSelectedKeyframes", () => {
it("coalesces all removals and reloads only after the last one", () => {
usePlayerStore.setState({
diff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.ts
index 7609d8a9f5..a99b33cbad 100644
--- a/packages/studio/src/hooks/timelineEditingHelpers.ts
+++ b/packages/studio/src/hooks/timelineEditingHelpers.ts
@@ -5,13 +5,16 @@ import {
type TimelineStackingReorderIntent,
} from "../player/components/timelineEditing";
import { getElementZIndex } from "../player/lib/layerOrdering";
-import { getTimelineElementIdentity } from "../player/lib/timelineElementHelpers";
+import {
+ furthestClipEndFromSource,
+ getTimelineElementIdentity,
+} from "../player/lib/timelineElementHelpers";
import { saveProjectFilesWithHistory, type RecordEditInput } from "../utils/studioFileHistory";
import type { TimelineZIndexReorderCommit } from "./useTimelineEditingTypes";
-import { extendRootDurationInSource } from "../utils/rootDuration";
-import { postRuntimeControlMessage } from "../player/lib/runtimeProtocol";
-
+import { setCompositionDurationToContent } from "../utils/timelineAssetDrop";
+import { readFileContent } from "./timelineTimingSync";
export { deleteSelectedKeyframes } from "./deleteSelectedKeyframes";
+export { readFileContent };
function isHTMLElement(element: Element | null): element is HTMLElement {
if (!element) return false;
// Use the element's OWN realm's HTMLElement: timeline clips live in the preview
@@ -149,16 +152,6 @@ export function patchIframeDomTiming(
// Cross-origin or mid-navigation — file save is enqueued; iframe patch is best-effort.
}
}
-function postRootDurationToPreview(
- iframe: HTMLIFrameElement | null,
- durationSeconds: number,
-): void {
- const duration = Number(durationSeconds);
- if (!Number.isFinite(duration) || duration <= 0) return;
- postRuntimeControlMessage(iframe?.contentWindow, "set-root-duration", {
- durationSeconds: duration,
- });
-}
// fallow-ignore-next-line complexity
function resolveResizePlaybackStart(
original: string,
@@ -211,7 +204,12 @@ export function buildTimelineMoveTimingPatch(
value: formatTimelineAttributeNumber(track),
});
}
- return extendRootDurationInSource(patched, start + duration);
+ // Content-driven duration: sync data-duration to the furthest clip end read
+ // from the PATCHED SOURCE (raw data-duration), so it grows if a clip moved
+ // past the end and shrinks if the furthest clip moved left. Measured from the
+ // source, NOT the store — store durations are runtime-truncated to the current
+ // comp length, which would ratchet the duration down every move.
+ return setCompositionDurationToContent(patched, furthestClipEndFromSource(patched));
}
export function buildTimelineResizeTimingPatch(
@@ -238,7 +236,10 @@ export function buildTimelineResizeTimingPatch(
value: formatTimelineAttributeNumber(pbs.value),
});
}
- return extendRootDurationInSource(patched, updates.start + updates.duration);
+ // Content-driven duration from the PATCHED SOURCE (raw data-duration) —
+ // grows/shrinks to the furthest clip end. Not from the store, whose
+ // durations are runtime-truncated.
+ return setCompositionDurationToContent(patched, furthestClipEndFromSource(patched));
}
export interface PersistTimelineEditInput {
@@ -319,12 +320,16 @@ export async function persistTimelineBatchEdit(
const current = patchedByPath.get(targetPath) ?? original;
const patched = change.buildPatches(current, patchTarget);
- if (patched === current) {
- throw new Error(`Unable to patch timeline element ${change.element.id} in ${targetPath}`);
- }
+ // A member whose attributes already hold the target values patches to the
+ // identical string — e.g. a track-insert renumber where one clip's lane is
+ // already correct. That is a legitimate no-op, not a targeting failure:
+ // skip it instead of aborting (and rolling back) the whole batch.
+ if (patched === current) continue;
patchedByPath.set(targetPath, patched);
}
+ if (patchedByPath.size === 0) return;
+
const files = Object.fromEntries(patchedByPath);
for (const targetPath of Object.keys(files)) {
input.pendingTimelineEditPathRef.current.add(targetPath);
@@ -343,227 +348,6 @@ export async function persistTimelineBatchEdit(
input.domEditSaveTimestampRef.current = Date.now();
}
-export async function readFileContent(projectId: string, targetPath: string): Promise<string> {
- if (targetPath.includes("\0") || targetPath.includes("..")) {
- throw new Error(`Unsafe path: ${targetPath}`);
- }
- const response = await fetch(
- `/api/projects/${projectId}/files/${encodeURIComponent(targetPath)}`,
- );
- if (!response.ok) {
- throw new Error(`Failed to read ${targetPath}`);
- }
- const data = (await response.json()) as { content?: string };
- if (typeof data.content !== "string") {
- throw new Error(`Missing file contents for ${targetPath}`);
- }
- return data.content;
-}
-
-export type GsapMutationStatus = { mutated: boolean };
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null;
-}
-
-function readMutationStatus(value: unknown): GsapMutationStatus {
- if (!isRecord(value)) return { mutated: false };
- return { mutated: value.mutated === true || value.changed === true };
-}
-
-function readMutationError(value: unknown, fallback: string): string {
- if (isRecord(value) && typeof value.error === "string") return value.error;
- return fallback;
-}
-
-export async function finishTimelineTimingFallback(input: {
- iframe: HTMLIFrameElement | null;
- needsExtension: boolean;
- rootDurationSeconds: number;
- reloadPreview: () => void;
- gsapMutation?: () => Promise<GsapMutationStatus>;
- onGsapError: (error: unknown) => void;
-}): Promise<void> {
- let gsapMutated = false;
- if (input.gsapMutation) {
- try {
- gsapMutated = (await input.gsapMutation()).mutated;
- } catch (error) {
- input.onGsapError(error);
- return;
- }
- }
- if (input.needsExtension) {
- postRootDurationToPreview(input.iframe, input.rootDurationSeconds);
- if (gsapMutated) input.reloadPreview();
- return;
- }
- input.reloadPreview();
-}
-
-// Coalesce window for folding a GSAP mutation into the preceding timing edit; only has to
-// outlast one GSAP server round-trip, never a real second edit.
-const GSAP_HISTORY_COALESCE_MS = 10_000;
-
-/**
- * A server GSAP rewrite mutates the same file the timing patch just wrote, but AFTER the
- * timing edit was recorded, leaving the recorded `after` stale so an undo hits a hash
- * conflict. This snapshots every touched file, runs the mutation, then records a follow-up
- * edit under the same coalesceKey with a window wide enough to survive the GSAP round-trip,
- * folding both writes into one undo step. Returns the mutation status for caller reloads.
- */
-export async function foldGsapMutationIntoHistory(input: {
- projectId: string;
- paths: string[];
- label: string;
- coalesceKey?: string;
- recordEdit: (edit: RecordEditInput) => Promise<void>;
- gsapMutation: () => Promise<GsapMutationStatus>;
-}): Promise<GsapMutationStatus> {
- const uniquePaths = [...new Set(input.paths)];
- const before = new Map<string, string>();
- for (const path of uniquePaths) {
- before.set(path, await readFileContent(input.projectId, path));
- }
- const status = await input.gsapMutation();
- if (status.mutated) {
- const files: Record<string, { before: string; after: string }> = {};
- for (const path of uniquePaths) {
- const priorContent = before.get(path);
- const finalContent = await readFileContent(input.projectId, path);
- if (priorContent !== undefined && finalContent !== priorContent) {
- files[path] = { before: priorContent, after: finalContent };
- }
- }
- if (Object.keys(files).length > 0) {
- await input.recordEdit({
- label: input.label,
- kind: "timeline",
- coalesceKey: input.coalesceKey,
- coalesceMs: GSAP_HISTORY_COALESCE_MS,
- files,
- });
- }
- }
- return status;
-}
-
-/**
- * Shift all GSAP animation positions targeting a given element by a time delta.
- * Calls the server-side GSAP mutation endpoint which uses the AST-based parser.
- */
-export async function shiftGsapPositions(
- projectId: string,
- filePath: string,
- elementId: string,
- delta: number,
-): Promise<GsapMutationStatus> {
- if (delta === 0 || !elementId) return { mutated: false };
- const res = await fetch(
- `/api/projects/${projectId}/gsap-mutations/${encodeURIComponent(filePath)}`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- type: "shift-positions",
- targetSelector: `#${elementId}`,
- delta,
- }),
- },
- );
- if (!res.ok) {
- const err = await res.json().catch(() => null);
- throw new Error(readMutationError(err, "shift-positions failed"));
- }
- return readMutationStatus(await res.json().catch(() => null));
-}
-
-export async function scaleGsapPositions(
- projectId: string,
- filePath: string,
- elementId: string,
- oldStart: number,
- oldDuration: number,
- newStart: number,
- newDuration: number,
-): Promise<GsapMutationStatus> {
- if (!elementId || oldDuration <= 0 || newDuration <= 0) return { mutated: false };
- if (oldStart === newStart && oldDuration === newDuration) return { mutated: false };
- const res = await fetch(
- `/api/projects/${projectId}/gsap-mutations/${encodeURIComponent(filePath)}`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- type: "scale-positions",
- targetSelector: `#${elementId}`,
- oldStart,
- oldDuration,
- newStart,
- newDuration,
- }),
- },
- );
- if (!res.ok) {
- const err = await res.json().catch(() => null);
- throw new Error(readMutationError(err, "scale-positions failed"));
- }
- return readMutationStatus(await res.json().catch(() => null));
-}
-
-/** Single-clip move GSAP shift, folded into the timing edit's history entry (see above). */
-export function foldedShiftGsapMutation(input: {
- projectId: string;
- targetPath: string;
- domId: string;
- delta: number;
- label: string;
- coalesceKey?: string;
- recordEdit: (edit: RecordEditInput) => Promise<void>;
-}): () => Promise<GsapMutationStatus> {
- return () =>
- foldGsapMutationIntoHistory({
- projectId: input.projectId,
- paths: [input.targetPath],
- label: input.label,
- coalesceKey: input.coalesceKey,
- recordEdit: input.recordEdit,
- gsapMutation: () =>
- shiftGsapPositions(input.projectId, input.targetPath, input.domId, input.delta),
- });
-}
-
-/** Single-clip resize GSAP scale, folded into the timing edit's history entry (see above). */
-export function foldedScaleGsapMutation(input: {
- projectId: string;
- targetPath: string;
- domId: string;
- from: { start: number; duration: number };
- to: { start: number; duration: number };
- label: string;
- coalesceKey?: string;
- recordEdit: (edit: RecordEditInput) => Promise<void>;
-}): () => Promise<GsapMutationStatus> {
- return () =>
- foldGsapMutationIntoHistory({
- projectId: input.projectId,
- paths: [input.targetPath],
- label: input.label,
- coalesceKey: input.coalesceKey,
- recordEdit: input.recordEdit,
- gsapMutation: () =>
- scaleGsapPositions(
- input.projectId,
- input.targetPath,
- input.domId,
- input.from.start,
- input.from.duration,
- input.to.start,
- input.to.duration,
- ),
- });
-}
-
export { applyPatchByTarget, formatTimelineAttributeNumber };
export { patchDocumentRootDuration } from "./timelineEditingGsap";
diff --git a/packages/studio/src/hooks/timelineTimingSync.ts b/packages/studio/src/hooks/timelineTimingSync.ts
new file mode 100644
index 0000000000..4840d3b708
--- /dev/null
+++ b/packages/studio/src/hooks/timelineTimingSync.ts
@@ -0,0 +1,377 @@
+// Soft-reload-first preview sync for timeline timing edits: server GSAP
+// position mutations (shift / scale), folding those rewrites into the timing
+// edit's undo history, and swapping the rewritten script into the live preview
+// without a full iframe reload when possible.
+import { type TimelineElement, usePlayerStore } from "../player/store/playerStore";
+import { applySoftReload } from "../utils/gsapSoftReload";
+import { furthestClipEndFromDocument } from "../player/lib/timelineElementHelpers";
+import type { RecordEditInput } from "../utils/studioFileHistory";
+import { patchDocumentRootDuration } from "./timelineEditingGsap";
+
+export async function readFileContent(projectId: string, targetPath: string): Promise<string> {
+ if (targetPath.includes("\0") || targetPath.includes("..")) {
+ throw new Error(`Unsafe path: ${targetPath}`);
+ }
+ const response = await fetch(
+ `/api/projects/${projectId}/files/${encodeURIComponent(targetPath)}`,
+ );
+ if (!response.ok) {
+ throw new Error(`Failed to read ${targetPath}`);
+ }
+ const data = (await response.json()) as { content?: string };
+ if (typeof data.content !== "string") {
+ throw new Error(`Missing file contents for ${targetPath}`);
+ }
+ return data.content;
+}
+
+/** Best-effort live-iframe wrapper for patchDocumentRootDuration (see timelineEditingGsap). */
+function patchIframeRootDuration(iframe: HTMLIFrameElement | null, contentEnd: number): void {
+ try {
+ patchDocumentRootDuration(iframe?.contentDocument ?? null, contentEnd);
+ } catch {
+ // Cross-origin or mid-navigation — file save is enqueued; iframe patch is best-effort.
+ }
+}
+
+/**
+ * Optimistically push the composition's content-driven length into the player
+ * store right after the live DOM patch, so the duration readout + seek bar
+ * update immediately. The readout binds to store.duration (PlayerControls);
+ * edits only patched store.elements, so the number stayed frozen (esp. on
+ * shrink) until a manual refresh. Read from the just-patched preview DOM (raw
+ * data-duration) so it's immune to the runtime's truncated live durations.
+ *
+ * Also writes the content end into the live root's `data-duration`. Timing
+ * edits take the soft-reload path (no full iframe reload), which lets the
+ * runtime recompute the length from the root's declared duration and post it
+ * back — reading the STALE root would revert this optimistic set.
+ */
+export function syncPreviewContentDuration(iframe: HTMLIFrameElement | null): void {
+ const end = furthestClipEndFromDocument(iframe?.contentDocument ?? null);
+ if (end > 0) {
+ usePlayerStore.getState().setDuration(end);
+ patchIframeRootDuration(iframe, end);
+ }
+}
+
+/**
+ * The bits of the server GSAP-mutation response the timeline edit path needs.
+ * `scriptText` is the rewritten root GSAP script — feeding it to `applySoftReload`
+ * swaps the runtime timeline in place (no iframe reload = no all-clips flash). Null
+ * when the endpoint didn't return one (older server, or a multi-script comp the
+ * soft path can't scope), in which case the caller full-reloads as before.
+ */
+export type GsapMutationStatus = { mutated: boolean; scriptText: string | null };
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
+
+function readMutationStatus(value: unknown): GsapMutationStatus {
+ if (!isRecord(value)) return { mutated: false, scriptText: null };
+ return {
+ mutated: value.mutated === true || value.changed === true,
+ scriptText: typeof value.scriptText === "string" ? value.scriptText : null,
+ };
+}
+
+function readMutationError(value: unknown, fallback: string): string {
+ if (isRecord(value) && typeof value.error === "string") return value.error;
+ return fallback;
+}
+
+/**
+ * Sync the live preview after a TIMING-ONLY edit (move / resize), preferring a
+ * soft reload over the full iframe reload that flashes every clip.
+ *
+ * Why this is safe WITHOUT re-deriving timeline elements: a move/resize commit has
+ * already (a) patched the live DOM timing attributes, (b) updated the store's
+ * elements optimistically (the drag commit calls `updateElement` before the
+ * persist), and (c) had the server rewrite the GSAP tween positions — which is the
+ * `scriptText` we swap in here. `applySoftReload` re-runs that script in the LIVE
+ * document (no navigation), re-seeks to the current playhead, and rebinds the
+ * timeline, so the runtime matches the already-correct store. Nothing structural
+ * changed (no clip added/removed), so `processTimelineMessage` would re-derive the
+ * identical element set — skipping it just avoids the flash.
+ *
+ * Escalates to the full `reloadPreview()` only on the PERMANENT `cannot-soft-reload`
+ * result (no gsap runtime / rebind hook / scopable key / script element, or the
+ * re-run threw). The TRANSIENT `verify-failed` is NOT escalated — the live re-run
+ * already applied the shift; a remount would re-flash for nothing. When the server
+ * returned no `scriptText` (older server, multi-script comp), we also full-reload.
+ */
+function syncTimingEditPreview(
+ iframe: HTMLIFrameElement | null,
+ outcome: Pick<GsapMutationStatus, "scriptText">,
+ currentTime: number,
+ reloadPreview: () => void,
+): void {
+ if (!iframe || !outcome.scriptText) {
+ reloadPreview();
+ return;
+ }
+ const result = applySoftReload(iframe, outcome.scriptText, {
+ onAsyncFailure: reloadPreview,
+ currentTimeOverride: currentTime,
+ });
+ if (result === "cannot-soft-reload") reloadPreview();
+}
+
+async function finishTimelineTimingFallback(input: {
+ iframe: HTMLIFrameElement | null;
+ reloadPreview: () => void;
+ gsapMutation?: () => Promise<GsapMutationStatus>;
+ onGsapError: (error: unknown) => void;
+}): Promise<void> {
+ let outcome: GsapMutationStatus = { mutated: false, scriptText: null };
+ if (input.gsapMutation) {
+ try {
+ outcome = await input.gsapMutation();
+ } catch (error) {
+ input.onGsapError(error);
+ return;
+ }
+ }
+ syncTimingEditPreview(
+ input.iframe,
+ outcome,
+ usePlayerStore.getState().currentTime,
+ input.reloadPreview,
+ );
+}
+
+// Coalesce window for folding a GSAP mutation into the preceding timing edit; only has to
+// outlast one GSAP server round-trip, never a real second edit.
+const GSAP_HISTORY_COALESCE_MS = 10_000;
+
+/**
+ * A server GSAP rewrite mutates the same file the timing patch just wrote, but AFTER the
+ * timing edit was recorded, leaving the recorded `after` stale so an undo hits a hash
+ * conflict. This snapshots every touched file, runs the mutation, then records a follow-up
+ * edit under the same coalesceKey with a window wide enough to survive the GSAP round-trip,
+ * folding both writes into one undo step. Returns the mutation status for caller reloads.
+ */
+async function foldGsapMutationIntoHistory(input: {
+ projectId: string;
+ paths: string[];
+ label: string;
+ coalesceKey?: string;
+ recordEdit: (edit: RecordEditInput) => Promise<void>;
+ gsapMutation: () => Promise<GsapMutationStatus>;
+}): Promise<GsapMutationStatus> {
+ const uniquePaths = [...new Set(input.paths)];
+ const before = new Map<string, string>();
+ for (const path of uniquePaths) {
+ before.set(path, await readFileContent(input.projectId, path));
+ }
+ const status = await input.gsapMutation();
+ if (status.mutated) {
+ const files: Record<string, { before: string; after: string }> = {};
+ for (const path of uniquePaths) {
+ const priorContent = before.get(path);
+ const finalContent = await readFileContent(input.projectId, path);
+ if (priorContent !== undefined && finalContent !== priorContent) {
+ files[path] = { before: priorContent, after: finalContent };
+ }
+ }
+ if (Object.keys(files).length > 0) {
+ await input.recordEdit({
+ label: input.label,
+ kind: "timeline",
+ coalesceKey: input.coalesceKey,
+ coalesceMs: GSAP_HISTORY_COALESCE_MS,
+ files,
+ });
+ }
+ }
+ return status;
+}
+
+/**
+ * Shift all GSAP animation positions targeting a given element by a time delta.
+ * Calls the server-side GSAP mutation endpoint which uses the AST-based parser.
+ * Returns the rewritten script so the caller can soft-reload instead of full-reload.
+ */
+export async function shiftGsapPositions(
+ projectId: string,
+ filePath: string,
+ elementId: string,
+ delta: number,
+): Promise<GsapMutationStatus> {
+ if (delta === 0 || !elementId) return { mutated: false, scriptText: null };
+ const res = await fetch(
+ `/api/projects/${projectId}/gsap-mutations/${encodeURIComponent(filePath)}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ type: "shift-positions",
+ targetSelector: `#${elementId}`,
+ delta,
+ }),
+ },
+ );
+ if (!res.ok) {
+ const err = await res.json().catch(() => null);
+ throw new Error(readMutationError(err, "shift-positions failed"));
+ }
+ return readMutationStatus(await res.json().catch(() => null));
+}
+
+export async function scaleGsapPositions(
+ projectId: string,
+ filePath: string,
+ elementId: string,
+ oldStart: number,
+ oldDuration: number,
+ newStart: number,
+ newDuration: number,
+): Promise<GsapMutationStatus> {
+ if (!elementId || oldDuration <= 0 || newDuration <= 0)
+ return { mutated: false, scriptText: null };
+ if (oldStart === newStart && oldDuration === newDuration)
+ return { mutated: false, scriptText: null };
+ const res = await fetch(
+ `/api/projects/${projectId}/gsap-mutations/${encodeURIComponent(filePath)}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ type: "scale-positions",
+ targetSelector: `#${elementId}`,
+ oldStart,
+ oldDuration,
+ newStart,
+ newDuration,
+ }),
+ },
+ );
+ if (!res.ok) {
+ const err = await res.json().catch(() => null);
+ throw new Error(readMutationError(err, "scale-positions failed"));
+ }
+ return readMutationStatus(await res.json().catch(() => null));
+}
+
+/** Timing delta a single-clip edit applies to its GSAP tweens. */
+export type SingleClipGsapEdit =
+ | { kind: "shift"; delta: number }
+ | {
+ kind: "scale";
+ from: { start: number; duration: number };
+ to: { start: number; duration: number };
+ };
+
+/**
+ * Post-persist GSAP sync for a SINGLE-clip timing edit (move / resize): runs the
+ * server shift/scale mutation, folds the rewrite into the timing edit's history
+ * entry (see foldGsapMutationIntoHistory), then soft-reloads the preview with
+ * the rewritten script — full reload when the mutation is skipped, failed, or
+ * returned no script.
+ */
+export function finishClipTimingFallback(input: {
+ iframe: HTMLIFrameElement | null;
+ reloadPreview: () => void;
+ projectId: string | null;
+ targetPath: string;
+ domId: string | undefined;
+ label: string;
+ coalesceKey?: string;
+ recordEdit: (edit: RecordEditInput) => Promise<void>;
+ edit: SingleClipGsapEdit;
+}): Promise<void> {
+ const { projectId, targetPath, domId, edit } = input;
+ const timingChanged =
+ edit.kind === "shift"
+ ? edit.delta !== 0
+ : edit.from.start !== edit.to.start || edit.from.duration !== edit.to.duration;
+ const runMutation = (pid: string, id: string): Promise<GsapMutationStatus> =>
+ edit.kind === "shift"
+ ? shiftGsapPositions(pid, targetPath, id, edit.delta)
+ : scaleGsapPositions(
+ pid,
+ targetPath,
+ id,
+ edit.from.start,
+ edit.from.duration,
+ edit.to.start,
+ edit.to.duration,
+ );
+ return finishTimelineTimingFallback({
+ iframe: input.iframe,
+ reloadPreview: input.reloadPreview,
+ gsapMutation:
+ timingChanged && domId && projectId
+ ? () =>
+ foldGsapMutationIntoHistory({
+ projectId,
+ paths: [targetPath],
+ label: input.label,
+ coalesceKey: input.coalesceKey,
+ recordEdit: input.recordEdit,
+ gsapMutation: () => runMutation(projectId, domId),
+ })
+ : undefined,
+ onGsapError: (err) => console.error(`[Timeline] Failed to ${edit.kind} GSAP positions`, err),
+ });
+}
+
+/**
+ * Shared post-persist GSAP sync for GROUP timing edits (move / resize): runs the
+ * per-change server mutation for every changed clip, folds the rewrites into the
+ * timing edit's history entry, and soft-reloads the preview when possible.
+ *
+ * The preview is a SINGLE shared iframe showing the ACTIVE composition, so only
+ * the active comp's rewritten script can be soft-reloaded (swapped in place, no
+ * all-clips flash). If any OTHER file changed too — e.g. a sub-comp group in a
+ * multi-file move — no scriptText is passed, so the fallback does ONE full
+ * reload that reflects every changed file.
+ */
+export async function finishGroupTimingGsapFallback<C extends { element: TimelineElement }>(input: {
+ projectId: string;
+ iframe: HTMLIFrameElement | null;
+ reloadPreview: () => void;
+ label: string;
+ errorLabel: string;
+ coalesceKey?: string;
+ recordEdit: (edit: RecordEditInput) => Promise<void>;
+ activeCompPath: string | null;
+ changes: readonly C[];
+ resolveChangePath: (element: TimelineElement) => string;
+ /** Per-change GSAP mutation; return null to skip a change with no timing delta. */
+ mutateChange: (change: C, changePath: string) => Promise<GsapMutationStatus> | null;
+}): Promise<void> {
+ const activePath = input.activeCompPath || "index.html";
+ const otherFileChanged = input.changes.some(
+ (change) => input.resolveChangePath(change.element) !== activePath,
+ );
+ await finishTimelineTimingFallback({
+ iframe: input.iframe,
+ reloadPreview: input.reloadPreview,
+ gsapMutation: () =>
+ foldGsapMutationIntoHistory({
+ projectId: input.projectId,
+ paths: input.changes.map((change) => input.resolveChangePath(change.element)),
+ label: input.label,
+ coalesceKey: input.coalesceKey,
+ recordEdit: input.recordEdit,
+ gsapMutation: async () => {
+ let mutated = false;
+ let scriptText: GsapMutationStatus["scriptText"] = null;
+ for (const change of input.changes) {
+ const changePath = input.resolveChangePath(change.element);
+ const pending = input.mutateChange(change, changePath);
+ if (!pending) continue;
+ const status = await pending;
+ mutated = mutated || status.mutated;
+ // The LAST mutation against the active comp carries the cumulative
+ // rewritten script for that file.
+ if (changePath === activePath) scriptText = status.scriptText;
+ }
+ return { mutated, scriptText: otherFileChanged ? null : scriptText };
+ },
+ }),
+ onGsapError: (err) => console.error(`[Timeline] ${input.errorLabel}`, err),
+ });
+}
diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx
index 3cc74fbfd7..9a652d83e9 100644
--- a/packages/studio/src/hooks/useTimelineEditing.test.tsx
+++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx
@@ -77,6 +77,21 @@ function timelineElement(input: {
};
}
+/** Mount a harness component under act() and return its unmount hook. */
+function mountHarness(node: React.ReactElement): { unmount: () => void } {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ act(() => {
+ root.render(node);
+ });
+ return {
+ unmount: () => {
+ act(() => root.unmount());
+ },
+ };
+}
+
function renderTimelineEditingHook(input: {
timelineElements: TimelineElement[];
iframe: HTMLIFrameElement;
@@ -130,26 +145,12 @@ function renderTimelineEditingHook(input: {
return null;
}
- const host = document.createElement("div");
- document.body.append(host);
- const root = createRoot(host);
- act(() => {
- root.render(<Harness />);
- });
-
+ const { unmount } = mountHarness(<Harness />);
if (!move) throw new Error("Expected hook to expose move handler");
if (!resize) throw new Error("Expected hook to expose resize handler");
if (!groupMove) throw new Error("Expected hook to expose group move handler");
if (!groupResize) throw new Error("Expected hook to expose group resize handler");
- return {
- move,
- resize,
- groupMove,
- groupResize,
- unmount: () => {
- act(() => root.unmount());
- },
- };
+ return { move, resize, groupMove, groupResize, unmount };
}
type TimelineRecordEdit = NonNullable<
@@ -198,20 +199,9 @@ function renderTimelineEditingHookWithLifecycle(input: {
return null;
}
- const host = document.createElement("div");
- document.body.append(host);
- const root = createRoot(host);
- act(() => {
- root.render(<Harness />);
- });
-
+ const { unmount } = mountHarness(<Harness />);
if (!move) throw new Error("Expected hook to expose move handler");
- return {
- move,
- unmount: () => {
- act(() => root.unmount());
- },
- };
+ return { move, unmount };
}
function jsonResponse(body: unknown): Response {
@@ -233,139 +223,118 @@ async function flushAsyncWork(): Promise<void> {
}
}
+/**
+ * Stub global fetch for project "p1": serves file contents (a single source
+ * string, or a path → content map) and answers the GSAP-mutation endpoint
+ * with `gsapBody`. Returns the mock for call inspection.
+ */
+function stubProjectFetch(
+ files: string | Record<string, string>,
+ gsapBody: unknown = { ok: true },
+) {
+ const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
+ const url = requestUrl(input);
+ if (url.includes("/api/projects/p1/files/")) {
+ if (typeof files === "string") return jsonResponse({ content: files });
+ const path = decodeURIComponent(url.split("/files/")[1] ?? "index.html");
+ return jsonResponse({ content: files[path] });
+ }
+ if (url.includes("/api/projects/p1/gsap-mutations/")) return jsonResponse(gsapBody);
+ throw new Error(`Unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+const ROOT_DURATION_FALLBACK_SOURCE = [
+ `<div data-composition-id="main" data-duration="4">`,
+ ` <div id="clip" data-hf-id="hf-clip" data-start="0" data-duration="2"></div>`,
+ `</div>`,
+].join("\n");
+
+/** Shared setup for the SDK-fallback root-duration tests: one 2s clip in a 4s comp. */
+async function setupRootDurationFallback() {
+ const iframe = createPreviewIframe([{ id: "clip", track: 0 }]);
+ const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
+ const sdkSession = await openComposition(ROOT_DURATION_FALLBACK_SOURCE);
+ const setTimingSpy = vi.spyOn(sdkSession, "setTiming");
+ const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ const recordEdit = vi.fn<TimelineRecordEdit>(async () => {});
+ const forceReloadSdkSession = vi.fn();
+ const reloadPreview = vi.fn();
+ const iframeWindow = iframe.contentWindow;
+ if (!iframeWindow) throw new Error("Expected iframe window");
+ const postMessageSpy = vi.spyOn(iframeWindow, "postMessage");
+ stubProjectFetch(ROOT_DURATION_FALLBACK_SOURCE, { ok: true, mutated: false });
+ usePlayerStore.getState().setDuration(4);
+ const hook = renderTimelineEditingHook({
+ timelineElements: [clip],
+ iframe,
+ onZIndexCommit: vi.fn().mockResolvedValue(undefined),
+ projectId: "p1",
+ writeProjectFile,
+ recordEdit,
+ sdkSession,
+ forceReloadSdkSession,
+ reloadPreview,
+ });
+ return {
+ hook,
+ clip,
+ setTimingSpy,
+ writeProjectFile,
+ forceReloadSdkSession,
+ reloadPreview,
+ postMessageSpy,
+ };
+}
+
+/** Shared assertions: the fallback path grew the root to 5s and did ONE full reload. */
+function expectRootDurationExtendedViaFallback(
+ ctx: Awaited<ReturnType<typeof setupRootDurationFallback>>,
+): void {
+ expect(ctx.setTimingSpy).not.toHaveBeenCalled();
+ expect(ctx.writeProjectFile.mock.calls[0]![1]).toContain(
+ 'data-composition-id="main" data-duration="5"',
+ );
+ expect(usePlayerStore.getState().duration).toBe(5);
+ expect(ctx.forceReloadSdkSession).toHaveBeenCalledTimes(1);
+ // The GSAP endpoint returned no rewritten scriptText, so the timing sync
+ // escalates from the flash-free soft reload to ONE full reload. The root
+ // duration travels via the persisted content-driven `data-duration` (above),
+ // not a `set-root-duration` postMessage.
+ expect(ctx.reloadPreview).toHaveBeenCalledTimes(1);
+ expect(ctx.postMessageSpy).not.toHaveBeenCalledWith(
+ expect.objectContaining({ action: "set-root-duration" }),
+ "*",
+ );
+}
+
describe("useTimelineEditing timeline z-index reorder", () => {
it("extends root duration through the fallback path when an SDK-backed move passes the end", async () => {
- const source = [
- `<div data-composition-id="main" data-duration="4">`,
- ` <div id="clip" data-hf-id="hf-clip" data-start="0" data-duration="2"></div>`,
- `</div>`,
- ].join("\n");
- const iframe = createPreviewIframe([{ id: "clip", track: 0 }]);
- const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
- const sdkSession = await openComposition(source);
- const setTimingSpy = vi.spyOn(sdkSession, "setTiming");
- const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
- const recordEdit = vi.fn<TimelineRecordEdit>(async () => {});
- const forceReloadSdkSession = vi.fn();
- const reloadPreview = vi.fn();
- const iframeWindow = iframe.contentWindow;
- if (!iframeWindow) throw new Error("Expected iframe window");
- const postMessageSpy = vi.spyOn(iframeWindow, "postMessage");
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
- const url = requestUrl(input);
- if (url.includes("/api/projects/p1/files/")) return jsonResponse({ content: source });
- if (url.includes("/api/projects/p1/gsap-mutations/")) {
- return jsonResponse({ ok: true, mutated: false });
- }
- throw new Error(`Unexpected fetch: ${url}`);
- }),
- );
- usePlayerStore.getState().setDuration(4);
- const { move, unmount } = renderTimelineEditingHook({
- timelineElements: [clip],
- iframe,
- onZIndexCommit: vi.fn().mockResolvedValue(undefined),
- projectId: "p1",
- writeProjectFile,
- recordEdit,
- sdkSession,
- forceReloadSdkSession,
- reloadPreview,
- });
+ const ctx = await setupRootDurationFallback();
await act(async () => {
- await move(clip, { start: 3, track: clip.track });
- });
-
- expect(setTimingSpy).not.toHaveBeenCalled();
- expect(writeProjectFile.mock.calls[0]![1]).toContain(
- 'data-composition-id="main" data-duration="5"',
- );
- expect(writeProjectFile.mock.calls[0]![1]).toContain('data-start="3"');
- expect(usePlayerStore.getState().duration).toBe(5);
- expect(forceReloadSdkSession).toHaveBeenCalledTimes(1);
- expect(reloadPreview).not.toHaveBeenCalled();
- expect(postMessageSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- source: "hf-parent",
- type: "control",
- action: "set-root-duration",
- durationSeconds: 5,
- protocolVersion: 1,
- }),
- "*",
- );
+ await ctx.hook.move(ctx.clip, { start: 3, track: ctx.clip.track });
+ });
- unmount();
+ expect(ctx.writeProjectFile.mock.calls[0]![1]).toContain('data-start="3"');
+ expectRootDurationExtendedViaFallback(ctx);
+
+ ctx.hook.unmount();
});
it("extends root duration through the fallback path when an SDK-backed resize passes the end", async () => {
- const source = [
- `<div data-composition-id="main" data-duration="4">`,
- ` <div id="clip" data-hf-id="hf-clip" data-start="0" data-duration="2"></div>`,
- `</div>`,
- ].join("\n");
- const iframe = createPreviewIframe([{ id: "clip", track: 0 }]);
- const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
- const sdkSession = await openComposition(source);
- const setTimingSpy = vi.spyOn(sdkSession, "setTiming");
- const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
- const recordEdit = vi.fn<TimelineRecordEdit>(async () => {});
- const forceReloadSdkSession = vi.fn();
- const reloadPreview = vi.fn();
- const iframeWindow = iframe.contentWindow;
- if (!iframeWindow) throw new Error("Expected iframe window");
- const postMessageSpy = vi.spyOn(iframeWindow, "postMessage");
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
- const url = requestUrl(input);
- if (url.includes("/api/projects/p1/files/")) return jsonResponse({ content: source });
- if (url.includes("/api/projects/p1/gsap-mutations/")) {
- return jsonResponse({ ok: true, mutated: false });
- }
- throw new Error(`Unexpected fetch: ${url}`);
- }),
- );
- usePlayerStore.getState().setDuration(4);
- const { resize, unmount } = renderTimelineEditingHook({
- timelineElements: [clip],
- iframe,
- onZIndexCommit: vi.fn().mockResolvedValue(undefined),
- projectId: "p1",
- writeProjectFile,
- recordEdit,
- sdkSession,
- forceReloadSdkSession,
- reloadPreview,
- });
+ const ctx = await setupRootDurationFallback();
await act(async () => {
- await resize(clip, { start: 0, duration: 5, playbackStart: undefined });
- });
-
- expect(setTimingSpy).not.toHaveBeenCalled();
- expect(writeProjectFile.mock.calls[0]![1]).toContain(
- 'data-composition-id="main" data-duration="5"',
- );
- expect(writeProjectFile.mock.calls[0]![1]).toContain('data-duration="5"></div>');
- expect(usePlayerStore.getState().duration).toBe(5);
- expect(forceReloadSdkSession).toHaveBeenCalledTimes(1);
- expect(reloadPreview).not.toHaveBeenCalled();
- expect(postMessageSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- source: "hf-parent",
- type: "control",
- action: "set-root-duration",
- durationSeconds: 5,
- protocolVersion: 1,
- }),
- "*",
- );
+ await ctx.hook.resize(ctx.clip, { start: 0, duration: 5, playbackStart: undefined });
+ });
- unmount();
+ expect(ctx.writeProjectFile.mock.calls[0]![1]).toContain('data-duration="5"></div>');
+ expectRootDurationExtendedViaFallback(ctx);
+
+ ctx.hook.unmount();
});
it("routes a vertical drag through the shared z-index commit without writing track-index", async () => {
@@ -640,24 +609,7 @@ describe("useTimelineEditing timeline z-index reorder", () => {
const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
const recordEdit = vi.fn<TimelineRecordEdit>(async (_entry) => {});
const reloadPreview = vi.fn();
- const fetchMock = vi.fn(
- async (
- input: Parameters<typeof fetch>[0],
- _init?: Parameters<typeof fetch>[1],
- ): Promise<Response> => {
- const url = requestUrl(input);
- if (url.includes("/api/projects/p1/files/")) {
- return jsonResponse({
- content: '<div id="clip" data-start="0" data-track-index="0"></div>',
- });
- }
- if (url.includes("/api/projects/p1/gsap-mutations/")) {
- return jsonResponse({ ok: true });
- }
- throw new Error(`Unexpected fetch: ${url}`);
- },
- );
- vi.stubGlobal("fetch", fetchMock);
+ const fetchMock = stubProjectFetch('<div id="clip" data-start="0" data-track-index="0"></div>');
const { move, unmount } = renderTimelineEditingHook({
timelineElements: [clip],
iframe,
@@ -699,17 +651,7 @@ describe("useTimelineEditing timeline z-index reorder", () => {
});
const commit = vi.fn<(entries: ZIndexEntry[]) => Promise<void>>().mockReturnValue(commitGate);
const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
- const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
- const url = requestUrl(input);
- if (url.includes("/api/projects/p1/files/")) {
- return jsonResponse({
- content: '<div id="clip" data-start="0" data-track-index="0"></div>',
- });
- }
- if (url.includes("/api/projects/p1/gsap-mutations/")) return jsonResponse({ ok: true });
- throw new Error(`Unexpected fetch: ${url}`);
- });
- vi.stubGlobal("fetch", fetchMock);
+ stubProjectFetch('<div id="clip" data-start="0" data-track-index="0"></div>');
const { move, unmount } = renderTimelineEditingHook({
timelineElements: [clip],
iframe,
@@ -768,15 +710,7 @@ describe("useTimelineEditing timeline z-index reorder", () => {
];
const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
const recordEdit = vi.fn<TimelineRecordEdit>(async (_entry) => {});
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
- const url = requestUrl(input);
- if (url.includes("/api/projects/p1/files/")) return jsonResponse({ content: source });
- if (url.includes("/api/projects/p1/gsap-mutations/")) return jsonResponse({ ok: true });
- throw new Error(`Unexpected fetch: ${url}`);
- }),
- );
+ stubProjectFetch(source);
const { groupMove, unmount } = renderTimelineEditingHook({
timelineElements: clips,
iframe,
@@ -825,18 +759,7 @@ describe("useTimelineEditing timeline z-index reorder", () => {
});
const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
const recordEdit = vi.fn<TimelineRecordEdit>(async (_entry) => {});
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
- const url = requestUrl(input);
- if (url.includes("/api/projects/p1/files/")) {
- const path = decodeURIComponent(url.split("/files/")[1] ?? "index.html");
- return jsonResponse({ content: files[path] });
- }
- if (url.includes("/api/projects/p1/gsap-mutations/")) return jsonResponse({ ok: true });
- throw new Error(`Unexpected fetch: ${url}`);
- }),
- );
+ stubProjectFetch(files);
const { groupMove, unmount } = renderTimelineEditingHook({
timelineElements: [a, b],
iframe,
@@ -877,15 +800,7 @@ describe("useTimelineEditing timeline z-index reorder", () => {
releaseCommit = resolve;
});
const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
- const url = requestUrl(input);
- if (url.includes("/api/projects/p1/files/")) return jsonResponse({ content: source });
- if (url.includes("/api/projects/p1/gsap-mutations/")) return jsonResponse({ ok: true });
- throw new Error(`Unexpected fetch: ${url}`);
- }),
- );
+ stubProjectFetch(source);
const { groupMove, unmount } = renderTimelineEditingHook({
timelineElements: [clip],
iframe,
@@ -915,13 +830,7 @@ describe("useTimelineEditing timeline z-index reorder", () => {
it("matches the single-clip move output when a group move contains one clip", async () => {
const source = '<div id="clip" data-start="0" data-duration="1"></div>';
const clip = timelineElement({ id: "clip", track: 0, zIndex: 0, start: 0, duration: 1 });
- const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
- const url = requestUrl(input);
- if (url.includes("/api/projects/p1/files/")) return jsonResponse({ content: source });
- if (url.includes("/api/projects/p1/gsap-mutations/")) return jsonResponse({ ok: true });
- throw new Error(`Unexpected fetch: ${url}`);
- });
- vi.stubGlobal("fetch", fetchMock);
+ stubProjectFetch(source);
const singleWrite = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
const single = renderTimelineEditingHook({
diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts
index b873f85178..5cf07b0fe5 100644
--- a/packages/studio/src/hooks/useTimelineEditing.ts
+++ b/packages/studio/src/hooks/useTimelineEditing.ts
@@ -7,12 +7,16 @@ import {
buildTimelineAssetId,
buildTimelineAssetInsertHtml,
buildTimelineFileDropPlacements,
+ fitTimelineAssetGeometry,
getTimelineAssetKind,
insertTimelineAssetIntoSource,
- resolveTimelineAssetInitialGeometry,
+ resolveTimelineAssetCompositionSize,
resolveTimelineAssetSrc,
} from "../utils/timelineAssetDrop";
+import { generateId } from "../utils/generateId";
import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
+import { setCompositionDurationToContent } from "../utils/timelineAssetDrop";
+import { furthestClipEndFromSource } from "../player/lib/timelineElementHelpers";
import {
getTimelineElementLabel,
collectHtmlIds,
@@ -23,15 +27,16 @@ import {
buildPatchTarget,
patchIframeDomTiming,
persistTimelineEdit,
- readFileContent,
- foldedShiftGsapMutation,
- foldedScaleGsapMutation,
formatTimelineAttributeNumber,
- finishTimelineTimingFallback,
extendRootDurationIfNeeded,
buildTimelineMoveTimingPatch,
buildTimelineResizeTimingPatch,
} from "./timelineEditingHelpers";
+import {
+ finishClipTimingFallback,
+ readFileContent,
+ syncPreviewContentDuration,
+} from "./timelineTimingSync";
import type { PersistTimelineEditInput } from "./timelineEditingHelpers";
import type { TimelineStackingReorderIntent } from "../player/components/timelineEditing";
import {
@@ -155,36 +160,35 @@ export function useTimelineEditing({
if (!startChanged) return reorderDone;
+ // needsExtension gates the SDK path (setTiming can't grow the root duration),
+ // so read the store BEFORE the readout sync below optimistically updates it.
+ const needsExtension = extendRootDurationIfNeeded(updates.start + element.duration);
+ // Optimistic duration readout: content-driven (grow AND shrink), read from
+ // the just-patched live DOM. See syncPreviewContentDuration.
+ syncPreviewContentDuration(previewIframeRef.current);
+
const buildMovePatches: PersistTimelineEditInput["buildPatches"] = (original, target) => {
return buildTimelineMoveTimingPatch(original, target, updates.start, element.duration);
};
const coalesceKey = `timeline-move:${element.hfId ?? element.id}`;
const moveFallback = () =>
- enqueueEdit(element, "Move timeline clip", buildMovePatches, coalesceKey).then(() => {
- const pid = projectIdRef.current;
- const delta = updates.start - element.start;
- const domId = element.domId;
- return finishTimelineTimingFallback({
+ enqueueEdit(element, "Move timeline clip", buildMovePatches, coalesceKey).then(() =>
+ // Soft-reload with the server's rewritten GSAP script instead of a full
+ // iframe reload — a timing-only move already patched the DOM + store, so
+ // swapping the script in place avoids the all-clips flash. Falls back to
+ // reloadPreview() when the soft path can't apply. (See timelineTimingSync.)
+ finishClipTimingFallback({
iframe: previewIframeRef.current,
- needsExtension,
- rootDurationSeconds: updates.start + element.duration,
reloadPreview,
- gsapMutation:
- delta !== 0 && domId && pid
- ? foldedShiftGsapMutation({
- projectId: pid,
- targetPath,
- domId,
- delta,
- label: "Move timeline clip",
- coalesceKey,
- recordEdit,
- })
- : undefined,
- onGsapError: (err) => console.error("[Timeline] Failed to shift GSAP positions", err),
- });
- });
- const needsExtension = extendRootDurationIfNeeded(updates.start + element.duration);
+ projectId: projectIdRef.current,
+ targetPath,
+ domId: element.domId,
+ label: "Move timeline clip",
+ coalesceKey,
+ recordEdit,
+ edit: { kind: "shift", delta: updates.start - element.start },
+ }),
+ );
return reorderDone.then(() => {
if (sdkSession && element.hfId && !needsExtension) {
return sdkTimingPersist(
@@ -245,6 +249,12 @@ export function useTimelineEditing({
liveAttrs.push([liveAttr, formatTimelineAttributeNumber(updates.playbackStart)]);
}
patchIframeDomTiming(previewIframeRef.current, element, liveAttrs);
+ // needsExtension gates the SDK path (setTiming can't grow the root duration),
+ // so read the store BEFORE the readout sync below optimistically updates it.
+ const needsExtension = extendRootDurationIfNeeded(updates.start + updates.duration);
+ // Optimistic duration readout: content-driven (grow AND shrink), read from
+ // the just-patched live DOM. See syncPreviewContentDuration.
+ syncPreviewContentDuration(previewIframeRef.current);
const targetPath = element.sourceFile || activeCompPath || "index.html";
const buildResizePatches: PersistTimelineEditInput["buildPatches"] = (original, target) => {
return buildTimelineResizeTimingPatch(original, target, element, updates);
@@ -253,37 +263,28 @@ export function useTimelineEditing({
updates.playbackStart != null ||
(updates.start !== element.start && element.playbackStart != null);
// Server-path fallback: after persisting the attr patch, scale GSAP tween
- // positions/durations on the server. Extending edits can keep the iframe
- // live unless a GSAP source rewrite needs a fresh run.
+ // positions/durations on the server, then soft-reload with the rewritten
+ // script (timing-only resize) — same no-flash path as move; full reload is
+ // the fallback.
const coalesceKey = `timeline-resize:${element.hfId ?? element.id}`;
- const timingChanged =
- updates.start !== element.start || updates.duration !== element.duration;
- const needsExtension = extendRootDurationIfNeeded(updates.start + updates.duration);
const resizeFallback = () =>
- enqueueEdit(element, "Resize timeline clip", buildResizePatches, coalesceKey).then(() => {
- const pid = projectIdRef.current;
- const domId = element.domId;
- return finishTimelineTimingFallback({
+ enqueueEdit(element, "Resize timeline clip", buildResizePatches, coalesceKey).then(() =>
+ finishClipTimingFallback({
iframe: previewIframeRef.current,
- needsExtension,
- rootDurationSeconds: updates.start + updates.duration,
reloadPreview,
- gsapMutation:
- timingChanged && domId && pid
- ? foldedScaleGsapMutation({
- projectId: pid,
- targetPath,
- domId,
- from: { start: element.start, duration: element.duration },
- to: { start: updates.start, duration: updates.duration },
- label: "Resize timeline clip",
- coalesceKey,
- recordEdit,
- })
- : undefined,
- onGsapError: (err) => console.error("[Timeline] Failed to scale GSAP positions", err),
- });
- });
+ projectId: projectIdRef.current,
+ targetPath,
+ domId: element.domId,
+ label: "Resize timeline clip",
+ coalesceKey,
+ recordEdit,
+ edit: {
+ kind: "scale",
+ from: { start: element.start, duration: element.duration },
+ to: { start: updates.start, duration: updates.duration },
+ },
+ }),
+ );
if (sdkSession && element.hfId && !hasPbsAdjustment && !needsExtension) {
return sdkTimingPersist(
element.hfId,
@@ -384,8 +385,19 @@ export function useTimelineEditing({
changed?: boolean;
content?: string;
};
- const patchedContent =
+ const removedContent =
typeof removeData.content === "string" ? removeData.content : originalContent;
+ // Content-driven duration: shrink the composition to the furthest
+ // remaining clip end, read from the post-removal SOURCE (raw
+ // data-duration), so deleting the last/longest clip removes trailing
+ // empty space. Measured from the source, not the store, whose
+ // durations are runtime-truncated.
+ const deleteContentEnd = furthestClipEndFromSource(removedContent);
+ const patchedContent = setCompositionDurationToContent(removedContent, deleteContentEnd);
+ // Optimistically reflect the shrunk length in the readout/seek bar.
+ if (deleteContentEnd > 0 && targetPath === (activeCompPath || "index.html")) {
+ usePlayerStore.getState().setDuration(deleteContentEnd);
+ }
domEditSaveTimestampRef.current = Date.now();
await saveProjectFilesWithHistory({
@@ -469,13 +481,17 @@ export function useTimelineEditing({
originalContent,
buildTimelineAssetInsertHtml({
id: newId,
+ hfId: `hf-${generateId()}`,
assetPath: resolvedAssetSrc,
kind,
start: normalizedStart,
duration: normalizedDuration,
track: placement.track,
zIndex: newElementZIndex,
- geometry: resolveTimelineAssetInitialGeometry(originalContent),
+ geometry: fitTimelineAssetGeometry(
+ null,
+ resolveTimelineAssetCompositionSize(originalContent),
+ ),
}),
);
@@ -532,17 +548,6 @@ export function useTimelineEditing({
const placements = buildTimelineFileDropPlacements(
placement ?? { start: 0, track: 0 },
durations,
- timelineElements
- .filter(
- (te) =>
- (te.sourceFile || activeCompPath || "index.html") ===
- (activeCompPath || "index.html"),
- )
- .map((te) => ({
- start: te.start,
- duration: te.duration,
- track: te.track,
- })),
);
for (const [index, assetPath] of uploaded.entries()) {
await handleTimelineAssetDrop(
@@ -552,14 +557,7 @@ export function useTimelineEditing({
);
}
},
- [
- activeCompPath,
- handleTimelineAssetDrop,
- timelineElements,
- uploadProjectFiles,
- isRecordingRef,
- showToast,
- ],
+ [handleTimelineAssetDrop, uploadProjectFiles, isRecordingRef, showToast],
);
const handleBlockedTimelineEdit = useCallback(
diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts
index 7225b50d59..2dc4179ff2 100644
--- a/packages/studio/src/hooks/useTimelineGroupEditing.ts
+++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts
@@ -6,17 +6,19 @@ import {
buildTimelineMoveTimingPatch,
buildTimelineResizeTimingPatch,
extendRootDurationIfNeeded,
- finishTimelineTimingFallback,
- foldGsapMutationIntoHistory,
formatTimelineAttributeNumber,
patchIframeDomTiming,
persistTimelineBatchEdit,
- readFileContent,
- scaleGsapPositions,
- shiftGsapPositions,
type PersistTimelineBatchChange,
type RecordEditInput,
} from "./timelineEditingHelpers";
+import {
+ finishGroupTimingGsapFallback,
+ readFileContent,
+ scaleGsapPositions,
+ shiftGsapPositions,
+ syncPreviewContentDuration,
+} from "./timelineTimingSync";
export interface TimelineGroupMoveChange {
element: TimelineElement;
@@ -149,6 +151,55 @@ export function useTimelineGroupEditing({
],
);
+ // Shared SDK fast path for group move/resize: eligible when nothing needs the
+ // server (no root-duration growth, one shared file, every change SDK-addressable
+ // and `eligible` per the caller's own gate). Returns whether the SDK handled it;
+ // false → caller falls through to the server batch persist.
+ const trySdkBatchPersist = useCallback(
+ async (input: {
+ changes: readonly { element: TimelineElement }[];
+ sdkChanges: Array<{
+ hfId: string;
+ timingUpdate: { start: number; duration?: number };
+ } | null>;
+ eligible: boolean;
+ needsExtension: boolean;
+ label: string;
+ coalesceKey: string;
+ }): Promise<boolean> => {
+ const sharedPath = allChangesSharePath(input.changes, activeCompPath);
+ const canUseSdk =
+ !input.needsExtension &&
+ sharedPath !== null &&
+ input.eligible &&
+ input.sdkChanges.every((change) => change !== null);
+ if (!canUseSdk) return false;
+ return sdkTimingBatchPersist(
+ input.sdkChanges.filter((change): change is NonNullable<typeof change> => change !== null),
+ sharedPath,
+ sdkSession,
+ {
+ editHistory: { recordEdit },
+ writeProjectFile,
+ reloadPreview,
+ domEditSaveTimestampRef,
+ compositionPath: activeCompPath,
+ readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),
+ },
+ { label: input.label, coalesceKey: input.coalesceKey },
+ );
+ },
+ [
+ activeCompPath,
+ domEditSaveTimestampRef,
+ projectIdRef,
+ recordEdit,
+ reloadPreview,
+ sdkSession,
+ writeProjectFile,
+ ],
+ );
+
const handleTimelineGroupMove = useCallback(
(changes: TimelineGroupMoveChange[], options?: TimelineGroupCommitOptions) => {
if (changes.length === 0) return Promise.resolve();
@@ -163,38 +214,28 @@ export function useTimelineGroupEditing({
}
const maxEnd = Math.max(...changes.map((change) => change.start + change.element.duration));
+ // needsExtension gates the SDK path (setTiming can't grow the root duration),
+ // so read the store BEFORE the readout sync below optimistically updates it.
const needsExtension = extendRootDurationIfNeeded(maxEnd);
+ // Optimistic duration readout: content-driven (grow AND shrink), read from
+ // the just-patched live DOM. See syncPreviewContentDuration.
+ syncPreviewContentDuration(previewIframeRef.current);
const coalesceKey = options?.coalesceKey ?? moveCoalesceKey(changes);
return enqueueGroupOperation("Move timeline clips", async (projectId) => {
await options?.beforeTiming;
- const sharedPath = allChangesSharePath(changes, activeCompPath);
- const sdkChanges = changes.map((change) =>
- change.element.hfId
- ? { hfId: change.element.hfId, timingUpdate: { start: change.start } }
- : null,
- );
- const canUseSdk =
- !needsExtension &&
- sharedPath !== null &&
- changes.every((change) => change.track == null) &&
- sdkChanges.every((change) => change !== null);
- if (canUseSdk) {
- const handled = await sdkTimingBatchPersist(
- sdkChanges.filter((change): change is NonNullable<typeof change> => change !== null),
- sharedPath,
- sdkSession,
- {
- editHistory: { recordEdit },
- writeProjectFile,
- reloadPreview,
- domEditSaveTimestampRef,
- compositionPath: activeCompPath,
- readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),
- },
- { label: "Move timeline clips", coalesceKey },
- );
- if (handled) return;
- }
+ const handledBySdk = await trySdkBatchPersist({
+ changes,
+ sdkChanges: changes.map((change) =>
+ change.element.hfId
+ ? { hfId: change.element.hfId, timingUpdate: { start: change.start } }
+ : null,
+ ),
+ eligible: changes.every((change) => change.track == null),
+ needsExtension,
+ label: "Move timeline clips",
+ coalesceKey,
+ });
+ if (handledBySdk) return;
await persistServerBatch(
projectId,
@@ -212,50 +253,34 @@ export function useTimelineGroupEditing({
})),
coalesceKey,
);
- await finishTimelineTimingFallback({
+ await finishGroupTimingGsapFallback({
+ projectId,
iframe: previewIframeRef.current,
- needsExtension,
- rootDurationSeconds: maxEnd,
reloadPreview,
- gsapMutation: () =>
- foldGsapMutationIntoHistory({
- projectId,
- paths: changes.map((change) => targetPathFor(change.element, activeCompPath)),
- label: "Move timeline clips",
- coalesceKey,
- recordEdit,
- gsapMutation: async () => {
- let mutated = false;
- for (const change of changes) {
- const delta = change.start - change.element.start;
- const domId = change.element.domId;
- if (delta === 0 || !domId) continue;
- const status = await shiftGsapPositions(
- projectId,
- targetPathFor(change.element, activeCompPath),
- domId,
- delta,
- );
- mutated = mutated || status.mutated;
- }
- return { mutated };
- },
- }),
- onGsapError: (err) => console.error("[Timeline] Failed to shift GSAP positions", err),
+ label: "Move timeline clips",
+ errorLabel: "Failed to shift GSAP positions",
+ coalesceKey,
+ recordEdit,
+ activeCompPath,
+ changes,
+ resolveChangePath: (element) => targetPathFor(element, activeCompPath),
+ mutateChange: (change, changePath) => {
+ const delta = change.start - change.element.start;
+ const domId = change.element.domId;
+ if (delta === 0 || !domId) return null;
+ return shiftGsapPositions(projectId, changePath, domId, delta);
+ },
});
});
},
[
activeCompPath,
- domEditSaveTimestampRef,
enqueueGroupOperation,
persistServerBatch,
previewIframeRef,
- projectIdRef,
recordEdit,
reloadPreview,
- sdkSession,
- writeProjectFile,
+ trySdkBatchPersist,
],
);
@@ -278,41 +303,31 @@ export function useTimelineGroupEditing({
}
const maxEnd = Math.max(...changes.map((change) => change.start + change.duration));
+ // needsExtension gates the SDK path (setTiming can't grow the root duration),
+ // so read the store BEFORE the readout sync below optimistically updates it.
const needsExtension = extendRootDurationIfNeeded(maxEnd);
+ // Optimistic duration readout: content-driven (grow AND shrink), read from
+ // the just-patched live DOM. See syncPreviewContentDuration.
+ syncPreviewContentDuration(previewIframeRef.current);
const coalesceKey = options?.coalesceKey ?? resizeCoalesceKey(changes);
return enqueueGroupOperation("Resize timeline clips", async (projectId) => {
await options?.beforeTiming;
- const sharedPath = allChangesSharePath(changes, activeCompPath);
- const sdkChanges = changes.map((change) =>
- change.element.hfId
- ? {
- hfId: change.element.hfId,
- timingUpdate: { start: change.start, duration: change.duration },
- }
- : null,
- );
- const canUseSdk =
- !needsExtension &&
- sharedPath !== null &&
- changes.every((change) => !resizeHasPlaybackStartAdjustment(change)) &&
- sdkChanges.every((change) => change !== null);
- if (canUseSdk) {
- const handled = await sdkTimingBatchPersist(
- sdkChanges.filter((change): change is NonNullable<typeof change> => change !== null),
- sharedPath,
- sdkSession,
- {
- editHistory: { recordEdit },
- writeProjectFile,
- reloadPreview,
- domEditSaveTimestampRef,
- compositionPath: activeCompPath,
- readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),
- },
- { label: "Resize timeline clips", coalesceKey },
- );
- if (handled) return;
- }
+ const handledBySdk = await trySdkBatchPersist({
+ changes,
+ sdkChanges: changes.map((change) =>
+ change.element.hfId
+ ? {
+ hfId: change.element.hfId,
+ timingUpdate: { start: change.start, duration: change.duration },
+ }
+ : null,
+ ),
+ eligible: changes.every((change) => !resizeHasPlaybackStartAdjustment(change)),
+ needsExtension,
+ label: "Resize timeline clips",
+ coalesceKey,
+ });
+ if (handledBySdk) return;
await persistServerBatch(
projectId,
@@ -328,55 +343,43 @@ export function useTimelineGroupEditing({
})),
coalesceKey,
);
- await finishTimelineTimingFallback({
+ await finishGroupTimingGsapFallback({
+ projectId,
iframe: previewIframeRef.current,
- needsExtension,
- rootDurationSeconds: maxEnd,
reloadPreview,
- gsapMutation: () =>
- foldGsapMutationIntoHistory({
+ label: "Resize timeline clips",
+ errorLabel: "Failed to scale GSAP positions",
+ coalesceKey,
+ recordEdit,
+ activeCompPath,
+ changes,
+ resolveChangePath: (element) => targetPathFor(element, activeCompPath),
+ mutateChange: (change, changePath) => {
+ const domId = change.element.domId;
+ const timingChanged =
+ change.start !== change.element.start || change.duration !== change.element.duration;
+ if (!timingChanged || !domId) return null;
+ return scaleGsapPositions(
projectId,
- paths: changes.map((change) => targetPathFor(change.element, activeCompPath)),
- label: "Resize timeline clips",
- coalesceKey,
- recordEdit,
- gsapMutation: async () => {
- let mutated = false;
- for (const change of changes) {
- const domId = change.element.domId;
- const timingChanged =
- change.start !== change.element.start ||
- change.duration !== change.element.duration;
- if (!timingChanged || !domId) continue;
- const status = await scaleGsapPositions(
- projectId,
- targetPathFor(change.element, activeCompPath),
- domId,
- change.element.start,
- change.element.duration,
- change.start,
- change.duration,
- );
- mutated = mutated || status.mutated;
- }
- return { mutated };
- },
- }),
- onGsapError: (err) => console.error("[Timeline] Failed to scale GSAP positions", err),
+ changePath,
+ domId,
+ change.element.start,
+ change.element.duration,
+ change.start,
+ change.duration,
+ );
+ },
});
});
},
[
activeCompPath,
- domEditSaveTimestampRef,
enqueueGroupOperation,
persistServerBatch,
previewIframeRef,
- projectIdRef,
recordEdit,
reloadPreview,
- sdkSession,
- writeProjectFile,
+ trySdkBatchPersist,
],
);
diff --git a/packages/studio/src/player/components/PlayerControls.tsx b/packages/studio/src/player/components/PlayerControls.tsx
index 5df14ed537..dd32c1342c 100644
--- a/packages/studio/src/player/components/PlayerControls.tsx
+++ b/packages/studio/src/player/components/PlayerControls.tsx
@@ -9,10 +9,8 @@ import { Tooltip } from "../../components/ui";
import { ShortcutsPanel } from "./ShortcutsPanel";
import { SpeedMenu } from "./SpeedMenu";
import { useSeekBarDrag, resolveSeekPercent } from "./useSeekBarDrag";
-import { useState } from "react";
export { resolveSeekPercent };
-type TimeDisplayMode = "time" | "frame";
/* ── Icon sub-components ─────────────────────────────────────────── */
@@ -369,7 +367,8 @@ export const PlayerControls = memo(function PlayerControls({
const outPoint = usePlayerStore((s) => s.outPoint);
const setInPoint = usePlayerStore.getState().setInPoint;
const setOutPoint = usePlayerStore.getState().setOutPoint;
- const [timeDisplayMode, setTimeDisplayMode] = useState<TimeDisplayMode>("time");
+ const timeDisplayMode = usePlayerStore((s) => s.timeDisplayMode);
+ const setTimeDisplayMode = usePlayerStore.getState().setTimeDisplayMode;
const progressFillRef = useRef<HTMLDivElement>(null);
const progressThumbRef = useRef<HTMLDivElement>(null);
@@ -428,10 +427,11 @@ export const PlayerControls = memo(function PlayerControls({
return (
<div
+ // No own background/border: the transport blends into the preview
+ // panel's surface — buttons carry their own chrome.
className="px-4 py-2 flex flex-wrap items-center gap-x-2 gap-y-1"
aria-disabled={disabled || undefined}
style={{
- borderTop: "1px solid rgba(255,255,255,0.04)",
paddingBottom: "calc(0.5rem + env(safe-area-inset-bottom))",
}}
>
@@ -456,7 +456,7 @@ export const PlayerControls = memo(function PlayerControls({
>
<button
type="button"
- onClick={() => setTimeDisplayMode((m) => (m === "time" ? "frame" : "time"))}
+ onClick={() => setTimeDisplayMode(timeDisplayMode === "time" ? "frame" : "time")}
disabled={disabled}
className="font-mono text-[11px] tabular-nums flex-shrink-0 w-[118px] text-left transition-colors disabled:pointer-events-none hover:opacity-80"
style={{ color: "#A1A1AA", cursor: "pointer" }}
diff --git a/packages/studio/src/player/components/TimelineCanvas.tsx b/packages/studio/src/player/components/TimelineCanvas.tsx
index d4ae3b75f4..1dc8964835 100644
--- a/packages/studio/src/player/components/TimelineCanvas.tsx
+++ b/packages/studio/src/player/components/TimelineCanvas.tsx
@@ -20,6 +20,7 @@ import type { Rect } from "../../utils/marqueeGeometry";
import { TimelineClip } from "./TimelineClip";
import { TimelineLanes, type TimelineLaneBaseProps } from "./TimelineLanes";
import { renderClipChildren } from "./timelineClipChildren";
+import { useTimelineRevealClip } from "./useTimelineRevealClip";
interface TimelineCanvasProps extends TimelineLaneBaseProps {
major: number[];
@@ -41,6 +42,8 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvas
const { onResizeElement, onMoveElement, onToggleTrackHidden, onRazorSplit, onRazorSplitAll } =
useTimelineEditContextOptional();
const beatDragging = usePlayerStore((s) => s.beatDragging);
+ // Scroll a clip into view when the sidebar (asset card) requests a reveal.
+ useTimelineRevealClip(scrollRef);
const draggedElement = draggedClip?.element ?? null;
const activeDraggedElement =
draggedClip?.started === true && draggedElement
diff --git a/packages/studio/src/player/components/TimelineRuler.tsx b/packages/studio/src/player/components/TimelineRuler.tsx
index 73416fd003..1eb8b51440 100644
--- a/packages/studio/src/player/components/TimelineRuler.tsx
+++ b/packages/studio/src/player/components/TimelineRuler.tsx
@@ -1,6 +1,8 @@
import { memo } from "react";
import type { TimelineTheme } from "./timelineTheme";
import { GUTTER, RULER_H, formatTimelineTickLabel } from "./timelineLayout";
+import { usePlayerStore } from "../store/playerStore";
+import { secondsToFrame } from "../lib/time";
import type { MusicBeatAnalysis } from "@hyperframes/core/beats";
interface TimelineRulerProps {
@@ -26,6 +28,7 @@ export const TimelineRuler = memo(function TimelineRuler({
theme,
beatAnalysis,
}: TimelineRulerProps) {
+ const timeDisplayMode = usePlayerStore((s) => s.timeDisplayMode);
const beatTimes = beatAnalysis?.beatTimes ?? [];
const beatStrengths = beatAnalysis?.beatStrengths ?? [];
@@ -38,27 +41,13 @@ export const TimelineRuler = memo(function TimelineRuler({
return (
<>
- {/* Grid lines (major ticks + beat lines) — behind the tracks (background).
- Opaque track rows hide them; only the beat dots show on tracks. */}
+ {/* Background SVG — beat lines only; major-tick gridlines removed so only
+ the ruler's own small ticks mark intervals (no full-height lines). */}
<svg
className="absolute pointer-events-none"
style={{ left: GUTTER, width: trackContentWidth, zIndex: 0 }}
height={totalH}
>
- {major.map((t) => {
- const x = t * pps;
- return (
- <line
- key={`g-${t}`}
- x1={x}
- y1={RULER_H}
- x2={x}
- y2={totalH}
- stroke={theme.tickMinor}
- strokeWidth="1"
- />
- );
- })}
{showBeats &&
beatTimes.map((t, i) => {
const x = t * pps;
@@ -79,41 +68,58 @@ export const TimelineRuler = memo(function TimelineRuler({
})}
</svg>
- {/* Ruler. The bar fills the full panel width (canvas is min 100% wide);
- calc(100% - GUTTER) equals trackContentWidth when zoomed in and extends
- past the content when zoomed out. Ticks stay at composition coordinates. */}
+ {/* Ruler — sticky so the timestamps stay visible while the tracks scroll
+ vertically. Opaque background (plus the gutter corner block) so clips
+ scrolling underneath don't bleed through; z-index sits above the track
+ rows and drag overlays but below the playhead (z 100). */}
<div
- className="relative overflow-hidden"
- style={{
- height: RULER_H,
- marginLeft: GUTTER,
- width: `calc(100% - ${GUTTER}px)`,
- background: theme.gutterBackground,
- borderBottom: `1px solid ${theme.rulerBorder}`,
- }}
+ className="sticky top-0 flex"
+ style={{ height: RULER_H, width: GUTTER + trackContentWidth, zIndex: 70 }}
>
- {minor.map((t) => (
- <div key={`m-${t}`} className="absolute bottom-0" style={{ left: t * pps }}>
- <div className="w-px h-2" style={{ background: theme.tickMinor }} />
- </div>
- ))}
+ <div
+ className="sticky left-0 z-[12] flex-shrink-0"
+ style={{
+ width: GUTTER,
+ // Ruler corner uses the panel surface — same as the ruler strip itself.
+ background: theme.shellBackground,
+ borderRight: `1px solid ${theme.gutterBorder}`,
+ }}
+ />
+ <div
+ className="relative overflow-hidden"
+ style={{
+ height: RULER_H,
+ width: trackContentWidth,
+ // Ruler background = panel surface (#0A0A0B) — no bottom border,
+ // no tick lines (CapCut-style clean ruler, labels only).
+ background: theme.shellBackground,
+ }}
+ >
+ {minor.map((t) => (
+ <div key={`m-${t}`} className="absolute bottom-0" style={{ left: t * pps }}>
+ <div className="w-px h-2" style={{ background: theme.tickMinor }} />
+ </div>
+ ))}
- {major.map((t) => (
- <div key={`M-${t}`} className="absolute top-0" style={{ left: t * pps }}>
- <span
- className="absolute font-mono tabular-nums leading-none whitespace-nowrap"
- style={{
- color: theme.tickText,
- left: 5,
- top: 5,
- fontSize: 10,
- }}
- >
- {formatTimelineTickLabel(t, effectiveDuration, majorTickInterval)}
- </span>
- <div className="w-px" style={{ height: RULER_H, background: theme.tickMajor }} />
- </div>
- ))}
+ {major.map((t) => (
+ <div key={`M-${t}`} className="absolute top-0" style={{ left: t * pps }}>
+ <span
+ className="absolute font-mono tabular-nums leading-none whitespace-nowrap"
+ style={{
+ color: theme.tickText,
+ left: 5,
+ top: 5,
+ fontSize: 10,
+ }}
+ >
+ {timeDisplayMode === "frame"
+ ? secondsToFrame(t)
+ : formatTimelineTickLabel(t, effectiveDuration, majorTickInterval)}
+ </span>
+ <div className="w-px" style={{ height: RULER_H, background: theme.tickMajor }} />
+ </div>
+ ))}
+ </div>
</div>
</>
);
diff --git a/packages/studio/src/player/components/timelineClipDragCommit.test.ts b/packages/studio/src/player/components/timelineClipDragCommit.test.ts
index f158762fcf..7cc9123553 100644
--- a/packages/studio/src/player/components/timelineClipDragCommit.test.ts
+++ b/packages/studio/src/player/components/timelineClipDragCommit.test.ts
@@ -283,8 +283,9 @@ describe("commitDraggedClipMove", () => {
const map = editMap(onMoveElements.mock.calls[0][0]);
// Lanes are contiguous and distinct (no two overlapping clips share a lane).
expect(new Set([map.a.track, map.b.track, map.c.track])).toEqual(new Set([0, 1, 2]));
- // The z-aware normalization may reverse the authored lane numbers, but the
- // insert must still leave three distinct, contiguous visual lanes.
+ expect(map.a.track).toBe(0); // above the insert → unchanged
+ expect(map.c.track).toBe(1); // dragged clip lands on the new lane
+ expect(map.b.track).toBe(2); // at/below the insert → +1 shift
});
describe("lane ↔ stacking sync", () => {
@@ -440,9 +441,9 @@ describe("commitDraggedClipMove", () => {
drag(elements[2], { previewStart: 30, previewTrack: 1, insertRow: 0 }),
[0, 1],
);
- // Non-overlapping clips retain their authored/z-derived ordering; a lane
- // gesture cannot invent a DOM stacking relationship where none overlaps.
- expect(lane.dragged).toBe(2);
+ expect(lane.dragged).toBe(0); // aimed at the very top
+ expect(lane.top).toBe(1);
+ expect(lane.mid).toBe(2);
});
it("BETWEEN-insert of a non-overlapping clip lands it between its neighbours", async () => {
@@ -453,8 +454,8 @@ describe("commitDraggedClipMove", () => {
[0, 1, 2],
);
expect(lane.a).toBe(0);
- expect(lane.b).toBe(1);
- expect(lane.x).toBe(2);
+ expect(lane.x).toBe(1); // between a and b, as aimed
+ expect(lane.b).toBe(2);
});
it("TOP-insert clears a NON-overlapping clip that currently tops the timeline", async () => {
@@ -466,7 +467,7 @@ describe("commitDraggedClipMove", () => {
drag(elements[2], { previewStart: 10, previewTrack: 2, insertRow: 0 }),
[0, 1, 2],
);
- expect(lane.X).toBe(1); // X reorders against overlapping M, not disjoint T
+ expect(lane.X).toBe(0); // aimed top, cleared the non-overlapping T
});
it("dragging X among overlapping neighbours preserves the RELATIVE order of the others (symptom 2)", async () => {
diff --git a/packages/studio/src/player/components/timelineRevealScroll.test.ts b/packages/studio/src/player/components/timelineRevealScroll.test.ts
new file mode 100644
index 0000000000..932124ec26
--- /dev/null
+++ b/packages/studio/src/player/components/timelineRevealScroll.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from "vitest";
+import {
+ computeRevealScroll,
+ REVEAL_SCROLL_PADDING_PX,
+ type RevealScrollInput,
+} from "./timelineRevealScroll";
+
+/** A 1000×400 viewport with a 32px sticky gutter and 24px sticky ruler. */
+function makeInput(overrides: Partial<RevealScrollInput> = {}): RevealScrollInput {
+ return {
+ scrollLeft: 0,
+ scrollTop: 0,
+ viewportWidth: 1000,
+ viewportHeight: 400,
+ clipLeft: 100,
+ clipRight: 200,
+ clipTop: 100,
+ clipBottom: 148,
+ stickyLeft: 32,
+ stickyTop: 24,
+ allowHorizontal: true,
+ ...overrides,
+ };
+}
+
+describe("computeRevealScroll", () => {
+ it("returns null on both axes when the clip is fully visible", () => {
+ expect(computeRevealScroll(makeInput())).toEqual({ left: null, top: null });
+ });
+
+ it("scrolls right minimally when the clip end is past the right edge", () => {
+ const result = computeRevealScroll(makeInput({ clipLeft: 1500, clipRight: 1600 }));
+ // Clip end lands padding px inside the right edge.
+ expect(result.left).toBe(1600 - 1000 + REVEAL_SCROLL_PADDING_PX);
+ expect(result.top).toBeNull();
+ });
+
+ it("scrolls left when the clip start is hidden (including under the sticky gutter)", () => {
+ const result = computeRevealScroll(
+ makeInput({ scrollLeft: 500, clipLeft: 510, clipRight: 610 }),
+ );
+ // clipLeft 510 sits under the 32px sticky gutter (window starts at 500+32+pad).
+ expect(result.left).toBe(510 - 32 - REVEAL_SCROLL_PADDING_PX);
+ });
+
+ it("aligns the start edge when the clip is wider than the viewport", () => {
+ const result = computeRevealScroll(makeInput({ clipLeft: 2000, clipRight: 4000 }));
+ expect(result.left).toBe(2000 - 32 - REVEAL_SCROLL_PADDING_PX);
+ });
+
+ it("never returns a negative scroll target", () => {
+ const result = computeRevealScroll(
+ makeInput({
+ scrollLeft: 300,
+ clipLeft: 10,
+ clipRight: 60,
+ scrollTop: 200,
+ clipTop: 4,
+ clipBottom: 20,
+ }),
+ );
+ expect(result.left).toBe(0);
+ expect(result.top).toBe(0);
+ });
+
+ it("suppresses horizontal scroll when allowHorizontal is false (fit zoom)", () => {
+ const result = computeRevealScroll(
+ makeInput({
+ allowHorizontal: false,
+ clipLeft: 1500,
+ clipRight: 1600,
+ clipTop: 700,
+ clipBottom: 748,
+ }),
+ );
+ expect(result.left).toBeNull();
+ // Vertical reveal still happens.
+ expect(result.top).toBe(748 - 400 + REVEAL_SCROLL_PADDING_PX);
+ });
+
+ it("scrolls up when the clip lane is hidden under the sticky ruler", () => {
+ const result = computeRevealScroll(
+ makeInput({ scrollTop: 200, clipTop: 210, clipBottom: 258 }),
+ );
+ // clipTop 210 sits under the 24px sticky ruler (window starts at 200+24+pad).
+ expect(result.top).toBe(210 - 24 - REVEAL_SCROLL_PADDING_PX);
+ });
+
+ it("scrolls down minimally when the clip lane is below the viewport", () => {
+ const result = computeRevealScroll(makeInput({ clipTop: 500, clipBottom: 548 }));
+ expect(result.top).toBe(548 - 400 + REVEAL_SCROLL_PADDING_PX);
+ expect(result.left).toBeNull();
+ });
+});
diff --git a/packages/studio/src/player/components/timelineRevealScroll.ts b/packages/studio/src/player/components/timelineRevealScroll.ts
new file mode 100644
index 0000000000..05818f8778
--- /dev/null
+++ b/packages/studio/src/player/components/timelineRevealScroll.ts
@@ -0,0 +1,88 @@
+/**
+ * Pure scroll-target math for revealing a timeline clip inside the timeline's
+ * scroll container (the overflow div in Timeline.tsx).
+ *
+ * Coordinates are content-space: a clip edge measured from the scroll
+ * container's content origin (rect delta + current scroll offset). The visible
+ * window on each axis is reduced by the sticky chrome that occludes it — the
+ * track gutter on the left (GUTTER) and the ruler on top (RULER_H) — so a clip
+ * "hidden" under the sticky gutter still counts as off-screen.
+ *
+ * Scrolls minimally: an axis already fully visible returns null for that axis;
+ * otherwise the nearest edge is brought just inside the window (plus padding).
+ * A clip larger than the window aligns its start edge. Pure — unit-tested.
+ */
+
+export interface RevealScrollInput {
+ scrollLeft: number;
+ scrollTop: number;
+ /** Scroll container clientWidth / clientHeight. */
+ viewportWidth: number;
+ viewportHeight: number;
+ /** Clip bounds in content-space (relative to the scroll content origin). */
+ clipLeft: number;
+ clipRight: number;
+ clipTop: number;
+ clipBottom: number;
+ /** Width of the sticky left gutter occluding the viewport's left edge. */
+ stickyLeft: number;
+ /** Height of the sticky ruler occluding the viewport's top edge. */
+ stickyTop: number;
+ /** False in "fit" zoom mode, where horizontal scrolling is disabled. */
+ allowHorizontal: boolean;
+}
+
+export interface RevealScrollTarget {
+ /** Target scrollLeft, or null when the horizontal axis needs no scroll. */
+ left: number | null;
+ /** Target scrollTop, or null when the vertical axis needs no scroll. */
+ top: number | null;
+}
+
+/** Breathing room between the revealed clip edge and the window edge. */
+export const REVEAL_SCROLL_PADDING_PX = 12;
+
+/**
+ * Minimal scroll on one axis to bring [start, end] inside the visible window
+ * [scroll + stickyStart, scroll + viewport], with padding. Returns null when
+ * the range is already fully visible.
+ */
+function revealAxis(
+ scroll: number,
+ viewport: number,
+ stickyStart: number,
+ start: number,
+ end: number,
+): number | null {
+ const windowStart = scroll + stickyStart + REVEAL_SCROLL_PADDING_PX;
+ const windowEnd = scroll + viewport - REVEAL_SCROLL_PADDING_PX;
+ if (start >= windowStart && end <= windowEnd) return null;
+ const windowSize = windowEnd - windowStart;
+ // Oversized range (or start hidden): align the start edge to the window start.
+ if (end - start > windowSize || start < windowStart) {
+ return Math.max(0, start - stickyStart - REVEAL_SCROLL_PADDING_PX);
+ }
+ // Only the end is clipped: pull it just inside the window's far edge.
+ return Math.max(0, end - viewport + REVEAL_SCROLL_PADDING_PX);
+}
+
+export function computeRevealScroll(input: RevealScrollInput): RevealScrollTarget {
+ return {
+ left: input.allowHorizontal
+ ? revealAxis(
+ input.scrollLeft,
+ input.viewportWidth,
+ input.stickyLeft,
+ input.clipLeft,
+ input.clipRight,
+ )
+ : null,
+ top: revealAxis(
+ input.scrollTop,
+ input.viewportHeight,
+ input.stickyTop,
+ input.clipTop,
+ input.clipBottom,
+ ),
+ };
+}
diff --git a/packages/studio/src/player/components/timelineZones.test.ts b/packages/studio/src/player/components/timelineZones.test.ts
index 4e446b0568..02e721379e 100644
--- a/packages/studio/src/player/components/timelineZones.test.ts
+++ b/packages/studio/src/player/components/timelineZones.test.ts
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vitest";
import type { TimelineElement } from "../store/playerStore";
import { classifyZone, normalizeToZones } from "./timelineZones";
-import { computeStackingPatches, type StackingElement } from "./timelineStackingSync";
function el(id: string, tag: string, track: number, duration = 2): TimelineElement {
return { id, tag, start: 0, duration, track };
@@ -29,16 +28,6 @@ function expectZoningIdempotent(input: TimelineElement[]): void {
for (const e of once) expect(trackOf(twice, e.id)).toBe(e.track);
}
-/** The exact qa-clean live repro (array order = DOM order); fresh objects per call. */
-function qaCleanRepro(): TimelineElement[] {
- return [
- zClip("blue-logo", 6.37, 3, 0, 3, "img"),
- zClip("ralu", 6.37, 3, 0, 0, "img"),
- zClip("black-logo", 11.92, 3, 1, 1, "img"),
- zClip("video", 0.84, 20, 3, 2, "video"),
- ];
-}
-
describe("classifyZone", () => {
it("audio → audio; video / image / everything else → visual", () => {
expect(classifyZone(el("m", "audio", 3))).toBe("audio");
@@ -66,52 +55,77 @@ describe("classifyZone", () => {
});
});
-describe("normalizeToZones", () => {
- it("orders visual (top) → audio (bottom); equal-z overlap stacks by DOM order", () => {
- // img and vid are both z=0, start=0 → they OVERLAP in time. CSS paints
- // equal-z siblings by DOM order (later paints on top), so the later-in-array
- // `vid` must own the upper lane. (Was: pinned img=0/vid=1 to authored order,
- // which contradicts the canvas — updated for per-clip DOM-order tie-break.)
+describe("normalizeToZones — CapCut-stable lanes follow the track-index (never z)", () => {
+ it("orders visual lanes by authored track-index (ascending), audio at the bottom", () => {
+ // img (track 0), vid (track 2), mus (audio, track 5). Lanes follow the track
+ // index: the LOWER visual track owns the upper lane. z is irrelevant (absent).
const out = normalizeToZones([
el("img", "img", 0),
el("vid", "video", 2),
el("mus", "audio", 5),
]);
- expect(trackOf(out, "vid")).toBe(0); // later in DOM → paints on top → upper lane
- expect(trackOf(out, "img")).toBe(1); // earlier in DOM → below
- expect(trackOf(out, "mus")).toBe(2); // audio (bottom)
+ expect(trackOf(out, "img")).toBe(0); // track 0 → top lane
+ expect(trackOf(out, "vid")).toBe(1); // track 2 → below it
+ expect(trackOf(out, "mus")).toBe(2); // audio → bottom
});
- it("keeps all visual lanes together on top; equal-z overlap stacks by DOM order", () => {
- // All three z=0, start=0 → mutually overlapping. DOM order (later on top)
- // decides the stack: v3 (last) top, then i1, then v0. (Was: pinned to authored
- // order v0=0/i1=1/v3=2, which the canvas contradicts for overlapping equal-z.)
- const out = normalizeToZones([el("v0", "video", 0), el("i1", "img", 1), el("v3", "video", 3)]);
- expect(trackOf(out, "v3")).toBe(0);
- expect(trackOf(out, "i1")).toBe(1);
- expect(trackOf(out, "v0")).toBe(2);
+ it("compacts sparse visual track-indexes to contiguous lanes, preserving ascending order", () => {
+ // Distinct authored tracks 0, 3, 7 → three adjacent lanes in the same order.
+ const out = normalizeToZones([el("a", "video", 7), el("b", "img", 0), el("c", "video", 3)]);
+ expect(trackOf(out, "b")).toBe(0); // track 0
+ expect(trackOf(out, "c")).toBe(1); // track 3
+ expect(trackOf(out, "a")).toBe(2); // track 7
+ });
+
+ it("drops audio below the visual lanes even when it holds a LOWER authored index", () => {
+ // Audio authored at track 0, video at track 5 — audio must still sink below.
+ const out = normalizeToZones([zClip("a", 0, 10, 0, 0, "audio"), zClip("v", 0, 10, 5, 0)]);
+ expect(trackOf(out, "v")).toBe(0); // visual on top
+ expect(trackOf(out, "a")).toBe(1); // audio below, despite its lower track index
});
it("drops audio below the visual lanes even when sharing a track index", () => {
const out = normalizeToZones([el("v", "video", 0), el("a", "audio", 0)]);
- expect(trackOf(out, "v")).toBe(0); // visual
- expect(trackOf(out, "a")).toBe(1); // audio, below
+ expect(trackOf(out, "v")).toBe(0);
+ expect(trackOf(out, "a")).toBe(1);
});
- it("groups multiple audio tracks at the bottom preserving relative order", () => {
- const out = normalizeToZones([el("v", "video", 0), el("a1", "audio", 1), el("a2", "audio", 4)]);
+ it("groups multiple audio tracks at the bottom, ordered by their track index", () => {
+ const out = normalizeToZones([el("v", "video", 0), el("a2", "audio", 4), el("a1", "audio", 1)]);
expect(trackOf(out, "v")).toBe(0);
- expect(trackOf(out, "a1")).toBe(1);
+ expect(trackOf(out, "a1")).toBe(1); // audio track 1 above audio track 4
expect(trackOf(out, "a2")).toBe(2);
});
+ it("ignores z-index entirely — a high-z clip does NOT jump above a lower-track clip", () => {
+ // lo on track 0 with z=1; hi on track 1 with z=99. They fully overlap in time.
+ // The old z-rank pack lifted hi above lo; the CapCut rule keeps lane = track.
+ const out = normalizeToZones([zClip("lo", 0, 10, 0, 1), zClip("hi", 0, 10, 1, 99)]);
+ expect(trackOf(out, "lo")).toBe(0); // track 0 stays on top
+ expect(trackOf(out, "hi")).toBe(1); // higher z does NOT lift it
+ });
+
+ it("ignores z-index across authored tracks (scattered z, lanes still by track)", () => {
+ const out = normalizeToZones([
+ zClip("t0", 0, 10, 0, 3),
+ zClip("t1", 0, 10, 1, 26),
+ zClip("t2", 0, 10, 2, 0),
+ ]);
+ expect(trackOf(out, "t0")).toBe(0);
+ expect(trackOf(out, "t1")).toBe(1);
+ expect(trackOf(out, "t2")).toBe(2);
+ });
+
+ it("sequential (non-overlapping) same-track clips share a lane", () => {
+ const out = normalizeToZones([zClip("a", 0, 5, 0, 1), zClip("c", 6, 3, 0, 9)]);
+ expect(trackOf(out, "a")).toBe(0);
+ expect(trackOf(out, "c")).toBe(0); // shares the lane regardless of z
+ });
+
it("returns the same array (identity) when already zoned", () => {
- // A fixed-point layout: the two overlapping equal-z visual clips are already
- // in DOM-order-consistent lanes (later-in-array `v` on the upper lane 0), so
- // re-zoning is a no-op and the SAME array reference comes back. (Was: i=0/v=1,
- // which the new per-clip DOM-order pack would flip — so it wasn't a fixed
- // point under the corrected canvas semantics; swapped to the stable order.)
- const input = [el("v", "video", 1), el("i", "img", 0), el("a", "audio", 2)];
+ // i on track 0, v on track 1, a (audio) on track 2 — already contiguous, visual
+ // above audio, so re-zoning is a no-op and the SAME reference comes back.
+ const input = [el("i", "img", 0), el("v", "video", 1), el("a", "audio", 2)];
expect(normalizeToZones(input)).toBe(input);
});
@@ -125,301 +139,99 @@ describe("normalizeToZones", () => {
expectZoningIdempotent(input);
});
- it("splits time-overlapping clips on one track onto separate lanes (no visible overlap)", () => {
+ it("re-derives identical lanes from fresh objects carrying the same tracks (reload-stable)", () => {
+ const build = (): TimelineElement[] => [
+ zClip("hi", 0, 10, 0, 9),
+ zClip("lo", 0, 10, 1, 1),
+ zClip("mid", 3, 5, 2, 5),
+ ];
+ const first = normalizeToZones(build());
+ const second = normalizeToZones(build());
+ for (const e of first) expect(trackOf(second, e.id)).toBe(e.track);
+ });
+});
+
+describe("normalizeToZones — legacy overlap spill (display-only, deterministic)", () => {
+ it("splits time-overlapping SAME-track clips onto adjacent sub-lanes (no visible overlap)", () => {
+ // a [0,5), b [2,7) overlaps a, c [6,9) sequential — all authored on track 1.
+ // The editor forbids per-track overlap, but a legacy file can carry it; the
+ // spill orders by stable id (a, b, c) and first-fits: a→lane0, b overlaps a→
+ // lane1, c fits back on lane0 (no overlap with a).
const clip = (id: string, start: number, duration: number): TimelineElement => ({
id,
tag: "video",
start,
duration,
- track: 1, // all authored on the SAME track, some overlapping in time
+ track: 1,
});
- // a [0,5), b [2,7) overlaps a, c [6,9) fits after a. All equal-z (absent).
- // Per-clip pack (DOM-order tie-break): c is last in DOM so it places on the
- // top lane 0; b overlaps c and lands on lane 1; a overlaps b (and is earlier
- // in DOM than b, so it must paint BELOW b) → lane 2. a can NOT drop onto c's
- // lane 0 even though it doesn't overlap c, because that would place a ABOVE b
- // in lane order while a paints below b — the canvas-correct constraint the old
- // whole-track packer ignored (it shared a/c on lane 0, contradicting paint).
const out = normalizeToZones([clip("a", 0, 5), clip("b", 2, 5), clip("c", 6, 3)]);
- expect(trackOf(out, "c")).toBe(0); // last in DOM → top lane
- expect(trackOf(out, "b")).toBe(1); // overlaps c → below it
- expect(trackOf(out, "a")).toBe(2); // paints below b (earlier DOM, equal z) → lane below b
-
- // No two time-overlapping clips share a lane (the real NLE invariant).
+ expect(trackOf(out, "a")).toBe(0);
+ expect(trackOf(out, "b")).toBe(1); // overlaps a → adjacent sub-lane
+ expect(trackOf(out, "c")).toBe(0); // sequential to a → shares lane 0
+ // No two time-overlapping clips share a lane.
expect(trackOf(out, "a")).not.toBe(trackOf(out, "b"));
- expect(trackOf(out, "b")).not.toBe(trackOf(out, "c"));
-
// Idempotent: re-laying the split result changes nothing.
const twice = normalizeToZones(out);
for (const e of out) expect(trackOf(twice, e.id)).toBe(e.track);
});
-});
-describe("normalizeToZones — reverse z→lane mapping", () => {
- it("orders overlapping same-zone clips by z: higher z → higher (upper) lane", () => {
- // lo (z=1) and hi (z=9) fully overlap in time on the same authored track.
- const out = normalizeToZones([zClip("lo", 0, 10, 0, 1), zClip("hi", 0, 10, 0, 9)]);
- expect(trackOf(out, "hi")).toBe(0); // higher z → upper lane (top)
- expect(trackOf(out, "lo")).toBe(1); // lower z → below
- });
-
- it("orders three overlapping clips strictly by descending z", () => {
- const out = normalizeToZones([
- zClip("mid", 0, 10, 0, 5),
- zClip("top", 0, 10, 0, 8),
- zClip("bot", 0, 10, 0, 2),
- ]);
- expect(trackOf(out, "top")).toBe(0);
- expect(trackOf(out, "mid")).toBe(1);
- expect(trackOf(out, "bot")).toBe(2);
- });
-
- it("does NOT reorder non-overlapping (sequential) clips by z — they share a lane", () => {
- // a [0,5) z=1 then c [6,9) z=9 — no time overlap, so z is irrelevant.
- const out = normalizeToZones([zClip("a", 0, 5, 0, 1), zClip("c", 6, 3, 0, 9)]);
- expect(trackOf(out, "a")).toBe(0);
- expect(trackOf(out, "c")).toBe(0); // shares the lane regardless of higher z
- });
-
- it("leaves the audio zone unaffected by z", () => {
- const out = normalizeToZones([
- zClip("v", 0, 10, 0, 1),
- zClip("m1", 0, 10, 1, 99, "audio"),
- zClip("m2", 0, 10, 1, 0, "audio"),
- ]);
- // Two overlapping audio clips split onto lanes below the visual clip; their
- // relative z does not lift one above a visual clip.
- expect(trackOf(out, "v")).toBe(0);
- expect(trackOf(out, "m1")).toBeGreaterThan(trackOf(out, "v"));
- expect(trackOf(out, "m2")).toBeGreaterThan(trackOf(out, "v"));
- });
-
- it("treats missing / auto z as 0 (undefined z clip sinks below a positive-z overlap)", () => {
- const out = normalizeToZones([
- { id: "noz", tag: "video", start: 0, duration: 10, track: 0 }, // no zIndex
- zClip("pos", 0, 10, 0, 3),
- ]);
- expect(trackOf(out, "pos")).toBe(0); // z=3 → upper
- expect(trackOf(out, "noz")).toBe(1); // absent z ⇒ 0 → below
- });
-
- it("tie-breaks equal-z overlapping clips on the STABLE id, not the mutated lane", () => {
- // Equal z + full overlap: order must be deterministic (id asc) and survive
- // re-normalization — the historical oscillation bug tie-broke on the track.
+ it("spills two fully-overlapping same-track clips by stable id (a above b)", () => {
const out = normalizeToZones([zClip("b", 0, 10, 0, 5), zClip("a", 0, 10, 0, 5)]);
expect(trackOf(out, "a")).toBe(0); // "a" < "b"
expect(trackOf(out, "b")).toBe(1);
+ // Survives re-normalization (stable id tie-break, never the mutated lane).
const twice = normalizeToZones(out);
for (const e of out) expect(trackOf(twice, e.id)).toBe(e.track);
});
-
- it("FIXED POINT: normalizeToZones(normalizeToZones(x)) === normalizeToZones(x) with z present", () => {
- const input = [
- zClip("hi", 0, 10, 0, 9),
- zClip("lo", 0, 10, 0, 1),
- zClip("mid", 2, 6, 0, 5),
- zClip("seq", 12, 4, 0, 7),
- zClip("music", 0, 16, 1, 3, "audio"),
- ];
- expectZoningIdempotent(input);
- });
-
- it("reload simulation: re-deriving lanes from the SAME z values yields identical lanes", () => {
- // Simulate two independent discovery passes producing fresh element objects
- // carrying the same z — lane assignment must be stable across reloads.
- const build = (): TimelineElement[] => [
- zClip("hi", 0, 10, 0, 9),
- zClip("lo", 0, 10, 0, 1),
- zClip("mid", 3, 5, 0, 5),
- ];
- const first = normalizeToZones(build());
- const second = normalizeToZones(build());
- for (const e of first) expect(trackOf(second, e.id)).toBe(e.track);
- });
});
-describe("normalizeToZones — cross-track z→lane (real qa-clean shape)", () => {
- // Derived from /tmp/hf-dnd-qa/qa-clean: a full-length video on authored track 0
- // (z=0), two logo SVGs on track 1 (z=26 and z=0), an icon on track 3 (z=5), and
- // background music on track 2. In the canvas the z=26 / z=5 icons paint ON TOP of
- // the z=0 video; the timeline must agree — the higher-z tracks sit on upper lanes.
- const realProject = (): TimelineElement[] => [
- zClip("ralu", 6.14, 3, 3, 5, "img"),
- zClip("video", 1, 20, 0, 0, "video"),
- zClip("blueLogo", 5.93, 3, 1, 26, "img"),
- zClip("blackLogo", 1, 3, 1, 0, "img"),
- zClip("music", 8.93, 8, 2, 0, "audio"),
+describe("normalizeToZones — legacy file with scattered z (requirement 6)", () => {
+ // Mirrors /tmp/hf-fixwave/userproj/index.html: many visual clips on contiguous
+ // authored tracks (0..17) each carrying an unrelated, scattered inline z-index,
+ // and audio on the highest tracks (18..). The display must follow the
+ // track-index, NOT the z, and a well-formed (contiguous, audio-last) legacy file
+ // must not be re-laned at all — normalize is the identity.
+ const legacy = (): TimelineElement[] => [
+ zClip("sub-0", 3, 1.15, 0, 0, "div"), // no explicit z (0)
+ zClip("cap-hit", 4.51, 1.73, 3, 26, "div"), // scattered z
+ zClip("cap-send", 5.85, 1.27, 4, 25, "div"),
+ zClip("avatar", 6.4, 1.148, 1, 26),
+ zClip("v-opener", 0, 3, 15, 12),
+ zClip("v-letters", 30.08, 4.39, 5, 25),
+ zClip("music", 3, 42.95, 18, 10, "audio"),
+ zClip("vo", 3.2, 10.3, 19, 4, "audio"),
];
- it("stacks a higher-z track ABOVE a lower-z track on a different authored track", () => {
- const out = normalizeToZones(realProject());
- // Track 1 (max z 26) tops the visual zone, then track 3 (z 5), then track 0 (z 0).
- expect(trackOf(out, "blueLogo")).toBe(0);
- expect(trackOf(out, "blackLogo")).toBe(0); // sequential to blueLogo → shares lane
- expect(trackOf(out, "ralu")).toBe(1);
- expect(trackOf(out, "video")).toBe(2);
- // Audio stays at the very bottom regardless of its authored track index.
- expect(trackOf(out, "music")).toBe(3);
- });
-
- it("the video (z=0) no longer sits above the z=26 / z=5 icons — canvas & timeline agree", () => {
- const out = normalizeToZones(realProject());
- expect(trackOf(out, "video")).toBeGreaterThan(trackOf(out, "blueLogo"));
- expect(trackOf(out, "video")).toBeGreaterThan(trackOf(out, "ralu"));
- });
-
- it("is idempotent on the real-project shape (no lane drift on re-discovery)", () => {
- const once = normalizeToZones(realProject());
- const twice = normalizeToZones(once);
- for (const e of once) expect(trackOf(twice, e.id)).toBe(e.track);
- });
-
- it("re-derives identical lanes from fresh objects carrying the same z (reload-stable)", () => {
- const first = normalizeToZones(realProject());
- const second = normalizeToZones(realProject());
- for (const e of first) expect(trackOf(second, e.id)).toBe(e.track);
- });
-
- it("all-equal-z overlapping clips stack by DOM order (later on top), lanes contiguous", () => {
- // Was: "keeps ascending authored track order when all tracks share z" — that
- // pinned t0=0/t1=1/t3=2 to the authored track index. But these three all
- // start at 0 and OVERLAP, all z=0, so CSS paints them by DOM order: t3 (last)
- // on top. The per-clip pack now reflects that (t3 lane 0, then t1, then t0),
- // which is what the canvas actually shows. Lanes stay contiguous 0..2.
- const out = normalizeToZones([
- zClip("t0", 0, 2, 0, 0),
- zClip("t1", 0, 2, 1, 0),
- zClip("t3", 0, 2, 3, 0),
- ]);
- expect(trackOf(out, "t3")).toBe(0); // last in DOM → paints on top
- expect(trackOf(out, "t1")).toBe(1);
- expect(trackOf(out, "t0")).toBe(2);
- });
-});
-
-describe("normalizeToZones — EXACT qa-clean repro (per-clip constrained pack)", () => {
- // The live repro from /tmp/hf-dnd-qa/qa-clean/index.html:
- // blue-logo authored track 0, z=3, 6.37–9.37
- // ralu image authored track 0, z=0, 6.37–9.37 (shares track 0 with blue-logo)
- // black-logo authored track 1, z=1, 11.92–14.92
- // video authored track 3, z=2, 0.84–20.84
- // Canvas truth: video (z=2) covers ralu (z=0). The OLD whole-track packer
- // ordered track 0 by its MAX z (3, from blue-logo), so ralu rode above the
- // z=2 video — the timeline↔canvas contradiction. Array order below = DOM order.
-
- it("ACCEPTANCE: lane order top→bottom is blue-logo, video, black-logo, ralu", () => {
- const out = normalizeToZones(qaCleanRepro());
- expect(trackOf(out, "blue-logo")).toBe(0); // z=3 → top
- expect(trackOf(out, "video")).toBe(1); // z=2, overlaps blue-logo → below it
- expect(trackOf(out, "black-logo")).toBe(2); // z=1, overlaps video (11.92–14.92 ∩ 0.84–20.84)
- expect(trackOf(out, "ralu")).toBe(3); // z=0, overlaps blue-logo AND video → bottom
- });
-
- it("REGRESSION: a low-z clip must not ride its authored trackmate's high z above a clip that covers it", () => {
- const out = normalizeToZones(qaCleanRepro());
- // ralu (z=0) shares authored track 0 with blue-logo (z=3) but must sink BELOW
- // the video (z=2) that overlaps and paints over it — the whole-track bug.
- expect(trackOf(out, "ralu")).toBeGreaterThan(trackOf(out, "video"));
- // black-logo (z=1) below video (z=2) because they overlap in time.
- expect(trackOf(out, "black-logo")).toBeGreaterThan(trackOf(out, "video"));
- });
-
- it("FIXED POINT: running the NEW pack on its own output changes nothing", () => {
- const once = normalizeToZones(qaCleanRepro());
- const twice = normalizeToZones(once);
- for (const e of once) expect(trackOf(twice, e.id)).toBe(e.track);
- // And a third pass, to be sure convergence is genuine.
- const thrice = normalizeToZones(twice);
- for (const e of twice) expect(trackOf(thrice, e.id)).toBe(e.track);
- });
-});
-
-describe("z ↔ lane round-trip convergence (both directions agree)", () => {
- // Project a normalized TimelineElement onto the StackingElement view the
- // forward (lane→z) mapping reasons over.
- const toStacking = (els: TimelineElement[]): StackingElement[] =>
- els.map((e, domIndex) => ({
- key: e.key ?? e.id,
- start: e.start,
- duration: e.duration,
- track: e.track,
- zIndex: Number.isFinite(e.zIndex) ? (e.zIndex as number) : 0,
- isAudio: classifyZone(e) === "audio",
- domIndex,
- }));
-
- it("lane-move → z patch → re-discovery orders lanes by that same z → identical lanes (no oscillation)", () => {
- // Two fully-overlapping visual clips. Authored: a below (z=1), b above (z=5).
- const authored: TimelineElement[] = [zClip("a", 0, 10, 0, 1), zClip("b", 0, 10, 0, 5)];
- const normalized = normalizeToZones(authored);
- // z→lane placed b (z=5) on the upper lane 0, a on lane 1.
- expect(trackOf(normalized, "b")).toBe(0);
- expect(trackOf(normalized, "a")).toBe(1);
-
- // USER lane-move: drag a to the TOP (lane 0) and push b down (lane 1).
- const afterMove = normalized.map((e) =>
- e.id === "a" ? { ...e, track: 0 } : e.id === "b" ? { ...e, track: 1 } : e,
- );
-
- // FORWARD: a lane-move writes the minimal z patch for the edited clip.
- const patches = computeStackingPatches(toStacking(afterMove), ["a"]);
- expect(patches).toEqual([{ key: "a", zIndex: 6 }]); // lifted above b (5)
-
- // Apply the z patch back onto the elements (what handleDomZIndexReorderCommit
- // persists; next discovery re-reads it as TimelineElement.zIndex).
- const rediscovered = afterMove.map((e) => {
- const p = patches.find((pp) => pp.key === (e.key ?? e.id));
- return p ? { ...e, zIndex: p.zIndex } : e;
- });
-
- // REVERSE: re-normalize from the new z. a (z=6) must now own the upper lane —
- // the same lane the user moved it to. Directions converge, they do not fight.
- const renormalized = normalizeToZones(rediscovered);
- expect(trackOf(renormalized, "a")).toBe(0);
- expect(trackOf(renormalized, "b")).toBe(1);
-
- // FIXED POINT: forward on the converged state produces NO further patch, and
- // reverse is idempotent — the round-trip is stable.
- expect(computeStackingPatches(toStacking(renormalized), ["a"])).toEqual([]);
- const twice = normalizeToZones(renormalized);
- for (const e of renormalized) expect(trackOf(twice, e.id)).toBe(e.track);
+ it("lanes follow the track-index, not the scattered z", () => {
+ const out = normalizeToZones(legacy());
+ // Visual tracks 0,1,3,4,5,15 compact to lanes 0..5 in ascending track order —
+ // z (0,26,25,26,12,25) is ignored.
+ expect(trackOf(out, "sub-0")).toBe(0); // track 0
+ expect(trackOf(out, "avatar")).toBe(1); // track 1
+ expect(trackOf(out, "cap-hit")).toBe(2); // track 3
+ expect(trackOf(out, "cap-send")).toBe(3); // track 4
+ expect(trackOf(out, "v-letters")).toBe(4); // track 5
+ expect(trackOf(out, "v-opener")).toBe(5); // track 15
+ // Audio stays below every visual lane.
+ expect(trackOf(out, "music")).toBe(6);
+ expect(trackOf(out, "vo")).toBe(7);
+ // The z=26 caption does NOT ride above the z=0 subtitle on track 0.
+ expect(trackOf(out, "cap-hit")).toBeGreaterThan(trackOf(out, "sub-0"));
+ });
+
+ it("does not rewrite a well-formed (contiguous, audio-last) legacy set — identity", () => {
+ // Same shape but authored tracks already contiguous 0..7 with audio last.
+ const input = [
+ zClip("a", 0, 3, 0, 12),
+ zClip("b", 0, 3, 1, 26),
+ zClip("c", 0, 3, 2, 3),
+ zClip("m", 0, 3, 3, 9, "audio"),
+ ];
+ // Every clip already sits on its track-index lane, so normalize is a no-op.
+ expect(normalizeToZones(input)).toBe(input);
});
- it("qa-clean: drag video BELOW ralu → z patch → re-pack keeps it below, no oscillation", () => {
- // EXACT repro fixture (array order = DOM order).
- const normalized = normalizeToZones(qaCleanRepro());
- // Baseline lanes: blue-logo 0, video 1, black-logo 2, ralu 3.
- expect(trackOf(normalized, "video")).toBe(1);
- expect(trackOf(normalized, "ralu")).toBe(3);
-
- // USER lane-move: drag video to the lane BELOW ralu (bottom). ralu is at
- // lane 3, so video goes to a lane strictly greater — model it as lane 4.
- const afterMove = normalized.map((e) => (e.id === "video" ? { ...e, track: 4 } : e));
-
- // FORWARD: video (z=2) must drop below ralu (z=0). No integer z ≥ 0 fits
- // strictly below 0, so the tie-aware sync cascades: video→0 and the clips that
- // must stay above it (ralu z=0, black-logo z=1, blue-logo z=3) are bumped as
- // needed so video paints below ralu with all z ≥ 0.
- const patches = computeStackingPatches(toStacking(afterMove), ["video"]);
- const patchByKey = new Map(patches.map((p) => [p.key, p.zIndex]));
- // Video was moved; it must now be strictly below ralu in paint order.
- const zAfter = (id: string): number =>
- patchByKey.get(id) ?? (afterMove.find((e) => e.id === id)!.zIndex as number);
- expect(zAfter("video")).toBeLessThan(zAfter("ralu"));
- expect(zAfter("video")).toBeGreaterThanOrEqual(0);
- expect(patchByKey.size).toBeGreaterThan(0);
-
- // Apply patches and re-pack: video's lane must now be BELOW ralu's.
- const rediscovered = afterMove.map((e) => {
- const z = patchByKey.get(e.id);
- return z != null ? { ...e, zIndex: z } : e;
- });
- const renormalized = normalizeToZones(rediscovered);
- expect(trackOf(renormalized, "video")).toBeGreaterThan(trackOf(renormalized, "ralu"));
-
- // FIXED POINT: re-running BOTH directions on the converged state is a no-op.
- expect(computeStackingPatches(toStacking(renormalized), ["video"])).toEqual([]);
- const twice = normalizeToZones(renormalized);
- for (const e of renormalized) expect(trackOf(twice, e.id)).toBe(e.track);
+ it("is idempotent on the scattered-z legacy shape (no drift on re-discovery)", () => {
+ expectZoningIdempotent(legacy());
});
});
diff --git a/packages/studio/src/player/components/timelineZones.ts b/packages/studio/src/player/components/timelineZones.ts
index aed2a0a921..515555b3e1 100644
--- a/packages/studio/src/player/components/timelineZones.ts
+++ b/packages/studio/src/player/components/timelineZones.ts
@@ -3,8 +3,8 @@ import { isAudioTimelineElement } from "../../utils/timelineInspector";
/**
* Free-form vertical zones, top → bottom: visual, audio. There is no "main track"
- * — layering is CSS z-index (the renderer ignores track index), so the timeline's
- * only job is to keep visual clips grouped above audio clips.
+ * — canvas layering is CSS z-index (the renderer ignores track index), so the
+ * timeline's only job is to keep visual clips grouped above audio clips.
*/
export type TrackZone = "visual" | "audio";
@@ -16,9 +16,6 @@ export function classifyZone(el: TimelineElement): TrackZone {
const keyOf = (el: TimelineElement) => el.key ?? el.id;
-/** Stacking order for a clip: missing / "auto" z is treated as 0. */
-const zOf = (el: TimelineElement) => (Number.isFinite(el.zIndex) ? (el.zIndex as number) : 0);
-
const EPS = 1e-6;
/** Two clips overlap when their half-open [start, end) intervals intersect. */
@@ -26,166 +23,105 @@ function overlaps(a: TimelineElement, b: TimelineElement): boolean {
return a.start < b.start + b.duration - EPS && b.start < a.start + a.duration - EPS;
}
-/** A clip paired with its position in the discovery/document (input) order. */
-interface IndexedClip {
- el: TimelineElement;
- /** Index in the input `elements` array = discovery/DOM order. */
- domIndex: number;
-}
-
-/** One display lane: the clips packed onto it, in placement order. */
-interface Lane {
- occupants: IndexedClip[];
- /** The single authored track all occupants share, or null once mixed (never
- * happens — we only ever add same-track clips to an existing lane). */
- track: number;
-}
-
-/**
- * Lowest lane index a clip may occupy: strictly above every already-placed lane
- * holding a clip it overlaps in time (all of which out-stack it by the z-desc
- * placement order).
- */
-function lowestAllowedLane(lanes: Lane[], item: IndexedClip): number {
- let minLane = 0;
- for (let i = 0; i < lanes.length; i++) {
- if (lanes[i].occupants.some((o) => overlaps(o.el, item.el))) minLane = i + 1;
- }
- return minLane;
+/** Deterministic order on the stable clip id (never the mutated lane/track). */
+function byStableId(a: TimelineElement, b: TimelineElement): number {
+ const ka = keyOf(a);
+ const kb = keyOf(b);
+ return ka < kb ? -1 : ka > kb ? 1 : 0;
}
/**
- * First lane at index ≥ minLane that holds solely this clip's authored track and
- * nothing overlapping (so sequential same-track clips share a lane); -1 when none
- * qualifies and a fresh lane must open.
- */
-function findReusableLane(lanes: Lane[], minLane: number, item: IndexedClip): number {
- for (let i = minLane; i < lanes.length; i++) {
- const lane = lanes[i];
- if (lane.track !== item.el.track) continue;
- if (lane.occupants.some((o) => overlaps(o.el, item.el))) continue;
- return i;
- }
- return -1;
-}
-
-/**
- * Pack a WHOLE zone's clips onto display lanes with a single constrained pass so
- * that, for EVERY pair of time-overlapping clips, lane order (upper = lower index)
- * equals canvas stacking order. This replaces the old two-stage
- * `orderTrackBlocksByZ` + per-track `packTrackLanes`, which ordered whole authored
- * tracks by their MAX z and so lifted a low-z clip above a clip that covers it
- * whenever it shared a track with a high-z clip (the qa-clean ralu/video bug — a
- * low-z image rode its z=3 trackmate above the z=2 video that paints over it). No
- * whole-track mapping can fix that; the mapping must be per-clip.
+ * Pack ONE authored track's clips onto sub-lanes so no two time-overlapping clips
+ * share a lane. Clips are ordered by their STABLE id (a function of the input, not
+ * of the lane being computed — the historical oscillation bug tie-broke on the
+ * mutated track) and placed first-fit, so sequential (non-overlapping) clips
+ * collapse onto a single lane and only genuine time overlaps spill onto adjacent
+ * sub-lanes. Writes each clip's absolute display lane into `laneOf`; returns the
+ * number of lanes used (≥ 1 when non-empty).
*
- * Algorithm:
- * 1. Order clips by z DESC; z-tie → INPUT-ARRAY-INDEX (DOM order) DESC (CSS
- * paints equal-z siblings by DOM order — LATER in DOM paints on top, so it
- * must place first / upper); final tie → stable key. NEVER tie-break on the
- * mutated lane/track index (historic oscillation bug — the tie-break must be
- * a stable function of the input, not of the output being computed).
- * 2. Place each clip at lane ≥ (1 + highest lane among already-placed clips it
- * OVERLAPS IN TIME). By z-desc placement every already-placed overlapping
- * clip out-stacks this one (higher z, or equal z but later in DOM), so this
- * guarantees lane order == stacking order for every overlapping pair.
- * 3. To preserve the "distinct authored tracks stay distinct / sequential
- * same-track clips share a lane" feel, reuse an existing lane at index ≥ that
- * minimum ONLY when the lane's occupants are all from the SAME authored track
- * AND none overlaps this clip in time; otherwise open a fresh lane.
- *
- * Writes each clip's absolute display lane (`base + laneIndex`) into `laneOf` and
- * returns the number of lanes used (≥ 1 when non-empty).
+ * The editor enforces no per-track time overlap, so the spill only fires on legacy
+ * files. It is DISPLAY-ONLY — a drag commit persists just the dragged clip, never
+ * this re-lane — so it never rewrites the source.
*/
-function packZoneLanes(clips: IndexedClip[], base: number, laneOf: Map<string, number>): number {
- const ordered = [...clips].sort(
- (a, b) =>
- zOf(b.el) - zOf(a.el) || b.domIndex - a.domIndex || (keyOf(a.el) < keyOf(b.el) ? -1 : 1),
- );
- const lanes: Lane[] = [];
- for (const item of ordered) {
- const minLane = lowestAllowedLane(lanes, item);
- let placed = findReusableLane(lanes, minLane, item);
- if (placed === -1) {
- placed = lanes.length;
- lanes.push({ occupants: [], track: item.el.track });
+function packTrackLanes(
+ clips: TimelineElement[],
+ base: number,
+ laneOf: Map<string, number>,
+): number {
+ const ordered = [...clips].sort(byStableId);
+ const lanes: TimelineElement[][] = [];
+ for (const el of ordered) {
+ let sub = lanes.findIndex((occ) => occ.every((o) => !overlaps(o, el)));
+ if (sub === -1) {
+ sub = lanes.length;
+ lanes.push([]);
}
- lanes[placed].occupants.push(item);
- laneOf.set(keyOf(item.el), base + placed);
+ lanes[sub].push(el);
+ laneOf.set(keyOf(el), base + sub);
}
- return lanes.length;
+ return Math.max(1, lanes.length);
}
/**
- * Legacy per-track interval packing for the AUDIO zone (no z semantics): pack one
- * authored track's clips onto sub-lanes so no two overlap in time — sequential
- * clips share a lane, overlapping ones spill onto the next (first-fit). Ordered by
- * start (then stable key) so the layout is deterministic and idempotent. Returns
- * the number of lanes used (≥ 1 when non-empty).
+ * Pack a whole zone's clips onto contiguous display lanes, CapCut-stable: lanes
+ * follow the authored `data-track-index` (ASCENDING; ties by stable id) — NEVER a
+ * z-rank. Each distinct authored track owns its own lane (in ascending order);
+ * sequential same-track clips share it; time-overlapping same-track clips spill to
+ * adjacent sub-lanes (packTrackLanes). Returns the number of lanes used.
+ *
+ * This REPLACES the old global-z-rank interval pack. That pack ordered visual
+ * lanes by z-index and interval-packed overlaps, so editing one clip's z (or the
+ * whole-set re-pack a lane drag triggered) silently re-laned OTHER clips. The
+ * product decision is the opposite: a clip's lane is its track, period — z is
+ * canvas paint order only, and lane assignment must ignore it.
*/
-function packAudioTrackLanes(
- clips: IndexedClip[],
+function packZoneLanes(
+ clips: TimelineElement[],
base: number,
laneOf: Map<string, number>,
): number {
- const ordered = [...clips].sort(
- (a, b) => a.el.start - b.el.start || (keyOf(a.el) < keyOf(b.el) ? -1 : 1),
- );
- const lanes: IndexedClip[][] = [];
- for (const item of ordered) {
- let sub = lanes.findIndex((occ) => occ.every((o) => !overlaps(o.el, item.el)));
- if (sub === -1) {
- sub = lanes.length;
- lanes.push([]);
- }
- lanes[sub].push(item);
- laneOf.set(keyOf(item.el), base + sub);
+ const byTrack = new Map<number, TimelineElement[]>();
+ for (const el of clips) {
+ const list = byTrack.get(el.track);
+ if (list) list.push(el);
+ else byTrack.set(el.track, [el]);
}
- return Math.max(1, lanes.length);
+ let used = 0;
+ for (const track of [...byTrack.keys()].sort((a, b) => a - b)) {
+ used += packTrackLanes(byTrack.get(track)!, base + used, laneOf);
+ }
+ return used;
}
/**
* Assign display lanes for the timeline: visual lanes on top, audio lanes below.
*
- * The VISUAL zone is packed per-clip (packZoneLanes) so the timeline's vertical
- * order matches the canvas's CSS stacking for EVERY time-overlapping pair — a
- * low-z clip sinks below a clip that covers it even if it shares an authored track
- * with a higher-z clip. Time-overlapping clips still split onto separate lanes
- * (standard NLE), sequential same-track clips still share a lane, and distinct
- * authored tracks stay distinct.
- *
- * The AUDIO zone keeps the original behavior — authored-track order, per-track
- * interval packing — because audio has no z / stacking semantics.
+ * Both zones are packed the SAME way — by authored track-index, ascending (see
+ * packZoneLanes) — so the timeline's vertical order follows each clip's track and
+ * nothing else. z-index does not participate in lane assignment (it is canvas
+ * paint order only; the lane ↔ z stacking sync in timelineStackingSync runs the
+ * other direction, only on a deliberate vertical edit). Time-overlapping same-track
+ * clips still split onto separate sub-lanes (legacy files only — the editor forbids
+ * per-track overlap), and that split is display-only, never persisted.
*
* Pure — returns a new array; unchanged clips keep their identity. Display-only
* (runs on discovery); it does not rewrite the source. Idempotent (running it on
- * its own output is a fixed point).
+ * its own output is a fixed point): the lanes it emits are contiguous integers in
+ * ascending track order, and re-running groups by those same integers unchanged.
*/
export function normalizeToZones(elements: TimelineElement[]): TimelineElement[] {
if (elements.length === 0) return elements;
const laneOf = new Map<string, number>();
- let nextLane = 0;
-
- const visual: IndexedClip[] = [];
- const audio: IndexedClip[] = [];
- elements.forEach((el, domIndex) => {
- (classifyZone(el) === "audio" ? audio : visual).push({ el, domIndex });
- });
+ const visual: TimelineElement[] = [];
+ const audio: TimelineElement[] = [];
+ for (const el of elements) {
+ (classifyZone(el) === "audio" ? audio : visual).push(el);
+ }
+ let nextLane = 0;
nextLane += packZoneLanes(visual, nextLane, laneOf);
-
- // Audio: preserve legacy behavior — group by authored track (ascending), pack
- // each track's overlapping clips onto sub-lanes.
- const audioByTrack = new Map<number, IndexedClip[]>();
- for (const item of audio) {
- const list = audioByTrack.get(item.el.track);
- if (list) list.push(item);
- else audioByTrack.set(item.el.track, [item]);
- }
- for (const track of [...audioByTrack.keys()].sort((a, b) => a - b)) {
- nextLane += packAudioTrackLanes(audioByTrack.get(track)!, nextLane, laneOf);
- }
+ packZoneLanes(audio, nextLane, laneOf);
let changed = false;
const remapped = elements.map((el) => {
diff --git a/packages/studio/src/player/components/useTimelineRevealClip.ts b/packages/studio/src/player/components/useTimelineRevealClip.ts
new file mode 100644
index 0000000000..1c67654b24
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineRevealClip.ts
@@ -0,0 +1,56 @@
+/**
+ * Consumes playerStore.clipRevealRequest: when another surface (the sidebar
+ * asset card / audio row) asks for a clip to be revealed, smooth-scroll the
+ * timeline's scroll container so that clip is visible — horizontally to its
+ * time and vertically to its lane.
+ *
+ * The request is consumed (cleared) whether or not the clip node is found, so
+ * a stale request can never replay a scroll later. Respects zoom mode: in
+ * "fit" the timeline disables horizontal scrolling (overflow-x-hidden), so
+ * only the vertical axis is scrolled there.
+ */
+import { useEffect } from "react";
+import { usePlayerStore } from "../store/playerStore";
+import { GUTTER, RULER_H } from "./timelineLayout";
+import { computeRevealScroll } from "./timelineRevealScroll";
+
+export function useTimelineRevealClip(scrollRef: React.RefObject<HTMLDivElement | null>): void {
+ const revealRequest = usePlayerStore((s) => s.clipRevealRequest);
+
+ useEffect(() => {
+ if (!revealRequest) return;
+ // Consume the request first — reveal is one-shot, even when the clip node
+ // isn't currently rendered (e.g. drilled into a different composition).
+ usePlayerStore.getState().clearClipRevealRequest();
+
+ const container = scrollRef.current;
+ if (!container) return;
+ const clip = container.querySelector(`[data-el-id="${CSS.escape(revealRequest.elementId)}"]`);
+ if (!(clip instanceof HTMLElement)) return;
+
+ const containerRect = container.getBoundingClientRect();
+ const clipRect = clip.getBoundingClientRect();
+ const clipLeft = clipRect.left - containerRect.left + container.scrollLeft;
+ const clipTop = clipRect.top - containerRect.top + container.scrollTop;
+
+ const target = computeRevealScroll({
+ scrollLeft: container.scrollLeft,
+ scrollTop: container.scrollTop,
+ viewportWidth: container.clientWidth,
+ viewportHeight: container.clientHeight,
+ clipLeft,
+ clipRight: clipLeft + clipRect.width,
+ clipTop,
+ clipBottom: clipTop + clipRect.height,
+ stickyLeft: GUTTER,
+ stickyTop: RULER_H,
+ allowHorizontal: usePlayerStore.getState().zoomMode === "manual",
+ });
+ if (target.left === null && target.top === null) return;
+ container.scrollTo({
+ left: target.left ?? container.scrollLeft,
+ top: target.top ?? container.scrollTop,
+ behavior: "smooth",
+ });
+ }, [revealRequest, scrollRef]);
+}
diff --git a/packages/studio/src/player/components/useTimelineStackingSync.ts b/packages/studio/src/player/components/useTimelineStackingSync.ts
index 65d7c827e4..84e12a0abc 100644
--- a/packages/studio/src/player/components/useTimelineStackingSync.ts
+++ b/packages/studio/src/player/components/useTimelineStackingSync.ts
@@ -45,10 +45,16 @@ export function useTimelineStackingSync({ expandedElementsRef }: UseTimelineStac
[zSyncPreviewIframeRef, zSyncActiveCompPath],
);
+ // NaN (NOT 0) when the element can't be resolved in the preview iframe — a
+ // nested / unmounted sub-comp node, or one outside the active file. Fabricating
+ // z=0 would enter computeStackingPatches as a real overlapping neighbour at the
+ // z-floor and skew the boundary math; a non-finite value tells it to EXCLUDE this
+ // clip instead. NaN (rather than null) keeps the return assignable to the
+ // `(el) => number` reader contract the drag hook / commit deps declare.
const readClipZIndex = useCallback(
(el: TimelineElement): number => {
const node = resolveIframeElement(el);
- return node ? readEffectiveZIndex(node) : 0;
+ return node ? readEffectiveZIndex(node) : Number.NaN;
},
[resolveIframeElement],
);
@@ -71,7 +77,9 @@ export function useTimelineStackingSync({ expandedElementsRef }: UseTimelineStac
},
];
});
- if (entries.length) return handleDomZIndexReorderCommit(entries, coalesceKey);
+ // Forward the drag-commit's shared coalesce key so the z-reorder history
+ // entry merges with the lane change's move entry into one undo step.
+ if (entries.length) handleDomZIndexReorderCommit(entries, coalesceKey);
},
[handleDomZIndexReorderCommit, resolveIframeElement, zSyncActiveCompPath, expandedElementsRef],
);
diff --git a/packages/studio/src/player/store/playerStore.test.ts b/packages/studio/src/player/store/playerStore.test.ts
index 8d70cc81ba..ed86efaa36 100644
--- a/packages/studio/src/player/store/playerStore.test.ts
+++ b/packages/studio/src/player/store/playerStore.test.ts
@@ -1,6 +1,16 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { usePlayerStore, liveTime, type TimelineElement } from "./playerStore";
+/** The playback/selection state `reset()` restores (persistent prefs asserted separately). */
+function expectResettableDefaults(state: ReturnType<typeof usePlayerStore.getState>): void {
+ expect(state.isPlaying).toBe(false);
+ expect(state.currentTime).toBe(0);
+ expect(state.duration).toBe(0);
+ expect(state.timelineReady).toBe(false);
+ expect(state.elements).toEqual([]);
+ expect(state.selectedElementId).toBeNull();
+}
+
describe("usePlayerStore", () => {
beforeEach(() => {
usePlayerStore.getState().reset();
@@ -9,12 +19,7 @@ describe("usePlayerStore", () => {
describe("initial state", () => {
it("has correct defaults", () => {
const state = usePlayerStore.getState();
- expect(state.isPlaying).toBe(false);
- expect(state.currentTime).toBe(0);
- expect(state.duration).toBe(0);
- expect(state.timelineReady).toBe(false);
- expect(state.elements).toEqual([]);
- expect(state.selectedElementId).toBeNull();
+ expectResettableDefaults(state);
expect(state.playbackRate).toBe(1);
expect(state.audioMuted).toBe(false);
expect(state.loopEnabled).toBe(false);
@@ -384,6 +389,32 @@ describe("usePlayerStore", () => {
});
});
+ describe("clipRevealRequest", () => {
+ it("starts null and carries the requested element id", () => {
+ expect(usePlayerStore.getState().clipRevealRequest).toBeNull();
+ usePlayerStore.getState().requestClipReveal("el-1");
+ expect(usePlayerStore.getState().clipRevealRequest?.elementId).toBe("el-1");
+ });
+
+ it("bumps the nonce on repeat requests for the same clip", () => {
+ usePlayerStore.getState().requestClipReveal("el-1");
+ const first = usePlayerStore.getState().clipRevealRequest;
+ usePlayerStore.getState().requestClipReveal("el-1");
+ const second = usePlayerStore.getState().clipRevealRequest;
+ expect(second?.nonce).not.toBe(first?.nonce);
+ });
+
+ it("clears via clearClipRevealRequest and on reset", () => {
+ usePlayerStore.getState().requestClipReveal("el-1");
+ usePlayerStore.getState().clearClipRevealRequest();
+ expect(usePlayerStore.getState().clipRevealRequest).toBeNull();
+
+ usePlayerStore.getState().requestClipReveal("el-2");
+ usePlayerStore.getState().reset();
+ expect(usePlayerStore.getState().clipRevealRequest).toBeNull();
+ });
+ });
+
describe("reset", () => {
it("resets all state to defaults", () => {
// Mutate everything
@@ -398,13 +429,7 @@ describe("usePlayerStore", () => {
// Reset
usePlayerStore.getState().reset();
- const state = usePlayerStore.getState();
- expect(state.isPlaying).toBe(false);
- expect(state.currentTime).toBe(0);
- expect(state.duration).toBe(0);
- expect(state.timelineReady).toBe(false);
- expect(state.elements).toEqual([]);
- expect(state.selectedElementId).toBeNull();
+ expectResettableDefaults(usePlayerStore.getState());
});
it("does not reset playbackRate, audioMuted, loopEnabled, zoomMode, or manualZoomPercent", () => {
diff --git a/packages/studio/src/player/store/playerStore.ts b/packages/studio/src/player/store/playerStore.ts
index 2d537bc80f..8a7cdcff04 100644
--- a/packages/studio/src/player/store/playerStore.ts
+++ b/packages/studio/src/player/store/playerStore.ts
@@ -153,6 +153,9 @@ interface PlayerState {
/** Timeline magnet toggle — when false, clip drags/trims/drops never snap. */
timelineSnapEnabled: boolean;
setTimelineSnapEnabled: (enabled: boolean) => void;
+ /** Transport + ruler readout: timecode ("time") or frame number ("frame"). */
+ timeDisplayMode: "time" | "frame";
+ setTimeDisplayMode: (mode: "time" | "frame") => void;
/**
* Pin the timeline zoom to its current visual scale before a duration-changing
* edit, so a subsequent duration change (which recomputes fit-pps) stops
@@ -210,6 +213,16 @@ interface PlayerState {
requestSeek: (time: number) => void;
clearSeekRequest: () => void;
+ /**
+ * Request the timeline to scroll a clip into view (e.g. clicking an
+ * already-added asset card in the sidebar). Consumed and cleared by
+ * useTimelineRevealClip. The nonce makes repeat requests for the same
+ * clip observable so a second click re-reveals after the user scrolls away.
+ */
+ clipRevealRequest: { elementId: string; nonce: number } | null;
+ requestClipReveal: (elementId: string) => void;
+ clearClipRevealRequest: () => void;
+
lintFindingsByElement: Map<string, { count: number; messages: string[] }>;
setLintFindingsByElement: (map: Map<string, { count: number; messages: string[] }>) => void;
@@ -341,6 +354,13 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
requestSeek: (time) => set({ requestedSeekTime: time }),
clearSeekRequest: () => set({ requestedSeekTime: null }),
+ clipRevealRequest: null,
+ requestClipReveal: (elementId) =>
+ set((s) => ({
+ clipRevealRequest: { elementId, nonce: (s.clipRevealRequest?.nonce ?? 0) + 1 },
+ })),
+ clearClipRevealRequest: () => set({ clipRevealRequest: null }),
+
lintFindingsByElement: new Map(),
setLintFindingsByElement: (map) => set({ lintFindingsByElement: map }),
@@ -416,6 +436,11 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
writeStudioUiPreferences({ timelineSnapEnabled: enabled });
set({ timelineSnapEnabled: enabled });
},
+ timeDisplayMode: readStudioUiPreferences().timeDisplayMode ?? "time",
+ setTimeDisplayMode: (mode) => {
+ writeStudioUiPreferences({ timeDisplayMode: mode });
+ set({ timeDisplayMode: mode });
+ },
pinTimelineZoom: (currentPixelsPerSecond, fitPixelsPerSecond) =>
set((s) => {
// Already pinned (or the user manually zoomed) — never clobber that.
@@ -522,6 +547,7 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
activeTool: "select",
selectedKeyframes: new Set(),
selectedElementIds: new Set(),
+ clipRevealRequest: null,
keyframeCache: new Map(),
beatAnalysis: null,
beatEdits: null,
diff --git a/packages/studio/src/utils/assetPreviewDismiss.test.ts b/packages/studio/src/utils/assetPreviewDismiss.test.ts
new file mode 100644
index 0000000000..c18e46ac17
--- /dev/null
+++ b/packages/studio/src/utils/assetPreviewDismiss.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { shouldDismissAssetPreview } from "./assetPreviewDismiss";
+
+describe("shouldDismissAssetPreview", () => {
+ const idle = { isPlaying: false, currentTime: 3.5, requestedSeekTime: null };
+
+ it("keeps the preview open while nothing moves", () => {
+ expect(shouldDismissAssetPreview(3.5, idle)).toBe(false);
+ });
+
+ it("tolerates sub-epsilon float noise in currentTime echoes", () => {
+ expect(shouldDismissAssetPreview(3.5, { ...idle, currentTime: 3.5 + 1e-9 })).toBe(false);
+ });
+
+ it("dismisses when playback starts", () => {
+ expect(shouldDismissAssetPreview(3.5, { ...idle, isPlaying: true })).toBe(true);
+ });
+
+ it("dismisses when the playhead is scrubbed/seeked to a new time", () => {
+ expect(shouldDismissAssetPreview(3.5, { ...idle, currentTime: 4.2 })).toBe(true);
+ expect(shouldDismissAssetPreview(3.5, { ...idle, currentTime: 0 })).toBe(true);
+ });
+
+ it("dismisses on a pending out-of-loop seek request", () => {
+ expect(shouldDismissAssetPreview(3.5, { ...idle, requestedSeekTime: 3.5 })).toBe(true);
+ });
+});
diff --git a/packages/studio/src/utils/assetPreviewDismiss.ts b/packages/studio/src/utils/assetPreviewDismiss.ts
new file mode 100644
index 0000000000..8065c18d09
--- /dev/null
+++ b/packages/studio/src/utils/assetPreviewDismiss.ts
@@ -0,0 +1,29 @@
+/**
+ * Dismissal rule for the sidebar asset preview overlay (AssetPreviewOverlay):
+ * the preview is a transient "look at this asset" state, so any playhead
+ * activity — starting playback, or seeking/scrubbing away from where the
+ * playhead sat when the preview opened — hands focus back to the canvas and
+ * closes it.
+ *
+ * Pure — unit-tested. The overlay captures `openedTime` when the preview
+ * opens and feeds every subsequent player-store snapshot through this.
+ */
+
+export interface AssetPreviewDismissSnapshot {
+ isPlaying: boolean;
+ currentTime: number;
+ /** Pending out-of-loop seek request (playerStore.requestedSeekTime). */
+ requestedSeekTime: number | null;
+}
+
+/** Tolerance for float noise in currentTime echoes (well under one frame). */
+const TIME_EPSILON_S = 1e-6;
+
+export function shouldDismissAssetPreview(
+ openedTime: number,
+ snapshot: AssetPreviewDismissSnapshot,
+): boolean {
+ if (snapshot.isPlaying) return true;
+ if (snapshot.requestedSeekTime !== null) return true;
+ return Math.abs(snapshot.currentTime - openedTime) > TIME_EPSILON_S;
+}
diff --git a/packages/studio/src/utils/timelineAssetDrop.test.ts b/packages/studio/src/utils/timelineAssetDrop.test.ts
index 046c5eba9f..6d2aa49d11 100644
--- a/packages/studio/src/utils/timelineAssetDrop.test.ts
+++ b/packages/studio/src/utils/timelineAssetDrop.test.ts
@@ -1,13 +1,80 @@
+// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import {
buildTimelineFileDropPlacements,
buildTimelineAssetInsertHtml,
+ extendCompositionDurationIfNeeded,
+ fitTimelineAssetGeometry,
getTimelineAssetKind,
insertTimelineAssetIntoSource,
- resolveTimelineAssetInitialGeometry,
+ resolveTimelineAssetCompositionSize,
resolveTimelineAssetSrc,
+ setCompositionDurationToContent,
} from "./timelineAssetDrop";
+describe("setCompositionDurationToContent", () => {
+ const src = (dur: number) =>
+ `<div id="root" data-composition-id="c" data-duration="${dur}">x</div>`;
+
+ it("shrinks the root duration to the content end", () => {
+ expect(setCompositionDurationToContent(src(20), 8)).toContain('data-duration="8"');
+ });
+
+ it("grows the root duration to the content end", () => {
+ expect(setCompositionDurationToContent(src(5), 12)).toContain('data-duration="12"');
+ });
+
+ it("is a no-op when content end is 0 (empty timeline keeps its declared length)", () => {
+ expect(setCompositionDurationToContent(src(12), 0)).toBe(src(12));
+ });
+
+ it("is a no-op when already equal", () => {
+ expect(setCompositionDurationToContent(src(9), 9)).toBe(src(9));
+ });
+
+ // Reviewer round-2 finding #3: attribute-order and single-quote variants that
+ // the old order-dependent, double-quotes-only regex silently ignored.
+ it("patches when data-duration precedes data-composition-id", () => {
+ const source = `<div data-duration="20" data-composition-id="c">x</div>`;
+ expect(setCompositionDurationToContent(source, 8)).toBe(
+ `<div data-duration="8" data-composition-id="c">x</div>`,
+ );
+ });
+
+ it("patches single-quoted attributes and keeps the quote style", () => {
+ const source = `<div data-composition-id='c' data-duration='20'>x</div>`;
+ expect(setCompositionDurationToContent(source, 8)).toBe(
+ `<div data-composition-id='c' data-duration='8'>x</div>`,
+ );
+ });
+});
+
+describe("extendCompositionDurationIfNeeded", () => {
+ it("grows the root duration when a clip lands past the end", () => {
+ const source = `<div data-composition-id="c" data-duration="5">x</div>`;
+ expect(extendCompositionDurationIfNeeded(source, 8)).toBe(
+ `<div data-composition-id="c" data-duration="8">x</div>`,
+ );
+ });
+
+ it("is a no-op when the required end fits within the current duration", () => {
+ const source = `<div data-composition-id="c" data-duration="10">x</div>`;
+ expect(extendCompositionDurationIfNeeded(source, 8)).toBe(source);
+ });
+
+ it("grows even when the attribute order is swapped and quotes are single", () => {
+ const source = `<div data-duration='5' data-composition-id='c'>x</div>`;
+ expect(extendCompositionDurationIfNeeded(source, 8)).toBe(
+ `<div data-duration='8' data-composition-id='c'>x</div>`,
+ );
+ });
+
+ it("is a no-op when there is no composition root", () => {
+ const source = `<div data-duration="5">x</div>`;
+ expect(extendCompositionDurationIfNeeded(source, 8)).toBe(source);
+ });
+});
+
describe("getTimelineAssetKind", () => {
it("detects image, video, and audio assets", () => {
expect(getTimelineAssetKind("assets/photo.png")).toBe("image");
@@ -16,12 +83,28 @@ describe("getTimelineAssetKind", () => {
expect(getTimelineAssetKind("assets/music.mp3")).toBe("audio");
expect(getTimelineAssetKind("assets/music.wav")).toBe("audio");
});
+
+ it("classifies svg as image", () => {
+ expect(getTimelineAssetKind("assets/logo.svg")).toBe("image");
+ expect(getTimelineAssetKind("assets/ICON.SVG")).toBe("image");
+ });
+
+ it("classifies avif and webp as image", () => {
+ expect(getTimelineAssetKind("assets/photo.avif")).toBe("image");
+ expect(getTimelineAssetKind("assets/photo.webp")).toBe("image");
+ });
+
+ it("returns null for unknown extensions", () => {
+ expect(getTimelineAssetKind("assets/data.json")).toBeNull();
+ expect(getTimelineAssetKind("assets/font.woff2")).toBeNull();
+ });
});
describe("buildTimelineAssetInsertHtml", () => {
it("builds an image clip with explicit timing and track", () => {
const html = buildTimelineAssetInsertHtml({
id: "photo_asset",
+ hfId: "hf-abc123",
assetPath: "assets/photo.png",
kind: "image",
start: 1.25,
@@ -40,6 +123,7 @@ describe("buildTimelineAssetInsertHtml", () => {
it("builds an audio clip without visual layout styles", () => {
const html = buildTimelineAssetInsertHtml({
id: "music_asset",
+ hfId: "hf-xyz789",
assetPath: "assets/music.wav",
kind: "audio",
start: 0.5,
@@ -52,15 +136,13 @@ describe("buildTimelineAssetInsertHtml", () => {
});
});
-describe("resolveTimelineAssetInitialGeometry", () => {
+describe("resolveTimelineAssetCompositionSize", () => {
it("uses the target composition dimensions for visual media", () => {
expect(
- resolveTimelineAssetInitialGeometry(
+ resolveTimelineAssetCompositionSize(
`<div data-composition-id="main" data-width="330" data-height="228"></div>`,
),
).toEqual({
- left: 0,
- top: 0,
width: 330,
height: 228,
});
@@ -84,7 +166,9 @@ describe("buildTimelineFileDropPlacements", () => {
expect(buildTimelineFileDropPlacements({ start: 1.5, track: 2 }, [])).toEqual([]);
});
- it("uses the dropped start and spaces multiple files by duration on the same track", () => {
+ it("spaces multiple files by duration and keeps every one on the dropped track", () => {
+ // A clip placed onto an occupied track stays there (overlap is allowed); it is
+ // NOT bumped to a new track — that produced surprise empty tracks for users.
expect(buildTimelineFileDropPlacements({ start: 1.5, track: 2 }, [1.2, 1.6, 1.1])).toEqual([
{ start: 1.5, track: 2 },
{ start: 2.7, track: 2 },
@@ -99,52 +183,6 @@ describe("buildTimelineFileDropPlacements", () => {
{ start: 7.7, track: 2 },
]);
});
-
- it("moves the spaced sequence to a clear track when the dropped row is occupied", () => {
- expect(
- buildTimelineFileDropPlacements(
- { start: 1.5, track: 2 },
- [1.2, 1.6, 1.1],
- [
- { start: 0, duration: 8, track: 2 },
- { start: 0, duration: 4, track: 5 },
- ],
- ),
- ).toEqual([
- { start: 1.5, track: 6 },
- { start: 2.7, track: 6 },
- { start: 4.3, track: 6 },
- ]);
- });
-
- it("keeps a requested track above occupied rows when that track is clear", () => {
- expect(
- buildTimelineFileDropPlacements(
- { start: 1.5, track: 8 },
- [1.2, 1.6],
- [
- { start: 0, duration: 8, track: 2 },
- { start: 0, duration: 4, track: 5 },
- ],
- ),
- ).toEqual([
- { start: 1.5, track: 8 },
- { start: 2.7, track: 8 },
- ]);
- });
-
- it("moves a default-track drop to a clear row when track 0 is occupied at time 0", () => {
- expect(
- buildTimelineFileDropPlacements(
- { start: 0, track: 0 },
- [1.2, 1.6],
- [{ start: 0, duration: 8, track: 0 }],
- ),
- ).toEqual([
- { start: 0, track: 1 },
- { start: 1.2, track: 1 },
- ]);
- });
});
describe("insertTimelineAssetIntoSource", () => {
@@ -159,3 +197,57 @@ describe("insertTimelineAssetIntoSource", () => {
expect(html).toContain('<img id="photo_asset" data-start="0" data-duration="3" />');
});
});
+
+describe("buildTimelineAssetInsertHtml markup quality", () => {
+ const base = {
+ id: "clip_1",
+ hfId: "hf-test-1",
+ assetPath: "assets/a.mp4",
+ start: 1,
+ duration: 4,
+ track: 2,
+ zIndex: 3,
+ };
+
+ it("stamps data-hf-id on all kinds", () => {
+ for (const kind of ["image", "video", "audio"] as const) {
+ expect(buildTimelineAssetInsertHtml({ ...base, kind })).toContain('data-hf-id="hf-test-1"');
+ }
+ });
+
+ it("audio gets an explicit data-volume", () => {
+ expect(buildTimelineAssetInsertHtml({ ...base, kind: "audio" })).toContain('data-volume="1"');
+ });
+});
+
+describe("fitTimelineAssetGeometry", () => {
+ const comp = { width: 1920, height: 1080 };
+
+ it("centers a smaller-than-comp asset at natural size", () => {
+ expect(fitTimelineAssetGeometry({ width: 640, height: 360 }, comp)).toEqual({
+ left: 640,
+ top: 360,
+ width: 640,
+ height: 360,
+ });
+ });
+
+ it("scales an oversized asset down to fit, preserving aspect, centered", () => {
+ // 4000x1000 → capped to 1920 wide → 1920x480, centered vertically
+ expect(fitTimelineAssetGeometry({ width: 4000, height: 1000 }, comp)).toEqual({
+ left: 0,
+ top: 300,
+ width: 1920,
+ height: 480,
+ });
+ });
+
+ it("falls back to full-frame when natural size is unknown", () => {
+ expect(fitTimelineAssetGeometry(null, comp)).toEqual({
+ left: 0,
+ top: 0,
+ width: 1920,
+ height: 1080,
+ });
+ });
+});
diff --git a/packages/studio/src/utils/timelineAssetDrop.ts b/packages/studio/src/utils/timelineAssetDrop.ts
index 5194f5899b..7015169b26 100644
--- a/packages/studio/src/utils/timelineAssetDrop.ts
+++ b/packages/studio/src/utils/timelineAssetDrop.ts
@@ -1,7 +1,7 @@
import { AUDIO_EXT, IMAGE_EXT, VIDEO_EXT } from "./mediaTypes";
-import { patchRootCompositionDuration, readRootCompositionDuration } from "./rootDuration";
import { roundToCenti } from "./rounding";
import { COMPOSITION_ROOT_OPEN_TAG_RE } from "./compositionPatterns";
+import { patchRootCompositionDuration, readRootCompositionDuration } from "./rootDuration";
export const TIMELINE_ASSET_MIME = "application/x-hyperframes-asset";
export const TIMELINE_BLOCK_MIME = "application/x-hyperframes-block";
@@ -49,58 +49,66 @@ export function resolveTimelineAssetSrc(targetPath: string, assetPath: string):
return relative || assetPath.split("/").pop() || assetPath;
}
+/**
+ * Sequence one or more dropped files end-to-end starting at the drop point, all on
+ * the track the user dropped onto. The clip lands where the ghost showed it — we do
+ * NOT bump to a different track on overlap (that produced surprise "new tracks" and,
+ * because it jumped past high indices like a grain-overlay track, wild numbers).
+ * HyperFrames allows time-overlap on a track; the user can nudge if they want a gap.
+ */
export function buildTimelineFileDropPlacements(
placement: { start: number; track: number },
durations: number[],
- occupiedClips: Array<{ start: number; duration: number; track: number }> = [],
): Array<{ start: number; track: number }> {
let nextStart = roundToCenti(Math.max(0, placement.start));
- const sequenceStart = nextStart;
- const resolvedDurations = durations.map((duration) =>
- Number.isFinite(duration) && duration > 0 ? duration : FALLBACK_TIMELINE_FILE_DROP_DURATION,
- );
- const sequenceEnd = resolvedDurations.reduce(
- (end, duration) => roundToCenti(end + duration),
- sequenceStart,
- );
- const overlapsDropTrack = occupiedClips.some((clip) => {
- if (clip.track !== placement.track) return false;
- const clipStart = Math.max(0, clip.start);
- const clipEnd = clipStart + Math.max(0, clip.duration);
- return sequenceStart < clipEnd && sequenceEnd > clipStart;
- });
- const track = overlapsDropTrack
- ? Math.max(placement.track, ...occupiedClips.map((clip) => clip.track)) + 1
- : placement.track;
-
- return resolvedDurations.map((duration) => {
+ return durations.map((rawDuration) => {
+ const duration =
+ Number.isFinite(rawDuration) && rawDuration > 0
+ ? rawDuration
+ : FALLBACK_TIMELINE_FILE_DROP_DURATION;
const start = nextStart;
nextStart = roundToCenti(nextStart + duration);
- return { start, track };
+ return { start, track: placement.track };
});
}
-export function resolveTimelineAssetInitialGeometry(source: string): {
- left: number;
- top: number;
+export function resolveTimelineAssetCompositionSize(source: string): {
width: number;
height: number;
} {
const width = Number.parseFloat(source.match(/\bdata-width=(["'])([^"']+)\1/i)?.[2] ?? "");
const height = Number.parseFloat(source.match(/\bdata-height=(["'])([^"']+)\1/i)?.[2] ?? "");
-
return {
- left: 0,
- top: 0,
width: Number.isFinite(width) && width > 0 ? Math.round(width) : 640,
height: Number.isFinite(height) && height > 0 ? Math.round(height) : 360,
};
}
+/**
+ * CapCut-style placement: natural size when it fits, scaled-to-fit when
+ * oversized, always centered. Unknown natural size → full-frame.
+ */
+export function fitTimelineAssetGeometry(
+ natural: { width: number; height: number } | null,
+ comp: { width: number; height: number },
+): { left: number; top: number; width: number; height: number } {
+ if (!natural || natural.width <= 0 || natural.height <= 0) {
+ return { left: 0, top: 0, width: comp.width, height: comp.height };
+ }
+ const scale = Math.min(1, comp.width / natural.width, comp.height / natural.height);
+ const width = Math.round(natural.width * scale);
+ const height = Math.round(natural.height * scale);
+ return {
+ left: Math.round((comp.width - width) / 2),
+ top: Math.round((comp.height - height) / 2),
+ width,
+ height,
+ };
+}
+
export function buildTimelineAssetInsertHtml(input: {
id: string;
- /** Stable hf-id stamped as data-hf-id by the NLE drop path (optional in the legacy path). */
- hfId?: string;
+ hfId: string;
assetPath: string;
kind: TimelineAssetKind;
start: number;
@@ -109,7 +117,7 @@ export function buildTimelineAssetInsertHtml(input: {
zIndex: number;
geometry?: { left: number; top: number; width: number; height: number };
}): string {
- const sharedAttrs = `id="${input.id}" class="clip" src="${input.assetPath}" data-start="${input.start}" data-duration="${input.duration}" data-track-index="${input.track}"`;
+ const sharedAttrs = `id="${input.id}" data-hf-id="${input.hfId}" class="clip" src="${input.assetPath}" data-start="${input.start}" data-duration="${input.duration}" data-track-index="${input.track}"`;
const geometry = input.geometry ?? { left: 0, top: 0, width: 640, height: 360 };
const visualStyles = `position: absolute; left: ${geometry.left}px; top: ${geometry.top}px; width: ${geometry.width}px; height: ${geometry.height}px; object-fit: contain; z-index: ${input.zIndex}`;
@@ -121,23 +129,18 @@ export function buildTimelineAssetInsertHtml(input: {
return `<video ${sharedAttrs} muted playsinline style="${visualStyles}"></video>`;
}
- return `<audio ${sharedAttrs} style="z-index: ${input.zIndex}"></audio>`;
+ return `<audio ${sharedAttrs} data-volume="1" style="z-index: ${input.zIndex}"></audio>`;
}
-export function insertTimelineAssetIntoSource(source: string, assetHtml: string): string {
- const match = COMPOSITION_ROOT_OPEN_TAG_RE.exec(source);
- if (!match || match.index == null) {
- throw new Error("No composition root found in target source");
- }
- const insertAt = match.index + match[0].length;
- const lineStart = source.lastIndexOf("\n", match.index);
- const leadingWhitespace = source.slice(lineStart + 1, match.index).match(/^(\s*)/)?.[1] ?? "";
- const childIndent = leadingWhitespace + " ";
- const indented = assetHtml
- .split("\n")
- .map((line, i) => (i === 0 ? line : childIndent + line))
- .join("\n");
- return `${source.slice(0, insertAt)}\n${childIndent}${indented}${source.slice(insertAt)}`;
+/**
+ * A clip inserted past the composition end would exist in the HTML but never
+ * appear on the timeline or in playback. Extend the root's data-duration to
+ * cover it (mirrors blockInstaller's behavior for installed blocks).
+ */
+export function extendCompositionDurationIfNeeded(source: string, requiredEnd: number): string {
+ const rootDur = readRootCompositionDuration(source);
+ if (rootDur == null || !Number.isFinite(rootDur) || requiredEnd <= rootDur) return source;
+ return patchRootCompositionDuration(source, String(roundToCenti(requiredEnd)));
}
/**
@@ -156,45 +159,18 @@ export function setCompositionDurationToContent(source: string, contentEnd: numb
return patchRootCompositionDuration(source, String(next));
}
-export function extendCompositionDurationIfNeeded(source: string, requiredEnd: number): string {
- const rootDur = readRootCompositionDuration(source);
- if (rootDur == null || !Number.isFinite(rootDur) || requiredEnd <= rootDur) return source;
- return patchRootCompositionDuration(source, String(roundToCenti(requiredEnd)));
-}
-
-/**
- * Set the composition root's `data-duration` to `contentEnd` (grow OR shrink) so the
- * timeline length tracks content — the content-driven counterpart to
- * extendCompositionDurationIfNeeded's grow-only ratchet. Used after edits that can
- * reduce the furthest clip end (delete/trim). No-op when `contentEnd` is not > 0, so
- * an empty timeline keeps its declared duration instead of collapsing to 0.
- */
-export function fitTimelineAssetGeometry(
- natural: { width: number; height: number } | null,
- comp: { width: number; height: number },
-): { left: number; top: number; width: number; height: number } {
- if (!natural || natural.width <= 0 || natural.height <= 0) {
- return { left: 0, top: 0, width: comp.width, height: comp.height };
+export function insertTimelineAssetIntoSource(source: string, assetHtml: string): string {
+ const match = COMPOSITION_ROOT_OPEN_TAG_RE.exec(source);
+ if (!match || match.index == null) {
+ throw new Error("No composition root found in target source");
}
- const scale = Math.min(1, comp.width / natural.width, comp.height / natural.height);
- const width = Math.round(natural.width * scale);
- const height = Math.round(natural.height * scale);
- return {
- left: Math.round((comp.width - width) / 2),
- top: Math.round((comp.height - height) / 2),
- width,
- height,
- };
-}
-
-export function resolveTimelineAssetCompositionSize(source: string): {
- width: number;
- height: number;
-} {
- const width = Number.parseFloat(source.match(/\bdata-width=(["'])([^"']+)\1/i)?.[2] ?? "");
- const height = Number.parseFloat(source.match(/\bdata-height=(["'])([^"']+)\1/i)?.[2] ?? "");
- return {
- width: Number.isFinite(width) && width > 0 ? Math.round(width) : 640,
- height: Number.isFinite(height) && height > 0 ? Math.round(height) : 360,
- };
+ const insertAt = match.index + match[0].length;
+ const lineStart = source.lastIndexOf("\n", match.index);
+ const leadingWhitespace = source.slice(lineStart + 1, match.index).match(/^(\s*)/)?.[1] ?? "";
+ const childIndent = leadingWhitespace + " ";
+ const indented = assetHtml
+ .split("\n")
+ .map((line, i) => (i === 0 ? line : childIndent + line))
+ .join("\n");
+ return `${source.slice(0, insertAt)}\n${childIndent}${indented}${source.slice(insertAt)}`;
}